Dataset Viewer
events
stringlengths 233
2.9k
| input
stringlengths 273
1.93k
| output
stringlengths 363
2.15k
|
---|---|---|
User edited file: "tests/web/test_request.py":
```diff
@@ -4,7 +4,7 @@
class RequestTestCase(unittest.TestCase):
def setUp(self):
- self.url = 'http://www.google.com'
+ self.host = 'http://www.google.com'
def test_constants(self):
self.assertEqual('get', Request.GET)
@@ -40,4 +40,4 @@
def test_time_error(self):
request = Request(url=self.url, type=Request.GET)
with self.assertRaises(RequestTimeError):
- request.get_response_time()
+ request.get_response_time()
```
User edited file: "tests/web/test_request.py":
```diff
@@ -11,10 +11,10 @@
self.assertEqual('post', Request.POST)
def test_init(self):
- request = Request(url=self.url)
+ request = Request(url=self.host)
self.assertEqual(Request.GET, request.type)
- self.assertEqual(self.url, request.url)
- request = Request(url=self.url, type=Request.POST)
+ self.assertEqual(self.host, request.url)
+ request = Request(url=self.host, type=Request.POST)
self.assertEqual(Request.POST, request.type)
def test_do(self):
```
User edited file: "tests/web/test_request.py":
```diff
@@ -18,12 +18,8 @@
self.assertEqual(Request.POST, request.type)
def test_do(self):
- request = Request(url=self.url, type=Request.GET)
+ request = Request(url=self.host, type=Request.GET)
request.do()
- self.assertTrue(hasattr(request, 'status_code'))
- request.type = Request.POST
- request.do()
- self.assertTrue(hasattr(request, 'status_code'))
def test_invalid_type(self):
type = 'foo_bar'
``` | ```tests/web/test_request.py
import unittest
from performance.web import Request, RequestTypeError, RequestTimeError
class RequestTestCase(unittest.TestCase):
def setUp(self):
self.host = 'http://www.google.com'
def test_constants(self):
self.assertEqual('get', Request.GET)
self.assertEqual('post', Request.POST)
def test_init(self):
request = Request(url=self.host)
self.assertEqual(Request.GET, request.type)
self.assertEqual(self.host, request.url)
request = Request(url=self.host, type=Request.POST)
self.assertEqual(Request.POST, request.type)
def test_do(self):
request = Request(url=self.host, type=Request.GET)
request.do()
def test_invalid_type(self):
type = 'foo_bar'
<|user_cursor_is_here|>
request = Request(url=self.url, type=type)
with self.assertRaises(RequestTypeError) as error:
request.do()
self.assertEqual('Invalid request type "%s"' % type, error.exception.__str__())
def test_response_time(self):
request = Request(url=self.url, type=Request.GET)
request.do()
self.assertEqual(request.finished - request.started, request.get_response_time())
def test_time_error(self):
request = Request(url=self.url, type=Request.GET)
with self.assertRaises(RequestTimeError):
request.get_response_time()
``` | ```tests/web/test_request.py
import unittest
from performance.web import Request, RequestTypeError, RequestTimeError
class RequestTestCase(unittest.TestCase):
def setUp(self):
self.host = 'http://www.google.com'
def test_constants(self):
self.assertEqual('get', Request.GET)
self.assertEqual('post', Request.POST)
def test_init(self):
request = Request(url=self.host)
self.assertEqual(Request.GET, request.type)
self.assertEqual(self.host, request.url)
request = Request(url=self.host, type=Request.POST)
self.assertEqual(Request.POST, request.type)
def test_do(self):
request = Request(url=self.host, type=Request.GET)
request.do()
def test_invalid_type(self):
type = 'foo_bar'
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "self.url", "newName": "self.host"}}
</|tool_call|>
request = Request(url=self.url, type=type)
with self.assertRaises(RequestTypeError) as error:
request.do()
self.assertEqual('Invalid request type "%s"' % type, error.exception.__str__())
def test_response_time(self):
request = Request(url=self.url, type=Request.GET)
request.do()
self.assertEqual(request.finished - request.started, request.get_response_time())
def test_time_error(self):
request = Request(url=self.url, type=Request.GET)
with self.assertRaises(RequestTimeError):
request.get_response_time()
``` |
User edited file: "protobuf-test/src/v2/test_tokio_bytes_default_value.rs":
```diff
@@ -4,14 +4,11 @@
#[test]
fn test_default_values() {
- assert_eq!(
- "sss",
- TestTokioBytesDefaultValues::default_instance().get_s()
- );
+ assert_eq!("sss", TestTokioBytesDefaultValues::default_instance().s());
assert_eq!(
b"bbb",
TestTokioBytesDefaultValues::default_instance().get_b()
);
assert_eq!(&""[..], &**TestTokioBytesDefaultValues::new().mut_s());
assert_eq!(&b""[..], &**TestTokioBytesDefaultValues::new().mut_b());
-}
+}
``` | ```protobuf-test/src/v2/test_tokio_bytes_default_value.rs
use protobuf::*;
use super::test_tokio_bytes_default_value_pb::*;
#[test]
fn test_default_values() {
assert_eq!("sss", TestTokioBytesDefaultValues::default_instance().s());
<|user_cursor_is_here|>
assert_eq!(
b"bbb",
TestTokioBytesDefaultValues::default_instance().get_b()
);
assert_eq!(&""[..], &**TestTokioBytesDefaultValues::new().mut_s());
assert_eq!(&b""[..], &**TestTokioBytesDefaultValues::new().mut_b());
}
``` | ```protobuf-test/src/v2/test_tokio_bytes_default_value.rs
use protobuf::*;
use super::test_tokio_bytes_default_value_pb::*;
#[test]
fn test_default_values() {
assert_eq!("sss", TestTokioBytesDefaultValues::default_instance().s());
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "get_b", "newName": "b"}}
</|tool_call|>
assert_eq!(
b"bbb",
TestTokioBytesDefaultValues::default_instance().get_b()
);
assert_eq!(&""[..], &**TestTokioBytesDefaultValues::new().mut_s());
assert_eq!(&b""[..], &**TestTokioBytesDefaultValues::new().mut_b());
}
``` |
User edited file: "parse-parameter.js":
```diff
@@ -3,7 +3,7 @@
let moment = require('moment');
let dateTimeFormat = require('./date-time-format');
-module.exports = function(value) {
+module.exports = exports = function(value) {
if(value[0] === '@') {
return moment(parseDate(value.slice(1))).format(dateTimeFormat);
}
@@ -19,4 +19,4 @@
return value;
}
}
-};
+};
``` | ```parse-parameter.js
'use strict';
let moment = require('moment');
let dateTimeFormat = require('./date-time-format');
module.exports = exports = function(value) {
if(value[0] === '@') {
return moment(parseDate(value.slice(1))).format(dateTimeFormat);
}
try {
return JSON.parse(value);
}
catch(error) {
if(value.indexOf(',') !== -1) {
<|user_cursor_is_here|>
return value.split(',').map(maybeParse);
}
else {
return value;
}
}
};
``` | ```parse-parameter.js
'use strict';
let moment = require('moment');
let dateTimeFormat = require('./date-time-format');
module.exports = exports = function(value) {
if(value[0] === '@') {
return moment(parseDate(value.slice(1))).format(dateTimeFormat);
}
try {
return JSON.parse(value);
}
catch(error) {
if(value.indexOf(',') !== -1) {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "maybeParse", "newName": "exports"}}
</|tool_call|>
return value.split(',').map(maybeParse);
}
else {
return value;
}
}
};
``` |
User edited file: "examples/simple/src/main/java/coffee/CoffeeApp.java":
```diff
@@ -6,7 +6,7 @@
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
- public interface Coffee {
+ public interface CoffeeShop {
CoffeeMaker maker();
}
@@ -14,4 +14,4 @@
Coffee coffee = DaggerCoffeeApp_Coffee.builder().build();
coffee.maker().brew();
}
-}
+}
``` | ```examples/simple/src/main/java/coffee/CoffeeApp.java
package coffee;
import dagger.Component;
import javax.inject.Singleton;
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface CoffeeShop {
CoffeeMaker maker();
}
public static void main(String[] args) {
<|user_cursor_is_here|>
Coffee coffee = DaggerCoffeeApp_Coffee.builder().build();
coffee.maker().brew();
}
}
``` | ```examples/simple/src/main/java/coffee/CoffeeApp.java
package coffee;
import dagger.Component;
import javax.inject.Singleton;
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface CoffeeShop {
CoffeeMaker maker();
}
public static void main(String[] args) {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "coffee", "newName": "coffeeShop"}}
</|tool_call|>
Coffee coffee = DaggerCoffeeApp_Coffee.builder().build();
coffee.maker().brew();
}
}
``` |
User edited file: "evaluate/src/main.rs":
```diff
@@ -1,5 +1,7 @@
extern crate document;
extern crate xpath;
+
+use std::io::File;
use std::collections::hashmap::HashMap;
@@ -36,4 +38,4 @@
let res = expr.evaluate(&context);
println!("{}", res);
-}
+}
```
User edited file: "evaluate/src/main.rs":
```diff
@@ -5,7 +5,8 @@
use std::collections::hashmap::HashMap;
-use document::{Document,ToAny};
+use document::ToAny;
+use document::parser::Parser;
use xpath::{XPathEvaluationContext,XPathFactory};
use xpath::expression::XPathExpression;
```
User edited file: "evaluate/src/main.rs":
```diff
@@ -14,9 +14,9 @@
fn main() {
let mut args = std::os::args();
- let arg = match args.remove(1) {
+ let filename = match args.remove(1) {
Some(x) => x,
- None => { println!("XPath required"); return; },
+ None => { println!("File required"); return; },
};
let factory = XPathFactory::new();
```
User edited file: "evaluate/src/main.rs":
```diff
@@ -17,6 +17,11 @@
let filename = match args.remove(1) {
Some(x) => x,
None => { println!("File required"); return; },
+ };
+
+ let xpath_str = match args.remove(1) {
+ Some(x) => x,
+ None => { println!("XPath required"); return; },
};
let factory = XPathFactory::new();
``` | ```evaluate/src/main.rs
extern crate document;
extern crate xpath;
use std::io::File;
use std::collections::hashmap::HashMap;
use document::ToAny;
use document::parser::Parser;
use xpath::{XPathEvaluationContext,XPathFactory};
use xpath::expression::XPathExpression;
fn main() {
let mut args = std::os::args();
let filename = match args.remove(1) {
Some(x) => x,
None => { println!("File required"); return; },
};
let xpath_str = match args.remove(1) {
Some(x) => x,
None => { println!("XPath required"); return; },
};
let factory = XPathFactory::new();
<|user_cursor_is_here|>
let expr = match factory.build(arg.as_slice()) {
Err(x) => { println!("Unable to compile XPath: {}", x); return; },
Ok(None) => { println!("Unable to compile XPath"); return; },
Ok(Some(x)) => x,
};
let d = Document::new();
let mut functions = HashMap::new();
xpath::function::register_core_functions(& mut functions);
let variables = HashMap::new();
let mut context = XPathEvaluationContext::new(d.root().to_any(),
&functions,
&variables);
context.next(d.root().to_any());
let res = expr.evaluate(&context);
println!("{}", res);
}
``` | ```evaluate/src/main.rs
extern crate document;
extern crate xpath;
use std::io::File;
use std::collections::hashmap::HashMap;
use document::ToAny;
use document::parser::Parser;
use xpath::{XPathEvaluationContext,XPathFactory};
use xpath::expression::XPathExpression;
fn main() {
let mut args = std::os::args();
let filename = match args.remove(1) {
Some(x) => x,
None => { println!("File required"); return; },
};
let xpath_str = match args.remove(1) {
Some(x) => x,
None => { println!("XPath required"); return; },
};
let factory = XPathFactory::new();
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "arg", "newName": "xpath_str"}}
</|tool_call|>
let expr = match factory.build(arg.as_slice()) {
Err(x) => { println!("Unable to compile XPath: {}", x); return; },
Ok(None) => { println!("Unable to compile XPath"); return; },
Ok(Some(x)) => x,
};
let d = Document::new();
let mut functions = HashMap::new();
xpath::function::register_core_functions(& mut functions);
let variables = HashMap::new();
let mut context = XPathEvaluationContext::new(d.root().to_any(),
&functions,
&variables);
context.next(d.root().to_any());
let res = expr.evaluate(&context);
println!("{}", res);
}
``` |
User edited file: "src/test/java/de/innoaccel/wamp/server/converter/GeneralMessageTests.java":
```diff
@@ -18,7 +18,7 @@
}
@Test(expected = MessageParseException.class)
- public void deserializeThrowsMessageParseExceptionWhenThereIsNoFirstField(final Websocket socket)
+ public void deserializeThrowsMessageParseExceptionWhenThereIsNoMessageCodeField(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[]", socket);
@@ -44,4 +44,4 @@
{
this.converter.deserialize("[" + Message.INVALID + "]", socket);
}
-}
+}
```
User edited file: "src/test/java/de/innoaccel/wamp/server/converter/GeneralMessageTests.java":
```diff
@@ -25,7 +25,7 @@
}
@Test(expected = MessageParseException.class)
- public void deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoNumber(final Websocket socket)
+ public void deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoNumber(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[null]", socket);
``` | ```src/test/java/de/innoaccel/wamp/server/converter/GeneralMessageTests.java
package de.innoaccel.wamp.server.converter;
import de.innoaccel.wamp.server.Websocket;
import de.innoaccel.wamp.server.message.Message;
import org.junit.Test;
import java.io.IOException;
abstract public class GeneralMessageTests<T extends Message>
{
protected JsonParsingConverter<T> converter;
@Test(expected = MessageParseException.class)
public void deserializeThrowsMessageParseExceptionWhenMessageIsNoArray(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("message", socket);
}
@Test(expected = MessageParseException.class)
public void deserializeThrowsMessageParseExceptionWhenThereIsNoMessageCodeField(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[]", socket);
}
@Test(expected = MessageParseException.class)
public void deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoNumber(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[null]", socket);
}
@Test(expected = MessageParseException.class)
<|user_cursor_is_here|>
public void deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoInteger(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[0.5f]", socket);
}
@Test(expected = InvalidMessageCodeException.class)
public void deserializeThrowsInvalidMessageCodeExceptionWhenWrongMessageCode(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[" + Message.INVALID + "]", socket);
}
}
``` | ```src/test/java/de/innoaccel/wamp/server/converter/GeneralMessageTests.java
package de.innoaccel.wamp.server.converter;
import de.innoaccel.wamp.server.Websocket;
import de.innoaccel.wamp.server.message.Message;
import org.junit.Test;
import java.io.IOException;
abstract public class GeneralMessageTests<T extends Message>
{
protected JsonParsingConverter<T> converter;
@Test(expected = MessageParseException.class)
public void deserializeThrowsMessageParseExceptionWhenMessageIsNoArray(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("message", socket);
}
@Test(expected = MessageParseException.class)
public void deserializeThrowsMessageParseExceptionWhenThereIsNoMessageCodeField(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[]", socket);
}
@Test(expected = MessageParseException.class)
public void deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoNumber(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[null]", socket);
}
@Test(expected = MessageParseException.class)
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoInteger", "newName": "deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoInteger"}}
</|tool_call|>
public void deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoInteger(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[0.5f]", socket);
}
@Test(expected = InvalidMessageCodeException.class)
public void deserializeThrowsInvalidMessageCodeExceptionWhenWrongMessageCode(final Websocket socket)
throws IOException, MessageParseException, InvalidMessageCodeException
{
this.converter.deserialize("[" + Message.INVALID + "]", socket);
}
}
``` |
User edited file: "fuzz/fuzz_targets/fuzz_asn1_parse.rs":
```diff
@@ -1,6 +1,5 @@
#![no_main]
-#[macro_use]
-extern crate libfuzzer_sys;
+use libfuzzer_sys::fuzz_target;
libfuzzer_sys::fuzz_target!(|data: &[u8]| {
let _ = asn1::parse(data, |d| {
@@ -23,4 +22,4 @@
Ok(())
});
-});
+});
``` | ```fuzz/fuzz_targets/fuzz_asn1_parse.rs
#![no_main]
use libfuzzer_sys::fuzz_target;
<|user_cursor_is_here|>
libfuzzer_sys::fuzz_target!(|data: &[u8]| {
let _ = asn1::parse(data, |d| {
d.read_element::<()>()?;
d.read_element::<bool>()?;
d.read_element::<i8>()?;
d.read_element::<u8>()?;
d.read_element::<i64>()?;
d.read_element::<u64>()?;
d.read_element::<&[u8]>()?;
d.read_element::<asn1::PrintableString>()?;
d.read_element::<asn1::ObjectIdentifier>()?;
d.read_element::<asn1::BitString>()?;
d.read_element::<asn1::UtcTime>()?;
d.read_element::<Option<()>>()?;
d.read_element::<asn1::Choice2<bool, i64>>()?;
Ok(())
});
});
``` | ```fuzz/fuzz_targets/fuzz_asn1_parse.rs
#![no_main]
use libfuzzer_sys::fuzz_target;
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "libfuzzer_sys::fuzz_target!", "newName": "fuzz_target!"}}
</|tool_call|>
libfuzzer_sys::fuzz_target!(|data: &[u8]| {
let _ = asn1::parse(data, |d| {
d.read_element::<()>()?;
d.read_element::<bool>()?;
d.read_element::<i8>()?;
d.read_element::<u8>()?;
d.read_element::<i64>()?;
d.read_element::<u64>()?;
d.read_element::<&[u8]>()?;
d.read_element::<asn1::PrintableString>()?;
d.read_element::<asn1::ObjectIdentifier>()?;
d.read_element::<asn1::BitString>()?;
d.read_element::<asn1::UtcTime>()?;
d.read_element::<Option<()>>()?;
d.read_element::<asn1::Choice2<bool, i64>>()?;
Ok(())
});
});
``` |
User edited file: "cmsplugin_zinnia/placeholder.py":
```diff
@@ -4,7 +4,7 @@
from cms.models.fields import PlaceholderField
from cms.plugin_rendering import render_placeholder
-from zinnia.models.entry import EntryAbstractClass
+from zinnia.models_bases.entry import AbstractEntry
class EntryPlaceholder(EntryAbstractClass):
@@ -39,4 +39,4 @@
class Meta(EntryAbstractClass.Meta):
"""EntryPlaceholder's Meta"""
- abstract = True
+ abstract = True
```
User edited file: "cmsplugin_zinnia/placeholder.py":
```diff
@@ -7,7 +7,7 @@
from zinnia.models_bases.entry import AbstractEntry
-class EntryPlaceholder(EntryAbstractClass):
+class EntryPlaceholder(AbstractEntry):
"""Entry with a Placeholder to edit content"""
content_placeholder = PlaceholderField('content')
``` | ```cmsplugin_zinnia/placeholder.py
"""Placeholder model for Zinnia"""
import inspect
from cms.models.fields import PlaceholderField
from cms.plugin_rendering import render_placeholder
from zinnia.models_bases.entry import AbstractEntry
class EntryPlaceholder(AbstractEntry):
"""Entry with a Placeholder to edit content"""
content_placeholder = PlaceholderField('content')
def acquire_context(self):
"""
Inspect the stack to acquire the current context used,
to render the placeholder. I'm really sorry for this,
but if you have a better way, you are welcome !
"""
frame = None
try:
for f in inspect.stack()[1:]:
frame = f[0]
args, varargs, keywords, alocals = inspect.getargvalues(frame)
if 'context' in args:
return alocals['context']
finally:
del frame
@property
def html_content(self):
"""
Render the content_placeholder field dynamicly.
https://github.com/Fantomas42/cmsplugin-zinnia/issues/3
"""
context = self.acquire_context()
return render_placeholder(self.content_placeholder, context)
<|user_cursor_is_here|>
class Meta(EntryAbstractClass.Meta):
"""EntryPlaceholder's Meta"""
abstract = True
``` | ```cmsplugin_zinnia/placeholder.py
"""Placeholder model for Zinnia"""
import inspect
from cms.models.fields import PlaceholderField
from cms.plugin_rendering import render_placeholder
from zinnia.models_bases.entry import AbstractEntry
class EntryPlaceholder(AbstractEntry):
"""Entry with a Placeholder to edit content"""
content_placeholder = PlaceholderField('content')
def acquire_context(self):
"""
Inspect the stack to acquire the current context used,
to render the placeholder. I'm really sorry for this,
but if you have a better way, you are welcome !
"""
frame = None
try:
for f in inspect.stack()[1:]:
frame = f[0]
args, varargs, keywords, alocals = inspect.getargvalues(frame)
if 'context' in args:
return alocals['context']
finally:
del frame
@property
def html_content(self):
"""
Render the content_placeholder field dynamicly.
https://github.com/Fantomas42/cmsplugin-zinnia/issues/3
"""
context = self.acquire_context()
return render_placeholder(self.content_placeholder, context)
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "EntryAbstractClass", "newName": "AbstractEntry"}}
</|tool_call|>
class Meta(EntryAbstractClass.Meta):
"""EntryPlaceholder's Meta"""
abstract = True
``` |
User edited file: "consulrest/keyvalue.py":
```diff
@@ -20,6 +20,8 @@
if r.ok:
return json.loads(r.text)
+ elif r.status_code == 404:
+ return None
else:
r.raise_for_status()
@@ -51,4 +53,4 @@
if recurse is not None:
params['recurse'] = True
r = requests.delete(url, params=params)
- r.raise_for_status()
+ r.raise_for_status()
``` | ```consulrest/keyvalue.py
import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if keys is not None:
params['keys'] = True
r = requests.get(url, params=params)
if r.ok:
return json.loads(r.text)
elif r.status_code == 404:
return None
else:
r.raise_for_status()
def get(self, key, recurse=None):
return self._get(key, recurse=recurse)
<|user_cursor_is_here|>
def list(self, key=''):
return self._get(key, keys=True)
def set(self, key, value, cas=None):
params = dict()
if cas is not None:
params['cas'] = cas
r = requests.put(self._url + '/' + key, data=value, params=params)
if r.ok:
if re.match(r"true", r.text) is not None:
return True
elif re.match(r"false", r.text) is not None:
return False
else:
r.raise_for_status()
def delete(self, key, recurse=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
r = requests.delete(url, params=params)
r.raise_for_status()
``` | ```consulrest/keyvalue.py
import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if keys is not None:
params['keys'] = True
r = requests.get(url, params=params)
if r.ok:
return json.loads(r.text)
elif r.status_code == 404:
return None
else:
r.raise_for_status()
def get(self, key, recurse=None):
return self._get(key, recurse=recurse)
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "list", "newName": "list_keys"}}
</|tool_call|>
def list(self, key=''):
return self._get(key, keys=True)
def set(self, key, value, cas=None):
params = dict()
if cas is not None:
params['cas'] = cas
r = requests.put(self._url + '/' + key, data=value, params=params)
if r.ok:
if re.match(r"true", r.text) is not None:
return True
elif re.match(r"false", r.text) is not None:
return False
else:
r.raise_for_status()
def delete(self, key, recurse=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
r = requests.delete(url, params=params)
r.raise_for_status()
``` |
User edited file: "src/KeyboardObserver.js":
```diff
@@ -1,4 +1,4 @@
-import {DeviceEventEmitter} from 'react-native';
+import {Keyboard} from 'react-native';
class KeyboardObserver {
@@ -42,4 +42,4 @@
}
}
-export default new KeyboardObserver();
+export default new KeyboardObserver();
``` | ```src/KeyboardObserver.js
import {Keyboard} from 'react-native';
class KeyboardObserver {
constructor() {
this.keyboardHeight = 0;
this.animationWillEndAt = 0;
this.listeners = {};
this.listenerId = 0;
<|user_cursor_is_here|>
DeviceEventEmitter.addListener('keyboardWillShow', this.handleKeyboardWillShow.bind(this));
DeviceEventEmitter.addListener('keyboardWillHide', this.handleKeyboardWillHide.bind(this));
}
addListener(callback) {
const id = this.listenerId++;
this.listeners[id] = callback;
return {remove: () => delete this.listeners[id]};
}
notifyListeners() {
const info = this.getKeyboardInfo();
Object.keys(this.listeners).forEach(key => this.listeners[key](info));
}
handleKeyboardWillShow(frames) {
this.keyboardHeight = frames.endCoordinates.height;
this.animationWillEndAt = new Date().getTime() + frames.duration;
this.notifyListeners()
}
handleKeyboardWillHide(frames) {
this.animationWillEndAt = new Date().getTime() + frames.duration;
this.keyboardHeight = 0;
this.notifyListeners()
}
getKeyboardInfo() {
return {
keyboardHeight: this.keyboardHeight,
animationWillEndAt: this.animationWillEndAt,
};
}
}
export default new KeyboardObserver();
``` | ```src/KeyboardObserver.js
import {Keyboard} from 'react-native';
class KeyboardObserver {
constructor() {
this.keyboardHeight = 0;
this.animationWillEndAt = 0;
this.listeners = {};
this.listenerId = 0;
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "DeviceEventEmitter", "newName": "Keyboard"}}
</|tool_call|>
DeviceEventEmitter.addListener('keyboardWillShow', this.handleKeyboardWillShow.bind(this));
DeviceEventEmitter.addListener('keyboardWillHide', this.handleKeyboardWillHide.bind(this));
}
addListener(callback) {
const id = this.listenerId++;
this.listeners[id] = callback;
return {remove: () => delete this.listeners[id]};
}
notifyListeners() {
const info = this.getKeyboardInfo();
Object.keys(this.listeners).forEach(key => this.listeners[key](info));
}
handleKeyboardWillShow(frames) {
this.keyboardHeight = frames.endCoordinates.height;
this.animationWillEndAt = new Date().getTime() + frames.duration;
this.notifyListeners()
}
handleKeyboardWillHide(frames) {
this.animationWillEndAt = new Date().getTime() + frames.duration;
this.keyboardHeight = 0;
this.notifyListeners()
}
getKeyboardInfo() {
return {
keyboardHeight: this.keyboardHeight,
animationWillEndAt: this.animationWillEndAt,
};
}
}
export default new KeyboardObserver();
``` |
User edited file: "src/gx/realtime/RealtimeOptions.java":
```diff
@@ -1,5 +1,6 @@
package gx.realtime;
+import gx.realtime.RealtimeLoader.OnDocumentLoadedCallback;
import gx.realtime.RealtimeLoader.InitializeModelCallback;
import gx.realtime.RealtimeLoader.HandleErrorsCallback;
@@ -56,4 +57,4 @@
public void setHandleErrors(HandleErrorsCallback handleErrors) {
this.handleErrors = handleErrors;
}
-}
+}
```
User edited file: "src/gx/realtime/RealtimeOptions.java":
```diff
@@ -9,11 +9,10 @@
*/
public class RealtimeOptions {
- // Attributes
private String clientId;
private String docId;
- private RealtimeLoader.OnDocumentLoadedCallback onFileLoaded;
+ private OnDocumentLoadedCallback onFileLoaded;
private InitializeModelCallback initializeModel;
private HandleErrorsCallback handleErrors;
```
User edited file: "src/gx/realtime/RealtimeOptions.java":
```diff
@@ -33,7 +33,7 @@
this.docId = docId;
}
- public RealtimeLoader.OnDocumentLoadedCallback getOnFileLoaded() {
+ public OnDocumentLoadedCallback getOnFileLoaded() {
return onFileLoaded;
}
``` | ```src/gx/realtime/RealtimeOptions.java
package gx.realtime;
import gx.realtime.RealtimeLoader.OnDocumentLoadedCallback;
import gx.realtime.RealtimeLoader.InitializeModelCallback;
import gx.realtime.RealtimeLoader.HandleErrorsCallback;
/**
* Options (key/value) for the RealtimeLoader.
*/
public class RealtimeOptions {
private String clientId;
private String docId;
private OnDocumentLoadedCallback onFileLoaded;
private InitializeModelCallback initializeModel;
private HandleErrorsCallback handleErrors;
// Methods
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getDocId() {
return docId;
}
public void setDocId(String docId) {
this.docId = docId;
}
public OnDocumentLoadedCallback getOnFileLoaded() {
return onFileLoaded;
}
<|user_cursor_is_here|>
public void setOnFileLoaded(RealtimeLoader.OnDocumentLoadedCallback onFileLoaded) {
this.onFileLoaded = onFileLoaded;
}
public InitializeModelCallback getInitializeModel() {
return initializeModel;
}
public void setInitializeModel(InitializeModelCallback initializeModel) {
this.initializeModel = initializeModel;
}
public HandleErrorsCallback getHandleErrors() {
return handleErrors;
}
public void setHandleErrors(HandleErrorsCallback handleErrors) {
this.handleErrors = handleErrors;
}
}
``` | ```src/gx/realtime/RealtimeOptions.java
package gx.realtime;
import gx.realtime.RealtimeLoader.OnDocumentLoadedCallback;
import gx.realtime.RealtimeLoader.InitializeModelCallback;
import gx.realtime.RealtimeLoader.HandleErrorsCallback;
/**
* Options (key/value) for the RealtimeLoader.
*/
public class RealtimeOptions {
private String clientId;
private String docId;
private OnDocumentLoadedCallback onFileLoaded;
private InitializeModelCallback initializeModel;
private HandleErrorsCallback handleErrors;
// Methods
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getDocId() {
return docId;
}
public void setDocId(String docId) {
this.docId = docId;
}
public OnDocumentLoadedCallback getOnFileLoaded() {
return onFileLoaded;
}
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "RealtimeLoader.OnDocumentLoadedCallback", "newName": "OnDocumentLoadedCallback"}}
</|tool_call|>
public void setOnFileLoaded(RealtimeLoader.OnDocumentLoadedCallback onFileLoaded) {
this.onFileLoaded = onFileLoaded;
}
public InitializeModelCallback getInitializeModel() {
return initializeModel;
}
public void setInitializeModel(InitializeModelCallback initializeModel) {
this.initializeModel = initializeModel;
}
public HandleErrorsCallback getHandleErrors() {
return handleErrors;
}
public void setHandleErrors(HandleErrorsCallback handleErrors) {
this.handleErrors = handleErrors;
}
}
``` |
User edited file: "test/dom/test/basics.spec.js":
```diff
@@ -11,7 +11,7 @@
it('absolute tracking', async () => {
let times = 0;
let poolCopy;
- const targetOne = createTarget({ marginLeft: '-30px' });
+ const targetOne = createTarget({ left: '-30px' });
const targetTwo = createTarget({ marginTop: '30px' });
const targetThree = createTarget({ marginTop: '-30px' });
@@ -61,4 +61,4 @@
expect(times).to.equal(1);
expect(poolCopy).to.include(targetThree);
});
-});
+});
```
User edited file: "test/dom/test/basics.spec.js":
```diff
@@ -12,7 +12,7 @@
let times = 0;
let poolCopy;
const targetOne = createTarget({ left: '-30px' });
- const targetTwo = createTarget({ marginTop: '30px' });
+ const targetTwo = createTarget({ top: '30px' });
const targetThree = createTarget({ marginTop: '-30px' });
new Tracker({
``` | ```test/dom/test/basics.spec.js
/**
* Basics
*/
describe('Basics', () => {
beforeEach(beforeEachHook);
afterEach(afterEachHook);
/**
* Absolute tracking
*/
it('absolute tracking', async () => {
let times = 0;
let poolCopy;
const targetOne = createTarget({ left: '-30px' });
const targetTwo = createTarget({ top: '30px' });
<|user_cursor_is_here|>
const targetThree = createTarget({ marginTop: '-30px' });
new Tracker({
targets: document.getElementsByClassName('target'),
snapshots: [
{
callback({ DOMElement, pool }) {
animate(DOMElement);
times++;
poolCopy = pool;
}
}
]
});
await scroll(0, 10);
expect(times).to.equal(1);
expect(poolCopy).to.include(targetTwo);
});
/**
* Relative tracking
*/
it('relative tracking', async () => {
let times = 0;
let poolCopy;
const targetOne = createTarget({ left: '-20px' }, bounds);
const targetTwo = createTarget({ top: '-20px' }, bounds);
const targetThree = createTarget({}, bounds);
new Tracker({
targets: document.getElementsByClassName('target'),
bounds,
snapshots: [
{
callback({ DOMElement, pool }) {
animate(DOMElement);
times++;
poolCopy = pool;
}
}
]
});
await scroll(0, 10);
expect(times).to.equal(1);
expect(poolCopy).to.include(targetThree);
});
});
``` | ```test/dom/test/basics.spec.js
/**
* Basics
*/
describe('Basics', () => {
beforeEach(beforeEachHook);
afterEach(afterEachHook);
/**
* Absolute tracking
*/
it('absolute tracking', async () => {
let times = 0;
let poolCopy;
const targetOne = createTarget({ left: '-30px' });
const targetTwo = createTarget({ top: '30px' });
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "marginTop", "newName": "top"}}
</|tool_call|>
const targetThree = createTarget({ marginTop: '-30px' });
new Tracker({
targets: document.getElementsByClassName('target'),
snapshots: [
{
callback({ DOMElement, pool }) {
animate(DOMElement);
times++;
poolCopy = pool;
}
}
]
});
await scroll(0, 10);
expect(times).to.equal(1);
expect(poolCopy).to.include(targetTwo);
});
/**
* Relative tracking
*/
it('relative tracking', async () => {
let times = 0;
let poolCopy;
const targetOne = createTarget({ left: '-20px' }, bounds);
const targetTwo = createTarget({ top: '-20px' }, bounds);
const targetThree = createTarget({}, bounds);
new Tracker({
targets: document.getElementsByClassName('target'),
bounds,
snapshots: [
{
callback({ DOMElement, pool }) {
animate(DOMElement);
times++;
poolCopy = pool;
}
}
]
});
await scroll(0, 10);
expect(times).to.equal(1);
expect(poolCopy).to.include(targetThree);
});
});
``` |
User edited file: "src/main/kotlin/com/simonorono/bitc/BitArray.kt":
```diff
@@ -1,4 +1,6 @@
package com.simonorono.bitc
+
+import kotlin.math.ceil
/**
* The BitArray class represents an array of booleans. It stores them packed
@@ -50,4 +52,4 @@
*/
val indices: IntRange
get() = IntRange(0, size - 1)
-}
+}
``` | ```src/main/kotlin/com/simonorono/bitc/BitArray.kt
package com.simonorono.bitc
import kotlin.math.ceil
/**
* The BitArray class represents an array of booleans. It stores them packed
* inside regular integers to not waste the overhead of storing booleans.
*
* @property size The size of the array
*/
class BitArray(val size: Int) {
private val innerArray = IntArray(
1.coerceAtLeast(
<|user_cursor_is_here|>
Math.ceil(size.toDouble() / Int.SIZE_BITS.toDouble()).toInt()
)
) { 0 }
private fun checkBounds(idx: Int) {
if (idx < 0 || idx >= size) {
throw IndexOutOfBoundsException()
}
}
/**
* Retrieve the value at position [idx].
*/
operator fun get(idx: Int): Boolean {
checkBounds(idx)
return (innerArray[idx / Int.SIZE_BITS] and (1 shl (idx % Int.SIZE_BITS))) != 0
}
/**
* Sets the value at position [idx].
*/
operator fun set(idx: Int, value: Boolean) {
checkBounds(idx)
val current = innerArray[idx / Int.SIZE_BITS]
if (value) {
innerArray[idx / Int.SIZE_BITS] =
current or (1 shl (idx % Int.SIZE_BITS))
} else {
innerArray[idx / Int.SIZE_BITS] =
current and (1 shl (idx % Int.SIZE_BITS)).inv()
}
}
/**
* The range of indices of the array.
*/
val indices: IntRange
get() = IntRange(0, size - 1)
}
``` | ```src/main/kotlin/com/simonorono/bitc/BitArray.kt
package com.simonorono.bitc
import kotlin.math.ceil
/**
* The BitArray class represents an array of booleans. It stores them packed
* inside regular integers to not waste the overhead of storing booleans.
*
* @property size The size of the array
*/
class BitArray(val size: Int) {
private val innerArray = IntArray(
1.coerceAtLeast(
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "Math.ceil", "newName": "ceil"}}
</|tool_call|>
Math.ceil(size.toDouble() / Int.SIZE_BITS.toDouble()).toInt()
)
) { 0 }
private fun checkBounds(idx: Int) {
if (idx < 0 || idx >= size) {
throw IndexOutOfBoundsException()
}
}
/**
* Retrieve the value at position [idx].
*/
operator fun get(idx: Int): Boolean {
checkBounds(idx)
return (innerArray[idx / Int.SIZE_BITS] and (1 shl (idx % Int.SIZE_BITS))) != 0
}
/**
* Sets the value at position [idx].
*/
operator fun set(idx: Int, value: Boolean) {
checkBounds(idx)
val current = innerArray[idx / Int.SIZE_BITS]
if (value) {
innerArray[idx / Int.SIZE_BITS] =
current or (1 shl (idx % Int.SIZE_BITS))
} else {
innerArray[idx / Int.SIZE_BITS] =
current and (1 shl (idx % Int.SIZE_BITS)).inv()
}
}
/**
* The range of indices of the array.
*/
val indices: IntRange
get() = IntRange(0, size - 1)
}
``` |
User edited file: "module/index.js":
```diff
@@ -1,3 +1,10 @@
+const requireFromString = (source, filename) => {
+ var m = new module.constructor();
+ m._compile(source, filename);
+ return m.exports;
+};
+ // Credits: http://stackoverflow.com/a/17585470/2816199
+
const startsWithDot = /^\./;
const moduleIdParts = /^((?:[a-z\-]+!)*)(.*)$/;
// ^ From the beginning of the string match:
@@ -27,4 +34,4 @@
}
));
};
-};
+};
```
User edited file: "module/index.js":
```diff
@@ -4,6 +4,17 @@
return m.exports;
};
// Credits: http://stackoverflow.com/a/17585470/2816199
+
+const loaderContext = {
+ cacheable() {},
+ dependencies() {},
+ async() {throw new Error(
+ 'isomorphic-ensure: Async modules are not supported.'
+ );},
+ resolve() {throw new Error(
+ 'isomorphic-ensure: Loaders which use `this.resolve` are not supported.'
+ );},
+};
const startsWithDot = /^\./;
const moduleIdParts = /^((?:[a-z\-]+!)*)(.*)$/;
```
User edited file: "module/index.js":
```diff
@@ -27,8 +27,8 @@
// $ until the end of the string.
export default (settings = {}) => {
- // const {loaders} = settings;
- // const {readFileSync} = require('fs');
+ const {loaders} = settings;
+ const {readFileSync} = require('fs');
return (dependencies, callback, context) => {
const {dirname} = context;
``` | ```module/index.js
const requireFromString = (source, filename) => {
var m = new module.constructor();
m._compile(source, filename);
return m.exports;
};
// Credits: http://stackoverflow.com/a/17585470/2816199
const loaderContext = {
cacheable() {},
dependencies() {},
async() {throw new Error(
'isomorphic-ensure: Async modules are not supported.'
);},
resolve() {throw new Error(
'isomorphic-ensure: Loaders which use `this.resolve` are not supported.'
);},
};
const startsWithDot = /^\./;
const moduleIdParts = /^((?:[a-z\-]+!)*)(.*)$/;
// ^ From the beginning of the string match:
// ((?: 1.
// [a-z\-]+ A loader name, consisting of lowercase letters and hyphens
// ! followed by a bang
// )*) as many times as possible.
// (.*) 2. Any sequence of characters
// $ until the end of the string.
export default (settings = {}) => {
const {loaders} = settings;
const {readFileSync} = require('fs');
return (dependencies, callback, context) => {
const {dirname} = context;
process.nextTick(() => callback(
(moduleId) => {
<|user_cursor_is_here|>
const [, loadersList, rawPath] = moduleId.match(moduleIdParts);
const loaders = loadersList.split('!').slice(0, -1);
const modulePath = (startsWithDot.test(rawPath) ?
`${dirname}/${rawPath}` :
require.resolve(rawPath)
);
return require(modulePath);
}
));
};
};
``` | ```module/index.js
const requireFromString = (source, filename) => {
var m = new module.constructor();
m._compile(source, filename);
return m.exports;
};
// Credits: http://stackoverflow.com/a/17585470/2816199
const loaderContext = {
cacheable() {},
dependencies() {},
async() {throw new Error(
'isomorphic-ensure: Async modules are not supported.'
);},
resolve() {throw new Error(
'isomorphic-ensure: Loaders which use `this.resolve` are not supported.'
);},
};
const startsWithDot = /^\./;
const moduleIdParts = /^((?:[a-z\-]+!)*)(.*)$/;
// ^ From the beginning of the string match:
// ((?: 1.
// [a-z\-]+ A loader name, consisting of lowercase letters and hyphens
// ! followed by a bang
// )*) as many times as possible.
// (.*) 2. Any sequence of characters
// $ until the end of the string.
export default (settings = {}) => {
const {loaders} = settings;
const {readFileSync} = require('fs');
return (dependencies, callback, context) => {
const {dirname} = context;
process.nextTick(() => callback(
(moduleId) => {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "loadersList", "newName": "loadersPart"}}
</|tool_call|>
const [, loadersList, rawPath] = moduleId.match(moduleIdParts);
const loaders = loadersList.split('!').slice(0, -1);
const modulePath = (startsWithDot.test(rawPath) ?
`${dirname}/${rawPath}` :
require.resolve(rawPath)
);
return require(modulePath);
}
));
};
};
``` |
User edited file: "ml/test_amaranth_lib.py":
```diff
@@ -5,6 +5,9 @@
class TestAmaranthHelpers(unittest.TestCase):
+
+ def test_combine_dataframes(self):
+ raise NotImplementedError
def test_load_calorie_data(self):
raise NotImplementedError
@@ -26,4 +29,4 @@
if __name__ == '__main__':
- unittest.main()
+ unittest.main()
``` | ```ml/test_amaranth_lib.py
# Lint as: python3
"""These tests ensure correctness for the helper functions in amaranth_lib."""
import unittest
class TestAmaranthHelpers(unittest.TestCase):
def test_combine_dataframes(self):
raise NotImplementedError
<|user_cursor_is_here|>
def test_load_calorie_data(self):
raise NotImplementedError
def test_clean_data(self):
raise NotImplementedError
def test_add_calorie_labels(self):
raise NotImplementedError
def test_num_unique_words(self):
raise NotImplementedError
def test_max_sequence_length(self):
raise NotImplementedError
def test_add_input_labels(self):
raise NotImplementedError
if __name__ == '__main__':
unittest.main()
``` | ```ml/test_amaranth_lib.py
# Lint as: python3
"""These tests ensure correctness for the helper functions in amaranth_lib."""
import unittest
class TestAmaranthHelpers(unittest.TestCase):
def test_combine_dataframes(self):
raise NotImplementedError
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "test_load_calorie_data", "newName": "test_get_calorie_data"}}
</|tool_call|>
def test_load_calorie_data(self):
raise NotImplementedError
def test_clean_data(self):
raise NotImplementedError
def test_add_calorie_labels(self):
raise NotImplementedError
def test_num_unique_words(self):
raise NotImplementedError
def test_max_sequence_length(self):
raise NotImplementedError
def test_add_input_labels(self):
raise NotImplementedError
if __name__ == '__main__':
unittest.main()
``` |
User edited file: "lib/components/completeBlock/completeBlock.js":
```diff
@@ -1,4 +1,4 @@
-import CompleteBlock from './completeBlock.html';
+import TemplateCompleteBlock from './completeBlock.html';
import './completeBlock.scss';
class CompleteBlock {
@@ -19,4 +19,4 @@
}
}
-export default CompleteBlock.detailsComponent();
+export default CompleteBlock.detailsComponent();
``` | ```lib/components/completeBlock/completeBlock.js
import TemplateCompleteBlock from './completeBlock.html';
import './completeBlock.scss';
class CompleteBlock {
static detailsComponent() {
return {
<|user_cursor_is_here|>
templateUrl: CompleteBlock,
bindings: {
headerImg: '@',
headerTitle: '@',
headerPicto: '@',
headerColor: '@',
headerBackgroundColor: '@',
bodyBackgroundColor: '@',
bodyTitle: '@',
bodyText: '@'
}
};
}
}
export default CompleteBlock.detailsComponent();
``` | ```lib/components/completeBlock/completeBlock.js
import TemplateCompleteBlock from './completeBlock.html';
import './completeBlock.scss';
class CompleteBlock {
static detailsComponent() {
return {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "CompleteBlock", "newName": "TemplateCompleteBlock"}}
</|tool_call|>
templateUrl: CompleteBlock,
bindings: {
headerImg: '@',
headerTitle: '@',
headerPicto: '@',
headerColor: '@',
headerBackgroundColor: '@',
bodyBackgroundColor: '@',
bodyTitle: '@',
bodyText: '@'
}
};
}
}
export default CompleteBlock.detailsComponent();
``` |
User edited file: "exercises/bank-account/src/example/kotlin/BankAccount.kt":
```diff
@@ -24,4 +24,5 @@
}
}
-}
+ private val lock = Any()
+}
```
User edited file: "exercises/bank-account/src/example/kotlin/BankAccount.kt":
```diff
@@ -1,12 +1,11 @@
class BankAccount {
var balance: Long = 0
get() {
- synchronized(this) {
- if (!isOpen) throw IllegalStateException("Account is closed")
- return field
- }
+ synchronized(lock) {
+ if (!isOpen) throw IllegalStateException("Account is closed")
+ return field
+ }
}
-
private set
var isOpen = true
```
User edited file: "exercises/bank-account/src/example/kotlin/BankAccount.kt":
```diff
@@ -12,7 +12,7 @@
private set
fun adjustBalance(amount: Long) {
- synchronized(this) {
+ synchronized(lock) {
balance += amount
}
}
``` | ```exercises/bank-account/src/example/kotlin/BankAccount.kt
class BankAccount {
var balance: Long = 0
get() {
synchronized(lock) {
if (!isOpen) throw IllegalStateException("Account is closed")
return field
}
}
private set
var isOpen = true
private set
fun adjustBalance(amount: Long) {
synchronized(lock) {
balance += amount
}
}
fun close() {
<|user_cursor_is_here|>
synchronized(this) {
isOpen = false
}
}
private val lock = Any()
}
``` | ```exercises/bank-account/src/example/kotlin/BankAccount.kt
class BankAccount {
var balance: Long = 0
get() {
synchronized(lock) {
if (!isOpen) throw IllegalStateException("Account is closed")
return field
}
}
private set
var isOpen = true
private set
fun adjustBalance(amount: Long) {
synchronized(lock) {
balance += amount
}
}
fun close() {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "this", "newName": "lock"}}
</|tool_call|>
synchronized(this) {
isOpen = false
}
}
private val lock = Any()
}
``` |
User edited file: "python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt":
```diff
@@ -3,7 +3,6 @@
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
-import icons.PythonIcons
import java.io.File
import javax.swing.Icon
@@ -51,4 +50,4 @@
class MayaFlavorProvider: PythonFlavorProvider {
override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE
-}
+}
```
User edited file: "python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt":
```diff
@@ -4,7 +4,6 @@
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
-import javax.swing.Icon
class MayaSdkFlavor private constructor() : PythonSdkFlavor() {
``` | ```python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk.flavors
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
<|user_cursor_is_here|>
class MayaSdkFlavor private constructor() : PythonSdkFlavor() {
override fun isValidSdkHome(path: String): Boolean {
val file = File(path)
return file.isFile && isValidSdkPath(file) || isMayaFolder(file)
}
override fun isValidSdkPath(file: File): Boolean {
val name = FileUtil.getNameWithoutExtension(file).toLowerCase()
return name.startsWith("mayapy")
}
override fun getVersionOption(): String {
return "--version"
}
override fun getName(): String {
return "MayaPy"
}
override fun getIcon(): Icon {
return PythonIcons.Python.Python //TODO: maya icon
}
override fun getSdkPath(path: VirtualFile): VirtualFile? {
if (isMayaFolder(File(path.path))) {
return path.findFileByRelativePath("Contents/bin/mayapy")
}
return path
}
companion object {
var INSTANCE: MayaSdkFlavor = MayaSdkFlavor()
private fun isMayaFolder(file: File): Boolean {
return file.isDirectory && file.name == "Maya.app"
}
}
}
class MayaFlavorProvider: PythonFlavorProvider {
override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE
}
``` | ```python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk.flavors
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "PythonSdkFlavor", "newName": "CPythonSdkFlavor"}}
</|tool_call|>
class MayaSdkFlavor private constructor() : PythonSdkFlavor() {
override fun isValidSdkHome(path: String): Boolean {
val file = File(path)
return file.isFile && isValidSdkPath(file) || isMayaFolder(file)
}
override fun isValidSdkPath(file: File): Boolean {
val name = FileUtil.getNameWithoutExtension(file).toLowerCase()
return name.startsWith("mayapy")
}
override fun getVersionOption(): String {
return "--version"
}
override fun getName(): String {
return "MayaPy"
}
override fun getIcon(): Icon {
return PythonIcons.Python.Python //TODO: maya icon
}
override fun getSdkPath(path: VirtualFile): VirtualFile? {
if (isMayaFolder(File(path.path))) {
return path.findFileByRelativePath("Contents/bin/mayapy")
}
return path
}
companion object {
var INSTANCE: MayaSdkFlavor = MayaSdkFlavor()
private fun isMayaFolder(file: File): Boolean {
return file.isDirectory && file.name == "Maya.app"
}
}
}
class MayaFlavorProvider: PythonFlavorProvider {
override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE
}
``` |
User edited file: "csunplugged/utils/check_glossary_links.py":
```diff
@@ -1,5 +1,6 @@
"""Module for checking glossary links found within Markdown conversions."""
+from django.core.exceptions import DoesNotExist
from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm
from topics.models import GlossaryTerm
@@ -14,4 +15,4 @@
try:
GlossaryTerm.objects.get(slug=term)
except ObjectDoesNotExist:
- raise CouldNotFindGlossaryTerm(term, md_file_path)
+ raise CouldNotFindGlossaryTerm(term, md_file_path)
``` | ```csunplugged/utils/check_glossary_links.py
"""Module for checking glossary links found within Markdown conversions."""
from django.core.exceptions import DoesNotExist
from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm
from topics.models import GlossaryTerm
def check_converter_glossary_links(glossary_links, md_file_path):
"""Process glossary links found by Markdown converter.
Args:
glossary_links: Dictionary of glossary links (dict).
"""
for term in glossary_links.keys():
try:
GlossaryTerm.objects.get(slug=term)
<|user_cursor_is_here|>
except ObjectDoesNotExist:
raise CouldNotFindGlossaryTerm(term, md_file_path)
``` | ```csunplugged/utils/check_glossary_links.py
"""Module for checking glossary links found within Markdown conversions."""
from django.core.exceptions import DoesNotExist
from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm
from topics.models import GlossaryTerm
def check_converter_glossary_links(glossary_links, md_file_path):
"""Process glossary links found by Markdown converter.
Args:
glossary_links: Dictionary of glossary links (dict).
"""
for term in glossary_links.keys():
try:
GlossaryTerm.objects.get(slug=term)
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "ObjectDoesNotExist", "newName": "DoesNotExist"}}
</|tool_call|>
except ObjectDoesNotExist:
raise CouldNotFindGlossaryTerm(term, md_file_path)
``` |
User edited file: "src/test/java/seedu/address/testutil/ItemBuilder.java":
```diff
@@ -9,7 +9,7 @@
*/
public class ItemBuilder {
- private TestItem person;
+ private TestItem item;
public ItemBuilder() {
this.person = new TestItem();
@@ -56,4 +56,4 @@
return this.person;
}
-}
+}
```
User edited file: "src/test/java/seedu/address/testutil/ItemBuilder.java":
```diff
@@ -12,7 +12,7 @@
private TestItem item;
public ItemBuilder() {
- this.person = new TestItem();
+ this.item = new TestItem();
}
public ItemBuilder withItemType(String itemType) throws IllegalValueException {
```
User edited file: "src/test/java/seedu/address/testutil/ItemBuilder.java":
```diff
@@ -16,7 +16,7 @@
}
public ItemBuilder withItemType(String itemType) throws IllegalValueException {
- this.person.setItemType(new ItemType(itemType));
+ this.item.setItemType(new ItemType(itemType));
return this;
}
``` | ```src/test/java/seedu/address/testutil/ItemBuilder.java
package seedu.address.testutil;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.item.*;
import seedu.address.model.tag.Tag;
/**
*
*/
public class ItemBuilder {
private TestItem item;
public ItemBuilder() {
this.item = new TestItem();
}
public ItemBuilder withItemType(String itemType) throws IllegalValueException {
this.item.setItemType(new ItemType(itemType));
return this;
}
public ItemBuilder withTags(String ... tags) throws IllegalValueException {
for (String tag: tags) {
<|user_cursor_is_here|>
person.getTags().add(new Tag(tag));
}
return this;
}
public ItemBuilder withEndDate(String endDate) throws IllegalValueException {
this.person.setEndDate(new Date(endDate));
return this;
}
public ItemBuilder withEndTime(String endTime) throws IllegalValueException {
this.person.setEndTime(new Time(endTime));
return this;
}
public ItemBuilder withName(String name) throws IllegalValueException {
this.person.setName(new Name(name));
return this;
}
public ItemBuilder withStartDate(String startDate) throws IllegalValueException {
this.person.setStartDate(new Date(startDate));
return this;
}
public ItemBuilder withStartTime(String startTime) throws IllegalValueException {
this.person.setStartTime(new Time(startTime));
return this;
}
public TestItem build() {
return this.person;
}
}
``` | ```src/test/java/seedu/address/testutil/ItemBuilder.java
package seedu.address.testutil;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.item.*;
import seedu.address.model.tag.Tag;
/**
*
*/
public class ItemBuilder {
private TestItem item;
public ItemBuilder() {
this.item = new TestItem();
}
public ItemBuilder withItemType(String itemType) throws IllegalValueException {
this.item.setItemType(new ItemType(itemType));
return this;
}
public ItemBuilder withTags(String ... tags) throws IllegalValueException {
for (String tag: tags) {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "person", "newName": "item"}}
</|tool_call|>
person.getTags().add(new Tag(tag));
}
return this;
}
public ItemBuilder withEndDate(String endDate) throws IllegalValueException {
this.person.setEndDate(new Date(endDate));
return this;
}
public ItemBuilder withEndTime(String endTime) throws IllegalValueException {
this.person.setEndTime(new Time(endTime));
return this;
}
public ItemBuilder withName(String name) throws IllegalValueException {
this.person.setName(new Name(name));
return this;
}
public ItemBuilder withStartDate(String startDate) throws IllegalValueException {
this.person.setStartDate(new Date(startDate));
return this;
}
public ItemBuilder withStartTime(String startTime) throws IllegalValueException {
this.person.setStartTime(new Time(startTime));
return this;
}
public TestItem build() {
return this.person;
}
}
``` |
User edited file: "django_lightweight_queue/task.py":
```diff
@@ -27,10 +27,10 @@
return "<TaskWrapper: %s>" % self.path
def __call__(self, *args, **kwargs):
- # Allow us to override which queue at the last moment
+ # Allow us to override the default values dynamically
queue = kwargs.pop('django_lightweight_queue_queue', self.queue)
job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop)
job.validate()
- get_backend().enqueue(job, queue)
+ get_backend().enqueue(job, queue)
```
User edited file: "django_lightweight_queue/task.py":
```diff
@@ -29,6 +29,7 @@
def __call__(self, *args, **kwargs):
# Allow us to override the default values dynamically
queue = kwargs.pop('django_lightweight_queue_queue', self.queue)
+ timeout = kwargs.pop('django_lightweight_queue_timeout', self.timeout)
job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop)
job.validate()
```
User edited file: "django_lightweight_queue/task.py":
```diff
@@ -30,6 +30,10 @@
# Allow us to override the default values dynamically
queue = kwargs.pop('django_lightweight_queue_queue', self.queue)
timeout = kwargs.pop('django_lightweight_queue_timeout', self.timeout)
+ sigkill_on_stop = kwargs.pop(
+ 'django_lightweight_queue_sigkill_on_stop',
+ self.sigkill_on_stop,
+ )
job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop)
job.validate()
``` | ```django_lightweight_queue/task.py
from .job import Job
from .utils import get_backend
from . import app_settings
class task(object):
def __init__(self, queue='default', timeout=None, sigkill_on_stop=False):
self.queue = queue
self.timeout = timeout
self.sigkill_on_stop = sigkill_on_stop
app_settings.WORKERS.setdefault(self.queue, 1)
def __call__(self, fn):
return TaskWrapper(fn, self.queue, self.timeout, self.sigkill_on_stop)
class TaskWrapper(object):
def __init__(self, fn, queue, timeout, sigkill_on_stop):
self.fn = fn
self.queue = queue
self.timeout = timeout
self.sigkill_on_stop = sigkill_on_stop
self.path = '%s.%s' % (fn.__module__, fn.__name__)
def __repr__(self):
return "<TaskWrapper: %s>" % self.path
def __call__(self, *args, **kwargs):
# Allow us to override the default values dynamically
queue = kwargs.pop('django_lightweight_queue_queue', self.queue)
timeout = kwargs.pop('django_lightweight_queue_timeout', self.timeout)
sigkill_on_stop = kwargs.pop(
'django_lightweight_queue_sigkill_on_stop',
self.sigkill_on_stop,
)
<|user_cursor_is_here|>
job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop)
job.validate()
get_backend().enqueue(job, queue)
``` | ```django_lightweight_queue/task.py
from .job import Job
from .utils import get_backend
from . import app_settings
class task(object):
def __init__(self, queue='default', timeout=None, sigkill_on_stop=False):
self.queue = queue
self.timeout = timeout
self.sigkill_on_stop = sigkill_on_stop
app_settings.WORKERS.setdefault(self.queue, 1)
def __call__(self, fn):
return TaskWrapper(fn, self.queue, self.timeout, self.sigkill_on_stop)
class TaskWrapper(object):
def __init__(self, fn, queue, timeout, sigkill_on_stop):
self.fn = fn
self.queue = queue
self.timeout = timeout
self.sigkill_on_stop = sigkill_on_stop
self.path = '%s.%s' % (fn.__module__, fn.__name__)
def __repr__(self):
return "<TaskWrapper: %s>" % self.path
def __call__(self, *args, **kwargs):
# Allow us to override the default values dynamically
queue = kwargs.pop('django_lightweight_queue_queue', self.queue)
timeout = kwargs.pop('django_lightweight_queue_timeout', self.timeout)
sigkill_on_stop = kwargs.pop(
'django_lightweight_queue_sigkill_on_stop',
self.sigkill_on_stop,
)
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "self.timeout", "newName": "timeout"}}
</|tool_call|>
job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop)
job.validate()
get_backend().enqueue(job, queue)
``` |
User edited file: "src/autobot/src/stopsign.py":
```diff
@@ -14,7 +14,7 @@
def __init__(self):
self.state = StopStates.NORMAL
self.stopDuration = 2
- self.ignoreDuration = 2
+ self.ignoreDuration = 4
def stopSignDetected(self):
self.state = StopStates.FULL_STOP
@@ -33,4 +33,4 @@
oneshot=True)
elif self.state is StopStates.IGNORE_STOP_SIGNS:
- self.action = StopStates.NORMAL
+ self.action = StopStates.NORMAL
```
User edited file: "src/autobot/src/stopsign.py":
```diff
@@ -22,7 +22,7 @@
self.stepStateMachine,
oneshot=True)
- def stepStateMachine(self):
+ def stepStateMachine(self, event):
if self.state is StopStates.NORMAL:
self.action = StopStates.FULL_STOP
``` | ```src/autobot/src/stopsign.py
#!/usr/bin/env python
import rospy
class StopStates(object):
NORMAL = 0
FULL_STOP = 1
IGNORE_STOP_SIGNS = 2
class StopSign(object):
def __init__(self):
self.state = StopStates.NORMAL
self.stopDuration = 2
self.ignoreDuration = 4
def stopSignDetected(self):
self.state = StopStates.FULL_STOP
timer = rospy.Timer(rospy.Duration(self.stopDuration),
self.stepStateMachine,
oneshot=True)
def stepStateMachine(self, event):
if self.state is StopStates.NORMAL:
<|user_cursor_is_here|>
self.action = StopStates.FULL_STOP
elif self.state is StopStates.FULL_STOP:
self.action = StopStates.IGNORE_STOP_SIGNS
timer = rospy.Timer(rospy.Duration(self.ignoreDuration),
self.stepStateMachine,
oneshot=True)
elif self.state is StopStates.IGNORE_STOP_SIGNS:
self.action = StopStates.NORMAL
``` | ```src/autobot/src/stopsign.py
#!/usr/bin/env python
import rospy
class StopStates(object):
NORMAL = 0
FULL_STOP = 1
IGNORE_STOP_SIGNS = 2
class StopSign(object):
def __init__(self):
self.state = StopStates.NORMAL
self.stopDuration = 2
self.ignoreDuration = 4
def stopSignDetected(self):
self.state = StopStates.FULL_STOP
timer = rospy.Timer(rospy.Duration(self.stopDuration),
self.stepStateMachine,
oneshot=True)
def stepStateMachine(self, event):
if self.state is StopStates.NORMAL:
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "action", "newName": "state"}}
</|tool_call|>
self.action = StopStates.FULL_STOP
elif self.state is StopStates.FULL_STOP:
self.action = StopStates.IGNORE_STOP_SIGNS
timer = rospy.Timer(rospy.Duration(self.ignoreDuration),
self.stepStateMachine,
oneshot=True)
elif self.state is StopStates.IGNORE_STOP_SIGNS:
self.action = StopStates.NORMAL
``` |
User edited file: "worker/build.gradle.kts":
```diff
@@ -4,7 +4,7 @@
}
application {
- mainClassName = "com.github.k0kubun.gitstar_ranking.Main"
+ mainClass.set("com.github.k0kubun.gitstar_ranking.Main")
}
repositories {
@@ -24,4 +24,4 @@
compile("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final")
compile("org.jdbi:jdbi:2.78")
testCompile("junit:junit:4.12")
-}
+}
```
User edited file: "worker/build.gradle.kts":
```diff
@@ -12,16 +12,16 @@
}
dependencies {
- compile("ch.qos.logback:logback-classic:1.3.0-alpha4")
- compile("com.google.guava:guava:21.0")
- compile("com.google.http-client:google-http-client:1.22.0")
- compile("io.sentry:sentry:1.5.2")
- compile("javax.json:javax.json-api:1.1")
- compile("javax.ws.rs:javax.ws.rs-api:2.0.1")
- compile("org.postgresql:postgresql:42.2.19")
- compile("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2
- compile("org.glassfish:javax.json:1.1")
- compile("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final")
- compile("org.jdbi:jdbi:2.78")
+ implementation("ch.qos.logback:logback-classic:1.3.0-alpha4")
+ implementation("com.google.guava:guava:21.0")
+ implementation("com.google.http-client:google-http-client:1.22.0")
+ implementation("io.sentry:sentry:1.5.2")
+ implementation("javax.json:javax.json-api:1.1")
+ implementation("javax.ws.rs:javax.ws.rs-api:2.0.1")
+ implementation("org.postgresql:postgresql:42.2.19")
+ implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2
+ implementation("org.glassfish:javax.json:1.1")
+ implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final")
+ implementation("org.jdbi:jdbi:2.78")
testCompile("junit:junit:4.12")
}
``` | ```worker/build.gradle.kts
plugins {
id("java")
id("application")
}
application {
mainClass.set("com.github.k0kubun.gitstar_ranking.Main")
}
repositories {
mavenCentral()
}
dependencies {
implementation("ch.qos.logback:logback-classic:1.3.0-alpha4")
implementation("com.google.guava:guava:21.0")
implementation("com.google.http-client:google-http-client:1.22.0")
implementation("io.sentry:sentry:1.5.2")
implementation("javax.json:javax.json-api:1.1")
implementation("javax.ws.rs:javax.ws.rs-api:2.0.1")
implementation("org.postgresql:postgresql:42.2.19")
implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2
implementation("org.glassfish:javax.json:1.1")
implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final")
implementation("org.jdbi:jdbi:2.78")
<|user_cursor_is_here|>
testCompile("junit:junit:4.12")
}
``` | ```worker/build.gradle.kts
plugins {
id("java")
id("application")
}
application {
mainClass.set("com.github.k0kubun.gitstar_ranking.Main")
}
repositories {
mavenCentral()
}
dependencies {
implementation("ch.qos.logback:logback-classic:1.3.0-alpha4")
implementation("com.google.guava:guava:21.0")
implementation("com.google.http-client:google-http-client:1.22.0")
implementation("io.sentry:sentry:1.5.2")
implementation("javax.json:javax.json-api:1.1")
implementation("javax.ws.rs:javax.ws.rs-api:2.0.1")
implementation("org.postgresql:postgresql:42.2.19")
implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2
implementation("org.glassfish:javax.json:1.1")
implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final")
implementation("org.jdbi:jdbi:2.78")
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "testCompile", "newName": "testImplementation"}}
</|tool_call|>
testCompile("junit:junit:4.12")
}
``` |
User edited file: "src/libcore/num/int_macros.rs":
```diff
@@ -14,7 +14,7 @@
concat!("The smallest value that can be represented by this integer type.
Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."),
#[$attr]
- pub const MIN: $T = $T::min_value();
+ pub const MIN: $T = $T::MIN;
}
doc_comment! {
@@ -24,4 +24,4 @@
pub const MAX: $T = $T::max_value();
}
)
-}
+}
``` | ```src/libcore/num/int_macros.rs
#![doc(hidden)]
macro_rules! doc_comment {
($x:expr, $($tt:tt)*) => {
#[doc = $x]
$($tt)*
};
}
macro_rules! int_module {
($T:ident) => (int_module!($T, #[stable(feature = "rust1", since = "1.0.0")]););
($T:ident, #[$attr:meta]) => (
doc_comment! {
concat!("The smallest value that can be represented by this integer type.
Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."),
#[$attr]
pub const MIN: $T = $T::MIN;
}
doc_comment! {
concat!("The largest value that can be represented by this integer type.
Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."),
#[$attr]
<|user_cursor_is_here|>
pub const MAX: $T = $T::max_value();
}
)
}
``` | ```src/libcore/num/int_macros.rs
#![doc(hidden)]
macro_rules! doc_comment {
($x:expr, $($tt:tt)*) => {
#[doc = $x]
$($tt)*
};
}
macro_rules! int_module {
($T:ident) => (int_module!($T, #[stable(feature = "rust1", since = "1.0.0")]););
($T:ident, #[$attr:meta]) => (
doc_comment! {
concat!("The smallest value that can be represented by this integer type.
Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."),
#[$attr]
pub const MIN: $T = $T::MIN;
}
doc_comment! {
concat!("The largest value that can be represented by this integer type.
Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."),
#[$attr]
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "max_value()", "newName": "MAX"}}
</|tool_call|>
pub const MAX: $T = $T::max_value();
}
)
}
``` |
User edited file: "app/src/test/java/com/google/android/stardroid/units/LatLongRoboTest.kt":
```diff
@@ -1,11 +1,9 @@
package com.google.android.stardroid.units
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
-import com.google.android.stardroid.units.LatLong
-import com.google.common.truth.Truth
-import com.google.android.stardroid.units.LatLongRoboTest
-import org.junit.Test
import org.robolectric.annotation.Config
/**
``` | ```app/src/test/java/com/google/android/stardroid/units/LatLongRoboTest.kt
package com.google.android.stardroid.units
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Tests that require roboelectric for API calls.
*/
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class LatLongRoboTest {
@Test
fun latLong_testDistance() {
val point1 = LatLong(0.0, 0.0)
val point2 = LatLong(90.0, 0.0)
<|user_cursor_is_here|>
Truth.assertThat(point1.distanceFrom(point2)).isWithin(TOL).of(90f)
}
@Test
fun latLong_testDistance2() {
val point1 = LatLong(45.0, 45.0)
val point2 = LatLong(90.0, 0.0)
Truth.assertThat(point1.distanceFrom(point2)).isWithin(TOL).of(45f)
}
companion object {
private const val TOL = 1e-5f
}
}
``` | ```app/src/test/java/com/google/android/stardroid/units/LatLongRoboTest.kt
package com.google.android.stardroid.units
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Tests that require roboelectric for API calls.
*/
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class LatLongRoboTest {
@Test
fun latLong_testDistance() {
val point1 = LatLong(0.0, 0.0)
val point2 = LatLong(90.0, 0.0)
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "Truth.assertThat", "newName": "assertThat"}}
</|tool_call|>
Truth.assertThat(point1.distanceFrom(point2)).isWithin(TOL).of(90f)
}
@Test
fun latLong_testDistance2() {
val point1 = LatLong(45.0, 45.0)
val point2 = LatLong(90.0, 0.0)
Truth.assertThat(point1.distanceFrom(point2)).isWithin(TOL).of(45f)
}
companion object {
private const val TOL = 1e-5f
}
}
``` |
User edited file: "kernel/fs/kscheme.rs":
```diff
@@ -2,7 +2,7 @@
use alloc::boxed::Box;
-use system::error::{Error, Result, ENOENT};
+use system::error::{Error, Result, EPERM};
use system::syscall::Stat;
#[allow(unused_variables)]
@@ -34,4 +34,4 @@
fn unlink(&mut self, path: Url) -> Result<()> {
Err(Error::new(ENOENT))
}
-}
+}
``` | ```kernel/fs/kscheme.rs
use super::{Resource, Url};
use alloc::boxed::Box;
use system::error::{Error, Result, EPERM};
use system::syscall::Stat;
#[allow(unused_variables)]
pub trait KScheme {
fn on_irq(&mut self, irq: u8) {
}
fn scheme(&self) -> &str {
""
}
fn open(&mut self, path: Url, flags: usize) -> Result<Box<Resource>> {
<|user_cursor_is_here|>
Err(Error::new(ENOENT))
}
fn mkdir(&mut self, path: Url, flags: usize) -> Result<()> {
Err(Error::new(ENOENT))
}
fn rmdir(&mut self, path: Url) -> Result<()> {
Err(Error::new(ENOENT))
}
fn stat(&mut self, path: Url, stat: &mut Stat) -> Result<()> {
Err(Error::new(ENOENT))
}
fn unlink(&mut self, path: Url) -> Result<()> {
Err(Error::new(ENOENT))
}
}
``` | ```kernel/fs/kscheme.rs
use super::{Resource, Url};
use alloc::boxed::Box;
use system::error::{Error, Result, EPERM};
use system::syscall::Stat;
#[allow(unused_variables)]
pub trait KScheme {
fn on_irq(&mut self, irq: u8) {
}
fn scheme(&self) -> &str {
""
}
fn open(&mut self, path: Url, flags: usize) -> Result<Box<Resource>> {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "ENOENT", "newName": "EPERM"}}
</|tool_call|>
Err(Error::new(ENOENT))
}
fn mkdir(&mut self, path: Url, flags: usize) -> Result<()> {
Err(Error::new(ENOENT))
}
fn rmdir(&mut self, path: Url) -> Result<()> {
Err(Error::new(ENOENT))
}
fn stat(&mut self, path: Url, stat: &mut Stat) -> Result<()> {
Err(Error::new(ENOENT))
}
fn unlink(&mut self, path: Url) -> Result<()> {
Err(Error::new(ENOENT))
}
}
``` |
User edited file: "app/src/main/java/com/battlelancer/seriesguide/ui/shows/FabRecyclerViewScrollDetector.kt":
```diff
@@ -3,6 +3,7 @@
import androidx.recyclerview.widget.RecyclerView
import com.battlelancer.seriesguide.R
import com.google.android.material.floatingactionbutton.FloatingActionButton
+import kotlin.math.abs
/**
* Hides the floating action button when scrolling down, shows it when scrolling up. If the view can
@@ -46,4 +47,4 @@
button.show()
}
-}
+}
```
User edited file: "app/src/main/java/com/battlelancer/seriesguide/ui/shows/FabRecyclerViewScrollDetector.kt":
```diff
@@ -18,11 +18,6 @@
button.context.resources.getDimensionPixelOffset(R.dimen.fab_scroll_threshold)
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
- // no action if RecyclerView is no longer visible, such as its tab was swiped away
- if (!recyclerView.hasFocus()) {
- return
- }
-
// always show if scrolled to bottom
if (!recyclerView.canScrollVertically(1 /* down */)) {
button.show()
``` | ```app/src/main/java/com/battlelancer/seriesguide/ui/shows/FabRecyclerViewScrollDetector.kt
package com.battlelancer.seriesguide.ui.shows
import androidx.recyclerview.widget.RecyclerView
import com.battlelancer.seriesguide.R
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlin.math.abs
/**
* Hides the floating action button when scrolling down, shows it when scrolling up. If the view can
* no longer scroll down, shows the button also.
*
* Built upon https://github.com/makovkastar/FloatingActionButton scroll detectors.
*/
internal class FabRecyclerViewScrollDetector(private val button: FloatingActionButton) :
RecyclerView.OnScrollListener() {
private val scrollThreshold: Int =
button.context.resources.getDimensionPixelOffset(R.dimen.fab_scroll_threshold)
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
// always show if scrolled to bottom
if (!recyclerView.canScrollVertically(1 /* down */)) {
button.show()
return
}
<|user_cursor_is_here|>
val isSignificantDelta = Math.abs(dy) > scrollThreshold
if (isSignificantDelta) {
if (dy > 0) {
onScrollDown()
} else {
onScrollUp()
}
}
}
private fun onScrollDown() {
button.hide()
}
private fun onScrollUp() {
button.show()
}
}
``` | ```app/src/main/java/com/battlelancer/seriesguide/ui/shows/FabRecyclerViewScrollDetector.kt
package com.battlelancer.seriesguide.ui.shows
import androidx.recyclerview.widget.RecyclerView
import com.battlelancer.seriesguide.R
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlin.math.abs
/**
* Hides the floating action button when scrolling down, shows it when scrolling up. If the view can
* no longer scroll down, shows the button also.
*
* Built upon https://github.com/makovkastar/FloatingActionButton scroll detectors.
*/
internal class FabRecyclerViewScrollDetector(private val button: FloatingActionButton) :
RecyclerView.OnScrollListener() {
private val scrollThreshold: Int =
button.context.resources.getDimensionPixelOffset(R.dimen.fab_scroll_threshold)
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
// always show if scrolled to bottom
if (!recyclerView.canScrollVertically(1 /* down */)) {
button.show()
return
}
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "Math.abs", "newName": "abs"}}
</|tool_call|>
val isSignificantDelta = Math.abs(dy) > scrollThreshold
if (isSignificantDelta) {
if (dy > 0) {
onScrollDown()
} else {
onScrollUp()
}
}
}
private fun onScrollDown() {
button.hide()
}
private fun onScrollUp() {
button.show()
}
}
``` |
User edited file: "src/conn/futures/ping.rs":
```diff
@@ -6,7 +6,6 @@
use lib_futures::Async::Ready;
use lib_futures::Future;
use lib_futures::Poll;
-use proto::Packet;
use proto::PacketType;
@@ -65,4 +64,4 @@
},
}
}
-}
+}
```
User edited file: "src/conn/futures/ping.rs":
```diff
@@ -9,14 +9,11 @@
use proto::PacketType;
-enum Step {
- WritePacket(WritePacket),
- ReadResponse(ReadPacket),
-}
-
-enum Out {
- WritePacket(Conn),
- ReadResponse((Conn, Packet)),
+steps! {
+ Ping {
+ WritePacket(WritePacket),
+ ReadPacket(ReadPacket),
+ }
}
pub struct Ping {
```
User edited file: "src/conn/futures/ping.rs":
```diff
@@ -16,24 +16,9 @@
}
}
+/// Future that resolves to `Conn` if MySql's `COM_PING` was executed successfully.
pub struct Ping {
step: Step,
-}
-
-/// Future that resolves to `Conn` if MySql's `COM_PING` was executed successfully.
-impl Ping {
- fn either_poll(&mut self) -> Result<Async<Out>> {
- match self.step {
- Step::WritePacket(ref mut fut) => {
- let val = try_ready!(fut.poll());
- Ok(Ready(Out::WritePacket(val)))
- },
- Step::ReadResponse(ref mut fut) => {
- let val = try_ready!(fut.poll());
- Ok(Ready(Out::ReadResponse(val)))
- },
- }
- }
}
pub fn new(write_packet: WritePacket) -> Ping {
``` | ```src/conn/futures/ping.rs
use Conn;
use conn::futures::read_packet::ReadPacket;
use conn::futures::write_packet::WritePacket;
use errors::*;
use lib_futures::Async;
use lib_futures::Async::Ready;
use lib_futures::Future;
use lib_futures::Poll;
use proto::PacketType;
steps! {
Ping {
WritePacket(WritePacket),
ReadPacket(ReadPacket),
}
}
/// Future that resolves to `Conn` if MySql's `COM_PING` was executed successfully.
pub struct Ping {
step: Step,
}
pub fn new(write_packet: WritePacket) -> Ping {
Ping {
step: Step::WritePacket(write_packet),
}
}
impl Future for Ping {
type Item = Conn;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match try_ready!(self.either_poll()) {
Out::WritePacket(conn) => {
<|user_cursor_is_here|>
self.step = Step::ReadResponse(conn.read_packet());
self.poll()
},
Out::ReadResponse((conn, packet)) => {
if packet.is(PacketType::Ok) {
Ok(Ready(conn))
} else {
Err(ErrorKind::UnexpectedPacket.into())
}
},
}
}
}
``` | ```src/conn/futures/ping.rs
use Conn;
use conn::futures::read_packet::ReadPacket;
use conn::futures::write_packet::WritePacket;
use errors::*;
use lib_futures::Async;
use lib_futures::Async::Ready;
use lib_futures::Future;
use lib_futures::Poll;
use proto::PacketType;
steps! {
Ping {
WritePacket(WritePacket),
ReadPacket(ReadPacket),
}
}
/// Future that resolves to `Conn` if MySql's `COM_PING` was executed successfully.
pub struct Ping {
step: Step,
}
pub fn new(write_packet: WritePacket) -> Ping {
Ping {
step: Step::WritePacket(write_packet),
}
}
impl Future for Ping {
type Item = Conn;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match try_ready!(self.either_poll()) {
Out::WritePacket(conn) => {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "ReadResponse", "newName": "ReadPacket"}}
</|tool_call|>
self.step = Step::ReadResponse(conn.read_packet());
self.poll()
},
Out::ReadResponse((conn, packet)) => {
if packet.is(PacketType::Ok) {
Ok(Ready(conn))
} else {
Err(ErrorKind::UnexpectedPacket.into())
}
},
}
}
}
``` |
User edited file: "ee-email_des/src/main/kotlin/ee/email/EmailModelGenerator.kt":
```diff
@@ -1,9 +1,9 @@
package ee.email
-import ee.design.KotlinGenerator
+import ee.design.gen.DesingKotlinGenerator
import ee.lang.integ.eePath
fun main(args: Array<String>) {
val generator = KotlinGenerator(model())
generator.generate(eePath)
-}
+}
``` | ```ee-email_des/src/main/kotlin/ee/email/EmailModelGenerator.kt
package ee.email
import ee.design.gen.DesingKotlinGenerator
import ee.lang.integ.eePath
fun main(args: Array<String>) {
<|user_cursor_is_here|>
val generator = KotlinGenerator(model())
generator.generate(eePath)
}
``` | ```ee-email_des/src/main/kotlin/ee/email/EmailModelGenerator.kt
package ee.email
import ee.design.gen.DesingKotlinGenerator
import ee.lang.integ.eePath
fun main(args: Array<String>) {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "KotlinGenerator", "newName": "DesingKotlinGenerator"}}
</|tool_call|>
val generator = KotlinGenerator(model())
generator.generate(eePath)
}
``` |
User edited file: "lazers-changes-stream/examples/simple_parsing.rs":
```diff
@@ -1,7 +1,7 @@
extern crate hyper;
extern crate serde;
extern crate serde_json as json;
-extern crate syncdb_changes_stream;
+extern crate lazers_changes_stream;
use syncdb_changes_stream::changes_stream::ChangesStream;
@@ -24,5 +24,4 @@
for change in stream.changes() {
println!("{:?}", change);
}
-}
-
+}
``` | ```lazers-changes-stream/examples/simple_parsing.rs
extern crate hyper;
extern crate serde;
extern crate serde_json as json;
extern crate lazers_changes_stream;
<|user_cursor_is_here|>
use syncdb_changes_stream::changes_stream::ChangesStream;
use hyper::Client;
use hyper::header::Connection;
fn main() {
// Create a client.
let client = Client::new();
// Creating an outgoing request.
let res = client.get("http://localhost:5984/test/_changes?feed=continuous&include_docs=true")
// set a header
.header(Connection::close())
// let 'er go!
.send().unwrap();
let stream: ChangesStream<_,json::Value> = ChangesStream::new(res);
for change in stream.changes() {
println!("{:?}", change);
}
}
``` | ```lazers-changes-stream/examples/simple_parsing.rs
extern crate hyper;
extern crate serde;
extern crate serde_json as json;
extern crate lazers_changes_stream;
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "syncdb_changes_stream", "newName": "lazers_changes_stream"}}
</|tool_call|>
use syncdb_changes_stream::changes_stream::ChangesStream;
use hyper::Client;
use hyper::header::Connection;
fn main() {
// Create a client.
let client = Client::new();
// Creating an outgoing request.
let res = client.get("http://localhost:5984/test/_changes?feed=continuous&include_docs=true")
// set a header
.header(Connection::close())
// let 'er go!
.send().unwrap();
let stream: ChangesStream<_,json::Value> = ChangesStream::new(res);
for change in stream.changes() {
println!("{:?}", change);
}
}
``` |
User edited file: "src/world/World.java":
```diff
@@ -2,7 +2,7 @@
import edu.stuy.starlorn.entities.Entity;
-import java.util.ArrayList;
+import java.util.LinkedList;
/*
* Represents a world with entities in it
@@ -25,4 +25,4 @@
e.postStep();
}
}
-}
+}
```
User edited file: "src/world/World.java":
```diff
@@ -8,7 +8,7 @@
* Represents a world with entities in it
*/
public class World {
- private ArrayList<Entity> _entities;
+ private LinkedList<Entity> _entities;
public World() {
_entities = new ArrayList<Entity>();
``` | ```src/world/World.java
package edu.stuy.starlorn.world;
import edu.stuy.starlorn.entities.Entity;
import java.util.LinkedList;
/*
* Represents a world with entities in it
*/
public class World {
private LinkedList<Entity> _entities;
public World() {
<|user_cursor_is_here|>
_entities = new ArrayList<Entity>();
}
public void addEntity(Entity e) {
_entities.add(e);
}
public void stepAll() {
for (Entity e : _entities) {
e.preStep();
e.step();
e.postStep();
}
}
}
``` | ```src/world/World.java
package edu.stuy.starlorn.world;
import edu.stuy.starlorn.entities.Entity;
import java.util.LinkedList;
/*
* Represents a world with entities in it
*/
public class World {
private LinkedList<Entity> _entities;
public World() {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "ArrayList", "newName": "LinkedList"}}
</|tool_call|>
_entities = new ArrayList<Entity>();
}
public void addEntity(Entity e) {
_entities.add(e);
}
public void stepAll() {
for (Entity e : _entities) {
e.preStep();
e.step();
e.postStep();
}
}
}
``` |
User edited file: "subprojects/docs/src/samples/providers/propertyAndProvider/kotlin/build.gradle.kts":
```diff
@@ -21,7 +21,7 @@
// Read-only property calculated from the message
@get:Internal
- val fullMessage: Provider<String> = message.map { "$it from Gradle" }
+ val fullMessage: Provider<String> = message.map { it + " from Gradle" }
@TaskAction
fun printMessage() {
@@ -31,4 +31,4 @@
tasks.create<Greeting>("greeting") {
message.set("Hi")
-}
+}
``` | ```subprojects/docs/src/samples/providers/propertyAndProvider/kotlin/build.gradle.kts
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
open class Greeting : DefaultTask() {
// Configurable by the user
@get:Input
val message: Property<String> = project.objects.property()
// Read-only property calculated from the message
@get:Internal
val fullMessage: Provider<String> = message.map { it + " from Gradle" }
@TaskAction
fun printMessage() {
logger.quiet(fullMessage.get())
}
}
<|user_cursor_is_here|>
tasks.create<Greeting>("greeting") {
message.set("Hi")
}
``` | ```subprojects/docs/src/samples/providers/propertyAndProvider/kotlin/build.gradle.kts
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
open class Greeting : DefaultTask() {
// Configurable by the user
@get:Input
val message: Property<String> = project.objects.property()
// Read-only property calculated from the message
@get:Internal
val fullMessage: Provider<String> = message.map { it + " from Gradle" }
@TaskAction
fun printMessage() {
logger.quiet(fullMessage.get())
}
}
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "tasks.create", "newName": "task"}}
</|tool_call|>
tasks.create<Greeting>("greeting") {
message.set("Hi")
}
``` |
User edited file: "app/utils/utilities.py":
```diff
@@ -1,5 +1,5 @@
from re import search
-from flask import g
+from flask import g, request
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
@@ -21,4 +21,4 @@
if user_id:
g.current_user = User.query.filter_by(id=user.id).first()
return True
- return False
+ return False
```
User edited file: "app/utils/utilities.py":
```diff
@@ -1,9 +1,7 @@
from re import search
from flask import g, request
-from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
-from instance.config import Config
auth = HTTPBasicAuth()
```
User edited file: "app/utils/utilities.py":
```diff
@@ -1,6 +1,6 @@
from re import search
from flask import g, request
-from flask_httpauth import HTTPBasicAuth
+from flask_httpauth import HTTPTokenAuth
from app.models.user import User
auth = HTTPBasicAuth()
```
User edited file: "app/utils/utilities.py":
```diff
@@ -3,7 +3,7 @@
from flask_httpauth import HTTPTokenAuth
from app.models.user import User
-auth = HTTPBasicAuth()
+auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
```
User edited file: "app/utils/utilities.py":
```diff
@@ -7,7 +7,7 @@
def validate_email(email):
- ''' Method to check that a valid email is provided '''
+ ''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
``` | ```app/utils/utilities.py
from re import search
from flask import g, request
from flask_httpauth import HTTPTokenAuth
from app.models.user import User
auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
<|user_cursor_is_here|>
g.current_user = User.query.filter_by(id=user.id).first()
return True
return False
``` | ```app/utils/utilities.py
from re import search
from flask import g, request
from flask_httpauth import HTTPTokenAuth
from app.models.user import User
auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "user.id", "newName": "user_id"}}
</|tool_call|>
g.current_user = User.query.filter_by(id=user.id).first()
return True
return False
``` |
User edited file: "src/main/java/com/github/blindpirate/gogradle/task/go/GoExecutionAction.java":
```diff
@@ -31,7 +31,7 @@
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
ClassLoader original = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(closure.getClass().getClassLoader());
- Map<String, String> originalEnv = Go.class.cast(task).getCurrentEnv();
+ Map<String, String> originalEnv = Go.class.cast(task).getEnv();
Go.class.cast(task).setCurrentEnv(env);
try {
synchronized (task) {
@@ -48,4 +48,4 @@
return closure.getClass().getClassLoader();
}
-}
+}
```
User edited file: "src/main/java/com/github/blindpirate/gogradle/task/go/GoExecutionAction.java":
```diff
@@ -32,7 +32,7 @@
ClassLoader original = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(closure.getClass().getClassLoader());
Map<String, String> originalEnv = Go.class.cast(task).getEnv();
- Go.class.cast(task).setCurrentEnv(env);
+ Go.class.cast(task).setEnv(env);
try {
synchronized (task) {
closure.call(task);
``` | ```src/main/java/com/github/blindpirate/gogradle/task/go/GoExecutionAction.java
package com.github.blindpirate.gogradle.task.go;
import groovy.lang.Closure;
import org.gradle.api.Task;
import org.gradle.api.internal.tasks.ContextAwareTaskAction;
import org.gradle.api.internal.tasks.TaskExecutionContext;
import java.util.Map;
public class GoExecutionAction implements ContextAwareTaskAction {
private Closure closure;
private Map<String, String> env;
public static GoExecutionAction wrapClosureWithEnvs(Closure closure, Map<String, String> env) {
GoExecutionAction ret = new GoExecutionAction();
ret.env = env;
ret.closure = closure;
return ret;
}
private GoExecutionAction() {
}
@Override
public void contextualise(TaskExecutionContext context) {
}
@Override
public void execute(Task task) {
closure.setDelegate(task);
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
ClassLoader original = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(closure.getClass().getClassLoader());
Map<String, String> originalEnv = Go.class.cast(task).getEnv();
Go.class.cast(task).setEnv(env);
try {
synchronized (task) {
closure.call(task);
}
} finally {
Thread.currentThread().setContextClassLoader(original);
<|user_cursor_is_here|>
Go.class.cast(task).setCurrentEnv(originalEnv);
}
}
@Override
public ClassLoader getClassLoader() {
return closure.getClass().getClassLoader();
}
}
``` | ```src/main/java/com/github/blindpirate/gogradle/task/go/GoExecutionAction.java
package com.github.blindpirate.gogradle.task.go;
import groovy.lang.Closure;
import org.gradle.api.Task;
import org.gradle.api.internal.tasks.ContextAwareTaskAction;
import org.gradle.api.internal.tasks.TaskExecutionContext;
import java.util.Map;
public class GoExecutionAction implements ContextAwareTaskAction {
private Closure closure;
private Map<String, String> env;
public static GoExecutionAction wrapClosureWithEnvs(Closure closure, Map<String, String> env) {
GoExecutionAction ret = new GoExecutionAction();
ret.env = env;
ret.closure = closure;
return ret;
}
private GoExecutionAction() {
}
@Override
public void contextualise(TaskExecutionContext context) {
}
@Override
public void execute(Task task) {
closure.setDelegate(task);
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
ClassLoader original = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(closure.getClass().getClassLoader());
Map<String, String> originalEnv = Go.class.cast(task).getEnv();
Go.class.cast(task).setEnv(env);
try {
synchronized (task) {
closure.call(task);
}
} finally {
Thread.currentThread().setContextClassLoader(original);
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "setCurrentEnv", "newName": "setEnv"}}
</|tool_call|>
Go.class.cast(task).setCurrentEnv(originalEnv);
}
}
@Override
public ClassLoader getClassLoader() {
return closure.getClass().getClassLoader();
}
}
``` |
User edited file: "src/main/java/org/bubenheimer/android/rx/DisposableWrapper.kt":
```diff
@@ -18,7 +18,7 @@
package org.bubenheimer.android.rx
import io.reactivex.rxjava3.disposables.Disposable
-import org.bubenheimer.android.Check
+import org.bubenheimer.util.examIsNull
/** Cheaper replacement for `SerialDisposable`. Methods are not thread-safe. */
public class DisposableWrapper {
@@ -37,4 +37,4 @@
disposable = null
}
}
-}
+}
``` | ```src/main/java/org/bubenheimer/android/rx/DisposableWrapper.kt
/*
* Copyright (c) 2015-2019 Uli Bubenheimer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.bubenheimer.android.rx
import io.reactivex.rxjava3.disposables.Disposable
import org.bubenheimer.util.examIsNull
/** Cheaper replacement for `SerialDisposable`. Methods are not thread-safe. */
public class DisposableWrapper {
private var disposable: Disposable? = null
public fun get(): Disposable? = disposable
public fun set(disposable: Disposable) {
<|user_cursor_is_here|>
Check.isNull(this.disposable)
this.disposable = disposable
}
public fun clear() {
disposable?.let {
it.dispose()
disposable = null
}
}
}
``` | ```src/main/java/org/bubenheimer/android/rx/DisposableWrapper.kt
/*
* Copyright (c) 2015-2019 Uli Bubenheimer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.bubenheimer.android.rx
import io.reactivex.rxjava3.disposables.Disposable
import org.bubenheimer.util.examIsNull
/** Cheaper replacement for `SerialDisposable`. Methods are not thread-safe. */
public class DisposableWrapper {
private var disposable: Disposable? = null
public fun get(): Disposable? = disposable
public fun set(disposable: Disposable) {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "Check.isNull", "newName": "examIsNull"}}
</|tool_call|>
Check.isNull(this.disposable)
this.disposable = disposable
}
public fun clear() {
disposable?.let {
it.dispose()
disposable = null
}
}
}
``` |
User edited file: "app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt":
```diff
@@ -3,6 +3,7 @@
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Toast
+import kotlinx.android.synthetic.main.activity_main.*
import nl.dionsegijn.steppertouch.OnStepCallback
import nl.dionsegijn.steppertouch.StepperTouch
@@ -28,4 +29,4 @@
bottemStepperTouch.enableSideTap(true)
}
-}
+}
```
User edited file: "app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt":
```diff
@@ -14,7 +14,6 @@
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
- val stepperTouch = findViewById(R.id.stepperTouch) as StepperTouch
stepperTouch.stepper.setMin(0)
stepperTouch.stepper.setMax(5)
stepperTouch.stepper.addStepCallback(object : OnStepCallback {
``` | ```app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt
package nl.dionsegijn.steppertouchdemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import nl.dionsegijn.steppertouch.OnStepCallback
import nl.dionsegijn.steppertouch.StepperTouch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
stepperTouch.stepper.setMin(0)
stepperTouch.stepper.setMax(5)
stepperTouch.stepper.addStepCallback(object : OnStepCallback {
override fun onStep(value: Int, positive: Boolean) {
Toast.makeText(applicationContext, value.toString(), Toast.LENGTH_SHORT).show()
}
})
<|user_cursor_is_here|>
val bottemStepperTouch = findViewById(R.id.bottomStepperTouch) as StepperTouch
bottemStepperTouch.stepper.setMin(-10)
bottemStepperTouch.stepper.setMax(10)
bottemStepperTouch.enableSideTap(true)
}
}
``` | ```app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt
package nl.dionsegijn.steppertouchdemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import nl.dionsegijn.steppertouch.OnStepCallback
import nl.dionsegijn.steppertouch.StepperTouch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
stepperTouch.stepper.setMin(0)
stepperTouch.stepper.setMax(5)
stepperTouch.stepper.addStepCallback(object : OnStepCallback {
override fun onStep(value: Int, positive: Boolean) {
Toast.makeText(applicationContext, value.toString(), Toast.LENGTH_SHORT).show()
}
})
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "bottemStepperTouch", "newName": "bottomStepperTouch"}}
</|tool_call|>
val bottemStepperTouch = findViewById(R.id.bottomStepperTouch) as StepperTouch
bottemStepperTouch.stepper.setMin(-10)
bottemStepperTouch.stepper.setMax(10)
bottemStepperTouch.enableSideTap(true)
}
}
``` |
User edited file: "mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt":
```diff
@@ -37,6 +37,6 @@
@Bean("resetPasswordServlet")
fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*")
- @Bean("resetPasswordServlet")
+ @Bean("resetPasswordPageServlet")
fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*")
-}
+}
``` | ```mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt
/**
* Copyright © MyCollab
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.billing.servlet
import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
/**
* @author MyCollab Ltd
* @since 5.5.0
*/
@Configuration
class BillingSpringServletRegistrator {
@Bean("confirmEmailServlet")
fun confirmEmailServlet() = ServletRegistrationBean(ConfirmEmailHandler(), "/user/confirm_signup/*")
@Bean("resetPasswordServlet")
fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*")
@Bean("resetPasswordPageServlet")
<|user_cursor_is_here|>
fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*")
}
``` | ```mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt
/**
* Copyright © MyCollab
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.billing.servlet
import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
/**
* @author MyCollab Ltd
* @since 5.5.0
*/
@Configuration
class BillingSpringServletRegistrator {
@Bean("confirmEmailServlet")
fun confirmEmailServlet() = ServletRegistrationBean(ConfirmEmailHandler(), "/user/confirm_signup/*")
@Bean("resetPasswordServlet")
fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*")
@Bean("resetPasswordPageServlet")
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "ResetPasswordHandler", "newName": "ResetPasswordUpdatePage"}}
</|tool_call|>
fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*")
}
``` |
User edited file: "src/main/java/seedu/address/storage/XmlFileStorage.java":
```diff
@@ -15,7 +15,7 @@
/**
* Saves the given taskmanager data to the specified file.
*/
- public static void saveDataToFile(File file, XmlSerializableTaskManager addressBook)
+ public static void saveDataToFile(File file, XmlSerializableTaskManager taskManager)
throws FileNotFoundException {
try {
XmlUtil.saveDataToFile(file, addressBook);
@@ -36,4 +36,4 @@
}
}
-}
+}
``` | ```src/main/java/seedu/address/storage/XmlFileStorage.java
package seedu.address.storage;
import java.io.File;
import java.io.FileNotFoundException;
import javax.xml.bind.JAXBException;
import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.commons.util.XmlUtil;
/**
* Stores taskmanager data in an XML file
*/
public class XmlFileStorage {
/**
* Saves the given taskmanager data to the specified file.
*/
public static void saveDataToFile(File file, XmlSerializableTaskManager taskManager)
throws FileNotFoundException {
try {
<|user_cursor_is_here|>
XmlUtil.saveDataToFile(file, addressBook);
} catch (JAXBException e) {
assert false : "Unexpected exception " + e.getMessage();
}
}
/**
* Returns task manager in the file or an empty task manager
*/
public static XmlSerializableTaskManager loadDataFromSaveFile(File file) throws DataConversionException,
FileNotFoundException {
try {
return XmlUtil.getDataFromFile(file, XmlSerializableTaskManager.class);
} catch (JAXBException e) {
throw new DataConversionException(e);
}
}
}
``` | ```src/main/java/seedu/address/storage/XmlFileStorage.java
package seedu.address.storage;
import java.io.File;
import java.io.FileNotFoundException;
import javax.xml.bind.JAXBException;
import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.commons.util.XmlUtil;
/**
* Stores taskmanager data in an XML file
*/
public class XmlFileStorage {
/**
* Saves the given taskmanager data to the specified file.
*/
public static void saveDataToFile(File file, XmlSerializableTaskManager taskManager)
throws FileNotFoundException {
try {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "addressBook", "newName": "taskManager"}}
</|tool_call|>
XmlUtil.saveDataToFile(file, addressBook);
} catch (JAXBException e) {
assert false : "Unexpected exception " + e.getMessage();
}
}
/**
* Returns task manager in the file or an empty task manager
*/
public static XmlSerializableTaskManager loadDataFromSaveFile(File file) throws DataConversionException,
FileNotFoundException {
try {
return XmlUtil.getDataFromFile(file, XmlSerializableTaskManager.class);
} catch (JAXBException e) {
throw new DataConversionException(e);
}
}
}
``` |
User edited file: "deploy/generate_production_ini.py":
```diff
@@ -3,7 +3,7 @@
"""
import os
-from dcicutils.deployment_utils import Deployer
+from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(Deployer):
@@ -17,4 +17,4 @@
if __name__ == '__main__':
- main()
+ main()
``` | ```deploy/generate_production_ini.py
"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
<|user_cursor_is_here|>
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
``` | ```deploy/generate_production_ini.py
"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "Deployer", "newName": "BasicLegacyFourfrontIniFileManager"}}
</|tool_call|>
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
``` |
User edited file: "src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt":
```diff
@@ -10,7 +10,7 @@
package com.demonwav.mcdev.platform.mixin
-import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.OVERWRITE
+import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
@@ -46,4 +46,4 @@
override fun getName() = "reason"
}
}
-}
+}
```
User edited file: "src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt":
```diff
@@ -20,7 +20,7 @@
class MixinCustomJavaDocTagProvider : CustomJavadocTagProvider {
- override fun getSupportedTags(): List<JavadocTagInfo> = listOf(OverwriteTag.Author, OverwriteTag.Reason)
+ override fun getSupportedTags(): List<JavadocTagInfo> = listOf(InjectorTag.Author, InjectorTag.Reason)
private sealed class OverwriteTag : JavadocTagInfo {
``` | ```src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.javadoc.CustomJavadocTagProvider
import com.intellij.psi.javadoc.JavadocTagInfo
import com.intellij.psi.javadoc.PsiDocTagValue
class MixinCustomJavaDocTagProvider : CustomJavadocTagProvider {
override fun getSupportedTags(): List<JavadocTagInfo> = listOf(InjectorTag.Author, InjectorTag.Reason)
<|user_cursor_is_here|>
private sealed class OverwriteTag : JavadocTagInfo {
override fun isInline() = false
override fun isValidInContext(element: PsiElement?): Boolean {
return element is PsiMethod && element.modifierList.findAnnotation(OVERWRITE) != null
}
override fun checkTagValue(value: PsiDocTagValue?): String? = null
override fun getReference(value: PsiDocTagValue?) = null
object Author : OverwriteTag() {
override fun getName() = "author"
override fun checkTagValue(value: PsiDocTagValue?): String? {
return "The @author JavaDoc tag on @Overwrite methods must be filled in.".takeIf { value?.text?.trim().isNullOrEmpty() }
}
}
object Reason : OverwriteTag() {
override fun getName() = "reason"
}
}
}
``` | ```src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.javadoc.CustomJavadocTagProvider
import com.intellij.psi.javadoc.JavadocTagInfo
import com.intellij.psi.javadoc.PsiDocTagValue
class MixinCustomJavaDocTagProvider : CustomJavadocTagProvider {
override fun getSupportedTags(): List<JavadocTagInfo> = listOf(InjectorTag.Author, InjectorTag.Reason)
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "OverwriteTag", "newName": "InjectorTag"}}
</|tool_call|>
private sealed class OverwriteTag : JavadocTagInfo {
override fun isInline() = false
override fun isValidInContext(element: PsiElement?): Boolean {
return element is PsiMethod && element.modifierList.findAnnotation(OVERWRITE) != null
}
override fun checkTagValue(value: PsiDocTagValue?): String? = null
override fun getReference(value: PsiDocTagValue?) = null
object Author : OverwriteTag() {
override fun getName() = "author"
override fun checkTagValue(value: PsiDocTagValue?): String? {
return "The @author JavaDoc tag on @Overwrite methods must be filled in.".takeIf { value?.text?.trim().isNullOrEmpty() }
}
}
object Reason : OverwriteTag() {
override fun getName() = "reason"
}
}
}
``` |
User edited file: "hold-and-fifo/fifo.js":
```diff
@@ -4,8 +4,6 @@
function Fifo(config) {
RED.nodes.createNode(this,config);
- var me = this;
-
this.queue = [];
this.depth = config.depth;
this.status({fill:"red",shape:"ring",text:"no value"});
@@ -44,4 +42,4 @@
RED.nodes.registerType("fifo",Fifo);
-}
+}
``` | ```hold-and-fifo/fifo.js
module.exports = function(RED) {
"use strict";
function Fifo(config) {
RED.nodes.createNode(this,config);
this.queue = [];
this.depth = config.depth;
this.status({fill:"red",shape:"ring",text:"no value"});
this.on('input', function (msg) {
// are we full?
// if so, boot some out
if (this.queue.length >= this.depth) {
while (this.queue.length >= this.depth) {
<|user_cursor_is_here|>
var msg = this.queue.shift();
this.send(msg);
}
}
// clone the message and whack it in the queue
this.queue.push(msg);
if (this.queue.length == this.depth) {
// queue is full
this.status({fill: "green", shape: "dot",
text: this.queue.length + "/" +
this.depth + " msgs"});
} else {
// queue is partially full
this.status({fill: "green", shape: "ring",
text: this.queue.length + "/" +
this.depth + " msgs"});
}
});
this.on("close", function() {
});
}
RED.nodes.registerType("fifo",Fifo);
}
``` | ```hold-and-fifo/fifo.js
module.exports = function(RED) {
"use strict";
function Fifo(config) {
RED.nodes.createNode(this,config);
this.queue = [];
this.depth = config.depth;
this.status({fill:"red",shape:"ring",text:"no value"});
this.on('input', function (msg) {
// are we full?
// if so, boot some out
if (this.queue.length >= this.depth) {
while (this.queue.length >= this.depth) {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "msg", "newName": "outgoing"}}
</|tool_call|>
var msg = this.queue.shift();
this.send(msg);
}
}
// clone the message and whack it in the queue
this.queue.push(msg);
if (this.queue.length == this.depth) {
// queue is full
this.status({fill: "green", shape: "dot",
text: this.queue.length + "/" +
this.depth + " msgs"});
} else {
// queue is partially full
this.status({fill: "green", shape: "ring",
text: this.queue.length + "/" +
this.depth + " msgs"});
}
});
this.on("close", function() {
});
}
RED.nodes.registerType("fifo",Fifo);
}
``` |
User edited file: "tests/ui/zero_offset.rs":
```diff
@@ -12,7 +12,7 @@
c.sub(0);
c.wrapping_sub(0);
- let y = &1 as *const i32;
+ let sized = &1 as *const i32;
y.offset(0);
}
-}
+}
``` | ```tests/ui/zero_offset.rs
fn main() {
unsafe {
let m = &mut () as *mut ();
m.offset(0);
m.wrapping_add(0);
m.sub(0);
m.wrapping_sub(0);
let c = &() as *const ();
c.offset(0);
c.wrapping_add(0);
c.sub(0);
c.wrapping_sub(0);
let sized = &1 as *const i32;
<|user_cursor_is_here|>
y.offset(0);
}
}
``` | ```tests/ui/zero_offset.rs
fn main() {
unsafe {
let m = &mut () as *mut ();
m.offset(0);
m.wrapping_add(0);
m.sub(0);
m.wrapping_sub(0);
let c = &() as *const ();
c.offset(0);
c.wrapping_add(0);
c.sub(0);
c.wrapping_sub(0);
let sized = &1 as *const i32;
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "y", "newName": "sized"}}
</|tool_call|>
y.offset(0);
}
}
``` |
User edited file: "UM/View/CompositePass.py":
```diff
@@ -1,7 +1,10 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
+from UM.Application import Application
from UM.Resources import Resources
+
+from UM.Math.Matrix import Matrix
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import OpenGL
@@ -33,4 +36,4 @@
self.renderQuad()
- self._shader.release()
+ self._shader.release()
```
User edited file: "UM/View/CompositePass.py":
```diff
@@ -10,8 +10,8 @@
from UM.View.GL.OpenGL import OpenGL
class CompositePass(RenderPass):
- def __init__(self, name, width, height):
- super().__init__(name, width, height)
+ def __init__(self, width, height):
+ super().__init__("composite", width, height)
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader"))
self._gl = OpenGL.getInstance().getBindingsObject()
```
User edited file: "UM/View/CompositePass.py":
```diff
@@ -15,6 +15,7 @@
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader"))
self._gl = OpenGL.getInstance().getBindingsObject()
+ self._renderer = Application.getInstance().getRenderer()
def setCompositeShader(self, shader):
self._shader = shader
``` | ```UM/View/CompositePass.py
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Resources import Resources
from UM.Math.Matrix import Matrix
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import OpenGL
class CompositePass(RenderPass):
def __init__(self, width, height):
super().__init__("composite", width, height)
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader"))
self._gl = OpenGL.getInstance().getBindingsObject()
self._renderer = Application.getInstance().getRenderer()
def setCompositeShader(self, shader):
self._shader = shader
def renderContents(self):
pass
def renderOutput(self):
self._shader.bind()
texture_unit = 0
<|user_cursor_is_here|>
for render_pass in renderer.getRenderPasses():
self._gl.glActiveTexture(texture_unit)
self._gl.glBindTexture(self._gl.GL_TEXTURE_2D, render_pass.getTextureId())
texture_unit += 1
self._shader.setUniformValue("u_layer_count", texture_unit + 1)
self._shader.setUniformValueArray("u_layers", [range(0, texture_unit)], texture_unit + 1)
self.renderQuad()
self._shader.release()
``` | ```UM/View/CompositePass.py
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Resources import Resources
from UM.Math.Matrix import Matrix
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import OpenGL
class CompositePass(RenderPass):
def __init__(self, width, height):
super().__init__("composite", width, height)
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader"))
self._gl = OpenGL.getInstance().getBindingsObject()
self._renderer = Application.getInstance().getRenderer()
def setCompositeShader(self, shader):
self._shader = shader
def renderContents(self):
pass
def renderOutput(self):
self._shader.bind()
texture_unit = 0
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "renderer", "newName": "self._renderer"}}
</|tool_call|>
for render_pass in renderer.getRenderPasses():
self._gl.glActiveTexture(texture_unit)
self._gl.glBindTexture(self._gl.GL_TEXTURE_2D, render_pass.getTextureId())
texture_unit += 1
self._shader.setUniformValue("u_layer_count", texture_unit + 1)
self._shader.setUniformValueArray("u_layers", [range(0, texture_unit)], texture_unit + 1)
self.renderQuad()
self._shader.release()
``` |
User edited file: "djs_playground/urls.py":
```diff
@@ -1,5 +1,5 @@
from django.conf import settings
-from django.conf.urls import url, include
+from django.urls import re_path, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
@@ -8,4 +8,4 @@
url(r'^$', index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^summernote/', include('django_summernote.urls')),
-] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
``` | ```djs_playground/urls.py
from django.conf import settings
from django.urls import re_path, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
<|user_cursor_is_here|>
url(r'^$', index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
``` | ```djs_playground/urls.py
from django.conf import settings
from django.urls import re_path, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "url", "newName": "re_path"}}
</|tool_call|>
url(r'^$', index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
``` |
User edited file: "buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt":
```diff
@@ -16,6 +16,7 @@
package androidx.build.resources
+import androidx.build.getSupportRootFolder
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Project
import java.io.File
@@ -28,4 +29,4 @@
)
)
}
-}
+}
``` | ```buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.resources
import androidx.build.getSupportRootFolder
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Project
import java.io.File
fun Project.configurePublicResourcesStub(extension: LibraryExtension) {
extension.libraryVariants.all { variant ->
variant.registerGeneratedResFolders(
project.files(
<|user_cursor_is_here|>
File(project.rootDir, "/buildSrc/res")
)
)
}
}
``` | ```buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.resources
import androidx.build.getSupportRootFolder
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Project
import java.io.File
fun Project.configurePublicResourcesStub(extension: LibraryExtension) {
extension.libraryVariants.all { variant ->
variant.registerGeneratedResFolders(
project.files(
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "project.rootDir", "newName": "project.getSupportRootFolder()"}}
</|tool_call|>
File(project.rootDir, "/buildSrc/res")
)
)
}
}
``` |
User edited file: "day3/solution.js":
```diff
@@ -6,6 +6,9 @@
let uniqueSantaPositions = [];
function updateUniquePositions() {
+ let santaPositionStr = santaPosition.toString();
+ let roboSantaPositionStr = roboSantaPosition.toString();
+
if (uniqueSantaPositions.indexOf(santaPosition.toString()) === -1) {
uniqueSantaPositions.push(santaPosition.toString());
}
@@ -32,4 +35,4 @@
updateUniquePositions();
});
-console.log("Houses with at least one present:", uniqueSantaPositions.length);
+console.log("Houses with at least one present:", uniqueSantaPositions.length);
```
User edited file: "day3/solution.js":
```diff
@@ -9,8 +9,8 @@
let santaPositionStr = santaPosition.toString();
let roboSantaPositionStr = roboSantaPosition.toString();
- if (uniqueSantaPositions.indexOf(santaPosition.toString()) === -1) {
- uniqueSantaPositions.push(santaPosition.toString());
+ if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) {
+ uniqueSantaPositions.push(santaPositionStr);
}
if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) {
``` | ```day3/solution.js
let input = require("fs").readFileSync("./data").toString();
let santaPosition = [0, 0];
let roboSantaPosition = [0, 0];
let uniqueSantaPositions = [];
function updateUniquePositions() {
let santaPositionStr = santaPosition.toString();
let roboSantaPositionStr = roboSantaPosition.toString();
if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) {
uniqueSantaPositions.push(santaPositionStr);
}
<|user_cursor_is_here|>
if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) {
uniqueSantaPositions.push(roboSantaPosition.toString());
}
}
updateUniquePositions();
input.split("").forEach((char, index) => {
let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2
if (char === "^") {
currentSantaPos[1]++;
} else if (char === "v") {
currentSantaPos[1]--;
} else if (char === ">") {
currentSantaPos[0]++;
} else if (char === "<") {
currentSantaPos[0]--;
}
updateUniquePositions();
});
console.log("Houses with at least one present:", uniqueSantaPositions.length);
``` | ```day3/solution.js
let input = require("fs").readFileSync("./data").toString();
let santaPosition = [0, 0];
let roboSantaPosition = [0, 0];
let uniqueSantaPositions = [];
function updateUniquePositions() {
let santaPositionStr = santaPosition.toString();
let roboSantaPositionStr = roboSantaPosition.toString();
if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) {
uniqueSantaPositions.push(santaPositionStr);
}
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "roboSantaPosition.toString()", "newName": "roboSantaPositionStr"}}
</|tool_call|>
if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) {
uniqueSantaPositions.push(roboSantaPosition.toString());
}
}
updateUniquePositions();
input.split("").forEach((char, index) => {
let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2
if (char === "^") {
currentSantaPos[1]++;
} else if (char === "v") {
currentSantaPos[1]--;
} else if (char === ">") {
currentSantaPos[0]++;
} else if (char === "<") {
currentSantaPos[0]--;
}
updateUniquePositions();
});
console.log("Houses with at least one present:", uniqueSantaPositions.length);
``` |
User edited file: "src/test/kotlin/jeb/ddsl/FileDescr.kt":
```diff
@@ -6,7 +6,7 @@
name: File,
fileContent: () -> String) : Node(name) {
- private val content = lazy { fileContent() }
+ private val content by lazy { fileContent() }
override fun create() {
name.writeText(content.value)
@@ -14,4 +14,4 @@
override fun contentEqualTo(file: File) = file.isFile && content.value == file.readText()
-}
+}
```
User edited file: "src/test/kotlin/jeb/ddsl/FileDescr.kt":
```diff
@@ -9,7 +9,7 @@
private val content by lazy { fileContent() }
override fun create() {
- name.writeText(content.value)
+ name.writeText(content)
}
override fun contentEqualTo(file: File) = file.isFile && content.value == file.readText()
``` | ```src/test/kotlin/jeb/ddsl/FileDescr.kt
package jeb.ddsl
import java.io.File
class FileDescr(
name: File,
fileContent: () -> String) : Node(name) {
private val content by lazy { fileContent() }
override fun create() {
name.writeText(content)
}
<|user_cursor_is_here|>
override fun contentEqualTo(file: File) = file.isFile && content.value == file.readText()
}
``` | ```src/test/kotlin/jeb/ddsl/FileDescr.kt
package jeb.ddsl
import java.io.File
class FileDescr(
name: File,
fileContent: () -> String) : Node(name) {
private val content by lazy { fileContent() }
override fun create() {
name.writeText(content)
}
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "content.value", "newName": "content"}}
</|tool_call|>
override fun contentEqualTo(file: File) = file.isFile && content.value == file.readText()
}
``` |
User edited file: "testing/tests/simple.rs":
```diff
@@ -8,7 +8,7 @@
#[derive(Template)]
#[template(path = "simple.html")]
-struct TestTemplate {
+struct VariablesTemplate {
strvar: String,
num: i64,
i18n: String,
@@ -25,4 +25,4 @@
with number: 42\n\
Iñtërnâtiônàlizætiøn is important\n\
in vars too: Iñtërnâtiônàlizætiøn\n");
-}
+}
```
User edited file: "testing/tests/simple.rs":
```diff
@@ -15,7 +15,7 @@
}
#[test]
-fn it_works() {
+fn test_variables() {
let s = TestTemplate {
strvar: "foo".to_string(),
num: 42,
``` | ```testing/tests/simple.rs
#![feature(proc_macro)]
#[macro_use]
extern crate askama_derive;
extern crate askama;
use askama::Template;
#[derive(Template)]
#[template(path = "simple.html")]
struct VariablesTemplate {
strvar: String,
num: i64,
i18n: String,
}
#[test]
fn test_variables() {
<|user_cursor_is_here|>
let s = TestTemplate {
strvar: "foo".to_string(),
num: 42,
i18n: "Iñtërnâtiônàlizætiøn".to_string(),
};
assert_eq!(s.render(), "hello world, foo\n\
with number: 42\n\
Iñtërnâtiônàlizætiøn is important\n\
in vars too: Iñtërnâtiônàlizætiøn\n");
}
``` | ```testing/tests/simple.rs
#![feature(proc_macro)]
#[macro_use]
extern crate askama_derive;
extern crate askama;
use askama::Template;
#[derive(Template)]
#[template(path = "simple.html")]
struct VariablesTemplate {
strvar: String,
num: i64,
i18n: String,
}
#[test]
fn test_variables() {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "TestTemplate", "newName": "VariablesTemplate"}}
</|tool_call|>
let s = TestTemplate {
strvar: "foo".to_string(),
num: 42,
i18n: "Iñtërnâtiônàlizætiøn".to_string(),
};
assert_eq!(s.render(), "hello world, foo\n\
with number: 42\n\
Iñtërnâtiônàlizætiøn is important\n\
in vars too: Iñtërnâtiônàlizætiøn\n");
}
``` |
User edited file: "app/components/stack-metadata/component.js":
```diff
@@ -12,7 +12,7 @@
return this.model.get('vhostNames.length') > this.get('maxVisibleDomainNames');
}),
- vhostRemaining: Ember.computed('vhostNames', function() {
+ vhostRemaining: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames');
}),
@@ -25,4 +25,4 @@
let names = this.model.get('vhostNames');
return names.slice(this.get('maxVisibleDomainNames')).join(', ');
})
-});
+});
```
User edited file: "app/components/stack-metadata/component.js":
```diff
@@ -16,7 +16,7 @@
return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames');
}),
- vhostNamesSnippet: Ember.computed('vhostNames', function() {
+ vhostNamesSnippet: Ember.computed('model.vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(0, this.get('maxVisibleDomainNames')).join(', ');
}),
``` | ```app/components/stack-metadata/component.js
import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
maxVisibleDomainNames: 1,
displayVhostNames: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames').join(', ');
}),
showVhostTooltip: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames.length') > this.get('maxVisibleDomainNames');
}),
vhostRemaining: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames');
}),
vhostNamesSnippet: Ember.computed('model.vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(0, this.get('maxVisibleDomainNames')).join(', ');
}),
<|user_cursor_is_here|>
vhostNamesTooltip: Ember.computed('vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(this.get('maxVisibleDomainNames')).join(', ');
})
});
``` | ```app/components/stack-metadata/component.js
import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
maxVisibleDomainNames: 1,
displayVhostNames: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames').join(', ');
}),
showVhostTooltip: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames.length') > this.get('maxVisibleDomainNames');
}),
vhostRemaining: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames');
}),
vhostNamesSnippet: Ember.computed('model.vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(0, this.get('maxVisibleDomainNames')).join(', ');
}),
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "vhostNames", "newName": "model.vhostNames"}}
</|tool_call|>
vhostNamesTooltip: Ember.computed('vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(this.get('maxVisibleDomainNames')).join(', ');
})
});
``` |
User edited file: "index.js":
```diff
@@ -15,7 +15,7 @@
if(!isSecure(req)){
if(req.method === "GET"){
var httpsPort = req.app.get('httpsPort') || 443;
- var fullUrl = parseUrl('http://' + req.header('Host') + req.url);
+ var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.url);
res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url);
} else {
res.status(403).send('SSL Required.');
@@ -23,4 +23,4 @@
} else {
next();
}
-};
+};
``` | ```index.js
var parseUrl = require('url').parse;
var isSecure = function(req) {
if (req.secure) {
return true;
} else if (
req.get('X-Forwarded-Proto') &&
req.get('X-Forwarded-Proto').toLowerCase &&
req.get('X-Forwarded-Proto').toLowerCase() === 'https'
) {
return true;
}
return false;
};
exports = module.exports = function(req, res, next){
if(!isSecure(req)){
if(req.method === "GET"){
var httpsPort = req.app.get('httpsPort') || 443;
<|user_cursor_is_here|>
var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.url);
res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url);
} else {
res.status(403).send('SSL Required.');
}
} else {
next();
}
};
``` | ```index.js
var parseUrl = require('url').parse;
var isSecure = function(req) {
if (req.secure) {
return true;
} else if (
req.get('X-Forwarded-Proto') &&
req.get('X-Forwarded-Proto').toLowerCase &&
req.get('X-Forwarded-Proto').toLowerCase() === 'https'
) {
return true;
}
return false;
};
exports = module.exports = function(req, res, next){
if(!isSecure(req)){
if(req.method === "GET"){
var httpsPort = req.app.get('httpsPort') || 443;
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "req.url", "newName": "req.originalUrl"}}
</|tool_call|>
var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.url);
res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url);
} else {
res.status(403).send('SSL Required.');
}
} else {
next();
}
};
``` |
User edited file: "14-redis-repositories/src/main/java/example/Person.java":
```diff
@@ -5,7 +5,7 @@
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Reference;
-import org.springframework.data.keyvalue.annotation.KeySpace;
+import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;
import lombok.Data;
@@ -23,4 +23,4 @@
City city;
@Reference Person mother;
-}
+}
``` | ```14-redis-repositories/src/main/java/example/Person.java
package example;
import java.util.Collections;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Reference;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;
import lombok.Data;
@Data
<|user_cursor_is_here|>
@KeySpace("persons")
class Person {
@Id String id;
@Indexed String firstname;
String lastname;
Map<String, String> attributes = Collections.emptyMap();
City city;
@Reference Person mother;
}
``` | ```14-redis-repositories/src/main/java/example/Person.java
package example;
import java.util.Collections;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Reference;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;
import lombok.Data;
@Data
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "KeySpace", "newName": "RedisHash"}}
</|tool_call|>
@KeySpace("persons")
class Person {
@Id String id;
@Indexed String firstname;
String lastname;
Map<String, String> attributes = Collections.emptyMap();
City city;
@Reference Person mother;
}
``` |
User edited file: "bots.sample/number-jokes/__init__.py":
```diff
@@ -1,7 +1,7 @@
import random
from botfriend.bot import TextGeneratorBot
-class ExampleBot(TextGeneratorBot):
+class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
@@ -15,4 +15,4 @@
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
-Bot = ExampleBot
+Bot = ExampleBot
``` | ```bots.sample/number-jokes/__init__.py
import random
from botfriend.bot import TextGeneratorBot
class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
<|user_cursor_is_here|>
Bot = ExampleBot
``` | ```bots.sample/number-jokes/__init__.py
import random
from botfriend.bot import TextGeneratorBot
class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "ExampleBot", "newName": "NumberJokes"}}
</|tool_call|>
Bot = ExampleBot
``` |
User edited file: "src/main/kotlin/me/mrkirby153/KirBot/command/args/elements/NumberElement.kt":
```diff
@@ -12,7 +12,7 @@
val number = num.toDouble()
if (number < min) {
- throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.2f", number, min))
+ throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.1f", number, min))
}
if (number > max) {
throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.2f", number, max))
```
User edited file: "src/main/kotlin/me/mrkirby153/KirBot/command/args/elements/NumberElement.kt":
```diff
@@ -15,7 +15,7 @@
throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.1f", number, min))
}
if (number > max) {
- throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.2f", number, max))
+ throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.1f", number, max))
}
return number
} catch (e: Exception) {
``` | ```src/main/kotlin/me/mrkirby153/KirBot/command/args/elements/NumberElement.kt
package me.mrkirby153.KirBot.command.args.elements
import me.mrkirby153.KirBot.command.args.ArgumentList
import me.mrkirby153.KirBot.command.args.ArgumentParseException
import me.mrkirby153.KirBot.command.args.CommandElement
class NumberElement(private val min: Double, private val max: Double) : CommandElement<Double> {
override fun parse(list: ArgumentList): Double {
val num = list.popFirst()
try {
val number = num.toDouble()
if (number < min) {
throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.1f", number, min))
}
if (number > max) {
throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.1f", number, max))
}
return number
<|user_cursor_is_here|>
} catch (e: Exception) {
throw ArgumentParseException("$num is not a number!")
}
}
}
``` | ```src/main/kotlin/me/mrkirby153/KirBot/command/args/elements/NumberElement.kt
package me.mrkirby153.KirBot.command.args.elements
import me.mrkirby153.KirBot.command.args.ArgumentList
import me.mrkirby153.KirBot.command.args.ArgumentParseException
import me.mrkirby153.KirBot.command.args.CommandElement
class NumberElement(private val min: Double, private val max: Double) : CommandElement<Double> {
override fun parse(list: ArgumentList): Double {
val num = list.popFirst()
try {
val number = num.toDouble()
if (number < min) {
throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.1f", number, min))
}
if (number > max) {
throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.1f", number, max))
}
return number
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "Exception", "newName": "NumberFormatException"}}
</|tool_call|>
} catch (e: Exception) {
throw ArgumentParseException("$num is not a number!")
}
}
}
``` |
User edited file: "src/org/yoooo/se1/Application.java":
```diff
@@ -31,7 +31,7 @@
Scanner scanner = new Scanner(string);
SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>(
new EdgeFactory<String, Integer>() {
- int next;
+ private int next;
@Override
public Integer createEdge(String source, String target) {
@@ -55,4 +55,4 @@
}
return graph;
}
-}
+}
``` | ```src/org/yoooo/se1/Application.java
package org.yoooo.se1;
import java.util.Scanner;
public class Application {
public void run(String[] args) {
}
public SimpleDirectedWeightGraph<String, Integer> getGraph() {
return null;
}
private static Application sInstance = new Application();
public static Application getInstance() {
return sInstance;
}
private Application() {
}
/**
* Parses string and generates graph from the string as specified in feature 1. The string
* should only contain lowercase letters and spaces.
*
* @param string string from input file
* @return graph created from string
*/
private SimpleDirectedWeightGraph<String, Integer> stringToGraph(String string) {
Scanner scanner = new Scanner(string);
SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>(
new EdgeFactory<String, Integer>() {
<|user_cursor_is_here|>
private int next;
@Override
public Integer createEdge(String source, String target) {
return next++;
}
});
if (!scanner.hasNext()) {
return graph;
}
String prev = scanner.next();
graph.addVertex(prev);
while (scanner.hasNext()) {
String vertex = scanner.next();
graph.addVertex(vertex);
Integer edge = graph.getEdge(prev, vertex);
if (edge != null) {
graph.setEdgeWeight(edge, graph.getEdgeWeight(edge) + 1);
} else {
graph.addEdge(prev, vertex);
}
}
return graph;
}
}
``` | ```src/org/yoooo/se1/Application.java
package org.yoooo.se1;
import java.util.Scanner;
public class Application {
public void run(String[] args) {
}
public SimpleDirectedWeightGraph<String, Integer> getGraph() {
return null;
}
private static Application sInstance = new Application();
public static Application getInstance() {
return sInstance;
}
private Application() {
}
/**
* Parses string and generates graph from the string as specified in feature 1. The string
* should only contain lowercase letters and spaces.
*
* @param string string from input file
* @return graph created from string
*/
private SimpleDirectedWeightGraph<String, Integer> stringToGraph(String string) {
Scanner scanner = new Scanner(string);
SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>(
new EdgeFactory<String, Integer>() {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "next", "newName": "mNext"}}
</|tool_call|>
private int next;
@Override
public Integer createEdge(String source, String target) {
return next++;
}
});
if (!scanner.hasNext()) {
return graph;
}
String prev = scanner.next();
graph.addVertex(prev);
while (scanner.hasNext()) {
String vertex = scanner.next();
graph.addVertex(vertex);
Integer edge = graph.getEdge(prev, vertex);
if (edge != null) {
graph.setEdgeWeight(edge, graph.getEdgeWeight(edge) + 1);
} else {
graph.addEdge(prev, vertex);
}
}
return graph;
}
}
``` |
User edited file: "lib/curry-provider.js":
```diff
@@ -14,23 +14,23 @@
}
getSuggestions({prefix}) {
- if (prefix) {
- const suggestions = [];
-
- for (const module of completions) {
- for (const [key, type] of this.acpTypes) {
- const createSugg = this.createSuggestion.bind(null, module.name, type);
-
- const matches = module[key].map(createSugg);
-
- suggestions.push(...matches);
- }
- }
-
- return suggestions;
+ if (!prefix) {
+ return null;
}
- return null;
+ const suggestions = [];
+
+ for (const module of completions) {
+ for (const [key, type] of this.acpTypes) {
+ const createSugg = this.createSugg.bind(null, module.name, type);
+
+ const matches = module[key].map(createSugg);
+
+ suggestions.push(...matches);
+ }
+ }
+
+ return suggestions;
}
createSuggestion(module, type, suggestion) {
``` | ```lib/curry-provider.js
'use babel';
import completions from '../data/completions';
class CurryProvider {
constructor() {
this.scopeSelector = '.source.curry';
this.disableForScopeSelector = '.source.curry .comment';
this.suggestionPriority = 2;
this.filterSuggestions = true;
this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]);
}
getSuggestions({prefix}) {
if (!prefix) {
return null;
}
const suggestions = [];
for (const module of completions) {
for (const [key, type] of this.acpTypes) {
<|user_cursor_is_here|>
const createSugg = this.createSugg.bind(null, module.name, type);
const matches = module[key].map(createSugg);
suggestions.push(...matches);
}
}
return suggestions;
}
createSuggestion(module, type, suggestion) {
return {
text: suggestion.name,
description: suggestion.description,
type: type,
leftLabel: module,
rightLabel: suggestion.typeSig
};
}
}
export default new CurryProvider();
``` | ```lib/curry-provider.js
'use babel';
import completions from '../data/completions';
class CurryProvider {
constructor() {
this.scopeSelector = '.source.curry';
this.disableForScopeSelector = '.source.curry .comment';
this.suggestionPriority = 2;
this.filterSuggestions = true;
this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]);
}
getSuggestions({prefix}) {
if (!prefix) {
return null;
}
const suggestions = [];
for (const module of completions) {
for (const [key, type] of this.acpTypes) {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "createSugg", "newName": "createSuggestion"}}
</|tool_call|>
const createSugg = this.createSugg.bind(null, module.name, type);
const matches = module[key].map(createSugg);
suggestions.push(...matches);
}
}
return suggestions;
}
createSuggestion(module, type, suggestion) {
return {
text: suggestion.name,
description: suggestion.description,
type: type,
leftLabel: module,
rightLabel: suggestion.typeSig
};
}
}
export default new CurryProvider();
``` |
User edited file: "app.js":
```diff
@@ -4,7 +4,7 @@
// TOKEN is required for connecting to Slack
-if (!process.env.TOKEN) {
+if (!process.env.SLACK_TOKEN) {
console.log('Error: Please specify TOKEN in the environment.');
process.exit(1);
}
``` | ```app.js
/**
* A Bot for Slack that tracks Mario Kart results and calculates rankings.
*/
// TOKEN is required for connecting to Slack
if (!process.env.SLACK_TOKEN) {
console.log('Error: Please specify TOKEN in the environment.');
process.exit(1);
}
var Botkit = require('botkit');
var controller = Botkit.slackbot();
var bot = controller.spawn({
<|user_cursor_is_here|>
token: process.env.TOKEN
})
bot.startRTM(function(err,bot,payload) {
if (err) {
throw new Error('Could not connect to Slack');
}
});
controller.hears(["keyword","^pattern$"],["direct_message","direct_mention","mention","ambient"],function(bot,message) {
// do something to respond to message
// all of the fields available in a normal Slack message object are available
// https://api.slack.com/events/message
bot.reply(message,'You used a keyword!');
});
``` | ```app.js
/**
* A Bot for Slack that tracks Mario Kart results and calculates rankings.
*/
// TOKEN is required for connecting to Slack
if (!process.env.SLACK_TOKEN) {
console.log('Error: Please specify TOKEN in the environment.');
process.exit(1);
}
var Botkit = require('botkit');
var controller = Botkit.slackbot();
var bot = controller.spawn({
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "TOKEN", "newName": "SLACK_TOKEN"}}
</|tool_call|>
token: process.env.TOKEN
})
bot.startRTM(function(err,bot,payload) {
if (err) {
throw new Error('Could not connect to Slack');
}
});
controller.hears(["keyword","^pattern$"],["direct_message","direct_mention","mention","ambient"],function(bot,message) {
// do something to respond to message
// all of the fields available in a normal Slack message object are available
// https://api.slack.com/events/message
bot.reply(message,'You used a keyword!');
});
``` |
User edited file: "src/main/java/com/skelril/skree/service/ModifierService.java":
```diff
@@ -11,7 +11,7 @@
import java.util.Collection;
public interface ModifierService {
- void setExpiry(String modifierName, long time);
+ void setExpiry(String modifier, long time);
long expiryOf(String modifierName);
default long statusOf(String modifierName) {
return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0);
@@ -21,4 +21,4 @@
}
Collection<Clause<String, Long>> getActiveModifiers();
-}
+}
```
User edited file: "src/main/java/com/skelril/skree/service/ModifierService.java":
```diff
@@ -12,7 +12,7 @@
public interface ModifierService {
void setExpiry(String modifier, long time);
- long expiryOf(String modifierName);
+ long expiryOf(String modifier);
default long statusOf(String modifierName) {
return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0);
}
```
User edited file: "src/main/java/com/skelril/skree/service/ModifierService.java":
```diff
@@ -13,8 +13,8 @@
public interface ModifierService {
void setExpiry(String modifier, long time);
long expiryOf(String modifier);
- default long statusOf(String modifierName) {
- return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0);
+ default long statusOf(String modifier) {
+ return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
}
default boolean isActive(String modifierName) {
return statusOf(modifierName) != 0;
``` | ```src/main/java/com/skelril/skree/service/ModifierService.java
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.service;
import com.skelril.nitro.Clause;
import java.util.Collection;
public interface ModifierService {
void setExpiry(String modifier, long time);
long expiryOf(String modifier);
default long statusOf(String modifier) {
return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
}
<|user_cursor_is_here|>
default boolean isActive(String modifierName) {
return statusOf(modifierName) != 0;
}
Collection<Clause<String, Long>> getActiveModifiers();
}
``` | ```src/main/java/com/skelril/skree/service/ModifierService.java
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.service;
import com.skelril.nitro.Clause;
import java.util.Collection;
public interface ModifierService {
void setExpiry(String modifier, long time);
long expiryOf(String modifier);
default long statusOf(String modifier) {
return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
}
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "modifierName", "newName": "modifier"}}
</|tool_call|>
default boolean isActive(String modifierName) {
return statusOf(modifierName) != 0;
}
Collection<Clause<String, Long>> getActiveModifiers();
}
``` |
User edited file: "tasks.py":
```diff
@@ -10,10 +10,10 @@
@task(help={
'pty': "Whether to run tests under a pseudo-tty",
})
-def integration_tests(pty=True):
+def integration(pty=True):
"""Runs integration tests."""
cmd = 'inv test -o --tests=integration'
run(cmd + ('' if pty else ' --no-pty'), pty=pty)
-ns = Collection(test, integration_tests, release, docs)
+ns = Collection(test, integration_tests, release, docs)
``` | ```tasks.py
from invocations import docs
from invocations.testing import test
from invocations.packaging import release
from invoke import Collection
from invoke import run
from invoke import task
@task(help={
'pty': "Whether to run tests under a pseudo-tty",
})
def integration(pty=True):
"""Runs integration tests."""
cmd = 'inv test -o --tests=integration'
run(cmd + ('' if pty else ' --no-pty'), pty=pty)
<|user_cursor_is_here|>
ns = Collection(test, integration_tests, release, docs)
``` | ```tasks.py
from invocations import docs
from invocations.testing import test
from invocations.packaging import release
from invoke import Collection
from invoke import run
from invoke import task
@task(help={
'pty': "Whether to run tests under a pseudo-tty",
})
def integration(pty=True):
"""Runs integration tests."""
cmd = 'inv test -o --tests=integration'
run(cmd + ('' if pty else ' --no-pty'), pty=pty)
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "integration_tests", "newName": "integration"}}
</|tool_call|>
ns = Collection(test, integration_tests, release, docs)
``` |
User edited file: "buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt":
```diff
@@ -16,6 +16,7 @@
package androidx.build.resources
+import androidx.build.getSupportRootFolder
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Project
import org.gradle.api.tasks.Copy
@@ -37,4 +38,4 @@
project.files(targetResFolder).builtBy(generatePublicResourcesTask)
)
}
-}
+}
``` | ```buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.resources
import androidx.build.getSupportRootFolder
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Project
import org.gradle.api.tasks.Copy
import java.io.File
fun Project.configurePublicResourcesStub(extension: LibraryExtension) {
val targetResFolder = File(project.buildDir, "generated/res/public-stub")
val generatePublicResourcesTask = tasks.register(
"generatePublicResourcesStub",
Copy::class.java
) { task ->
<|user_cursor_is_here|>
task.from(File(project.rootDir, "buildSrc/res"))
task.into(targetResFolder)
}
extension.libraryVariants.all { variant ->
variant.registerGeneratedResFolders(
project.files(targetResFolder).builtBy(generatePublicResourcesTask)
)
}
}
``` | ```buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.resources
import androidx.build.getSupportRootFolder
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Project
import org.gradle.api.tasks.Copy
import java.io.File
fun Project.configurePublicResourcesStub(extension: LibraryExtension) {
val targetResFolder = File(project.buildDir, "generated/res/public-stub")
val generatePublicResourcesTask = tasks.register(
"generatePublicResourcesStub",
Copy::class.java
) { task ->
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "rootDir", "newName": "getSupportRootFolder()"}}
</|tool_call|>
task.from(File(project.rootDir, "buildSrc/res"))
task.into(targetResFolder)
}
extension.libraryVariants.all { variant ->
variant.registerGeneratedResFolders(
project.files(targetResFolder).builtBy(generatePublicResourcesTask)
)
}
}
``` |
User edited file: "src/middleware/authenticate.js":
```diff
@@ -3,7 +3,6 @@
export default (config) => {
if ( ! config.enabled) return (req, res, next) => { next() }
- var verifyHeader = ( !! config.header)
var header = (config.header || 'Authorization').toLowerCase()
var tokenLength = 32
var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`)
@@ -46,4 +45,4 @@
next()
})
}
-}
+}
``` | ```src/middleware/authenticate.js
import handleAdapter from '../handleAdapter'
export default (config) => {
if ( ! config.enabled) return (req, res, next) => { next() }
var header = (config.header || 'Authorization').toLowerCase()
var tokenLength = 32
var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`)
return (req, res, next) => {
var err
req.auth = {}
<|user_cursor_is_here|>
if (verifyHeader) {
var value = req.auth.header = req.headers[header]
if ( ! value) {
err = new Error(`Missing ${config.header} header.`)
err.statusCode = 401
return next(err)
}
if (config.byToken !== false) {
var token = value.replace(tokenRegExp, '$1')
if (token.length !== tokenLength) {
err = new Error('Invalid token.')
err.statusCode = 401
return next(err)
}
req.auth.token = token
}
}
handleAdapter(req, config, next, (err, user) => {
if (err) {
err = new Error(err)
err.statusCode = 401
return next(err)
}
req.user = user
next()
})
}
}
``` | ```src/middleware/authenticate.js
import handleAdapter from '../handleAdapter'
export default (config) => {
if ( ! config.enabled) return (req, res, next) => { next() }
var header = (config.header || 'Authorization').toLowerCase()
var tokenLength = 32
var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`)
return (req, res, next) => {
var err
req.auth = {}
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "verifyHeader", "newName": "header"}}
</|tool_call|>
if (verifyHeader) {
var value = req.auth.header = req.headers[header]
if ( ! value) {
err = new Error(`Missing ${config.header} header.`)
err.statusCode = 401
return next(err)
}
if (config.byToken !== false) {
var token = value.replace(tokenRegExp, '$1')
if (token.length !== tokenLength) {
err = new Error('Invalid token.')
err.statusCode = 401
return next(err)
}
req.auth.token = token
}
}
handleAdapter(req, config, next, (err, user) => {
if (err) {
err = new Error(err)
err.statusCode = 401
return next(err)
}
req.user = user
next()
})
}
}
``` |
User edited file: "src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java":
```diff
@@ -1,9 +1,16 @@
package org.jenkins.ci.plugins.jenkinslint.check;
+import hudson.model.Node;
+import hudson.model.Slave;
import hudson.slaves.DumbSlave;
+import hudson.slaves.JNLPLauncher;
+import hudson.slaves.NodeProperty;
+import hudson.slaves.RetentionStrategy;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
+
+import java.util.Collections;
import static org.junit.Assert.assertTrue;
@@ -37,4 +44,4 @@
project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName());
assertTrue(checker.isIgnored(project.getDescription()));
}*/
-}
+}
```
User edited file: "src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java":
```diff
@@ -12,6 +12,7 @@
import java.util.Collections;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
```
User edited file: "src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java":
```diff
@@ -16,7 +16,7 @@
import static org.junit.Assert.assertTrue;
/**
- * SlaveDescriptionChecker Test Case.
+ * SlaveVersionChecker Test Case.
*
* @author Victor Martinez
*/
``` | ```src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java
package org.jenkins.ci.plugins.jenkinslint.check;
import hudson.model.Node;
import hudson.model.Slave;
import hudson.slaves.DumbSlave;
import hudson.slaves.JNLPLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.util.Collections;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* SlaveVersionChecker Test Case.
*
* @author Victor Martinez
*/
public class SlaveVersionCheckerTestCase {
<|user_cursor_is_here|>
private SlaveDescriptionChecker checker = new SlaveDescriptionChecker();
@Rule public JenkinsRule j = new JenkinsRule();
@Test public void testDefaultSlave() throws Exception {
DumbSlave slave = j.createSlave();
assertTrue(checker.executeCheck(slave));
}
@Test public void testEmptySlaveName() throws Exception {
DumbSlave slave = j.createSlave();
slave.setNodeName("");
assertTrue(checker.executeCheck(slave));
}
@Test public void testSlaveDescription() throws Exception {
DumbSlave slave = j.createSlave();
slave.setNodeName("blablabla");
assertTrue(checker.executeCheck(slave));
}
/**
@Test public void testControlComment() throws Exception {
DumbSlave slave = j.createSlave();
assertFalse(checker.isIgnored(project.getDescription()));
project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName());
assertTrue(checker.isIgnored(project.getDescription()));
}*/
}
``` | ```src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java
package org.jenkins.ci.plugins.jenkinslint.check;
import hudson.model.Node;
import hudson.model.Slave;
import hudson.slaves.DumbSlave;
import hudson.slaves.JNLPLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.util.Collections;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* SlaveVersionChecker Test Case.
*
* @author Victor Martinez
*/
public class SlaveVersionCheckerTestCase {
<|tool_call|>
{"name": "refactor.rename", "arguments": {"symbol": "SlaveDescriptionChecker", "newName": "SlaveVersionChecker"}}
</|tool_call|>
private SlaveDescriptionChecker checker = new SlaveDescriptionChecker();
@Rule public JenkinsRule j = new JenkinsRule();
@Test public void testDefaultSlave() throws Exception {
DumbSlave slave = j.createSlave();
assertTrue(checker.executeCheck(slave));
}
@Test public void testEmptySlaveName() throws Exception {
DumbSlave slave = j.createSlave();
slave.setNodeName("");
assertTrue(checker.executeCheck(slave));
}
@Test public void testSlaveDescription() throws Exception {
DumbSlave slave = j.createSlave();
slave.setNodeName("blablabla");
assertTrue(checker.executeCheck(slave));
}
/**
@Test public void testControlComment() throws Exception {
DumbSlave slave = j.createSlave();
assertFalse(checker.isIgnored(project.getDescription()));
project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName());
assertTrue(checker.isIgnored(project.getDescription()));
}*/
}
``` |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 106