content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
add import actions for clarity
23f811b6c16a06e26bfdbcbee4ab9fccb56f8622
<ide><path>docs/basics/Reducers.md <ide> Note that: <ide> We have two more actions to handle! Just like we did with `SET_VISIBILITY_FILTER`, we'll import the `ADD_TODO` and `TOGGLE_TODO` actions and then extend our reducer to handle `ADD_TODO`. <ide> <ide> ```js <add>import { VisibilityFilters, ADD_TODO, TOGGLE_TODO } from './actions' <add> <add>... <add> <ide> function todoApp(state = initialState, action) { <ide> switch (action.type) { <ide> case SET_VISIBILITY_FILTER:
1
Ruby
Ruby
remove all testing temporaries when done
e9dbdadcacba4dda800dedf7511a510a149a4742
<ide><path>Library/Homebrew/unittest.rb <ide> <ide> HOMEBREW_CELLAR.mkpath <ide> raise "HOMEBREW_CELLAR couldn't be created!" unless HOMEBREW_CELLAR.directory? <del>at_exit { HOMEBREW_CACHE.rmtree } <add>at_exit { HOMEBREW_PREFIX.parent.rmtree } <ide> require 'test/unit' # must be after at_exit <ide> <ide>
1
Ruby
Ruby
use our bazaar formula for now
a9895432ce92fcb4cb3794805d2a82e409626493
<ide><path>Library/Homebrew/brew.h.rb <ide> def check_for_blacklisted_formula names <ide> <ide> names.each do |name| <ide> case name <del> when 'bazaar', 'bzr' then abort <<-EOS <del>Bazaar can be installed thusly: <del> <del> brew install pip && pip install bzr==2.0.1 <del> <del> EOS <add> # bazaar don't maintain their PyPi entry properly yet <add> # when they do we'll remove our formula and use that <add># when 'bazaar', 'bzr' then abort <<-EOS <add>#Bazaar can be installed thusly: <add># <add># brew install pip && pip install bzr==2.0.1 <add># <add># EOS <ide> when 'mercurial', 'hg' then abort <<-EOS <ide> Mercurial can be install thusly: <ide>
1
Python
Python
remove old upgrade script
e0cd80c6bff0d5ca3720f2f8dcac21274827caa5
<ide><path>scripts/flask-07-upgrade.py <del>#!/usr/bin/env python <del># -*- coding: utf-8 -*- <del>""" <del> flask-07-upgrade <del> ~~~~~~~~~~~~~~~~ <del> <del> This command line script scans a whole application tree and attempts to <del> output a unified diff with all the changes that are necessary to easily <del> upgrade the application to 0.7 and to not yield deprecation warnings. <del> <del> This will also attempt to find `after_request` functions that don't modify <del> the response and appear to be better suited for `teardown_request`. <del> <del> This application is indeed an incredible hack, but because what it <del> attempts to accomplish is impossible to do statically it tries to support <del> the most common patterns at least. The diff it generates should be <del> hand reviewed and not applied blindly without making backups. <del> <del> :copyright: (c) Copyright 2015 by Armin Ronacher. <del> :license: see LICENSE for more details. <del>""" <del>from __future__ import print_function <del>import re <del>import os <del>import inspect <del>import difflib <del>import posixpath <del>from optparse import OptionParser <del> <del>try: <del> import ast <del>except ImportError: <del> ast = None <del> <del> <del>TEMPLATE_LOOKAHEAD = 4096 <del> <del>_app_re_part = r'((?:[a-zA-Z_][a-zA-Z0-9_]*app)|app|application)' <del>_string_re_part = r"('([^'\\]*(?:\\.[^'\\]*)*)'" \ <del> r'|"([^"\\]*(?:\\.[^"\\]*)*)")' <del> <del>_from_import_re = re.compile(r'^\s*from flask import\s+') <del>_url_for_re = re.compile(r'\b(url_for\()(%s)' % _string_re_part) <del>_render_template_re = re.compile(r'\b(render_template\()(%s)' % _string_re_part) <del>_after_request_re = re.compile(r'((?:@\S+\.(?:app_)?))(after_request)(\b\s*$)(?m)') <del>_module_constructor_re = re.compile(r'([a-zA-Z0-9_][a-zA-Z0-9_]*)\s*=\s*Module' <del> r'\(__name__\s*(?:,\s*(?:name\s*=\s*)?(%s))?' % <del> _string_re_part) <del>_error_handler_re = re.compile(r'%s\.error_handlers\[\s*(\d+)\s*\]' % _app_re_part) <del>_mod_route_re = re.compile(r'@([a-zA-Z0-9_][a-zA-Z0-9_]*)\.route') <del>_blueprint_related = [ <del> (re.compile(r'request\.module'), 'request.blueprint'), <del> (re.compile(r'register_module'), 'register_blueprint'), <del> (re.compile(r'%s\.modules' % _app_re_part), '\\1.blueprints') <del>] <del> <del> <del>def make_diff(filename, old, new): <del> for line in difflib.unified_diff(old.splitlines(), new.splitlines(), <del> posixpath.normpath(posixpath.join('a', filename)), <del> posixpath.normpath(posixpath.join('b', filename)), <del> lineterm=''): <del> print(line) <del> <del> <del>def looks_like_teardown_function(node): <del> returns = [x for x in ast.walk(node) if isinstance(x, ast.Return)] <del> if len(returns) != 1: <del> return <del> return_def = returns[0] <del> resp_name = node.args.args[0] <del> if not isinstance(return_def.value, ast.Name) or \ <del> return_def.value.id != resp_name.id: <del> return <del> <del> for body_node in node.body: <del> for child in ast.walk(body_node): <del> if isinstance(child, ast.Name) and \ <del> child.id == resp_name.id: <del> if child is not return_def.value: <del> return <del> <del> return resp_name.id <del> <del> <del>def fix_url_for(contents, module_declarations=None): <del> if module_declarations is None: <del> skip_module_test = True <del> else: <del> skip_module_test = False <del> mapping = dict(module_declarations) <del> annotated_lines = [] <del> <del> def make_line_annotations(): <del> if not annotated_lines: <del> last_index = 0 <del> for line in contents.splitlines(True): <del> last_index += len(line) <del> annotated_lines.append((last_index, line)) <del> <del> def backtrack_module_name(call_start): <del> make_line_annotations() <del> for idx, (line_end, line) in enumerate(annotated_lines): <del> if line_end > call_start: <del> for _, line in reversed(annotated_lines[:idx]): <del> match = _mod_route_re.search(line) <del> if match is not None: <del> shortname = match.group(1) <del> return mapping.get(shortname) <del> <del> def handle_match(match): <del> if not skip_module_test: <del> modname = backtrack_module_name(match.start()) <del> if modname is None: <del> return match.group(0) <del> prefix = match.group(1) <del> endpoint = ast.literal_eval(match.group(2)) <del> if endpoint.startswith('.'): <del> endpoint = endpoint[1:] <del> elif '.' not in endpoint: <del> endpoint = '.' + endpoint <del> else: <del> return match.group(0) <del> return prefix + repr(endpoint) <del> return _url_for_re.sub(handle_match, contents) <del> <del> <del>def fix_teardown_funcs(contents): <del> <del> def is_return_line(line): <del> args = line.strip().split() <del> return args and args[0] == 'return' <del> <del> def fix_single(match, lines, lineno): <del> if not lines[lineno + 1].startswith('def'): <del> return <del> block_lines = inspect.getblock(lines[lineno + 1:]) <del> func_code = ''.join(block_lines) <del> if func_code[0].isspace(): <del> node = ast.parse('if 1:\n' + func_code).body[0].body <del> else: <del> node = ast.parse(func_code).body[0] <del> response_param_name = looks_like_teardown_function(node) <del> if response_param_name is None: <del> return <del> before = lines[:lineno] <del> decorator = [match.group(1) + <del> match.group(2).replace('after_', 'teardown_') + <del> match.group(3)] <del> body = [line.replace(response_param_name, 'exception') <del> for line in block_lines if <del> not is_return_line(line)] <del> after = lines[lineno + len(block_lines) + 1:] <del> return before + decorator + body + after <del> <del> content_lines = contents.splitlines(True) <del> while 1: <del> found_one = False <del> for idx, line in enumerate(content_lines): <del> match = _after_request_re.match(line) <del> if match is None: <del> continue <del> new_content_lines = fix_single(match, content_lines, idx) <del> if new_content_lines is not None: <del> content_lines = new_content_lines <del> break <del> else: <del> break <del> <del> return ''.join(content_lines) <del> <del> <del>def get_module_autoname(filename): <del> directory, filename = os.path.split(filename) <del> if filename != '__init__.py': <del> return os.path.splitext(filename)[0] <del> return os.path.basename(directory) <del> <del> <del>def rewrite_from_imports(prefix, fromlist, lineiter): <del> import_block = [prefix, fromlist] <del> if fromlist[0] == '(' and fromlist[-1] != ')': <del> for line in lineiter: <del> import_block.append(line) <del> if line.rstrip().endswith(')'): <del> break <del> elif fromlist[-1] == '\\': <del> for line in lineiter: <del> import_block.append(line) <del> if line.rstrip().endswith('\\'): <del> break <del> <del> return ''.join(import_block).replace('Module', 'Blueprint') <del> <del> <del>def rewrite_blueprint_imports(contents): <del> new_file = [] <del> lineiter = iter(contents.splitlines(True)) <del> for line in lineiter: <del> match = _from_import_re.search(line) <del> if match is not None: <del> new_file.extend(rewrite_from_imports(match.group(), <del> line[match.end():], <del> lineiter)) <del> else: <del> new_file.append(line) <del> return ''.join(new_file) <del> <del> <del>def rewrite_for_blueprints(contents, filename): <del> modules_declared = [] <del> def handle_match(match): <del> target = match.group(1) <del> name_param = match.group(2) <del> if name_param is None: <del> modname = get_module_autoname(filename) <del> else: <del> modname = ast.literal_eval(name_param) <del> modules_declared.append((target, modname)) <del> return '%s = %s' % (target, 'Blueprint(%r, __name__' % modname) <del> new_contents = _module_constructor_re.sub(handle_match, contents) <del> <del> if modules_declared: <del> new_contents = rewrite_blueprint_imports(new_contents) <del> <del> for pattern, replacement in _blueprint_related: <del> new_contents = pattern.sub(replacement, new_contents) <del> return new_contents, dict(modules_declared) <del> <del> <del>def upgrade_python_file(filename, contents, teardown): <del> new_contents = contents <del> if teardown: <del> new_contents = fix_teardown_funcs(new_contents) <del> new_contents, modules = rewrite_for_blueprints(new_contents, filename) <del> new_contents = fix_url_for(new_contents, modules) <del> new_contents = _error_handler_re.sub('\\1.error_handler_spec[None][\\2]', <del> new_contents) <del> make_diff(filename, contents, new_contents) <del> <del> <del>def upgrade_template_file(filename, contents): <del> new_contents = fix_url_for(contents, None) <del> make_diff(filename, contents, new_contents) <del> <del> <del>def walk_path(path): <del> this_file = os.path.realpath(__file__).rstrip('c') <del> for dirpath, dirnames, filenames in os.walk(path): <del> dirnames[:] = [x for x in dirnames if not x.startswith('.')] <del> for filename in filenames: <del> filename = os.path.join(dirpath, filename) <del> if os.path.realpath(filename) == this_file: <del> continue <del> if filename.endswith('.py'): <del> yield filename, 'python' <del> # skip files that are diffs. These might be false positives <del> # when run multiple times. <del> elif not filename.endswith(('.diff', '.patch', '.udiff')): <del> with open(filename) as f: <del> contents = f.read(TEMPLATE_LOOKAHEAD) <del> if '{% for' or '{% if' or '{{ url_for' in contents: <del> yield filename, 'template' <del> <del> <del>def scan_path(path=None, teardown=True): <del> for filename, type in walk_path(path): <del> with open(filename) as f: <del> contents = f.read() <del> if type == 'python': <del> upgrade_python_file(filename, contents, teardown) <del> elif type == 'template': <del> upgrade_template_file(filename, contents) <del> <del> <del>def main(): <del> """Entrypoint""" <del> parser = OptionParser(usage='%prog [options] [paths]') <del> parser.add_option('-T', '--no-teardown-detection', dest='no_teardown', <del> action='store_true', help='Do not attempt to ' <del> 'detect teardown function rewrites.') <del> parser.add_option('-b', '--bundled-templates', dest='bundled_tmpl', <del> action='store_true', help='Indicate to the system ' <del> 'that templates are bundled with modules. Default ' <del> 'is auto detect.') <del> options, args = parser.parse_args() <del> if not args: <del> args = ['.'] <del> <del> if ast is None: <del> parser.error('Python 2.6 or later is required to run the upgrade script.') <del> <del> for path in args: <del> scan_path(path, teardown=not options.no_teardown) <del> <del> <del>if __name__ == '__main__': <del> main()
1
Text
Text
add params to getstaticprops on err.sh
c52c0389fd2eb554761ced854eb3c833859b6ec4
<ide><path>errors/invalid-getstaticprops-value.md <ide> In one of the page's `getStaticProps` the return value had the incorrect shape. <ide> Make sure to return the following shape from `getStaticProps`: <ide> <ide> ```js <del>export async function getStaticProps() { <add>export async function getStaticProps(ctx: { <add> params?: ParsedUrlQuery <add> preview?: boolean <add> previewData?: any <add>}) { <ide> return { <ide> props: { [key: string]: any } <ide> }
1
Javascript
Javascript
use internet.addresses in internet tests
5dca78799340c975d273e2babee128f978aeeb3c
<ide><path>test/internet/test-dns-cares-domains.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <add>const { addresses } = require('../common/internet'); <ide> const assert = require('assert'); <ide> const dns = require('dns'); <ide> const domain = require('domain'); <ide> const methods = [ <ide> methods.forEach(function(method) { <ide> const d = domain.create(); <ide> d.run(function() { <del> dns[method]('google.com', function() { <add> dns[method](addresses.INET_HOST, common.mustCall(() => { <ide> assert.strictEqual(process.domain, d, `${method} retains domain`); <del> }); <add> })); <ide> }); <ide> }); <ide><path>test/internet/test-dns-ipv4.js <ide> 'use strict'; <ide> const common = require('../common'); <add>const { addresses } = require('../common/internet'); <ide> const assert = require('assert'); <ide> const dns = require('dns'); <ide> const net = require('net'); <ide> function checkWrap(req) { <ide> } <ide> <ide> TEST(function test_resolve4(done) { <del> const req = dns.resolve4('www.google.com', <del> common.mustCall((err, ips) => { <del> assert.ifError(err); <add> const req = dns.resolve4( <add> addresses.INET4_HOST, <add> common.mustCall((err, ips) => { <add> assert.ifError(err); <ide> <del> assert.ok(ips.length > 0); <add> assert.ok(ips.length > 0); <ide> <del> for (let i = 0; i < ips.length; i++) { <del> assert.ok(isIPv4(ips[i])); <del> } <add> for (let i = 0; i < ips.length; i++) { <add> assert.ok(isIPv4(ips[i])); <add> } <ide> <del> done(); <del> })); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_reverse_ipv4(done) { <del> const req = dns.reverse('8.8.8.8', <del> common.mustCall((err, domains) => { <del> assert.ifError(err); <add> const req = dns.reverse( <add> addresses.INET4_IP, <add> common.mustCall((err, domains) => { <add> assert.ifError(err); <ide> <del> assert.ok(domains.length > 0); <add> assert.ok(domains.length > 0); <ide> <del> for (let i = 0; i < domains.length; i++) { <del> assert.ok(domains[i]); <del> assert.ok(typeof domains[i] === 'string'); <del> } <add> for (let i = 0; i < domains.length; i++) { <add> assert.ok(domains[i]); <add> assert.ok(typeof domains[i] === 'string'); <add> } <ide> <del> done(); <del> })); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv4_explicit(done) { <del> const req = dns.lookup('www.google.com', 4, <del> common.mustCall((err, ip, family) => { <del> assert.ifError(err); <del> assert.ok(net.isIPv4(ip)); <del> assert.strictEqual(family, 4); <add> const req = dns.lookup( <add> addresses.INET4_HOST, 4, <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(net.isIPv4(ip)); <add> assert.strictEqual(family, 4); <ide> <del> done(); <del> })); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv4_implicit(done) { <del> const req = dns.lookup('www.google.com', <del> common.mustCall((err, ip, family) => { <del> assert.ifError(err); <del> assert.ok(net.isIPv4(ip)); <del> assert.strictEqual(family, 4); <add> const req = dns.lookup( <add> addresses.INET4_HOST, <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(net.isIPv4(ip)); <add> assert.strictEqual(family, 4); <ide> <del> done(); <del> })); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv4_explicit_object(done) { <del> const req = dns.lookup('www.google.com', { <add> const req = dns.lookup(addresses.INET4_HOST, { <ide> family: 4 <ide> }, common.mustCall((err, ip, family) => { <ide> assert.ifError(err); <ide> TEST(function test_lookup_ipv4_explicit_object(done) { <ide> }); <ide> <ide> TEST(function test_lookup_ipv4_hint_addrconfig(done) { <del> const req = dns.lookup('www.google.com', { <add> const req = dns.lookup(addresses.INET4_HOST, { <ide> hints: dns.ADDRCONFIG <ide> }, common.mustCall((err, ip, family) => { <ide> assert.ifError(err); <ide> TEST(function test_lookup_localhost_ipv4(done) { <ide> <ide> TEST(function test_lookup_all_ipv4(done) { <ide> const req = dns.lookup( <del> 'www.google.com', <add> addresses.INET4_HOST, <ide> { all: true, family: 4 }, <ide> common.mustCall((err, ips) => { <ide> assert.ifError(err); <ide><path>test/internet/test-dns-ipv6.js <ide> 'use strict'; <ide> const common = require('../common'); <add>const { addresses } = require('../common/internet'); <ide> if (!common.hasIPv6) <ide> common.skip('this test, no IPv6 support'); <ide> <ide> function checkWrap(req) { <ide> } <ide> <ide> TEST(function test_resolve6(done) { <del> const req = dns.resolve6('ipv6.google.com', <del> common.mustCall((err, ips) => { <del> assert.ifError(err); <add> const req = dns.resolve6( <add> addresses.INET6_HOST, <add> common.mustCall((err, ips) => { <add> assert.ifError(err); <ide> <del> assert.ok(ips.length > 0); <add> assert.ok(ips.length > 0); <ide> <del> for (let i = 0; i < ips.length; i++) <del> assert.ok(isIPv6(ips[i])); <add> for (let i = 0; i < ips.length; i++) <add> assert.ok(isIPv6(ips[i])); <ide> <del> done(); <del> })); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_reverse_ipv6(done) { <del> const req = dns.reverse('2001:4860:4860::8888', <del> common.mustCall((err, domains) => { <del> assert.ifError(err); <add> const req = dns.reverse( <add> addresses.INET6_IP, <add> common.mustCall((err, domains) => { <add> assert.ifError(err); <ide> <del> assert.ok(domains.length > 0); <add> assert.ok(domains.length > 0); <ide> <del> for (let i = 0; i < domains.length; i++) <del> assert.ok(typeof domains[i] === 'string'); <add> for (let i = 0; i < domains.length; i++) <add> assert.ok(typeof domains[i] === 'string'); <ide> <del> done(); <del> })); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv6_explicit(done) { <del> const req = dns.lookup('ipv6.google.com', 6, <del> common.mustCall((err, ip, family) => { <del> assert.ifError(err); <del> assert.ok(isIPv6(ip)); <del> assert.strictEqual(family, 6); <add> const req = dns.lookup( <add> addresses.INET6_HOST, <add> 6, <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(isIPv6(ip)); <add> assert.strictEqual(family, 6); <ide> <del> done(); <del> })); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> /* This ends up just being too problematic to test <ide> TEST(function test_lookup_ipv6_implicit(done) { <del> var req = dns.lookup('ipv6.google.com', function(err, ip, family) { <add> var req = dns.lookup(addresses.INET6_HOST, function(err, ip, family) { <ide> assert.ifError(err); <ide> assert.ok(net.isIPv6(ip)); <ide> assert.strictEqual(family, 6); <ide> TEST(function test_lookup_ipv6_implicit(done) { <ide> */ <ide> <ide> TEST(function test_lookup_ipv6_explicit_object(done) { <del> const req = dns.lookup('ipv6.google.com', { <add> const req = dns.lookup(addresses.INET6_HOST, { <ide> family: 6 <ide> }, common.mustCall((err, ip, family) => { <ide> assert.ifError(err); <ide> TEST(function test_lookup_ipv6_explicit_object(done) { <ide> }); <ide> <ide> TEST(function test_lookup_ipv6_hint(done) { <del> const req = dns.lookup('www.google.com', { <add> const req = dns.lookup(addresses.INET6_HOST, { <ide> family: 6, <ide> hints: dns.V4MAPPED <ide> }, common.mustCall((err, ip, family) => { <ide> TEST(function test_lookup_ipv6_hint(done) { <ide> if (common.isFreeBSD) { <ide> assert(err instanceof Error); <ide> assert.strictEqual(err.code, 'EAI_BADFLAGS'); <del> assert.strictEqual(err.hostname, 'www.google.com'); <add> assert.strictEqual(err.hostname, addresses.INET_HOST); <ide> assert.ok(/getaddrinfo EAI_BADFLAGS/.test(err.message)); <ide> done(); <ide> return; <ide> TEST(function test_lookup_ipv6_hint(done) { <ide> }); <ide> <ide> TEST(function test_lookup_ip_ipv6(done) { <del> const req = dns.lookup('::1', <del> common.mustCall((err, ip, family) => { <del> assert.ifError(err); <del> assert.ok(isIPv6(ip)); <del> assert.strictEqual(family, 6); <add> const req = dns.lookup( <add> '::1', <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(isIPv6(ip)); <add> assert.strictEqual(family, 6); <ide> <del> done(); <del> })); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_all_ipv6(done) { <ide> const req = dns.lookup( <del> 'www.google.com', <add> addresses.INET6_HOST, <ide> { all: true, family: 6 }, <ide> common.mustCall((err, ips) => { <ide> assert.ifError(err); <ide><path>test/internet/test-dns-setserver-in-callback-of-resolve4.js <ide> // a crash or not. If it doesn't crash, the test succeeded. <ide> <ide> const common = require('../common'); <add>const { addresses } = require('../common/internet'); <ide> const dns = require('dns'); <ide> <del>dns.resolve4('google.com', common.mustCall(function(/* err, nameServers */) { <del> dns.setServers([ '8.8.8.8' ]); <del>})); <add>dns.resolve4( <add> addresses.INET4_HOST, <add> common.mustCall(function(/* err, nameServers */) { <add> dns.setServers([ addresses.DNS4_SERVER ]); <add> })); <ide><path>test/internet/test-dns.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <add>const { addresses } = require('../common/internet'); <ide> const assert = require('assert'); <ide> const dns = require('dns'); <ide> const net = require('net'); <ide> TEST(function test_reverse_bogus(done) { <ide> }); <ide> <ide> TEST(function test_resolve4_ttl(done) { <del> const req = dns.resolve4('google.com', { ttl: true }, function(err, result) { <add> const req = dns.resolve4(addresses.INET4_HOST, { <add> ttl: true <add> }, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> TEST(function test_resolve4_ttl(done) { <ide> }); <ide> <ide> TEST(function test_resolve6_ttl(done) { <del> const req = dns.resolve6('google.com', { ttl: true }, function(err, result) { <add> const req = dns.resolve6(addresses.INET6_HOST, { <add> ttl: true <add> }, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> TEST(function test_resolve6_ttl(done) { <ide> }); <ide> <ide> TEST(function test_resolveMx(done) { <del> const req = dns.resolveMx('gmail.com', function(err, result) { <add> const req = dns.resolveMx(addresses.MX_HOST, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> TEST(function test_resolveMx(done) { <ide> }); <ide> <ide> TEST(function test_resolveMx_failure(done) { <del> const req = dns.resolveMx('something.invalid', function(err, result) { <add> const req = dns.resolveMx(addresses.INVALID_HOST, function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveMx_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveNs(done) { <del> const req = dns.resolveNs('rackspace.com', function(err, names) { <add> const req = dns.resolveNs(addresses.NS_HOST, function(err, names) { <ide> assert.ifError(err); <ide> assert.ok(names.length > 0); <ide> <ide> TEST(function test_resolveNs(done) { <ide> }); <ide> <ide> TEST(function test_resolveNs_failure(done) { <del> const req = dns.resolveNs('something.invalid', function(err, result) { <add> const req = dns.resolveNs(addresses.INVALID_HOST, function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveNs_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveSrv(done) { <del> const req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { <add> const req = dns.resolveSrv(addresses.SRV_HOST, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> TEST(function test_resolveSrv(done) { <ide> }); <ide> <ide> TEST(function test_resolveSrv_failure(done) { <del> const req = dns.resolveSrv('something.invalid', function(err, result) { <add> const req = dns.resolveSrv(addresses.INVALID_HOST, function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveSrv_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolvePtr(done) { <del> const req = dns.resolvePtr('8.8.8.8.in-addr.arpa', function(err, result) { <add> const req = dns.resolvePtr(addresses.PTR_HOST, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> TEST(function test_resolvePtr(done) { <ide> }); <ide> <ide> TEST(function test_resolvePtr_failure(done) { <del> const req = dns.resolvePtr('something.invalid', function(err, result) { <add> const req = dns.resolvePtr(addresses.INVALID_HOST, function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolvePtr_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveNaptr(done) { <del> const req = dns.resolveNaptr('sip2sip.info', function(err, result) { <add> const req = dns.resolveNaptr(addresses.NAPTR_HOST, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <ide> TEST(function test_resolveNaptr(done) { <ide> }); <ide> <ide> TEST(function test_resolveNaptr_failure(done) { <del> const req = dns.resolveNaptr('something.invalid', function(err, result) { <add> const req = dns.resolveNaptr(addresses.INVALID_HOST, function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveNaptr_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveSoa(done) { <del> const req = dns.resolveSoa('nodejs.org', function(err, result) { <add> const req = dns.resolveSoa(addresses.SOA_HOST, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result); <ide> assert.strictEqual(typeof result, 'object'); <ide> TEST(function test_resolveSoa(done) { <ide> }); <ide> <ide> TEST(function test_resolveSoa_failure(done) { <del> const req = dns.resolveSoa('something.invalid', function(err, result) { <add> const req = dns.resolveSoa(addresses.INVALID_HOST, function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveSoa_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveCname(done) { <del> const req = dns.resolveCname('www.microsoft.com', function(err, names) { <add> const req = dns.resolveCname(addresses.CNAME_HOST, function(err, names) { <ide> assert.ifError(err); <ide> assert.ok(names.length > 0); <ide> <ide> TEST(function test_resolveCname(done) { <ide> }); <ide> <ide> TEST(function test_resolveCname_failure(done) { <del> const req = dns.resolveCname('something.invalid', function(err, result) { <add> const req = dns.resolveCname(addresses.INVALID_HOST, function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveCname_failure(done) { <ide> <ide> <ide> TEST(function test_resolveTxt(done) { <del> const req = dns.resolveTxt('google.com', function(err, records) { <add> const req = dns.resolveTxt(addresses.TXT_HOST, function(err, records) { <ide> assert.ifError(err); <ide> assert.strictEqual(records.length, 1); <ide> assert.ok(util.isArray(records[0])); <ide> TEST(function test_resolveTxt(done) { <ide> }); <ide> <ide> TEST(function test_resolveTxt_failure(done) { <del> const req = dns.resolveTxt('something.invalid', function(err, result) { <add> const req = dns.resolveTxt(addresses.INVALID_HOST, function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveTxt_failure(done) { <ide> <ide> <ide> TEST(function test_lookup_failure(done) { <del> const req = dns.lookup('this.hostname.is.invalid', 4, (err, ip, family) => { <add> const req = dns.lookup(addresses.INVALID_HOST, 4, (err, ip, family) => { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, dns.NOTFOUND); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> assert.ok(!/ENOENT/.test(err.message)); <del> assert.ok(err.message.includes('this.hostname.is.invalid')); <add> assert.ok(err.message.includes(addresses.INVALID_HOST)); <ide> <ide> done(); <ide> }); <ide> TEST(function test_lookup_null_all(done) { <ide> <ide> <ide> TEST(function test_lookup_all_mixed(done) { <del> const req = dns.lookup('www.google.com', { all: true }, function(err, ips) { <add> const req = dns.lookup(addresses.INET_HOST, { <add> all: true <add> }, function(err, ips) { <ide> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.ok(ips.length > 0); <ide> TEST(function test_reverse_failure(done) { <ide> <ide> <ide> TEST(function test_lookup_failure(done) { <del> const req = dns.lookup('this.hostname.is.invalid', (err) => { <add> const req = dns.lookup(addresses.INVALID_HOST, (err) => { <ide> assert(err instanceof Error); <ide> assert.strictEqual(err.code, 'ENOTFOUND'); // Silly error code... <del> assert.strictEqual(err.hostname, 'this.hostname.is.invalid'); <del> assert.ok(err.message.includes('this.hostname.is.invalid')); <add> assert.strictEqual(err.hostname, addresses.INVALID_HOST); <add> assert.ok(err.message.includes(addresses.INVALID_HOST)); <ide> <ide> done(); <ide> }); <ide> TEST(function test_lookup_failure(done) { <ide> <ide> <ide> TEST(function test_resolve_failure(done) { <del> const req = dns.resolve4('this.hostname.is.invalid', (err) => { <add> const req = dns.resolve4(addresses.INVALID_HOST, (err) => { <ide> assert(err instanceof Error); <ide> <ide> switch (err.code) { <ide> TEST(function test_resolve_failure(done) { <ide> break; <ide> } <ide> <del> assert.strictEqual(err.hostname, 'this.hostname.is.invalid'); <del> assert.ok(err.message.includes('this.hostname.is.invalid')); <add> assert.strictEqual(err.hostname, addresses.INVALID_HOST); <add> assert.ok(err.message.includes(addresses.INVALID_HOST)); <ide> <ide> done(); <ide> }); <ide> TEST(function test_resolve_failure(done) { <ide> <ide> let getaddrinfoCallbackCalled = false; <ide> <del>console.log('looking up nodejs.org...'); <add>console.log(`looking up ${addresses.INET4_HOST}..`); <ide> <ide> const cares = process.binding('cares_wrap'); <ide> const req = new cares.GetAddrInfoReqWrap(); <del>cares.getaddrinfo(req, 'nodejs.org', 4, /* hints */ 0, /* verbatim */ true); <add>cares.getaddrinfo(req, addresses.INET4_HOST, 4, <add> /* hints */ 0, /* verbatim */ true); <ide> <ide> req.oncomplete = function(err, domains) { <ide> assert.strictEqual(err, 0); <del> console.log('nodejs.org = ', domains); <add> console.log(`${addresses.INET4_HOST} = ${domains}`); <ide> assert.ok(Array.isArray(domains)); <ide> assert.ok(domains.length >= 1); <ide> assert.strictEqual(typeof domains[0], 'string'); <ide> process.on('exit', function() { <ide> }); <ide> <ide> <del>assert.doesNotThrow(() => dns.lookup('nodejs.org', 6, common.mustCall())); <add>assert.doesNotThrow(() => <add> dns.lookup(addresses.INET6_HOST, 6, common.mustCall())); <ide> <del>assert.doesNotThrow(() => dns.lookup('nodejs.org', {}, common.mustCall())); <add>assert.doesNotThrow(() => <add> dns.lookup(addresses.INET_HOST, {}, common.mustCall())); <ide> <del>assert.doesNotThrow(() => dns.lookupService('0.0.0.0', '0', common.mustCall())); <add>assert.doesNotThrow(() => <add> dns.lookupService('0.0.0.0', '0', common.mustCall())); <ide> <del>assert.doesNotThrow(() => dns.lookupService('0.0.0.0', 0, common.mustCall())); <add>assert.doesNotThrow(() => <add> dns.lookupService('0.0.0.0', 0, common.mustCall())); <ide><path>test/internet/test-http-https-default-ports.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <add>const { addresses } = require('../common/internet'); <ide> <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> const https = require('https'); <ide> <ide> const http = require('http'); <ide> <del>https.get('https://www.google.com/', common.mustCall(function(res) { <add>https.get(`https://${addresses.INET_HOST}/`, common.mustCall(function(res) { <ide> res.resume(); <ide> })); <ide> <del>http.get('http://www.google.com/', common.mustCall(function(res) { <add>http.get(`http://${addresses.INET_HOST}/`, common.mustCall(function(res) { <ide> res.resume(); <ide> }));
6
Python
Python
improve batchnorm documentation
58fb2b8af56c76c332cc7dfeada7496687d65163
<ide><path>keras/layers/normalization.py <ide> <ide> <ide> class BatchNormalization(Layer): <del> '''Normalize the activations of the previous layer at each batch. <add> '''Normalize the activations of the previous layer at each batch, <add> i.e. applies a transformation that maintains the mean activation <add> close to 0. and the activation standard deviation close to 1. <ide> <ide> # Input shape <ide> Arbitrary. Use the keyword argument `input_shape` <ide> class BatchNormalization(Layer): <ide> epsilon: small float > 0. Fuzz parameter. <ide> mode: integer, 0 or 1. <ide> - 0: feature-wise normalization. <del> - 1: sample-wise normalization. <add> If the input has multiple feature dimensions, <add> each will be normalized separately <add> (e.g. for an image input with shape <add> `(channels, rows, cols)`, <add> each combination of a channel, row and column <add> will be normalized separately). <add> - 1: sample-wise normalization. This mode assumes a 2D input. <ide> momentum: momentum in the computation of the <ide> exponential average of the mean and standard deviation <ide> of the data, for feature-wise normalization.
1
Ruby
Ruby
remove unused require
b6d86add73a659554a42918d54b607cec7b517bc
<ide><path>activestorage/app/models/active_storage/variant.rb <ide> # frozen_string_literal: true <ide> <del>require "ostruct" <del> <ide> # Image blobs can have variants that are the result of a set of transformations applied to the original. <ide> # These variants are used to create thumbnails, fixed-size avatars, or any other derivative image from the <ide> # original.
1
PHP
PHP
remove unnecessary sprintf
72965f793c7c974a3e33548d1ec11a16ca35d155
<ide><path>lib/Cake/Cache/Engine/MemcachedEngine.php <ide> protected function _setOptions() { <ide> <ide> if (!array_key_exists($this->settings['serializer'], self::$serializer)) { <ide> throw new CacheException( <del> __d('cake_dev', sprintf('%s is not a valid serializer engine for Memcached', $this->settings['serializer'])) <add> __d('cake_dev', '%s is not a valid serializer engine for Memcached', $this->settings['serializer']) <ide> ); <ide> } <ide>
1
Text
Text
fix spelling and grammar
8bd3df35a22cbade28568a580fa05e820ef31489
<ide><path>guide/english/r/functions/index.md <ide> Functions can be named and called repeatedly or can be run anonymously in place <ide> Developing full understanding of R functions requires understanding of environments. <ide> Environments are simply a way to manage objects. An example of environments in action is that you can use a redundant variable <ide> name within a function, that won't be affected if the larger runtime already has the same variable. Additionally, if a <del>function calls a variable not defined within the function it will check the higher level environment for that variable. <add>function calls a variable which is not defined within the function, it will check the higher level environment for that variable. <ide> <ide> ### Syntax <ide> <ide> In R, a function definition has the following features: <ide> <ide> 1. The keyword `function` <del>2. a function name <del>3. input parameters (optional) <del>4. some block of code to execute <del>5. a return statement (optional) <add>2. A function name <add>3. Input parameters (optional) <add>4. Some block of code to execute <add>5. A return statement (optional) <ide> <ide> ```{r} <ide> # a function with no parameters or returned values <ide> multiply = function(val1, val2){ <ide> multiply(3, 5) # prints 15 to the console <ide> ``` <ide> <del>Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegent code reuse without explicitly re-writing sections of code. This makes code both more readable, makes for easier debugging, and limits typing errors. <add>Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegant code reuse without explicitly re-writing sections of code. This makes code both more readable, makes for easier debugging, and limits typing errors. <ide> <ide> Functions in R are created using the `function` keyword, along with a function name and function parameters inside parentheses. <ide> <ide> its factorial with the `factorial()`. <ide> <ide> - The data that you pass into the function is called the function’s argument. <ide> <del>- You can simulate a roll of the die with R’s `sample()`function. The `sample()` function takes two arguments:a vector named x and a number named size. For example: <add>- You can simulate a roll of the die with R’s `sample()`function. The `sample()` function takes two arguments: a vector named `x` and a number named `size`. For example: <ide> <ide> ```r <ide> > sample(x = 1:4, size = 2)
1
Javascript
Javascript
add test for
636be2466ef303b5a48ef35fb4014fce13398dd3
<ide><path>test/integration/amphtml/test/index.test.js <ide> describe('AMP Usage', () => { <ide> }) <ide> }) <ide> <add> describe('AMP dev no-warn', () => { <add> let dynamicAppPort <add> let ampDynamic <add> <add> it('should not warn on valid amp', async () => { <add> let inspectPayload = '' <add> dynamicAppPort = await findPort() <add> ampDynamic = await launchApp(join(__dirname, '../'), dynamicAppPort, { <add> onStdout (msg) { <add> inspectPayload += msg <add> } <add> }) <add> <add> await renderViaHTTP(dynamicAppPort, '/only-amp') <add> <add> await killApp(ampDynamic) <add> <add> expect(inspectPayload).not.toContain('warn') <add> }) <add> }) <add> <ide> describe('AMP dev mode', () => { <ide> let dynamicAppPort <ide> let ampDynamic
1
Ruby
Ruby
inline the job wrappers
501cc60ff2528ba75c0bf0715918516864546539
<ide><path>lib/active_job/job_wrappers/delayed_job_wrapper.rb <del>module ActiveJob <del> module JobWrappers <del> class DelayedJobWrapper <del> def perform(job, *args) <del> job.perform(*ActiveJob::Parameters.deserialize(args)) <del> end <del> end <del> end <del>end <ide><path>lib/active_job/job_wrappers/resque_wrapper.rb <del>require 'resque' <del> <del>require 'active_support/core_ext/enumerable' <del>require 'active_support/core_ext/array/access' <del> <del>module ActiveJob <del> module JobWrappers <del> class ResqueWrapper <del> class << self <del> def wrap(job, args) <del> [ new(job), *args.prepend(job) ] <del> end <del> <del> def perform(job_name, *args) <del> job_name.constantize.perform(*ActiveJob::Parameters.deserialize(args)) <del> end <del> end <del> <del> <del> def initialize(job) <del> @queue = job.queue_name <del> end <del> <del> def to_s <del> self.class.to_s <del> end <del> end <del> end <del>end <ide><path>lib/active_job/job_wrappers/sidekiq_wrapper.rb <del>require 'active_job/parameters' <del> <del>module ActiveJob <del> module JobWrappers <del> class SidekiqWrapper <del> include Sidekiq::Worker <del> <del> def perform(job_name, *args) <del> job_name.constantize.perform(*ActiveJob::Parameters.deserialize(args)) <del> end <del> end <del> end <del>end <ide><path>lib/active_job/job_wrappers/sucker_punch_wrapper.rb <del>module ActiveJob <del> module JobWrappers <del> class SuckerPunchWrapper <del> include SuckerPunch::Job <del> <del> def perform(job_name, *args) <del> job_name.perform(*ActiveJob::Parameters.deserialize(args)) <del> end <del> end <del> end <del>end <ide><path>lib/active_job/queue_adapters/delayed_job_adapter.rb <ide> require 'delayed_job' <del>require 'active_job/job_wrappers/delayed_job_wrapper' <ide> <ide> module ActiveJob <ide> module QueueAdapters <ide> class DelayedJobAdapter <ide> class << self <ide> def queue(job, *args) <del> JobWrappers::DelayedJobWrapper.new.delay(queue: job.queue_name).perform(job, *args) <add> JobWrapper.new.delay(queue: job.queue_name).perform(job, *args) <add> end <add> end <add> <add> class JobWrapper <add> def perform(job, *args) <add> job.perform(*ActiveJob::Parameters.deserialize(args)) <ide> end <ide> end <ide> end <ide><path>lib/active_job/queue_adapters/resque_adapter.rb <ide> require 'resque' <del>require 'active_job/job_wrappers/resque_wrapper' <add>require 'active_support/core_ext/enumerable' <add>require 'active_support/core_ext/array/access' <ide> <ide> module ActiveJob <ide> module QueueAdapters <ide> class ResqueAdapter <ide> class << self <ide> def queue(job, *args) <del> Resque.enqueue *JobWrappers::ResqueWrapper.wrap(job, args) <add> Resque.enqueue *JobWrapper.wrap(job, args) <add> end <add> end <add> <add> class JobWrapper <add> class << self <add> def wrap(job, args) <add> [ new(job), *args.prepend(job) ] <add> end <add> <add> def perform(job_name, *args) <add> job_name.constantize.perform(*ActiveJob::Parameters.deserialize(args)) <add> end <add> end <add> <add> def initialize(job) <add> @queue = job.queue_name <add> end <add> <add> def to_s <add> self.class.to_s <ide> end <ide> end <ide> end <ide><path>lib/active_job/queue_adapters/sidekiq_adapter.rb <ide> require 'sidekiq' <del>require 'active_job/job_wrappers/sidekiq_wrapper' <ide> <ide> module ActiveJob <ide> module QueueAdapters <ide> class SidekiqAdapter <ide> class << self <ide> def queue(job, *args) <del> JobWrappers::SidekiqWrapper.perform_async(job, *args) <add> JobWrapper.perform_async(job, *args) <add> end <add> end <add> <add> class JobWrapper <add> include Sidekiq::Worker <add> <add> def perform(job_name, *args) <add> job_name.constantize.perform(*ActiveJob::Parameters.deserialize(args)) <ide> end <ide> end <ide> end <ide><path>lib/active_job/queue_adapters/sucker_punch_adapter.rb <ide> require 'sucker_punch' <del>require 'active_job/job_wrappers/sucker_punch_wrapper' <ide> <ide> module ActiveJob <ide> module QueueAdapters <ide> class SuckerPunchAdapter <ide> class << self <ide> def queue(job, *args) <del> JobWrappers::SuckerPunchWrapper.new.async.perform(job, *args) <add> JobWrapper.new.async.perform(job, *args) <add> end <add> end <add> <add> class JobWrapper <add> include SuckerPunch::Job <add> <add> def perform(job_name, *args) <add> job_name.perform(*ActiveJob::Parameters.deserialize(args)) <ide> end <ide> end <ide> end
8
Ruby
Ruby
use gem api rather than env to set paths
a5b12a33c2160cc1ff9ca9f42171d774ec392d5a
<ide><path>Library/Homebrew/test/support/helper/spec/shared_context/integration_test.rb <ide> def brew(*args) <ide> ruby_args = HOMEBREW_RUBY_EXEC_ARGS.dup <ide> if ENV["HOMEBREW_TESTS_COVERAGE"] <ide> simplecov_spec = Gem.loaded_specs["simplecov"] <del> specs = [simplecov_spec] <del> simplecov_spec.runtime_dependencies.each do |dep| <del> specs += dep.to_specs <del> rescue Gem::LoadError => e <del> onoe e <add> parallel_tests_spec = Gem.loaded_specs["parallel_tests"] <add> specs = [] <add> [simplecov_spec, parallel_tests_spec].each do |spec| <add> specs << spec <add> spec.runtime_dependencies.each do |dep| <add> specs += dep.to_specs <add> rescue Gem::LoadError => e <add> onoe e <add> end <ide> end <ide> libs = specs.flat_map do |spec| <ide> full_gem_path = spec.full_gem_path <ide><path>Library/Homebrew/utils/gems.rb <ide> def odie_if_defined(message) <ide> def setup_gem_environment!(gem_home: nil, gem_bindir: nil, setup_path: true) <ide> # Match where our bundler gems are. <ide> gem_home ||= "#{ENV["HOMEBREW_LIBRARY"]}/Homebrew/vendor/bundle/ruby/#{RbConfig::CONFIG["ruby_version"]}" <del> ENV["GEM_HOME"] = gem_home <del> ENV["GEM_PATH"] = gem_home <add> Gem.paths = { <add> "GEM_HOME" => gem_home, <add> "GEM_PATH" => gem_home, <add> } <ide> <ide> # Set TMPDIR so Xcode's `make` doesn't fall back to `/var/tmp/`, <ide> # which may be not user-writable. <ide> ENV["TMPDIR"] = ENV["HOMEBREW_TEMP"] <ide> <del> # Make RubyGems notice environment changes. <del> Gem.clear_paths <del> Gem::Specification.reset <del> <ide> return unless setup_path <ide> <ide> # Add necessary Ruby and Gem binary directories to `PATH`. <ide><path>Library/Homebrew/utils/rubocop.rb <ide> # typed: false <ide> # frozen_string_literal: true <ide> <add>require_relative "gems" <add>Homebrew.setup_gem_environment! <add> <ide> require_relative "../warnings" <ide> <ide> Warnings.ignore :parser_syntax do
3
Javascript
Javascript
add unit test for fix to
a2c2d68d7f29eb543d937a72bdf4b5399b7aa14a
<ide><path>test/unit/ajax.js <ide> test("jQuery.getScript(String, Function) - no callback", function() { <ide> }); <ide> <ide> test("jQuery.ajax() - JSONP, Local", function() { <del> expect(8); <add> expect(9); <ide> <ide> var count = 0; <del> function plus(){ if ( ++count == 8 ) start(); } <add> function plus(){ if ( ++count == 9 ) start(); } <ide> <ide> stop(); <ide> <ide> test("jQuery.ajax() - JSONP, Local", function() { <ide> plus(); <ide> } <ide> }); <add> <add> //#7578 <add> jQuery.ajax({ <add> url: "data/jsonp.php", <add> dataType: "jsonp", <add> beforeSend: function(){ <add> strictEqual( this.cache, false, "cache must be false on JSON request" ); <add> plus(); <add> return false; <add> } <add> }); <ide> }); <ide> <ide> test("JSONP - Custom JSONP Callback", function() {
1
Java
Java
add contextualname to http observations
b9070ae75222091ccb49267e27341689ec1687c6
<ide><path>spring-web/src/main/java/org/springframework/http/client/observation/DefaultClientHttpObservationConvention.java <ide> public String getName() { <ide> return this.name; <ide> } <ide> <add> @Override <add> public String getContextualName(ClientHttpObservationContext context) { <add> return "http " + context.getCarrier().getMethod().name().toLowerCase(); <add> } <add> <ide> @Override <ide> public KeyValues getLowCardinalityKeyValues(ClientHttpObservationContext context) { <ide> return KeyValues.of(uri(context), method(context), status(context), exception(context), outcome(context)); <ide><path>spring-web/src/main/java/org/springframework/web/observation/DefaultHttpRequestsObservationConvention.java <ide> public String getName() { <ide> return this.name; <ide> } <ide> <add> @Override <add> public String getContextualName(HttpRequestsObservationContext context) { <add> return "http " + context.getCarrier().getMethod().toLowerCase(); <add> } <add> <ide> @Override <ide> public KeyValues getLowCardinalityKeyValues(HttpRequestsObservationContext context) { <ide> return KeyValues.of(method(context), uri(context), status(context), exception(context), outcome(context)); <ide><path>spring-web/src/main/java/org/springframework/web/observation/reactive/DefaultHttpRequestsObservationConvention.java <ide> public String getName() { <ide> return this.name; <ide> } <ide> <add> @Override <add> public String getContextualName(HttpRequestsObservationContext context) { <add> return "http " + context.getCarrier().getMethod().name().toLowerCase(); <add> } <add> <ide> @Override <ide> public KeyValues getLowCardinalityKeyValues(HttpRequestsObservationContext context) { <ide> return KeyValues.of(method(context), uri(context), status(context), exception(context), outcome(context)); <ide><path>spring-web/src/test/java/org/springframework/http/client/observation/DefaultClientHttpObservationConventionTests.java <ide> class DefaultClientHttpObservationConventionTests { <ide> <ide> private final DefaultClientHttpObservationConvention observationConvention = new DefaultClientHttpObservationConvention(); <ide> <add> @Test <add> void shouldHaveName() { <add> assertThat(this.observationConvention.getName()).isEqualTo("http.client.requests"); <add> } <add> <add> @Test <add> void shouldHaveContextualName() { <add> ClientHttpObservationContext context = new ClientHttpObservationContext(); <add> context.setCarrier(new MockClientHttpRequest(HttpMethod.GET, "/test")); <add> assertThat(this.observationConvention.getContextualName(context)).isEqualTo("http get"); <add> } <add> <ide> @Test <ide> void supportsOnlyClientHttpObservationContext() { <ide> assertThat(this.observationConvention.supportsContext(new ClientHttpObservationContext())).isTrue(); <ide><path>spring-web/src/test/java/org/springframework/web/observation/DefaultHttpRequestsObservationConventionTests.java <ide> class DefaultHttpRequestsObservationConventionTests { <ide> <ide> private final DefaultHttpRequestsObservationConvention convention = new DefaultHttpRequestsObservationConvention(); <ide> <del> private final MockHttpServletRequest request = new MockHttpServletRequest(); <add> private final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/resource"); <ide> <ide> private final MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> void shouldHaveDefaultName() { <ide> assertThat(convention.getName()).isEqualTo("http.server.requests"); <ide> } <ide> <add> @Test <add> void shouldHaveContextualName() { <add> assertThat(convention.getContextualName(this.context)).isEqualTo("http get"); <add> } <add> <ide> @Test <ide> void supportsOnlyHttpRequestsObservationContext() { <ide> assertThat(this.convention.supportsContext(this.context)).isTrue(); <ide> void addsKeyValuesForExchange() { <ide> <ide> @Test <ide> void addsKeyValuesForExchangeWithPathPattern() { <del> this.request.setMethod("GET"); <ide> this.request.setRequestURI("/test/resource"); <ide> this.request.setPathInfo("/test/resource"); <ide> this.context.setPathPattern("/test/{name}"); <ide> void addsKeyValuesForExchangeWithPathPattern() { <ide> <ide> @Test <ide> void addsKeyValuesForErrorExchange() { <del> this.request.setMethod("GET"); <ide> this.request.setRequestURI("/test/resource"); <ide> this.request.setPathInfo("/test/resource"); <ide> this.context.setError(new IllegalArgumentException("custom error")); <ide> void addsKeyValuesForErrorExchange() { <ide> <ide> @Test <ide> void addsKeyValuesForRedirectExchange() { <del> this.request.setMethod("GET"); <ide> this.request.setRequestURI("/test/redirect"); <ide> this.request.setPathInfo("/test/redirect"); <ide> this.response.setStatus(302); <ide> void addsKeyValuesForRedirectExchange() { <ide> <ide> @Test <ide> void addsKeyValuesForNotFoundExchange() { <del> this.request.setMethod("GET"); <ide> this.request.setRequestURI("/test/notFound"); <ide> this.request.setPathInfo("/test/notFound"); <ide> this.response.setStatus(404); <ide><path>spring-web/src/test/java/org/springframework/web/observation/reactive/DefaultHttpRequestsObservationConventionTests.java <ide> void shouldHaveDefaultName() { <ide> assertThat(convention.getName()).isEqualTo("http.server.requests"); <ide> } <ide> <add> @Test <add> void shouldHaveContextualName() { <add> ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test/resource")); <add> HttpRequestsObservationContext context = new HttpRequestsObservationContext(exchange); <add> assertThat(convention.getContextualName(context)).isEqualTo("http get"); <add> } <add> <ide> @Test <ide> void supportsOnlyHttpRequestsObservationContext() { <ide> ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/test/resource")); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientObservationConvention.java <ide> public String getName() { <ide> return this.name; <ide> } <ide> <add> @Override <add> public String getContextualName(ClientObservationContext context) { <add> return "http " + context.getCarrier().method().name().toLowerCase(); <add> } <add> <ide> @Override <ide> public KeyValues getLowCardinalityKeyValues(ClientObservationContext context) { <ide> return KeyValues.of(uri(context), method(context), status(context), exception(context), outcome(context)); <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientObservationConventionTests.java <ide> class DefaultClientObservationConventionTests { <ide> <ide> private DefaultClientObservationConvention observationConvention = new DefaultClientObservationConvention(); <ide> <add> @Test <add> void shouldHaveName() { <add> assertThat(this.observationConvention.getName()).isEqualTo("http.client.requests"); <add> } <add> <add> @Test <add> void shouldHaveContextualName() { <add> ClientObservationContext context = new ClientObservationContext(); <add> context.setCarrier(ClientRequest.create(HttpMethod.GET, URI.create("/test")).build()); <add> assertThat(this.observationConvention.getContextualName(context)).isEqualTo("http get"); <add> } <add> <ide> @Test <ide> void shouldOnlySupportWebClientObservationContext() { <ide> assertThat(this.observationConvention.supportsContext(new ClientObservationContext())).isTrue();
8
Python
Python
fix meta path
8c758ed1ebc3d35f03707e593b83b214d40f434b
<ide><path>spacy/tests/test_misc.py <ide> def test_load_model_version_compat(): <ide> <ide> # additional compatible upper pin <ide> nlp.meta["spacy_version"] = ">=2.3.0,<2.4.0" <del> srsly.write_json(Path(d / "meta.json"), nlp.meta) <add> srsly.write_json(meta_path, nlp.meta) <ide> util.get_model_meta(d) <ide> <ide> # incompatible older version <ide> nlp.meta["spacy_version"] = ">=2.2.5" <del> srsly.write_json(Path(d / "meta.json"), nlp.meta) <add> srsly.write_json(meta_path, nlp.meta) <ide> with pytest.warns(UserWarning): <ide> util.get_model_meta(d) <ide> <ide> # invalid version specification <ide> nlp.meta["spacy_version"] = ">@#$%_invalid_version" <del> srsly.write_json(Path(d / "meta.json"), nlp.meta) <add> srsly.write_json(meta_path, nlp.meta) <ide> with pytest.warns(UserWarning): <ide> util.get_model_meta(d)
1
Javascript
Javascript
enhance dev error reports
f378f54ac3cda43073b4a45d31921359584b7fa0
<ide><path>api-server/server/middlewares/error-handlers.js <ide> import { homeLocation } from '../../../config/env'; <ide> <ide> import { unwrapHandledError } from '../utils/create-handled-error.js'; <ide> <add>const errTemplate = (error, req) => { <add> const { message, stack } = error; <add> return ` <add>Error: ${message} <add>Is authenticated user: ${!!req.user} <add>Headers: ${JSON.stringify(req.headers, null, 2)} <add>Original request: ${req.originalMethod} ${req.originalUrl} <add>Stack: ${stack} <add> <add>// raw <add>${JSON.stringify(error, null, 2)} <add> <add>`; <add>}; <add> <ide> const isDev = process.env.FREECODECAMP_NODE_ENV !== 'production'; <ide> <ide> export default function prodErrorHandler() { <ide> export default function prodErrorHandler() { <ide> 'Oops! Something went wrong. Please try again in a moment.'; <ide> <ide> if (isDev) { <del> console.error(err); <add> console.error(errTemplate(err, req)); <ide> } <ide> <ide> if (type === 'html') {
1
Python
Python
improve handing of files and subprocesses
9c09f0105b6a62c0dfe9167fa78c0fb59878e222
<ide><path>numpy/linalg/lapack_lite/make_lite.py <ide> #!/usr/bin/env python <add>""" <add>Usage: make_lite.py <wrapped_routines_file> <lapack_dir> <output_dir> <add> <add>Typical invocation: <add> <add> make_lite.py wrapped_routines /tmp/lapack-3.x.x . <add> <add>Requires the following to be on the path: <add> * f2c <add> <add>""" <ide> from __future__ import division, absolute_import, print_function <ide> <del>import sys, os <add>import sys <add>import os <add>import subprocess <add> <ide> import fortran <ide> import clapack_scrub <ide> <del>try: set <del>except NameError: <del> from sets import Set as set <del> <ide> # Arguments to pass to f2c. You'll always want -A for ANSI C prototypes <ide> # Others of interest: -a to not make variables static by default <ide> # -C to check array subscripts <del>F2C_ARGS = '-A' <add>F2C_ARGS = ['-A'] <ide> <ide> # The header to add to the top of the *_lite.c file. Note that dlamch_() calls <ide> # will be replaced by the macros below by clapack_scrub.scrub_source() <ide> def dependencies(self): <ide> self._dependencies = [d.lower() for d in deps] <ide> return self._dependencies <ide> <add> def __repr__(self): <add> return "FortranRoutine({!r}, filename={!r})".format(self.name, self.filename) <add> <ide> class UnknownFortranRoutine(FortranRoutine): <ide> """Wrapper for a Fortran routine for which the corresponding file <ide> is not known. <ide> def getLapackRoutines(wrapped_routines, ignores, lapack_dir): <ide> return library <ide> <ide> def getWrappedRoutineNames(wrapped_routines_file): <del> fo = open(wrapped_routines_file) <ide> routines = [] <ide> ignores = [] <del> for line in fo: <del> line = line.strip() <del> if not line or line.startswith('#'): <del> continue <del> if line.startswith('IGNORE:'): <del> line = line[7:].strip() <del> ig = line.split() <del> ignores.extend(ig) <del> else: <del> routines.append(line) <add> with open(wrapped_routines_file) as fo: <add> for line in fo: <add> line = line.strip() <add> if not line or line.startswith('#'): <add> continue <add> if line.startswith('IGNORE:'): <add> line = line[7:].strip() <add> ig = line.split() <add> ignores.extend(ig) <add> else: <add> routines.append(line) <ide> return routines, ignores <ide> <add>types = {'blas', 'zlapack', 'dlapack'} <add> <ide> def dumpRoutineNames(library, output_dir): <del> for typename in ['unknown', 'blas', 'dlapack', 'zlapack']: <add> for typename in {'unknown'} | types: <ide> routines = library.allRoutinesByType(typename) <ide> filename = os.path.join(output_dir, typename + '_routines.lst') <del> fo = open(filename, 'w') <del> for r in routines: <del> deps = r.dependencies() <del> fo.write('%s: %s\n' % (r.name, ' '.join(deps))) <del> fo.close() <add> with open(filename, 'w') as fo: <add> for r in routines: <add> deps = r.dependencies() <add> fo.write('%s: %s\n' % (r.name, ' '.join(deps))) <ide> <ide> def concatenateRoutines(routines, output_file): <del> output_fo = open(output_file, 'w') <del> for r in routines: <del> fo = open(r.filename, 'r') <del> source = fo.read() <del> fo.close() <del> output_fo.write(source) <del> output_fo.close() <add> with open(output_file, 'w') as output_fo: <add> for r in routines: <add> with open(r.filename, 'r') as fo: <add> source = fo.read() <add> output_fo.write(source) <ide> <ide> class F2CError(Exception): <ide> pass <ide> <ide> def runF2C(fortran_filename, output_dir): <del> # we're assuming no funny business that needs to be quoted for the shell <del> cmd = "f2c %s -d %s %s" % (F2C_ARGS, output_dir, fortran_filename) <del> rc = os.system(cmd) <del> if rc != 0: <add> try: <add> subprocess.check_call( <add> ["f2c"] + F2C_ARGS + ['-d', output_dir, fortran_filename] <add> ) <add> except subprocess.CalledProcessError: <ide> raise F2CError <ide> <ide> def scrubF2CSource(c_file): <del> fo = open(c_file, 'r') <del> source = fo.read() <del> fo.close() <add> with open(c_file) as fo: <add> source = fo.read() <ide> source = clapack_scrub.scrubSource(source, verbose=True) <del> fo = open(c_file, 'w') <del> fo.write(HEADER) <del> fo.write(source) <del> fo.close() <add> with open(c_file, 'w') as fo: <add> fo.write(HEADER) <add> fo.write(source) <ide> <ide> def main(): <ide> if len(sys.argv) != 4: <del> print('Usage: %s wrapped_routines_file lapack_dir output_dir' % \ <del> (sys.argv[0],)) <add> print(__doc__) <ide> return <ide> wrapped_routines_file = sys.argv[1] <ide> lapack_src_dir = sys.argv[2] <ide> def main(): <ide> <ide> dumpRoutineNames(library, output_dir) <ide> <del> for typename in ['blas', 'dlapack', 'zlapack']: <del> print('creating %s_lite.c ...' % typename) <del> routines = library.allRoutinesByType(typename) <del> fortran_file = os.path.join(output_dir, typename+'_lite.f') <add> for typename in types: <add> fortran_file = os.path.join(output_dir, '%s_lite.f' % typename) <ide> c_file = fortran_file[:-2] + '.c' <add> print('creating %s ...' % c_file) <add> routines = library.allRoutinesByType(typename) <ide> concatenateRoutines(routines, fortran_file) <ide> try: <ide> runF2C(fortran_file, output_dir) <ide> def main(): <ide> break <ide> scrubF2CSource(c_file) <ide> <add> print() <add> <ide> if __name__ == '__main__': <ide> main()
1
Javascript
Javascript
fix csm helper
d6ff1df09f8c9c30f7812eda0bf6516832f6671b
<ide><path>examples/jsm/csm/CSM.js <ide> import Shader from './Shader.js'; <ide> <ide> const _cameraToLightMatrix = new Matrix4(); <ide> const _lightSpaceFrustum = new Frustum(); <add>const _frustum = new Frustum(); <ide> const _center = new Vector3(); <ide> const _bbox = new FrustumBoundingBox(); <ide> <ide> export default class CSM { <ide> <ide> helper( cameraMatrix ) { <ide> <del> let frustum; <ide> let geometry, vertices; <ide> const material = new LineBasicMaterial( { color: 0xffffff } ); <ide> const object = new Object3D(); <ide> <ide> for ( let i = 0; i < this.frustums.length; i ++ ) { <ide> <del> frustum = this.frustums[ i ].toSpace( cameraMatrix ); <add> this.frustums[ i ].toSpace( cameraMatrix, _frustum ); <ide> <ide> geometry = new BufferGeometry(); <ide> vertices = []; <ide> <ide> <ide> for ( let i = 0; i < 5; i ++ ) { <ide> <del> const point = frustum.vertices.near[ i === 4 ? 0 : i ]; <add> const point = _frustum.vertices.near[ i === 4 ? 0 : i ]; <ide> vertices.push( point.x, point.y, point.z ); <ide> <ide> } <ide> export default class CSM { <ide> <ide> for ( let i = 0; i < 5; i ++ ) { <ide> <del> const point = frustum.vertices.far[ i === 4 ? 0 : i ]; <add> const point = _frustum.vertices.far[ i === 4 ? 0 : i ]; <ide> vertices.push( point.x, point.y, point.z ); <ide> <ide> } <ide> export default class CSM { <ide> geometry = new BufferGeometry(); <ide> vertices = []; <ide> <del> const near = frustum.vertices.near[ i ]; <del> const far = frustum.vertices.far[ i ]; <add> const near = _frustum.vertices.near[ i ]; <add> const far = _frustum.vertices.far[ i ]; <ide> <ide> vertices.push( near.x, near.y, near.z ); <ide> vertices.push( far.x, far.y, far.z );
1
Ruby
Ruby
remove unused method
13cbe12aebc09053b06b93e6fe53062f424674a0
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def check_required_ivars <ide> end <ide> end <ide> end <del> <del> def html_format?(parameters) <del> return true unless parameters.key?(:format) <del> Mime.fetch(parameters[:format]) { Mime["html"] }.html? <del> end <ide> end <ide> <ide> include Behavior
1
Text
Text
remove set_primary_key, replace with primary_key=
df52eee15fc63b5224c0ff993c748ae9784b5b63
<ide><path>guides/source/active_record_basics.md <ide> end <ide> ``` <ide> <ide> It's also possible to override the column that should be used as the table's <del>primary key using the `ActiveRecord::Base.set_primary_key` method: <add>primary key using the `ActiveRecord::Base.primary_key=` method: <ide> <ide> ```ruby <ide> class Product < ActiveRecord::Base <del> set_primary_key "product_id" <add> self.primary_key = "product_id" <ide> end <ide> ``` <ide>
1
Python
Python
profile hostname for celery executor
decf7e83d86bfacf7b1a5aaea3ab523426420569
<ide><path>airflow/executors/base_executor.py <ide> # Tuple of: command, priority, queue name, SimpleTaskInstance <ide> QueuedTaskInstanceType = Tuple[CommandType, int, Optional[str], Union[SimpleTaskInstance, TaskInstance]] <ide> <add># Event_buffer dict value type <add># Tuple of: state, info <add>EventBufferValueType = Tuple[Optional[str], Any] <add> <ide> <ide> class BaseExecutor(LoggingMixin): <ide> """ <ide> def __init__(self, parallelism: int = PARALLELISM): <ide> self.queued_tasks: OrderedDict[TaskInstanceKeyType, QueuedTaskInstanceType] \ <ide> = OrderedDict() <ide> self.running: Set[TaskInstanceKeyType] = set() <del> self.event_buffer: Dict[TaskInstanceKeyType, Optional[str]] = {} <add> self.event_buffer: Dict[TaskInstanceKeyType, EventBufferValueType] = {} <ide> <ide> def start(self): # pragma: no cover <ide> """ <ide> def trigger_tasks(self, open_slots: int) -> None: <ide> queue=None, <ide> executor_config=simple_ti.executor_config) <ide> <del> def change_state(self, key: TaskInstanceKeyType, state: str) -> None: <add> def change_state(self, key: TaskInstanceKeyType, state: str, info=None) -> None: <ide> """ <ide> Changes state of the task. <ide> <add> :param info: Executor information for the task instance <ide> :param key: Unique key for the task instance <ide> :param state: State to set for the task. <ide> """ <ide> def change_state(self, key: TaskInstanceKeyType, state: str) -> None: <ide> self.running.remove(key) <ide> except KeyError: <ide> self.log.debug('Could not find key: %s', str(key)) <del> self.event_buffer[key] = state <add> self.event_buffer[key] = state, info <ide> <del> def fail(self, key: TaskInstanceKeyType) -> None: <add> def fail(self, key: TaskInstanceKeyType, info=None) -> None: <ide> """ <ide> Set fail state for the event. <ide> <add> :param info: Executor information for the task instance <ide> :param key: Unique key for the task instance <ide> """ <del> self.change_state(key, State.FAILED) <add> self.change_state(key, State.FAILED, info) <ide> <del> def success(self, key: TaskInstanceKeyType) -> None: <add> def success(self, key: TaskInstanceKeyType, info=None) -> None: <ide> """ <ide> Set success state for the event. <ide> <add> :param info: Executor information for the task instance <ide> :param key: Unique key for the task instance <ide> """ <del> self.change_state(key, State.SUCCESS) <add> self.change_state(key, State.SUCCESS, info) <ide> <del> def get_event_buffer(self, dag_ids=None) -> Dict[TaskInstanceKeyType, Optional[str]]: <add> def get_event_buffer(self, dag_ids=None) -> Dict[TaskInstanceKeyType, EventBufferValueType]: <ide> """ <ide> Returns and flush the event buffer. In case dag_ids is specified <ide> it will only return and flush events for the given dag_ids. Otherwise <ide> def get_event_buffer(self, dag_ids=None) -> Dict[TaskInstanceKeyType, Optional[s <ide> :param dag_ids: to dag_ids to return events for, if None returns all <ide> :return: a dict of events <ide> """ <del> cleared_events: Dict[TaskInstanceKeyType, Optional[str]] = dict() <add> cleared_events: Dict[TaskInstanceKeyType, EventBufferValueType] = dict() <ide> if dag_ids is None: <ide> cleared_events = self.event_buffer <ide> self.event_buffer = dict() <ide><path>airflow/executors/celery_executor.py <ide> from airflow.config_templates.default_celery import DEFAULT_CELERY_CONFIG <ide> from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException <del>from airflow.executors.base_executor import BaseExecutor, CommandType <add>from airflow.executors.base_executor import BaseExecutor, CommandType, EventBufferValueType <ide> from airflow.models.taskinstance import SimpleTaskInstance, TaskInstanceKeyType <ide> from airflow.utils.log.logging_mixin import LoggingMixin <add>from airflow.utils.net import get_hostname <ide> from airflow.utils.timeout import timeout <ide> <ide> log = logging.getLogger(__name__) <ide> def execute_command(command_to_exec: CommandType) -> None: <ide> except subprocess.CalledProcessError as e: <ide> log.exception('execute_command encountered a CalledProcessError') <ide> log.error(e.output) <del> raise AirflowException('Celery command failed') <add> msg = 'Celery command failed on host: ' + get_hostname() <add> raise AirflowException(msg) <ide> <ide> <ide> class ExceptionWithTraceback: <ide> def update_all_task_states(self) -> None: <ide> """Updates states of the tasks.""" <ide> <ide> self.log.debug("Inquiring about %s celery task(s)", len(self.tasks)) <del> states_by_celery_task_id = self.bulk_state_fetcher.get_many(self.tasks.values()) <add> state_and_info_by_celery_task_id = self.bulk_state_fetcher.get_many(self.tasks.values()) <ide> <ide> self.log.debug("Inquiries completed.") <ide> for key, async_result in list(self.tasks.items()): <del> state_by_task_id = states_by_celery_task_id.get(async_result.task_id) <del> if state_by_task_id: <del> self.update_task_state(key, state_by_task_id) <add> state, info = state_and_info_by_celery_task_id.get(async_result.task_id) <add> if state: <add> self.update_task_state(key, state, info) <ide> <del> def update_task_state(self, key: TaskInstanceKeyType, state: str) -> None: <add> def update_task_state(self, key: TaskInstanceKeyType, state: str, info: Any) -> None: <ide> """Updates state of a single task.""" <ide> # noinspection PyBroadException <ide> try: <ide> if self.last_state[key] != state: <ide> if state == celery_states.SUCCESS: <del> self.success(key) <add> self.success(key, info) <ide> del self.tasks[key] <ide> del self.last_state[key] <ide> elif state == celery_states.FAILURE: <del> self.fail(key) <add> self.fail(key, info) <ide> del self.tasks[key] <ide> del self.last_state[key] <ide> elif state == celery_states.REVOKED: <del> self.fail(key) <add> self.fail(key, info) <ide> del self.tasks[key] <ide> del self.last_state[key] <ide> else: <ide> def terminate(self): <ide> pass <ide> <ide> <del>def fetch_celery_task_state(async_result: AsyncResult) -> Tuple[str, Union[str, ExceptionWithTraceback]]: <add>def fetch_celery_task_state(async_result: AsyncResult) -> \ <add> Tuple[str, Union[str, ExceptionWithTraceback], Any]: <ide> """ <ide> Fetch and return the state of the given celery task. The scope of this function is <ide> global so that it can be called by subprocesses in the pool. <ide> <ide> :param async_result: a tuple of the Celery task key and the async Celery object used <ide> to fetch the task's state <ide> :type async_result: tuple(str, celery.result.AsyncResult) <del> :return: a tuple of the Celery task key and the Celery state of the task <del> :rtype: tuple[str, str] <add> :return: a tuple of the Celery task key and the Celery state and the celery info <add> of the task <add> :rtype: tuple[str, str, str] <ide> """ <ide> <ide> try: <ide> with timeout(seconds=OPERATION_TIMEOUT): <ide> # Accessing state property of celery task will make actual network request <ide> # to get the current state of the task <del> return async_result.task_id, async_result.state <add> info = async_result.info if hasattr(async_result, 'info') else None <add> return async_result.task_id, async_result.state, info <ide> except Exception as e: # pylint: disable=broad-except <ide> exception_traceback = f"Celery Task ID: {async_result}\n{traceback.format_exc()}" <del> return async_result.task_id, ExceptionWithTraceback(e, exception_traceback) <add> return async_result.task_id, ExceptionWithTraceback(e, exception_traceback), None <ide> <ide> <ide> def _tasks_list_to_task_ids(async_tasks) -> Set[str]: <ide> def __init__(self, sync_parralelism=None): <ide> super().__init__() <ide> self._sync_parallelism = sync_parralelism <ide> <del> def get_many(self, async_results) -> Mapping[str, str]: <add> def get_many(self, async_results) -> Mapping[str, EventBufferValueType]: <ide> """ <ide> Gets status for many Celery tasks using the best method available. <ide> """ <ide> def get_many(self, async_results) -> Mapping[str, str]: <ide> self.log.debug("Fetched %d states for %d task", len(result), len(async_results)) <ide> return result <ide> <del> def _get_many_from_kv_backend(self, async_tasks) -> Mapping[str, str]: <add> def _get_many_from_kv_backend(self, async_tasks) -> Mapping[str, EventBufferValueType]: <ide> task_ids = _tasks_list_to_task_ids(async_tasks) <ide> keys = [app.backend.get_key_for_task(k) for k in task_ids] <ide> values = app.backend.mget(keys) <ide> task_results = [app.backend.decode_result(v) for v in values if v] <ide> task_results_by_task_id = {task_result["task_id"]: task_result for task_result in task_results} <ide> <del> return self._preapre_state_by_task_dict(task_ids, task_results_by_task_id) <add> return self._prepare_state_and_info_by_task_dict(task_ids, task_results_by_task_id) <ide> <del> def _get_many_from_db_backend(self, async_tasks) -> Mapping[str, str]: <add> def _get_many_from_db_backend(self, async_tasks) -> Mapping[str, EventBufferValueType]: <ide> task_ids = _tasks_list_to_task_ids(async_tasks) <ide> session = app.backend.ResultSession() <ide> with session_cleanup(session): <ide> tasks = session.query(TaskDb).filter(TaskDb.task_id.in_(task_ids)).all() <ide> <ide> task_results = [app.backend.meta_from_decoded(task.to_dict()) for task in tasks] <ide> task_results_by_task_id = {task_result["task_id"]: task_result for task_result in task_results} <del> return self._preapre_state_by_task_dict(task_ids, task_results_by_task_id) <add> return self._prepare_state_and_info_by_task_dict(task_ids, task_results_by_task_id) <ide> <ide> @staticmethod <del> def _preapre_state_by_task_dict(task_ids, task_results_by_task_id) -> Mapping[str, str]: <del> states: MutableMapping[str, str] = {} <add> def _prepare_state_and_info_by_task_dict(task_ids, <add> task_results_by_task_id) -> Mapping[str, EventBufferValueType]: <add> state_info: MutableMapping[str, EventBufferValueType] = {} <ide> for task_id in task_ids: <ide> task_result = task_results_by_task_id.get(task_id) <ide> if task_result: <ide> state = task_result["status"] <add> info = None if not hasattr(task_result, "info") else task_result["info"] <ide> else: <ide> state = celery_states.PENDING <del> states[task_id] = state <del> return states <add> info = None <add> state_info[task_id] = state, info <add> return state_info <ide> <del> def _get_many_using_multiprocessing(self, async_results) -> Mapping[str, str]: <add> def _get_many_using_multiprocessing(self, async_results) -> Mapping[str, EventBufferValueType]: <ide> num_process = min(len(async_results), self._sync_parallelism) <ide> <ide> with Pool(processes=num_process) as sync_pool: <ide> chunksize = max(1, math.floor(math.ceil(1.0 * len(async_results) / self._sync_parallelism))) <ide> <del> task_id_to_states_or_exception = sync_pool.map( <add> task_id_to_states_and_info = sync_pool.map( <ide> fetch_celery_task_state, <ide> async_results, <ide> chunksize=chunksize) <ide> <del> states_by_task_id: MutableMapping[str, str] = {} <del> for task_id, state_or_exception in task_id_to_states_or_exception: <add> states_and_info_by_task_id: MutableMapping[str, EventBufferValueType] = {} <add> for task_id, state_or_exception, info in task_id_to_states_and_info: <ide> if isinstance(state_or_exception, ExceptionWithTraceback): <ide> self.log.error( # pylint: disable=logging-not-lazy <ide> CELERY_FETCH_ERR_MSG_HEADER + ":%s\n%s\n", <ide> state_or_exception.exception, state_or_exception.traceback <ide> ) <ide> else: <del> states_by_task_id[task_id] = state_or_exception <del> return states_by_task_id <add> states_and_info_by_task_id[task_id] = state_or_exception, info <add> return states_and_info_by_task_id <ide><path>airflow/executors/debug_executor.py <ide> def end(self) -> None: <ide> def terminate(self) -> None: <ide> self._terminated.set() <ide> <del> def change_state(self, key: TaskInstanceKeyType, state: str) -> None: <add> def change_state(self, key: TaskInstanceKeyType, state: str, info=None) -> None: <ide> self.log.debug("Popping %s from executor task queue.", key) <ide> self.running.remove(key) <del> self.event_buffer[key] = state <add> self.event_buffer[key] = state, info <ide><path>airflow/executors/kubernetes_executor.py <ide> def _change_state(self, <ide> self.running.remove(key) <ide> except KeyError: <ide> self.log.debug('Could not find key: %s', str(key)) <del> self.event_buffer[key] = state <add> self.event_buffer[key] = state, None <ide> <ide> def _flush_task_queue(self) -> None: <ide> if not self.task_queue: <ide><path>airflow/jobs/backfill_job.py <ide> def _manage_executor_state(self, running): <ide> executor = self.executor <ide> <ide> # TODO: query all instead of refresh from db <del> for key, state in list(executor.get_event_buffer().items()): <add> for key, value in list(executor.get_event_buffer().items()): <add> state, info = value <ide> if key not in running: <ide> self.log.warning( <ide> "%s state %s not in running=%s", <ide> def _manage_executor_state(self, running): <ide> if ti.state == State.RUNNING or ti.state == State.QUEUED: <ide> msg = ("Executor reports task instance {} finished ({}) " <ide> "although the task says its {}. Was the task " <del> "killed externally?".format(ti, state, ti.state)) <add> "killed externally? Info: {}".format(ti, state, ti.state, info)) <ide> self.log.error(msg) <ide> ti.handle_failure(msg) <ide> <ide><path>airflow/jobs/scheduler_job.py <ide> def _process_executor_events(self, simple_dag_bag, session=None): <ide> <ide> TI = models.TaskInstance <ide> # pylint: disable=too-many-nested-blocks <del> for key, state in list(self.executor.get_event_buffer(simple_dag_bag.dag_ids) <add> for key, value in list(self.executor.get_event_buffer(simple_dag_bag.dag_ids) <ide> .items()): <add> state, info = value <ide> dag_id, task_id, execution_date, try_number = key <ide> self.log.info( <ide> "Executor reports execution of %s.%s execution_date=%s " <ide> def _process_executor_events(self, simple_dag_bag, session=None): <ide> Stats.incr('scheduler.tasks.killed_externally') <ide> self.log.error( <ide> "Executor reports task instance %s finished (%s) although the task says its %s. " <del> "Was the task killed externally?", <del> ti, state, ti.state <add> "(Info: %s) Was the task killed externally?", <add> ti, state, ti.state, info <ide> ) <ide> simple_dag = simple_dag_bag.get_dag(dag_id) <ide> self.processor_agent.send_callback_to_execute( <ide> full_filepath=simple_dag.full_filepath, <ide> task_instance=ti, <ide> msg="Executor reports task instance finished ({}) although the task says its {}. " <del> "Was the task killed externally?".format(state, ti.state) <add> "(Info: {}) Was the task killed externally?".format(state, ti.state, info) <ide> ) <ide> <ide> def _execute(self): <ide><path>scripts/perf/scheduler_dag_execution_timing.py <ide> def reset(self, dag_ids_to_watch): <ide> ) for dag_id in dag_ids_to_watch <ide> } <ide> <del> def change_state(self, key, state): <add> def change_state(self, key, state, info=None): <ide> ''' <ide> Change the state of scheduler by waiting till the tasks is complete <ide> and then shut down the scheduler after the task is complete <ide> ''' <ide> from airflow.utils.state import State <del> super().change_state(key, state) <add> super().change_state(key, state, info=info) <ide> <ide> dag_id, _, execution_date, __ = key <ide> if dag_id not in self.dags_to_watch: <ide><path>tests/executors/test_base_executor.py <ide> def test_get_event_buffer(self): <ide> key2 = ("my_dag2", "my_task1", date, try_number) <ide> key3 = ("my_dag2", "my_task2", date, try_number) <ide> state = State.SUCCESS <del> executor.event_buffer[key1] = state <del> executor.event_buffer[key2] = state <del> executor.event_buffer[key3] = state <add> executor.event_buffer[key1] = state, None <add> executor.event_buffer[key2] = state, None <add> executor.event_buffer[key3] = state, None <ide> <ide> self.assertEqual(len(executor.get_event_buffer(("my_dag1",))), 1) <ide> self.assertEqual(len(executor.get_event_buffer()), 2) <ide><path>tests/executors/test_celery_executor.py <ide> def test_celery_integration(self, broker_url): <ide> <ide> executor.end(synchronous=True) <ide> <del> self.assertEqual(executor.event_buffer[('success', 'fake_simple_ti', execute_date, 0)], State.SUCCESS) <del> self.assertEqual(executor.event_buffer[('fail', 'fake_simple_ti', execute_date, 0)], State.FAILED) <add> self.assertEqual(executor.event_buffer[('success', 'fake_simple_ti', execute_date, 0)][0], <add> State.SUCCESS) <add> self.assertEqual(executor.event_buffer[('fail', 'fake_simple_ti', execute_date, 0)][0], <add> State.FAILED) <ide> <ide> self.assertNotIn('success', executor.tasks) <ide> self.assertNotIn('fail', executor.tasks) <ide> def test_should_support_kv_backend(self, mock_mget): <ide> self.assertEqual(set(mget_args[0]), {b'celery-task-meta-456', b'celery-task-meta-123'}) <ide> mock_mget.assert_called_once_with(mock.ANY) <ide> <del> self.assertEqual(result, {'123': 'SUCCESS', '456': "PENDING"}) <add> self.assertEqual(result, {'123': ('SUCCESS', None), '456': ("PENDING", None)}) <ide> <ide> @mock.patch("celery.backends.database.DatabaseBackend.ResultSession") <ide> @pytest.mark.integration("redis") <ide> def test_should_support_db_backend(self, mock_session): <ide> mock.MagicMock(task_id="456"), <ide> ]) <ide> <del> self.assertEqual(result, {'123': 'SUCCESS', '456': "PENDING"}) <add> self.assertEqual(result, {'123': ('SUCCESS', None), '456': ("PENDING", None)}) <ide> <ide> @pytest.mark.integration("redis") <ide> @pytest.mark.integration("rabbitmq") <ide> def test_should_support_base_backend(self): <ide> ClassWithCustomAttributes(task_id="456", state="PENDING"), <ide> ]) <ide> <del> self.assertEqual(result, {'123': 'SUCCESS', '456': "PENDING"}) <add> self.assertEqual(result, {'123': ('SUCCESS', None), '456': ("PENDING", None)}) <ide><path>tests/executors/test_kubernetes_executor.py <ide> def test_change_state_running(self, mock_get_kube_client, mock_kubernetes_job_wa <ide> executor.start() <ide> key = ('dag_id', 'task_id', 'ex_time', 'try_number1') <ide> executor._change_state(key, State.RUNNING, 'pod_id', 'default') <del> self.assertTrue(executor.event_buffer[key] == State.RUNNING) <add> self.assertTrue(executor.event_buffer[key][0] == State.RUNNING) <ide> <ide> @mock.patch('airflow.executors.kubernetes_executor.KubernetesJobWatcher') <ide> @mock.patch('airflow.executors.kubernetes_executor.get_kube_client') <ide> def test_change_state_success(self, mock_delete_pod, mock_get_kube_client, mock_ <ide> test_time = timezone.utcnow() <ide> key = ('dag_id', 'task_id', test_time, 'try_number2') <ide> executor._change_state(key, State.SUCCESS, 'pod_id', 'default') <del> self.assertTrue(executor.event_buffer[key] == State.SUCCESS) <add> self.assertTrue(executor.event_buffer[key][0] == State.SUCCESS) <ide> mock_delete_pod.assert_called_once_with('pod_id', 'default') <ide> <ide> @mock.patch('airflow.executors.kubernetes_executor.KubernetesJobWatcher') <ide> def test_change_state_failed_no_deletion( <ide> test_time = timezone.utcnow() <ide> key = ('dag_id', 'task_id', test_time, 'try_number3') <ide> executor._change_state(key, State.FAILED, 'pod_id', 'default') <del> self.assertTrue(executor.event_buffer[key] == State.FAILED) <add> self.assertTrue(executor.event_buffer[key][0] == State.FAILED) <ide> mock_delete_pod.assert_not_called() <ide> # pylint: enable=unused-argument <ide> <ide> def test_change_state_skip_pod_deletion(self, mock_delete_pod, mock_get_kube_cli <ide> executor.start() <ide> key = ('dag_id', 'task_id', test_time, 'try_number2') <ide> executor._change_state(key, State.SUCCESS, 'pod_id', 'default') <del> self.assertTrue(executor.event_buffer[key] == State.SUCCESS) <add> self.assertTrue(executor.event_buffer[key][0] == State.SUCCESS) <ide> mock_delete_pod.assert_not_called() <ide> <ide> @mock.patch('airflow.executors.kubernetes_executor.KubernetesJobWatcher') <ide> def test_change_state_failed_pod_deletion(self, mock_delete_pod, mock_get_kube_c <ide> executor.start() <ide> key = ('dag_id', 'task_id', 'ex_time', 'try_number2') <ide> executor._change_state(key, State.FAILED, 'pod_id', 'test-namespace') <del> self.assertTrue(executor.event_buffer[key] == State.FAILED) <add> self.assertTrue(executor.event_buffer[key][0] == State.FAILED) <ide> mock_delete_pod.assert_called_once_with('pod_id', 'test-namespace') <ide><path>tests/executors/test_local_executor.py <ide> def execution_parallelism(self, parallelism=0): <ide> for i in range(self.TEST_SUCCESS_COMMANDS): <ide> key_id = success_key.format(i) <ide> key = key_id, 'fake_ti', execution_date, 0 <del> self.assertEqual(executor.event_buffer[key], State.SUCCESS) <del> self.assertEqual(executor.event_buffer[fail_key], State.FAILED) <add> self.assertEqual(executor.event_buffer[key][0], State.SUCCESS) <add> self.assertEqual(executor.event_buffer[fail_key][0], State.FAILED) <ide> <ide> expected = self.TEST_SUCCESS_COMMANDS + 1 if parallelism == 0 else parallelism <ide> self.assertEqual(executor.workers_used, expected) <ide><path>tests/jobs/test_backfill_job.py <ide> def test_backfill_multi_dates(self): <ide> ("run_this_last", end_date), <ide> ] <ide> self.assertListEqual( <del> [((dag.dag_id, task_id, when, 1), State.SUCCESS) <add> [((dag.dag_id, task_id, when, 1), (State.SUCCESS, None)) <ide> for (task_id, when) in expected_execution_order], <ide> executor.sorted_tasks <ide> ) <ide> def test_backfill_examples(self, dag_id, expected_execution_order): <ide> <ide> job.run() <ide> self.assertListEqual( <del> [((dag_id, task_id, DEFAULT_DATE, 1), State.SUCCESS) <add> [((dag_id, task_id, DEFAULT_DATE, 1), (State.SUCCESS, None)) <ide> for task_id in expected_execution_order], <ide> executor.sorted_tasks <ide> ) <ide><path>tests/jobs/test_scheduler_job.py <ide> def test_process_executor_events(self, mock_stats_incr): <ide> session.commit() <ide> <ide> executor = MockExecutor(do_update=False) <del> executor.event_buffer[ti1.key] = State.FAILED <add> executor.event_buffer[ti1.key] = State.FAILED, None <ide> <ide> scheduler.executor = executor <ide> <ide> def test_process_executor_events(self, mock_stats_incr): <ide> full_filepath='/test_path1/', <ide> task_instance=mock.ANY, <ide> msg='Executor reports task instance finished (failed) ' <del> 'although the task says its queued. Was the task killed externally?' <add> 'although the task says its queued. (Info: None) Was the task killed externally?' <ide> ) <ide> scheduler.processor_agent.reset_mock() <ide> <ide> # ti in success state <ide> ti1.state = State.SUCCESS <ide> session.merge(ti1) <ide> session.commit() <del> executor.event_buffer[ti1.key] = State.SUCCESS <add> executor.event_buffer[ti1.key] = State.SUCCESS, None <ide> <ide> scheduler._process_executor_events(simple_dag_bag=dagbag1) <ide> ti1.refresh_from_db() <ide> def test_scheduler_start_date(self): <ide> len(session.query(TaskInstance).filter(TaskInstance.dag_id == dag_id).all()), 1) <ide> self.assertListEqual( <ide> [ <del> ((dag.dag_id, 'dummy', DEFAULT_DATE, 1), State.SUCCESS), <add> ((dag.dag_id, 'dummy', DEFAULT_DATE, 1), (State.SUCCESS, None)), <ide> ], <ide> bf_exec.sorted_tasks <ide> ) <ide><path>tests/test_utils/mock_executor.py <ide> def terminate(self): <ide> def end(self): <ide> self.sync() <ide> <del> def change_state(self, key, state): <del> super().change_state(key, state) <add> def change_state(self, key, state, info=None): <add> super().change_state(key, state, info=info) <ide> # The normal event buffer is cleared after reading, we want to keep <ide> # a list of all events for testing <del> self.sorted_tasks.append((key, state)) <add> self.sorted_tasks.append((key, (state, info))) <ide> <ide> def mock_task_fail(self, dag_id, task_id, date, try_number=1): <ide> """
14
Text
Text
add 2.9.0-beta.3 to changelog.md
620092fb2a5ee86967f1516ca4c49c2ea0443860
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### 2.9.0-beta.3 (September 20, 2016) <add> <add>- [#14313](https://github.com/emberjs/ember.js/pull/14313) [BUGFIX] Ensure `id` attribute bindings of `undefined` are handled properly. <add>- [#14291](https://github.com/emberjs/ember.js/pull/14291) [BUGFIX] Fix component action bubbling semantics. <add>- [#14296](https://github.com/emberjs/ember.js/pull/14296) [BUGFIX] Prevent invalid markup when used with XHTML `doctype`. <add>- [#14300](https://github.com/emberjs/ember.js/pull/14300) [BUGFIX] Ensure component is `inDOM` during `didInsertElement`. <add>- [#14312](https://github.com/emberjs/ember.js/pull/14312) [BUGFIX] Allow a components `layout` to be injected. <add>- [#14315](https://github.com/emberjs/ember.js/pull/14315) [BUGFIX] Fix DOM output for properties and attributes. <add>- [#14319](https://github.com/emberjs/ember.js/pull/14319) [BUGFIX] Fixes rerendering issues when rendering aliased paths. <add> <add> <ide> ### 2.9.0-beta.2 (September 12, 2016) <ide> <ide> - [#14237](https://github.com/emberjs/ember.js/pull/14237) [BUGFIX] Ensure Engine Routes are deactivated before destruction
1
Python
Python
fix error in test case parameterization
123d3f2d38f86779cdbc03abd512a59fea169856
<ide><path>spacy/tests/tokenizer/test_tokenizer.py <ide> def test_tokenizer_handles_digits(tokenizer): <ide> assert tokens[3].text == "1984" <ide> <ide> <del>@pytest.mark.parametrize('text', ["google.com", "python.org", "spacy.io", "explosion.ai, http://www.google.com"]) <add>@pytest.mark.parametrize('text', ["google.com", "python.org", "spacy.io", "explosion.ai", "http://www.google.com"]) <ide> def test_tokenizer_keep_urls(tokenizer, text): <ide> tokens = tokenizer(text) <ide> assert len(tokens) == 1
1
Ruby
Ruby
add `sparkle` livecheck strategy
c24af82a25f9ce625a81dbe19a93b0242989ae11
<ide><path>Library/Homebrew/livecheck/strategy.rb <ide> def self.page_contents(url) <ide> require_relative "strategy/pypi" <ide> require_relative "strategy/follow_redirection" <ide> require_relative "strategy/sourceforge" <add>require_relative "strategy/sparkle" <ide> require_relative "strategy/xorg" <ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb <add># typed: false <add># frozen_string_literal: true <add> <add>require_relative "page_match" <add> <add>module Homebrew <add> module Livecheck <add> module Strategy <add> # The {Sparkle} strategy fetches content at a URL and parses <add> # its contents as a Sparkle appcast in XML format. <add> # <add> # @api private <add> class Sparkle <add> extend T::Sig <add> <add> NICE_NAME = "Sparkle" <add> <add> PRIORITY = 1 <add> <add> # Whether the strategy can be applied to the provided URL. <add> sig { params(url: String).returns(T::Boolean) } <add> def self.match?(url) <add> url.match?(%r{^https?://}) && <add> ["application/xml", "text/xml"].include?(Strategy.page_headers(url)["content-type"]) && <add> Strategy.page_contents(url).include?("http://www.andymatuschak.org/xml-namespaces/sparkle") <add> end <add> <add> # Checks the content at the URL for new versions. <add> sig { params(url: String, regex: T.nilable(Regexp)).returns(T::Hash[Symbol, T.untyped]) } <add> def self.find_versions(url, regex) <add> raise ArgumentError, "The #{NICE_NAME} strategy does not support regular expressions." if regex <add> <add> require "nokogiri" <add> <add> match_data = { matches: {}, regex: regex, url: url } <add> <add> contents = Strategy.page_contents(url) <add> <add> xml = Nokogiri.parse(contents) <add> xml.remove_namespaces! <add> <add> match = xml.xpath("//rss//channel//item//enclosure") <add> .map { |enclosure| [*enclosure["shortVersionString"], *enclosure["version"]].uniq } <add> .reject(&:empty?) <add> .uniq <add> .max_by { |versions| versions.map { |v| Version.new(v) } } <add> &.join(",") <add> <add> match_data[:matches][match] = Version.new(match) if match <add> <add> match_data <add> end <add> end <add> end <add> end <add>end
2
Python
Python
add dispatch to generate_umath
9bb27e8559877eca5159b43b92b7436ffcb621d7
<ide><path>numpy/core/code_generators/generate_umath.py <ide> def english_upper(s): <ide> docstrings.get('numpy.core.umath.floor_divide'), <ide> 'PyUFunc_DivisionTypeResolver', <ide> TD(ints, cfunc_alias='divide', <del> dispatch=[('loops_arithmetic', 'BHILQ')]), <add> dispatch=[('loops_arithmetic', 'bBhHiIlLqQ')]), <ide> TD(flts + cmplx), <ide> [TypeDescription('m', FullTypeDescr, 'mq', 'm'), <ide> TypeDescription('m', FullTypeDescr, 'md', 'm'),
1
Ruby
Ruby
fix disable_joins when foreign key is not id
566c4033f70e82910ffa347d025380215e5c86a8
<ide><path>activerecord/lib/active_record/associations/disable_joins_association_scope.rb <ide> def scope(association) <ide> <ide> private <ide> def last_scope_chain(reverse_chain, owner) <del> first_scope = [reverse_chain.shift, false, [owner.id]] <add> first_item = reverse_chain.shift <add> first_scope = [first_item, false, [owner._read_attribute(first_item.join_foreign_key)]] <ide> <ide> reverse_chain.inject(first_scope) do |(reflection, ordered, join_ids), next_reflection| <ide> key = reflection.join_primary_key <ide><path>activerecord/test/cases/associations/has_one_through_disable_joins_associations_test.rb <ide> require "models/member" <ide> require "models/member_detail" <ide> require "models/organization" <add>require "models/project" <add>require "models/developer" <add>require "models/company" <add>require "models/computer" <ide> <ide> class HasOneThroughDisableJoinsAssociationsTest < ActiveRecord::TestCase <del> fixtures :members, :organizations <add> fixtures :members, :organizations, :projects, :developers, :companies <ide> <ide> def setup <ide> @member = members(:groucho) <ide> def test_preload_on_disable_joins_through <ide> assert_no_queries { members[0].organization } <ide> assert_no_queries { members[0].organization_without_joins } <ide> end <add> <add> def test_has_one_through_with_belongs_to_on_disable_joins <add> firm = Firm.create!(name: "Adequate Holdings") <add> project = Project.create!(name: "Project 1", firm: firm) <add> Developer.create!(name: "Gorbypuff", firm: firm) <add> <add> joins = capture_sql { project.lead_developer } <add> no_joins = capture_sql { project.lead_developer_disable_joins } <add> <add> assert_equal project.lead_developer, project.lead_developer_disable_joins <add> assert_equal 2, no_joins.count <add> assert_equal 1, joins.count <add> assert_match(/INNER JOIN/, joins.first) <add> no_joins.each do |nj| <add> assert_no_match(/INNER JOIN/, nj) <add> end <add> end <ide> end <ide><path>activerecord/test/models/project.rb <ide> class Project < ActiveRecord::Base <ide> has_and_belongs_to_many :well_paid_salary_groups, -> { group("developers.salary").having("SUM(salary) > 10000").select("SUM(salary) as salary") }, class_name: "Developer" <ide> belongs_to :firm <ide> has_one :lead_developer, through: :firm, inverse_of: :contracted_projects <add> has_one :lead_developer_disable_joins, through: :firm, inverse_of: :contracted_projects, source: :lead_developer, disable_joins: true <ide> <ide> begin <ide> previous_value, ActiveRecord::Base.belongs_to_required_by_default =
3
Ruby
Ruby
flatten array before matching
27466b01da0aabb3681956c50141ddbfc4e45c6b
<ide><path>Library/Homebrew/searchable.rb <ide> def simplify_string(string) <ide> def search_regex(regex) <ide> select do |*args| <ide> args = yield(*args) if block_given? <del> args = Array(args).compact <add> args = Array(args).flatten.compact <ide> args.any? { |arg| arg.match?(regex) } <ide> end <ide> end
1
Python
Python
fix broken tag parsing
cf7653e7727f81b81a1daeab01f80206ff206326
<ide><path>glances/exports/glances_export.py <ide> def get_item_key(self, item): <ide> else: <ide> return ret <ide> <del> def parse_tags(self): <del> """ Parses some tags into a dict""" <del> if self.tags: <add> def parse_tags(self, tags): <add> """Parse tags into a dict. <add> <add> tags: a comma separated list of 'key:value' pairs. <add> Example: foo:bar,spam:eggs <add> dtags: a dict of tags. <add> Example: {'foo': 'bar', 'spam': 'eggs'} <add> """ <add> dtags = {} <add> if tags: <ide> try: <del> self.tags = dict([x.split(':') for x in self.tags.split(',')]) <add> dtags = dict([x.split(':') for x in tags.split(',')]) <ide> except ValueError: <del> # one of the keyvalue pairs was missing <del> logger.info('invalid tags passed: %s', self.tags) <del> self.tags = {} <del> else: <del> self.tags = {} <add> # one of the 'key:value' pairs was missing <add> logger.info('Invalid tags passed: %s', tags) <add> dtags = {} <add> <add> return dtags <ide> <ide> def update(self, stats): <ide> """Update stats to a server. <ide><path>glances/exports/glances_influxdb.py <ide> def __init__(self, config=None, args=None): <ide> self.password = None <ide> self.db = None <ide> self.prefix = None <add> self.tags = None <ide> self.export_enable = self.load_conf() <ide> if not self.export_enable: <ide> sys.exit(2) <ide> def load_conf(self, section="influxdb"): <ide> try: <ide> self.tags = self.config.get_value(section, 'tags') <ide> except NoOptionError: <del> self.tags = '' <add> pass <ide> <ide> return True <ide> <ide> def init(self): <ide> logger.critical("InfluxDB database '%s' did not exist. Please create it" % self.db) <ide> sys.exit(2) <ide> <del> # Read tags <del> self.parse_tags() <del> <ide> return db <ide> <ide> def export(self, name, columns, points): <ide> def export(self, name, columns, points): <ide> # Create DB input <ide> if self.version == INFLUXDB_09: <ide> data = [{'measurement': name, <del> 'tags': self.tags, <add> 'tags': self.parse_tags(self.tags), <ide> 'fields': dict(zip(columns, points))}] <ide> else: <ide> data = [{'name': name, 'columns': columns, 'points': [points]}] <ide><path>glances/exports/glances_opentsdb.py <ide> def __init__(self, config=None, args=None): <ide> self.host = None <ide> self.port = None <ide> self.prefix = None <add> self.tags = None <ide> self.export_enable = self.load_conf() <ide> if not self.export_enable: <ide> sys.exit(2) <ide> def load_conf(self, section="opentsdb"): <ide> try: <ide> self.tags = self.config.get_value(section, 'tags') <ide> except NoOptionError: <del> self.tags = '' <add> pass <ide> <ide> return True <ide> <ide> def init(self): <ide> logger.critical("Cannot connect to OpenTSDB server %s:%s (%s)" % (self.host, self.port, e)) <ide> sys.exit(2) <ide> <del> # Read tags <del> self.parse_tags() <del> <ide> return db <ide> <ide> def export(self, name, columns, points): <ide> def export(self, name, columns, points): <ide> continue <ide> stat_name = '{0}.{1}.{2}'.format(self.prefix, name, columns[i]) <ide> stat_value = points[i] <add> tags = self.parse_tags(self.tags) <ide> try: <del> self.client.send(stat_name, stat_value, **self.tags) <add> self.client.send(stat_name, stat_value, **tags) <ide> except Exception as e: <ide> logger.error("Can not export stats %s to OpenTSDB (%s)" % (name, e)) <ide> logger.debug("Export {0} stats to OpenTSDB".format(name))
3
Text
Text
add method reference
f0ca685a1612e97da0e5401b6f8ec7643f5b3044
<ide><path>CONTRIBUTING.md <ide> in the proper package's repository. <ide> * Use [TomDoc](http://tomdoc.org/). <ide> * Use [Markdown](https://daringfireball.net/projects/markdown/). <ide> * Reference classes with `{ClassName}` style notation. <add>* Reference methods with `{ClassName.methodName}` style notation. <ide> * Delegate to comments elsewhere with `{Delegates to: ClassName.methodName}` <ide> style notation. <ide>
1
Javascript
Javascript
handle position between rows correctly
1e07b8df0553572369c4f8c2ea8249e646573be9
<ide><path>spec/line-top-index-spec.js <ide> describe("LineTopIndex", function () { <ide> expect(lineTopIndex.rowForTopPixelPosition(70)).toBe(4) <ide> expect(lineTopIndex.rowForTopPixelPosition(80)).toBe(5) <ide> expect(lineTopIndex.rowForTopPixelPosition(90)).toBe(5) <del> expect(lineTopIndex.rowForTopPixelPosition(100)).toBe(6) <add> expect(lineTopIndex.rowForTopPixelPosition(95)).toBe(5) <add> expect(lineTopIndex.rowForTopPixelPosition(105)).toBe(6) <ide> expect(lineTopIndex.rowForTopPixelPosition(110)).toBe(6) <add> expect(lineTopIndex.rowForTopPixelPosition(160)).toBe(11) <add> expect(lineTopIndex.rowForTopPixelPosition(166)).toBe(12) <add> expect(lineTopIndex.rowForTopPixelPosition(170)).toBe(12) <add> expect(lineTopIndex.rowForTopPixelPosition(240)).toBe(12) <ide> <ide> lineTopIndex.removeBlock(block1) <ide> lineTopIndex.removeBlock(block3) <ide><path>src/linear-line-top-index.js <ide> class LineTopIndex { <ide> let lastRow = 0 <ide> let lastTop = 0 <ide> for (let block of this.blocks) { <del> blocksHeight += block.height <add> let nextBlocksHeight = blocksHeight + block.height <ide> let linesHeight = block.row * this.defaultLineHeight <del> if (blocksHeight + linesHeight > top) { <del> break <add> if (nextBlocksHeight + linesHeight > top) { <add> while (lastRow < block.row && lastTop + this.defaultLineHeight / 2 < top) { <add> lastTop += this.defaultLineHeight <add> lastRow++ <add> } <add> return lastRow <ide> } else { <add> blocksHeight = nextBlocksHeight <ide> lastRow = block.row <ide> lastTop = blocksHeight + linesHeight <ide> }
2
PHP
PHP
fix assertcookie
09ffc3a2eeddd31d43e1121ae865dd37e16f0cef
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php <ide> use Illuminate\Http\Response; <ide> use Illuminate\Contracts\View\View; <ide> use PHPUnit_Framework_Assert as PHPUnit; <add>use Symfony\Component\HttpFoundation\Cookie; <ide> <ide> class TestResponse extends Response <ide> { <ide> public function assertPlainCookie($cookieName, $value = null) <ide> * @param string $cookieName <ide> * @param mixed $value <ide> * @param bool $encrypted <del> * @return void <add> * @return $this <ide> */ <ide> public function assertCookie($cookieName, $value = null, $encrypted = true) <ide> { <del> PHPUnit::assertTrue( <del> $exists = $this->hasCookie($cookieName), <add> PHPUnit::assertNotNull( <add> $cookie = $this->getCookie($cookieName), <ide> "Cookie [{$cookieName}] not present on response." <ide> ); <ide> <del> if (! $exists || is_null($value)) { <add> if (! $cookie || is_null($value)) { <ide> return $this; <ide> } <ide> <ide> public function assertCookie($cookieName, $value = null, $encrypted = true) <ide> $actual, $value, <ide> "Cookie [{$cookieName}] was found, but value [{$actual}] does not match [{$value}]." <ide> ); <add> <add> return $this; <ide> } <ide> <ide> /** <del> * Determine if the response has a given cookie. <add> * Get the given cookie from the response. <ide> * <ide> * @param string $cookieName <del> * @return bool <add> * @return Cookie|null <ide> */ <del> protected function hasCookie($cookieName) <add> protected function getCookie($cookieName) <ide> { <ide> foreach ($this->headers->getCookies() as $cookie) { <ide> if ($cookie->getName() === $cookieName) { <del> return true; <add> return $cookie; <ide> } <ide> } <del> <del> return false; <ide> } <ide> <ide> /**
1
Text
Text
add link to react-redux docs
841b4037b93fe900a143adc50e1a9c7998963aa7
<ide><path>docs/basics/UsageWithReact.md <ide> From the very beginning, we need to stress that Redux has no relation to React. <ide> <ide> That said, Redux works especially well with libraries like [React](http://facebook.github.io/react/) and [Deku](https://github.com/dekujs/deku) because they let you describe UI as a function of state, and Redux emits state updates in response to actions. <ide> <del>We will use React to build our simple todo app. <add>We will use React to build our simple todo app, and cover the basics of how to use React with Redux. <add> <add>> **Note**: see **the official React-Redux docs at https://react-redux.js.org** for a complete guide on how to use Redux and React together. <ide> <ide> ## Installing React Redux <ide>
1
Ruby
Ruby
check version mismatch
b1fff3205584e1e42ae750b2af7ca17963929aa9
<ide><path>Library/Homebrew/exceptions.rb <ide> def initialize(resource) <ide> super "Resource #{resource.inspect} is defined more than once" <ide> end <ide> end <add> <add>class BottleVersionMismatchError < RuntimeError <add> def initialize bottle_file, bottle_version, formula, formula_version <add> super <<-EOS.undent <add> Bottle version mismatch <add> Bottle: #{bottle_file} (#{bottle_version}) <add> Formula: #{formula.full_name} (#{formula_version}) <add> EOS <add> end <add>end <ide><path>Library/Homebrew/formulary.rb <ide> def initialize bottle_name <ide> def get_formula(spec) <ide> formula = super <ide> formula.local_bottle_path = @bottle_filename <add> formula_version = formula.pkg_version <add> bottle_version = bottle_resolve_version(@bottle_filename) <add> unless formula_version == bottle_version <add> raise BottleVersionMismatchError.new(@bottle_filename, bottle_version, formula, formula_version) <add> end <ide> formula <ide> end <ide> end
2
Python
Python
add missing module __spec__
35236b870ee4102fb82f7a1d4713dc83af78a00a
<ide><path>src/transformers/__init__.py <ide> import sys <ide> <ide> sys.modules[__name__] = _LazyModule( <del> __name__, globals()["__file__"], _import_structure, extra_objects={"__version__": __version__} <add> __name__, <add> globals()["__file__"], <add> _import_structure, <add> module_spec=__spec__, <add> extra_objects={"__version__": __version__}, <ide> ) <ide> <ide> <ide><path>src/transformers/file_utils.py <ide> class _LazyModule(ModuleType): <ide> <ide> # Very heavily inspired by optuna.integration._IntegrationModule <ide> # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py <del> def __init__(self, name, module_file, import_structure, extra_objects=None): <add> def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None): <ide> super().__init__(name) <ide> self._modules = set(import_structure.keys()) <ide> self._class_to_module = {} <ide> def __init__(self, name, module_file, import_structure, extra_objects=None): <ide> # Needed for autocompletion in an IDE <ide> self.__all__ = list(import_structure.keys()) + sum(import_structure.values(), []) <ide> self.__file__ = module_file <add> self.__spec__ = module_spec <ide> self.__path__ = [os.path.dirname(module_file)] <ide> self._objects = {} if extra_objects is None else extra_objects <ide> self._name = name <ide><path>tests/test_file_utils.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <add>import importlib <ide> import unittest <ide> <ide> import requests <add>import transformers <ide> <ide> # Try to import everything from transformers to ensure every object can be loaded. <ide> from transformers import * # noqa F406 <ide> # Sha-256 of pytorch_model.bin on the top of `main`, for checking purposes <ide> <ide> <add>def test_module_spec(): <add> assert transformers.__spec__ is not None <add> assert importlib.util.find_spec("transformers") is not None <add> <add> <ide> class GetFromCacheTests(unittest.TestCase): <ide> def test_bogus_url(self): <ide> # This lets us simulate no connection
3
PHP
PHP
apply fixes from styleci
469b7719a8dca40841a74f59f2e9f30f01d3a106
<ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php <ide> <ide> use Illuminate\Database\Eloquent\Builder; <ide> use Illuminate\Database\Eloquent\Model; <del>use Illuminate\Database\Eloquent\Relations\MorphPivot; <ide> use Illuminate\Support\Arr; <ide> <ide> class MorphToMany extends BelongsToMany
1
Python
Python
support truncation off beginning of sequence
7e069956787750724d30b59bd5c0db50c9eed43e
<ide><path>keras/preprocessing/sequence.py <ide> import random <ide> from six.moves import range <ide> <del>def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', value=0.): <add>def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.): <ide> """ <ide> Pad each sequence to the same length: <ide> the length of the longuest sequence. <ide> <ide> If maxlen is provided, any sequence longer <del> than maxlen is truncated to maxlen. <add> than maxlen is truncated to maxlen. Truncation happens off either the beginning (default) or <add> the end of the sequence. <add> <add> Supports post-padding and pre-padding (default). <ide> <del> Support post-padding and pre-padding (default). <ide> """ <ide> lengths = [len(s) for s in sequences] <ide> <ide> def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', value=0. <ide> <ide> x = (np.ones((nb_samples, maxlen)) * value).astype(dtype) <ide> for idx, s in enumerate(sequences): <add> if truncating == 'pre': <add> trunc = s[-maxlen:] <add> elif truncating == 'post': <add> trunc = s[:maxlen] <add> else: <add> raise ValueError("Truncating type '%s' not understood" % padding) <add> <ide> if padding == 'post': <del> x[idx, :lengths[idx]] = s[:maxlen] <add> x[idx, :len(trunc)] = trunc <add> elif padding == 'pre': <add> x[idx, -len(trunc):] = trunc <ide> else: <del> x[idx, -min(maxlen, lengths[idx]):] = s[:maxlen] <add> raise ValueError("Padding type '%s' not understood" % padding) <ide> return x <ide> <ide>
1
PHP
PHP
move common code into translatestrategytrait
5dd316999218f7fb6fd5d9e28f3bc6d142d133aa
<ide><path>src/ORM/Behavior/Translate/EavStrategy.php <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\QueryInterface; <ide> use Cake\Event\Event; <del>use Cake\I18n\I18n; <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <ide> use Cake\ORM\PropertyMarshalInterface; <ide> class EavStrategy implements PropertyMarshalInterface <ide> <ide> use InstanceConfigTrait; <ide> use LocatorAwareTrait; <del> <del> /** <del> * Table instance <del> * <del> * @var \Cake\ORM\Table <del> */ <del> protected $table; <del> <del> /** <del> * The locale name that will be used to override fields in the bound table <del> * from the translations table <del> * <del> * @var string <del> */ <del> protected $locale; <del> <del> /** <del> * Instance of Table responsible for translating <del> * <del> * @var \Cake\ORM\Table <del> */ <del> protected $translationTable; <add> use TranslateStrategyTrait; <ide> <ide> /** <ide> * Default config <ide> public function __construct(Table $table, array $config = []) <ide> ); <ide> } <ide> <del> /** <del> * Return translation table instance. <del> * <del> * @return \Cake\ORM\Table <del> */ <del> public function getTranslationTable(): Table <del> { <del> return $this->translationTable; <del> } <del> <ide> /** <ide> * Creates the associations between the bound table and every field passed to <ide> * this method. <ide> public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $o <ide> } <ide> } <ide> <del> /** <del> * Unsets the temporary `_i18n` property after the entity has been saved <del> * <del> * @param \Cake\Event\Event $event The beforeSave event that was fired <del> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved <del> * @return void <del> */ <del> public function afterSave(Event $event, EntityInterface $entity): void <del> { <del> $entity->unsetProperty('_i18n'); <del> } <del> <del> /** <del> * Add in `_translations` marshalling handlers. You can disable marshalling <del> * of translations by setting `'translations' => false` in the options <del> * provided to `Table::newEntity()` or `Table::patchEntity()`. <del> * <del> * {@inheritDoc} <del> */ <del> public function buildMarshalMap($marshaller, $map, $options) <del> { <del> if (isset($options['translations']) && !$options['translations']) { <del> return []; <del> } <del> <del> return [ <del> '_translations' => function ($value, $entity) use ($marshaller, $options) { <del> /* @var \Cake\Datasource\EntityInterface $entity */ <del> $translations = $entity->get('_translations'); <del> foreach ($this->_config['fields'] as $field) { <del> $options['validate'] = $this->_config['validator']; <del> $errors = []; <del> if (!is_array($value)) { <del> return null; <del> } <del> foreach ($value as $language => $fields) { <del> if (!isset($translations[$language])) { <del> $translations[$language] = $this->table->newEntity(); <del> } <del> $marshaller->merge($translations[$language], $fields, $options); <del> if ((bool)$translations[$language]->getErrors()) { <del> $errors[$language] = $translations[$language]->getErrors(); <del> } <del> } <del> // Set errors into the root entity, so validation errors <del> // match the original form data position. <del> $entity->setErrors($errors); <del> } <del> <del> return $translations; <del> }, <del> ]; <del> } <del> <del> /** <del> * Sets the locale that should be used for all future find and save operations on <del> * the table where this behavior is attached to. <del> * <del> * When fetching records, the behavior will include the content for the locale set <del> * via this method, and likewise when saving data, it will save the data in that <del> * locale. <del> * <del> * Note that in case an entity has a `_locale` property set, that locale will win <del> * over the locale set via this method (and over the globally configured one for <del> * that matter)! <del> * <del> * @param string|null $locale The locale to use for fetching and saving records. Pass `null` <del> * in order to unset the current locale, and to make the behavior fall back to using the <del> * globally configured locale. <del> * @return $this <del> * @see \Cake\ORM\Behavior\TranslateBehavior::getLocale() <del> * @link https://book.cakephp.org/3.0/en/orm/behaviors/translate.html#retrieving-one-language-without-using-i18n-locale <del> * @link https://book.cakephp.org/3.0/en/orm/behaviors/translate.html#saving-in-another-language <del> */ <del> public function setLocale(?string $locale) <del> { <del> $this->locale = $locale; <del> <del> return $this; <del> } <del> <del> /** <del> * Returns the current locale. <del> * <del> * If no locale has been explicitly set via `setLocale()`, this method will return <del> * the currently configured global locale. <del> * <del> * @return string <del> * @see \Cake\I18n\I18n::getLocale() <del> * @see \Cake\ORM\Behavior\TranslateBehavior::setLocale() <del> */ <del> public function getLocale(): string <del> { <del> return $this->locale ?: I18n::getLocale(); <del> } <del> <ide> /** <ide> * Returns a fully aliased field name for translated fields. <ide> * <ide> protected function bundleTranslatedFields($entity) <ide> $entity->set('_i18n', $contents); <ide> } <ide> <del> /** <del> * Unset empty translations to avoid persistence. <del> * <del> * Should only be called if $this->_config['allowEmptyTranslations'] is false. <del> * <del> * @param \Cake\Datasource\EntityInterface $entity The entity to check for empty translations fields inside. <del> * @return void <del> */ <del> protected function unsetEmptyFields($entity) <del> { <del> $translations = (array)$entity->get('_translations'); <del> foreach ($translations as $locale => $translation) { <del> $fields = $translation->extract($this->_config['fields'], false); <del> foreach ($fields as $field => $value) { <del> if (strlen($value) === 0) { <del> $translation->unsetProperty($field); <del> } <del> } <del> <del> $translation = $translation->extract($this->_config['fields']); <del> <del> // If now, the current locale property is empty, <del> // unset it completely. <del> if (empty(array_filter($translation))) { <del> unset($entity->get('_translations')[$locale]); <del> } <del> } <del> <del> // If now, the whole _translations property is empty, <del> // unset it completely and return <del> if (empty($entity->get('_translations'))) { <del> $entity->unsetProperty('_translations'); <del> } <del> } <del> <ide> /** <ide> * Returns the ids found for each of the condition arrays passed for the translations <ide> * table. Each records is indexed by the corresponding position to the conditions array <ide><path>src/ORM/Behavior/Translate/ShadowTableStrategy.php <ide> use Cake\Database\Expression\FieldInterface; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Event\Event; <del>use Cake\I18n\I18n; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <ide> use Cake\ORM\PropertyMarshalInterface; <ide> use Cake\ORM\Query; <ide> class ShadowTableStrategy implements PropertyMarshalInterface <ide> <ide> use InstanceConfigTrait; <ide> use LocatorAwareTrait; <del> <del> /** <del> * Table instance <del> * <del> * @var \Cake\ORM\Table <del> */ <del> protected $table; <del> <del> /** <del> * The locale name that will be used to override fields in the bound table <del> * from the translations table <del> * <del> * @var string <del> */ <del> protected $locale; <del> <del> /** <del> * Instance of Table responsible for translating <del> * <del> * @var \Cake\ORM\Table <del> */ <del> protected $translationTable; <add> use TranslateStrategyTrait { <add> buildMarshalMap as private _buildMarshalMap; <add> } <ide> <ide> /** <ide> * Default config <ide> public function __construct(Table $table, array $config = []) <ide> ); <ide> } <ide> <del> /** <del> * Return translation table instance. <del> * <del> * @return \Cake\ORM\Table <del> */ <del> public function getTranslationTable(): Table <del> { <del> return $this->translationTable; <del> } <del> <del> /** <del> * Sets the locale that should be used for all future find and save operations on <del> * the table where this behavior is attached to. <del> * <del> * When fetching records, the behavior will include the content for the locale set <del> * via this method, and likewise when saving data, it will save the data in that <del> * locale. <del> * <del> * Note that in case an entity has a `_locale` property set, that locale will win <del> * over the locale set via this method (and over the globally configured one for <del> * that matter)! <del> * <del> * @param string|null $locale The locale to use for fetching and saving records. Pass `null` <del> * in order to unset the current locale, and to make the behavior fall back to using the <del> * globally configured locale. <del> * @return $this <del> * @see \Cake\ORM\Behavior\TranslateBehavior::getLocale() <del> * @link https://book.cakephp.org/3.0/en/orm/behaviors/translate.html#retrieving-one-language-without-using-i18n-locale <del> * @link https://book.cakephp.org/3.0/en/orm/behaviors/translate.html#saving-in-another-language <del> */ <del> public function setLocale(?string $locale) <del> { <del> $this->locale = $locale; <del> <del> return $this; <del> } <del> <del> /** <del> * Returns the current locale. <del> * <del> * If no locale has been explicitly set via `setLocale()`, this method will return <del> * the currently configured global locale. <del> * <del> * @return string <del> * @see \Cake\I18n\I18n::getLocale() <del> * @see \Cake\ORM\Behavior\TranslateBehavior::setLocale() <del> */ <del> public function getLocale(): string <del> { <del> return $this->locale ?: I18n::getLocale(); <del> } <del> <ide> /** <ide> * Create a hasMany association for all records <ide> * <ide> public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $o <ide> } <ide> } <ide> <del> /** <del> * Unsets the temporary `_i18n` property after the entity has been saved <del> * <del> * @param \Cake\Event\Event $event The beforeSave event that was fired <del> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved <del> * @return void <del> */ <del> public function afterSave(Event $event, EntityInterface $entity): void <del> { <del> $entity->unsetProperty('_i18n'); <del> } <del> <ide> /** <ide> * {@inheritDoc} <ide> */ <ide> public function buildMarshalMap($marshaller, $map, $options) <ide> { <ide> $this->translatedFields(); <ide> <del> if (isset($options['translations']) && !$options['translations']) { <del> return []; <del> } <del> <del> return [ <del> '_translations' => function ($value, $entity) use ($marshaller, $options) { <del> /* @var \Cake\Datasource\EntityInterface $entity */ <del> $translations = $entity->get('_translations'); <del> foreach ($this->_config['fields'] as $field) { <del> $options['validate'] = $this->_config['validator']; <del> $errors = []; <del> if (!is_array($value)) { <del> return null; <del> } <del> foreach ($value as $language => $fields) { <del> if (!isset($translations[$language])) { <del> $translations[$language] = $this->table->newEntity(); <del> } <del> $marshaller->merge($translations[$language], $fields, $options); <del> if ((bool)$translations[$language]->getErrors()) { <del> $errors[$language] = $translations[$language]->getErrors(); <del> } <del> } <del> // Set errors into the root entity, so validation errors <del> // match the original form data position. <del> $entity->setErrors($errors); <del> } <del> <del> return $translations; <del> }, <del> ]; <add> return $this->_buildMarshalMap($marshaller, $map, $options); <ide> } <ide> <ide> /** <ide> protected function bundleTranslatedFields($entity) <ide> $entity->set('_i18n', $translations); <ide> } <ide> <del> /** <del> * Unset empty translations to avoid persistence. <del> * <del> * Should only be called if $this->_config['allowEmptyTranslations'] is false. <del> * <del> * @param \Cake\Datasource\EntityInterface $entity The entity to check for empty translations fields inside. <del> * @return void <del> */ <del> protected function unsetEmptyFields($entity) <del> { <del> $translations = (array)$entity->get('_translations'); <del> foreach ($translations as $locale => $translation) { <del> $fields = $translation->extract($this->_config['fields'], false); <del> foreach ($fields as $field => $value) { <del> if (strlen($value) === 0) { <del> $translation->unsetProperty($field); <del> } <del> } <del> <del> $translation = $translation->extract($this->_config['fields']); <del> <del> // If now, the current locale property is empty, <del> // unset it completely. <del> if (empty(array_filter($translation))) { <del> unset($entity->get('_translations')[$locale]); <del> } <del> } <del> <del> // If now, the whole _translations property is empty, <del> // unset it completely and return <del> if (empty($entity->get('_translations'))) { <del> $entity->unsetProperty('_translations'); <del> } <del> } <del> <ide> /** <ide> * Lazy define and return the main table fields <ide> * <ide><path>src/ORM/Behavior/Translate/TranslateStrategyTrait.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.0.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\ORM\Behavior\Translate; <add> <add>use Cake\Datasource\EntityInterface; <add>use Cake\Event\Event; <add>use Cake\I18n\I18n; <add>use Cake\ORM\Table; <add> <add>/** <add> * Contains common code needed by TranslateBehavior strategy classes. <add> */ <add>trait TranslateStrategyTrait <add>{ <add> <add> /** <add> * Table instance <add> * <add> * @var \Cake\ORM\Table <add> */ <add> protected $table; <add> <add> /** <add> * The locale name that will be used to override fields in the bound table <add> * from the translations table <add> * <add> * @var string <add> */ <add> protected $locale; <add> <add> /** <add> * Instance of Table responsible for translating <add> * <add> * @var \Cake\ORM\Table <add> */ <add> protected $translationTable; <add> <add> /** <add> * Return translation table instance. <add> * <add> * @return \Cake\ORM\Table <add> */ <add> public function getTranslationTable(): Table <add> { <add> return $this->translationTable; <add> } <add> <add> /** <add> * Sets the locale that should be used for all future find and save operations on <add> * the table where this behavior is attached to. <add> * <add> * When fetching records, the behavior will include the content for the locale set <add> * via this method, and likewise when saving data, it will save the data in that <add> * locale. <add> * <add> * Note that in case an entity has a `_locale` property set, that locale will win <add> * over the locale set via this method (and over the globally configured one for <add> * that matter)! <add> * <add> * @param string|null $locale The locale to use for fetching and saving records. Pass `null` <add> * in order to unset the current locale, and to make the behavior fall back to using the <add> * globally configured locale. <add> * @return $this <add> * @see \Cake\ORM\Behavior\TranslateBehavior::getLocale() <add> * @link https://book.cakephp.org/3.0/en/orm/behaviors/translate.html#retrieving-one-language-without-using-i18n-locale <add> * @link https://book.cakephp.org/3.0/en/orm/behaviors/translate.html#saving-in-another-language <add> */ <add> public function setLocale(?string $locale) <add> { <add> $this->locale = $locale; <add> <add> return $this; <add> } <add> <add> /** <add> * Returns the current locale. <add> * <add> * If no locale has been explicitly set via `setLocale()`, this method will return <add> * the currently configured global locale. <add> * <add> * @return string <add> * @see \Cake\I18n\I18n::getLocale() <add> * @see \Cake\ORM\Behavior\TranslateBehavior::setLocale() <add> */ <add> public function getLocale(): string <add> { <add> return $this->locale ?: I18n::getLocale(); <add> } <add> <add> /** <add> * Unset empty translations to avoid persistence. <add> * <add> * Should only be called if $this->_config['allowEmptyTranslations'] is false. <add> * <add> * @param \Cake\Datasource\EntityInterface $entity The entity to check for empty translations fields inside. <add> * @return void <add> */ <add> protected function unsetEmptyFields($entity) <add> { <add> $translations = (array)$entity->get('_translations'); <add> foreach ($translations as $locale => $translation) { <add> $fields = $translation->extract($this->_config['fields'], false); <add> foreach ($fields as $field => $value) { <add> if (strlen($value) === 0) { <add> $translation->unsetProperty($field); <add> } <add> } <add> <add> $translation = $translation->extract($this->_config['fields']); <add> <add> // If now, the current locale property is empty, <add> // unset it completely. <add> if (empty(array_filter($translation))) { <add> unset($entity->get('_translations')[$locale]); <add> } <add> } <add> <add> // If now, the whole _translations property is empty, <add> // unset it completely and return <add> if (empty($entity->get('_translations'))) { <add> $entity->unsetProperty('_translations'); <add> } <add> } <add> <add> /** <add> * Build a set of properties that should be included in the marshalling process. <add> <add> * Add in `_translations` marshalling handlers. You can disable marshalling <add> * of translations by setting `'translations' => false` in the options <add> * provided to `Table::newEntity()` or `Table::patchEntity()`. <add> * <add> * @param \Cake\ORM\Marshaller $marshaller The marhshaller of the table the behavior is attached to. <add> * @param array $map The property map being built. <add> * @param array $options The options array used in the marshalling call. <add> * @return array A map of `[property => callable]` of additional properties to marshal. <add> */ <add> public function buildMarshalMap($marshaller, $map, $options) <add> { <add> if (isset($options['translations']) && !$options['translations']) { <add> return []; <add> } <add> <add> return [ <add> '_translations' => function ($value, $entity) use ($marshaller, $options) { <add> /* @var \Cake\Datasource\EntityInterface $entity */ <add> $translations = $entity->get('_translations'); <add> foreach ($this->_config['fields'] as $field) { <add> $options['validate'] = $this->_config['validator']; <add> $errors = []; <add> if (!is_array($value)) { <add> return null; <add> } <add> foreach ($value as $language => $fields) { <add> if (!isset($translations[$language])) { <add> $translations[$language] = $this->table->newEntity(); <add> } <add> $marshaller->merge($translations[$language], $fields, $options); <add> if ((bool)$translations[$language]->getErrors()) { <add> $errors[$language] = $translations[$language]->getErrors(); <add> } <add> } <add> // Set errors into the root entity, so validation errors <add> // match the original form data position. <add> $entity->setErrors($errors); <add> } <add> <add> return $translations; <add> }, <add> ]; <add> } <add> <add> /** <add> * Unsets the temporary `_i18n` property after the entity has been saved <add> * <add> * @param \Cake\Event\Event $event The beforeSave event that was fired <add> * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved <add> * @return void <add> */ <add> public function afterSave(Event $event, EntityInterface $entity): void <add> { <add> $entity->unsetProperty('_i18n'); <add> } <add>}
3
Text
Text
fix typo occuring -> occurring
e98da3d0307b288f254e6e2dfcb3a7ce7bc4d555
<ide><path>doc/api/util.md <ide> supported encodings or an alias. <ide> * Returns: {string} <ide> <ide> Decodes the `input` and returns a string. If `options.stream` is `true`, any <del>incomplete byte sequences occuring at the end of the `input` are buffered <add>incomplete byte sequences occurring at the end of the `input` are buffered <ide> internally and emitted after the next call to `textDecoder.decode()`. <ide> <ide> If `textDecoder.fatal` is `true`, decoding errors that occur will result in a
1
Javascript
Javascript
remove debug statement
f3410a3a95e072753509d1b73eeb14370231501f
<ide><path>server/boot/challenge.js <ide> module.exports = function(app) { <ide> <ide> // create a stream of challenge blocks <ide> const blocks$ = challenge$ <del> .doOnNext(() => debug('query challenges')) <ide> .map(challenge => challenge.toJSON()) <ide> // group challenges by block | returns a stream of observables <ide> .groupBy(challenge => challenge.block)
1
Ruby
Ruby
fix rubocop space before comma
0699a3df9a137a97d50af4a29f96553bf2942d0e
<ide><path>activesupport/test/core_ext/object/blank_test.rb <ide> def empty? <ide> end <ide> <ide> BLANK = [ EmptyTrue.new, nil, false, "", " ", " \n\t \r ", " ", "\u00a0", [], {}, " ".encode("UTF-16LE")] <del> NOT = [ EmptyFalse.new, Object.new, true, 0, 1, "a", [nil], { nil => 0 }, Time.now , "my value".encode("UTF-16LE")] <add> NOT = [ EmptyFalse.new, Object.new, true, 0, 1, "a", [nil], { nil => 0 }, Time.now, "my value".encode("UTF-16LE")] <ide> <ide> def test_blank <ide> BLANK.each { |v| assert_equal true, v.blank?, "#{v.inspect} should be blank" }
1
Javascript
Javascript
remove use of object.assign module
cb5d37713f381aa8e57e9b314c03a25a2e11796b
<ide><path>Libraries/ReactNative/ReactNativeTextComponent.js <ide> var ReactNativeTagHandles = require('ReactNativeTagHandles'); <ide> var UIManager = require('UIManager'); <ide> <del>var assign = require('Object.assign'); <ide> var invariant = require('fbjs/lib/invariant'); <ide> <ide> var ReactNativeTextComponent = function(props) { <ide> // This constructor and its argument is currently used by mocks. <ide> }; <ide> <del>assign(ReactNativeTextComponent.prototype, { <add>Object.assign(ReactNativeTextComponent.prototype, { <ide> <ide> construct: function(text) { <ide> // This is really a ReactText (ReactNode), not a ReactElement
1
Javascript
Javascript
include stack with test errors
ab1f14246ac0c520909ffbfccf379780f4fbe77f
<ide><path>curriculum/test/test-challenges.js <ide> function cleanup() { <ide> } <ide> <ide> function runTests({ challengesForLang, meta }) { <add> // rethrow unhandled rejections to make sure the tests exit with -1 <ide> process.on('unhandledRejection', err => { <del> throw new Error(`unhandledRejection: ${err.name}, ${err.message}`); <add> throw err; <ide> }); <ide> <ide> describe('Check challenges', function() {
1
Ruby
Ruby
improve example in migrations docs, closes
f65ab3b233e112679fc7a183b488c5356a01c96c
<ide><path>activerecord/lib/active_record/migration.rb <ide> def initialize(version) <ide> # add_column :people, :salary, :integer <ide> # Person.reset_column_information <ide> # Person.find(:all).each do |p| <del> # p.salary = SalaryCalculator.compute(p) <add> # p.update_attribute :salary, SalaryCalculator.compute(p) <ide> # end <ide> # end <ide> # end <ide> def initialize(version) <ide> # ... <ide> # say_with_time "Updating salaries..." do <ide> # Person.find(:all).each do |p| <del> # p.salary = SalaryCalculator.compute(p) <add> # p.update_attribute :salary, SalaryCalculator.compute(p) <ide> # end <ide> # end <ide> # ...
1
Java
Java
update license header for https (nohttp rule)
a22feac8036393725113222055166eb9e7211c9a
<ide><path>spring-core/src/main/java/org/springframework/cglib/beans/BeanMap.java <ide> * you may not use this file except in compliance with the License. <ide> * You may obtain a copy of the License at <ide> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <add> * https://www.apache.org/licenses/LICENSE-2.0 <ide> * <ide> * Unless required by applicable law or agreed to in writing, software <ide> * distributed under the License is distributed on an "AS IS" BASIS, <ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.cglib.beans; <ide> <ide> import java.security.ProtectionDomain;
1
Javascript
Javascript
fix links to frostbite pbr document
07d757661ebd729eb38a18ab2f0394dd3fa61d9b
<ide><path>src/lights/PointLight.js <ide> function PointLight( color, intensity, distance, decay ) { <ide> get: function () { <ide> <ide> // intensity = power per solid angle. <del> // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf <add> // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf <ide> return this.intensity * 4 * Math.PI; <ide> <ide> }, <ide> set: function ( power ) { <ide> <ide> // intensity = power per solid angle. <del> // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf <add> // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf <ide> this.intensity = power / ( 4 * Math.PI ); <ide> <ide> } <ide><path>src/lights/SpotLight.js <ide> function SpotLight( color, intensity, distance, angle, penumbra, decay ) { <ide> get: function () { <ide> <ide> // intensity = power per solid angle. <del> // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf <add> // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf <ide> return this.intensity * Math.PI; <ide> <ide> }, <ide> set: function ( power ) { <ide> <ide> // intensity = power per solid angle. <del> // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf <add> // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf <ide> this.intensity = power / Math.PI; <ide> <ide> }
2
Go
Go
remove signal_freebsd (already in pkg/signal)
3f8ffb461ab66535b3c3a96a564c06db12a27281
<ide><path>utils/signal_freebsd.go <del>package utils <del> <del>import ( <del> "os" <del> "os/signal" <del> "syscall" <del>) <del> <del>func CatchAll(sigc chan os.Signal) { <del> signal.Notify(sigc, <del> syscall.SIGABRT, <del> syscall.SIGALRM, <del> syscall.SIGBUS, <del> syscall.SIGCHLD, <del> syscall.SIGCONT, <del> syscall.SIGFPE, <del> syscall.SIGHUP, <del> syscall.SIGILL, <del> syscall.SIGINT, <del> syscall.SIGIO, <del> syscall.SIGIOT, <del> syscall.SIGKILL, <del> syscall.SIGPIPE, <del> syscall.SIGPROF, <del> syscall.SIGQUIT, <del> syscall.SIGSEGV, <del> syscall.SIGSTOP, <del> syscall.SIGSYS, <del> syscall.SIGTERM, <del> syscall.SIGTRAP, <del> syscall.SIGTSTP, <del> syscall.SIGTTIN, <del> syscall.SIGTTOU, <del> syscall.SIGURG, <del> syscall.SIGUSR1, <del> syscall.SIGUSR2, <del> syscall.SIGVTALRM, <del> syscall.SIGWINCH, <del> syscall.SIGXCPU, <del> syscall.SIGXFSZ, <del> ) <del>}
1
Ruby
Ruby
use dedicated exception for already tapped
1cb7eca3a58a6297c833f4d6f3f8931ebc3a2e52
<ide><path>Library/Homebrew/cmd/tap.rb <ide> def install_tap user, repo <ide> <ide> # we downcase to avoid case-insensitive filesystem issues <ide> tapd = HOMEBREW_LIBRARY/"Taps/#{user.downcase}-#{repo.downcase}" <del> raise "Already tapped!" if tapd.directory? <add> raise AlreadyTappedError if tapd.directory? <ide> abort unless system "git clone https://github.com/#{repouser}/homebrew-#{repo} #{tapd}" <ide> <ide> files = [] <ide><path>Library/Homebrew/exceptions.rb <ide> def message; <<-EOS.undent <ide> end <ide> end <ide> <add># raised in install_tap <add>class AlreadyTappedError < RuntimeError <add> def initialize; super "Already tapped!" end <add>end <add> <ide> # raised in CurlDownloadStrategy.fetch <ide> class CurlDownloadStrategyError < RuntimeError; end <ide>
2
Go
Go
fix a panic introduced by
e28730d44b257597b6c37f9040eee3fbd3a7ff43
<ide><path>libnetwork/sandbox.go <ide> func (sb *sandbox) ResolveName(name string, ipType int) ([]net.IP, bool) { <ide> newList := []*endpoint{} <ide> if !sb.controller.isDistributedControl() { <ide> newList = append(newList, getDynamicNwEndpoints(epList)...) <del> newList = append(newList, getIngressNwEndpoint(epList)) <add> ingressEP := getIngressNwEndpoint(epList) <add> if ingressEP != nil { <add> newList = append(newList, ingressEP) <add> } <ide> newList = append(newList, getLocalNwEndpoints(epList)...) <ide> epList = newList <ide> }
1
Javascript
Javascript
cover the error cases
909d2e5503db90283a7a849a4fb2408f311a1ecb
<ide><path>packager/src/node-haste/Package.js <ide> class Package { <ide> <ide> isHaste() { <ide> return this._cache.get(this.path, 'package-haste', () => <del> Promise.resolve(!!this.read().name) <add> Promise.resolve().then(() => !!this.read().name) <ide> ); <ide> } <ide> <ide> getName(): Promise<string> { <ide> return this._cache.get(this.path, 'package-name', () => <del> Promise.resolve(this.read().name) <add> Promise.resolve().then(() => this.read().name) <ide> ); <ide> } <ide>
1
PHP
PHP
add default type
0565d80699af9fc9cb417241ddef6e4563d42551
<ide><path>src/Database/Connection.php <ide> public function inTransaction(): bool <ide> * @param string|int|\Cake\Database\TypeInterface $type Type to be used for determining kind of quoting to perform <ide> * @return string Quoted value <ide> */ <del> public function quote($value, $type): string <add> public function quote($value, $type = 'string'): string <ide> { <ide> [$value, $type] = $this->cast($value, $type); <ide> <ide><path>src/Database/TypeConverterTrait.php <ide> trait TypeConverterTrait <ide> * @return array list containing converted value and internal type <ide> * @pslam-return array{mixed, int} <ide> */ <del> public function cast($value, $type): array <add> public function cast($value, $type = 'string'): array <ide> { <ide> if (is_string($type)) { <ide> $type = TypeFactory::build($type);
2
Java
Java
polish forwardedheaderfilter and related code
ac495d7380e56b0160391a7764fb7e2f5eefb8c9
<ide><path>spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java <ide> public void setRemoveOnly(boolean removeOnly) { <ide> } <ide> <ide> /** <del> * Use this property to enable relative redirects as explained in and also <del> * using the same response wrapper as {@link RelativeRedirectFilter} does. <del> * Or if both filters are used, only one will wrap the response. <add> * Use this property to enable relative redirects as explained in <add> * {@link RelativeRedirectFilter}, and also using the same response wrapper <add> * as that filter does, or if both are configured, only one will wrap. <ide> * <p>By default, if this property is set to false, in which case calls to <ide> * {@link HttpServletResponse#sendRedirect(String)} are overridden in order <del> * to turn relative into absolute URLs since (which Servlet containers are <del> * also required to do) also taking forwarded headers into consideration. <add> * to turn relative into absolute URLs, also taking into account forwarded <add> * headers. <ide> * @param relativeRedirects whether to use relative redirects <ide> * @since 4.3.10 <ide> */ <ide> public ForwardedHeaderExtractingResponse(HttpServletResponse response, HttpServl <ide> this.request = request; <ide> } <ide> <del> @Override <del> public void sendRedirect(String location) throws IOException { <del> UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(location); <del> <del> // Absolute location <del> if (builder.build().getScheme() != null) { <del> super.sendRedirect(location); <del> return; <del> } <add>@Override <add>public void sendRedirect(String location) throws IOException { <ide> <del> // Network-path reference <del> if (location.startsWith("//")) { <del> String scheme = this.request.getScheme(); <del> super.sendRedirect(builder.scheme(scheme).toUriString()); <del> return; <del> } <add> UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(location); <add> UriComponents uriComponents = builder.build(); <ide> <del> String fragment = null; <del> int fragmentIndex = location.indexOf('#'); <del> if (fragmentIndex != -1) { <del> if (location.length() > fragmentIndex) { <del> fragment = location.substring(fragmentIndex + 1); <del> } <del> location = location.substring(0, fragmentIndex); <del> } <add> // Absolute location <add> if (uriComponents.getScheme() != null) { <add> super.sendRedirect(location); <add> return; <add> } <ide> <del> String query = null; <del> int queryIndex = location.indexOf('?'); <del> if (queryIndex != -1) { <del> if (location.length() > queryIndex) { <del> query = location.substring(queryIndex + 1); <del> } <del> location = location.substring(0, queryIndex); <del> } <add> // Network-path reference <add> if (location.startsWith("//")) { <add> String scheme = this.request.getScheme(); <add> super.sendRedirect(builder.scheme(scheme).toUriString()); <add> return; <add> } <ide> <del> // Relative to Servlet container root or to current request <del> String path = (location.startsWith(FOLDER_SEPARATOR) ? location : <del> StringUtils.applyRelativePath(this.request.getRequestURI(), location)); <add> String path = uriComponents.getPath(); <add> if (path != null) { <add> // Relative to Servlet container root or to current request <add> path = (path.startsWith(FOLDER_SEPARATOR) ? path : <add> StringUtils.applyRelativePath(this.request.getRequestURI(), path)); <add> } <ide> <del> String result = UriComponentsBuilder <del> .fromHttpRequest(new ServletServerHttpRequest(this.request)) <del> .replacePath(path) <del> .replaceQuery(query) <del> .fragment(fragment) <del> .build().normalize().toUriString(); <add> String result = UriComponentsBuilder <add> .fromHttpRequest(new ServletServerHttpRequest(this.request)) <add> .replacePath(path) <add> .replaceQuery(uriComponents.getQuery()) <add> .fragment(uriComponents.getFragment()) <add> .build().normalize().toUriString(); <ide> <del> super.sendRedirect(result); <del> } <add> super.sendRedirect(result); <add>} <ide> } <ide> <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/filter/RelativeRedirectFilter.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> /** <ide> * Overrides {@link HttpServletResponse#sendRedirect(String)} and handles it by <del> * setting the HTTP status and "Location" headers. This keeps the Servlet <del> * container from re-writing relative redirect URLs and instead follows the <del> * recommendation in <a href="https://tools.ietf.org/html/rfc7231#section-7.1.2"> <del> * RFC 7231 Section 7.1.2</a>. <add> * setting the HTTP status and "Location" headers, which keeps the Servlet <add> * container from re-writing relative redirect URLs into absolute ones. <add> * Servlet containers are required to do that but against the recommendation of <add> * <a href="https://tools.ietf.org/html/rfc7231#section-7.1.2"> RFC 7231 Section 7.1.2</a>, <add> * and furthermore not necessarily taking into account "X-Forwarded" headers. <ide> * <del> * <p><strong>Note:</strong> While relative redirects are more efficient they <del> * may not work with reverse proxies under some configurations. <add> * <p><strong>Note:</strong> While relative redirects are recommended in the <add> * RFC, under some configurations with reverse proxies they may not work. <ide> * <ide> * @author Rob Winch <ide> * @author Rossen Stoyanchev <ide><path>spring-web/src/main/java/org/springframework/web/filter/RelativeRedirectResponseWrapper.java <ide> */ <ide> package org.springframework.web.filter; <ide> <del>import java.io.IOException; <del>import javax.servlet.ServletResponse; <ide> import javax.servlet.http.HttpServletResponse; <ide> import javax.servlet.http.HttpServletResponseWrapper; <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.util.Assert; <add>import org.springframework.web.util.WebUtils; <ide> <ide> /** <ide> * A response wrapper used for the implementation of <ide> private RelativeRedirectResponseWrapper(HttpServletResponse response, HttpStatus <ide> <ide> <ide> @Override <del> public void sendRedirect(String location) throws IOException { <add> public void sendRedirect(String location) { <ide> setStatus(this.redirectStatus.value()); <ide> setHeader(HttpHeaders.LOCATION, location); <ide> } <ide> public void sendRedirect(String location) throws IOException { <ide> public static HttpServletResponse wrapIfNecessary(HttpServletResponse response, <ide> HttpStatus redirectStatus) { <ide> <del> return (hasWrapper(response) ? response : new RelativeRedirectResponseWrapper(response, redirectStatus)); <del> } <add> RelativeRedirectResponseWrapper wrapper = <add> WebUtils.getNativeResponse(response, RelativeRedirectResponseWrapper.class); <ide> <del> private static boolean hasWrapper(ServletResponse response) { <del> if (response instanceof RelativeRedirectResponseWrapper) { <del> return true; <del> } <del> while (response instanceof HttpServletResponseWrapper) { <del> response = ((HttpServletResponseWrapper) response).getResponse(); <del> if (response instanceof RelativeRedirectResponseWrapper) { <del> return true; <del> } <del> } <del> return false; <add> return (wrapper != null ? response : <add> new RelativeRedirectResponseWrapper(response, redirectStatus)); <ide> } <ide> <ide> } <ide><path>spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java <ide> public void sendRedirectWhenRequestOnlyAndNoXForwardedThenUsesRelativeRedirects( <ide> } <ide> <ide> private String sendRedirect(final String location) throws ServletException, IOException { <del> MockHttpServletResponse response = doWithFiltersAndGetResponse(this.filter, new OncePerRequestFilter() { <add> Filter filter = new OncePerRequestFilter() { <ide> @Override <del> protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) <del> throws ServletException, IOException { <del> response.sendRedirect(location); <add> protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, <add> FilterChain chain) throws IOException { <add> <add> res.sendRedirect(location); <ide> } <del> }); <add> }; <add> MockHttpServletResponse response = doWithFiltersAndGetResponse(this.filter, filter); <ide> return response.getRedirectedUrl(); <ide> } <ide> <ide> @SuppressWarnings("serial") <del> private MockHttpServletResponse doWithFiltersAndGetResponse(Filter... filters) throws ServletException, IOException { <add> private MockHttpServletResponse doWithFiltersAndGetResponse(Filter... filters) <add> throws ServletException, IOException { <add> <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> FilterChain filterChain = new MockFilterChain(new HttpServlet() {}, filters); <ide> filterChain.doFilter(request, response);
4
Python
Python
fix tf_idf output mode for lookup layers
66290dec4381ebd9f618aa4d43360fd10866a9ec
<ide><path>keras/layers/preprocessing/index_lookup.py <ide> def set_vocabulary(self, vocabulary, idf_weights=None): <ide> idf_weights, (front_padding, back_padding), <ide> "constant", <ide> constant_values=(front_padding_value, back_padding_value)) <del> weights = tf.convert_to_tensor(weights, dtype=backend.floatx()) <add> weights = tf.convert_to_tensor(weights, dtype=self.compute_dtype) <ide> self.idf_weights.assign(weights) <ide> self.idf_weights_const = self.idf_weights.value() <ide> <ide> def update_state(self, data): <ide> <ide> data = self._standardize_inputs(data, self.vocabulary_dtype) <ide> if data.shape.rank == 0: <del> data = tf.expand_dims(data, -1) <add> data = tf.expand_dims(data, 0) <ide> if data.shape.rank == 1: <del> data = tf.expand_dims(data, -1) <add> # Expand dims on axis 0 for tf-idf. A 1-d tensor is a single document. <add> data = tf.expand_dims(data, 0) <ide> <ide> tokens, counts = self._num_tokens(data) <ide> self.token_counts.insert(tokens, counts + self.token_counts.lookup(tokens)) <ide> def finalize_state(self): <ide> token_document_counts = self.token_document_counts.lookup(tokens) <ide> idf_weights = self._inverse_document_frequency(token_document_counts, <ide> self.num_documents) <del> idf_weights = tf.cast(idf_weights, backend.floatx()) <add> idf_weights = tf.cast(idf_weights, self.compute_dtype) <ide> # Pad the front of idf_weights with the average idf weight for OOV tokens. <ide> # We cannot compute the real idf weight of OOV in a single pass. <ide> idf_weights = tf.pad( <ide> idf_weights, [[self._token_start_index(), 0]], <ide> constant_values=tf.reduce_mean(idf_weights)) <add> if self.pad_to_max_tokens and self.max_tokens is not None: <add> # Pad the back of idf_weights with zeros. <add> idf_weights = tf.pad( <add> idf_weights, [[0, self.max_tokens - tf.size(idf_weights)]], <add> constant_values=0) <ide> self.idf_weights.assign(idf_weights) <ide> self.idf_weights_const = self.idf_weights.value() <ide> <ide><path>keras/layers/preprocessing/index_lookup_test.py <ide> """Tests for Keras text vectorization preprocessing layer.""" <ide> <ide> import itertools <add>import math <ide> import os <ide> import random <ide> import string <ide> def test_one_hot_output_shape(self): <ide> outputs = layer(inputs) <ide> self.assertAllEqual(outputs.shape.as_list(), [16, 2]) <ide> <del> @parameterized.named_parameters( <del> ("float32", tf.float32), <del> ("float64", tf.float64), <add> @parameterized.product( <add> sparse=[True, False], <add> adapt=[True, False], <add> pad_to_max=[True, False], <add> mode=["multi_hot", "count", "tf_idf"], <add> dtype=[tf.float32, tf.float64], <ide> ) <del> def test_one_hot_output_dtype(self, dtype): <del> inputs = keras.Input(batch_size=16, shape=(1,), dtype=tf.string) <add> def test_binned_output(self, sparse, adapt, pad_to_max, mode, dtype): <add> """Check "multi_hot", "count", and "tf_idf" output.""" <add> # Adapt breaks ties with sort order. <add> vocab_data = ["wind", "fire", "earth", "and"] <add> # IDF weight for a term in 1 out of 1 document is log(1 + 1/2). <add> idf_data = [math.log(1.5)] * 4 <add> input_data = np.array([["and", "earth", "fire", "and", ""], <add> ["michigan", "wind", "and", "ohio", ""]]) <add> <add> if mode == "count": <add> expected_output = np.array([ <add> [0, 0, 1, 1, 2], <add> [2, 1, 0, 0, 1], <add> ]) <add> elif mode == "tf_idf": <add> expected_output = np.array([ <add> [0, 0, 1, 1, 2], <add> [2, 1, 0, 0, 1], <add> ]) * math.log(1.5) <add> else: <add> expected_output = np.array([ <add> [0, 0, 1, 1, 1], <add> [1, 1, 0, 0, 1], <add> ]) <add> expected_output_shape = [None, 5] <add> if pad_to_max: <add> expected_output = np.concatenate((expected_output, [[0], [0]]), axis=1) <add> expected_output_shape = [None, 6] <add> <add> inputs = keras.Input(shape=(None,), dtype=tf.string) <ide> layer = index_lookup.IndexLookup( <del> vocabulary=["earth"], <del> max_tokens=2, <add> max_tokens=6, <ide> num_oov_indices=1, <ide> mask_token="", <ide> oov_token="[OOV]", <del> output_mode=index_lookup.ONE_HOT, <add> output_mode=mode, <add> pad_to_max_tokens=pad_to_max, <ide> vocabulary_dtype=tf.string, <add> sparse=sparse, <add> vocabulary=None if adapt else vocab_data, <add> idf_weights=None if adapt or mode != "tf_idf" else idf_data, <ide> dtype=dtype) <add> if adapt: <add> layer.adapt(vocab_data) <ide> outputs = layer(inputs) <del> self.assertAllEqual(outputs.dtype, dtype) <del> <del> def test_multi_hot_output_hard_maximum(self): <del> """Check binary output when pad_to_max_tokens=True.""" <del> vocab_data = ["earth", "wind", "and", "fire"] <del> input_array = np.array([["earth", "wind", "and", "fire", ""], <del> ["fire", "fire", "and", "earth", "michigan"]]) <del> expected_output = [ <del> [0, 1, 1, 1, 1, 0], <del> [1, 1, 0, 1, 1, 0], <del> ] <del> <del> input_data = keras.Input(shape=(None,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=6, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.MULTI_HOT, <del> pad_to_max_tokens=True, <del> vocabulary_dtype=tf.string) <del> layer.set_vocabulary(vocab_data) <del> binary_data = layer(input_data) <del> model = keras.Model(inputs=input_data, outputs=binary_data) <del> output_dataset = model.predict(input_array) <del> self.assertAllEqual(expected_output, output_dataset) <add> model = keras.Model(inputs, outputs) <add> output_data = model.predict(input_data) <add> if sparse: <add> output_data = tf.sparse.to_dense(output_data) <add> # Check output data. <add> self.assertAllClose(expected_output, output_data) <add> # Check symbolic output shape. <add> self.assertAllEqual(expected_output_shape, outputs.shape.as_list()) <add> # Check output dtype. <add> self.assertAllEqual(dtype, output_data.dtype) <ide> <ide> def test_multi_hot_output_no_oov(self): <del> """Check binary output when pad_to_max_tokens=True.""" <add> """Check multi hot output when num_oov_indices=0.""" <ide> vocab_data = ["earth", "wind", "and", "fire"] <ide> valid_input = np.array([["earth", "wind", "and", "fire"], <ide> ["fire", "and", "earth", ""]]) <ide> def test_multi_hot_output_hard_maximum_multiple_adapts(self): <ide> self.assertAllEqual(first_expected_output, first_output) <ide> self.assertAllEqual(second_expected_output, second_output) <ide> <del> def test_multi_hot_output_soft_maximum(self): <del> """Check multi_hot output when pad_to_max_tokens=False.""" <del> vocab_data = ["earth", "wind", "and", "fire"] <del> input_array = np.array([["earth", "wind", "and", "fire", ""], <del> ["fire", "and", "earth", "michigan", ""]]) <del> expected_output = [ <del> [0, 1, 1, 1, 1], <del> [1, 1, 0, 1, 1], <del> ] <del> <del> input_data = keras.Input(shape=(None,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=None, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.MULTI_HOT, <del> vocabulary_dtype=tf.string) <del> layer.set_vocabulary(vocab_data) <del> binary_data = layer(input_data) <del> model = keras.Model(inputs=input_data, outputs=binary_data) <del> output_dataset = model.predict(input_array) <del> self.assertAllEqual(expected_output, output_dataset) <del> <del> def test_multi_hot_output_shape(self): <del> input_data = keras.Input(batch_size=16, shape=(4,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=2, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.MULTI_HOT, <del> vocabulary=["foo"], <del> vocabulary_dtype=tf.string) <del> binary_data = layer(input_data) <del> self.assertAllEqual(binary_data.shape.as_list(), [16, 2]) <del> <del> def test_count_output_hard_maxiumum(self): <del> """Check count output when pad_to_max_tokens=True.""" <del> vocab_data = ["earth", "wind", "and", "fire"] <del> input_array = np.array([["earth", "wind", "and", "wind", ""], <del> ["fire", "fire", "fire", "michigan", ""]]) <del> expected_output = [ <del> [0, 1, 2, 1, 0, 0], <del> [1, 0, 0, 0, 3, 0], <del> ] <del> <del> input_data = keras.Input(shape=(None,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=6, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.COUNT, <del> pad_to_max_tokens=True, <del> vocabulary_dtype=tf.string) <del> layer.set_vocabulary(vocab_data) <del> count_data = layer(input_data) <del> model = keras.Model(inputs=input_data, outputs=count_data) <del> output_dataset = model.predict(input_array) <del> self.assertAllEqual(expected_output, output_dataset) <del> <del> def test_count_output_soft_maximum(self): <del> """Check count output when pad_to_max_tokens=False.""" <del> vocab_data = ["earth", "wind", "and", "fire"] <del> input_array = np.array([["earth", "wind", "and", "wind", ""], <del> ["fire", "fire", "fire", "michigan", ""]]) <del> expected_output = [ <del> [0, 1, 2, 1, 0], <del> [1, 0, 0, 0, 3], <del> ] <del> <del> input_data = keras.Input(shape=(None,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=None, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.COUNT, <del> vocabulary_dtype=tf.string) <del> layer.set_vocabulary(vocab_data) <del> count_data = layer(input_data) <del> model = keras.Model(inputs=input_data, outputs=count_data) <del> output_dataset = model.predict(input_array) <del> self.assertAllEqual(expected_output, output_dataset) <del> <del> def test_count_output_shape(self): <del> input_data = keras.Input(batch_size=16, shape=(4,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=2, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.COUNT, <del> vocabulary=["foo"], <del> vocabulary_dtype=tf.string) <del> count_data = layer(input_data) <del> self.assertAllEqual(count_data.shape.as_list(), [16, 2]) <del> <del> @parameterized.named_parameters( <del> ("sparse", True), <del> ("dense", False), <del> ) <del> def test_ifidf_output_hard_maximum(self, sparse): <del> """Check tf-idf output when pad_to_max_tokens=True.""" <del> vocab_data = ["earth", "wind", "and", "fire"] <del> # OOV idf weight (bucket 0) should 0.5, the average of passed weights. <del> idf_weights = [.4, .25, .75, .6] <del> input_array = np.array([["earth", "wind", "and", "earth", ""], <del> ["ohio", "fire", "earth", "michigan", ""]]) <del> expected_output = [ <del> [0.00, 0.80, 0.25, 0.75, 0.00, 0.00], <del> [1.00, 0.40, 0.00, 0.00, 0.60, 0.00], <del> ] <del> <del> input_data = keras.Input(shape=(None,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=6, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.TF_IDF, <del> pad_to_max_tokens=True, <del> vocabulary_dtype=tf.string, <del> sparse=sparse, <del> vocabulary=vocab_data, <del> idf_weights=idf_weights) <del> layer_output = layer(input_data) <del> model = keras.Model(inputs=input_data, outputs=layer_output) <del> output_dataset = model.predict(input_array) <del> if sparse: <del> output_dataset = tf.sparse.to_dense(output_dataset) <del> self.assertAllClose(expected_output, output_dataset) <del> <del> @parameterized.named_parameters( <del> ("sparse", True), <del> ("dense", False), <del> ) <del> def test_ifidf_output_soft_maximum(self, sparse): <del> """Check tf-idf output when pad_to_max_tokens=False.""" <del> vocab_data = ["earth", "wind", "and", "fire"] <del> # OOV idf weight (bucket 0) should 0.5, the average of passed weights. <del> idf_weights = [.4, .25, .75, .6] <del> input_array = np.array([["earth", "wind", "and", "earth", ""], <del> ["ohio", "fire", "earth", "michigan", ""]]) <del> expected_output = [ <del> [0.00, 0.80, 0.25, 0.75, 0.00], <del> [1.00, 0.40, 0.00, 0.00, 0.60], <del> ] <del> <del> input_data = keras.Input(shape=(None,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=None, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.TF_IDF, <del> vocabulary_dtype=tf.string, <del> sparse=sparse, <del> vocabulary=vocab_data, <del> idf_weights=idf_weights) <del> layer_output = layer(input_data) <del> model = keras.Model(inputs=input_data, outputs=layer_output) <del> output_dataset = model.predict(input_array) <del> if sparse: <del> output_dataset = tf.sparse.to_dense(output_dataset) <del> self.assertAllClose(expected_output, output_dataset) <del> <del> def test_ifidf_output_shape(self): <del> input_data = keras.Input(batch_size=16, shape=(4,), dtype=tf.string) <del> layer = index_lookup.IndexLookup( <del> max_tokens=2, <del> num_oov_indices=1, <del> mask_token="", <del> oov_token="[OOV]", <del> output_mode=index_lookup.TF_IDF, <del> vocabulary_dtype=tf.string, <del> vocabulary=["foo"], <del> idf_weights=[1.0]) <del> layer_output = layer(input_data) <del> self.assertAllEqual(layer_output.shape.as_list(), [16, 2]) <del> <ide> def test_int_output_file_vocab(self): <ide> vocab_data = ["earth", "wind", "and", "fire"] <ide> input_array = np.array([["earth", "wind", "and", "fire"],
2
Java
Java
fix handling of @enableloadtimeweaving autodetect
2e5f3559d3bd2f9166d3a6cde7fc4c402bc0b802
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/LoadTimeWeavingConfiguration.java <ide> public LoadTimeWeaver loadTimeWeaver() { <ide> // AJ weaving is disabled -> do nothing <ide> break; <ide> case AUTODETECT: <del> if (this.beanClassLoader.getResource(ASPECTJ_AOP_XML_RESOURCE) != null) { <add> if (this.beanClassLoader.getResource(ASPECTJ_AOP_XML_RESOURCE) == null) { <ide> // No aop.xml present on the classpath -> treat as 'disabled' <ide> break; <ide> } <ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/EnableLoadTimeWeavingTests.java <ide> <ide> package org.springframework.context.annotation; <ide> <add>import static org.easymock.EasyMock.createMock; <add>import static org.easymock.EasyMock.expectLastCall; <add>import static org.easymock.EasyMock.isA; <add>import static org.easymock.EasyMock.replay; <add> <add>import java.lang.instrument.ClassFileTransformer; <add> <ide> import org.junit.Test; <add>import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving; <ide> import org.springframework.context.support.GenericXmlApplicationContext; <ide> import org.springframework.instrument.classloading.LoadTimeWeaver; <del>import org.springframework.instrument.classloading.SimpleLoadTimeWeaver; <ide> <ide> /** <ide> * Unit tests for @EnableLoadTimeWeaving <ide> public void control() { <ide> } <ide> <ide> @Test <del> public void test() { <add> public void enableLTW_withAjWeavingDisabled() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <add> ctx.register(EnableLTWConfig_withAjWeavingDisabled.class); <add> ctx.refresh(); <add> ctx.getBean("loadTimeWeaver"); <add> } <add> <add> @Test <add> public void enableLTW_withAjWeavingAutodetect() { <ide> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <del> ctx.register(Config.class); <add> ctx.register(EnableLTWConfig_withAjWeavingAutodetect.class); <add> ctx.refresh(); <add> ctx.getBean("loadTimeWeaver"); <add> } <add> <add> @Test <add> public void enableLTW_withAjWeavingEnabled() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <add> ctx.register(EnableLTWConfig_withAjWeavingEnabled.class); <ide> ctx.refresh(); <ide> ctx.getBean("loadTimeWeaver"); <ide> } <ide> <ide> @Configuration <del> @EnableLoadTimeWeaving <del> static class Config implements LoadTimeWeavingConfigurer { <add> @EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.DISABLED) <add> static class EnableLTWConfig_withAjWeavingDisabled implements LoadTimeWeavingConfigurer { <add> public LoadTimeWeaver getLoadTimeWeaver() { <add> LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class); <add> // no expectations -> a class file transformer should NOT be added <add> replay(mockLTW); <add> return mockLTW; <add> } <add> } <ide> <add> @Configuration <add> @EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.AUTODETECT) <add> static class EnableLTWConfig_withAjWeavingAutodetect implements LoadTimeWeavingConfigurer { <add> public LoadTimeWeaver getLoadTimeWeaver() { <add> LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class); <add> // no expectations -> a class file transformer should NOT be added <add> // because no META-INF/aop.xml is present on the classpath <add> replay(mockLTW); <add> return mockLTW; <add> } <add> } <add> <add> @Configuration <add> @EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED) <add> static class EnableLTWConfig_withAjWeavingEnabled implements LoadTimeWeavingConfigurer { <ide> public LoadTimeWeaver getLoadTimeWeaver() { <del> return new SimpleLoadTimeWeaver(); <add> LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class); <add> mockLTW.addTransformer(isA(ClassFileTransformer.class)); <add> expectLastCall(); <add> replay(mockLTW); <add> return mockLTW; <ide> } <ide> } <ide> }
2
Ruby
Ruby
ignore .ds_store files when listing keg contents
8e8875f8f41d22cf03f7d14fdcd494bd9a8aef05
<ide><path>Library/Homebrew/brew.h.rb <ide> def initialize path <ide> else <ide> print_dir pn <ide> end <del> elsif not FORMULA_META_FILES.include? pn.basename.to_s <add> elsif not (FORMULA_META_FILES.include? pn.basename.to_s or pn.basename.to_s == '.DS_Store') <ide> puts pn <ide> end <ide> end <ide> def print_dir root <ide> puts pn <ide> other = 'other ' <ide> else <del> remaining_root_files << pn <add> remaining_root_files << pn unless pn.basename.to_s == '.DS_Store' <ide> end <ide> end <ide>
1
Mixed
Python
update indonesian model
81564cc4e819851e9b4473027b5fa672dbe072b6
<ide><path>.github/contributors/aongko.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [ ] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [x] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Andrew Ongko | <add>| Company name (if applicable) | Kurio | <add>| Title or role (if applicable) | Senior Data Science | <add>| Date | Sep 10, 2018 | <add>| GitHub username | aongko | <add>| Website (optional) | | <ide><path>spacy/lang/id/__init__.py <ide> from .syntax_iterators import SYNTAX_ITERATORS <ide> <ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS <add>from ..norm_exceptions import BASE_NORMS <ide> from ...language import Language <del>from ...attrs import LANG <del>from ...util import update_exc <add>from ...attrs import LANG, NORM <add>from ...util import update_exc, add_lookups <ide> <ide> <ide> class IndonesianDefaults(Language.Defaults): <ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters) <ide> lex_attr_getters[LANG] = lambda text: 'id' <ide> lex_attr_getters.update(LEX_ATTRS) <add> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], <add> BASE_NORMS, NORM_EXCEPTIONS) <ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) <ide> stop_words = STOP_WORDS <ide> prefixes = TOKENIZER_PREFIXES <ide><path>spacy/lang/id/_tokenizer_exceptions_list.py <ide> aco-acoan <ide> ad-blocker <ide> ad-interim <del>ada-ada saja <add>ada-ada <ide> ada-adanya <ide> ada-adanyakah <ide> adang-adang <ide> barik-barik <ide> baris-berbaris <ide> baru-baru <del>baru-baru ini <ide> baru-batu <ide> barung-barung <ide> basa-basi <ide> boyo-boyo <ide> buah-buahan <ide> buang-buang <del>buang-buang air <ide> buat-buatan <ide> buaya-buaya <ide> bubun-bubun <ide> degap-degap <ide> dekak-dekak <ide> dekat-dekat <del>dengan - <ide> dengar-dengaran <ide> dengking-mendengking <ide> departemen-departemen <ide> dibuat-buat <ide> diiming-imingi <ide> dilebih-lebihkan <add>dimana-mana <ide> dimata-matai <ide> dinas-dinas <ide> dinul-Islam <ide> duri-duri <ide> duta-duta <ide> dwi-kewarganegaraan <add>e-arena <add>e-billing <add>e-budgeting <add>e-cctv <add>e-class <add>e-commerce <add>e-counting <add>e-elektronik <add>e-entertainment <add>e-evolution <add>e-faktur <add>e-filing <add>e-fin <add>e-form <add>e-government <add>e-govt <add>e-hakcipta <add>e-id <add>e-info <add>e-katalog <add>e-ktp <add>e-leadership <add>e-lhkpn <add>e-library <add>e-loket <add>e-m1 <add>e-money <add>e-news <add>e-nisn <add>e-npwp <add>e-paspor <add>e-paten <add>e-pay <add>e-perda <add>e-perizinan <add>e-planning <add>e-polisi <add>e-power <add>e-punten <add>e-retribusi <add>e-samsat <add>e-sport <add>e-store <add>e-tax <add>e-ticketing <add>e-tilang <add>e-toll <add>e-visa <add>e-voting <add>e-wallet <add>e-warong <ide> ecek-ecek <ide> eco-friendly <ide> eco-park <ide> girap-girap <ide> girik-girik <ide> giring-giring <add>go-auto <add>go-bills <add>go-bluebird <add>go-box <add>go-car <add>go-clean <add>go-food <add>go-glam <add>go-jek <ide> go-kart <add>go-mart <add>go-massage <add>go-med <add>go-points <add>go-pulsa <add>go-ride <add>go-send <add>go-shop <add>go-tix <ide> go-to-market <ide> goak-goak <ide> goal-line <ide> hantu-hantu <ide> happy-happy <ide> harap-harap <del>harap-harap cemas <ide> harap-harapan <ide> hard-disk <ide> harga-harga <ide> jotos-jotosan <ide> juak-juak <ide> jual-beli <del>juang-juang !!? lenjuang <add>juang-juang <ide> julo-julo <ide> julung-julung <ide> julur-julur <ide> kemasam-masaman <ide> kemati-matian <ide> kembang-kembang <add>kemenpan-rb <ide> kementerian-kementerian <ide> kemerah-merahan <ide> kempang-kempis <ide> kercap-kercip <ide> kercap-kercup <ide> keriang-keriut <del>kering-kering air <ide> kerja-kerja <ide> kernyat-kernyut <ide> kerobak-kerabit <ide> kudap-kudap <ide> kue-kue <ide> kulah-kulah <del>kulak-kulak tangan <add>kulak-kulak <ide> kulik-kulik <ide> kulum-kulum <ide> kumat-kamit <ide> lumi-lumi <ide> luntang-lantung <ide> lupa-lupa <del>lupa-lupa ingat <ide> lupa-lupaan <ide> lurah-camat <ide> maaf-memaafkan <ide> machine-to-machine <ide> mafia-mafia <ide> mahasiswa-mahasiswi <add>mahasiswa/i <ide> mahi-mahi <ide> main-main <ide> main-mainan <ide> memanggil-manggil <ide> memanis-manis <ide> memanjut-manjut <del>memantas-mantas diri <add>memantas-mantas <ide> memasak-masak <ide> memata-matai <ide> mematah-matah <ide> mematuk-matuk <ide> mematut-matut <ide> memau-mau <del>memayah-mayahkan (diri) <add>memayah-mayahkan <ide> membaca-baca <ide> membacah-bacah <ide> membagi-bagikan <ide> merayau-rayau <ide> merayu-rayu <ide> mercak-mercik <add>mercedes-benz <ide> merek-merek <ide> mereka-mereka <ide> mereka-reka <ide> move-on <ide> muda-muda <ide> muda-mudi <add>muda/i <ide> mudah-mudahan <ide> muka-muka <del>muka-muka (dengan -) <ide> mula-mula <ide> multiple-output <ide> muluk-muluk <ide> paut-memaut <ide> pay-per-click <ide> paya-paya <add>pdi-p <ide> pecah-pecah <ide> pecat-pecatan <ide> peer-to-peer <ide> putih-putih <ide> putra-putra <ide> putra-putri <add>putra/i <ide> putri-putri <ide> putus-putus <ide> putusan-putusan <ide> sambung-menyambung <ide> sambut-menyambut <ide> samo-samo <add>sampah-sampah <ide> sampai-sampai <ide> samping-menyamping <ide> sana-sini <ide> sepala-pala <ide> sepandai-pandai <ide> sepetang-petangan <del>sepoi-sepoi (basa) <add>sepoi-sepoi <ide> sepraktis-praktisnya <ide> sepuas-puasnya <ide> serak-serak <ide> sisi-sisi <ide> siswa-siswa <ide> siswa-siswi <add>siswa/i <ide> siswi-siswi <ide> situ-situ <ide> situs-situs <ide> tanggung-menanggung <ide> tanggung-tanggung <ide> tank-tank <add>tante-tante <ide> tanya-jawab <ide> tapa-tapa <ide> tapak-tapak <ide> terambang-ambang <ide> terambung-ambung <ide> terang-terang <del>terang-terang laras <ide> terang-terangan <ide> teranggar-anggar <ide> terangguk-angguk <ide> terbada-bada <ide> terbahak-bahak <ide> terbang-terbang <del>terbang-terbang hinggap <ide> terbata-bata <ide> terbatuk-batuk <ide> terbayang-bayang <ide><path>spacy/lang/id/lemmatizer.py <ide> 'sekelap': 'kelap', <ide> 'kelap-kelip': 'terkelap', <ide> 'mengelapkan': 'lap', <del> 'sekelap': 'terkelap', <ide> 'berlapar': 'lapar', <ide> 'kelaparan': 'lapar', <ide> 'kelaparannya': 'lapar', <ide> 'terperonyok': 'peronyok', <ide> 'terperosok': 'perosok', <ide> 'terperosoknya': 'perosok', <del> 'merosot': 'perosot', <ide> 'memerosot': 'perosot', <ide> 'memerosotkan': 'perosot', <ide> 'kepustakaan': 'pustaka', <ide><path>spacy/lang/id/lex_attrs.py <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <del>from ...attrs import LIKE_NUM <add>import unicodedata <add> <add>from .punctuation import LIST_CURRENCY <add>from ...attrs import IS_CURRENCY, LIKE_NUM <ide> <ide> <ide> _num_words = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', <ide> def like_num(text): <ide> return False <ide> <ide> <add>def is_currency(text): <add> if text in LIST_CURRENCY: <add> return True <add> <add> for char in text: <add> if unicodedata.category(char) != 'Sc': <add> return False <add> return True <add> <add> <ide> LEX_ATTRS = { <add> IS_CURRENCY: is_currency, <ide> LIKE_NUM: like_num <ide> } <ide><path>spacy/lang/id/norm_exceptions.py <add>""" <add>Slang and abbreviations <add> <add>Daftar kosakata yang sering salah dieja <add>https://id.wikipedia.org/wiki/Wikipedia:Daftar_kosakata_bahasa_Indonesia_yang_sering_salah_dieja <add> <add>""" <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <del>_exc = {} <add>_exc = { <add> # Slang and abbreviations <add> "silahkan": "silakan", <add> "yg": "yang", <add> "kalo": "kalau", <add> "cawu": "caturwulan", <add> "ok": "oke", <add> "gak": "tidak", <add> "enggak": "tidak", <add> "nggak": "tidak", <add> "ndak": "tidak", <add> "ngga": "tidak", <add> "dgn": "dengan", <add> "tdk": "tidak", <add> "jg": "juga", <add> "klo": "kalau", <add> "denger": "dengar", <add> "pinter": "pintar", <add> "krn": "karena", <add> "nemuin": "menemukan", <add> "jgn": "jangan", <add> "udah": "sudah", <add> "sy": "saya", <add> "udh": "sudah", <add> "dapetin": "mendapatkan", <add> "ngelakuin": "melakukan", <add> "ngebuat": "membuat", <add> "membikin": "membuat", <add> "bikin": "buat", <add> <add> # Daftar kosakata yang sering salah dieja <add> "malpraktik": "malapraktik", <add> "malfungsi": "malafungsi", <add> "malserap": "malaserap", <add> "maladaptasi": "malaadaptasi", <add> "malsuai": "malasuai", <add> "maldistribusi": "maladistribusi", <add> "malgizi": "malagizi", <add> "malsikap": "malasikap", <add> "memperhatikan": "memerhatikan", <add> "akte": "akta", <add> "cemilan": "camilan", <add> "esei": "esai", <add> "frase": "frasa", <add> "kafeteria": "kafetaria", <add> "ketapel": "katapel", <add> "kenderaan": "kendaraan", <add> "menejemen": "manajemen", <add> "menejer": "manajer", <add> "mesjid": "masjid", <add> "rebo": "rabu", <add> "seksama": "saksama", <add> "senggama": "sanggama", <add> "sekedar": "sekadar", <add> "seprei": "seprai", <add> "semedi": "semadi", <add> "samadi": "semadi", <add> "amandemen": "amendemen", <add> "algoritma": "algoritme", <add> "aritmatika": "aritmetika", <add> "metoda": "metode", <add> "materai": "meterai", <add> "meterei": "meterai", <add> "kalendar": "kalender", <add> "kadaluwarsa": "kedaluwarsa", <add> "katagori": "kategori", <add> "parlamen": "parlemen", <add> "sekular": "sekuler", <add> "selular": "seluler", <add> "sirkular": "sirkuler", <add> "survai": "survei", <add> "survey": "survei", <add> "aktuil": "aktual", <add> "formil": "formal", <add> "trotoir": "trotoar", <add> "komersiil": "komersial", <add> "komersil": "komersial", <add> "tradisionil": "tradisionial", <add> "orisinil": "orisinal", <add> "orijinil": "orisinal", <add> "afdol": "afdal", <add> "antri": "antre", <add> "apotik": "apotek", <add> "atlit": "atlet", <add> "atmosfir": "atmosfer", <add> "cidera": "cedera", <add> "cendikiawan": "cendekiawan", <add> "cepet": "cepat", <add> "cinderamata": "cenderamata", <add> "debet": "debit", <add> "difinisi": "definisi", <add> "dekrit": "dekret", <add> "disain": "desain", <add> "diskripsi": "deskripsi", <add> "diskotik": "diskotek", <add> "eksim": "eksem", <add> "exim": "eksem", <add> "faidah": "faedah", <add> "ekstrim": "ekstrem", <add> "ekstrimis": "ekstremis", <add> "komplit": "komplet", <add> "konkrit": "konkret", <add> "kongkrit": "konkret", <add> "kongkret": "konkret", <add> "kridit": "kredit", <add> "musium": "museum", <add> "pinalti": "penalti", <add> "piranti": "peranti", <add> "pinsil": "pensil", <add> "personil": "personel", <add> "sistim": "sistem", <add> "teoritis": "teoretis", <add> "vidio": "video", <add> "cengkeh": "cengkih", <add> "desertasi": "disertasi", <add> "hakekat": "hakikat", <add> "intelejen": "intelijen", <add> "kaedah": "kaidah", <add> "kempes": "kempis", <add> "kementrian": "kementerian", <add> "ledeng": "leding", <add> "nasehat": "nasihat", <add> "penasehat": "penasihat", <add> "praktek": "praktik", <add> "praktekum": "praktikum", <add> "resiko": "risiko", <add> "retsleting": "ritsleting", <add> "senen": "senin", <add> "amuba": "ameba", <add> "punggawa": "penggawa", <add> "surban": "serban", <add> "nomer": "nomor", <add> "sorban": "serban", <add> "bis": "bus", <add> "agribisnis": "agrobisnis", <add> "kantung": "kantong", <add> "khutbah": "khotbah", <add> "mandur": "mandor", <add> "rubuh": "roboh", <add> "pastur": "pastor", <add> "supir": "sopir", <add> "goncang": "guncang", <add> "goa": "gua", <add> "kaos": "kaus", <add> "kokoh": "kukuh", <add> "komulatif": "kumulatif", <add> "kolomnis": "kolumnis", <add> "korma": "kurma", <add> "lobang": "lubang", <add> "limo": "limusin", <add> "limosin": "limusin", <add> "mangkok": "mangkuk", <add> "saos": "saus", <add> "sop": "sup", <add> "sorga": "surga", <add> "tegor": "tegur", <add> "telor": "telur", <add> "obrak-abrik": "ubrak-abrik", <add> "ekwivalen": "ekuivalen", <add> "frekwensi": "frekuensi", <add> "konsekwensi": "konsekuensi", <add> "kwadran": "kuadran", <add> "kwadrat": "kuadrat", <add> "kwalifikasi": "kualifikasi", <add> "kwalitas": "kualitas", <add> "kwalitet": "kualitas", <add> "kwalitatif": "kualitatif", <add> "kwantitas": "kuantitas", <add> "kwantitatif": "kuantitatif", <add> "kwantum": "kuantum", <add> "kwartal": "kuartal", <add> "kwintal": "kuintal", <add> "kwitansi": "kuitansi", <add> "kwatir": "khawatir", <add> "kuatir": "khawatir", <add> "jadual": "jadwal", <add> "hirarki": "hierarki", <add> "karir": "karier", <add> "aktip": "aktif", <add> "daptar": "daftar", <add> "efektip": "efektif", <add> "epektif": "efektif", <add> "epektip": "efektif", <add> "Pebruari": "Februari", <add> "pisik": "fisik", <add> "pondasi": "fondasi", <add> "photo": "foto", <add> "photokopi": "fotokopi", <add> "hapal": "hafal", <add> "insap": "insaf", <add> "insyaf": "insaf", <add> "konperensi": "konferensi", <add> "kreatip": "kreatif", <add> "kreativ": "kreatif", <add> "maap": "maaf", <add> "napsu": "nafsu", <add> "negatip": "negatif", <add> "negativ": "negatif", <add> "objektip": "objektif", <add> "obyektip": "objektif", <add> "obyektif": "objektif", <add> "pasip": "pasif", <add> "pasiv": "pasif", <add> "positip": "positif", <add> "positiv": "positif", <add> "produktip": "produktif", <add> "produktiv": "produktif", <add> "sarap": "saraf", <add> "sertipikat": "sertifikat", <add> "subjektip": "subjektif", <add> "subyektip": "subjektif", <add> "subyektif": "subjektif", <add> "tarip": "tarif", <add> "transitip": "transitif", <add> "transitiv": "transitif", <add> "faham": "paham", <add> "fikir": "pikir", <add> "berfikir": "berpikir", <add> "telefon": "telepon", <add> "telfon": "telepon", <add> "telpon": "telepon", <add> "tilpon": "telepon", <add> "nafas": "napas", <add> "bernafas": "bernapas", <add> "pernafasan": "pernapasan", <add> "vermak": "permak", <add> "vulpen": "pulpen", <add> "aktifis": "aktivis", <add> "konfeksi": "konveksi", <add> "motifasi": "motivasi", <add> "Nopember": "November", <add> "propinsi": "provinsi", <add> "babtis": "baptis", <add> "jerembab": "jerembap", <add> "lembab": "lembap", <add> "sembab": "sembap", <add> "saptu": "sabtu", <add> "tekat": "tekad", <add> "bejad": "bejat", <add> "nekad": "nekat", <add> "otoped": "otopet", <add> "skuad": "skuat", <add> "jenius": "genius", <add> "marjin": "margin", <add> "marjinal": "marginal", <add> "obyek": "objek", <add> "subyek": "subjek", <add> "projek": "proyek", <add> "azas": "asas", <add> "ijasah": "ijazah", <add> "jenasah": "jenazah", <add> "plasa": "plaza", <add> "bathin": "batin", <add> "Katholik": "Katolik", <add> "orthografi": "ortografi", <add> "pathogen": "patogen", <add> "theologi": "teologi", <add> "ijin": "izin", <add> "rejeki": "rezeki", <add> "rejim": "rezim", <add> "jaman": "zaman", <add> "jamrud": "zamrud", <add> "jinah": "zina", <add> "perjinahan": "perzinaan", <add> "anugrah": "anugerah", <add> "cendrawasih": "cenderawasih", <add> "jendral": "jenderal", <add> "kripik": "keripik", <add> "krupuk": "kerupuk", <add> "ksatria": "kesatria", <add> "mentri": "menteri", <add> "negri": "negeri", <add> "Prancis": "Perancis", <add> "sebrang": "seberang", <add> "menyebrang": "menyeberang", <add> "Sumatra": "Sumatera", <add> "trampil": "terampil", <add> "isteri": "istri", <add> "justeru": "justru", <add> "perajurit": "prajurit", <add> "putera": "putra", <add> "puteri": "putri", <add> "samudera": "samudra", <add> "sastera": "sastra", <add> "sutera": "sutra", <add> "terompet": "trompet", <add> "iklas": "ikhlas", <add> "iktisar": "ikhtisar", <add> "kafilah": "khafilah", <add> "kawatir": "khawatir", <add> "kotbah": "khotbah", <add> "kusyuk": "khusyuk", <add> "makluk": "makhluk", <add> "mahluk": "makhluk", <add> "mahkluk": "makhluk", <add> "nahkoda": "nakhoda", <add> "nakoda": "nakhoda", <add> "tahta": "takhta", <add> "takhyul": "takhayul", <add> "tahyul": "takhayul", <add> "tahayul": "takhayul", <add> "akhli": "ahli", <add> "anarkhi": "anarki", <add> "kharisma": "karisma", <add> "kharismatik": "karismatik", <add> "mahsud": "maksud", <add> "makhsud": "maksud", <add> "rakhmat": "rahmat", <add> "tekhnik": "teknik", <add> "tehnik": "teknik", <add> "tehnologi": "teknologi", <add> "ikhwal": "ihwal", <add> "expor": "ekspor", <add> "extra": "ekstra", <add> "komplex": "komplek", <add> "sex": "seks", <add> "taxi": "taksi", <add> "extasi": "ekstasi", <add> "syaraf": "saraf", <add> "syurga": "surga", <add> "mashur": "masyhur", <add> "masyur": "masyhur", <add> "mahsyur": "masyhur", <add> "mashyur": "masyhur", <add> "muadzin": "muazin", <add> "adzan": "azan", <add> "ustadz": "ustaz", <add> "ustad": "ustaz", <add> "ustadzah": "ustaz", <add> "dzikir": "zikir", <add> "dzuhur": "zuhur", <add> "dhuhur": "zuhur", <add> "zhuhur": "zuhur", <add> "analisa": "analisis", <add> "diagnosa": "diagnosis", <add> "hipotesa": "hipotesis", <add> "sintesa": "sintesis", <add> "aktiviti": "aktivitas", <add> "aktifitas": "aktivitas", <add> "efektifitas": "efektivitas", <add> "komuniti": "komunitas", <add> "kreatifitas": "kreativitas", <add> "produktifitas": "produktivitas", <add> "realiti": "realitas", <add> "realita": "realitas", <add> "selebriti": "selebritas", <add> "spotifitas": "sportivitas", <add> "universiti": "universitas", <add> "utiliti": "utilitas", <add> "validiti": "validitas", <add> "dilokalisir": "dilokalisasi", <add> "didramatisir": "didramatisasi", <add> "dipolitisir": "dipolitisasi", <add> "dinetralisir": "dinetralisasi", <add> "dikonfrontir": "dikonfrontasi", <add> "mendominir": "mendominasi", <add> "koordinir": "koordinasi", <add> "proklamir": "proklamasi", <add> "terorganisir": "terorganisasi", <add> "terealisir": "terealisasi", <add> "robah": "ubah", <add> "dirubah": "diubah", <add> "merubah": "mengubah", <add> "terlanjur": "telanjur", <add> "terlantar": "telantar", <add> "penglepasan": "pelepasan", <add> "pelihatan": "penglihatan", <add> "pemukiman": "permukiman", <add> "pengrumahan": "perumahan", <add> "penyewaan": "persewaan", <add> "menyintai": "mencintai", <add> "menyolok": "mencolok", <add> "contek": "sontek", <add> "mencontek": "menyontek", <add> "pungkir": "mungkir", <add> "dipungkiri": "dimungkiri", <add> "kupungkiri": "kumungkiri", <add> "kaupungkiri": "kaumungkiri", <add> "nampak": "tampak", <add> "nampaknya": "tampaknya", <add> "nongkrong": "tongkrong", <add> "berternak": "beternak", <add> "berterbangan": "beterbangan", <add> "berserta": "beserta", <add> "berperkara": "beperkara", <add> "berpergian": "bepergian", <add> "berkerja": "bekerja", <add> "berberapa": "beberapa", <add> "terbersit": "tebersit", <add> "terpercaya": "tepercaya", <add> "terperdaya": "teperdaya", <add> "terpercik": "tepercik", <add> "terpergok": "tepergok", <add> "aksesoris": "aksesori", <add> "handal": "andal", <add> "hantar": "antar", <add> "panutan": "anutan", <add> "atsiri": "asiri", <add> "bhakti": "bakti", <add> "china": "cina", <add> "dharma": "darma", <add> "diktaktor": "diktator", <add> "eksport": "ekspor", <add> "hembus": "embus", <add> "hadits": "hadis", <add> "hadist": "hadits", <add> "harafiah": "harfiah", <add> "himbau": "imbau", <add> "import": "impor", <add> "inget": "ingat", <add> "hisap": "isap", <add> "interprestasi": "interpretasi", <add> "kangker": "kanker", <add> "konggres": "kongres", <add> "lansekap": "lanskap", <add> "maghrib": "magrib", <add> "emak": "mak", <add> "moderen": "modern", <add> "pasport": "paspor", <add> "perduli": "peduli", <add> "ramadhan": "ramadan", <add> "rapih": "rapi", <add> "Sansekerta": "Sanskerta", <add> "shalat": "salat", <add> "sholat": "salat", <add> "silahkan": "silakan", <add> "standard": "standar", <add> "hutang": "utang", <add> "zinah": "zina", <add> "ambulan": "ambulans", <add> "antartika": "sntarktika", <add> "arteri": "arteria", <add> "asik": "asyik", <add> "australi": "australia", <add> "denga": "dengan", <add> "depo": "depot", <add> "detil": "detail", <add> "ensiklopedi": "ensiklopedia", <add> "elit": "elite", <add> "frustasi": "frustrasi", <add> "gladi": "geladi", <add> "greget": "gereget", <add> "itali": "italia", <add> "karna": "karena", <add> "klenteng": "kelenteng", <add> "erling": "kerling", <add> "kontruksi": "konstruksi", <add> "masal": "massal", <add> "merk": "merek", <add> "respon": "respons", <add> "diresponi": "direspons", <add> "skak": "sekak", <add> "stir": "setir", <add> "singapur": "singapura", <add> "standarisasi": "standardisasi", <add> "varitas": "varietas", <add> "amphibi": "amfibi", <add> "anjlog": "anjlok", <add> "alpukat": "avokad", <add> "alpokat": "avokad", <add> "bolpen": "pulpen", <add> "cabe": "cabai", <add> "cabay": "cabai", <add> "ceret": "cerek", <add> "differensial": "diferensial", <add> "duren": "durian", <add> "faksimili": "faksimile", <add> "faksimil": "faksimile", <add> "graha": "gerha", <add> "goblog": "goblok", <add> "gombrong": "gombroh", <add> "horden": "gorden", <add> "korden": "gorden", <add> "gubug": "gubuk", <add> "imaginasi": "imajinasi", <add> "jerigen": "jeriken", <add> "jirigen": "jeriken", <add> "carut-marut": "karut-marut", <add> "kwota": "kuota", <add> "mahzab": "mazhab", <add> "mempesona": "memesona", <add> "milyar": "miliar", <add> "missi": "misi", <add> "nenas": "nanas", <add> "negoisasi": "negosiasi", <add> "automotif": "otomotif", <add> "pararel": "paralel", <add> "paska": "pasca", <add> "prosen": "persen", <add> "pete": "petai", <add> "petay": "petai", <add> "proffesor": "profesor", <add> "rame": "ramai", <add> "rapot": "rapor", <add> "rileks": "relaks", <add> "rileksasi": "relaksasi", <add> "renumerasi": "remunerasi", <add> "seketaris": "sekretaris", <add> "sekertaris": "sekretaris", <add> "sensorik": "sensoris", <add> "sentausa": "sentosa", <add> "strawberi": "stroberi", <add> "strawbery": "stroberi", <add> "taqwa": "takwa", <add> "tauco": "taoco", <add> "tauge": "taoge", <add> "toge": "taoge", <add> "tauladan": "teladan", <add> "taubat": "tobat", <add> "trilyun": "triliun", <add> "vissi": "visi", <add> "coklat": "cokelat", <add> "narkotika": "narkotik", <add> "oase": "oasis", <add> "politisi": "politikus", <add> "terong": "terung", <add> "wool": "wol", <add> "himpit": "impit", <add> "mujizat": "mukjizat", <add> "mujijat": "mukjizat", <add> "yag": "yang", <add>} <ide> <ide> NORM_EXCEPTIONS = {} <ide> <ide><path>spacy/lang/id/punctuation.py <ide> from ..punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES, TOKENIZER_INFIXES <ide> from ..char_classes import merge_chars, split_chars, _currency, _units <ide> from ..char_classes import LIST_PUNCT, LIST_ELLIPSES, LIST_QUOTES <del>from ..char_classes import QUOTES, UNITS, ALPHA, ALPHA_LOWER, ALPHA_UPPER, HYPHENS <add>from ..char_classes import QUOTES, ALPHA, ALPHA_LOWER, ALPHA_UPPER, HYPHENS <ide> <ide> _units = (_units + 's bit Gbps Mbps mbps Kbps kbps ƒ ppi px ' <ide> 'Hz kHz MHz GHz mAh ' <ide> MONTHS = merge_chars(_months) <ide> LIST_CURRENCY = split_chars(_currency) <ide> <del>TOKENIZER_PREFIXES.remove('#') # hashtag <add>TOKENIZER_PREFIXES.remove('#') # hashtag <ide> _prefixes = TOKENIZER_PREFIXES + LIST_CURRENCY + [HTML_PREFIX] + ['/', '—'] <ide> <ide> _suffixes = TOKENIZER_SUFFIXES + [r'\-[Nn]ya', '-[KkMm]u', '[—-]'] + [ <ide><path>spacy/lang/id/stop_words.py <add>""" <add>List of stop words in Bahasa Indonesia. <add>""" <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <ide> STOP_WORDS = set(""" <del>ada <del>adalah <del>adanya <del>adapun <del>agak <del>agaknya <del>agar <del>akan <del>akankah <del>akhir <del>akhiri <del>akhirnya <del>aku <del>akulah <del>amat <del>amatlah <del>anda <del>andalah <del>antar <del>antara <del>antaranya <del>apa <del>apaan <del>apabila <del>apakah <del>apalagi <del>apatah <del>artinya <del>asal <del>asalkan <del>atas <del>atau <del>ataukah <del>ataupun <del>awal <add>ada adalah adanya adapun agak agaknya agar akan akankah akhir akhiri akhirnya <add>aku akulah amat amatlah anda andalah antar antara antaranya apa apaan apabila <add>apakah apalagi apatah artinya asal asalkan atas atau ataukah ataupun awal <ide> awalnya <del>bagai <del>bagaikan <del>bagaimana <del>bagaimanakah <del>bagaimanapun <del>bagi <del>bagian <del>bahkan <del>bahwa <del>bahwasanya <del>baik <del>bakal <del>bakalan <del>balik <del>banyak <del>bapak <del>baru <del>bawah <del>beberapa <del>begini <del>beginian <del>beginikah <del>beginilah <del>begitu <del>begitukah <del>begitulah <del>begitupun <del>bekerja <del>belakang <del>belakangan <del>belum <del>belumlah <del>benar <del>benarkah <del>benarlah <del>berada <del>berakhir <del>berakhirlah <del>berakhirnya <del>berapa <del>berapakah <del>berapalah <del>berapapun <del>berarti <del>berawal <del>berbagai <del>berdatangan <del>beri <del>berikan <del>berikut <del>berikutnya <del>berjumlah <del>berkali-kali <del>berkata <del>berkehendak <del>berkeinginan <del>berkenaan <del>berlainan <del>berlalu <del>berlangsung <del>berlebihan <del>bermacam <del>bermacam-macam <del>bermaksud <del>bermula <del>bersama <del>bersama-sama <del>bersiap <del>bersiap-siap <del>bertanya <del>bertanya-tanya <del>berturut <del>berturut-turut <del>bertutur <del>berujar <del>berupa <del>besar <del>betul <del>betulkah <del>biasa <del>biasanya <del>bila <del>bilakah <del>bisa <del>bisakah <del>boleh <del>bolehkah <del>bolehlah <del>buat <del>bukan <del>bukankah <del>bukanlah <del>bukannya <del>bulan <del>bung <del>cara <del>caranya <del>cukup <del>cukupkah <del>cukuplah <del>cuma <del>dahulu <del>dalam <del>dan <del>dapat <del>dari <del>daripada <del>datang <del>dekat <del>demi <del>demikian <del>demikianlah <del>dengan <del>depan <del>di <del>dia <del>diakhiri <del>diakhirinya <del>dialah <del>diantara <del>diantaranya <del>diberi <del>diberikan <del>diberikannya <del>dibuat <del>dibuatnya <del>didapat <del>didatangkan <del>digunakan <del>diibaratkan <del>diibaratkannya <del>diingat <del>diingatkan <del>diinginkan <del>dijawab <del>dijelaskan <del>dijelaskannya <del>dikarenakan <del>dikatakan <del>dikatakannya <del>dikerjakan <del>diketahui <del>diketahuinya <del>dikira <del>dilakukan <del>dilalui <del>dilihat <del>dimaksud <del>dimaksudkan <del>dimaksudkannya <del>dimaksudnya <del>diminta <del>dimintai <del>dimisalkan <del>dimulai <del>dimulailah <del>dimulainya <del>dimungkinkan <del>dini <del>dipastikan <del>diperbuat <del>diperbuatnya <del>dipergunakan <del>diperkirakan <del>diperlihatkan <del>diperlukan <del>diperlukannya <del>dipersoalkan <del>dipertanyakan <del>dipunyai <del>diri <del>dirinya <del>disampaikan <del>disebut <del>disebutkan <del>disebutkannya <del>disini <del>disinilah <del>ditambahkan <del>ditandaskan <del>ditanya <del>ditanyai <del>ditanyakan <del>ditegaskan <del>ditujukan <del>ditunjuk <del>ditunjuki <del>ditunjukkan <del>ditunjukkannya <del>ditunjuknya <del>dituturkan <del>dituturkannya <del>diucapkan <del>diucapkannya <del>diungkapkan <del>dong <del>dua <del>dulu <del>empat <del>enggak <del>enggaknya <del>entah <del>entahlah <del>guna <del>gunakan <del>hal <del>hampir <del>hanya <del>hanyalah <del>hari <del>harus <del>haruslah <del>harusnya <del>hendak <del>hendaklah <del>hendaknya <del>hingga <del>ia <del>ialah <del>ibarat <del>ibaratkan <del>ibaratnya <del>ibu <del>ikut <del>ingat <del>ingat-ingat <del>ingin <del>inginkah <del>inginkan <del>ini <del>inikah <del>inilah <del>itu <del>itukah <del>itulah <del>jadi <del>jadilah <del>jadinya <del>jangan <del>jangankan <del>janganlah <del>jauh <del>jawab <del>jawaban <del>jawabnya <del>jelas <del>jelaskan <del>jelaslah <del>jelasnya <del>jika <del>jikalau <del>juga <del>jumlah <del>jumlahnya <del>justru <del>kala <del>kalau <del>kalaulah <del>kalaupun <del>kalian <del>kami <del>kamilah <del>kamu <del>kamulah <del>kan <del>kapan <del>kapankah <del>kapanpun <del>karena <del>karenanya <del>kasus <del>kata <del>katakan <del>katakanlah <del>katanya <del>ke <del>keadaan <del>kebetulan <del>kecil <del>kedua <del>keduanya <del>keinginan <del>kelamaan <del>kelihatan <del>kelihatannya <del>kelima <del>keluar <del>kembali <del>kemudian <del>kemungkinan <del>kemungkinannya <del>kenapa <del>kepada <del>kepadanya <del>kesampaian <del>keseluruhan <del>keseluruhannya <del>keterlaluan <del>ketika <del>khususnya <del>kini <del>kinilah <del>kira <del>kira-kira <del>kiranya <del>kita <del>kitalah <del>kok <del>kurang <del>lagi <del>lagian <del>lah <del>lain <del>lainnya <del>lalu <del>lama <del>lamanya <del>lanjut <del>lanjutnya <del>lebih <del>lewat <del>lima <del>luar <del>macam <del>maka <del>makanya <del>makin <del>malah <del>malahan <del>mampu <del>mampukah <del>mana <del>manakala <del>manalagi <del>masa <del>masalah <del>masalahnya <del>masih <del>masihkah <del>masing <del>masing-masing <del>mau <del>maupun <del>melainkan <del>melakukan <del>melalui <del>melihat <del>melihatnya <del>memang <del>memastikan <del>memberi <del>memberikan <del>membuat <del>memerlukan <del>memihak <del>meminta <del>memintakan <del>memisalkan <del>memperbuat <del>mempergunakan <del>memperkirakan <del>memperlihatkan <del>mempersiapkan <del>mempersoalkan <del>mempertanyakan <del>mempunyai <del>memulai <del>memungkinkan <del>menaiki <del>menambahkan <del>menandaskan <del>menanti <del>menanti-nanti <del>menantikan <del>menanya <del>menanyai <del>menanyakan <del>mendapat <del>mendapatkan <del>mendatang <del>mendatangi <del>mendatangkan <del>menegaskan <del>mengakhiri <del>mengapa <del>mengatakan <del>mengatakannya <del>mengenai <del>mengerjakan <del>mengetahui <del>menggunakan <del>menghendaki <del>mengibaratkan <del>mengibaratkannya <del>mengingat <del>mengingatkan <del>menginginkan <del>mengira <del>mengucapkan <del>mengucapkannya <del>mengungkapkan <del>menjadi <del>menjawab <del>menjelaskan <del>menuju <del>menunjuk <del>menunjuki <del>menunjukkan <del>menunjuknya <del>menurut <del>menuturkan <del>menyampaikan <del>menyangkut <del>menyatakan <del>menyebutkan <del>menyeluruh <del>menyiapkan <del>merasa <del>mereka <del>merekalah <del>merupakan <del>meski <del>meskipun <del>meyakini <del>meyakinkan <del>minta <del>mirip <del>misal <del>misalkan <del>misalnya <del>mula <del>mulai <del>mulailah <del>mulanya <del>mungkin <del>mungkinkah <del>nah <del>naik <del>namun <del>nanti <del>nantinya <del>nyaris <del>nyatanya <del>oleh <del>olehnya <del>pada <del>padahal <del>padanya <del>pak <del>paling <del>panjang <del>pantas <del>para <del>pasti <del>pastilah <del>penting <del>pentingnya <del>per <del>percuma <del>perlu <del>perlukah <del>perlunya <del>pernah <del>persoalan <del>pertama <del>pertama-tama <del>pertanyaan <del>pertanyakan <del>pihak <del>pihaknya <del>pukul <del>pula <del>pun <del>punya <del>rasa <del>rasanya <del>rata <del>rupanya <del>saat <del>saatnya <del>saja <del>sajalah <del>saling <del>sama <del>sama-sama <del>sambil <del>sampai <del>sampai-sampai <del>sampaikan <del>sana <del>sangat <del>sangatlah <del>satu <del>saya <del>sayalah <del>se <del>sebab <del>sebabnya <del>sebagai <del>sebagaimana <del>sebagainya <del>sebagian <del>sebaik <del>sebaik-baiknya <del>sebaiknya <del>sebaliknya <del>sebanyak <del>sebegini <del>sebegitu <del>sebelum <del>sebelumnya <del>sebenarnya <del>seberapa <del>sebesar <del>sebetulnya <del>sebisanya <del>sebuah <del>sebut <del>sebutlah <del>sebutnya <del>secara <del>secukupnya <del>sedang <del>sedangkan <del>sedemikian <del>sedikit <del>sedikitnya <del>seenaknya <del>segala <del>segalanya <del>segera <del>seharusnya <del>sehingga <del>seingat <del>sejak <del>sejauh <del>sejenak <del>sejumlah <del>sekadar <del>sekadarnya <del>sekali <del>sekali-kali <del>sekalian <del>sekaligus <del>sekalipun <del>sekarang <del>sekarang <del>sekecil <del>seketika <del>sekiranya <del>sekitar <del>sekitarnya <del>sekurang-kurangnya <del>sekurangnya <del>sela <del>selain <del>selaku <del>selalu <del>selama <del>selama-lamanya <del>selamanya <del>selanjutnya <del>seluruh <del>seluruhnya <del>semacam <del>semakin <del>semampu <del>semampunya <del>semasa <del>semasih <del>semata <del>semata-mata <del>semaunya <del>sementara <del>semisal <del>semisalnya <del>sempat <del>semua <del>semuanya <del>semula <del>sendiri <del>sendirian <del>sendirinya <del>seolah <del>seolah-olah <del>seorang <del>sepanjang <del>sepantasnya <del>sepantasnyalah <del>seperlunya <del>seperti <del>sepertinya <del>sepihak <del>sering <del>seringnya <del>serta <del>serupa <del>sesaat <del>sesama <del>sesampai <del>sesegera <del>sesekali <del>seseorang <del>sesuatu <del>sesuatunya <del>sesudah <del>sesudahnya <del>setelah <del>setempat <del>setengah <del>seterusnya <del>setiap <del>setiba <del>setibanya <del>setidak-tidaknya <del>setidaknya <del>setinggi <del>seusai <del>sewaktu <del>siap <del>siapa <del>siapakah <del>siapapun <del>sini <del>sinilah <del>soal <del>soalnya <del>suatu <del>sudah <del>sudahkah <del>sudahlah <del>supaya <del>tadi <del>tadinya <del>tahu <del>tahun <del>tak <del>tambah <del>tambahnya <del>tampak <del>tampaknya <del>tandas <del>tandasnya <del>tanpa <del>tanya <del>tanyakan <del>tanyanya <del>tapi <del>tegas <del>tegasnya <del>telah <del>tempat <del>tengah <del>tentang <del>tentu <del>tentulah <del>tentunya <del>tepat <del>terakhir <del>terasa <del>terbanyak <del>terdahulu <del>terdapat <del>terdiri <del>terhadap <del>terhadapnya <del>teringat <del>teringat-ingat <del>terjadi <del>terjadilah <del>terjadinya <del>terkira <del>terlalu <del>terlebih <del>terlihat <del>termasuk <del>ternyata <del>tersampaikan <del>tersebut <del>tersebutlah <del>tertentu <del>tertuju <del>terus <del>terutama <del>tetap <del>tetapi <del>tiap <del>tiba <del>tiba-tiba <del>tidak <del>tidakkah <del>tidaklah <del>tiga <del>tinggi <del>toh <del>tunjuk <del>turut <del>tutur <del>tuturnya <del>ucap <del>ucapnya <del>ujar <del>ujarnya <del>umum <del>umumnya <del>ungkap <del>ungkapnya <del>untuk <del>usah <del>usai <del>waduh <del>wah <del>wahai <del>waktu <del>waktunya <del>walau <del>walaupun <del>wong <del>yaitu <del>yakin <del>yakni <del>yang <del>""".split()) <ide>\ No newline at end of file <add> <add>bagai bagaikan bagaimana bagaimanakah bagaimanapun bagi bagian bahkan bahwa <add>bahwasanya baik bakal bakalan balik banyak bapak baru bawah beberapa begini <add>beginian beginikah beginilah begitu begitukah begitulah begitupun bekerja <add>belakang belakangan belum belumlah benar benarkah benarlah berada berakhir <add>berakhirlah berakhirnya berapa berapakah berapalah berapapun berarti berawal <add>berbagai berdatangan beri berikan berikut berikutnya berjumlah berkali-kali <add>berkata berkehendak berkeinginan berkenaan berlainan berlalu berlangsung <add>berlebihan bermacam bermacam-macam bermaksud bermula bersama bersama-sama <add>bersiap bersiap-siap bertanya bertanya-tanya berturut berturut-turut bertutur <add>berujar berupa besar betul betulkah biasa biasanya bila bilakah bisa bisakah <add>boleh bolehkah bolehlah buat bukan bukankah bukanlah bukannya bulan bung <add> <add>cara caranya cukup cukupkah cukuplah cuma <add> <add>dahulu dalam dan dapat dari daripada datang dekat demi demikian demikianlah <add>dengan depan di dia diakhiri diakhirinya dialah diantara diantaranya diberi <add>diberikan diberikannya dibuat dibuatnya didapat didatangkan digunakan <add>diibaratkan diibaratkannya diingat diingatkan diinginkan dijawab dijelaskan <add>dijelaskannya dikarenakan dikatakan dikatakannya dikerjakan diketahui <add>diketahuinya dikira dilakukan dilalui dilihat dimaksud dimaksudkan <add>dimaksudkannya dimaksudnya diminta dimintai dimisalkan dimulai dimulailah <add>dimulainya dimungkinkan dini dipastikan diperbuat diperbuatnya dipergunakan <add>diperkirakan diperlihatkan diperlukan diperlukannya dipersoalkan dipertanyakan <add>dipunyai diri dirinya disampaikan disebut disebutkan disebutkannya disini <add>disinilah ditambahkan ditandaskan ditanya ditanyai ditanyakan ditegaskan <add>ditujukan ditunjuk ditunjuki ditunjukkan ditunjukkannya ditunjuknya dituturkan <add>dituturkannya diucapkan diucapkannya diungkapkan dong dua dulu <add> <add>empat enggak enggaknya entah entahlah <add> <add>guna gunakan <add> <add>hal hampir hanya hanyalah hari harus haruslah harusnya hendak hendaklah <add>hendaknya hingga <add> <add>ia ialah ibarat ibaratkan ibaratnya ibu ikut ingat ingat-ingat ingin inginkah <add>inginkan ini inikah inilah itu itukah itulah <add> <add>jadi jadilah jadinya jangan jangankan janganlah jauh jawab jawaban jawabnya <add>jelas jelaskan jelaslah jelasnya jika jikalau juga jumlah jumlahnya justru <add> <add>kala kalau kalaulah kalaupun kalian kami kamilah kamu kamulah kan kapan <add>kapankah kapanpun karena karenanya kasus kata katakan katakanlah katanya ke <add>keadaan kebetulan kecil kedua keduanya keinginan kelamaan kelihatan <add>kelihatannya kelima keluar kembali kemudian kemungkinan kemungkinannya kenapa <add>kepada kepadanya kesampaian keseluruhan keseluruhannya keterlaluan ketika <add>khususnya kini kinilah kira kira-kira kiranya kita kitalah kok kurang <add> <add>lagi lagian lah lain lainnya lalu lama lamanya lanjut lanjutnya lebih lewat <add>lima luar <add> <add>macam maka makanya makin malah malahan mampu mampukah mana manakala manalagi <add>masa masalah masalahnya masih masihkah masing masing-masing mau maupun <add>melainkan melakukan melalui melihat melihatnya memang memastikan memberi <add>memberikan membuat memerlukan memihak meminta memintakan memisalkan memperbuat <add>mempergunakan memperkirakan memperlihatkan mempersiapkan mempersoalkan <add>mempertanyakan mempunyai memulai memungkinkan menaiki menambahkan menandaskan <add>menanti menanti-nanti menantikan menanya menanyai menanyakan mendapat <add>mendapatkan mendatang mendatangi mendatangkan menegaskan mengakhiri mengapa <add>mengatakan mengatakannya mengenai mengerjakan mengetahui menggunakan <add>menghendaki mengibaratkan mengibaratkannya mengingat mengingatkan menginginkan <add>mengira mengucapkan mengucapkannya mengungkapkan menjadi menjawab menjelaskan <add>menuju menunjuk menunjuki menunjukkan menunjuknya menurut menuturkan <add>menyampaikan menyangkut menyatakan menyebutkan menyeluruh menyiapkan merasa <add>mereka merekalah merupakan meski meskipun meyakini meyakinkan minta mirip <add>misal misalkan misalnya mula mulai mulailah mulanya mungkin mungkinkah <add> <add>nah naik namun nanti nantinya nyaris nyatanya <add> <add>oleh olehnya <add> <add>pada padahal padanya pak paling panjang pantas para pasti pastilah penting <add>pentingnya per percuma perlu perlukah perlunya pernah persoalan pertama <add>pertama-tama pertanyaan pertanyakan pihak pihaknya pukul pula pun punya <add> <add>rasa rasanya rata rupanya <add> <add>saat saatnya saja sajalah saling sama sama-sama sambil sampai sampai-sampai <add>sampaikan sana sangat sangatlah satu saya sayalah se sebab sebabnya sebagai <add>sebagaimana sebagainya sebagian sebaik sebaik-baiknya sebaiknya sebaliknya <add>sebanyak sebegini sebegitu sebelum sebelumnya sebenarnya seberapa sebesar <add>sebetulnya sebisanya sebuah sebut sebutlah sebutnya secara secukupnya sedang <add>sedangkan sedemikian sedikit sedikitnya seenaknya segala segalanya segera <add>seharusnya sehingga seingat sejak sejauh sejenak sejumlah sekadar sekadarnya <add>sekali sekali-kali sekalian sekaligus sekalipun sekarang sekarang sekecil <add>seketika sekiranya sekitar sekitarnya sekurang-kurangnya sekurangnya sela <add>selain selaku selalu selama selama-lamanya selamanya selanjutnya seluruh <add>seluruhnya semacam semakin semampu semampunya semasa semasih semata semata-mata <add>semaunya sementara semisal semisalnya sempat semua semuanya semula sendiri <add>sendirian sendirinya seolah seolah-olah seorang sepanjang sepantasnya <add>sepantasnyalah seperlunya seperti sepertinya sepihak sering seringnya serta <add>serupa sesaat sesama sesampai sesegera sesekali seseorang sesuatu sesuatunya <add>sesudah sesudahnya setelah setempat setengah seterusnya setiap setiba setibanya <add>setidak-tidaknya setidaknya setinggi seusai sewaktu siap siapa siapakah <add>siapapun sini sinilah soal soalnya suatu sudah sudahkah sudahlah supaya <add> <add>tadi tadinya tahu tahun tak tambah tambahnya tampak tampaknya tandas tandasnya <add>tanpa tanya tanyakan tanyanya tapi tegas tegasnya telah tempat tengah tentang <add>tentu tentulah tentunya tepat terakhir terasa terbanyak terdahulu terdapat <add>terdiri terhadap terhadapnya teringat teringat-ingat terjadi terjadilah <add>terjadinya terkira terlalu terlebih terlihat termasuk ternyata tersampaikan <add>tersebut tersebutlah tertentu tertuju terus terutama tetap tetapi tiap tiba <add>tiba-tiba tidak tidakkah tidaklah tiga tinggi toh tunjuk turut tutur tuturnya <add> <add>ucap ucapnya ujar ujarnya umum umumnya ungkap ungkapnya untuk usah usai <add> <add>waduh wah wahai waktu waktunya walau walaupun wong <add> <add>yaitu yakin yakni yang <add>""".split()) <ide><path>spacy/lang/id/tokenizer_exceptions.py <add>""" <add>Daftar singkatan dan Akronim dari: <add>https://id.wiktionary.org/wiki/Wiktionary:Daftar_singkatan_dan_akronim_bahasa_Indonesia#A <add>""" <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <del>import regex as re <del> <ide> from ._tokenizer_exceptions_list import ID_BASE_EXCEPTIONS <del>from ..tokenizer_exceptions import URL_PATTERN <ide> from ...symbols import ORTH, LEMMA, NORM <ide> <ide> <ide> orth_lower = orth.lower() <ide> _exc[orth_lower] = [{ORTH: orth_lower}] <ide> <add> orth_first_upper = orth[0].upper() + orth[1:] <add> _exc[orth_first_upper] = [{ORTH: orth_first_upper}] <add> <ide> if '-' in orth: <ide> orth_title = '-'.join([part.title() for part in orth.split('-')]) <ide> _exc[orth_title] = [{ORTH: orth_title}] <ide> _exc[orth_caps] = [{ORTH: orth_caps}] <ide> <ide> for exc_data in [ <del> {ORTH: "CKG", LEMMA: "Cakung", NORM: "Cakung"}, <del> {ORTH: "CGP", LEMMA: "Grogol Petamburan", NORM: "Grogol Petamburan"}, <del> {ORTH: "KSU", LEMMA: "Kepulauan Seribu Utara", NORM: "Kepulauan Seribu Utara"}, <del> {ORTH: "KYB", LEMMA: "Kebayoran Baru", NORM: "Kebayoran Baru"}, <del> {ORTH: "TJP", LEMMA: "Tanjungpriok", NORM: "Tanjungpriok"}, <del> {ORTH: "TNA", LEMMA: "Tanah Abang", NORM: "Tanah Abang"}, <del> <del> {ORTH: "BEK", LEMMA: "Bengkayang", NORM: "Bengkayang"}, <del> {ORTH: "KTP", LEMMA: "Ketapang", NORM: "Ketapang"}, <del> {ORTH: "MPW", LEMMA: "Mempawah", NORM: "Mempawah"}, <del> {ORTH: "NGP", LEMMA: "Nanga Pinoh", NORM: "Nanga Pinoh"}, <del> {ORTH: "NBA", LEMMA: "Ngabang", NORM: "Ngabang"}, <del> {ORTH: "PTK", LEMMA: "Pontianak", NORM: "Pontianak"}, <del> {ORTH: "PTS", LEMMA: "Putussibau", NORM: "Putussibau"}, <del> {ORTH: "SBS", LEMMA: "Sambas", NORM: "Sambas"}, <del> {ORTH: "SAG", LEMMA: "Sanggau", NORM: "Sanggau"}, <del> {ORTH: "SED", LEMMA: "Sekadau", NORM: "Sekadau"}, <del> {ORTH: "SKW", LEMMA: "Singkawang", NORM: "Singkawang"}, <del> {ORTH: "STG", LEMMA: "Sintang", NORM: "Sintang"}, <del> {ORTH: "SKD", LEMMA: "Sukadane", NORM: "Sukadane"}, <del> {ORTH: "SRY", LEMMA: "Sungai Raya", NORM: "Sungai Raya"}, <del> <ide> {ORTH: "Jan.", LEMMA: "Januari", NORM: "Januari"}, <ide> {ORTH: "Feb.", LEMMA: "Februari", NORM: "Februari"}, <ide> {ORTH: "Mar.", LEMMA: "Maret", NORM: "Maret"}, <ide> {ORTH: "Des.", LEMMA: "Desember", NORM: "Desember"}]: <ide> _exc[exc_data[ORTH]] = [exc_data] <ide> <add>_other_exc = { <add> "do'a": [{ORTH: "do'a", LEMMA: "doa", NORM: "doa"}], <add> "jum'at": [{ORTH: "jum'at", LEMMA: "Jumat", NORM: "Jumat"}], <add> "Jum'at": [{ORTH: "Jum'at", LEMMA: "Jumat", NORM: "Jumat"}], <add> "la'nat": [{ORTH: "la'nat", LEMMA: "laknat", NORM: "laknat"}], <add> "ma'af": [{ORTH: "ma'af", LEMMA: "maaf", NORM: "maaf"}], <add> "mu'jizat": [{ORTH: "mu'jizat", LEMMA: "mukjizat", NORM: "mukjizat"}], <add> "Mu'jizat": [{ORTH: "Mu'jizat", LEMMA: "mukjizat", NORM: "mukjizat"}], <add> "ni'mat": [{ORTH: "ni'mat", LEMMA: "nikmat", NORM: "nikmat"}], <add> "raka'at": [{ORTH: "raka'at", LEMMA: "rakaat", NORM: "rakaat"}], <add> "ta'at": [{ORTH: "ta'at", LEMMA: "taat", NORM: "taat"}], <add>} <add> <add>_exc.update(_other_exc) <add> <ide> for orth in [ <ide> "A.AB.", "A.Ma.", "A.Md.", "A.Md.Keb.", "A.Md.Kep.", "A.P.", <ide> "B.A.", "B.Ch.E.", "B.Sc.", "Dr.", "Dra.", "Drs.", "Hj.", "Ka.", "Kp.", <del> "M.AB", "M.Ag.", "M.AP", "M.Arl", "M.A.R.S", "M.Hum.", "M.I.Kom.", "M.Kes,", <del> "M.Kom.", "M.M.", "M.P.", "M.Pd.", "M.Psi.", "M.Psi.T.", "M.Sc.", "M.SArl", <del> "M.Si.", "M.Sn.", "M.T.", "M.Th.", "No.", "Pjs.", "Plt.", "R.A.", <add> "M.AB", "M.Ag.", "M.AP", "M.Arl", "M.A.R.S", "M.Hum.", "M.I.Kom.", <add> "M.Kes,", "M.Kom.", "M.M.", "M.P.", "M.Pd.", "M.Psi.", "M.Psi.T.", "M.Sc.", <add> "M.SArl", "M.Si.", "M.Sn.", "M.T.", "M.Th.", "No.", "Pjs.", "Plt.", "R.A.", <ide> "S.AB", "S.AP", "S.Adm", "S.Ag.", "S.Agr", "S.Ant", "S.Arl", "S.Ars", <ide> "S.A.R.S", "S.Ds", "S.E.", "S.E.I.", "S.Farm", "S.Gz.", "S.H.", "S.Han", <del> "S.H.Int", "S.Hum", "S.Hut.", "S.In.", "S.IK.", "S.I.Kom.", "S.I.P", "S.IP", <del> "S.P.", "S.Pt", "S.Psi", "S.Ptk", "S.Keb", "S.Ked", "S.Kep", "S.KG", "S.KH", <del> "S.Kel", "S.K.M.", "S.Kedg.", "S.Kedh.", "S.Kom.", "S.KPM", "S.Mb", "S.Mat", <del> "S.Par", "S.Pd.", "S.Pd.I.", "S.Pd.SD", "S.Pol.", "S.Psi.", "S.S.", "S.SArl.", <del> "S.Sn", "S.Si.", "S.Si.Teol.", "S.SI.", "S.ST.", "S.ST.Han", "S.STP", "S.Sos.", <del> "S.Sy.", "S.T.", "S.T.Han", "S.Th.", "S.Th.I" "S.TI.", "S.T.P.", "S.TrK", <del> "S.Tekp.", "S.Th.", <del> "a.l.", "a.n.", "a.s.", "b.d.", "d.a.", "d.l.", "d/h", "dkk.", "dll.", <del> "dr.", "drh.", "ds.", "dsb.", "dst.", "faks.", "fax.", "hlm.", "i/o", <del> "n.b.", "p.p." "pjs.", "s.d.", "tel.", "u.p.", <del> ]: <add> "S.H.Int", "S.Hum", "S.Hut.", "S.In.", "S.IK.", "S.I.Kom.", "S.I.P", <add> "S.IP", "S.P.", "S.Pt", "S.Psi", "S.Ptk", "S.Keb", "S.Ked", "S.Kep", <add> "S.KG", "S.KH", "S.Kel", "S.K.M.", "S.Kedg.", "S.Kedh.", "S.Kom.", "S.KPM", <add> "S.Mb", "S.Mat", "S.Par", "S.Pd.", "S.Pd.I.", "S.Pd.SD", "S.Pol.", <add> "S.Psi.", "S.S.", "S.SArl.", "S.Sn", "S.Si.", "S.Si.Teol.", "S.SI.", <add> "S.ST.", "S.ST.Han", "S.STP", "S.Sos.", "S.Sy.", "S.T.", "S.T.Han", <add> "S.Th.", "S.Th.I" "S.TI.", "S.T.P.", "S.TrK", "S.Tekp.", "S.Th.", <add> "Prof.", "drg.", "KH.", "Ust.", "Lc", "Pdt.", "S.H.H.", "Rm.", "Ps.", <add> "St.", "M.A.", "M.B.A", "M.Eng.", "M.Eng.Sc.", "M.Pharm.", "Dr. med", <add> "Dr.-Ing", "Dr. rer. nat.", "Dr. phil.", "Dr. iur.", "Dr. rer. oec", <add> "Dr. rer. pol.", "R.Ng.", "R.", "R.M.", "R.B.", "R.P.", "R.Ay.", "Rr.", <add> "R.Ngt.", "a.l.", "a.n.", "a.s.", "b.d.", "d.a.", "d.l.", "d/h", "dkk.", <add> "dll.", "dr.", "drh.", "ds.", "dsb.", "dst.", "faks.", "fax.", "hlm.", <add> "i/o", "n.b.", "p.p." "pjs.", "s.d.", "tel.", "u.p."]: <ide> _exc[orth] = [{ORTH: orth}] <ide> <ide> TOKENIZER_EXCEPTIONS = _exc
9
Javascript
Javascript
add splash to showcase
a0384dad3c582bdafbbf66585bba73bd0f255926
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=kr.dobbit.sharehows', <ide> author: 'Dobbit Co., Ltd.' <ide> }, <add> { <add> name: 'ShareWis', <add> icon: 'https://s3-ap-northeast-1.amazonaws.com/sw-misc/sharewis3_app.png', <add> link: 'https://itunes.apple.com/jp/app/id585517208', <add> author: 'ShareWis Inc.' <add> }, <ide> { <ide> name: 'sneat: réservez les meilleurs restaurants de Paris', <ide> icon: 'http://a3.mzstatic.com/eu/r30/Purple49/v4/71/71/df/7171df47-6e03-8619-19a8-07f52186b0ed/icon175x175.jpeg', <ide> var apps = [ <ide> link: 'https://play.google.com/store/apps/details?id=com.SoftwareInterview', <ide> author: 'Andrew F. Ly', <ide> }, <add> { <add> name: 'Spatula', <add> icon: 'https://lh3.googleusercontent.com/26xtcDsloLCAOpqgH_87sDxaSJsLuSN--oj-z5Frcdsaq4ta2GQlktF5ktTNWrRHyqo=w300-rw', <add> linkAppStore: 'https://itunes.apple.com/us/app/spatula/id1090496189?ls=1&mt=8', <add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.usespatula', <add> author: 'Kushal Dave' <add> }, <add> { <add> name: 'Splash: On-Demand Auto Detailing', <add> icon: 'http://a2.mzstatic.com/us/r30/Purple30/v4/c3/14/74/c314748f-ff16-c7ec-77c5-1a84657d9154/icon175x175.jpeg', <add> linkAppStore: 'https://itunes.apple.com/us/app/splash-on-demand-auto-detailing/id1111109177', <add> author: 'Alex Leventer' <add> }, <ide> { <ide> name: 'Spero for Cancer', <ide> icon: 'https://s3-us-west-1.amazonaws.com/cancerspot/site_images/Spero1024.png', <ide> var apps = [ <ide> linkAppStore: 'https://itunes.apple.com/cn/app/hong-bei-bang-hai-liang-hong/id1007812319?mt=8', <ide> author: 'Hongbeibang' <ide> }, <del> { <del> name: 'Spatula', <del> icon: 'https://lh3.googleusercontent.com/26xtcDsloLCAOpqgH_87sDxaSJsLuSN--oj-z5Frcdsaq4ta2GQlktF5ktTNWrRHyqo=w300-rw', <del> linkAppStore: 'https://itunes.apple.com/us/app/spatula/id1090496189?ls=1&mt=8', <del> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.usespatula', <del> author: 'Kushal Dave' <del> }, <del> { <del> name: 'ShareWis', <del> icon: 'https://s3-ap-northeast-1.amazonaws.com/sw-misc/sharewis3_app.png', <del> link: 'https://itunes.apple.com/jp/app/id585517208', <del> author: 'ShareWis Inc.' <del> }, <ide> { <ide> name: '找找', <ide> icon: 'https://lh3.googleusercontent.com/H0SILVHcDUxSMoSQwMb2QYtLjTBCqvK5ZEjOEwKQQ-2qnRV6Hd9Hn-gtSGPaoIOPwA=w300-rw',
1
Ruby
Ruby
update doc about `change_column_default` [ci skip]
2aab983fff209d5b696beb8d37564aeba9a6d7b3
<ide><path>activerecord/lib/active_record/migration.rb <ide> def initialize(current: nil, stored: nil) <ide> # <ide> # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes <ide> # the column to a different type using the same parameters as add_column. <del> # * <tt>change_column_default(table_name, column_name, default)</tt>: Sets a <del> # default value for +column_name+ defined by +default+ on +table_name+. <add> # * <tt>change_column_default(table_name, column_name, default_or_changes)</tt>: <add> # Sets a default value for +column_name+ defined by +default_or_changes+ on <add> # +table_name+. Passing a hash containing <tt>:from</tt> and <tt>:to</tt> <add> # as +default_or_changes+ will make this change reversible in the migration. <ide> # * <tt>change_column_null(table_name, column_name, null, default = nil)</tt>: <ide> # Sets or removes a +NOT NULL+ constraint on +column_name+. The +null+ flag <ide> # indicates whether the value can be +NULL+. See
1
Ruby
Ruby
remove warning from generator named base test
f5c27446bfc112043d833148446aeb7d72dedd8e
<ide><path>railties/test/generators/named_base_test.rb <ide> require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator' <ide> require 'mocha/setup' # FIXME: stop using mocha <ide> <del># Mock out what we need from AR::Base. <del>module ActiveRecord <del> class Base <del> class << self <del> attr_accessor :pluralize_table_names <del> end <del> self.pluralize_table_names = true <del> end <del>end <del> <ide> class NamedBaseTest < Rails::Generators::TestCase <ide> include GeneratorsTestHelper <ide> tests Rails::Generators::ScaffoldControllerGenerator
1
Go
Go
add readererrwrapper to readers
bd130e72a06dc3e8de521ce365bf4933f36b2417
<ide><path>pkg/ioutils/readers.go <ide> func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { <ide> } <ide> } <ide> <add>type readerErrWrapper struct { <add> reader io.Reader <add> closer func() <add>} <add> <add>func (r *readerErrWrapper) Read(p []byte) (int, error) { <add> n, err := r.reader.Read(p) <add> if err != nil { <add> r.closer() <add> } <add> return n, err <add>} <add> <add>func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader { <add> return &readerErrWrapper{ <add> reader: r, <add> closer: closer, <add> } <add>} <add> <ide> type bufReader struct { <ide> sync.Mutex <ide> buf *bytes.Buffer
1
Text
Text
remove news theme docs
c4139e292c0cd9752cdcdc14bc463764df64adc4
<ide><path>docs/_sidebar.md <ide> - [Work on localized client web app](how-to-work-on-localized-client-webapp.md) <ide> - [Work on Cypress tests](how-to-add-cypress-tests.md) <ide> - [Work on video challenges](how-to-help-with-video-challenges.md) <del> - [Work on the news theme](how-to-work-on-the-news-theme.md) <ide> - [Work on the docs theme](how-to-work-on-the-docs-theme.md) <ide> - **Additional Guides** <ide> - [Test translations locally](how-to-test-translations-locally.md) <ide><path>docs/how-to-work-on-the-news-theme.md <del># How to work on freeCodeCamp.org's developer news theme <del> <del>The developer news also known as [`/news`](https://www.freecodecamp.org/news) site is powered by [Ghost](https://ghost.org/). We use a custom theme for the look and feel of the site. The source code of the theme is available here: <https://github.com/freeCodeCamp/news-theme>. <del> <del>## The Theme <del> <del>Ghost uses a simple templating language called [Handlebars](http://handlebarsjs.com/) for its themes. The theme used on `/news` is based off of the default [casper theme](https://github.com/TryGhost/Casper). <del> <del>The default theme is commented pretty heavily so that it should be fairly easy to work out what's going on just by reading the code and the comments. Once you feel comfortable with how everything works, Ghost also has a full [theme API documentation](https://themes.ghost.org) which explains every possible Handlebars helper and template. <del> <del>**The main files are:** <del> <del>- `default.hbs` - The main template file <del>- `index.hbs` - Used for the home page <del>- `post.hbs` - Used for individual posts <del>- `page.hbs` - Used for individual pages <del>- `tag.hbs` - Used for tag archives <del>- `author.hbs` - Used for author archives <del> <del>One really neat trick is that you can also create custom one-off templates just by adding the slug of a page to a template file. For example: <del> <del>- `page-about.hbs` - Custom template for the `/about/` page <del>- `tag-news.hbs` - Custom template for `/tag/news/` archive <del>- `author-ali.hbs` - Custom template for `/author/ali/` archive <del> <del>## Development <del> <del>1. Get Ghost installed locally. <del> <del> ```sh <del> npm install -g ghost-cli@latest <del> mkdir ghost-local-site <del> cd ghost-local-site <del> ``` <del> <del> ```sh <del> ghost install local <del> ghost start <del> ``` <del> <del> > Note: Currently freeCodeCamp uses Ghost version `2.9.0`, so make sure you are using a version higher than that. <del> <del> Be sure to run `ghost` commands from the `ghost-local-site` directory. Follow additional instructions on [Ghost's official documentation](https://docs.ghost.org) if are not familiar with its interface. <del> <del>2. Fork and clone the repository in your theme directory (replacing `YOUR_USERNAME` with your GitHub username): <del> <del> ```sh <del> cd content/themes/ <del> git clone https://github.com/YOUR_USERNAME/news-theme.git <del> ``` <del> <del>3. Make sure you have all the pre-requisites. <del> <del> The theme styles are compiled using Gulp/PostCSS to polyfill future CSS spec. You'll need [Node.js](https://nodejs.org/). Make sure that your Node.js version is compatible with `ghost`. <del> <del>4. Install dependencies and develop the theme <del> <del> ```sh <del> npm ci <del> npm run develop <del> ``` <del> <del>5. Now you can edit `/assets/css/` files, which will be compiled to `/assets/built/` automatically. <del> <del>6. Access the development site. <del> <del> a. Enter `http://localhost:2368/ghost/` into your address bar. Continue with the setup prompted on the page (if running ghost for the first time). <del> <del> b. _(One-time only, during setup)_ Restart Ghost, on a separate terminal once to ensure the theme is available. <del> <del> ```sh <del> cd ghost-local-site <del> ghost restart <del> ``` <del> <del> c. _(One-time only, during setup)_ Once you've done this, go to `http://localhost:2368/ghost/#/settings/design` and scroll to the bottom. Make sure you click activate on the `freecodecamp-news-theme`. <del> <del>7. Zip the final code and make a pull-request <del> <del> The `zip` Gulp task packages the theme files into `dist/<theme-name>.zip`, which we can then upload to the production site. <del> <del> When you make a PR, please make sure you have run the below script prior to commiting the code and sending a PR. <del> <del> ```sh <del> npm run zip <del> ``` <del> <del>## Other Reference and resources <del> <del>### PostCSS Features Used <del> <del>- Autoprefixer - Don't worry about writing browser prefixes of any kind, it's all done automatically with support for the latest 2 major versions of every browser. <del>- Variables - Simple pure CSS variables <del>- [Color Function](https://github.com/postcss/postcss-color-function) <del> <del>### SVG Icons <del> <del>The theme uses inline SVG icons, included via Handlebars partials. You can find all icons inside `/partials/icons`. To use an icon just include the name of the relevant file, eg. To include the SVG icon in `/partials/icons/rss.hbs` - use `{{> "icons/rss"}}`. <del> <del>You can add your own SVG icons in the same manner.
2
Go
Go
fix a typo in udp cleanup path
7d2e851d8e921bf8f07f54c8afb8262580b36e8d
<ide><path>network.go <ide> func (iface *NetworkInterface) Release() { <ide> log.Printf("Unable to release port %s", nat) <ide> } <ide> } else if nat.Port.Proto() == "udp" { <del> if err := iface.manager.tcpPortAllocator.Release(ip, hostPort); err != nil { <add> if err := iface.manager.udpPortAllocator.Release(ip, hostPort); err != nil { <ide> log.Printf("Unable to release port %s: %s", nat, err) <ide> } <ide> }
1
Python
Python
add support for generators in numpy sum
a13aad3ac33b629f3e696b4d4d5dbf4b5605d567
<ide><path>numpy/core/oldnumeric.py <ide> 'compress', 'clip', 'sum', 'product', 'prod', 'sometrue', 'alltrue', <ide> 'any', 'all', 'cumsum', 'cumproduct', 'cumprod', 'ptp', 'ndim', <ide> 'rank', 'size', 'around', 'round_', 'mean', 'std', 'var', 'squeeze', <del> 'amax', 'amin','bsum' <add> 'amax', 'amin', <ide> ] <ide> <ide> import multiarray as mu <ide> import sys <ide> _dt_ = nt.dtype2char <ide> <add>import types <add> <add>try: <add> _gentype = types.GeneratorType <add>except AttributeError: <add> _gentype = types.NoneType <ide> #Use this to add a new axis to an array <ide> #compatibility only <ide> NewAxis = None <ide> LittleEndian = (sys.byteorder == 'little') <ide> <ide> # save away Python sum <del>bsum = sum <add>_sum_ = sum <ide> <ide> # backward compatible names from old Precision.py <ide> <ide> def sum(x, axis=0, dtype=None): <ide> >>> sum([[0, 1], [0, 5]], axis=1) <ide> array([1, 5]) <ide> """ <add> if isinstance(x, _gentype): <add> return _sum_(x) <ide> return asarray(x).sum(axis, dtype) <ide> <ide> def product (x, axis=0, dtype=None):
1
Text
Text
use gfm for clarity
4e08daabc889a87a14ad130d3386fd042274e6e7
<ide><path>benchmark/README.md <ide> directory, see [the guide on benchmarks](../doc/guides/writing-and-running-bench <ide> <ide> ## Benchmark Directories <ide> <del><table> <del> <thead> <del> <tr> <del> <th>Directory</th> <del> <th>Purpose</th> <del> </tr> <del> </thead> <del> <tbody> <del> <tr> <del> <td>assert</td> <del> <td> <del> Benchmarks for the <code>assert</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>buffers</td> <del> <td> <del> Benchmarks for the <code>buffer</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>child_process</td> <del> <td> <del> Benchmarks for the <code>child_process</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>crypto</td> <del> <td> <del> Benchmarks for the <code>crypto</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>dgram</td> <del> <td> <del> Benchmarks for the <code>dgram</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>domain</td> <del> <td> <del> Benchmarks for the <code>domain</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>es</td> <del> <td> <del> Benchmarks for various new ECMAScript features and their <del> pre-ES2015 counterparts. <del> </td> <del> </tr> <del> <tr> <del> <td>events</td> <del> <td> <del> Benchmarks for the <code>events</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>fixtures</td> <del> <td> <del> Benchmarks fixtures used in various benchmarks throughout <del> the benchmark suite. <del> </td> <del> </tr> <del> <tr> <del> <td>fs</td> <del> <td> <del> Benchmarks for the <code>fs</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>http</td> <del> <td> <del> Benchmarks for the <code>http</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>http2</td> <del> <td> <del> Benchmarks for the <code>http2</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>misc</td> <del> <td> <del> Miscellaneous benchmarks and benchmarks for shared <del> internal modules. <del> </td> <del> </tr> <del> <tr> <del> <td>module</td> <del> <td> <del> Benchmarks for the <code>module</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>net</td> <del> <td> <del> Benchmarks for the <code>net</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>path</td> <del> <td> <del> Benchmarks for the <code>path</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>process</td> <del> <td> <del> Benchmarks for the <code>process</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>querystring</td> <del> <td> <del> Benchmarks for the <code>querystring</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>streams</td> <del> <td> <del> Benchmarks for the <code>streams</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>string_decoder</td> <del> <td> <del> Benchmarks for the <code>string_decoder</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>timers</td> <del> <td> <del> Benchmarks for the <code>timers</code> subsystem, including <del> <code>setTimeout</code>, <code>setInterval</code>, .etc. <del> </td> <del> </tr> <del> <tr> <del> <td>tls</td> <del> <td> <del> Benchmarks for the <code>tls</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>url</td> <del> <td> <del> Benchmarks for the <code>url</code> subsystem, including the legacy <del> <code>url</code> implementation and the WHATWG URL implementation. <del> </td> <del> </tr> <del> <tr> <del> <td>util</td> <del> <td> <del> Benchmarks for the <code>util</code> subsystem. <del> </td> <del> </tr> <del> <tr> <del> <td>vm</td> <del> <td> <del> Benchmarks for the <code>vm</code> subsystem. <del> </td> <del> </tr> <del> </tbody> <del></table> <add>| Directory | Purpose | <add>| --------------- | ---------------------------------------------------------------------------------------------------------------- | <add>| assert | Benchmarks for the `assert` subsystem. | <add>| buffers | Benchmarks for the `buffer` subsystem. | <add>| child\_process | Benchmarks for the `child_process` subsystem. | <add>| crypto | Benchmarks for the `crypto` subsystem. | <add>| dgram | Benchmarks for the `dgram` subsystem. | <add>| domain | Benchmarks for the `domain` subsystem. | <add>| es | Benchmarks for various new ECMAScript features and their pre-ES2015 counterparts. | <add>| events | Benchmarks for the `events` subsystem. | <add>| fixtures | Benchmarks fixtures used in various benchmarks throughout the benchmark suite. | <add>| fs | Benchmarks for the `fs` subsystem. | <add>| http | Benchmarks for the `http` subsystem. | <add>| http2 | Benchmarks for the `http2` subsystem. | <add>| misc | Miscellaneous benchmarks and benchmarks for shared internal modules. | <add>| module | Benchmarks for the `module` subsystem. | <add>| net | Benchmarks for the `net` subsystem. | <add>| path | Benchmarks for the `path` subsystem. | <add>| process | Benchmarks for the `process` subsystem. | <add>| querystring | Benchmarks for the `querystring` subsystem. | <add>| streams | Benchmarks for the `streams` subsystem. | <add>| string\_decoder | Benchmarks for the `string_decoder` subsystem. | <add>| timers | Benchmarks for the `timers` subsystem, including `setTimeout`, `setInterval`, .etc. | <add>| tls | Benchmarks for the `tls` subsystem. | <add>| url | Benchmarks for the `url` subsystem, including the legacy `url` implementation and the WHATWG URL implementation. | <add>| util | Benchmarks for the `util` subsystem. | <add>| vm | Benchmarks for the `vm` subsystem. | <ide> <ide> ### Other Top-level files <ide>
1
Javascript
Javascript
remove unused initialpaths
e31a142a92e2c761976ee5f8383840b8756fe0d0
<ide><path>src/main-process/atom-application.js <ide> class AtomApplication extends EventEmitter { <ide> <ide> openWithOptions (options) { <ide> const { <del> initialPaths, <ide> pathsToOpen, <ide> executedFrom, <ide> urlsToOpen, <ide> class AtomApplication extends EventEmitter { <ide> }) <ide> } else if (pathsToOpen.length > 0) { <ide> return this.openPaths({ <del> initialPaths, <ide> pathsToOpen, <ide> executedFrom, <ide> pidToKillWhenClosed, <ide> class AtomApplication extends EventEmitter { <ide> } else { <ide> // Always open a editor window if this is the first instance of Atom. <ide> return this.openPath({ <del> initialPaths, <ide> pidToKillWhenClosed, <ide> newWindow, <ide> devMode, <ide> class AtomApplication extends EventEmitter { <ide> // :window - {AtomWindow} to open file paths in. <ide> // :addToLastWindow - Boolean of whether this should be opened in last focused window. <ide> openPath ({ <del> initialPaths, <ide> pathToOpen, <ide> pidToKillWhenClosed, <ide> newWindow, <ide> class AtomApplication extends EventEmitter { <ide> env <ide> } = {}) { <ide> return this.openPaths({ <del> initialPaths, <ide> pathsToOpen: [pathToOpen], <ide> pidToKillWhenClosed, <ide> newWindow, <ide> class AtomApplication extends EventEmitter { <ide> // :window - {AtomWindow} to open file paths in. <ide> // :addToLastWindow - Boolean of whether this should be opened in last focused window. <ide> openPaths ({ <del> initialPaths, <ide> pathsToOpen, <ide> executedFrom, <ide> pidToKillWhenClosed, <ide> class AtomApplication extends EventEmitter { <ide> if (!windowDimensions) windowDimensions = this.getDimensionsForNewWindow() <ide> <ide> openedWindow = new AtomWindow(this, this.fileRecoveryService, { <del> initialPaths, <ide> locationsToOpen, <ide> windowInitializationScript, <ide> resourcePath, <ide> class AtomApplication extends EventEmitter { <ide> const states = await this.storageFolder.load('application.json') <ide> if (states) { <ide> return states.map(state => ({ <del> initialPaths: state.initialPaths, <del> pathsToOpen: state.initialPaths.filter(p => fs.isDirectorySync(p)), <add> pathsToOpen: state.initialPaths, <ide> urlsToOpen: [], <ide> devMode: this.devMode, <ide> safeMode: this.safeMode
1
Ruby
Ruby
add change_rpath method
4d5971518de4a6cc8307d5c31567bca35072b5b6
<ide><path>Library/Homebrew/os/mac/keg.rb <ide> def change_install_name(old, new, file) <ide> raise <ide> end <ide> <add> def change_rpath(old, new, file) <add> return if old == new <add> <add> @require_relocation = true <add> odebug "Changing rpath in #{file}\n from #{old}\n to #{new}" <add> MachO::Tools.change_rpath(file, old, new, strict: false) <add> apply_ad_hoc_signature(file) <add> rescue MachO::MachOError <add> onoe <<~EOS <add> Failed changing rpath in #{file} <add> from #{old} <add> to #{new} <add> EOS <add> raise <add> end <add> <ide> def apply_ad_hoc_signature(file) <ide> return if MacOS.version < :big_sur <ide> return unless Hardware::CPU.arm?
1
Python
Python
run the `check_migration` loop at least once
84d7b5ba39b3ff1fb5b856faec8fd4e731d3f397
<ide><path>airflow/utils/db.py <ide> def check_migrations(timeout): <ide> :param timeout: Timeout for the migration in seconds <ide> :return: None <ide> """ <add> timeout = timeout or 1 # run the loop at least 1 <ide> with _configured_alembic_environment() as env: <ide> context = env.get_context() <ide> source_heads = None <ide><path>tests/utils/test_db.py <ide> def test_default_connections_sort(self): <ide> <ide> def test_check_migrations(self): <ide> # Should run without error. Can't easily test the behaviour, but we can check it works <add> check_migrations(0) <ide> check_migrations(1) <ide> <ide> @mock.patch('alembic.command')
2
Mixed
Python
update slim include.
e92334255e48b557e699e94b2d560bf0d88f6e7c
<ide><path>research/audioset/vggish/README.md <ide> $ sudo python -m pip install --upgrade pip <ide> # Install dependences. Resampy needs to be installed after NumPy and SciPy <ide> # are already installed. <ide> $ sudo pip install numpy scipy soundfile <del>$ sudo pip install resampy tensorflow six <add>$ sudo pip install resampy six <add>$ sudo pip install tensorflow==1.14 <ide> <ide> # Clone TensorFlow models repo into a 'models' directory. <ide> $ git clone https://github.com/tensorflow/models.git <ide><path>research/audioset/vggish/vggish_slim.py <ide> https://github.com/tensorflow/models/blob/master/research/slim/nets/vgg.py <ide> """ <ide> <del>import tensorflow as tf <add>import tensorflow.compat.v1 as tf <add>from tensorflow.contrib import slim as contrib_slim <ide> import vggish_params as params <ide> <del>slim = tf.contrib.slim <add>slim = contrib_slim <ide> <ide> <ide> def define_vggish_slim(training=False):
2
Ruby
Ruby
use didyoumean for broken link fixes in guides
8b71dc15ef5d2c0f3f27c1f077320d8ac76c4987
<ide><path>guides/rails_guides/generator.rb <ide> <ide> require "rails_guides/markdown" <ide> require "rails_guides/helpers" <del>require "rails_guides/levenshtein" <ide> <ide> module RailsGuides <ide> class Generator <ide> def check_fragment_identifiers(html, anchors) <ide> html.scan(/<a\s+href="#([^"]+)/).flatten.each do |fragment_identifier| <ide> next if fragment_identifier == "mainCol" # in layout, jumps to some DIV <ide> unless anchors.member?(CGI.unescape(fragment_identifier)) <del> guess = anchors.min { |a, b| <del> Levenshtein.distance(fragment_identifier, a) <=> Levenshtein.distance(fragment_identifier, b) <del> } <add> guess = DidYouMean::SpellChecker.new(dictionary: anchors).correct(fragment_identifier).first <ide> puts "*** BROKEN LINK: ##{fragment_identifier}, perhaps you meant ##{guess}." <ide> end <ide> end <ide><path>guides/rails_guides/levenshtein.rb <del># frozen_string_literal: true <del> <del>module RailsGuides <del> module Levenshtein <del> # This code is based directly on the Text gem implementation. <del> # Copyright (c) 2006-2013 Paul Battley, Michael Neumann, Tim Fletcher. <del> # <del> # Returns a value representing the "cost" of transforming str1 into str2 <del> def self.distance(str1, str2) <del> s = str1 <del> t = str2 <del> n = s.length <del> m = t.length <del> <del> return m if 0 == n <del> return n if 0 == m <del> <del> d = (0..m).to_a <del> x = nil <del> <del> # avoid duplicating an enumerable object in the loop <del> str2_codepoint_enumerable = str2.each_codepoint <del> <del> str1.each_codepoint.with_index do |char1, i| <del> e = i + 1 <del> <del> str2_codepoint_enumerable.with_index do |char2, j| <del> cost = (char1 == char2) ? 0 : 1 <del> x = [ <del> d[j + 1] + 1, # insertion <del> e + 1, # deletion <del> d[j] + cost # substitution <del> ].min <del> d[j] = e <del> e = x <del> end <del> <del> d[m] = x <del> end <del> <del> x <del> end <del> end <del>end
2
Python
Python
use an enum class for identity endpoint type
5af1bf3635435ea84becc4365d2ceba7d8462939
<ide><path>libcloud/common/openstack_identity.py <ide> 'OpenStackServiceCatalog', <ide> 'OpenStackServiceCatalogEntry', <ide> 'OpenStackServiceCatalogEntryEndpoint', <add> 'OpenStackIdentityEndpointType', <ide> <ide> 'OpenStackIdentityConnection', <ide> 'OpenStackIdentity_1_0_Connection', <ide> ] <ide> <ide> <add>class OpenStackIdentityEndpointType(object): <add> """ <add> Enum class for openstack identity endpoint type. <add> """ <add> INTERNAL = 'internal' <add> EXTERNAL = 'external' <add> ADMIN = 'admin' <add> <add> <ide> class OpenStackIdentityVersion(object): <ide> def __init__(self, version, status, updated, url): <ide> self.version = version <ide> def get_public_urls(self, service_type=None, name=None): <ide> <ide> result = [] <ide> for endpoint in endpoints: <del> if endpoint.endpoint_type == 'external': <add> endpoint_type = endpoint.endpoint_type <add> if endpoint_type == OpenStackIdentityEndpointType.EXTERNAL: <ide> result.append(endpoint.url) <ide> <ide> return result <ide> def get_endpoints(self, service_type=None, name=None): <ide> return endpoints <ide> <ide> def get_endpoint(self, service_type=None, name=None, region=None, <del> endpoint_type='external'): <add> endpoint_type=OpenStackIdentityEndpointType.EXTERNAL): <ide> """ <ide> Retrieve a single endpoint using the provided criteria. <ide> <ide> def _parse_service_catalog_auth_v1(self, service_catalog): <ide> if public_url: <ide> entry_endpoint = OpenStackServiceCatalogEntryEndpoint( <ide> region=region, url=public_url, <del> endpoint_type='external') <add> endpoint_type=OpenStackIdentityEndpointType.EXTERNAL) <ide> entry_endpoints.append(entry_endpoint) <ide> <ide> if private_url: <ide> entry_endpoint = OpenStackServiceCatalogEntryEndpoint( <ide> region=region, url=private_url, <del> endpoint_type='internal') <add> endpoint_type=OpenStackIdentityEndpointType.INTERNAL) <ide> entry_endpoints.append(entry_endpoint) <ide> <ide> entry = OpenStackServiceCatalogEntry(service_type=service, <ide> def _parse_service_catalog_auth_v2(self, service_catalog): <ide> if public_url: <ide> entry_endpoint = OpenStackServiceCatalogEntryEndpoint( <ide> region=region, url=public_url, <del> endpoint_type='external') <add> endpoint_type=OpenStackIdentityEndpointType.EXTERNAL) <ide> entry_endpoints.append(entry_endpoint) <ide> <ide> if private_url: <ide> entry_endpoint = OpenStackServiceCatalogEntryEndpoint( <ide> region=region, url=private_url, <del> endpoint_type='internal') <add> endpoint_type=OpenStackIdentityEndpointType.INTERNAL) <ide> entry_endpoints.append(entry_endpoint) <ide> <ide> entry = OpenStackServiceCatalogEntry(service_type=service_type, <ide> def _parse_service_catalog_auth_v3(self, service_catalog): <ide> endpoint_type = endpoint['interface'] <ide> <ide> if endpoint_type == 'internal': <del> endpoint_type = 'internal' <add> endpoint_type = OpenStackIdentityEndpointType.INTERNAL <ide> elif endpoint_type == 'public': <del> endpoint_type = 'external' <add> endpoint_type = OpenStackIdentityEndpointType.EXTERNAL <ide> elif endpoint_type == 'admin': <del> endpoint_type = 'admin' <add> endpoint_type = OpenStackIdentityEndpointType.ADMIN <ide> <ide> entry_endpoint = OpenStackServiceCatalogEntryEndpoint( <ide> region=region, url=url, endpoint_type=endpoint_type) <ide> def __repr__(self): <ide> <ide> <ide> class OpenStackServiceCatalogEntryEndpoint(object): <add> VALID_ENDPOINT_TYPES = [ <add> OpenStackIdentityEndpointType.INTERNAL, <add> OpenStackIdentityEndpointType.EXTERNAL, <add> OpenStackIdentityEndpointType.ADMIN, <add> ] <add> <ide> def __init__(self, region, url, endpoint_type='external'): <ide> """ <ide> :param region: Endpoint region. <ide> def __init__(self, region, url, endpoint_type='external'): <ide> :param endpoint_type: Endpoint type (external / internal / admin). <ide> :type endpoint_type: ``str`` <ide> """ <del> if endpoint_type not in ['internal', 'external', 'admin']: <add> if endpoint_type not in self.VALID_ENDPOINT_TYPES: <ide> raise ValueError('Invalid type: %s' % (endpoint_type)) <ide> <ide> # TODO: Normalize / lowercase all the region names
1
Go
Go
fix golint warnings for daemon/execdriver/*
3d17c3bb663a5d7a65bd39a5ef32cb4668b48c53
<ide><path>daemon/container_unix.go <ide> func populateCommand(c *Container, env []string) error { <ide> resources := &execdriver.Resources{ <ide> Memory: c.hostConfig.Memory, <ide> MemorySwap: c.hostConfig.MemorySwap, <del> CpuShares: c.hostConfig.CPUShares, <add> CPUShares: c.hostConfig.CPUShares, <ide> CpusetCpus: c.hostConfig.CpusetCpus, <ide> CpusetMems: c.hostConfig.CpusetMems, <del> CpuPeriod: c.hostConfig.CPUPeriod, <del> CpuQuota: c.hostConfig.CPUQuota, <add> CPUPeriod: c.hostConfig.CPUPeriod, <add> CPUQuota: c.hostConfig.CPUQuota, <ide> BlkioWeight: c.hostConfig.BlkioWeight, <ide> Rlimits: rlimits, <ide> OomKillDisable: c.hostConfig.OomKillDisable, <ide><path>daemon/execdriver/driver.go <ide> import ( <ide> // arbatrary data to be sent <ide> type Context map[string]string <ide> <add>// Define error messages <ide> var ( <ide> ErrNotRunning = errors.New("Container is not running") <ide> ErrWaitTimeoutReached = errors.New("Wait timeout reached") <ide> ErrDriverAlreadyRegistered = errors.New("A driver already registered this docker init function") <ide> ErrDriverNotFound = errors.New("The requested docker init has not been found") <ide> ) <ide> <add>// StartCallback defines a callback function. <add>// It's used by 'Run' and 'Exec', does some work in parent process <add>// after child process is started. <ide> type StartCallback func(*ProcessConfig, int) <ide> <del>// Driver specific information based on <add>// Info is driver specific information based on <ide> // processes registered with the driver <ide> type Info interface { <ide> IsRunning() bool <ide> } <ide> <del>// Terminal in an interface for drivers to implement <del>// if they want to support Close and Resize calls from <del>// the core <add>// Terminal represents a pseudo TTY, it is for when <add>// using a container interactively. <ide> type Terminal interface { <ide> io.Closer <ide> Resize(height, width int) error <ide> type ExitStatus struct { <ide> OOMKilled bool <ide> } <ide> <add>// Driver is an interface for drivers to implement <add>// including all basic functions a driver should have <ide> type Driver interface { <del> Run(c *Command, pipes *Pipes, startCallback StartCallback) (ExitStatus, error) // Run executes the process and blocks until the process exits and returns the exit code <del> // Exec executes the process in an existing container, blocks until the process exits and returns the exit code <add> // Run executes the process, blocks until the process exits and returns <add> // the exit code. It's the last stage on Docker side for running a container. <add> Run(c *Command, pipes *Pipes, startCallback StartCallback) (ExitStatus, error) <add> <add> // Exec executes the process in an existing container, blocks until the <add> // process exits and returns the exit code. <ide> Exec(c *Command, processConfig *ProcessConfig, pipes *Pipes, startCallback StartCallback) (int, error) <add> <add> // Kill sends signals to process in container. <ide> Kill(c *Command, sig int) error <add> <add> // Pause pauses a container. <ide> Pause(c *Command) error <add> <add> // Unpause unpauses a container. <ide> Unpause(c *Command) error <del> Name() string // Driver name <del> Info(id string) Info // "temporary" hack (until we move state from core to plugins) <del> GetPidsForContainer(id string) ([]int, error) // Returns a list of pids for the given container. <del> Terminate(c *Command) error // kill it with fire <del> Clean(id string) error // clean all traces of container exec <del> Stats(id string) (*ResourceStats, error) // Get resource stats for a running container <add> <add> // Name returns the name of the driver. <add> Name() string <add> <add> // Info returns the configuration stored in the driver struct, <add> // "temporary" hack (until we move state from core to plugins). <add> Info(id string) Info <add> <add> // GetPidsForContainer returns a list of pid for the processes running in a container. <add> GetPidsForContainer(id string) ([]int, error) <add> <add> // Terminate kills a container by sending signal SIGKILL. <add> Terminate(c *Command) error <add> <add> // Clean removes all traces of container exec. <add> Clean(id string) error <add> <add> // Stats returns resource stats for a running container <add> Stats(id string) (*ResourceStats, error) <ide> } <ide> <ide> // Network settings of the container <ide> type Network struct { <ide> HostNetworking bool `json:"host_networking"` <ide> } <ide> <del>// IPC settings of the container <add>// Ipc settings of the container <add>// It is for IPC namespace setting. Usually different containers <add>// have their own IPC namespace, however this specifies to use <add>// an existing IPC namespace. <add>// You can join the host's or a container's IPC namespace. <ide> type Ipc struct { <ide> ContainerID string `json:"container_id"` // id of the container to join ipc. <ide> HostIpc bool `json:"host_ipc"` <ide> } <ide> <del>// PID settings of the container <add>// Pid settings of the container <add>// It is for PID namespace setting. Usually different containers <add>// have their own PID namespace, however this specifies to use <add>// an existing PID namespace. <add>// Joining the host's PID namespace is currently the only supported <add>// option. <ide> type Pid struct { <ide> HostPid bool `json:"host_pid"` <ide> } <ide> <ide> // UTS settings of the container <add>// It is for UTS namespace setting. Usually different containers <add>// have their own UTS namespace, however this specifies to use <add>// an existing UTS namespace. <add>// Joining the host's UTS namespace is currently the only supported <add>// option. <ide> type UTS struct { <ide> HostUTS bool `json:"host_uts"` <ide> } <ide> <add>// NetworkInterface contains all network configs for a driver <ide> type NetworkInterface struct { <ide> Gateway string `json:"gateway"` <ide> IPAddress string `json:"ip"` <ide> type NetworkInterface struct { <ide> HairpinMode bool `json:"hairpin_mode"` <ide> } <ide> <add>// Resources contains all resource configs for a driver. <add>// Currently these are all for cgroup configs. <ide> // TODO Windows: Factor out ulimit.Rlimit <ide> type Resources struct { <ide> Memory int64 `json:"memory"` <ide> MemorySwap int64 `json:"memory_swap"` <del> CpuShares int64 `json:"cpu_shares"` <add> CPUShares int64 `json:"cpu_shares"` <ide> CpusetCpus string `json:"cpuset_cpus"` <ide> CpusetMems string `json:"cpuset_mems"` <del> CpuPeriod int64 `json:"cpu_period"` <del> CpuQuota int64 `json:"cpu_quota"` <add> CPUPeriod int64 `json:"cpu_period"` <add> CPUQuota int64 `json:"cpu_quota"` <ide> BlkioWeight int64 `json:"blkio_weight"` <ide> Rlimits []*ulimit.Rlimit `json:"rlimits"` <ide> OomKillDisable bool `json:"oom_kill_disable"` <ide> MemorySwappiness int64 `json:"memory_swappiness"` <ide> } <ide> <add>// ResourceStats contains information about resource usage by a container. <ide> type ResourceStats struct { <ide> *libcontainer.Stats <ide> Read time.Time `json:"read"` <ide> MemoryLimit int64 `json:"memory_limit"` <ide> SystemUsage uint64 `json:"system_usage"` <ide> } <ide> <add>// Mount contains information for a mount operation. <ide> type Mount struct { <ide> Source string `json:"source"` <ide> Destination string `json:"destination"` <ide> type Mount struct { <ide> Slave bool `json:"slave"` <ide> } <ide> <del>// Describes a process that will be run inside a container. <add>// ProcessConfig describes a process that will be run inside a container. <ide> type ProcessConfig struct { <ide> exec.Cmd `json:"-"` <ide> <ide> type ProcessConfig struct { <ide> ConsoleSize [2]int `json:"-"` // h,w of initial console size <ide> } <ide> <add>// Command wrapps an os/exec.Cmd to add more metadata <add>// <ide> // TODO Windows: Factor out unused fields such as LxcConfig, AppArmorProfile, <ide> // and CgroupParent. <del>// <del>// Process wrapps an os/exec.Cmd to add more metadata <ide> type Command struct { <ide> ID string `json:"id"` <ide> Rootfs string `json:"rootfs"` // root fs of the container <ide><path>daemon/execdriver/driver_linux.go <ide> import ( <ide> "github.com/opencontainers/runc/libcontainer/configs" <ide> ) <ide> <add>// InitContainer is the initialization of a container config. <add>// It returns the initial configs for a container. It's mostly <add>// defined by the default template. <ide> func InitContainer(c *Command) *configs.Config { <ide> container := template.New() <ide> <ide> func getEnv(key string, env []string) string { <ide> return "" <ide> } <ide> <add>// SetupCgroups setups cgroup resources for a container. <ide> func SetupCgroups(container *configs.Config, c *Command) error { <ide> if c.Resources != nil { <del> container.Cgroups.CpuShares = c.Resources.CpuShares <add> container.Cgroups.CpuShares = c.Resources.CPUShares <ide> container.Cgroups.Memory = c.Resources.Memory <ide> container.Cgroups.MemoryReservation = c.Resources.Memory <ide> container.Cgroups.MemorySwap = c.Resources.MemorySwap <ide> container.Cgroups.CpusetCpus = c.Resources.CpusetCpus <ide> container.Cgroups.CpusetMems = c.Resources.CpusetMems <del> container.Cgroups.CpuPeriod = c.Resources.CpuPeriod <del> container.Cgroups.CpuQuota = c.Resources.CpuQuota <add> container.Cgroups.CpuPeriod = c.Resources.CPUPeriod <add> container.Cgroups.CpuQuota = c.Resources.CPUQuota <ide> container.Cgroups.BlkioWeight = c.Resources.BlkioWeight <ide> container.Cgroups.OomKillDisable = c.Resources.OomKillDisable <ide> container.Cgroups.MemorySwappiness = c.Resources.MemorySwappiness <ide> func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) { <ide> return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) <ide> } <ide> <add>// Stats collects all the resource usage information from a container. <ide> func Stats(containerDir string, containerMemoryLimit int64, machineMemory int64) (*ResourceStats, error) { <ide> f, err := os.Open(filepath.Join(containerDir, "state.json")) <ide> if err != nil { <ide><path>daemon/execdriver/execdrivers/execdrivers_linux.go <ide> import ( <ide> "github.com/docker/docker/pkg/sysinfo" <ide> ) <ide> <add>// NewDriver returns a new execdriver.Driver from the given name configured with the provided options. <ide> func NewDriver(name string, options []string, root, libPath, initPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) { <ide> switch name { <ide> case "lxc": <ide><path>daemon/execdriver/execdrivers/execdrivers_windows.go <ide> import ( <ide> "github.com/docker/docker/pkg/sysinfo" <ide> ) <ide> <add>// NewDriver returns a new execdriver.Driver from the given name configured with the provided options. <ide> func NewDriver(name string, options []string, root, libPath, initPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) { <ide> switch name { <ide> case "windows": <ide><path>daemon/execdriver/lxc/driver.go <ide> import ( <ide> "github.com/vishvananda/netns" <ide> ) <ide> <add>// DriverName for lxc driver <ide> const DriverName = "lxc" <ide> <add>// ErrExec defines unsupported error message <ide> var ErrExec = errors.New("Unsupported: Exec is not supported by the lxc driver") <ide> <del>type driver struct { <add>// Driver contains all information for lxc driver, <add>// it implements execdriver.Driver <add>type Driver struct { <ide> root string // root path for the driver to use <ide> libPath string <ide> initPath string <ide> type activeContainer struct { <ide> cmd *exec.Cmd <ide> } <ide> <del>func NewDriver(root, libPath, initPath string, apparmor bool) (*driver, error) { <add>// NewDriver returns a new lxc driver, called from NewDriver of execdriver <add>func NewDriver(root, libPath, initPath string, apparmor bool) (*Driver, error) { <ide> if err := os.MkdirAll(root, 0700); err != nil { <ide> return nil, err <ide> } <ide> func NewDriver(root, libPath, initPath string, apparmor bool) (*driver, error) { <ide> if err != nil { <ide> return nil, err <ide> } <del> return &driver{ <add> return &Driver{ <ide> apparmor: apparmor, <ide> root: root, <ide> libPath: libPath, <ide> func NewDriver(root, libPath, initPath string, apparmor bool) (*driver, error) { <ide> }, nil <ide> } <ide> <del>func (d *driver) Name() string { <add>// Name implements the exec driver Driver interface. <add>func (d *Driver) Name() string { <ide> version := d.version() <ide> return fmt.Sprintf("%s-%s", DriverName, version) <ide> } <ide> func killNetNsProc(proc *os.Process) { <ide> proc.Wait() <ide> } <ide> <del>func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) { <add>// Run implements the exec driver Driver interface, <add>// it calls 'exec.Cmd' to launch lxc commands to run a container. <add>func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) { <ide> var ( <ide> term execdriver.Terminal <ide> err error <ide> func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) { <ide> <ide> // createContainer populates and configures the container type with the <ide> // data provided by the execdriver.Command <del>func (d *driver) createContainer(c *execdriver.Command) (*configs.Config, error) { <add>func (d *Driver) createContainer(c *execdriver.Command) (*configs.Config, error) { <ide> container := execdriver.InitContainer(c) <ide> if err := execdriver.SetupCgroups(container, c); err != nil { <ide> return nil, err <ide> } <ide> return container, nil <ide> } <ide> <del>// Return an map of susbystem -> container cgroup <del>func cgroupPaths(containerId string) (map[string]string, error) { <add>// Return an map of susbystem -> absolute container cgroup path <add>func cgroupPaths(containerID string) (map[string]string, error) { <ide> subsystems, err := cgroups.GetAllSubsystems() <ide> if err != nil { <ide> return nil, err <ide> func cgroupPaths(containerId string) (map[string]string, error) { <ide> //unsupported subystem <ide> continue <ide> } <del> path := filepath.Join(cgroupRoot, cgroupDir, "lxc", containerId) <add> path := filepath.Join(cgroupRoot, cgroupDir, "lxc", containerID) <ide> paths[subsystem] = path <ide> } <ide> <ide> func setupUser(userSpec string) error { <ide> return nil <ide> } <ide> <del>/// Return the exit code of the process <del>// if the process has not exited -1 will be returned <add>// getExitCode returns the exit code of the process. <add>// If the process has not exited -1 will be returned. <ide> func getExitCode(c *execdriver.Command) int { <ide> if c.ProcessConfig.ProcessState == nil { <ide> return -1 <ide> } <ide> return c.ProcessConfig.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() <ide> } <ide> <del>func (d *driver) Kill(c *execdriver.Command, sig int) error { <add>// Kill implements the exec driver Driver interface. <add>func (d *Driver) Kill(c *execdriver.Command, sig int) error { <ide> if sig == 9 || c.ProcessConfig.Process == nil { <del> return KillLxc(c.ID, sig) <add> return killLxc(c.ID, sig) <ide> } <ide> <ide> return c.ProcessConfig.Process.Signal(syscall.Signal(sig)) <ide> } <ide> <del>func (d *driver) Pause(c *execdriver.Command) error { <add>// Pause implements the exec driver Driver interface, <add>// it executes lxc-freeze to pause a container. <add>func (d *Driver) Pause(c *execdriver.Command) error { <ide> _, err := exec.LookPath("lxc-freeze") <ide> if err == nil { <ide> output, errExec := exec.Command("lxc-freeze", "-n", c.ID).CombinedOutput() <ide> func (d *driver) Pause(c *execdriver.Command) error { <ide> return err <ide> } <ide> <del>func (d *driver) Unpause(c *execdriver.Command) error { <add>// Unpause implements the exec driver Driver interface, <add>// it executes lxc-unfreeze to unpause a container. <add>func (d *Driver) Unpause(c *execdriver.Command) error { <ide> _, err := exec.LookPath("lxc-unfreeze") <ide> if err == nil { <ide> output, errExec := exec.Command("lxc-unfreeze", "-n", c.ID).CombinedOutput() <ide> func (d *driver) Unpause(c *execdriver.Command) error { <ide> return err <ide> } <ide> <del>func (d *driver) Terminate(c *execdriver.Command) error { <del> return KillLxc(c.ID, 9) <add>// Terminate implements the exec driver Driver interface. <add>func (d *Driver) Terminate(c *execdriver.Command) error { <add> return killLxc(c.ID, 9) <ide> } <ide> <del>func (d *driver) version() string { <add>func (d *Driver) version() string { <ide> var ( <ide> version string <ide> output []byte <ide> func (d *driver) version() string { <ide> return version <ide> } <ide> <del>func KillLxc(id string, sig int) error { <add>func killLxc(id string, sig int) error { <ide> var ( <ide> err error <ide> output []byte <ide> func KillLxc(id string, sig int) error { <ide> } <ide> <ide> // wait for the process to start and return the pid for the process <del>func (d *driver) waitForStart(c *execdriver.Command, waitLock chan struct{}) (int, error) { <add>func (d *Driver) waitForStart(c *execdriver.Command, waitLock chan struct{}) (int, error) { <ide> var ( <ide> err error <ide> output []byte <ide> func (d *driver) waitForStart(c *execdriver.Command, waitLock chan struct{}) (in <ide> return -1, execdriver.ErrNotRunning <ide> } <ide> <del>func (d *driver) getInfo(id string) ([]byte, error) { <add>func (d *Driver) getInfo(id string) ([]byte, error) { <ide> return exec.Command("lxc-info", "-n", id).CombinedOutput() <ide> } <ide> <ide> type info struct { <ide> ID string <del> driver *driver <add> driver *Driver <ide> } <ide> <ide> func (i *info) IsRunning() bool { <ide> func (i *info) IsRunning() bool { <ide> return running <ide> } <ide> <del>func (d *driver) Info(id string) execdriver.Info { <add>// Info implements the exec driver Driver interface. <add>func (d *Driver) Info(id string) execdriver.Info { <ide> return &info{ <ide> ID: id, <ide> driver: d, <ide> func findCgroupRootAndDir(subsystem string) (string, string, error) { <ide> return cgroupRoot, cgroupDir, nil <ide> } <ide> <del>func (d *driver) GetPidsForContainer(id string) ([]int, error) { <add>// GetPidsForContainer implements the exec driver Driver interface. <add>func (d *Driver) GetPidsForContainer(id string) ([]int, error) { <ide> pids := []int{} <ide> <ide> // cpu is chosen because it is the only non optional subsystem in cgroups <ide> func rootIsShared() bool { <ide> return true <ide> } <ide> <del>func (d *driver) containerDir(containerId string) string { <del> return path.Join(d.libPath, "containers", containerId) <add>func (d *Driver) containerDir(containerID string) string { <add> return path.Join(d.libPath, "containers", containerID) <ide> } <ide> <del>func (d *driver) generateLXCConfig(c *execdriver.Command) (string, error) { <add>func (d *Driver) generateLXCConfig(c *execdriver.Command) (string, error) { <ide> root := path.Join(d.containerDir(c.ID), "config.lxc") <ide> <ide> fo, err := os.Create(root) <ide> func (d *driver) generateLXCConfig(c *execdriver.Command) (string, error) { <ide> } <ide> defer fo.Close() <ide> <del> if err := LxcTemplateCompiled.Execute(fo, struct { <add> if err := lxcTemplateCompiled.Execute(fo, struct { <ide> *execdriver.Command <ide> AppArmor bool <ide> }{ <ide> func (d *driver) generateLXCConfig(c *execdriver.Command) (string, error) { <ide> return root, nil <ide> } <ide> <del>func (d *driver) generateEnvConfig(c *execdriver.Command) error { <add>func (d *Driver) generateEnvConfig(c *execdriver.Command) error { <ide> data, err := json.Marshal(c.ProcessConfig.Env) <ide> if err != nil { <ide> return err <ide> func (d *driver) generateEnvConfig(c *execdriver.Command) error { <ide> return ioutil.WriteFile(p, data, 0600) <ide> } <ide> <del>// Clean not implemented for lxc <del>func (d *driver) Clean(id string) error { <add>// Clean implements the exec driver Driver interface, <add>// it's not implemented by lxc. <add>func (d *Driver) Clean(id string) error { <ide> return nil <ide> } <ide> <add>// TtyConsole implements the exec driver Terminal interface, <add>// it stores the master and slave ends of the container's pty. <ide> type TtyConsole struct { <ide> MasterPty *os.File <ide> SlavePty *os.File <ide> } <ide> <add>// NewTtyConsole returns a new TtyConsole struct. <add>// Wired up to the provided process config and stdin/stdout/stderr pipes. <ide> func NewTtyConsole(processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes) (*TtyConsole, error) { <ide> // lxc is special in that we cannot create the master outside of the container without <ide> // opening the slave because we have nothing to provide to the cmd. We have to open both then do <ide> func NewTtyConsole(processConfig *execdriver.ProcessConfig, pipes *execdriver.Pi <ide> return tty, nil <ide> } <ide> <add>// Resize implements Resize method of Terminal interface <ide> func (t *TtyConsole) Resize(h, w int) error { <ide> return term.SetWinsize(t.MasterPty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)}) <ide> } <ide> <add>// AttachPipes attaches given pipes to exec.Cmd <ide> func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) error { <ide> command.Stdout = t.SlavePty <ide> command.Stderr = t.SlavePty <ide> func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) err <ide> return nil <ide> } <ide> <add>// Close implements Close method of Terminal interface <ide> func (t *TtyConsole) Close() error { <ide> t.SlavePty.Close() <ide> return t.MasterPty.Close() <ide> } <ide> <del>func (d *driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { <add>// Exec implements the exec driver Driver interface, <add>// it is not implemented by lxc. <add>func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { <ide> return -1, ErrExec <ide> } <ide> <del>func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) { <add>// Stats implements the exec driver Driver interface. <add>// Lxc doesn't implement it's own Stats, it does some trick by implementing <add>// execdriver.Stats to get stats info by libcontainer APIs. <add>func (d *Driver) Stats(id string) (*execdriver.ResourceStats, error) { <ide> if _, ok := d.activeContainers[id]; !ok { <ide> return nil, fmt.Errorf("%s is not a key in active containers", id) <ide> } <ide><path>daemon/execdriver/lxc/info.go <ide> import ( <ide> "strings" <ide> ) <ide> <add>// Define error messages <ide> var ( <ide> ErrCannotParse = errors.New("cannot parse raw input") <ide> ) <ide><path>daemon/execdriver/lxc/init.go <ide> import ( <ide> "github.com/docker/docker/pkg/reexec" <ide> ) <ide> <del>// Args provided to the init function for a driver <add>// InitArgs contains args provided to the init function for a driver <ide> type InitArgs struct { <ide> User string <ide> Gateway string <del> Ip string <add> IP string <ide> WorkDir string <ide> Privileged bool <ide> Env []string <ide> func getArgs() *InitArgs { <ide> return &InitArgs{ <ide> User: *user, <ide> Gateway: *gateway, <del> Ip: *ip, <add> IP: *ip, <ide> WorkDir: *workDir, <ide> Privileged: *privileged, <ide> Args: flag.Args(), <ide><path>daemon/execdriver/lxc/lxc_template.go <ide> import ( <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> ) <ide> <add>// LxcTemplate is the template for lxc driver, it's used <add>// to configure LXC. <ide> const LxcTemplate = ` <ide> lxc.network.type = none <ide> # root filesystem <ide> lxc.cgroup.memory.soft_limit_in_bytes = {{.Resources.Memory}} <ide> lxc.cgroup.memory.memsw.limit_in_bytes = {{$memSwap}} <ide> {{end}} <ide> {{end}} <del>{{if .Resources.CpuShares}} <del>lxc.cgroup.cpu.shares = {{.Resources.CpuShares}} <add>{{if .Resources.CPUShares}} <add>lxc.cgroup.cpu.shares = {{.Resources.CPUShares}} <ide> {{end}} <del>{{if .Resources.CpuPeriod}} <del>lxc.cgroup.cpu.cfs_period_us = {{.Resources.CpuPeriod}} <add>{{if .Resources.CPUPeriod}} <add>lxc.cgroup.cpu.cfs_period_us = {{.Resources.CPUPeriod}} <ide> {{end}} <ide> {{if .Resources.CpusetCpus}} <ide> lxc.cgroup.cpuset.cpus = {{.Resources.CpusetCpus}} <ide> {{end}} <ide> {{if .Resources.CpusetMems}} <ide> lxc.cgroup.cpuset.mems = {{.Resources.CpusetMems}} <ide> {{end}} <del>{{if .Resources.CpuQuota}} <del>lxc.cgroup.cpu.cfs_quota_us = {{.Resources.CpuQuota}} <add>{{if .Resources.CPUQuota}} <add>lxc.cgroup.cpu.cfs_quota_us = {{.Resources.CPUQuota}} <ide> {{end}} <ide> {{if .Resources.BlkioWeight}} <ide> lxc.cgroup.blkio.weight = {{.Resources.BlkioWeight}} <ide> lxc.cap.drop = {{.}} <ide> {{end}} <ide> ` <ide> <del>var LxcTemplateCompiled *template.Template <add>var lxcTemplateCompiled *template.Template <ide> <ide> // Escape spaces in strings according to the fstab documentation, which is the <ide> // format for "lxc.mount.entry" lines in lxc.conf. See also "man 5 fstab". <ide> func init() { <ide> "dropList": dropList, <ide> "getHostname": getHostname, <ide> } <del> LxcTemplateCompiled, err = template.New("lxc").Funcs(funcMap).Parse(LxcTemplate) <add> lxcTemplateCompiled, err = template.New("lxc").Funcs(funcMap).Parse(LxcTemplate) <ide> if err != nil { <ide> panic(err) <ide> } <ide><path>daemon/execdriver/lxc/lxc_template_unit_test.go <ide> func TestLXCConfig(t *testing.T) { <ide> ID: "1", <ide> Resources: &execdriver.Resources{ <ide> Memory: int64(mem), <del> CpuShares: int64(cpu), <add> CPUShares: int64(cpu), <ide> }, <ide> Network: &execdriver.Network{ <ide> Mtu: 1500, <ide><path>daemon/execdriver/native/create.go <ide> import ( <ide> <ide> // createContainer populates and configures the container type with the <ide> // data provided by the execdriver.Command <del>func (d *driver) createContainer(c *execdriver.Command) (*configs.Config, error) { <add>func (d *Driver) createContainer(c *execdriver.Command) (*configs.Config, error) { <ide> container := execdriver.InitContainer(c) <ide> <ide> if err := d.createIpc(container, c); err != nil { <ide> func generateIfaceName() (string, error) { <ide> return "", errors.New("Failed to find name for new interface") <ide> } <ide> <del>func (d *driver) createNetwork(container *configs.Config, c *execdriver.Command) error { <add>func (d *Driver) createNetwork(container *configs.Config, c *execdriver.Command) error { <ide> if c.Network == nil { <ide> return nil <ide> } <ide> func (d *driver) createNetwork(container *configs.Config, c *execdriver.Command) <ide> return nil <ide> } <ide> <del>func (d *driver) createIpc(container *configs.Config, c *execdriver.Command) error { <add>func (d *Driver) createIpc(container *configs.Config, c *execdriver.Command) error { <ide> if c.Ipc.HostIpc { <ide> container.Namespaces.Remove(configs.NEWIPC) <ide> return nil <ide> func (d *driver) createIpc(container *configs.Config, c *execdriver.Command) err <ide> return nil <ide> } <ide> <del>func (d *driver) createPid(container *configs.Config, c *execdriver.Command) error { <add>func (d *Driver) createPid(container *configs.Config, c *execdriver.Command) error { <ide> if c.Pid.HostPid { <ide> container.Namespaces.Remove(configs.NEWPID) <ide> return nil <ide> func (d *driver) createPid(container *configs.Config, c *execdriver.Command) err <ide> return nil <ide> } <ide> <del>func (d *driver) createUTS(container *configs.Config, c *execdriver.Command) error { <add>func (d *Driver) createUTS(container *configs.Config, c *execdriver.Command) error { <ide> if c.UTS.HostUTS { <ide> container.Namespaces.Remove(configs.NEWUTS) <ide> container.Hostname = "" <ide> func (d *driver) createUTS(container *configs.Config, c *execdriver.Command) err <ide> return nil <ide> } <ide> <del>func (d *driver) setPrivileged(container *configs.Config) (err error) { <add>func (d *Driver) setPrivileged(container *configs.Config) (err error) { <ide> container.Capabilities = execdriver.GetAllCapabilities() <ide> container.Cgroups.AllowAllDevices = true <ide> <ide> func (d *driver) setPrivileged(container *configs.Config) (err error) { <ide> return nil <ide> } <ide> <del>func (d *driver) setCapabilities(container *configs.Config, c *execdriver.Command) (err error) { <add>func (d *Driver) setCapabilities(container *configs.Config, c *execdriver.Command) (err error) { <ide> container.Capabilities, err = execdriver.TweakCapabilities(container.Capabilities, c.CapAdd, c.CapDrop) <ide> return err <ide> } <ide> <del>func (d *driver) setupRlimits(container *configs.Config, c *execdriver.Command) { <add>func (d *Driver) setupRlimits(container *configs.Config, c *execdriver.Command) { <ide> if c.Resources == nil { <ide> return <ide> } <ide> func (d *driver) setupRlimits(container *configs.Config, c *execdriver.Command) <ide> } <ide> } <ide> <del>func (d *driver) setupMounts(container *configs.Config, c *execdriver.Command) error { <add>func (d *Driver) setupMounts(container *configs.Config, c *execdriver.Command) error { <ide> userMounts := make(map[string]struct{}) <ide> for _, m := range c.Mounts { <ide> userMounts[m.Destination] = struct{}{} <ide> func (d *driver) setupMounts(container *configs.Config, c *execdriver.Command) e <ide> return nil <ide> } <ide> <del>func (d *driver) setupLabels(container *configs.Config, c *execdriver.Command) { <add>func (d *Driver) setupLabels(container *configs.Config, c *execdriver.Command) { <ide> container.ProcessLabel = c.ProcessLabel <ide> container.MountLabel = c.MountLabel <ide> } <ide><path>daemon/execdriver/native/driver.go <ide> import ( <ide> "github.com/opencontainers/runc/libcontainer/utils" <ide> ) <ide> <add>// Define constants for native driver <ide> const ( <ide> DriverName = "native" <ide> Version = "0.2" <ide> ) <ide> <del>type driver struct { <add>// Driver contains all information for native driver, <add>// it implements execdriver.Driver. <add>type Driver struct { <ide> root string <ide> initPath string <ide> activeContainers map[string]libcontainer.Container <ide> type driver struct { <ide> sync.Mutex <ide> } <ide> <del>func NewDriver(root, initPath string, options []string) (*driver, error) { <add>// NewDriver returns a new native driver, called from NewDriver of execdriver. <add>func NewDriver(root, initPath string, options []string) (*Driver, error) { <ide> meminfo, err := sysinfo.ReadMemInfo() <ide> if err != nil { <ide> return nil, err <ide> func NewDriver(root, initPath string, options []string) (*driver, error) { <ide> return nil, err <ide> } <ide> <del> return &driver{ <add> return &Driver{ <ide> root: root, <ide> initPath: initPath, <ide> activeContainers: make(map[string]libcontainer.Container), <ide> type execOutput struct { <ide> err error <ide> } <ide> <del>func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) { <add>// Run implements the exec driver Driver interface, <add>// it calls libcontainer APIs to run a container. <add>func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) { <ide> // take the Command and populate the libcontainer.Config from it <ide> container, err := d.createContainer(c) <ide> if err != nil { <ide> func waitInPIDHost(p *libcontainer.Process, c libcontainer.Container) func() (*o <ide> } <ide> } <ide> <del>func (d *driver) Kill(c *execdriver.Command, sig int) error { <add>// Kill implements the exec driver Driver interface. <add>func (d *Driver) Kill(c *execdriver.Command, sig int) error { <ide> d.Lock() <ide> active := d.activeContainers[c.ID] <ide> d.Unlock() <ide> func (d *driver) Kill(c *execdriver.Command, sig int) error { <ide> return syscall.Kill(state.InitProcessPid, syscall.Signal(sig)) <ide> } <ide> <del>func (d *driver) Pause(c *execdriver.Command) error { <add>// Pause implements the exec driver Driver interface, <add>// it calls libcontainer API to pause a container. <add>func (d *Driver) Pause(c *execdriver.Command) error { <ide> d.Lock() <ide> active := d.activeContainers[c.ID] <ide> d.Unlock() <ide> func (d *driver) Pause(c *execdriver.Command) error { <ide> return active.Pause() <ide> } <ide> <del>func (d *driver) Unpause(c *execdriver.Command) error { <add>// Unpause implements the exec driver Driver interface, <add>// it calls libcontainer API to unpause a container. <add>func (d *Driver) Unpause(c *execdriver.Command) error { <ide> d.Lock() <ide> active := d.activeContainers[c.ID] <ide> d.Unlock() <ide> func (d *driver) Unpause(c *execdriver.Command) error { <ide> return active.Resume() <ide> } <ide> <del>func (d *driver) Terminate(c *execdriver.Command) error { <add>// Terminate implements the exec driver Driver interface. <add>func (d *Driver) Terminate(c *execdriver.Command) error { <ide> defer d.cleanContainer(c.ID) <ide> container, err := d.factory.Load(c.ID) <ide> if err != nil { <ide> func (d *driver) Terminate(c *execdriver.Command) error { <ide> return err <ide> } <ide> <del>func (d *driver) Info(id string) execdriver.Info { <add>// Info implements the exec driver Driver interface. <add>func (d *Driver) Info(id string) execdriver.Info { <ide> return &info{ <ide> ID: id, <ide> driver: d, <ide> } <ide> } <ide> <del>func (d *driver) Name() string { <add>// Name implements the exec driver Driver interface. <add>func (d *Driver) Name() string { <ide> return fmt.Sprintf("%s-%s", DriverName, Version) <ide> } <ide> <del>func (d *driver) GetPidsForContainer(id string) ([]int, error) { <add>// GetPidsForContainer implements the exec driver Driver interface. <add>func (d *Driver) GetPidsForContainer(id string) ([]int, error) { <ide> d.Lock() <ide> active := d.activeContainers[id] <ide> d.Unlock() <ide> func (d *driver) GetPidsForContainer(id string) ([]int, error) { <ide> return active.Processes() <ide> } <ide> <del>func (d *driver) cleanContainer(id string) error { <add>func (d *Driver) cleanContainer(id string) error { <ide> d.Lock() <ide> delete(d.activeContainers, id) <ide> d.Unlock() <ide> return os.RemoveAll(filepath.Join(d.root, id)) <ide> } <ide> <del>func (d *driver) createContainerRoot(id string) error { <add>func (d *Driver) createContainerRoot(id string) error { <ide> return os.MkdirAll(filepath.Join(d.root, id), 0655) <ide> } <ide> <del>func (d *driver) Clean(id string) error { <add>// Clean implements the exec driver Driver interface. <add>func (d *Driver) Clean(id string) error { <ide> return os.RemoveAll(filepath.Join(d.root, id)) <ide> } <ide> <del>func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) { <add>// Stats implements the exec driver Driver interface. <add>func (d *Driver) Stats(id string) (*execdriver.ResourceStats, error) { <ide> d.Lock() <ide> c := d.activeContainers[id] <ide> d.Unlock() <ide> func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) { <ide> }, nil <ide> } <ide> <add>// TtyConsole implements the exec driver Terminal interface. <ide> type TtyConsole struct { <ide> console libcontainer.Console <ide> } <ide> <add>// NewTtyConsole returns a new TtyConsole struct. <ide> func NewTtyConsole(console libcontainer.Console, pipes *execdriver.Pipes) (*TtyConsole, error) { <ide> tty := &TtyConsole{ <ide> console: console, <ide> func NewTtyConsole(console libcontainer.Console, pipes *execdriver.Pipes) (*TtyC <ide> return tty, nil <ide> } <ide> <add>// Resize implements Resize method of Terminal interface <ide> func (t *TtyConsole) Resize(h, w int) error { <ide> return term.SetWinsize(t.console.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)}) <ide> } <ide> <add>// AttachPipes attaches given pipes to TtyConsole <ide> func (t *TtyConsole) AttachPipes(pipes *execdriver.Pipes) error { <ide> go func() { <ide> if wb, ok := pipes.Stdout.(interface { <ide> func (t *TtyConsole) AttachPipes(pipes *execdriver.Pipes) error { <ide> return nil <ide> } <ide> <add>// Close implements Close method of Terminal interface <ide> func (t *TtyConsole) Close() error { <ide> return t.console.Close() <ide> } <ide><path>daemon/execdriver/native/driver_unsupported.go <ide> import ( <ide> "github.com/docker/docker/daemon/execdriver" <ide> ) <ide> <add>// NewDriver returns a new native driver, called from NewDriver of execdriver. <ide> func NewDriver(root, initPath string) (execdriver.Driver, error) { <ide> return nil, fmt.Errorf("native driver not supported on non-linux") <ide> } <ide><path>daemon/execdriver/native/driver_unsupported_nocgo.go <ide> import ( <ide> "github.com/docker/docker/daemon/execdriver" <ide> ) <ide> <add>// NewDriver returns a new native driver, called from NewDriver of execdriver. <ide> func NewDriver(root, initPath string) (execdriver.Driver, error) { <ide> return nil, fmt.Errorf("native driver not supported on non-linux") <ide> } <ide><path>daemon/execdriver/native/exec.go <ide> import ( <ide> <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/opencontainers/runc/libcontainer" <add> // Blank import 'nsenter' so that init in that package will call c <add> // function 'nsexec()' to do 'setns' before Go runtime take over, <add> // it's used for join to exist ns like 'docker exec' command. <ide> _ "github.com/opencontainers/runc/libcontainer/nsenter" <ide> "github.com/opencontainers/runc/libcontainer/utils" <ide> ) <ide> <add>// Exec implements the exec driver Driver interface, <add>// it calls libcontainer APIs to execute a container. <ide> // TODO(vishh): Add support for running in privileged mode. <del>func (d *driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { <add>func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { <ide> active := d.activeContainers[c.ID] <ide> if active == nil { <ide> return -1, fmt.Errorf("No active container exists with ID %s", c.ID) <ide><path>daemon/execdriver/native/info.go <ide> package native <ide> <ide> type info struct { <ide> ID string <del> driver *driver <add> driver *Driver <ide> } <ide> <ide> // IsRunning is determined by looking for the <ide><path>daemon/execdriver/pipes.go <ide> import ( <ide> "io" <ide> ) <ide> <del>// Pipes is a wrapper around a containers output for <add>// Pipes is a wrapper around a container's output for <ide> // stdin, stdout, stderr <ide> type Pipes struct { <ide> Stdin io.ReadCloser <ide> Stdout, Stderr io.Writer <ide> } <ide> <add>// NewPipes returns a wrapper around a container's output <ide> func NewPipes(stdin io.ReadCloser, stdout, stderr io.Writer, useStdin bool) *Pipes { <ide> p := &Pipes{ <ide> Stdout: stdout, <ide><path>daemon/execdriver/termconsole.go <ide> import ( <ide> "os/exec" <ide> ) <ide> <add>// StdConsole defines standard console operations for execdriver <ide> type StdConsole struct { <ide> } <ide> <add>// NewStdConsole returns a new StdConsole struct <ide> func NewStdConsole(processConfig *ProcessConfig, pipes *Pipes) (*StdConsole, error) { <ide> std := &StdConsole{} <ide> <ide> func NewStdConsole(processConfig *ProcessConfig, pipes *Pipes) (*StdConsole, err <ide> return std, nil <ide> } <ide> <add>// AttachPipes attaches given pipes to exec.Cmd <ide> func (s *StdConsole) AttachPipes(command *exec.Cmd, pipes *Pipes) error { <ide> command.Stdout = pipes.Stdout <ide> command.Stderr = pipes.Stderr <ide> func (s *StdConsole) AttachPipes(command *exec.Cmd, pipes *Pipes) error { <ide> return nil <ide> } <ide> <add>// Resize implements Resize method of Terminal interface <ide> func (s *StdConsole) Resize(h, w int) error { <ide> // we do not need to reside a non tty <ide> return nil <ide> } <ide> <add>// Close implements Close method of Terminal interface <ide> func (s *StdConsole) Close() error { <ide> // nothing to close here <ide> return nil <ide><path>daemon/execdriver/utils.go <ide> func init() { <ide> } <ide> <ide> type ( <add> // CapabilityMapping maps linux capability name to its value of capability.Cap type <add> // Capabilities is one of the security systems in Linux Security Module (LSM) <add> // framework provided by the kernel. <add> // For more details on capabilities, see http://man7.org/linux/man-pages/man7/capabilities.7.html <ide> CapabilityMapping struct { <ide> Key string `json:"key,omitempty"` <ide> Value capability.Cap `json:"value,omitempty"` <ide> } <add> // Capabilities contains all CapabilityMapping <ide> Capabilities []*CapabilityMapping <ide> ) <ide> <add>// String returns <key> of CapabilityMapping <ide> func (c *CapabilityMapping) String() string { <ide> return c.Key <ide> } <ide> <add>// GetCapability returns CapabilityMapping which contains specific key <ide> func GetCapability(key string) *CapabilityMapping { <ide> for _, capp := range capabilityList { <ide> if capp.Key == key { <ide> func GetCapability(key string) *CapabilityMapping { <ide> return nil <ide> } <ide> <add>// GetAllCapabilities returns all of the capabilities <ide> func GetAllCapabilities() []string { <ide> output := make([]string, len(capabilityList)) <ide> for i, capability := range capabilityList { <ide> func GetAllCapabilities() []string { <ide> return output <ide> } <ide> <add>// TweakCapabilities can tweak capabilities by adding or dropping capabilities <add>// based on the basics capabilities. <ide> func TweakCapabilities(basics, adds, drops []string) ([]string, error) { <ide> var ( <ide> newCaps []string <ide><path>daemon/execdriver/windows/unsupported.go <ide> import ( <ide> "github.com/docker/docker/daemon/execdriver" <ide> ) <ide> <add>// NewDriver returns a new execdriver.Driver <ide> func NewDriver(root, initPath string) (execdriver.Driver, error) { <ide> return nil, fmt.Errorf("Windows driver not supported on non-Windows") <ide> }
20
Javascript
Javascript
fix instrumentation in shallow rendering
510155e027d56ce3cf5c890c9939d894528cf007
<ide><path>src/test/ReactTestUtils.js <ide> var ReactElement = require('ReactElement'); <ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); <ide> var ReactCompositeComponent = require('ReactCompositeComponent'); <ide> var ReactInstanceMap = require('ReactInstanceMap'); <add>var ReactInstrumentation = require('ReactInstrumentation'); <add>var ReactReconciler = require('ReactReconciler'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> var SyntheticEvent = require('SyntheticEvent'); <ide> <ide> NoopInternalComponent.prototype = { <ide> }; <ide> <ide> var ShallowComponentWrapper = function(element) { <add> // TODO: Consolidate with instantiateReactComponent <ide> this._debugID = nextDebugID++; <add> var displayName = element.type.displayName || element.type.name || 'Unknown'; <add> ReactInstrumentation.debugTool.onSetDisplayName(this._debugID, displayName); <add> <ide> this.construct(element); <ide> }; <ide> Object.assign( <ide> ReactShallowRenderer.prototype.getRenderOutput = function() { <ide> <ide> ReactShallowRenderer.prototype.unmount = function() { <ide> if (this._instance) { <del> this._instance.unmountComponent(false); <add> ReactReconciler.unmountComponent(this._instance, false); <ide> } <ide> }; <ide> <ide> ReactShallowRenderer.prototype._render = function(element, transaction, context) { <ide> if (this._instance) { <del> this._instance.receiveComponent(element, transaction, context); <add> ReactReconciler.receiveComponent( <add> this._instance, <add> element, <add> transaction, <add> context <add> ); <ide> } else { <ide> var instance = new ShallowComponentWrapper(element); <del> instance.mountComponent(transaction, null, null, context); <add> ReactReconciler.mountComponent(instance, transaction, null, null, context); <ide> this._instance = instance; <ide> } <ide> }; <ide><path>src/test/__tests__/ReactTestUtils-test.js <ide> describe('ReactTestUtils', function() { <ide> expect(result).toEqual(<div>foo</div>); <ide> }); <ide> <add> it('can fail context when shallowly rendering', function() { <add> spyOn(console, 'error'); <add> var SimpleComponent = React.createClass({ <add> contextTypes: { <add> name: React.PropTypes.string.isRequired, <add> }, <add> render: function() { <add> return <div>{this.context.name}</div>; <add> }, <add> }); <add> <add> var shallowRenderer = ReactTestUtils.createRenderer(); <add> shallowRenderer.render(<SimpleComponent />); <add> expect(console.error.argsForCall.length).toBe(1); <add> expect( <add> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)') <add> ).toBe( <add> 'Warning: Failed context type: Required context `name` was not ' + <add> 'specified in `SimpleComponent`.\n' + <add> ' in SimpleComponent (at **)' <add> ); <add> }); <add> <ide> it('can scryRenderedDOMComponentsWithClass with TextComponent', function() { <ide> var Wrapper = React.createClass({ <ide> render: function() {
2
Ruby
Ruby
add flag to suppress whitespace fixes
d54e7fb4deb98b5572fcdf9a55eba702a2a10f52
<ide><path>Library/Contributions/examples/brew-pull.rb <ide> end <ide> <ide> HOMEBREW_REPOSITORY.cd do <del> ARGV.each do|arg| <add> ARGV.named.each do|arg| <ide> if arg.to_i > 0 <ide> url = 'https://github.com/mxcl/homebrew/pull/' + arg + '.patch' <ide> else <ide> <ide> # Makes sense to squash whitespace errors, we don't want them. <ide> ohai 'Applying patch' <del> safe_system 'git', 'am', '--signoff', '--whitespace=fix', patchpath <add> patch_args = %w[am --signoff] <add> patch_args << '--whitespace=fix' unless ARGV.include? '--ignore-whitespace' <add> patch_args << patchpath <add> <add> safe_system 'git', *patch_args <ide> <ide> issue = arg.to_i > 0 ? arg.to_i : urlmatch[2] <ide> if issue <ide> ohai "Patch closes issue ##{issue}" <ide> message = `git log HEAD^.. --format=%B` <del> <add> <ide> # If this is a pull request, append a close message. <ide> if !message.include? 'Closes #' <ide> issueline = "Closes ##{issue}."
1
Javascript
Javascript
fix small typos
54f6ae9b1c0489784f6a95bbe26ffec31816d74a
<ide><path>packages/react-devtools-shared/src/__tests__/console-test.js <ide> describe('console', () => { <ide> ); <ide> } <ide> <del> it('should not patch console methods that are not explicitly overriden', () => { <add> it('should not patch console methods that are not explicitly overridden', () => { <ide> expect(fakeConsole.error).not.toBe(mockError); <ide> expect(fakeConsole.info).toBe(mockInfo); <ide> expect(fakeConsole.log).toBe(mockLog); <ide><path>packages/react-devtools-shared/src/backend/views/utils.js <ide> export function getBoundingClientRectWithBorderOffset(node: HTMLElement) { <ide> right: dimensions.borderRight, <ide> // This width and height won't get used by mergeRectOffsets (since this <ide> // is not the first rect in the array), but we set them so that this <del> // object typechecks as a ClientRect. <add> // object type checks as a ClientRect. <ide> width: 0, <ide> height: 0, <ide> }, <ide><path>scripts/release/prepare-release-from-npm-commands/update-stable-version-numbers.js <ide> const run = async ({cwd, packages, version}, versionsMap) => { <ide> let diff = ''; <ide> let numFilesModified = 0; <ide> <del> // Find-and-replace hard coded version (in built JS) for renderers. <add> // Find-and-replace hardcoded version (in built JS) for renderers. <ide> for (let i = 0; i < packages.length; i++) { <ide> const packageName = packages[i]; <ide> const packagePath = join(nodeModulesPath, packageName);
3
Python
Python
fix issue with custom application input_tensor
68af216772980a7c8811bc1ad5421970fb6a978c
<ide><path>keras/applications/inception_v3.py <ide> from ..models import Model <ide> from ..layers import Flatten, Dense, Input, BatchNormalization, merge <ide> from ..layers import Convolution2D, MaxPooling2D, AveragePooling2D <add>from ..engine.topology import get_source_inputs <ide> from ..utils.layer_utils import convert_all_kernels_in_model <ide> from ..utils.data_utils import get_file <ide> from .. import backend as K <ide> def InceptionV3(include_top=True, weights='imagenet', <ide> x = Flatten(name='flatten')(x) <ide> x = Dense(1000, activation='softmax', name='predictions')(x) <ide> <del> # Create model <del> model = Model(img_input, x) <add> # Ensure that the model takes into account <add> # any potential predecessors of `input_tensor`. <add> if input_tensor is not None: <add> inputs = get_source_inputs(input_tensor) <add> else: <add> inputs = img_input <add> # Create model. <add> model = Model(inputs, x) <ide> <ide> # load weights <ide> if weights == 'imagenet': <ide><path>keras/applications/music_tagger_crnn.py <ide> from ..layers.normalization import BatchNormalization <ide> from ..layers.advanced_activations import ELU <ide> from ..layers.recurrent import GRU <add>from ..engine.topology import get_source_inputs <ide> from ..utils.data_utils import get_file <ide> from ..utils.layer_utils import convert_all_kernels_in_model <ide> from .audio_conv_utils import decode_predictions, preprocess_input <ide> def MusicTaggerCRNN(weights='msd', input_tensor=None, <ide> if include_top: <ide> x = Dense(50, activation='sigmoid', name='output')(x) <ide> <del> # Create model <del> model = Model(melgram_input, x) <add> # Ensure that the model takes into account <add> # any potential predecessors of `input_tensor`. <add> if input_tensor is not None: <add> inputs = get_source_inputs(input_tensor) <add> else: <add> inputs = melgram_input <add> # Create model. <add> model = Model(inputs, x) <add> <ide> if weights is None: <ide> return model <ide> else: <ide><path>keras/applications/resnet50.py <ide> from ..layers import BatchNormalization <ide> from ..models import Model <ide> from .. import backend as K <add>from ..engine.topology import get_source_inputs <ide> from ..utils.layer_utils import convert_all_kernels_in_model <ide> from ..utils.data_utils import get_file <ide> from .imagenet_utils import decode_predictions, preprocess_input, _obtain_input_shape <ide> def ResNet50(include_top=True, weights='imagenet', <ide> x = Flatten()(x) <ide> x = Dense(1000, activation='softmax', name='fc1000')(x) <ide> <del> model = Model(img_input, x) <add> # Ensure that the model takes into account <add> # any potential predecessors of `input_tensor`. <add> if input_tensor is not None: <add> inputs = get_source_inputs(input_tensor) <add> else: <add> inputs = img_input <add> # Create model. <add> model = Model(inputs, x) <ide> <ide> # load weights <ide> if weights == 'imagenet': <ide><path>keras/applications/vgg16.py <ide> from ..models import Model <ide> from ..layers import Flatten, Dense, Input <ide> from ..layers import Convolution2D, MaxPooling2D <add>from ..engine.topology import get_source_inputs <ide> from ..utils.layer_utils import convert_all_kernels_in_model <ide> from ..utils.data_utils import get_file <ide> from .. import backend as K <ide> def VGG16(include_top=True, weights='imagenet', <ide> x = Dense(4096, activation='relu', name='fc2')(x) <ide> x = Dense(1000, activation='softmax', name='predictions')(x) <ide> <del> # Create model <del> model = Model(img_input, x) <add> # Ensure that the model takes into account <add> # any potential predecessors of `input_tensor`. <add> if input_tensor is not None: <add> inputs = get_source_inputs(input_tensor) <add> else: <add> inputs = img_input <add> # Create model. <add> model = Model(inputs, x) <ide> <ide> # load weights <ide> if weights == 'imagenet': <ide><path>keras/applications/vgg19.py <ide> from ..models import Model <ide> from ..layers import Flatten, Dense, Input <ide> from ..layers import Convolution2D, MaxPooling2D <add>from ..engine.topology import get_source_inputs <ide> from ..utils.layer_utils import convert_all_kernels_in_model <ide> from ..utils.data_utils import get_file <ide> from .. import backend as K <ide> def VGG19(include_top=True, weights='imagenet', <ide> x = Dense(4096, activation='relu', name='fc2')(x) <ide> x = Dense(1000, activation='softmax', name='predictions')(x) <ide> <del> # Create model <del> model = Model(img_input, x) <add> # Ensure that the model takes into account <add> # any potential predecessors of `input_tensor`. <add> if input_tensor is not None: <add> inputs = get_source_inputs(input_tensor) <add> else: <add> inputs = img_input <add> # Create model. <add> model = Model(inputs, x) <ide> <ide> # load weights <ide> if weights == 'imagenet': <ide><path>keras/applications/xception.py <ide> from ..models import Model <ide> from ..layers import Dense, Input, BatchNormalization, Activation, merge <ide> from ..layers import Conv2D, SeparableConv2D, MaxPooling2D, GlobalAveragePooling2D <add>from ..engine.topology import get_source_inputs <ide> from ..utils.data_utils import get_file <ide> from .. import backend as K <ide> from .imagenet_utils import decode_predictions, _obtain_input_shape <ide> def Xception(include_top=True, weights='imagenet', <ide> x = GlobalAveragePooling2D(name='avg_pool')(x) <ide> x = Dense(1000, activation='softmax', name='predictions')(x) <ide> <del> # Create model <del> model = Model(img_input, x) <add> # Ensure that the model takes into account <add> # any potential predecessors of `input_tensor`. <add> if input_tensor is not None: <add> inputs = get_source_inputs(input_tensor) <add> else: <add> inputs = img_input <add> # Create model. <add> model = Model(inputs, x) <ide> <ide> # load weights <ide> if weights == 'imagenet': <ide><path>keras/engine/topology.py <ide> def get_source_inputs(tensor, layer=None, node_index=None): <ide> node_index: Origin node index of the tensor. <ide> ''' <ide> if not hasattr(tensor, '_keras_history'): <del> raise Exception('Tensor must be a Keras tensor. Found: ' + str(tensor)) <add> return tensor <ide> <ide> if layer is None or node_index: <ide> layer, node_index, _ = tensor._keras_history
7
Javascript
Javascript
fix timing issue in signal test
10a9c005630b53a015a03bb813dbf4263fe78b5a
<ide><path>test/fixtures/should_exit.js <ide> process.removeListener('SIGINT', tmp); <ide> setInterval(function() { <ide> process.stdout.write('keep alive\n'); <ide> }, 1000); <add>process.stdout.write('start\n'); <ide><path>test/sequential/test-signal-unregister.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <add>var spawn = require('child_process').spawn; <ide> <del>var childKilled = false, done = false, <del> spawn = require('child_process').spawn, <del> util = require('util'), <del> child; <del> <del>var join = require('path').join; <del> <del>child = spawn(process.argv[0], [join(common.fixturesDir, 'should_exit.js')]); <del>child.on('exit', function() { <del> if (!done) childKilled = true; <del>}); <del> <del>setTimeout(function() { <del> console.log('Sending SIGINT'); <add>var child = spawn(process.argv[0], [common.fixturesDir + '/should_exit.js']); <add>child.stdout.once('data', function() { <ide> child.kill('SIGINT'); <del> setTimeout(function() { <del> console.log('Chance has been given to die'); <del> done = true; <del> if (!childKilled) { <del> // Cleanup <del> console.log('Child did not die on SIGINT, sending SIGTERM'); <del> child.kill('SIGTERM'); <del> } <del> }, 200); <del>}, 200); <del> <del>process.on('exit', function() { <del> assert.ok(childKilled); <ide> }); <add>child.on('exit', common.mustCall(function(exitCode, signalCode) { <add> assert.equal(exitCode, null); <add> assert.equal(signalCode, 'SIGINT'); <add>}));
2
Javascript
Javascript
use process._rawdebug() during setup
d32f769d75dc31773ad34b5c28ddefd2dbd84a57
<ide><path>lib/internal/process/coverage.js <ide> exports.writeCoverage = writeCoverage; <ide> function setup() { <ide> const { Connection } = internalBinding('inspector'); <ide> if (!Connection) { <del> console.warn('inspector not enabled'); <add> process._rawDebug('inspector not enabled'); <ide> return; <ide> } <ide> <ide> function setup() { <ide> coverageDirectory = process.env.NODE_V8_COVERAGE = <ide> resolve(process.env.NODE_V8_COVERAGE); <ide> } catch (err) { <del> console.error(err); <add> process._rawDebug(err.toString()); <ide> } <ide> } <ide>
1
Text
Text
add the valid link for curl(1) in repl.md
f5011786ba6352e265b24dcbf19c418885735e2a
<ide><path>doc/api/repl.md <ide> undefined <ide> ``` <ide> <ide> Unless otherwise scoped within blocks or functions, variables declared <del>either implicitly, or using the `const`, `let`, or `var` keywords <add>either implicitly or using the `const`, `let`, or `var` keywords <ide> are declared at the global scope. <ide> <ide> #### Global and Local Scope <ide> possible to connect to a long-running Node.js process without restarting it. <ide> For an example of running a "full-featured" (`terminal`) REPL over <ide> a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310 <ide> <del>For an example of running a REPL instance over curl(1), <add>For an example of running a REPL instance over [curl(1)][], <ide> see: https://gist.github.com/2053342 <ide> <ide> [stream]: stream.html <ide> [`util.inspect()`]: util.html#util_util_inspect_object_options <ide> [`readline.Interface`]: readline.html#readline_class_interface <ide> [`readline.InterfaceCompleter`]: readline.html#readline_use_of_the_completer_function <add>[curl(1)]: https://curl.haxx.se/docs/manpage.html
1
Java
Java
improve reactive support for access to principal
99cacaa72d075e86f458186e178348e6175bbfce
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/PrincipalArgumentResolver.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.web.reactive.result.method.annotation; <add> <add>import java.security.Principal; <add> <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.web.reactive.result.method.BindingContext; <add>import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver; <add>import org.springframework.web.server.ServerWebExchange; <add> <add>/** <add> * Resolves method argument value of type {@link java.security.Principal}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 5.0 <add> * @see ServerWebExchangeArgumentResolver <add> */ <add>public class PrincipalArgumentResolver implements HandlerMethodArgumentResolver { <add> <add> @Override <add> public boolean supportsParameter(MethodParameter parameter) { <add> return (Principal.class.isAssignableFrom(parameter.getParameterType())); <add> } <add> <add> @Override <add> public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext context, <add> ServerWebExchange exchange) { <add> <add> Class<?> paramType = parameter.getParameterType(); <add> if (Principal.class.isAssignableFrom(paramType)) { <add> return exchange.getPrincipal().cast(Object.class); <add> } <add> else { <add> // should never happen... <add> throw new IllegalArgumentException( <add> "Unknown parameter type: " + paramType + " in method: " + parameter.getMethod()); <add> } <add> } <add> <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerAdapter.java <ide> protected List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() { <ide> resolvers.add(new HttpEntityArgumentResolver(getMessageReaders(), getReactiveAdapterRegistry())); <ide> resolvers.add(new ModelArgumentResolver()); <ide> resolvers.add(new ServerWebExchangeArgumentResolver()); <add> resolvers.add(new PrincipalArgumentResolver()); <ide> resolvers.add(new WebSessionArgumentResolver()); <ide> <ide> // Custom resolvers <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeArgumentResolver.java <ide> * <ul> <ide> * <li>{@link ServerWebExchange} <ide> * <li>{@link ServerHttpRequest} <del> * <li>{@link HttpMethod} <ide> * <li>{@link ServerHttpResponse} <add> * <li>{@link HttpMethod} <ide> * </ul> <ide> * <del> * <p>For the {@code WebSession} see {@link WebSessionArgumentResolver}. <add> * <p>For the {@code WebSession} see {@link WebSessionArgumentResolver} <add> * and for the {@code Principal} see {@link PrincipalArgumentResolver}. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> * @see WebSessionArgumentResolver <add> * @see PrincipalArgumentResolver <ide> */ <ide> public class ServerWebExchangeArgumentResolver implements SyncHandlerMethodArgumentResolver { <ide> <ide> public Optional<Object> resolveArgumentValue(MethodParameter parameter, BindingC <ide> ServerWebExchange exchange) { <ide> <ide> Class<?> paramType = parameter.getParameterType(); <del> Object value; <ide> if (ServerWebExchange.class.isAssignableFrom(paramType)) { <del> value = exchange; <add> return Optional.of(exchange); <ide> } <ide> else if (ServerHttpRequest.class.isAssignableFrom(paramType)) { <del> value = exchange.getRequest(); <add> return Optional.of(exchange.getRequest()); <ide> } <ide> else if (ServerHttpResponse.class.isAssignableFrom(paramType)) { <del> value = exchange.getResponse(); <add> return Optional.of(exchange.getResponse()); <ide> } <ide> else if (HttpMethod.class == paramType) { <del> value = exchange.getRequest().getMethod(); <add> return Optional.of(exchange.getRequest().getMethod()); <ide> } <ide> else { <ide> // should never happen... <ide> throw new IllegalArgumentException( <ide> "Unknown parameter type: " + paramType + " in method: " + parameter.getMethod()); <ide> } <del> return Optional.of(value); <ide> } <ide> <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/server/DefaultServerWebExchangeMutativeBuilder.java <ide> package org.springframework.web.server; <ide> <ide> import java.security.Principal; <del>import java.util.Optional; <ide> <ide> import reactor.core.publisher.Mono; <ide> <ide> class DefaultServerWebExchangeMutativeBuilder implements ServerWebExchange.Mutat <ide> <ide> private ServerHttpResponse response; <ide> <del> private Principal user; <add> private Mono<Principal> user; <ide> <ide> private Mono<WebSession> session; <ide> <ide> public ServerWebExchange.MutativeBuilder setResponse(ServerHttpResponse response <ide> } <ide> <ide> @Override <del> public ServerWebExchange.MutativeBuilder setPrincipal(Principal user) { <add> public ServerWebExchange.MutativeBuilder setPrincipal(Mono<Principal> user) { <ide> this.user = user; <ide> return this; <ide> } <ide> private static class MutativeDecorator extends ServerWebExchangeDecorator { <ide> <ide> private final ServerHttpResponse response; <ide> <del> private final Principal user; <add> private final Mono<Principal> userMono; <ide> <ide> private final Mono<WebSession> session; <ide> <ide> private final Mono<MultiValueMap<String, String>> formData; <ide> <ide> <ide> public MutativeDecorator(ServerWebExchange delegate, <del> ServerHttpRequest request, ServerHttpResponse response, Principal user, <add> ServerHttpRequest request, ServerHttpResponse response, Mono<Principal> user, <ide> Mono<WebSession> session, Mono<MultiValueMap<String, String>> formData) { <ide> <ide> super(delegate); <ide> this.request = request; <ide> this.response = response; <del> this.user = user; <add> this.userMono = user; <ide> this.session = session; <ide> this.formData = formData; <ide> } <ide> public Mono<WebSession> getSession() { <ide> <ide> @SuppressWarnings("unchecked") <ide> @Override <del> public <T extends Principal> Optional<T> getPrincipal() { <del> return (this.user != null ? Optional.of((T) this.user) : getDelegate().getPrincipal()); <add> public <T extends Principal> Mono<T> getPrincipal() { <add> return (this.userMono != null ? (Mono<T>) this.userMono : getDelegate().getPrincipal()); <ide> } <ide> <ide> @Override <ide><path>spring-web/src/main/java/org/springframework/web/server/ServerWebExchange.java <ide> public interface ServerWebExchange { <ide> /** <ide> * Return the authenticated user for the request, if any. <ide> */ <del> <T extends Principal> Optional<T> getPrincipal(); <add> <T extends Principal> Mono<T> getPrincipal(); <ide> <ide> /** <ide> * Return the form data from the body of the request or an empty {@code Mono} <ide> interface MutativeBuilder { <ide> /** <ide> * Set the principal to use. <ide> */ <del> MutativeBuilder setPrincipal(Principal user); <add> MutativeBuilder setPrincipal(Mono<Principal> user); <ide> <ide> /** <ide> * Set the session to use. <ide><path>spring-web/src/main/java/org/springframework/web/server/ServerWebExchangeDecorator.java <ide> public Mono<WebSession> getSession() { <ide> } <ide> <ide> @Override <del> public <T extends Principal> Optional<T> getPrincipal() { <add> public <T extends Principal> Mono<T> getPrincipal() { <ide> return getDelegate().getPrincipal(); <ide> } <ide> <ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/DefaultServerWebExchange.java <ide> public Mono<WebSession> getSession() { <ide> } <ide> <ide> @Override <del> public <T extends Principal> Optional<T> getPrincipal() { <del> return Optional.empty(); <add> public <T extends Principal> Mono<T> getPrincipal() { <add> return Mono.empty(); <ide> } <ide> <ide> @Override
7
Python
Python
fix the tokenization warning noted in
c4734840876155a0f6c46f7100a486dfc7c78add
<ide><path>src/transformers/tokenization_utils.py <ide> def _batch_prepare_for_model( <ide> first_ids, <ide> second_ids, <ide> add_special_tokens=add_special_tokens, <del> padding_strategy=PaddingStrategy.DO_NOT_PAD, # we pad in batch afterward <del> truncation_strategy=truncation_strategy, <add> padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward <add> truncation=truncation_strategy.value, <ide> max_length=max_length, <ide> stride=stride, <ide> pad_to_multiple_of=None, # we pad in batch afterward
1
PHP
PHP
add array pull and array forget tests
cebc939e8ea6a5a17921b729333808a9bc8e814b
<ide><path>tests/Support/SupportArrTest.php <ide> public function testPull() <ide> $name = Arr::pull($array, 'name'); <ide> $this->assertEquals('Desk', $name); <ide> $this->assertEquals(['price' => 100], $array); <add> <add> // Only works on first level keys <add> $array = ['joe@example.com' => 'Joe', 'jane@localhost' => 'Jane']; <add> $name = Arr::pull($array, 'joe@example.com'); <add> $this->assertEquals('Joe', $name); <add> $this->assertEquals(['jane@localhost' => 'Jane'], $array); <add> <add> // Does not work for nested keys <add> $array = ['emails' => ['joe@example.com' => 'Joe', 'jane@localhost' => 'Jane']]; <add> $name = Arr::pull($array, 'emails.joe@example.com'); <add> $this->assertEquals(null, $name); <add> $this->assertEquals(['emails' => ['joe@example.com' => 'Joe', 'jane@localhost' => 'Jane']], $array); <ide> } <ide> <ide> public function testSet() <ide> public function testForget() <ide> $array = ['products' => ['desk' => ['price' => 50], null => 'something']]; <ide> Arr::forget($array, ['products.amount.all', 'products.desk.price']); <ide> $this->assertEquals(['products' => ['desk' => [], null => 'something']], $array); <add> <add> // Only works on first level keys <add> $array = ['joe@example.com' => 'Joe', 'jane@example.com' => 'Jane']; <add> Arr::forget($array, 'joe@example.com'); <add> $this->assertEquals(['jane@example.com' => 'Jane'], $array); <add> <add> // Does not work for nested keys <add> $array = ['emails' => ['joe@example.com' => ['name' => 'Joe'], 'jane@localhost' => ['name' => 'Jane']]]; <add> Arr::forget($array, ['emails.joe@example.com','emails.jane@localhost']); <add> $this->assertEquals(['emails' => ['joe@example.com' => ['name' => 'Joe']]], $array); <ide> } <ide> }
1
PHP
PHP
enable strict typing for view tests
5b3f8205ed32d71cde70b257731b961af39bed55
<ide><path>src/View/View.php <ide> public function getTemplate(): string <ide> * Set the name of the template file to render. The name specified is the <ide> * filename in /src/Template/<SubFolder> without the .ctp extension. <ide> * <del> * @param string $name Template file name to set. <add> * @param string|false $name Template file name to set. <ide> * @return $this <ide> */ <del> public function setTemplate(string $name): self <add> public function setTemplate($name): self <ide> { <ide> $this->template = $name; <ide> <ide> public function getLayout() <ide> * The name specified is the filename of the layout in /src/Template/Layout <ide> * without the .ctp extension. <ide> * <del> * @param string $name Layout file name to set. <add> * @param string|bool $name Layout file name to set. <ide> * @return $this <ide> */ <del> public function setLayout(string $name): self <add> public function setLayout($name): self <ide> { <ide> $this->layout = $name; <ide> <ide><path>tests/TestCase/View/CellTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Form/ArrayContextTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Form/FormContextTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Helper/BreadcrumbsHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Helper/FlashHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function testScriptTimestamping() <ide> Configure::write('Asset.timestamp', true); <ide> <ide> touch(WWW_ROOT . 'js/__cake_js_test.js'); <del> $timestamp = substr(strtotime('now'), 0, 8); <add> $timestamp = substr((string)strtotime('now'), 0, 8); <ide> <ide> $result = $this->Html->script('__cake_js_test', ['once' => false]); <ide> $this->assertRegExp('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <ide> public function testPluginScriptTimestamping() <ide> Configure::write('Asset.timestamp', true); <ide> <ide> touch($pluginJsPath . DS . '__cake_js_test.js'); <del> $timestamp = substr(strtotime('now'), 0, 8); <add> $timestamp = substr((string)strtotime('now'), 0, 8); <ide> <ide> $result = $this->Html->script('TestPlugin.__cake_js_test', ['once' => false]); <ide> $this->assertRegExp('/test_plugin\/js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <ide><path>tests/TestCase/View/Helper/NumberHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * NumberHelperTest file <ide> * <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Helper/TextHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Helper/TimeHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function testIsThisMonth() <ide> { <ide> $result = $this->Time->isThisMonth('+0 day'); <ide> $this->assertTrue($result); <del> $result = $this->Time->isThisMonth($time = mktime(0, 0, 0, date('m'), mt_rand(1, 28), date('Y'))); <add> $result = $this->Time->isThisMonth($time = mktime(0, 0, 0, (int)date('m'), mt_rand(1, 28), (int)date('Y'))); <ide> $this->assertTrue($result); <del> $result = $this->Time->isThisMonth(mktime(0, 0, 0, date('m'), mt_rand(1, 28), date('Y') - mt_rand(1, 12))); <add> $result = $this->Time->isThisMonth(mktime(0, 0, 0, (int)date('m'), mt_rand(1, 28), date('Y') - mt_rand(1, 12))); <ide> $this->assertFalse($result); <del> $result = $this->Time->isThisMonth(mktime(0, 0, 0, date('m'), mt_rand(1, 28), date('Y') + mt_rand(1, 12))); <add> $result = $this->Time->isThisMonth(mktime(0, 0, 0, (int)date('m'), mt_rand(1, 28), date('Y') + mt_rand(1, 12))); <ide> $this->assertFalse($result); <ide> } <ide> <ide> public function testIsThisYear() <ide> { <ide> $result = $this->Time->isThisYear('+0 day'); <ide> $this->assertTrue($result); <del> $result = $this->Time->isThisYear(mktime(0, 0, 0, mt_rand(1, 12), mt_rand(1, 28), date('Y'))); <add> $result = $this->Time->isThisYear(mktime(0, 0, 0, mt_rand(1, 12), mt_rand(1, 28), (int)date('Y'))); <ide> $this->assertTrue($result); <ide> } <ide> <ide><path>tests/TestCase/View/Helper/UrlHelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/HelperRegistryTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/HelperTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * HelperTest file <ide> * <ide><path>tests/TestCase/View/JsonViewTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * JsonViewTest file <ide> * <ide><path>tests/TestCase/View/StringTemplateTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/StringTemplateTraitTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/ViewBuilderTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/ViewTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/ViewVarsTraitTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/BasicWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/ButtonWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/CheckboxWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/FileWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/LabelWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/MultiCheckboxWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/RadioWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/SelectBoxWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/TextareaWidgetTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/Widget/WidgetLocatorTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/View/XmlViewTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * XmlViewTest file <ide> *
34
Javascript
Javascript
improve docs for container / registry
a5fe52c575f09b38a5b9b133d8b24b206cfe13e2
<ide><path>packages/container/lib/container.js <ide> import Ember from 'ember-metal/core'; // Ember.assert <ide> import emberKeys from "ember-metal/keys"; <ide> import dictionary from 'ember-metal/dictionary'; <ide> <del>// A lightweight container that helps to assemble and decouple components. <del>// Public api for the container is still in flux. <del>// The public api, specified on the application namespace should be considered the stable api. <add>/** <add> A lightweight container used to instantiate and cache objects. <add> <add> Every `Container` must be associated with a `Registry`, which is referenced <add> to determine the factory and options that should be used to instantiate <add> objects. <add> <add> The public API for `Container` is still in flux and should not be considered <add> stable. <add> <add> @private <add> @class Container <add> */ <ide> function Container(options) { <ide> Ember.assert("A Registry instance must be passed as an option when constructing a Container.", options && options.registry); <ide> <ide><path>packages/container/lib/registry.js <ide> import dictionary from 'ember-metal/dictionary'; <ide> <ide> var VALID_FULL_NAME_REGEXP = /^[^:]+.+:[^:]+$/; <ide> <del>// A lightweight registry that helps to assemble and decouple components. <del>// Public api for the registry is still in flux. <del>// The public api, specified on the application namespace should be considered the stable api. <add>/** <add> A lightweight registry used to store factory and option information keyed <add> by type. <add> <add> A `Registry` stores the factory and option information needed by a <add> `Container` to instantiate and cache objects. <add> <add> The public API for `Registry` is still in flux and should not be considered <add> stable. <add> <add> @private <add> @class Registry <add>*/ <ide> function Registry(options) { <ide> options = options || {}; <ide> <ide> Registry.prototype = { <ide> <ide> ```javascript <ide> var registry = new Registry(); <add> var container = new Container({registry: registry}); <ide> <ide> // if all of type `connection` must not be singletons <ide> registry.optionsForType('connection', { singleton: false }); <ide> <ide> registry.register('connection:twitter', TwitterConnection); <ide> registry.register('connection:facebook', FacebookConnection); <ide> <del> var twitter = registry.lookup('connection:twitter'); <del> var twitter2 = registry.lookup('connection:twitter'); <add> var twitter = container.lookup('connection:twitter'); <add> var twitter2 = container.lookup('connection:twitter'); <ide> <ide> twitter === twitter2; // => false <ide> <del> var facebook = registry.lookup('connection:facebook'); <del> var facebook2 = registry.lookup('connection:facebook'); <add> var facebook = container.lookup('connection:facebook'); <add> var facebook2 = container.lookup('connection:facebook'); <ide> <ide> facebook === facebook2; // => false <ide> ``` <ide> Registry.prototype = { <ide> <ide> ```javascript <ide> var registry = new Registry(); <add> var container = new Container({registry: registry}); <ide> <ide> registry.register('router:main', Router); <ide> registry.register('controller:user', UserController); <ide> registry.register('controller:post', PostController); <ide> <ide> registry.typeInjection('controller', 'router', 'router:main'); <ide> <del> var user = registry.lookup('controller:user'); <del> var post = registry.lookup('controller:post'); <add> var user = container.lookup('controller:user'); <add> var post = container.lookup('controller:post'); <ide> <ide> user.router instanceof Router; //=> true <ide> post.router instanceof Router; //=> true <ide> Registry.prototype = { <ide> typeInjection: function(type, property, fullName) { <ide> Ember.assert('fullName must be a proper full name', this.validateFullName(fullName)); <ide> <del> // if (this.parent) { illegalChildOperation('typeInjection'); } <del> <ide> var fullNameType = fullName.split(':')[0]; <ide> if (fullNameType === type) { <ide> throw new Error('Cannot inject a `' + fullName + <ide> Registry.prototype = { <ide> <ide> ```javascript <ide> var registry = new Registry(); <add> var container = new Container({registry: registry}); <ide> <ide> registry.register('source:main', Source); <ide> registry.register('model:user', User); <ide> Registry.prototype = { <ide> // injecting one fullName on another type <ide> registry.injection('model', 'source', 'source:main'); <ide> <del> var user = registry.lookup('model:user'); <del> var post = registry.lookup('model:post'); <add> var user = container.lookup('model:user'); <add> var post = container.lookup('model:post'); <ide> <ide> user.source instanceof Source; //=> true <ide> post.source instanceof Source; //=> true <ide> Registry.prototype = { <ide> @param {String} injectionName <ide> */ <ide> injection: function(fullName, property, injectionName) { <del> // if (this.parent) { illegalChildOperation('injection'); } <del> <ide> this.validateFullName(injectionName); <ide> var normalizedInjectionName = this.normalize(injectionName); <ide> <ide> Registry.prototype = { <ide> <ide> ```javascript <ide> var registry = new Registry(); <add> var container = new Container({registry: registry}); <ide> <ide> registry.register('store:main', Store); <ide> registry.register('store:secondary', OtherStore); <ide> Registry.prototype = { <ide> // injecting one fullName on another fullName <ide> registry.factoryInjection('model:post', 'secondaryStore', 'store:secondary'); <ide> <del> var UserFactory = registry.lookupFactory('model:user'); <del> var PostFactory = registry.lookupFactory('model:post'); <del> var store = registry.lookup('store:main'); <add> var UserFactory = container.lookupFactory('model:user'); <add> var PostFactory = container.lookupFactory('model:post'); <add> var store = container.lookup('store:main'); <ide> <ide> UserFactory.store instanceof Store; //=> true <ide> UserFactory.secondaryStore instanceof OtherStore; //=> false
2
Text
Text
add error type to package version doc
c24475c2c84b49eea2ed15b19959ce4dfd1efff2
<ide><path>docs/apm-rest-api.md <ide> name. <ide> #### Returns <ide> <ide> - **201** - Successfully created. Returns created version. <del>- **400** - Git tag not found / Repository inaccessible <add>- **400** - Git tag not found / Repository inaccessible / package.json invalid <ide> - **409** - Version exists <ide> <ide> ### Deleting a version
1
PHP
PHP
apply fixes from styleci
0218f6b829ef31193565c895e9b67dfcad9e765c
<ide><path>tests/Queue/QueueSqsQueueTest.php <ide> public function testGetQueueProperlyResolvesUrlWithPrefix() <ide> public function testGetQueueProperlyResolvesFifoUrlWithPrefix() <ide> { <ide> $this->queueName = 'emails.fifo'; <del> $this->queueUrl = $this->prefix . $this->queueName; <add> $this->queueUrl = $this->prefix.$this->queueName; <ide> $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); <ide> $this->assertEquals($this->queueUrl, $queue->getQueue(null)); <del> $queueUrl = $this->baseUrl . '/' . $this->account . '/test.fifo'; <add> $queueUrl = $this->baseUrl.'/'.$this->account.'/test.fifo'; <ide> $this->assertEquals($queueUrl, $queue->getQueue('test.fifo')); <ide> } <ide> <ide> public function testGetQueueProperlyResolvesUrlWithoutPrefix() <ide> public function testGetQueueProperlyResolvesFifoUrlWithoutPrefix() <ide> { <ide> $this->queueName = 'emails.fifo'; <del> $this->queueUrl = $this->prefix . $this->queueName; <add> $this->queueUrl = $this->prefix.$this->queueName; <ide> $queue = new SqsQueue($this->sqs, $this->queueUrl); <ide> $this->assertEquals($this->queueUrl, $queue->getQueue(null)); <del> $fifoQueueUrl = $this->baseUrl . '/' . $this->account . '/test.fifo'; <add> $fifoQueueUrl = $this->baseUrl.'/'.$this->account.'/test.fifo'; <ide> $this->assertEquals($fifoQueueUrl, $queue->getQueue($fifoQueueUrl)); <ide> } <ide> <ide> public function testGetQueueProperlyResolvesFifoUrlWithSuffix() <ide> $this->queueName = 'emails.fifo'; <ide> $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix, $suffix = '-staging'); <ide> $this->assertEquals("{$this->prefix}emails-staging.fifo", $queue->getQueue(null)); <del> $queueUrl = $this->baseUrl . '/' . $this->account . '/test' . $suffix . '.fifo'; <add> $queueUrl = $this->baseUrl.'/'.$this->account.'/test'.$suffix.'.fifo'; <ide> $this->assertEquals($queueUrl, $queue->getQueue('test.fifo')); <ide> } <ide> <ide> public function testGetFifoQueueEnsuresTheQueueIsOnlySuffixedOnce() <ide> { <ide> $queue = new SqsQueue($this->sqs, "{$this->queueName}-staging.fifo", $this->prefix, $suffix = '-staging'); <ide> $this->assertEquals("{$this->prefix}{$this->queueName}{$suffix}.fifo", $queue->getQueue(null)); <del> $queueUrl = $this->baseUrl . '/' . $this->account . '/test' . $suffix . '.fifo'; <add> $queueUrl = $this->baseUrl.'/'.$this->account.'/test'.$suffix.'.fifo'; <ide> $this->assertEquals($queueUrl, $queue->getQueue('test-staging.fifo')); <ide> } <ide> }
1
Javascript
Javascript
reduce loop times for preventing test from timeout
a506aa76a8cfb6438a0b4bc7604623bc6518a7c9
<ide><path>test/parallel/test-vm-break-on-sigint.js <ide> if (!process.env.HAS_STARTED_WORKER) { <ide> } <ide> } else { <ide> const ctx = vm.createContext({}); <del> for (let i = 0; i < 10000; i++) { <add> for (let i = 0; i < 100; i++) { <ide> vm.runInContext('console.log(1)', ctx, { breakOnSigint: true }); <ide> } <ide> }
1
Mixed
Python
review the docs
3a666b497db59491d71ce671e3b01af90332e8b9
<ide><path>docs/templates/backend.md <ide> If you want the Keras modules you write to be compatible with both Theano (`th`) <ide> <ide> You can import the backend module via: <ide> ```python <del>*from keras import backend as K* <add>from keras import backend as K <ide> ``` <ide> <ide> The code below instantiates an input placeholder. It's equivalent to `tf.placeholder()` or `th.tensor.matrix()`, `th.tensor.tensor3()`, etc. <ide><path>docs/templates/constraints.md <ide> <ide> Functions from the `constraints` module allow setting constraints (eg. non-negativity) on network parameters during optimization. <ide> <del>The penalties are applied on a per-layer basis. The exact API will depend on the layer, but the layers `Dense`, `Convolution1D`, `Convolution2D` and `Convolution3D` have a unified API. <add>The penalties are applied on a per-layer basis. The exact API will depend on the layer, but the layers `Dense`, `Conv1D`, `Conv2D` and `Conv3D` have a unified API. <ide> <ide> These layers expose 2 keyword arguments: <ide> <ide><path>docs/templates/getting-started/sequential-model-guide.md <ide> from keras.models import Sequential <ide> from keras.layers import Dense, Activation <ide> <ide> model = Sequential([ <del> Dense(32, input_dim=784), <add> Dense(32, input_shape=(784,)), <ide> Activation('relu'), <ide> Dense(10), <ide> Activation('softmax'), <ide><path>keras/initializers.py <ide> def from_config(cls, config): <ide> <ide> <ide> class Zeros(Initializer): <del> """Initializer that generates tensors initialized to 0.""" <add> """Initializer that generates tensors initialized to 0. <add> """ <ide> <ide> def __call__(self, shape, dtype=None): <ide> return K.constant(0, shape=shape, dtype=dtype) <ide> <ide> <ide> class Ones(Initializer): <del> """Initializer that generates tensors initialized to 1.""" <add> """Initializer that generates tensors initialized to 1. <add> """ <ide> <ide> def __call__(self, shape, dtype=None): <ide> return K.constant(1, shape=shape, dtype=dtype) <ide> def get_config(self): <ide> class TruncatedNormal(Initializer): <ide> """Initializer that generates a truncated normal distribution. <ide> <del> These values are similar to values from a `random_normal_initializer` <add> These values are similar to values from a `RandomNormal` <ide> except that values more than two standard deviations from the mean <ide> are discarded and re-drawn. This is the recommended initializer for <ide> neural network weights and filters. <ide> class VarianceScaling(Initializer): <ide> <ide> With `distribution="normal"`, samples are drawn from a truncated normal <ide> distribution centered on zero, with `stddev = sqrt(scale / n)` where n is: <add> <ide> - number of input units in the weight tensor, if mode = "fan_in" <ide> - number of output units, if mode = "fan_out" <ide> - average of the numbers of input and output units, if mode = "fan_avg" <ide><path>keras/layers/core.py <ide> class Dropout(Layer): <ide> """Applies Dropout to the input. <ide> <ide> Dropout consists in randomly setting <del> a fraction `p` of input units to 0 at each update during training time, <add> a fraction `rate` of input units to 0 at each update during training time, <ide> which helps prevent overfitting. <ide> <ide> # Arguments <ide><path>keras/layers/local.py <ide> class LocallyConnected2D(Layer): <ide> specifying the strides of the convolution along the width and height. <ide> Can be a single integer to specify the same value for <ide> all spatial dimensions. <del> Specifying any stride value != 1 is incompatible with specifying <del> any `dilation_rate` value != 1. <ide> padding: Currently only support `"valid"` (case-insensitive). <ide> `"same"` will be supported in future. <ide> data_format: A string, <ide><path>keras/models.py <ide> def generate_arrays_from_file(path): <ide> # and labels, from each line in the file <ide> x, y = process_line(line) <ide> yield (x, y) <del> f.close() <add> f.close() <ide> <ide> model.fit_generator(generate_arrays_from_file('/my_file.txt'), <ide> samples_per_epoch=10000, epochs=10)
7
Javascript
Javascript
introduce multi-flush logger
f9dec992843c1b695d13067c98a3de06371d2832
<ide><path>Libraries/Utilities/createPerformanceLogger.js <ide> const infoLog = require('./infoLog'); <ide> const performanceNow: () => number = <ide> global.nativeQPLTimestamp ?? global.performance.now.bind(global.performance); <ide> <del>type Timespan = { <add>export type Timespan = { <ide> startTime: number, <ide> endTime?: number, <ide> totalTime?: number, <ide> type Timespan = { <ide> }; <ide> <ide> // Extra values should be serializable primitives <del>type ExtraValue = number | string | boolean; <add>export type ExtraValue = number | string | boolean; <ide> <del>type Extras = {[key: string]: ExtraValue}; <add>export type Extras = {[key: string]: ExtraValue}; <ide> <ide> export interface IPerformanceLogger { <ide> addTimespan(
1
PHP
PHP
get default connection name on null reconnect
fce4751277c823539d088add456a2f6a45bbc30b
<ide><path>src/Illuminate/Database/DatabaseManager.php <ide> public function connection($name = null) <ide> */ <ide> public function reconnect($name = null) <ide> { <add> $name = $name ?: $this->getDefaultConnection(); <add> <ide> unset($this->connections[$name]); <ide> <ide> return $this->connection($name);
1
Javascript
Javascript
add missing await in fs-rm/fs-rmdir tests
6b9d2aefdb01888fe33a67807974c0ea9f5bd0d6
<ide><path>test/parallel/test-fs-rm.js <ide> function removeAsync(dir) { <ide> makeNonEmptyDirectory(4, 10, 2, dir, true); <ide> <ide> // Removal should fail without the recursive option set to true. <del> assert.rejects(fs.promises.rm(dir), { syscall: 'rm' }); <del> assert.rejects(fs.promises.rm(dir, { recursive: false }), { <add> await assert.rejects(fs.promises.rm(dir), { syscall: 'rm' }); <add> await assert.rejects(fs.promises.rm(dir, { recursive: false }), { <ide> syscall: 'rm' <ide> }); <ide> <ide> // Recursive removal should succeed. <ide> await fs.promises.rm(dir, { recursive: true }); <ide> <ide> // Attempted removal should fail now because the directory is gone. <del> assert.rejects(fs.promises.rm(dir), { syscall: 'stat' }); <add> await assert.rejects(fs.promises.rm(dir), { syscall: 'stat' }); <ide> <ide> // Should fail if target does not exist <del> assert.rejects(fs.promises.rm( <add> await assert.rejects(fs.promises.rm( <ide> path.join(tmpdir.path, 'noexist.txt'), <ide> { recursive: true } <ide> ), { <ide> function removeAsync(dir) { <ide> }); <ide> <ide> // Should not fail if target does not exist and force option is true <del> fs.promises.rm(path.join(tmpdir.path, 'noexist.txt'), { force: true }); <add> await fs.promises.rm(path.join(tmpdir.path, 'noexist.txt'), { force: true }); <ide> <ide> // Should delete file <ide> const filePath = path.join(tmpdir.path, 'rm-promises-file.txt'); <ide><path>test/parallel/test-fs-rmdir-recursive.js <ide> function removeAsync(dir) { <ide> makeNonEmptyDirectory(4, 10, 2, dir, true); <ide> <ide> // Removal should fail without the recursive option set to true. <del> assert.rejects(fs.promises.rmdir(dir), { syscall: 'rmdir' }); <del> assert.rejects(fs.promises.rmdir(dir, { recursive: false }), { <add> await assert.rejects(fs.promises.rmdir(dir), { syscall: 'rmdir' }); <add> await assert.rejects(fs.promises.rmdir(dir, { recursive: false }), { <ide> syscall: 'rmdir' <ide> }); <ide> <ide> function removeAsync(dir) { <ide> { code: 'ENOENT' }); <ide> <ide> // Attempted removal should fail now because the directory is gone. <del> assert.rejects(fs.promises.rmdir(dir), { syscall: 'rmdir' }); <add> await assert.rejects(fs.promises.rmdir(dir), { syscall: 'rmdir' }); <ide> })().then(common.mustCall()); <ide> <ide> // Test input validation.
2
Javascript
Javascript
use new configuration in react-native public cli
a32620dc3b7a0ebd53feeaf7794051705d80f49e
<ide><path>local-cli/bundle/buildBundle.js <ide> const log = require('../util/log').out('bundle'); <ide> /* $FlowFixMe(site=react_native_oss) */ <ide> const Server = require('metro/src/Server'); <ide> <del>const {convert} = require('metro-config'); <del> <ide> /* $FlowFixMe(site=react_native_oss) */ <ide> const outputBundle = require('metro/src/shared/output/bundle'); <add>const {convert} = require('metro-config'); <ide> const path = require('path'); <ide> const saveAssets = require('./saveAssets'); <ide> <del>const {ASSET_REGISTRY_PATH} = require('../core/Constants'); <del> <ide> import type {RequestOptions, OutputOptions} from './types.flow'; <ide> import type {ConfigT} from 'metro-config/src/configTypes.flow'; <ide> <ide> async function buildBundle( <ide> sourceMapUrl = path.basename(sourceMapUrl); <ide> } <ide> <add> config.transformModulePath = args.transformer <add> ? path.resolve(args.transformer) <add> : config.transformModulePath; <add> <ide> const requestOpts: RequestOptions = { <ide> entryFile: args.entryFile, <ide> sourceMapUrl, <ide> async function buildBundle( <ide> platform: args.platform, <ide> }; <ide> <del> const transformModulePath = args.transformer <del> ? path.resolve(args.transformer) <del> : config.transformModulePath; <del> <del> config.transformModulePath = transformModulePath; <del> config.transformer.assetRegistryPath = ASSET_REGISTRY_PATH; <del> <ide> const {serverOptions} = convert.convertNewToOld(config); <ide> <ide> const server = new Server(serverOptions); <ide><path>local-cli/cliEntry.js <ide> <ide> 'use strict'; <ide> <del>const config = require('./core'); <add>const {configPromise} = require('./core'); <ide> <ide> const assertRequiredOptions = require('./util/assertRequiredOptions'); <ide> /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error <ide> const addCommand = (command: CommandT, cfg: RNConfig) => { <ide> cmd.option('--config [string]', 'Path to the CLI configuration file'); <ide> }; <ide> <del>function run() { <add>async function run() { <add> const config = await configPromise; <ide> const setupEnvScript = /^win/.test(process.platform) <ide> ? 'setup_env.bat' <ide> : 'setup_env.sh'; <ide><path>local-cli/core/index.js <ide> const findPlugins = require('./findPlugins'); <ide> const findAssets = require('./findAssets'); <ide> const ios = require('./ios'); <ide> const wrapCommands = require('./wrapCommands'); <add>const {ASSET_REGISTRY_PATH} = require('./Constants'); <ide> <ide> /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error <ide> * found when Flow v0.54 was deployed. To see the error delete this comment and <ide> const minimist = require('minimist'); <ide> const path = require('path'); <ide> <ide> import type {CommandT} from '../commands'; <del>import type {ConfigT} from 'metro'; <add>import type {ConfigT} from 'metro-config/src/configTypes.flow'; <ide> <ide> export type RNConfig = { <ide> ...ConfigT, <ide> /** <ide> * Returns an object with all platform configurations. <ide> */ <ide> getPlatformConfig(): Object, <del> /** <del> * Returns an array of project commands used by the CLI to load <del> */ <del> getProjectCommands(): Array<CommandT>, <ide> /** <ide> * Returns project config from the current working directory <ide> */ <ide> const pluginPlatforms = plugins.platforms.reduce((acc, pathToPlatforms) => { <ide> ); <ide> }, {}); <ide> <del>const defaultRNConfig = { <add>const defaultConfig = { <ide> hasteImplModulePath: require.resolve('../../jest/hasteImpl'), <ide> <ide> getPlatforms(): Array<string> { <ide> const defaultRNConfig = { <ide> getProvidesModuleNodeModules(): Array<string> { <ide> return ['react-native', 'react-native-windows']; <ide> }, <add>}; <ide> <del> getProjectCommands(): Array<CommandT> { <del> const commands = plugins.commands.map(pathToCommands => { <del> const name = pathToCommands.split(path.sep)[0]; <del> <del> return attachPackage( <del> require(path.join(appRoot, 'node_modules', pathToCommands)), <del> require(path.join(appRoot, 'node_modules', name, 'package.json')), <del> ); <del> }); <del> <del> return flatten(commands); <del> }, <del> <add>const defaultRNConfig = { <ide> getPlatformConfig(): Object { <ide> return { <ide> ios, <ide> const defaultRNConfig = { <ide> /** <ide> * Loads the CLI configuration <ide> */ <del>function getCliConfig(): RNConfig { <add>async function getCliConfig(): Promise<RNConfig> { <ide> const cliArgs = minimist(process.argv.slice(2)); <del> const config = <del> cliArgs.config != null <del> ? Config.load(path.resolve(__dirname, cliArgs.config)) <del> : Config.findOptional(__dirname); <add> const config = await Config.load(path.resolve(__dirname, cliArgs.config)); <add> <add> config.transformer.assetRegistryPath = ASSET_REGISTRY_PATH; <add> config.resolver.hasteImplModulePath = defaultConfig.hasteImplModulePath; <add> config.resolver.platforms = defaultConfig.getPlatforms(); <add> config.resolver.providesModuleNodeModules = defaultConfig.getProvidesModuleNodeModules(); <ide> <ide> return {...defaultRNConfig, ...config}; <ide> } <ide> <del>module.exports = getCliConfig(); <add>/** <add> * Returns an array of project commands used by the CLI to load <add> */ <add>function getProjectCommands(): Array<CommandT> { <add> const commands = plugins.commands.map(pathToCommands => { <add> const name = pathToCommands.split(path.sep)[0]; <add> <add> return attachPackage( <add> require(path.join(appRoot, 'node_modules', pathToCommands)), <add> require(path.join(appRoot, 'node_modules', name, 'package.json')), <add> ); <add> }); <add> <add> return flatten(commands); <add>} <add> <add>module.exports.configPromise = getCliConfig(); <add>module.exports.getProjectCommands = getProjectCommands; <ide><path>local-cli/dependencies/dependencies.js <ide> const denodeify = require('denodeify'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> <del>const {ASSET_REGISTRY_PATH} = require('../core/Constants'); <del> <ide> async function dependencies(argv, configPromise, args, packagerInstance) { <ide> const rootModuleAbsolutePath = args.entryFile; <ide> const config = await configPromise; <ide> async function dependencies(argv, configPromise, args, packagerInstance) { <ide> config.transformModulePath = args.transformer <ide> ? path.resolve(args.transformer) <ide> : config.transformModulePath; <del> config.transformer.transformModulePath = ASSET_REGISTRY_PATH; <del> <del> const {serverOptions: packageOpts} = convert.convertNewToOld(config); <ide> <ide> const relativePath = path.relative( <del> packageOpts.projectRoot, <add> config.projectRoot, <ide> rootModuleAbsolutePath, <ide> ); <ide> <ide> async function dependencies(argv, configPromise, args, packagerInstance) { <ide> ? fs.createWriteStream(args.output) <ide> : process.stdout; <ide> <add> const {serverOptions} = convert.convertNewToOld(config); <add> <ide> return Promise.resolve( <ide> (packagerInstance <ide> ? packagerInstance.getOrderedDependencyPaths(options) <del> : Metro.getOrderedDependencyPaths(packageOpts, options) <add> : Metro.getOrderedDependencyPaths(serverOptions, options) <ide> ).then(deps => { <ide> deps.forEach(modulePath => { <ide> // Temporary hack to disable listing dependencies not under this directory. <ide> // Long term, we need either <ide> // (a) JS code to not depend on anything outside this directory, or <ide> // (b) Come up with a way to declare this dependency in Buck. <ide> const isInsideProjectRoots = <del> packageOpts.watchFolders.filter(root => modulePath.startsWith(root)) <add> config.watchFolders.filter(root => modulePath.startsWith(root)) <ide> .length > 0; <ide> <ide> if (isInsideProjectRoots) { <ide><path>local-cli/server/runServer.js <ide> const morgan = require('morgan'); <ide> const path = require('path'); <ide> const webSocketProxy = require('./util/webSocketProxy'); <ide> const MiddlewareManager = require('./middleware/MiddlewareManager'); <del>const {convertOldToNew} = require('metro-config/src/convertConfig'); <ide> <del>const {ASSET_REGISTRY_PATH} = require('../core/Constants'); <del> <del>import type {ConfigT} from 'metro'; <add>import type {ConfigT} from 'metro-config/src/configTypes.flow'; <ide> <ide> export type Args = {| <ide> +assetExts: $ReadOnlyArray<string>, <ide> async function runServer(args: Args, config: ConfigT) { <ide> <ide> args.watchFolders.forEach(middlewareManager.serveStatic); <ide> <add> config.maxWorkers = args.maxWorkers; <add> config.server.port = args.port; <add> config.reporter = reporter; <add> config.server.enhanceMiddleware = middleware => <add> middlewareManager.getConnectInstance().use(middleware); <add> <ide> const serverInstance = await Metro.runServer({ <del> config: convertOldToNew({ <del> config: { <del> ...config, <del> assetRegistryPath: ASSET_REGISTRY_PATH, <del> enhanceMiddleware: middleware => <del> middlewareManager.getConnectInstance().use(middleware), <del> transformModulePath: args.transformer <del> ? path.resolve(args.transformer) <del> : config.getTransformModulePath(), <del> }, <del> maxWorkers: args.maxWorkers, <del> port: args.port, <del> reporter, <del> }), <del> <del> hmrEnabled: true, <add> config, <ide> host: args.host, <ide> secure: args.https, <ide> secureCert: args.cert, <ide><path>local-cli/server/server.js <ide> const runServer = require('./runServer'); <ide> <ide> import type {RNConfig} from '../core'; <del>import type {ConfigT} from 'metro'; <add>import type {ConfigT} from 'metro-config/src/configTypes.flow'; <ide> import type {Args as RunServerArgs} from './runServer'; <ide> <ide> /** <ide> module.exports = { <ide> command: '--projectRoot [string]', <ide> description: 'Specify the main project root', <ide> default: (config: ConfigT) => { <del> return config.getProjectRoot(); <add> return config.projectRoot; <ide> }, <ide> }, <ide> { <ide> module.exports = { <ide> 'Specify any additional folders to be added to the watch list', <ide> parse: (val: string) => val.split(','), <ide> default: (config: ConfigT) => { <del> return config.getWatchFolders(); <add> return config.watchFolders; <ide> }, <ide> }, <ide> { <ide> command: '--assetExts [list]', <ide> description: <ide> 'Specify any additional asset extensions to be used by the packager', <ide> parse: (val: string) => val.split(','), <del> default: (config: ConfigT) => config.getAssetExts(), <add> default: (config: ConfigT) => config.resolver.assetExts, <ide> }, <ide> { <ide> command: '--sourceExts [list]', <ide> description: <ide> 'Specify any additional source extensions to be used by the packager', <ide> parse: (val: string) => val.split(','), <del> default: (config: ConfigT) => config.getSourceExts(), <add> default: (config: ConfigT) => config.resolver.sourceExts, <ide> }, <ide> { <ide> command: '--platforms [list]', <ide> description: <ide> 'Specify any additional platforms to be used by the packager', <ide> parse: (val: string) => val.split(','), <del> default: (config: ConfigT) => config.getPlatforms(), <add> default: (config: ConfigT) => config.resolver.platforms, <ide> }, <ide> { <ide> command: '--providesModuleNodeModules [list]', <ide> description: <ide> 'Specify any npm packages that import dependencies with providesModule', <ide> parse: (val: string) => val.split(','), <ide> default: (config: RNConfig) => { <del> if (typeof config.getProvidesModuleNodeModules === 'function') { <del> return config.getProvidesModuleNodeModules(); <del> } <del> return null; <add> return config.resolver <add> ? config.resolver.providesModuleNodeModules <add> : undefined; <ide> }, <ide> }, <ide> { <ide><path>local-cli/util/Config.js <ide> 'use strict'; <ide> <ide> const findSymlinkedModules = require('./findSymlinkedModules'); <del>const fs = require('fs'); <ide> const getPolyfills = require('../../rn-get-polyfills'); <del>const invariant = require('fbjs/lib/invariant'); <ide> const path = require('path'); <ide> <del>const {Config: MetroConfig, createBlacklist} = require('metro'); <del> <del>const RN_CLI_CONFIG = 'rn-cli.config.js'; <del> <del>import type {ConfigT as MetroConfigT} from 'metro'; <add>const {createBlacklist} = require('metro'); <add>const {loadConfig, mergeConfig} = require('metro-config'); <ide> <ide> /** <ide> * Configuration file of the CLI. <ide> */ <del>export type ConfigT = MetroConfigT; <add>import type {ConfigT} from 'metro-config/src/configTypes.flow'; <ide> <ide> function getProjectPath() { <ide> if ( <ide> const getBlacklistRE = () => { <ide> * hierarchy, an error will be thrown. <ide> */ <ide> const Config = { <del> DEFAULT: ({ <del> ...MetroConfig.DEFAULT, <del> getBlacklistRE, <del> getModulesRunBeforeMainModule: () => [ <del> require.resolve('../../Libraries/Core/InitializeCore'), <del> ], <del> getProjectRoots, <del> getPolyfills, <del> getWatchFolders: () => [getProjectPath()], <del> getResolverMainFields: () => ['react-native', 'browser', 'main'], <del> getTransformModulePath: () => <del> require.resolve('metro/src/reactNativeTransformer'), <del> }: ConfigT), <del> <del> find(startDir: string): ConfigT { <del> return this.findWithPath(startDir).config; <del> }, <del> <del> findWithPath(startDir: string): {config: ConfigT, projectPath: string} { <del> const configPath = findConfigPath(startDir); <del> invariant( <del> configPath, <del> `Can't find "${RN_CLI_CONFIG}" file in any parent folder of "${startDir}"`, <del> ); <del> const projectPath = path.dirname(configPath); <del> return {config: this.load(configPath, startDir), projectPath}; <del> }, <del> <del> findOptional(startDir: string): ConfigT { <del> const configPath = findConfigPath(startDir); <del> return configPath ? this.load(configPath, startDir) : {...Config.DEFAULT}; <add> DEFAULT: { <add> resolver: { <add> resolverMainFields: ['react-native', 'browser', 'main'], <add> blacklistRE: getBlacklistRE(), <add> }, <add> serializer: { <add> getModulesRunBeforeMainModule: () => [ <add> require.resolve('../../Libraries/Core/InitializeCore'), <add> ], <add> getPolyfills, <add> }, <add> <add> watchFolders: [getProjectPath(), ...getProjectRoots()], <add> transformModulePath: require.resolve('metro/src/reactNativeTransformer'), <ide> }, <ide> <ide> getProjectPath, <ide> getProjectRoots, <ide> <del> load(configFile: string): ConfigT { <del> return MetroConfig.load(configFile, Config.DEFAULT); <add> async load(configFile: string): Promise<ConfigT> { <add> const config: ConfigT = await loadConfig({config: configFile}); <add> <add> return mergeConfig(config, this.DEFAULT); <ide> }, <ide> }; <ide> <del>function findConfigPath(cwd: string): ?string { <del> const parentDir = findParentDirectory(cwd, RN_CLI_CONFIG); <del> return parentDir ? path.join(parentDir, RN_CLI_CONFIG) : null; <del>} <del> <del>// Finds the most near ancestor starting at `currentFullPath` that has <del>// a file named `filename` <del>function findParentDirectory(currentFullPath, filename) { <del> const root = path.parse(currentFullPath).root; <del> const testDir = parts => { <del> if (parts.length === 0) { <del> return null; <del> } <del> <del> const fullPath = path.join(root, parts.join(path.sep)); <del> <del> var exists = fs.existsSync(path.join(fullPath, filename)); <del> return exists ? fullPath : testDir(parts.slice(0, -1)); <del> }; <del> <del> return testDir(currentFullPath.substring(root.length).split(path.sep)); <del>} <del> <ide> module.exports = Config;
7
Ruby
Ruby
change method visibility to be private
6568cfd78c89fe70ac7304d03f8f4825fe0b7c72
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def match(path, *rest, &block) <ide> end <ide> end <ide> <del> def get_to_from_path(path, to, action) <del> return to if to || action <del> <del> path_without_format = path.sub(/\(\.:format\)$/, "") <del> if using_match_shorthand?(path_without_format) <del> path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1').tr("-", "_") <del> else <del> nil <del> end <del> end <del> <del> def using_match_shorthand?(path) <del> path =~ %r{^/?[-\w]+/[-\w/]+$} <del> end <del> <del> def decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) # :nodoc: <del> if on = options.delete(:on) <del> send(on) { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } <del> else <del> case @scope.scope_level <del> when :resources <del> nested { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } <del> when :resource <del> member { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } <del> else <del> add_route(path, controller, options, _path, to, via, formatted, anchor, options_constraints) <del> end <del> end <del> end <del> <del> def add_route(action, controller, options, _path, to, via, formatted, anchor, options_constraints) # :nodoc: <del> path = path_for_action(action, _path) <del> raise ArgumentError, "path is required" if path.blank? <del> <del> action = action.to_s <del> <del> default_action = options.delete(:action) || @scope[:action] <del> <del> if action =~ /^[\w\-\/]+$/ <del> default_action ||= action.tr("-", "_") unless action.include?("/") <del> else <del> action = nil <del> end <del> <del> as = if !options.fetch(:as, true) # if it's set to nil or false <del> options.delete(:as) <del> else <del> name_for_action(options.delete(:as), action) <del> end <del> <del> path = Mapping.normalize_path URI.parser.escape(path), formatted <del> ast = Journey::Parser.parse path <del> <del> mapping = Mapping.build(@scope, @set, ast, controller, default_action, to, via, formatted, options_constraints, anchor, options) <del> @set.add_route(mapping, ast, as, anchor) <del> end <del> <ide> # You can specify what Rails should route "/" to with the root method: <ide> # <ide> # root to: 'pages#main' <ide> def map_match(paths, options) <ide> self <ide> end <ide> <add> def get_to_from_path(path, to, action) <add> return to if to || action <add> <add> path_without_format = path.sub(/\(\.:format\)$/, "") <add> if using_match_shorthand?(path_without_format) <add> path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1').tr("-", "_") <add> else <add> nil <add> end <add> end <add> <add> def using_match_shorthand?(path) <add> path =~ %r{^/?[-\w]+/[-\w/]+$} <add> end <add> <add> def decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) # :nodoc: <add> if on = options.delete(:on) <add> send(on) { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } <add> else <add> case @scope.scope_level <add> when :resources <add> nested { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } <add> when :resource <add> member { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } <add> else <add> add_route(path, controller, options, _path, to, via, formatted, anchor, options_constraints) <add> end <add> end <add> end <add> <add> def add_route(action, controller, options, _path, to, via, formatted, anchor, options_constraints) # :nodoc: <add> path = path_for_action(action, _path) <add> raise ArgumentError, "path is required" if path.blank? <add> <add> action = action.to_s <add> <add> default_action = options.delete(:action) || @scope[:action] <add> <add> if action =~ /^[\w\-\/]+$/ <add> default_action ||= action.tr("-", "_") unless action.include?("/") <add> else <add> action = nil <add> end <add> <add> as = if !options.fetch(:as, true) # if it's set to nil or false <add> options.delete(:as) <add> else <add> name_for_action(options.delete(:as), action) <add> end <add> <add> path = Mapping.normalize_path URI.parser.escape(path), formatted <add> ast = Journey::Parser.parse path <add> <add> mapping = Mapping.build(@scope, @set, ast, controller, default_action, to, via, formatted, options_constraints, anchor, options) <add> @set.add_route(mapping, ast, as, anchor) <add> end <add> <ide> def match_root_route(options) <ide> name = has_named_route?(:root) ? nil : :root <ide> args = ["/", { as: name, via: :get }.merge!(options)]
1
Mixed
Python
add filepathfield, update docs
c20a0250dfbcd0b86ffd23f4657cf050ce6a2a2a
<ide><path>docs/api-guide/fields.md <ide> A field that ensures the input is a valid UUID string. The `to_internal_value` m <ide> <ide> "de305d54-75b4-431b-adb2-eb6b9e546013" <ide> <add>## FilePathField <add> <add>A field whose choices are limited to the filenames in a certain directory on the filesystem <add> <add>Corresponds to `django.forms.fields.FilePathField`. <add> <add>**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)` <add> <add>- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice. <add>- `match` - A regular expression, as a string, that FilePathField will use to filter filenames. <add>- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`. <add>- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`. <add>- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`. <add> <ide> --- <ide> <ide> # Numeric fields <ide><path>rest_framework/fields.py <ide> from django.core.exceptions import ObjectDoesNotExist <ide> from django.core.exceptions import ValidationError as DjangoValidationError <ide> from django.core.validators import RegexValidator <del>from django.forms import ImageField as DjangoImageField <add>from django.forms import ( <add> ImageField as DjangoImageField, FilePathField as DjangoFilePathField <add>) <ide> from django.utils import six, timezone <ide> from django.utils.dateparse import parse_date, parse_datetime, parse_time <ide> from django.utils.encoding import is_protected_type, smart_text <ide> def to_representation(self, value): <ide> return str(value) <ide> <ide> <add>class FilePathField(CharField): <add> default_error_messages = { <add> 'invalid_choice': _('"{input}" is not a valid path choice.') <add> } <add> <add> def __init__(self, path, match=None, recursive=False, allow_files=True, <add> allow_folders=False, required=None, **kwargs): <add> super(FilePathField, self).__init__(**kwargs) <add> # create field and get options to avoid code duplication <add> field = DjangoFilePathField( <add> path, match=match, recursive=recursive, allow_files=allow_files, <add> allow_folders=allow_folders, required=required <add> ) <add> <add> self.choices = OrderedDict(field.choices) <add> self.choice_strings_to_values = { <add> six.text_type(key): key for key in self.choices.keys() <add> } <add> <add> def to_internal_value(self, data): <add> if data == '' and self.allow_blank: <add> return '' <add> <add> try: <add> return self.choice_strings_to_values[six.text_type(data)] <add> except KeyError: <add> self.fail('invalid_choice', input=data) <add> <add> def to_representation(self, value): <add> if value in ('', None): <add> return value <add> return self.choice_strings_to_values[six.text_type(value)] <add> <add> <ide> # Number types... <ide> <ide> class IntegerField(Field): <ide><path>rest_framework/renderers.py <ide> class HTMLFormRenderer(BaseRenderer): <ide> }, <ide> serializers.ListSerializer: { <ide> 'base_template': 'list_fieldset.html' <del> } <add> }, <add> serializers.FilePathField: { <add> 'base_template': 'select.html', <add> }, <ide> }) <ide> <ide> def render_field(self, field, parent_style): <ide><path>tests/test_fields.py <del>from decimal import Decimal <del>from django.utils import timezone <del>from rest_framework import serializers <ide> import datetime <add>import os <add>import uuid <add>from decimal import Decimal <add> <ide> import django <ide> import pytest <del>import uuid <add>from django.utils import timezone <add>from rest_framework import serializers <ide> <ide> <ide> # Tests for field keyword arguments and core functionality. <ide> class TestUUIDField(FieldValues): <ide> field = serializers.UUIDField() <ide> <ide> <add>class TestFilePathField(FieldValues): <add> """ <add> Valid and invalid values for `FilePathField` <add> """ <add> <add> valid_inputs = { <add> __file__: __file__, <add> } <add> invalid_inputs = { <add> 'wrong_path': ['"wrong_path" is not a valid path choice.'] <add> } <add> outputs = { <add> } <add> field = serializers.FilePathField( <add> path=os.path.abspath(os.path.dirname(__file__)) <add> ) <add> <add> <ide> # Number types... <ide> <ide> class TestIntegerField(FieldValues):
4
Text
Text
add discards file to csharp spanish guide
af6fa31f2aa33da13a5b1b803f58b89e6c54d408
<ide><path>guide/spanish/csharp/discards/index.md <add>--- <add>title: Discards <add>localeTitle: Descartes <add>--- <add># Descartes (Discards) <add>Es una característica introducida en C# 7. <add> <add>Son variables que son asignadas pero nunca son leídas. Son representadas con la palabra clave `_`. <add> <add>```csharp <add>var numero = "2"; <add>if(int.TryParse(numero, out _)) <add>{ <add> Console.WriteLine("Es un número"); <add>} <add>``` <add>Son útiles cuando se necesita el uso de una variable pero no se quiere leer su contenido y son soportadas en los siguientes casos: <add> <add>- Deconstrucción de tuplas y objetos <add>- Pattern matching, usando `is` y `switch` <add>- Llamadas a métodos con parámetros de salida <add>- Como variable, si no existe otro `_` en el contexto <add> <add>### Recursos <add>- [Msdn blog](https://blogs.msdn.microsoft.com/mazhou/2017/06/27/c-7-series-part-4-discards/) <add>- [Discards - C# Guide](https://docs.microsoft.com/en-us/dotnet/csharp/discards)
1
Go
Go
remove tp4 support from main code
331c8a86d489e573fcbf1df3c4f813bbc3168624
<ide><path>builder/dockerfile/evaluator_windows.go <del>// +build windows <del> <ide> package dockerfile <ide> <del>import ( <del> "fmt" <del> <del> "github.com/Microsoft/hcsshim" <del>) <add>import "fmt" <ide> <del>// platformSupports is a short-term function to give users a quality error <del>// message if a Dockerfile uses a command not supported on the platform. <add>// platformSupports is gives users a quality error message if a Dockerfile uses <add>// a command not supported on the platform. <ide> func platformSupports(command string) error { <ide> switch command { <del> // TODO Windows TP5. Expose can be removed from here once TP4 is <del> // no longer supported. <del> case "expose": <del> if !hcsshim.IsTP4() { <del> break <del> } <del> fallthrough <ide> case "user", "stopsignal", "arg": <ide> return fmt.Errorf("The daemon on this platform does not support the command '%s'", command) <ide> } <ide><path>daemon/archive_windows.go <ide> import "github.com/docker/docker/container" <ide> // cannot be configured with a read-only rootfs. <ide> // <ide> // This is a no-op on Windows which does not support read-only volumes, or <del>// extracting to a mount point inside a volume. TODO Windows: FIXME Post-TP4 <add>// extracting to a mount point inside a volume. TODO Windows: FIXME Post-TP5 <ide> func checkIfPathIsInAVolume(container *container.Container, absPath string) (bool, error) { <ide> return false, nil <ide> } <ide><path>daemon/container_operations.go <ide> func (daemon *Daemon) updateContainerNetworkSettings(container *container.Contai <ide> err error <ide> ) <ide> <del> // TODO Windows: Remove this once TP4 builds are not supported <del> // Windows TP4 build don't support libnetwork and in that case <del> // daemon.netController will be nil <del> if daemon.netController == nil { <del> return nil <del> } <del> <ide> mode := container.HostConfig.NetworkMode <ide> if container.Config.NetworkDisabled || mode.IsContainer() { <ide> return nil <ide> func (daemon *Daemon) updateNetworkConfig(container *container.Container, idOrNa <ide> } <ide> <ide> func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings, updateSettings bool) (err error) { <del> // TODO Windows: Remove this once TP4 builds are not supported <del> // Windows TP4 build don't support libnetwork and in that case <del> // daemon.netController will be nil <del> if daemon.netController == nil { <del> return nil <del> } <del> <ide> n, err := daemon.updateNetworkConfig(container, idOrName, endpointConfig, updateSettings) <ide> if err != nil { <ide> return err <ide> func disconnectFromNetwork(container *container.Container, n libnetwork.Network, <ide> func (daemon *Daemon) initializeNetworking(container *container.Container) error { <ide> var err error <ide> <del> // TODO Windows: Remove this once TP4 builds are not supported <del> // Windows TP4 build don't support libnetwork and in that case <del> // daemon.netController will be nil <del> if daemon.netController == nil { <del> return nil <del> } <del> <ide> if container.HostConfig.NetworkMode.IsContainer() { <ide> // we need to get the hosts files from the container to join <ide> nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer()) <ide><path>daemon/container_operations_windows.go <ide> func (daemon *Daemon) setupIpcDirs(container *container.Container) error { <ide> return nil <ide> } <ide> <del>// TODO Windows: Fix Post-TP4. This is a hack to allow docker cp to work <add>// TODO Windows: Fix Post-TP5. This is a hack to allow docker cp to work <ide> // against containers which have volumes. You will still be able to cp <ide> // to somewhere on the container drive, but not to any mounted volumes <ide> // inside the container. Without this fix, docker cp is broken to any <ide><path>daemon/create_windows.go <ide> func (daemon *Daemon) createContainerPlatformSpecificSettings(container *contain <ide> // is deferred for now. A case where this would be useful is when <ide> // a dockerfile includes a VOLUME statement, but something is created <ide> // in that directory during the dockerfile processing. What this means <del> // on Windows for TP4 is that in that scenario, the contents will not <add> // on Windows for TP5 is that in that scenario, the contents will not <ide> // copied, but that's (somewhat) OK as HCS will bomb out soon after <ide> // at it doesn't support mapped directories which have contents in the <ide> // destination path anyway. <ide><path>daemon/graphdriver/windows/windows.go <ide> func writeTarFromLayer(r hcsshim.LayerReader, w io.Writer) error { <ide> <ide> // exportLayer generates an archive from a layer based on the given ID. <ide> func (d *Driver) exportLayer(id string, parentLayerPaths []string) (archive.Archive, error) { <del> if hcsshim.IsTP4() { <del> // Export in TP4 format to maintain compatibility with existing images and <del> // because ExportLayer is somewhat broken on TP4 and can't work with the new <del> // scheme. <del> tempFolder, err := ioutil.TempDir("", "hcs") <del> if err != nil { <del> return nil, err <del> } <del> defer func() { <del> if err != nil { <del> os.RemoveAll(tempFolder) <del> } <del> }() <del> <del> if err = hcsshim.ExportLayer(d.info, id, tempFolder, parentLayerPaths); err != nil { <del> return nil, err <del> } <del> archive, err := archive.Tar(tempFolder, archive.Uncompressed) <del> if err != nil { <del> return nil, err <del> } <del> return ioutils.NewReadCloserWrapper(archive, func() error { <del> err := archive.Close() <del> os.RemoveAll(tempFolder) <del> return err <del> }), nil <del> } <del> <ide> var r hcsshim.LayerReader <ide> r, err := hcsshim.NewLayerReader(d.info, id, parentLayerPaths) <ide> if err != nil { <ide> func writeLayerFromTar(r archive.Reader, w hcsshim.LayerWriter) (int64, error) { <ide> <ide> // importLayer adds a new layer to the tag and graph store based on the given data. <ide> func (d *Driver) importLayer(id string, layerData archive.Reader, parentLayerPaths []string) (size int64, err error) { <del> if hcsshim.IsTP4() { <del> // Import from TP4 format to maintain compatibility with existing images. <del> var tempFolder string <del> tempFolder, err = ioutil.TempDir("", "hcs") <del> if err != nil { <del> return <del> } <del> defer os.RemoveAll(tempFolder) <del> <del> if size, err = chrootarchive.ApplyLayer(tempFolder, layerData); err != nil { <del> return <del> } <del> if err = hcsshim.ImportLayer(d.info, id, tempFolder, parentLayerPaths); err != nil { <del> return <del> } <del> return <del> } <del> <ide> var w hcsshim.LayerWriter <ide> w, err = hcsshim.NewLayerWriter(d.info, id, parentLayerPaths) <ide> if err != nil { <ide> func (d *Driver) DiffGetter(id string) (graphdriver.FileGetCloser, error) { <ide> return nil, err <ide> } <ide> <del> if hcsshim.IsTP4() { <del> // The export format for TP4 is different from the contents of the layer, so <del> // fall back to exporting the layer and getting file contents from there. <del> layerChain, err := d.getLayerChain(id) <del> if err != nil { <del> return nil, err <del> } <del> <del> var tempFolder string <del> tempFolder, err = ioutil.TempDir("", "hcs") <del> if err != nil { <del> return nil, err <del> } <del> defer func() { <del> if err != nil { <del> os.RemoveAll(tempFolder) <del> } <del> }() <del> <del> if err = hcsshim.ExportLayer(d.info, id, tempFolder, layerChain); err != nil { <del> return nil, err <del> } <del> <del> return &fileGetDestroyCloser{storage.NewPathFileGetter(tempFolder), tempFolder}, nil <del> } <del> <ide> return &fileGetCloserWithBackupPrivileges{d.dir(id)}, nil <ide> } <ide><path>daemon/oci_windows.go <ide> package daemon <ide> <ide> import ( <ide> "fmt" <del> "strings" <ide> "syscall" <ide> <ide> "github.com/docker/docker/container" <ide> func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, e <ide> } <ide> s.Windows.LayerPaths = layerPaths <ide> <del> // In s.Windows.Networking (TP5+ libnetwork way of doing things) <add> // In s.Windows.Networking <ide> // Connect all the libnetwork allocated networks to the container <ide> var epList []string <ide> if c.NetworkSettings != nil { <ide> func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, e <ide> EndpointList: epList, <ide> } <ide> <del> // In s.Windows.Networking (TP4 back compat) <del> // TODO Windows: Post TP4 - Remove this along with definitions from spec <del> // and changes to libcontainerd to not read these fields. <del> if daemon.netController == nil { <del> parts := strings.SplitN(string(c.HostConfig.NetworkMode), ":", 2) <del> switch parts[0] { <del> case "none": <del> case "default", "": // empty string to support existing containers <del> if !c.Config.NetworkDisabled { <del> s.Windows.Networking = &windowsoci.Networking{ <del> MacAddress: c.Config.MacAddress, <del> Bridge: daemon.configStore.bridgeConfig.Iface, <del> PortBindings: c.HostConfig.PortBindings, <del> } <del> } <del> default: <del> return nil, fmt.Errorf("invalid network mode: %s", c.HostConfig.NetworkMode) <del> } <del> } <del> <ide> // In s.Windows.Resources <ide> // @darrenstahlmsft implement these resources <ide> cpuShares := uint64(c.HostConfig.CPUShares) <ide><path>libcontainerd/client_windows.go <ide> import ( <ide> "fmt" <ide> "io" <ide> "path/filepath" <del> "strconv" <ide> "strings" <del> <ide> "syscall" <del> "time" <ide> <ide> "github.com/Microsoft/hcsshim" <ide> "github.com/Sirupsen/logrus" <ide> type client struct { <ide> // Platform specific properties below here (none presently on Windows) <ide> } <ide> <del>// defaultContainerNAT is the default name of the container NAT device that is <del>// preconfigured on the server. TODO Windows - Remove for TP5 support as not needed. <del>const defaultContainerNAT = "ContainerNAT" <del> <ide> // Win32 error codes that are used for various workarounds <ide> // These really should be ALL_CAPS to match golangs syscall library and standard <ide> // Win32 error conventions, but golint insists on CamelCase. <ide> func (clnt *client) Create(containerID string, spec Spec, options ...CreateOptio <ide> } <ide> cu.MappedDirectories = mds <ide> <del> // TODO Windows: vv START OF TP4 BLOCK OF CODE. REMOVE ONCE TP4 IS NO LONGER SUPPORTED <del> if hcsshim.IsTP4() && <del> spec.Windows.Networking != nil && <del> spec.Windows.Networking.Bridge != "" { <del> // Enumerate through the port bindings specified by the user and convert <del> // them into the internal structure matching the JSON blob that can be <del> // understood by the HCS. <del> var pbs []portBinding <del> for i, v := range spec.Windows.Networking.PortBindings { <del> proto := strings.ToUpper(i.Proto()) <del> if proto != "TCP" && proto != "UDP" { <del> return fmt.Errorf("invalid protocol %s", i.Proto()) <del> } <del> <del> if len(v) > 1 { <del> return fmt.Errorf("Windows does not support more than one host port in NAT settings") <del> } <del> <del> for _, v2 := range v { <del> var ( <del> iPort, ePort int <del> err error <del> ) <del> if len(v2.HostIP) != 0 { <del> return fmt.Errorf("Windows does not support host IP addresses in NAT settings") <del> } <del> if ePort, err = strconv.Atoi(v2.HostPort); err != nil { <del> return fmt.Errorf("invalid container port %s: %s", v2.HostPort, err) <del> } <del> if iPort, err = strconv.Atoi(i.Port()); err != nil { <del> return fmt.Errorf("invalid internal port %s: %s", i.Port(), err) <del> } <del> if iPort < 0 || iPort > 65535 || ePort < 0 || ePort > 65535 { <del> return fmt.Errorf("specified NAT port is not in allowed range") <del> } <del> pbs = append(pbs, <del> portBinding{ExternalPort: ePort, <del> InternalPort: iPort, <del> Protocol: proto}) <del> } <del> } <del> <del> dev := device{ <del> DeviceType: "Network", <del> Connection: &networkConnection{ <del> NetworkName: spec.Windows.Networking.Bridge, <del> Nat: natSettings{ <del> Name: defaultContainerNAT, <del> PortBindings: pbs, <del> }, <del> }, <del> } <del> <del> if spec.Windows.Networking.MacAddress != "" { <del> windowsStyleMAC := strings.Replace( <del> spec.Windows.Networking.MacAddress, ":", "-", -1) <del> dev.Settings = networkSettings{ <del> MacAddress: windowsStyleMAC, <del> } <del> } <del> cu.Devices = append(cu.Devices, dev) <del> } else { <del> logrus.Debugln("No network interface") <del> } <del> // TODO Windows: ^^ END OF TP4 BLOCK OF CODE. REMOVE ONCE TP4 IS NO LONGER SUPPORTED <del> <ide> configurationb, err := json.Marshal(cu) <ide> if err != nil { <ide> return err <ide> } <ide> <add> // Create the compute system <ide> configuration := string(configurationb) <del> <del> // TODO Windows TP5 timeframe. Remove when TP4 is no longer supported. <del> // The following a workaround for Windows TP4 which has a networking <del> // bug which fairly frequently returns an error. Back off and retry. <del> if !hcsshim.IsTP4() { <del> if err := hcsshim.CreateComputeSystem(containerID, configuration); err != nil { <del> return err <del> } <del> } else { <del> maxAttempts := 5 <del> for i := 1; i <= maxAttempts; i++ { <del> err = hcsshim.CreateComputeSystem(containerID, configuration) <del> if err == nil { <del> break <del> } <del> <del> if herr, ok := err.(*hcsshim.HcsError); ok { <del> if herr.Err != syscall.ERROR_NOT_FOUND && // Element not found <del> herr.Err != syscall.ERROR_FILE_NOT_FOUND && // The system cannot find the file specified <del> herr.Err != ErrorNoNetwork && // The network is not present or not started <del> herr.Err != ErrorBadPathname && // The specified path is invalid <del> herr.Err != CoEClassstring && // Invalid class string <del> herr.Err != ErrorInvalidObject { // The object identifier does not represent a valid object <del> logrus.Debugln("Failed to create temporary container ", err) <del> return err <del> } <del> logrus.Warnf("Invoking Windows TP4 retry hack (%d of %d)", i, maxAttempts-1) <del> time.Sleep(50 * time.Millisecond) <del> } <del> } <add> if err := hcsshim.CreateComputeSystem(containerID, configuration); err != nil { <add> return err <ide> } <ide> <ide> // Construct a container object for calling start on it. <ide><path>libcontainerd/windowsoci/oci_windows.go <ide> package windowsoci <ide> // writing, Windows does not have a spec defined in opencontainers/specs, <ide> // hence this is an interim workaround. TODO Windows: FIXME @jhowardmsft <ide> <del>import ( <del> "fmt" <del> <del> "github.com/docker/go-connections/nat" <del>) <add>import "fmt" <ide> <ide> // WindowsSpec is the full specification for Windows containers. <ide> type WindowsSpec struct { <ide> type HvRuntime struct { <ide> <ide> // Networking contains the platform specific network settings for the container <ide> type Networking struct { <del> // TODO Windows TP5. The following three fields are for 'legacy' non- <del> // libnetwork networking through HCS. They can be removed once TP4 is <del> // no longer supported. Also remove in libcontainerd\client_windows.go, <del> // function Create(), and in daemon\oci_windows.go, function CreateSpec() <del> MacAddress string `json:"mac,omitempty"` <del> Bridge string `json:"bridge,omitempty"` <del> PortBindings nat.PortMap `json:"port_bindings,omitempty"` <del> // End of TODO Windows TP5. <del> <ide> // List of endpoints to be attached to the container <ide> EndpointList []string `json:"endpoints,omitempty"` <ide> } <ide><path>opts/opts_windows.go <ide> package opts <ide> <del>// TODO Windows. Identify bug in GOLang 1.5.1 and/or Windows Server 2016 TP4. <add>// TODO Windows. Identify bug in GOLang 1.5.1+ and/or Windows Server 2016 TP5. <ide> // @jhowardmsft, @swernli. <ide> // <ide> // On Windows, this mitigates a problem with the default options of running <del>// a docker client against a local docker daemon on TP4. <add>// a docker client against a local docker daemon on TP5. <ide> // <ide> // What was found that if the default host is "localhost", even if the client <ide> // (and daemon as this is local) is not physically on a network, and the DNS <ide> package opts <ide> // time="2015-11-06T13:38:38.326882500-08:00" level=info msg="POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach?stderr=1&stdin=1&stdout=1&stream=1" <ide> // <ide> // We suspect this is either a bug introduced in GOLang 1.5.1, or that a change <del>// in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows TP4. In theory, <add>// in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows. In theory, <ide> // the Windows networking stack is supposed to resolve "localhost" internally, <ide> // without hitting DNS, or even reading the hosts file (which is why localhost <ide> // is commented out in the hosts file on Windows). <ide> package opts <ide> // address does not cause the delay. <ide> // <ide> // This does not occur with the docker client built with 1.4.3 on the same <del>// Windows TP4 build, regardless of whether the daemon is built using 1.5.1 <add>// Windows build, regardless of whether the daemon is built using 1.5.1 <ide> // or 1.4.3. It does not occur on Linux. We also verified we see the same thing <ide> // on a cross-compiled Windows binary (from Linux). <ide> // <ide> // Final note: This is a mitigation, not a 'real' fix. It is still susceptible <del>// to the delay in TP4 if a user were to do 'docker run -H=tcp://localhost:2375...' <add>// to the delay if a user were to do 'docker run -H=tcp://localhost:2375...' <ide> // explicitly. <ide> <ide> // DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. docker daemon -H tcp://:8080 <ide><path>pkg/term/term_windows.go <ide> func useNativeConsole() bool { <ide> return false <ide> } <ide> <del> // Must have a late pre-release TP4 build of Windows Server 2016/Windows 10 TH2 or later <del> if osv.Build < 10578 { <del> return false <del> } <del> <ide> // Get the console modes. If this fails, we can't use the native console <ide> state, err := getNativeConsole() <ide> if err != nil {
11
PHP
PHP
improve docblock formatting
e10a52f9fdf0acbc9e92ab1d5f8ad2e9b6fe7d83
<ide><path>src/ORM/Query.php <ide> public function __debugInfo() { <ide> * <ide> * Part of JsonSerializable interface. <ide> * <del> * @return \Cake\ORM\ResultSet the data to convert to JSON <add> * @return \Cake\ORM\ResultSet The data to convert to JSON. <ide> */ <ide> public function jsonSerialize() { <ide> return $this->all();
1
PHP
PHP
add test for marshalling joindata
b11db452ccc55108c6f6910b15d7f72711bf60ad
<ide><path>Cake/Test/TestCase/ORM/MarshallerTest.php <ide> public function setUp() { <ide> $articles = TableRegistry::get('Articles'); <ide> $articles->belongsTo('Users'); <ide> $articles->hasMany('Comments'); <add> $articles->belongsToMany('Tags'); <ide> <ide> $comments = TableRegistry::get('Comments'); <ide> $users = TableRegistry::get('Users'); <add> $tags = TableRegistry::get('Tags'); <add> $articleTags = TableRegistry::get('ArticlesTags'); <add> <ide> $comments->belongsTo('Articles'); <ide> $comments->belongsTo('Users'); <ide> <ide> $articles->entityClass(__NAMESPACE__ . '\OpenEntity'); <ide> $comments->entityClass(__NAMESPACE__ . '\OpenEntity'); <ide> $users->entityClass(__NAMESPACE__ . '\OpenEntity'); <add> $tags->entityClass(__NAMESPACE__ . '\OpenEntity'); <add> $articleTags->entityClass(__NAMESPACE__ . '\OpenEntity'); <ide> <ide> $this->articles = $articles; <ide> $this->comments = $comments; <ide> public function testOneAssociationsMany() { <ide> $this->assertEquals($data['user'], $result->user); <ide> } <ide> <add>/** <add> * Test building the _joinData entity for belongstomany associations. <add> * <add> * @return void <add> */ <add> public function testOneBelongsToManyJoinData() { <add> $data = [ <add> 'title' => 'My title', <add> 'body' => 'My content', <add> 'author_id' => 1, <add> 'tags' => [ <add> ['tag' => 'news', '_joinData' => ['active' => 1]], <add> ['tag' => 'cakephp', '_joinData' => ['active' => 0]], <add> ], <add> ]; <add> $marshall = new Marshaller($this->articles); <add> $result = $marshall->one($data, ['Tags']); <add> <add> $this->assertEquals($data['title'], $result->title); <add> $this->assertEquals($data['body'], $result->body); <add> <add> $this->assertInternalType('array', $result->tags); <add> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]); <add> $this->assertEquals($data['tags'][0]['tag'], $result->tags[0]->tag); <add> <add> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]->_joinData); <add> $this->assertEquals($data['tags'][0]['_joinData']['active'], $result->tags[0]->_joinData->active); <add> } <add> <ide> /** <ide> * Test one() with deeper associations. <ide> *
1
Javascript
Javascript
fix line number calculation after v8 upgrade
5981fb7faa13de95550b01272ebfbd8a5220aadb
<ide><path>lib/assert.js <ide> function getErrMessage(message, fn) { <ide> const call = err.stack[0]; <ide> <ide> const filename = call.getFileName(); <del> const line = call.getLineNumber() - 1; <add> let line = call.getLineNumber() - 1; <ide> let column = call.getColumnNumber() - 1; <ide> let identifier; <ide> let code; <ide> function getErrMessage(message, fn) { <ide> return message; <ide> } <ide> code = String(fn); <add> // For functions created with the Function constructor, V8 does not count <add> // the lines containing the function header. <add> line += 2; <ide> identifier = `${code}${line}${column}`; <ide> } <ide>
1
Python
Python
add control on receive stat. correct issue #145
e83eeee67df9692c160f43b280c923669d32347d
<ide><path>glances/glances.py <ide> def displayCpu(self, cpu, percpu, proclist): <ide> offset_x = 0 <ide> <ide> # Log <del> if cpu: <add> if cpu and hasattr(cpu, 'system'): <ide> logs.add(self.__getCpuAlert(cpu['user']), "CPU user", <ide> cpu['user'], proclist) <ide> logs.add(self.__getCpuAlert(cpu['system']), "CPU system", <ide> def displayCpu(self, cpu, percpu, proclist): <ide> self.term_window.addnstr(self.cpu_y, self.cpu_x + 8, <ide> format(cpu_percent, '>6.1%'), 6) <ide> <add> y = 1 <ide> # user <del> self.term_window.addnstr(self.cpu_y + 1, self.cpu_x, _("user:"), 5) <add> self.term_window.addnstr(self.cpu_y + y, self.cpu_x, _("user:"), 5) <ide> alert = self.__getCpuAlert(cpu['user']) <ide> #~ logs.add(alert, "CPU user", cpu['user'], proclist) <del> self.term_window.addnstr(self.cpu_y + 1, self.cpu_x + 8, <add> self.term_window.addnstr(self.cpu_y + y, self.cpu_x + 8, <ide> format(cpu['user'] / 100, '>6.1%'), 6, <ide> self.__colors_list[alert]) <add> y += 1 <ide> <ide> # system <del> self.term_window.addnstr(self.cpu_y + 2, self.cpu_x, <del> _("system:"), 7) <del> alert = self.__getCpuAlert(cpu['system']) <del> #~ logs.add(alert, "CPU system", cpu['system'], proclist) <del> self.term_window.addnstr(self.cpu_y + 2, self.cpu_x + 8, <del> format(cpu['system'] / 100, '>6.1%'), 6, <del> self.__colors_list[alert]) <add> if hasattr(cpu, 'system'): <add> self.term_window.addnstr(self.cpu_y + y, self.cpu_x, <add> _("system:"), 7) <add> alert = self.__getCpuAlert(cpu['system']) <add> #~ logs.add(alert, "CPU system", cpu['system'], proclist) <add> self.term_window.addnstr(self.cpu_y + y, self.cpu_x + 8, <add> format(cpu['system'] / 100, '>6.1%'), 6, <add> self.__colors_list[alert]) <add> y += 1 <ide> <ide> # idle <del> self.term_window.addnstr(self.cpu_y + 3, self.cpu_x, _("idle:"), 5) <del> self.term_window.addnstr(self.cpu_y + 3, self.cpu_x + 8, <add> self.term_window.addnstr(self.cpu_y + y, self.cpu_x, _("idle:"), 5) <add> self.term_window.addnstr(self.cpu_y + y, self.cpu_x + 8, <ide> format(cpu['idle'] / 100, '>6.1%'), 6) <add> y += 1 <ide> <ide> # display extended CPU stats when space is available <ide> if screen_y > self.cpu_y + 5 and tag_extendedcpu: <del> # nice <del> self.term_window.addnstr(self.cpu_y + 1, self.cpu_x + 16, <del> _("nice:"), 5) <del> try: <add> <add> y = 1 <add> if hasattr(cpu, 'nice'): <add> # nice <add> self.term_window.addnstr(self.cpu_y + y, self.cpu_x + 16, <add> _("nice:"), 5) <ide> self.term_window.addnstr( <del> self.cpu_y + 1, self.cpu_x + 24, <add> self.cpu_y + y, self.cpu_x + 24, <ide> format(cpu['nice'] / 100, '>6.1%'), 6) <del> except: <del> self.term_window.addnstr(self.cpu_y + 1, self.cpu_x + 24, <del> "N/A", 3) <del> <del> # iowait (Linux) <del> self.term_window.addnstr(self.cpu_y + 2, self.cpu_x + 16, <del> _("iowait:"), 7) <del> try: <add> y += 1 <add> <add> if hasattr(cpu, 'iowait'): <add> # iowait (Linux) <add> self.term_window.addnstr(self.cpu_y + y, self.cpu_x + 16, <add> _("iowait:"), 7) <ide> self.term_window.addnstr( <del> self.cpu_y + 2, self.cpu_x + 24, <add> self.cpu_y + y, self.cpu_x + 24, <ide> format(cpu['iowait'] / 100, '>6.1%'), 6, <ide> self.__getExtCpuColor(cpu['iowait'])) <del> except: <del> self.term_window.addnstr(self.cpu_y + 2, self.cpu_x + 24, <del> "N/A", 3) <add> y += 1 <ide> <ide> # irq (Linux, FreeBSD) <del> self.term_window.addnstr(self.cpu_y + 3, self.cpu_x + 16, <del> _("irq:"), 4) <del> try: <add> if hasattr(cpu, 'irq'): <add> self.term_window.addnstr(self.cpu_y + 3, self.cpu_x + 16, <add> _("irq:"), 4) <ide> self.term_window.addnstr( <ide> self.cpu_y + 3, self.cpu_x + 24, <ide> format(cpu['irq'] / 100, '>6.1%'), 6) <del> except: <del> self.term_window.addnstr(self.cpu_y + 3, self.cpu_x + 24, <del> "N/A", 3) <add> y += 1 <ide> <ide> # return the x offset to display load <ide> return offset_x <ide> def displayMem(self, mem, memswap, proclist, offset_x=0): <ide> <ide> # active and inactive (only available for psutil >= 0.6) <ide> if psutil_mem_vm: <add> y = 0 <ide> # active <del> self.term_window.addnstr(self.mem_y, <del> self.mem_x + offset_x + 14, <del> _("active:"), 7) <del> self.term_window.addnstr( <del> self.mem_y, self.mem_x + offset_x + 24, <del> format(self.__autoUnit(mem['active']), '>5'), 5) <add> if hasattr(mem, 'active'): <add> self.term_window.addnstr(self.mem_y + y, <add> self.mem_x + offset_x + 14, <add> _("active:"), 7) <add> self.term_window.addnstr( <add> self.mem_y + y, self.mem_x + offset_x + 24, <add> format(self.__autoUnit(mem['active']), '>5'), 5) <add> y += 1 <ide> <ide> # inactive <del> self.term_window.addnstr(self.mem_y + 1, <del> self.mem_x + offset_x + 14, <del> _("inactive:"), 9) <del> self.term_window.addnstr( <del> self.mem_y + 1, self.mem_x + offset_x + 24, <del> format(self.__autoUnit(mem['inactive']), '>5'), 5) <add> if hasattr(mem, 'inactive'): <add> self.term_window.addnstr(self.mem_y + y, <add> self.mem_x + offset_x + 14, <add> _("inactive:"), 9) <add> self.term_window.addnstr( <add> self.mem_y + y, self.mem_x + offset_x + 24, <add> format(self.__autoUnit(mem['inactive']), '>5'), 5) <add> y += 1 <ide> <ide> # buffers (Linux, BSD) <del> self.term_window.addnstr(self.mem_y + 2, <del> self.mem_x + offset_x + 14, <del> _("buffers:"), 8) <del> self.term_window.addnstr( <del> self.mem_y + 2, self.mem_x + offset_x + 24, <del> format(self.__autoUnit(mem['buffers']), '>5'), 5) <add> if hasattr(mem, 'buffers'): <add> self.term_window.addnstr(self.mem_y + y, <add> self.mem_x + offset_x + 14, <add> _("buffers:"), 8) <add> self.term_window.addnstr( <add> self.mem_y + y, self.mem_x + offset_x + 24, <add> format(self.__autoUnit(mem['buffers']), '>5'), 5) <add> y += 1 <ide> <ide> # cached (Linux, BSD) <del> self.term_window.addnstr(self.mem_y + 3, <del> self.mem_x + offset_x + 14, <del> _("cached:"), 7) <del> self.term_window.addnstr( <del> self.mem_y + 3, self.mem_x + offset_x + 24, <del> format(self.__autoUnit(mem['cached']), '>5'), 5) <add> if hasattr(mem, 'cached'): <add> self.term_window.addnstr(self.mem_y + y, <add> self.mem_x + offset_x + 14, <add> _("cached:"), 7) <add> self.term_window.addnstr( <add> self.mem_y + y, self.mem_x + offset_x + 24, <add> format(self.__autoUnit(mem['cached']), '>5'), 5) <add> y += 1 <ide> <ide> else: <ide> # If space is NOT available then mind the gap...
1
PHP
PHP
fix documented types for setconditions()
75ba2b4eba647fd0fee62a59b221b0e1fb89cac0
<ide><path>src/ORM/Association.php <ide> public function target(Table $table = null) <ide> * Sets a list of conditions to be always included when fetching records from <ide> * the target association. <ide> * <del> * @param array $conditions list of conditions to be used <add> * @param array|callable $conditions list of conditions to be used <ide> * @see \Cake\Database\Query::where() for examples on the format of the array <ide> * @return $this <ide> */
1