conversations
listlengths
2
3
source
stringclasses
1 value
stack
stringclasses
1 value
[ { "from": "system", "value": "Remove warnings from test project\n\nAmusingly enough I need to add some more dead code to a failing test to\nget rid of the unused and unnecessarily `mut` warnings.\n" }, { "from": "human", "value": "extern crate basiccms;\n\n#[cfg(test)]\nmod tests {\n\n use basiccms::*;\n\n #[test]\n #[should_panic]\n fn you_cannot_add_two_sketches_together_if_they_have_different_hashers () {\n let mut left = Sketch::new(0.0001, 0.99);\n let mut right = Sketch::new(0.0001, 0.99);\n\n let third = &left + &right;\n }\n\n #[test]\n fn but_you_can_add_together_two_sketches_from_a_common_base () {\n let mut left = Sketch::new(0.0001, 0.99);\n let mut right = left.clone();\n\n left.add(1);\n right.add(1);\n\n let mut third = &left + &right;\n\n assert_eq!(1, left.point(1));\n assert_eq!(1, right.point(1));\n assert_eq!(2, third.point(1));\n }\n}\n" }, { "from": "gpt", "value": "extern crate basiccms;\n\n#[cfg(test)]\nmod tests {\n\n use basiccms::*;\n\n #[test]\n #[should_panic]\n fn you_cannot_add_two_sketches_together_if_they_have_different_hashers () {\n let mut left = Sketch::new(0.0001, 0.99);\n let mut right = Sketch::new(0.0001, 0.99);\n\n left.add(1); right.add(1);\n\n let mut third = &left + &right;\n\n third.point(1);\n }\n\n #[test]\n fn but_you_can_add_together_two_sketches_from_a_common_base () {\n let mut left = Sketch::new(0.0001, 0.99);\n let mut right = left.clone();\n\n left.add(1);\n right.add(1);\n\n let mut third = &left + &right;\n\n assert_eq!(1, left.point(1));\n assert_eq!(1, right.point(1));\n assert_eq!(2, third.point(1));\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Read at most `buffer_size` events\n" }, { "from": "human", "value": "extern crate portmidi as pm;\n\nextern crate rustc_serialize;\nextern crate docopt;\n\nconst USAGE: &'static str = r#\"\nportmidi-rs: monitor-device example\n\nUsage:\n monitor-device <id>\n\nOptions:\n -h --help Show this screen.\n\nOmitting <id> will list the available devices.\n\"#;\n\n#[derive(Debug, RustcDecodable)]\nstruct Args {\n arg_id: i32,\n}\n\nfn print_devices(pm: &pm::PortMidi) {\n for dev in pm.devices().unwrap() {\n println!(\"{}\", dev);\n }\n}\n\nfn main() {\n let context = pm::PortMidi::new(1024).unwrap();\n let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|err| {\n print_devices(&context);\n err.exit();\n });\n let info = context.device(args.arg_id).unwrap();\n println!(\"Listening on: {}) {}\", info.id(), info.name());\n\n let mut in_port = context.input_port(info).unwrap();\n while let Ok(_) = in_port.poll() {\n if let Ok(Some(event)) = in_port.read() {\n println!(\"{:?}\", event);\n }\n }\n}\n" }, { "from": "gpt", "value": "extern crate portmidi as pm;\n\nextern crate rustc_serialize;\nextern crate docopt;\n\nconst USAGE: &'static str = r#\"\nportmidi-rs: monitor-device example\n\nUsage:\n monitor-device <id>\n\nOptions:\n -h --help Show this screen.\n\nOmitting <id> will list the available devices.\n\"#;\n\n#[derive(Debug, RustcDecodable)]\nstruct Args {\n arg_id: i32,\n}\n\nfn print_devices(pm: &pm::PortMidi) {\n for dev in pm.devices().unwrap() {\n println!(\"{}\", dev);\n }\n}\n\nfn main() {\n let context = pm::PortMidi::new(1024).unwrap();\n let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|err| {\n print_devices(&context);\n err.exit();\n });\n let info = context.device(args.arg_id).unwrap();\n println!(\"Listening on: {}) {}\", info.id(), info.name());\n\n let mut in_port = context.input_port(info).unwrap();\n while let Ok(_) = in_port.poll() {\n if let Ok(Some(event)) = in_port.read_n(1024) {\n println!(\"{:?}\", event);\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add unreachable() fn, also nitpicking\n" }, { "from": "human", "value": "\n\nfn id<@T>(x: T) -> T { ret x; }\n\n\n/* FIXME (issue #141): See test/run-pass/constrained-type.rs. Uncomment\n * the constraint once fixed. */\ntype rational = {num: int, den: int};\n\n\n// : int::positive(*.den);\nfn rational_leq(x: rational, y: rational) -> bool {\n // NB: Uses the fact that rationals have positive denominators WLOG:\n\n ret x.num * y.den <= y.num * x.den;\n}\n\nfn orb(a: bool, b: bool) -> bool { ret a || b; }\n// Local Variables:\n// mode: rust;\n// fill-column: 78;\n// indent-tabs-mode: nil\n// c-basic-offset: 4\n// buffer-file-coding-system: utf-8-unix\n// compile-command: \"make -k -C $RBUILD 2>&1 | sed -e 's/\\\\/x\\\\//x:\\\\//g'\";\n// End:\n" }, { "from": "gpt", "value": "\npure fn id<@T>(x: T) -> T { x }\n\nfn unreachable() -> ! {\n fail \"Internal error: entered unreachable code\";\n}\n\n/* FIXME (issue #141): See test/run-pass/constrained-type.rs. Uncomment\n * the constraint once fixed. */\ntype rational = {num: int, den: int}; // : int::positive(*.den);\n\n// : int::positive(*.den);\npure fn rational_leq(x: rational, y: rational) -> bool {\n // NB: Uses the fact that rationals have positive denominators WLOG:\n\n x.num * y.den <= y.num * x.den\n}\n\npure fn orb(a: bool, b: bool) -> bool { a || b }\n// Local Variables:\n// mode: rust;\n// fill-column: 78;\n// indent-tabs-mode: nil\n// c-basic-offset: 4\n// buffer-file-coding-system: utf-8-unix\n// compile-command: \"make -k -C $RBUILD 2>&1 | sed -e 's/\\\\/x\\\\//x:\\\\//g'\";\n// End:\n" } ]
rust
chosen
[ { "from": "system", "value": "Add color field to Desc component\n" }, { "from": "human", "value": "/// Entity name and appearance.\n#[deriving(Clone, Show, Encodable, Decodable)]\npub struct Desc {\n pub name: String,\n pub icon: uint,\n}\n\nimpl Desc {\n pub fn new(name: String, icon: uint) -> Desc {\n Desc {\n name: name,\n icon: icon,\n }\n }\n}\n" }, { "from": "gpt", "value": "use calx::Rgb;\n\n/// Entity name and appearance.\n#[deriving(Clone, Show, Encodable, Decodable)]\npub struct Desc {\n pub name: String,\n pub icon: uint,\n pub color: Rgb,\n}\n\nimpl Desc {\n pub fn new(name: String, icon: uint, color: Rgb) -> Desc {\n Desc {\n name: name,\n icon: icon,\n color: color,\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update example to conform to new message arg behavior\n" }, { "from": "human", "value": "#[macro_use]\nextern crate serde_derive;\nextern crate serde;\nextern crate serde_bytes;\nextern crate serde_osc;\n\nuse serde_bytes::ByteBuf;\nuse serde_osc::{de, ser};\n\n/// Struct we'll serialize.\n/// This represents a single OSC message with three arguments:\n/// one of type 'i', 'f' and 'b', encoded in the order they appear in the struct.\n#[derive(Debug, Deserialize, Serialize)]\nstruct Message {\n address: String,\n num_channels: i32,\n rate: f32,\n // ByteBuf is the object we use for OSC \"blobs\".\n // It's a thin wrapper over Vec<u8> provided by Serde that allows\n // for more computationally-efficient serialization/deserialization.\n content: ByteBuf,\n}\n\nfn main() {\n let message = Message {\n address: \"/audio/play\".to_owned(),\n num_channels: 1,\n rate: 44100.0f32,\n content: ByteBuf::from(vec![0xde, 0xad, 0xbe, 0xef])\n };\n println!(\"Serializing {:?}\", message);\n\n // Serialize the message to an OSC packet stored in a Vec<u8>\n let as_vec = ser::to_vec(&message).unwrap();\n println!(\"Serialied to: {:?}\", as_vec);\n\n // Deserialize an OSC packet contained in a Vec<u8> into the Message struct\n let received: Message = de::from_vec(&as_vec).unwrap();\n println!(\"Received: {:?}\", received);\n}\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate serde_derive;\nextern crate serde;\nextern crate serde_bytes;\nextern crate serde_osc;\n\nuse serde_bytes::ByteBuf;\nuse serde_osc::{de, ser};\n\n/// Struct we'll serialize.\n/// This represents a single OSC message with three arguments:\n/// one of type 'i', 'f' and 'b', encoded in the order they appear in the struct.\n#[derive(Debug, Deserialize, Serialize)]\nstruct Message {\n address: String,\n // ByteBuf is the object we use for OSC \"blobs\".\n // It's a thin wrapper over Vec<u8> provided by Serde that allows\n // for more computationally-efficient serialization/deserialization.\n args: (i32, f32, ByteBuf),\n}\n\nfn main() {\n let message = Message {\n address: \"/audio/play\".to_owned(),\n args: (\n 1,\n 44100.0f32,\n ByteBuf::from(vec![0xde, 0xad, 0xbe, 0xef]),\n )\n };\n println!(\"Serializing {:?}\", message);\n\n // Serialize the message to an OSC packet stored in a Vec<u8>\n let as_vec = ser::to_vec(&message).unwrap();\n println!(\"Serialied to: {:?}\", as_vec);\n\n // Deserialize an OSC packet contained in a Vec<u8> into the Message struct\n let received: Message = de::from_vec(&as_vec).unwrap();\n println!(\"Received: {:?}\", received);\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Change deny attribute to warn in ruma-client-api\n" }, { "from": "human", "value": "//! Crate ruma_client_api contains serializable types for the requests and responses for each\n//! endpoint in the [Matrix](https://matrix.org/) client API specification. These types can be\n//! shared by client and server code.\n\n#![deny(missing_copy_implementations, missing_debug_implementations, missing_docs)]\n#![allow(clippy::new_without_default)]\n\npub mod error;\npub mod r0;\npub mod unversioned;\n\npub use error::Error;\n" }, { "from": "gpt", "value": "//! Crate ruma_client_api contains serializable types for the requests and responses for each\n//! endpoint in the [Matrix](https://matrix.org/) client API specification. These types can be\n//! shared by client and server code.\n\n#![warn(missing_copy_implementations, missing_debug_implementations, missing_docs)]\n#![allow(clippy::new_without_default)]\n\npub mod error;\npub mod r0;\npub mod unversioned;\n\npub use error::Error;\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix 'no information log' bug\n" }, { "from": "human", "value": "//! Helper functions for dealing with shaders.\n\n// External crates.\nuse gl;\nuse gl::types::{\n GLchar,\n GLenum,\n GLint,\n GLuint,\n};\n\nuse std::ptr;\n\n/// Compiles a shader.\n///\n/// Returns a shader or a message with the error.\npub fn compile_shader(\n shader_type: GLenum,\n source: &str\n) -> Result<GLuint, String> {\n let shader = gl::CreateShader(shader_type);\n unsafe {\n source.with_c_str(\n |ptr| gl::ShaderSource(shader, 1, &ptr, ptr::null())\n );\n gl::CompileShader(shader);\n let mut status = gl::FALSE as GLint;\n gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);\n if status == (gl::TRUE as GLint) {\n Ok(shader)\n } else {\n let mut len = 0;\n gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);\n // Subtract 1 to skip the trailing null character.\n let mut buf = Vec::from_elem(len as uint - 1, 0u8);\n gl::GetShaderInfoLog(\n shader, \n len, \n ptr::mut_null(), \n buf.as_mut_ptr() as *mut GLchar\n );\n\n gl::DeleteShader(shader);\n\n Err(String::from_utf8(buf).ok().expect(\n \"ShaderInfoLog not valid utf8\"\n ))\n }\n }\n}\n\n\n" }, { "from": "gpt", "value": "//! Helper functions for dealing with shaders.\n\n// External crates.\nuse gl;\nuse gl::types::{\n GLchar,\n GLenum,\n GLint,\n GLuint,\n};\n\nuse std::ptr;\n\n/// Compiles a shader.\n///\n/// Returns a shader or a message with the error.\npub fn compile_shader(\n shader_type: GLenum,\n source: &str\n) -> Result<GLuint, String> {\n let shader = gl::CreateShader(shader_type);\n unsafe {\n source.with_c_str(\n |ptr| gl::ShaderSource(shader, 1, &ptr, ptr::null())\n );\n gl::CompileShader(shader);\n let mut status = gl::FALSE as GLint;\n gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);\n if status == (gl::TRUE as GLint) {\n Ok(shader)\n } else {\n let mut len = 0;\n gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);\n\n if len == 0 {\n Err(\"Compilation failed with no log. The OpenGL context might have been created on another thread, or not have been created.\".to_string())\n }\n else {\n // Subtract 1 to skip the trailing null character.\n let mut buf = Vec::from_elem(len as uint - 1, 0u8);\n gl::GetShaderInfoLog(\n shader, \n len, \n ptr::mut_null(), \n buf.as_mut_ptr() as *mut GLchar\n );\n \n gl::DeleteShader(shader);\n \n Err(String::from_utf8(buf).ok().expect(\n \"ShaderInfoLog not valid utf8\"\n ))\n }\n }\n }\n}\n\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove unnecessary feature from instruction reference documentation generation code\n" }, { "from": "human", "value": "#![feature(proc_macro_hygiene)]\n\nuse std::io::{self, Write};\n\nfn main() {\n let mut args = std::env::args();\n args.next().unwrap();\n\n let opmap = match args.next().expect(\"Architecture name\").as_str() {\n \"x64\" => dynasm::dynasm_opmap!(x64),\n \"aarch64\" => dynasm::dynasm_opmap!(aarch64),\n x => panic!(\"Unknown opmap format '{}'\", x)\n };\n\n let stdout = io::stdout();\n let mut stdout = stdout.lock();\n stdout.write_all(opmap.as_bytes()).unwrap();\n}\n" }, { "from": "gpt", "value": "use std::io::{self, Write};\n\nfn main() {\n let mut args = std::env::args();\n args.next().unwrap();\n\n let opmap = match args.next().expect(\"Architecture name\").as_str() {\n \"x64\" => dynasm::dynasm_opmap!(x64),\n \"aarch64\" => dynasm::dynasm_opmap!(aarch64),\n x => panic!(\"Unknown opmap format '{}'\", x)\n };\n\n let stdout = io::stdout();\n let mut stdout = stdout.lock();\n stdout.write_all(opmap.as_bytes()).unwrap();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use bigint when computing binomial coefficients\n" }, { "from": "human", "value": "// http://rosettacode.org/wiki/Evaluate_binomial_coefficients\n\nfn binomial(n: uint, mut k: uint) -> u64 {\n // Since binomial(n, k) = binomial(n, n - k), we might as well use\n // the smaller k to optimize\n if n - k < k {\n k = n - k;\n }\n\n // Compute the coefficient\n let mut res = 1u64;\n for i in range(1, k as u64 + 1) {\n res *= (n - k) as u64 + i;\n res /= i;\n }\n\n res\n}\n\n#[cfg(not(test))]\nfn main() {\n println!(\"{}\", binomial(5, 3));\n}\n\n#[test]\nfn test_binomial() {\n assert_eq!(binomial(20, 0), binomial(20, 20));\n assert_eq!(binomial(20, 15), binomial(19, 14) + binomial(19, 15));\n assert_eq!(binomial(5, 3), 10);\n assert_eq!(binomial(31, 17), 265182525);\n}\n\n" }, { "from": "gpt", "value": "// http://rosettacode.org/wiki/Evaluate_binomial_coefficients\n\nextern crate num;\nextern crate core;\nuse num::bigint::BigUint;\nuse core::num::One;\n\nfn binomial(n: uint, mut k: uint) -> BigUint {\n // Since binomial(n, k) = binomial(n, n - k), we might as well use\n // the smaller k to optimize\n if n - k < k {\n k = n - k;\n }\n\n // Compute the coefficient\n let mut res: BigUint = One::one();\n for i in range(1, k + 1) {\n res = res * FromPrimitive::from_uint(n - k + i).unwrap();\n res = res / FromPrimitive::from_uint(i).unwrap();\n }\n\n res\n}\n\n#[cfg(not(test))]\nfn main() {\n println!(\"{}\", binomial(5, 3));\n}\n\n#[test]\nfn test_binomial() {\n use std::from_str::FromStr;\n\n assert_eq!(binomial(20, 0), binomial(20, 20));\n assert_eq!(binomial(20, 15), binomial(19, 14) + binomial(19, 15));\n assert_eq!(binomial(5, 3), FromPrimitive::from_uint(10).unwrap());\n assert_eq!(binomial(31, 17), FromPrimitive::from_uint(265182525).unwrap());\n assert_eq!(binomial(300, 30),\n FromStr::from_str(\"173193226149263513034110205899732811401360\").unwrap());\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Use macros for creating ruby methods\n" }, { "from": "human", "value": "#![no_std]\nextern crate ruru;\n\nuse ruru::VM;\nuse ruru::Hash;\nuse ruru::Fixnum;\nuse ruru::Class;\nuse ruru::types::Argc;\nuse ruru::AnyObject;\n\n#[no_mangle]\npub extern fn pow_3(argc: Argc, argv: *const AnyObject, _: Fixnum) -> Hash {\n let argv = VM::parse_arguments(argc, argv);\n let num = argv[0].as_fixnum().to_i64();\n\n let mut hash = Hash::new();\n\n for i in 1..num + 1 {\n hash.store(Fixnum::new(i), Fixnum::new(i.pow(3)));\n }\n\n hash\n}\n\n\n#[no_mangle]\npub extern fn initialize_my_app() {\n Class::new(\"Calculator\").define(|itself| {\n itself.def(\"pow_3\", pow_3);\n });\n}\n" }, { "from": "gpt", "value": "#![no_std]\n\n#[macro_use]\nextern crate ruru;\n\nuse ruru::VM;\nuse ruru::Hash;\nuse ruru::Fixnum;\nuse ruru::Class;\nuse ruru::AnyObject;\nuse ruru::types::{Argc, Value};\nuse ruru::traits::Object;\n\nclass!(Calculator);\n\nmethods!(\n Calculator,\n itself,\n\n pow_3(num: Fixnum) -> Hash {\n let mut hash = Hash::new();\n\n for i in 1..num.to_i64() + 1 {\n hash.store(Fixnum::new(i), Fixnum::new(i.pow(3)));\n }\n\n hash\n }\n);\n\n#[no_mangle]\npub extern fn initialize_my_app() {\n Class::new(\"Calculator\").define(|itself| {\n itself.def(\"pow_3\", pow_3);\n });\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Change return code for configuration error\n" }, { "from": "human", "value": "use ghclient::GithubClient;\nuse std;\nuse std::env;\nuse std::path::Path;\nuse std::string::String;\nuse structs::Config;\n\nlazy_static! {\n static ref DEFAULT_CONF_PATH_STR:String = String::from(\"/etc/sectora.conf\");\n static ref CONF_PATH_STR:String = env::var(\"SECTORA_CONFIG\").unwrap_or(DEFAULT_CONF_PATH_STR.clone());\n static ref CONF_PATH:&'static Path = Path::new(&(*CONF_PATH_STR));\n pub static ref CONFIG:Config = match Config::new(&CONF_PATH) {\n Ok(config) => config,\n Err(err) => {\n println!(\"Failed to open configuration file: {:?}\", *CONF_PATH);\n println!(\"[{:?}]\", err);\n std::process::exit(11);\n }\n };\n pub static ref CLIENT:GithubClient = GithubClient::new(&CONFIG);\n}\n" }, { "from": "gpt", "value": "use ghclient::GithubClient;\nuse std;\nuse std::env;\nuse std::path::Path;\nuse std::string::String;\nuse structs::Config;\n\nlazy_static! {\n static ref DEFAULT_CONF_PATH_STR:String = String::from(\"/etc/sectora.conf\");\n static ref CONF_PATH_STR:String = env::var(\"SECTORA_CONFIG\").unwrap_or(DEFAULT_CONF_PATH_STR.clone());\n static ref CONF_PATH:&'static Path = Path::new(&(*CONF_PATH_STR));\n pub static ref CONFIG:Config = match Config::new(&CONF_PATH) {\n Ok(config) => config,\n Err(err) => {\n println!(\"Failed to open configuration file: {:?}\", *CONF_PATH);\n println!(\"[{:?}]\", err);\n std::process::exit(-2);\n }\n };\n pub static ref CLIENT:GithubClient = GithubClient::new(&CONFIG);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Set lld flavor for MSVC to link.exe\n" }, { "from": "human", "value": "use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions};\nuse std::default::Default;\n\npub fn opts() -> TargetOptions {\n let mut args = LinkArgs::new();\n args.insert(LinkerFlavor::Msvc, vec![\"/NOLOGO\".to_string(), \"/NXCOMPAT\".to_string()]);\n\n TargetOptions {\n function_sections: true,\n dynamic_linking: true,\n executables: true,\n dll_prefix: String::new(),\n dll_suffix: \".dll\".to_string(),\n exe_suffix: \".exe\".to_string(),\n staticlib_prefix: String::new(),\n staticlib_suffix: \".lib\".to_string(),\n target_family: Some(\"windows\".to_string()),\n is_like_windows: true,\n is_like_msvc: true,\n // set VSLANG to 1033 can prevent link.exe from using\n // language packs, and avoid generating Non-UTF-8 error\n // messages if a link error occurred.\n link_env: vec![(\"VSLANG\".to_string(), \"1033\".to_string())],\n pre_link_args: args,\n crt_static_allows_dylibs: true,\n crt_static_respected: true,\n abi_return_struct_as_int: true,\n emit_debug_gdb_scripts: false,\n requires_uwtable: true,\n\n ..Default::default()\n }\n}\n" }, { "from": "gpt", "value": "use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, TargetOptions};\nuse std::default::Default;\n\npub fn opts() -> TargetOptions {\n let pre_args = vec![\"/NOLOGO\".to_string(), \"/NXCOMPAT\".to_string()];\n let mut args = LinkArgs::new();\n args.insert(LinkerFlavor::Msvc, pre_args.clone());\n args.insert(LinkerFlavor::Lld(LldFlavor::Link), pre_args);\n\n TargetOptions {\n function_sections: true,\n dynamic_linking: true,\n executables: true,\n dll_prefix: String::new(),\n dll_suffix: \".dll\".to_string(),\n exe_suffix: \".exe\".to_string(),\n staticlib_prefix: String::new(),\n staticlib_suffix: \".lib\".to_string(),\n target_family: Some(\"windows\".to_string()),\n is_like_windows: true,\n is_like_msvc: true,\n // set VSLANG to 1033 can prevent link.exe from using\n // language packs, and avoid generating Non-UTF-8 error\n // messages if a link error occurred.\n link_env: vec![(\"VSLANG\".to_string(), \"1033\".to_string())],\n lld_flavor: LldFlavor::Link,\n pre_link_args: args,\n crt_static_allows_dylibs: true,\n crt_static_respected: true,\n abi_return_struct_as_int: true,\n emit_debug_gdb_scripts: false,\n requires_uwtable: true,\n\n ..Default::default()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add with-deprecated and doc hidden attributes\n" }, { "from": "human", "value": "//! Provides types and functions related to working with PostgreSQL\n//!\n//! Much of this module is re-exported from database agnostic locations.\n//! However, if you are writing code specifically to extend Diesel on\n//! PostgreSQL, you may need to work with this module directly.\n\npub mod expression;\npub mod types;\n#[deprecated(since = \"1.4.0\", note = \"Use `diesel::upsert` instead\")]\npub use crate::upsert;\n\nmod backend;\nmod connection;\nmod metadata_lookup;\npub(crate) mod on_constraint;\nmod query_builder;\npub(crate) mod serialize;\nmod transaction;\nmod value;\n\npub use self::backend::{Pg, PgTypeMetadata};\npub use self::connection::PgConnection;\npub use self::metadata_lookup::PgMetadataLookup;\npub use self::query_builder::DistinctOnClause;\npub use self::query_builder::PgQueryBuilder;\npub use self::transaction::TransactionBuilder;\npub use self::value::PgValue;\n\n/// Data structures for PG types which have no corresponding Rust type\n///\n/// Most of these types are used to implement `ToSql` and `FromSql` for higher\n/// level types.\npub mod data_types {\n #[doc(inline)]\n pub use super::types::date_and_time::{PgDate, PgInterval, PgTime, PgTimestamp};\n #[doc(inline)]\n pub use super::types::floats::PgNumeric;\n #[doc(inline)]\n pub use super::types::money::PgMoney;\n pub use super::types::money::PgMoney as Cents;\n}\n" }, { "from": "gpt", "value": "//! Provides types and functions related to working with PostgreSQL\n//!\n//! Much of this module is re-exported from database agnostic locations.\n//! However, if you are writing code specifically to extend Diesel on\n//! PostgreSQL, you may need to work with this module directly.\n\npub mod expression;\npub mod types;\n\n#[doc(hidden)]\n#[cfg(feature = \"with-deprecated\")]\n#[deprecated(since = \"1.4.0\", note = \"Use `diesel::upsert` instead\")]\npub use crate::upsert;\n\nmod backend;\nmod connection;\nmod metadata_lookup;\npub(crate) mod on_constraint;\nmod query_builder;\npub(crate) mod serialize;\nmod transaction;\nmod value;\n\npub use self::backend::{Pg, PgTypeMetadata};\npub use self::connection::PgConnection;\npub use self::metadata_lookup::PgMetadataLookup;\npub use self::query_builder::DistinctOnClause;\npub use self::query_builder::PgQueryBuilder;\npub use self::transaction::TransactionBuilder;\npub use self::value::PgValue;\n\n/// Data structures for PG types which have no corresponding Rust type\n///\n/// Most of these types are used to implement `ToSql` and `FromSql` for higher\n/// level types.\npub mod data_types {\n #[doc(inline)]\n pub use super::types::date_and_time::{PgDate, PgInterval, PgTime, PgTimestamp};\n #[doc(inline)]\n pub use super::types::floats::PgNumeric;\n #[doc(inline)]\n pub use super::types::money::PgMoney;\n pub use super::types::money::PgMoney as Cents;\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add regression test for macro expansion\n" }, { "from": "human", "value": "// run-rustfix\n\n#![warn(clippy::toplevel_ref_arg)]\n#![allow(unused)]\n\nfn main() {\n // Closures should not warn\n let y = |ref x| println!(\"{:?}\", x);\n y(1u8);\n\n let ref x = 1;\n\n let ref y: (&_, u8) = (&1, 2);\n\n let ref z = 1 + 2;\n\n let ref mut z = 1 + 2;\n\n let (ref x, _) = (1, 2); // ok, not top level\n println!(\"The answer is {}.\", x);\n\n // Make sure that allowing the lint works\n #[allow(clippy::toplevel_ref_arg)]\n let ref mut x = 1_234_543;\n}\n" }, { "from": "gpt", "value": "// run-rustfix\n\n#![warn(clippy::toplevel_ref_arg)]\n#![allow(unused)]\n\nfn main() {\n // Closures should not warn\n let y = |ref x| println!(\"{:?}\", x);\n y(1u8);\n\n let ref x = 1;\n\n let ref y: (&_, u8) = (&1, 2);\n\n let ref z = 1 + 2;\n\n let ref mut z = 1 + 2;\n\n let (ref x, _) = (1, 2); // ok, not top level\n println!(\"The answer is {}.\", x);\n\n let ref x = vec![1, 2, 3];\n\n // Make sure that allowing the lint works\n #[allow(clippy::toplevel_ref_arg)]\n let ref mut x = 1_234_543;\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add a unit test module\n\nDoctests seem to suppress warnings (note PR #1 was about the \"unused type\" warning)\n\nSigned-off-by: NODA, Kai <a445972a03eaa731f8b4469e4f864a9a57c01ed3@gmail.com>\n" }, { "from": "human", "value": "//! A library implementation of so-called `static_assert` based on a macro which\n//! conditionally expands into an integer overflow, breaking the compilation.\n//!\n//! It can take one or more constant boolean expressions as its parameters.\n//! When you have multiple conditions to verify, pass them to a single\n//! invocation of this macro as multiple parameters.\n//!\n//! **You cannot invoke this macro more than once in a given scope.**\n//! This is because its implementation is based on a type synonym definition and\n//! two or more invocation causes name collision.\n//!\n//! ## Example\n//! ```\n//! #[macro_use]\n//! extern crate static_assert_macro;\n//!\n//! static_assert!(0 < 1, 1 < 2, 2 < 3);\n//!\n//! fn main() {\n//! const FOUR: i32 = 4;\n//! static_assert!(1 + 2 == { FOUR - 1 });\n//! }\n//! ```\n\n#[macro_export]\nmacro_rules! static_assert {\n (let $e:expr; ) => (\n type _ArrayForStaticAssert = [i8; 0 - ((false == ($e)) as usize)];\n );\n\n (let $e:expr; $e1:expr $(, $ee:expr)*) => (\n static_assert!(let ($e) && ($e1); $($ee),*);\n );\n\n ($e:expr $(, $ee:expr)*) => (\n static_assert!(let $e; $($ee),*);\n );\n}\n" }, { "from": "gpt", "value": "//! A library implementation of so-called `static_assert` based on a macro which\n//! conditionally expands into an integer overflow, breaking the compilation.\n//!\n//! It can take one or more constant boolean expressions as its parameters.\n//! When you have multiple conditions to verify, pass them to a single\n//! invocation of this macro as multiple parameters.\n//!\n//! **You cannot invoke this macro more than once in a given scope.**\n//! This is because its implementation is based on a type synonym definition and\n//! two or more invocation causes name collision.\n//!\n//! ## Example\n//! ```\n//! #[macro_use]\n//! extern crate static_assert_macro;\n//!\n//! static_assert!(0 < 1, 1 < 2, 2 < 3);\n//!\n//! fn main() {\n//! const FOUR: i32 = 4;\n//! static_assert!(1 + 2 == { FOUR - 1 });\n//! }\n//! ```\n\n#[macro_export]\nmacro_rules! static_assert {\n (let $e:expr; ) => (\n type _ArrayForStaticAssert = [i8; 0 - ((false == ($e)) as usize)];\n );\n\n (let $e:expr; $e1:expr $(, $ee:expr)*) => (\n static_assert!(let ($e) && ($e1); $($ee),*);\n );\n\n ($e:expr $(, $ee:expr)*) => (\n static_assert!(let $e; $($ee),*);\n );\n}\n\n#[cfg(test)]\nmod tests {\n const _FOUR: i32 = 4;\n\n #[test]\n fn test_0() {\n static_assert!(1 + 2 == { _FOUR - 1 }, 2 < 3);\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update serde_derive_internals to tool attrs\n" }, { "from": "human", "value": "#![doc(html_root_url = \"https://docs.rs/serde_derive_internals/0.25.0\")]\n#![allow(unknown_lints, bare_trait_objects)]\n#![cfg_attr(feature = \"cargo-clippy\", allow(renamed_and_removed_lints))]\n#![cfg_attr(\n feature = \"cargo-clippy\",\n allow(\n cognitive_complexity,\n redundant_field_names,\n result_unit_err,\n should_implement_trait,\n trivially_copy_pass_by_ref,\n wildcard_in_or_patterns,\n // clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704\n unnested_or_patterns,\n )\n)]\n\n#[macro_use]\nextern crate syn;\n\nextern crate proc_macro2;\nextern crate quote;\n\n#[path = \"src/mod.rs\"]\nmod internals;\n\npub use internals::*;\n" }, { "from": "gpt", "value": "#![doc(html_root_url = \"https://docs.rs/serde_derive_internals/0.25.0\")]\n#![allow(unknown_lints, bare_trait_objects)]\n#![deny(clippy::all)]\n#![allow(\n clippy::cognitive_complexity,\n clippy::redundant_field_names,\n clippy::result_unit_err,\n clippy::should_implement_trait,\n clippy::trivially_copy_pass_by_ref,\n clippy::wildcard_in_or_patterns,\n // clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704\n clippy::unnested_or_patterns,\n)]\n\n#[macro_use]\nextern crate syn;\n\nextern crate proc_macro2;\nextern crate quote;\n\n#[path = \"src/mod.rs\"]\nmod internals;\n\npub use internals::*;\n" } ]
rust
chosen
[ { "from": "system", "value": "Use `into_inner` instead of `unwrap`.\n" }, { "from": "human", "value": "use nalgebra::{Isometry3, Matrix4, Perspective3, Point3, Real, Scalar, Vector3};\n\npub struct Camera<T>\nwhere\n T: Real + Scalar,\n{\n projection: Perspective3<T>,\n view: Isometry3<T>,\n}\n\nimpl<T> Camera<T>\nwhere\n T: Real + Scalar,\n{\n pub fn new(aspect: T, fov: T, near: T, far: T) -> Self {\n Camera {\n projection: Perspective3::new(aspect, fov, near, far),\n view: Isometry3::look_at_rh(\n &Point3::origin(),\n &Point3::new(T::zero(), T::zero(), -T::one()),\n &Vector3::y(),\n ),\n }\n }\n\n pub fn look_at(&mut self, from: &Point3<T>, to: &Point3<T>) {\n self.view = Isometry3::look_at_rh(from, to, &Vector3::y());\n }\n\n pub fn transform(&self) -> Matrix4<T> {\n self.projection.unwrap() * self.view.to_homogeneous()\n }\n}\n" }, { "from": "gpt", "value": "use nalgebra::{Isometry3, Matrix4, Perspective3, Point3, Real, Scalar, Vector3};\n\npub struct Camera<T>\nwhere\n T: Real + Scalar,\n{\n projection: Perspective3<T>,\n view: Isometry3<T>,\n}\n\nimpl<T> Camera<T>\nwhere\n T: Real + Scalar,\n{\n pub fn new(aspect: T, fov: T, near: T, far: T) -> Self {\n Camera {\n projection: Perspective3::new(aspect, fov, near, far),\n view: Isometry3::look_at_rh(\n &Point3::origin(),\n &Point3::new(T::zero(), T::zero(), -T::one()),\n &Vector3::y(),\n ),\n }\n }\n\n pub fn look_at(&mut self, from: &Point3<T>, to: &Point3<T>) {\n self.view = Isometry3::look_at_rh(from, to, &Vector3::y());\n }\n\n pub fn transform(&self) -> Matrix4<T> {\n self.projection.into_inner() * self.view.to_homogeneous()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Improve solution for Scrabble Score\n" }, { "from": "human", "value": "pub fn score(word: &str) -> u32 {\n let mut score = 0;\n\n for c in word.chars() {\n score += match c.to_lowercase().to_string().as_ref() {\n \"a\" | \"e\" | \"i\" | \"o\" | \"u\" | \"l\" | \"n\" | \"r\" | \"s\" | \"t\" => 1,\n \"d\" | \"g\" => 2,\n \"b\" | \"c\" | \"m\" | \"p\" => 3,\n \"f\" | \"h\" | \"v\" | \"w\" | \"y\" => 4,\n \"k\" => 5,\n \"j\" | \"x\" => 8,\n \"q\" | \"z\" => 10,\n _ => 0\n }\n }\n\n score\n}\n" }, { "from": "gpt", "value": "pub fn score(word: &str) -> u32 {\n word.to_lowercase().chars().map(|c| {\n match c {\n 'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' | 's' | 't' => 1,\n 'd' | 'g' => 2,\n 'b' | 'c' | 'm' | 'p' => 3,\n 'f' | 'h' | 'v' | 'w' | 'y' => 4,\n 'k' => 5,\n 'j' | 'x' => 8,\n 'q' | 'z' => 10,\n _ => 0\n }\n }).sum()\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Redefine Multiboot info struct in an easier way. Because we do not know what tags will be there at startup, we need to use the tag iterator to search for the tags by their tag type as we need them.\n" }, { "from": "human", "value": "use bios_boot_device::BIOSBootDeviceTag;\nuse tag::{Tag, TagIter};\n\n\npub struct MultiBootInfo {\n total_size: u32,\n reserved: u32, // Should always be 0\n mem_lower: u32,\n mem_upper: u32,\n boot_device: u32,\n boot_cmd_line: u32,\n module_count: u32,\n modules: u32,\n elf_symbols: u32,\n memory_map: u32,\n boot_loader_name: u32,\n apm_table: u32,\n vbe_info: u32,\n framebuffer_info: u32\n}\n\nimpl MultiBootInfo {\n unsafe fn new(multiboot_addr: u32) -> () {\n let total_size = *(multiboot_addr as *const u32);\n let reserved = *((multiboot_addr + 4) as *const u32);\n let first_tag = (multiboot_addr + 8) as *const Tag;\n let tag_iter = TagIter::new(first_tag);\n }\n}" }, { "from": "gpt", "value": "use bios_boot_device::BIOSBootDeviceTag;\nuse tag::{Tag, TagIter};\n\n\n#[derive(Debug)]\n#[repr(C, packed)]\npub struct MultiBootInfo {\n total_size: u32,\n reserved: u32, // Should always be 0.\n first_tag: *const Tag\n}\n\nimpl MultiBootInfo {\n unsafe fn new(multiboot_addr: u32) -> MultiBootInfo {\n let total_size = *(multiboot_addr as *const u32);\n let reserved = *((multiboot_addr + 4) as *const u32);\n let first_tag = (multiboot_addr + 8) as *const Tag;\n \n MultiBootInfo {\n total_size: total_size,\n reserved: reserved,\n first_tag: first_tag\n }\n\n }\n\n pub fn start_address(&self) -> usize {\n self as *const _ as usize\n }\n\n pub fn end_address(&self) -> usize {\n self.start_address() + self.total_size()\n }\n\n pub fn total_size(&self) -> usize {\n self.total_size as usize\n }\n\n\n}" } ]
rust
chosen
[ { "from": "system", "value": "testsuite: Update error message, unbreak build\n" }, { "from": "human", "value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nstruct cat {\n priv mut meows : uint,\n\n how_hungry : int,\n}\n\nimpl cat {\n\n fn speak() { self.meows += 1u; }\n}\n\nfn cat(in_x : uint, in_y : int) -> cat {\n cat {\n meows: in_x,\n how_hungry: in_y\n }\n}\n\nfn main() {\n let nyan : cat = cat(52u, 99);\n nyan.speak = fn@() { debug!(\"meow\"); }; //~ ERROR attempted to take value of method\n //~^ ERROR mismatched types\n}\n" }, { "from": "gpt", "value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nstruct cat {\n priv mut meows : uint,\n\n how_hungry : int,\n}\n\nimpl cat {\n\n fn speak() { self.meows += 1u; }\n}\n\nfn cat(in_x : uint, in_y : int) -> cat {\n cat {\n meows: in_x,\n how_hungry: in_y\n }\n}\n\nfn main() {\n let nyan : cat = cat(52u, 99);\n nyan.speak = fn@() { debug!(\"meow\"); }; //~ ERROR attempted to take value of method\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Implement n = 1, n = 2 special cases\n" }, { "from": "human", "value": "//! Quicksort algorithm.\n//!\n//! The `efficient` module contains the efficient sorting algorithm \"Quicksort\".\n//!\n//! Source: https://en.wikipedia.org/wiki/Quicksort\n\n\n/// Quicksort\n///\n/// # Details\n///\n///\n///\n/// # Scaling\n///\n///\n///\n/// # Optimizations\n///\n/// None\n///\n/// # Notes\n///\n/// The type T of the vector elements to sort _must_ implement the `PartialOrd` trait so the\n/// compiler knows how to compare the elements and sort them.\n///\n/// # Examples\n///\n/// ```\n/// let mut data: Vec<i32> = vec![4, 2, 3, 1, 5];\n/// sorting::efficientsorts::quick::sort(&mut data);\n/// assert_eq!(vec![1, 2, 3, 4, 5], data);\n/// ```\n///\npub fn sort<T: PartialOrd>(array: &mut Vec<T>) {\n unimplemented!();\n}\n" }, { "from": "gpt", "value": "//! Quicksort algorithm.\n//!\n//! The `efficient` module contains the efficient sorting algorithm \"Quicksort\".\n//!\n//! Source: https://en.wikipedia.org/wiki/Quicksort\n\n\n/// Quicksort\n///\n/// # Details\n///\n///\n///\n/// # Scaling\n///\n///\n///\n/// # Optimizations\n///\n/// None\n///\n/// # Notes\n///\n/// The type T of the vector elements to sort _must_ implement the `PartialOrd` trait so the\n/// compiler knows how to compare the elements and sort them.\n///\n/// # Examples\n///\n/// ```\n/// let mut data: Vec<i32> = vec![4, 2, 3, 1, 5];\n/// sorting::efficientsorts::quick::sort(&mut data);\n/// assert_eq!(vec![1, 2, 3, 4, 5], data);\n/// ```\n///\npub fn sort<T: PartialOrd>(array: &mut Vec<T>) {\n let n = array.len();\n\n if n <= 1 {\n return;\n } else if n == 2 {\n if array.first() <= array.last() {\n return;\n } else {\n array.swap(0, 1);\n return;\n }\n } else {\n unimplemented!();\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "format: Drop the easy Buffered implementation for Cursor\n" }, { "from": "human", "value": "mod accreader;\n\npub use self::accreader::AccReader;\n\nuse std::io::{BufRead, Seek, Cursor};\n\npub trait Buffered: BufRead + Seek {\n fn data(&self) -> &[u8];\n}\n\nimpl<'a> Buffered for Cursor<&'a [u8]> {\n fn data(&self) -> &[u8] {\n &self.get_ref()[self.position() as usize..]\n }\n}\n" }, { "from": "gpt", "value": "mod accreader;\n\npub use self::accreader::AccReader;\n\nuse std::io::{BufRead, Seek, Cursor};\n\npub trait Buffered: BufRead + Seek {\n fn data(&self) -> &[u8];\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update IO references to use old_io module.\n" }, { "from": "human", "value": "use std::io::{File, Open, ReadWrite};\nuse std::io::IoResult;\nuse super::GapBuffer;\nuse super::gap_buffer;\nuse super::Position;\nuse super::Range;\n\npub struct Buffer {\n data: GapBuffer,\n file: Option<File>,\n}\n\npub fn from_file(path: &Path) -> IoResult<Buffer> {\n // Try to open and read the file, returning any errors encountered.\n let mut file = match File::open_mode(path, Open, ReadWrite) {\n Ok(f) => f,\n Err(error) => return Err(error),\n };\n let mut data = match file.read_to_string() {\n Ok(d) => d,\n Err(error) => return Err(error),\n };\n\n let data = gap_buffer::new(data);\n\n // Create a new buffer using the loaded data, file, and other defaults.\n Ok(Buffer{ data: data, file: Some(file) })\n}\n\n#[cfg(test)]\nmod tests {\n use super::from_file;\n\n #[test]\n fn from_file_loads_file_into_buffer() {\n match from_file(&Path::new(\"tests/sample/file\")) {\n Ok(buffer) => assert_eq!(buffer.data.to_string(), \"it works!\\n\"),\n Err(error) => panic!(error),\n }\n }\n}\n" }, { "from": "gpt", "value": "use std::old_io::{File, Open, ReadWrite};\nuse std::old_io::IoResult;\nuse super::GapBuffer;\nuse super::gap_buffer;\nuse super::Position;\nuse super::Range;\n\npub struct Buffer {\n data: GapBuffer,\n file: Option<File>,\n}\n\npub fn from_file(path: &Path) -> IoResult<Buffer> {\n // Try to open and read the file, returning any errors encountered.\n let mut file = match File::open_mode(path, Open, ReadWrite) {\n Ok(f) => f,\n Err(error) => return Err(error),\n };\n let mut data = match file.read_to_string() {\n Ok(d) => d,\n Err(error) => return Err(error),\n };\n\n let data = gap_buffer::new(data);\n\n // Create a new buffer using the loaded data, file, and other defaults.\n Ok(Buffer{ data: data, file: Some(file) })\n}\n\n#[cfg(test)]\nmod tests {\n use super::from_file;\n\n #[test]\n fn from_file_loads_file_into_buffer() {\n match from_file(&Path::new(\"tests/sample/file\")) {\n Ok(buffer) => assert_eq!(buffer.data.to_string(), \"it works!\\n\"),\n Err(error) => panic!(error),\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "[Fix] Add option \"indeed\" to cron contents\n" }, { "from": "human", "value": "use error::{CliError, Usage, UsageKind};\nuse super::Command;\n\nuse lib::setting::{Config, ConfigKey, Cron};\n\n#[derive(Debug)]\npub struct Start;\n\nimpl Command for Start {\n fn usage(&self) -> Usage {\n return Usage::new(UsageKind::Start);\n }\n\n fn main(&self) -> Result<(), CliError> {\n let cron = try!(Cron::read());\n\n let pair_for_burn = (\"0 0 * * *\", \"burn\");\n\n let config = try!(Config::read());\n let day_and_month = match try!(config.get(ConfigKey::SweepPeriod)).as_ref() {\n \"daily\" => \"* * *\",\n \"weekly\" => \"* * 0\",\n _ => unreachable!(\"Mistake SweepPeriod's validation!!\"),\n };\n let (hour, minute) = Config::to_hour_and_minute(try!(config.get(ConfigKey::SweepTime)));\n let when = format!(\"{} {} {}\", minute, hour, day_and_month);\n let pair_for_sweep = (&when as &str, \"sweep\");\n\n cron\n .update(&[pair_for_burn, pair_for_sweep])\n .and_then(|new_cron| new_cron.set())\n }\n}\n" }, { "from": "gpt", "value": "use error::{CliError, Usage, UsageKind};\nuse super::Command;\n\nuse lib::setting::{Config, ConfigKey, Cron};\n\n#[derive(Debug)]\npub struct Start;\n\nimpl Command for Start {\n fn usage(&self) -> Usage {\n return Usage::new(UsageKind::Start);\n }\n\n fn main(&self) -> Result<(), CliError> {\n let cron = try!(Cron::read());\n\n let pair_for_burn = (\"0 0 * * *\", \"burn indeed\");\n\n let config = try!(Config::read());\n let day_and_month = match try!(config.get(ConfigKey::SweepPeriod)).as_ref() {\n \"daily\" => \"* * *\",\n \"weekly\" => \"* * 0\",\n _ => unreachable!(\"Mistake SweepPeriod's validation!!\"),\n };\n let (hour, minute) = Config::to_hour_and_minute(try!(config.get(ConfigKey::SweepTime)));\n let when = format!(\"{} {} {}\", minute, hour, day_and_month);\n let pair_for_sweep = (&when as &str, \"sweep indeed\");\n\n cron\n .update(&[pair_for_burn, pair_for_sweep])\n .and_then(|new_cron| new_cron.set())\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix another Eq missing case.\n" }, { "from": "human", "value": "import option;\n\nenum mode { mode_compile_fail, mode_run_fail, mode_run_pass, mode_pretty, }\n\ntype config = {\n // The library paths required for running the compiler\n compile_lib_path: ~str,\n\n // The library paths required for running compiled programs\n run_lib_path: ~str,\n\n // The rustc executable\n rustc_path: Path,\n\n // The directory containing the tests to run\n src_base: Path,\n\n // The directory where programs should be built\n build_base: Path,\n\n // Directory for auxiliary libraries\n aux_base: Path,\n\n // The name of the stage being built (stage1, etc)\n stage_id: ~str,\n\n // The test mode, compile-fail, run-fail, run-pass\n mode: mode,\n\n // Run ignored tests\n run_ignored: bool,\n\n // Only run tests that match this filter\n filter: Option<~str>,\n\n // Write out a parseable log of tests that were run\n logfile: Option<Path>,\n\n // A command line to prefix program execution with,\n // for running under valgrind\n runtool: Option<~str>,\n\n // Flags to pass to the compiler\n rustcflags: Option<~str>,\n\n // Explain what's going on\n verbose: bool};\n" }, { "from": "gpt", "value": "import option;\n\nenum mode { mode_compile_fail, mode_run_fail, mode_run_pass, mode_pretty, }\n\nimpl mode : cmp::Eq {\n pure fn eq(&&other: mode) -> bool {\n other as int == self as int\n }\n}\n\ntype config = {\n // The library paths required for running the compiler\n compile_lib_path: ~str,\n\n // The library paths required for running compiled programs\n run_lib_path: ~str,\n\n // The rustc executable\n rustc_path: Path,\n\n // The directory containing the tests to run\n src_base: Path,\n\n // The directory where programs should be built\n build_base: Path,\n\n // Directory for auxiliary libraries\n aux_base: Path,\n\n // The name of the stage being built (stage1, etc)\n stage_id: ~str,\n\n // The test mode, compile-fail, run-fail, run-pass\n mode: mode,\n\n // Run ignored tests\n run_ignored: bool,\n\n // Only run tests that match this filter\n filter: Option<~str>,\n\n // Write out a parseable log of tests that were run\n logfile: Option<Path>,\n\n // A command line to prefix program execution with,\n // for running under valgrind\n runtool: Option<~str>,\n\n // Flags to pass to the compiler\n rustcflags: Option<~str>,\n\n // Explain what's going on\n verbose: bool};\n" } ]
rust
chosen
[ { "from": "system", "value": "Update for removal of std::error::FromError\n" }, { "from": "human", "value": "#![feature(plugin, str_char, slice_patterns, convert, core)]\n#![plugin(regex_macros)]\nextern crate regex;\nextern crate chrono;\n#[macro_use]\nextern crate log as l;\n\npub mod log;\npub mod format;\n\nuse std::error::FromError;\nuse std::{ io, result };\n\nuse chrono::format::ParseError;\n\npub type Result<T> = result::Result<T, IlcError>;\n\n#[derive(Debug, PartialEq)]\npub enum IlcError {\n Parse(String),\n Chrono(ParseError),\n Io(io::Error)\n}\n\nimpl FromError<ParseError> for IlcError {\n fn from_error(err: ParseError) -> IlcError { IlcError::Chrono(err) }\n}\n\nimpl FromError<io::Error> for IlcError {\n fn from_error(err: io::Error) -> IlcError { IlcError::Io(err) }\n}\n" }, { "from": "gpt", "value": "#![feature(plugin, slice_patterns, core)]\n#![plugin(regex_macros)]\nextern crate regex;\nextern crate chrono;\n#[macro_use]\nextern crate log as l;\n\npub mod log;\npub mod format;\n\nuse std::convert::From;\nuse std::{ io, result };\n\nuse chrono::format::ParseError;\n\npub type Result<T> = result::Result<T, IlcError>;\n\n#[derive(Debug)]\npub enum IlcError {\n Parse(String),\n Chrono(ParseError),\n Io(io::Error)\n}\n\nimpl From<ParseError> for IlcError {\n fn from(err: ParseError) -> IlcError { IlcError::Chrono(err) }\n}\n\nimpl From<io::Error> for IlcError {\n fn from(err: io::Error) -> IlcError { IlcError::Io(err) }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add test for filling tensor! macro\n" }, { "from": "human", "value": "use numeric::Tensor;\n\n#[test]\nfn tensor_1d() {\n let x = Tensor::new(vec![1, 2, 3, 4, 5, 6]);\n assert!(x == tensor![1, 2, 3, 4, 5, 6]);\n assert!(x == tensor![1, 2, 3, 4, 5, 6,]);\n}\n\n#[test]\nfn tensor_2d() {\n let x = Tensor::new(vec![1, 2, 3, 4, 5, 6]).reshape(&[3, 2]);\n assert!(x == tensor![1, 2; 3, 4; 5, 6]);\n assert!(x == tensor![1, 2; 3, 4; 5, 6;]);\n}\n" }, { "from": "gpt", "value": "use numeric::Tensor;\n\n#[test]\nfn tensor_1d() {\n let x = Tensor::new(vec![1, 2, 3, 4, 5, 6]);\n assert!(x == tensor![1, 2, 3, 4, 5, 6]);\n assert!(x == tensor![1, 2, 3, 4, 5, 6,]);\n}\n\n#[test]\nfn tensor_2d() {\n let x = Tensor::new(vec![1, 2, 3, 4, 5, 6]).reshape(&[3, 2]);\n assert!(x == tensor![1, 2; 3, 4; 5, 6]);\n assert!(x == tensor![1, 2; 3, 4; 5, 6;]);\n}\n\n#[test]\nfn tensor_filled_1d() {\n let x = Tensor::new(vec![3, 3, 3, 3, 3]);\n assert!(x == tensor![3; 5]);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use iterator, not indices, in mods_to_lua\n\nMore likely to be optimized by the compiler\n" }, { "from": "human", "value": "//! Utilities to talk to Lua\n\nuse rlua::{self, Table};\nuse rustwlc::*;\n\nconst MOD_NAMES: [&str; 8] = [\"Shift\", \"Caps\", \"Control\", \"Alt\",\n \"Mod2\", \"Mod3\", \"Mod4\", \"Mod5\"];\n\n/// Convert a modifier to the Lua interpretation\npub fn mods_to_lua(lua: &rlua::Lua, mut mods: KeyMod) -> rlua::Result<Table> {\n let mut mods_list: Vec<String> = Vec::with_capacity(MOD_NAMES.len());\n for index in 0..MOD_NAMES.len() {\n if mods == MOD_NONE {\n break;\n }\n if mods.bits() & 1 != 0 {\n mods_list.push(MOD_NAMES[index].into());\n }\n mods = KeyMod::from_bits_truncate(mods.bits() >> 1);\n }\n lua.create_table_from(mods_list.into_iter().enumerate())\n}\n" }, { "from": "gpt", "value": "//! Utilities to talk to Lua\n\nuse rlua::{self, Table};\nuse rustwlc::*;\n\nconst MOD_NAMES: [&str; 8] = [\"Shift\", \"Caps\", \"Control\", \"Alt\",\n \"Mod2\", \"Mod3\", \"Mod4\", \"Mod5\"];\n\n/// Convert a modifier to the Lua interpretation\npub fn mods_to_lua(lua: &rlua::Lua, mut mods: KeyMod) -> rlua::Result<Table> {\n let mut mods_list: Vec<String> = Vec::with_capacity(MOD_NAMES.len());\n for mod_name in &MOD_NAMES {\n if mods == MOD_NONE {\n break;\n }\n if mods.bits() & 1 != 0 {\n mods_list.push((*mod_name).into());\n }\n mods = KeyMod::from_bits_truncate(mods.bits() >> 1);\n }\n lua.create_table_from(mods_list.into_iter().enumerate())\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add basic loop to `Harness`.\n" }, { "from": "human", "value": "use event::Reactor;\nuse render::{Context, GlutinContext, MetaContext};\n\npub struct Harness<A, C>\n where A: Application,\n C: MetaContext\n{\n application: A,\n context: Context<C>,\n}\n\nimpl<A> Harness<A, GlutinContext>\n where A: Application\n{\n pub fn with_glutin_context(application: A) -> Self {\n panic!()\n }\n}\n\npub trait Application {\n fn reactors(&mut self) -> &mut [&mut Reactor];\n}\n" }, { "from": "gpt", "value": "use glutin::Window;\n\nuse event::{Event, PollEvents, Reactor};\nuse render::{Context, GlutinContext, MetaContext};\n\npub struct Harness<A, C>\n where A: Application<C>,\n C: MetaContext\n{\n application: A,\n context: Context<C>,\n}\n\nimpl<A> Harness<A, GlutinContext>\n where A: Application<GlutinContext>\n{\n pub fn from_glutin_window(application: A, window: Window) -> Self {\n Harness {\n application: application,\n context: Context::from_glutin_window(window),\n }\n }\n}\n\nimpl<A, C> Harness<A, C>\n where A: Application<C>,\n C: MetaContext\n{\n pub fn start(&mut self) {\n 'main: loop {\n for event in self.context.window.poll_events() {\n match event {\n Event::Closed => {\n break 'main;\n }\n _ => {}\n }\n self.application.react(&event);\n }\n self.context.clear();\n self.application.render(&mut self.context);\n self.context.flush().unwrap();\n }\n }\n}\n\npub trait Application<C>: Reactor\n where C: MetaContext\n{\n fn render(&mut self, context: &mut Context<C>);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add function to get closest word for specified word in words array\n" }, { "from": "human", "value": "pub mod sequencematcher;\npub mod differ;\nmod utils;" }, { "from": "gpt", "value": "pub mod sequencematcher;\npub mod differ;\nmod utils;\n\n\nuse sequencematcher::SequenceMatcher;\n\n\npub fn get_close_matches<'a>(word: &str, possibilities: Vec<&'a str>, n: usize, cutoff: f32) -> Vec<&'a str> {\n\tif !(0.0 <= cutoff && cutoff <= 1.0) {\n\t\t//error\n\t}\n\tlet mut res: Vec<(f32, &str)> = Vec::new();\n\tlet mut matcher = SequenceMatcher::new(\"\", word);\n\tfor i in &possibilities {\n\t\tmatcher.set_first_seq(i);\n\t\tlet ratio = matcher.ratio();\n\t\tif ratio >= cutoff {\n\t\t\tres.push((ratio, i));\n\t\t}\n\t}\n\tres.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap());\n\tres.truncate(n);\n\tres.iter().map(|x| x.1).collect()\n}" } ]
rust
chosen
[ { "from": "system", "value": "Mark the crate as experimental.\n" }, { "from": "human", "value": "#![crate_name = \"quickcheck\"]\n#![crate_type = \"lib\"]\n#![license = \"UNLICENSE\"]\n#![doc(html_root_url = \"http://burntsushi.net/rustdoc/quickcheck\")]\n\n//! This crate is a port of\n//! [Haskell's QuickCheck](http://hackage.haskell.org/package/QuickCheck).\n//!\n//! For detailed examples, please see the\n//! [README](https://github.com/BurntSushi/quickcheck).\n\n#![feature(macro_rules, phase)]\n\nextern crate collections;\n#[phase(plugin, link)] extern crate log;\n\npub use arbitrary::{\n Arbitrary, Gen, StdGen, Shrinker,\n empty_shrinker, single_shrinker,\n};\npub use tester::{QuickCheck, Testable, TestResult, quickcheck};\n\nmod arbitrary;\nmod tester;\n\n#[cfg(test)]\nmod tests;\n" }, { "from": "gpt", "value": "#![crate_name = \"quickcheck\"]\n#![crate_type = \"lib\"]\n#![license = \"UNLICENSE\"]\n#![doc(html_root_url = \"http://burntsushi.net/rustdoc/quickcheck\")]\n#![experimental]\n\n//! This crate is a port of\n//! [Haskell's QuickCheck](http://hackage.haskell.org/package/QuickCheck).\n//!\n//! For detailed examples, please see the\n//! [README](https://github.com/BurntSushi/quickcheck).\n\n#![feature(macro_rules, phase)]\n\nextern crate collections;\n#[phase(plugin, link)] extern crate log;\n\npub use arbitrary::{\n Arbitrary, Gen, StdGen, Shrinker,\n empty_shrinker, single_shrinker,\n};\npub use tester::{QuickCheck, Testable, TestResult, quickcheck};\n\nmod arbitrary;\nmod tester;\n\n#[cfg(test)]\nmod tests;\n" } ]
rust
chosen
[ { "from": "system", "value": "Add (But not yet implement) the Minecraft protocol version declaration\n" }, { "from": "human", "value": "//! Entry module for the Netherrack project\n\n// We'll be using serialization a lot\nextern crate rustc_serialize;\n\n// Enable logging and use of logging macros throughout Netherrack\n#[macro_use]\nextern crate log;\n\n// Allow use of Semantic Versioning througout Netherrack\nextern crate semver;\n// Also allow usage of Version through Netherrack\npub use semver::Version;\n\n// Allow use of the core module\npub mod core;\n\n// Allow access to I/O operations\npub mod io;\n\n// Allow access to the universe\npub mod universe;\n\n// Okay, this is the start of Netherrack's functions\n\n/// The version of Netherrack as determined at compile time\npub const NETHERRACK_VERSION_STRING: &'static str = env!(\"CARGO_PKG_VERSION\");\n\n/// Gets the current version of Netherrack\npub fn get_version() -> Version {\n Version::parse(NETHERRACK_VERSION_STRING).unwrap()\n}\n\n/// Starts a new Netherrack server instance\npub fn start_server() {\n \n info!(\"Netherrack startup called\");\n \n trace!(\"Starting network in a new thread\");\n \n std::thread::spawn(move || {\n io::network::start_network();\n });\n \n debug!(\"Networking should be set up\");\n \n loop {\n //TODO: In the future, execute a tick. Use Duration's span function to get time taken, sleep the remainder, and go again\n std::thread::sleep_ms(20);\n }\n \n}" }, { "from": "gpt", "value": "//! Entry module for the Netherrack project\n\n// We'll be using serialization a lot\nextern crate rustc_serialize;\n\n// Enable logging and use of logging macros throughout Netherrack\n#[macro_use]\nextern crate log;\n\n// Allow use of Semantic Versioning througout Netherrack\nextern crate semver;\n// Also allow usage of Version through Netherrack\npub use semver::Version;\n\n// Allow use of the core module\npub mod core;\n\n// Allow access to I/O operations\npub mod io;\n\n// Allow access to the universe\npub mod universe;\n\n// Okay, this is the start of Netherrack's functions\n\n/// The version of the Minecraft protocol accepted by Netherrack\npub const MINECRAFT_PROTOCOL_VERSION: u32 = 47;\n\n/// The version of Netherrack as determined at compile time\npub const NETHERRACK_VERSION_STRING: &'static str = env!(\"CARGO_PKG_VERSION\");\n\n/// Gets the current version of Netherrack\npub fn get_version() -> Version {\n Version::parse(NETHERRACK_VERSION_STRING).unwrap()\n}\n\n/// Starts a new Netherrack server instance\npub fn start_server() {\n \n info!(\"Netherrack startup called\");\n \n trace!(\"Starting network in a new thread\");\n \n std::thread::spawn(move || {\n io::network::start_network();\n });\n \n debug!(\"Networking should be set up\");\n \n loop {\n //TODO: In the future, execute a tick. Use Duration's span function to get time taken, sleep the remainder, and go again\n std::thread::sleep_ms(20);\n }\n \n}" } ]
rust
chosen
[ { "from": "system", "value": "Disable ui tests on emscripten\n\nThese hit a strange error in our Emscripten builder in Travis as well as\nlocally through cargo web:\n\n ERROR: failed to execute cargo: Resource temporarily unavailable (os error 11)\n" }, { "from": "human", "value": "#[rustc::attr(not(nightly), ignore)]\n#[test]\nfn ui() {\n let t = trybuild::TestCases::new();\n t.compile_fail(\"tests/ui/**/*.rs\");\n}\n" }, { "from": "gpt", "value": "#[cfg(not(target_os = \"emscripten\"))]\n#[rustc::attr(not(nightly), ignore)]\n#[test]\nfn ui() {\n let t = trybuild::TestCases::new();\n t.compile_fail(\"tests/ui/**/*.rs\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix sample `clone_dyn_trivial_sample`, add condition\n" }, { "from": "human", "value": "#[ allow( unused_imports ) ]\nuse clone_dyn::clone_dyn;\n\nfn main()\n{\n\n #[ clone_dyn ]\n trait Trait1\n {\n }\n\n let vec = Vec::< Box< dyn Trait1 > >::new();\n let _vec2 = vec.clone(); /* <- it does not work without `clone_dyn` */\n\n}\n" }, { "from": "gpt", "value": "#[ allow( unused_imports ) ]\nuse clone_dyn::clone_dyn;\n\nfn main()\n{\n\n #[ cfg( any( feature = \"use_std\", feature = \"use_alloc\" ) ) ]\n {\n #[ clone_dyn ]\n trait Trait1\n {\n }\n\n let vec = Vec::< Box< dyn Trait1 > >::new();\n let _vec2 = vec.clone(); /* <- it does not work without `clone_dyn` */\n }\n\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove reexport subframe module items\n" }, { "from": "human", "value": "//! An implementation of [FLAC](https://xiph.org/flac), free lossless audio\n//! codec, written in Rust.\n//!\n//! # Examples\n//!\n//! Basic decoding from a file.\n//!\n//! ```\n//! match flac::Stream::from_file(\"path/to/file.flac\") {\n//! Ok(mut stream) => {\n//! // Copy of `StreamInfo` to help convert to a different audio format.\n//! let info = stream.info();\n//!\n//! for sample in stream.iter() {\n//! // Iterate over each decoded sample\n//! }\n//! }\n//! Err(error) => println!(\"{}\", error),\n//! }\n//! ```\n\n#[macro_use]\nextern crate nom;\n\n#[macro_use]\nmod utility;\npub mod metadata;\nmod frame;\nmod subframe;\npub mod stream;\n\npub use metadata::{metadata_parser, Metadata};\npub use subframe::{subframe_parser, Subframe};\npub use stream::{stream_parser, Stream};\n" }, { "from": "gpt", "value": "//! An implementation of [FLAC](https://xiph.org/flac), free lossless audio\n//! codec, written in Rust.\n//!\n//! # Examples\n//!\n//! Basic decoding from a file.\n//!\n//! ```\n//! match flac::Stream::from_file(\"path/to/file.flac\") {\n//! Ok(mut stream) => {\n//! // Copy of `StreamInfo` to help convert to a different audio format.\n//! let info = stream.info();\n//!\n//! for sample in stream.iter() {\n//! // Iterate over each decoded sample\n//! }\n//! }\n//! Err(error) => println!(\"{}\", error),\n//! }\n//! ```\n\n#[macro_use]\nextern crate nom;\n\n#[macro_use]\nmod utility;\npub mod metadata;\nmod frame;\nmod subframe;\npub mod stream;\n\npub use metadata::{metadata_parser, Metadata};\npub use stream::{stream_parser, Stream};\n" } ]
rust
chosen
[ { "from": "system", "value": "Make the error module public\n" }, { "from": "human", "value": "//! A simple library for reading and writing Riegl .sdc files.\n//!\n//! .sdc files are simple binary tables of discrete-return LiDAR data.\n\nextern crate byteorder;\n\nmod error;\npub mod file;\npub mod point;\nmod result;\n\npub use file::File;\n" }, { "from": "gpt", "value": "//! A simple library for reading and writing Riegl .sdc files.\n//!\n//! .sdc files are simple binary tables of discrete-return LiDAR data.\n\nextern crate byteorder;\n\npub mod error;\npub mod file;\npub mod point;\nmod result;\n\npub use file::File;\n" } ]
rust
chosen
[ { "from": "system", "value": "Include C++ dependencies in license metadata\n" }, { "from": "human", "value": "//! Detect the language of a string using the [cld2 library][cld2] from the\n//! Chromium project.\n//!\n//! ```\n//! use cld2::{detect_language, Format, Reliable, Lang};\n//!\n//! let text = \"It is an ancient Mariner,\n//! And he stoppeth one of three.\n//! 'By thy long grey beard and glittering eye,\n//! Now wherefore stopp'st thou me?\";\n//!\n//! assert_eq!((Some(Lang(\"en\")), Reliable),\n//! detect_language(text, Format::Text));\n//! ```\n//!\n//! This library wraps the `cld2-sys` library, which provides a raw\n//! interface to cld2. The only major feature which isn't yet wrapped is\n//! the `ResultChunk` interface, because it tends to give fairly imprecise\n//! answers&mdash;it wouldn't make a very good multi-lingual spellchecker\n//! component, for example. As always, pull requests are eagerly welcome!\n//!\n//! For more information, see the [GitHub project][github] for this\n//! library.\n//!\n//! [cld2]: https://code.google.com/p/cld2/\n//! [github]: https://github.com/emk/rust-cld2\n\n#![license = \"Public domain (Unlicense)\"]\n#![unstable]\n#![deny(missing_docs)]\n#![feature(globs)]\n\nextern crate libc;\nextern crate \"cld2-sys\" as ffi;\n\npub use types::*;\npub use detection::*;\n\nmod types;\nmod language;\nmod detection;\n" }, { "from": "gpt", "value": "//! Detect the language of a string using the [cld2 library][cld2] from the\n//! Chromium project.\n//!\n//! ```\n//! use cld2::{detect_language, Format, Reliable, Lang};\n//!\n//! let text = \"It is an ancient Mariner,\n//! And he stoppeth one of three.\n//! 'By thy long grey beard and glittering eye,\n//! Now wherefore stopp'st thou me?\";\n//!\n//! assert_eq!((Some(Lang(\"en\")), Reliable),\n//! detect_language(text, Format::Text));\n//! ```\n//!\n//! This library wraps the `cld2-sys` library, which provides a raw\n//! interface to cld2. The only major feature which isn't yet wrapped is\n//! the `ResultChunk` interface, because it tends to give fairly imprecise\n//! answers&mdash;it wouldn't make a very good multi-lingual spellchecker\n//! component, for example. As always, pull requests are eagerly welcome!\n//!\n//! For more information, see the [GitHub project][github] for this\n//! library.\n//!\n//! [cld2]: https://code.google.com/p/cld2/\n//! [github]: https://github.com/emk/rust-cld2\n\n#![license = \"Public domain (Unlicense) + Apache License 2.0\"]\n#![unstable]\n#![deny(missing_docs)]\n#![feature(globs)]\n\nextern crate libc;\nextern crate \"cld2-sys\" as ffi;\n\npub use types::*;\npub use detection::*;\n\nmod types;\nmod language;\nmod detection;\n" } ]
rust
chosen
[ { "from": "system", "value": "Disable unstable warnings for now\n" }, { "from": "human", "value": "#![feature(slicing_syntax)]\n#![crate_type = \"lib\"]\n#![crate_name = \"suruga\"]\n#![allow(missing_copy_implementations)]\n\n#[macro_use]\nextern crate log;\n\npub use tls::Tls;\npub use client::TlsClient;\n\n#[macro_use]\npub mod macros;\npub mod util;\n\n// basic crypto primitives\npub mod crypto {\n pub mod sha2;\n pub mod p256;\n pub mod poly1305;\n pub mod chacha20;\n}\n\npub mod tls_result;\n#[macro_use]\npub mod tls_item;\npub mod record;\n\n// TLS AEAD cipehrsuites\npub mod cipher;\n\npub mod signature;\npub mod alert;\npub mod handshake;\n\npub mod tls;\npub mod client;\n\n#[cfg(test)] mod test;\n" }, { "from": "gpt", "value": "#![crate_type = \"lib\"]\n#![crate_name = \"suruga\"]\n\n#![allow(missing_copy_implementations)]\n\n#![feature(slicing_syntax)]\n#![allow(unstable)]\n\n#[macro_use]\nextern crate log;\n\npub use tls::Tls;\npub use client::TlsClient;\n\n#[macro_use]\npub mod macros;\npub mod util;\n\n// basic crypto primitives\npub mod crypto {\n pub mod sha2;\n pub mod p256;\n pub mod poly1305;\n pub mod chacha20;\n}\n\npub mod tls_result;\n#[macro_use]\npub mod tls_item;\npub mod record;\n\n// TLS AEAD cipehrsuites\npub mod cipher;\n\npub mod signature;\npub mod alert;\npub mod handshake;\n\npub mod tls;\npub mod client;\n\n#[cfg(test)] mod test;\n" } ]
rust
chosen
[ { "from": "system", "value": "Update the tests for Rust 1.0\n" }, { "from": "human", "value": "#![feature(plugin)]\n\n#![allow(unstable)] // TODO: remove this\n\n//! Making sure that no warning is generated by code from generate_gl_bindings!\n#![deny(warnings)]\n\nextern crate libc;\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/test_no_warnings.rs\"));\n" }, { "from": "gpt", "value": "//! Making sure that no warning is generated by code from generate_gl_bindings!\n#![deny(warnings)]\n\nextern crate libc;\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/test_no_warnings.rs\"));\n" } ]
rust
chosen
[ { "from": "system", "value": "refactor(build): Update clap usage for new crate requirements\n" }, { "from": "human", "value": "use clap::{FromArgMatches, IntoApp};\n\nuse casile::cli::{Cli, Subcommand};\nuse casile::config::CONF;\nuse casile::{make, setup, status};\nuse casile::{Result, VERSION};\n\nfn main() -> Result<()> {\n CONF.defaults()?;\n CONF.merge_env()?;\n CONF.merge_files()?;\n let app = Cli::into_app().version(VERSION);\n let matches = app.get_matches();\n let args = Cli::from_arg_matches(&matches);\n CONF.merge_args(&args)?;\n casile::show_welcome();\n let ret = match args.subcommand {\n Subcommand::Make { target } => make::run(target),\n Subcommand::Setup {} => setup::run(),\n Subcommand::Status {} => status::run(),\n };\n casile::show_outro();\n ret\n}\n" }, { "from": "gpt", "value": "use clap::{FromArgMatches, IntoApp};\n\nuse casile::cli::{Cli, Subcommand};\nuse casile::config::CONF;\nuse casile::{make, setup, status};\nuse casile::{Result, VERSION};\n\nfn main() -> Result<()> {\n CONF.defaults()?;\n CONF.merge_env()?;\n CONF.merge_files()?;\n let app = Cli::into_app().version(VERSION);\n let matches = app.get_matches();\n let args = Cli::from_arg_matches(&matches).expect(\"Unable to parse arguments\");\n CONF.merge_args(&args)?;\n casile::show_welcome();\n let ret = match args.subcommand {\n Subcommand::Make { target } => make::run(target),\n Subcommand::Setup {} => setup::run(),\n Subcommand::Status {} => status::run(),\n };\n casile::show_outro();\n ret\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Check agains `addr` field of source `msg`\n" }, { "from": "human", "value": "extern crate rosc;\n\nuse rosc::{encoder, decoder, errors};\nuse rosc::errors::OscError;\nuse rosc::types::{Result, OscMessage, OscPacket};\n\n#[test]\nfn test_encode_message_wo_args() {\n let msg = OscMessage {\n addr: \"/some/addr\".to_string(),\n args: None,\n };\n\n let enc_msg = encoder::encode_message(&msg).unwrap();\n match decoder::decode(&enc_msg).unwrap() {\n OscPacket::Message(dec_msg) => assert_eq!(\"/some/addr\", dec_msg.addr),\n _ => panic!(\"Expected OSC message!\")\n }\n}\n" }, { "from": "gpt", "value": "extern crate rosc;\n\nuse rosc::{encoder, decoder, errors};\nuse rosc::errors::OscError;\nuse rosc::types::{Result, OscMessage, OscPacket};\n\n#[test]\nfn test_encode_message_wo_args() {\n let msg = OscMessage {\n addr: \"/some/addr\".to_string(),\n args: None,\n };\n\n let enc_msg = encoder::encode_message(&msg).unwrap();\n match decoder::decode(&enc_msg).unwrap() {\n OscPacket::Message(dec_msg) => assert_eq!(msg.addr, dec_msg.addr),\n _ => panic!(\"Expected OSC message!\"),\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Change `_index` variable to something clearer\n" }, { "from": "human", "value": "use std::io::{self, Write};\nuse std::fs::File;\n\nuse flac::stream::StreamReader;\nuse flac::metadata::{self, Picture};\n\npub const USAGE: &'static str = \"\nUsage: metadata picture [options] <filename>\n metadata picture --help\n\nOptions:\n --export=FILE Export to file.\n --index=NUMBER Index of the current metadata type.\n -h, --help Show this message.\n\";\n\n#[derive(Debug, RustcDecodable)]\npub struct Arguments {\n arg_filename: String,\n flag_export: Option<String>,\n flag_index: Option<usize>,\n}\n\nfn export_picture(picture: &Picture, filename: &str) -> io::Result<()> {\n File::create(filename).and_then(|mut file| file.write_all(&picture.data))\n}\n\npub fn run(args: &Arguments) {\n let stream = StreamReader::<File>::from_file(&args.arg_filename)\n .expect(\"Couldn't parse file\");\n\n let mut index = 0;\n let _index = args.flag_index.unwrap_or(0);\n\n for meta in stream.metadata() {\n match meta.data {\n metadata::Data::Picture(ref p) => {\n if index != _index {\n index += 1;\n\n continue;\n }\n\n if let Some(ref filename) = args.flag_export {\n export_picture(p, filename).expect(\"couldn't write to file\");\n\n break;\n }\n }\n _ => continue,\n }\n }\n}\n" }, { "from": "gpt", "value": "use std::io::{self, Write};\nuse std::fs::File;\n\nuse flac::stream::StreamReader;\nuse flac::metadata::{self, Picture};\n\npub const USAGE: &'static str = \"\nUsage: metadata picture [options] <filename>\n metadata picture --help\n\nOptions:\n --export=FILE Export to file.\n --index=NUMBER Index of the current metadata type.\n -h, --help Show this message.\n\";\n\n#[derive(Debug, RustcDecodable)]\npub struct Arguments {\n arg_filename: String,\n flag_export: Option<String>,\n flag_index: Option<usize>,\n}\n\nfn export_picture(picture: &Picture, filename: &str) -> io::Result<()> {\n File::create(filename).and_then(|mut file| file.write_all(&picture.data))\n}\n\npub fn run(args: &Arguments) {\n let stream = StreamReader::<File>::from_file(&args.arg_filename)\n .expect(\"Couldn't parse file\");\n\n let mut index = 0;\n let end_index = args.flag_index.unwrap_or(0);\n\n for meta in stream.metadata() {\n match meta.data {\n metadata::Data::Picture(ref p) => {\n if index != end_index {\n index += 1;\n\n continue;\n }\n\n if let Some(ref filename) = args.flag_export {\n export_picture(p, filename).expect(\"couldn't write to file\");\n\n break;\n }\n }\n _ => continue,\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add features for when testing\n" }, { "from": "human", "value": "#![crate_name = \"rboy\"]\n#![crate_type = \"lib\" ]\n\n#![feature(io, core, path)]\n\n#[macro_use]\nextern crate log;\n\nextern crate time;\n\n#[cfg(test)]\nextern crate test;\n\npub use keypad::KeypadKey;\n\npub mod device;\n\nmod cpu;\nmod gbmode;\nmod gpu;\nmod keypad;\nmod mbc;\nmod mmu;\nmod register;\nmod serial;\nmod sound;\nmod timer;\nmod util;\n" }, { "from": "gpt", "value": "#![crate_name = \"rboy\"]\n#![crate_type = \"lib\" ]\n\n#![feature(io, core, path)]\n#![cfg_attr(test, feature(test, std_misc))]\n\n#[macro_use]\nextern crate log;\n\nextern crate time;\n\n#[cfg(test)]\nextern crate test;\n\npub use keypad::KeypadKey;\n\npub mod device;\n\nmod cpu;\nmod gbmode;\nmod gpu;\nmod keypad;\nmod mbc;\nmod mmu;\nmod register;\nmod serial;\nmod sound;\nmod timer;\nmod util;\n" } ]
rust
chosen
[ { "from": "system", "value": "Reformat and rename method testing tests for better organization\n" }, { "from": "human", "value": "#[macro_use]\nextern crate askama;\n\nuse askama::Template;\n\n#[derive(Template)]\n#[template(source = \"{{ self.get_s() }}\", ext = \"txt\")]\nstruct MethodTemplate<'a> {\n s: &'a str,\n}\n\nimpl<'a> MethodTemplate<'a> {\n fn get_s(&self) -> &str {\n self.s\n }\n}\n\n#[derive(Template)]\n#[template(source = \"{{ self.get_s() }} {{ t.get_s() }}\", ext = \"txt\")]\nstruct NestedMethodTemplate<'a> {\n t: MethodTemplate<'a>,\n}\n\nimpl<'a> NestedMethodTemplate<'a> {\n fn get_s(&self) -> &str {\n \"bar\"\n }\n}\n\n#[test]\nfn test_method() {\n let t = MethodTemplate { s: \"foo\" };\n assert_eq!(t.render().unwrap(), \"foo\");\n}\n\n#[test]\nfn test_nested() {\n let t = NestedMethodTemplate {\n t: MethodTemplate { s: \"foo\" },\n };\n assert_eq!(t.render().unwrap(), \"bar foo\");\n}\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate askama;\n\nuse askama::Template;\n\n#[derive(Template)]\n#[template(source = \"{{ self.get_s() }}\", ext = \"txt\")]\nstruct SelfMethodTemplate<'a> {\n s: &'a str,\n}\n\nimpl<'a> SelfMethodTemplate<'a> {\n fn get_s(&self) -> &str {\n self.s\n }\n}\n\n#[test]\nfn test_self_method() {\n let t = SelfMethodTemplate { s: \"foo\" };\n assert_eq!(t.render().unwrap(), \"foo\");\n}\n\n\n#[derive(Template)]\n#[template(source = \"{{ self.get_s() }} {{ t.get_s() }}\", ext = \"txt\")]\nstruct NestedSelfMethodTemplate<'a> {\n t: SelfMethodTemplate<'a>,\n}\n\nimpl<'a> NestedSelfMethodTemplate<'a> {\n fn get_s(&self) -> &str {\n \"bar\"\n }\n}\n\n#[test]\nfn test_nested() {\n let t = NestedSelfMethodTemplate {\n t: SelfMethodTemplate { s: \"foo\" },\n };\n assert_eq!(t.render().unwrap(), \"bar foo\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use `allow_internal_unstable` in rustc itself\n" }, { "from": "human", "value": "/// A simple static assertion macro. The first argument should be a unique\n/// ALL_CAPS identifier that describes the condition.\n#[macro_export]\n#[allow_internal_unstable]\nmacro_rules! static_assert {\n ($name:ident: $test:expr) => {\n // Use the bool to access an array such that if the bool is false, the access\n // is out-of-bounds.\n #[allow(dead_code)]\n static $name: () = [()][!($test: bool) as usize];\n }\n}\n" }, { "from": "gpt", "value": "/// A simple static assertion macro. The first argument should be a unique\n/// ALL_CAPS identifier that describes the condition.\n#[macro_export]\n#[cfg_attr(stage0, allow_internal_unstable)]\n#[cfg_attr(not(stage0), allow_internal_unstable(type_ascription))]\nmacro_rules! static_assert {\n ($name:ident: $test:expr) => {\n // Use the bool to access an array such that if the bool is false, the access\n // is out-of-bounds.\n #[allow(dead_code)]\n static $name: () = [()][!($test: bool) as usize];\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix shift-overflow in very old run-pass test.\n" }, { "from": "human", "value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// Regression test for issue #152.\npub fn main() {\n let mut b: uint = 1_usize;\n while b <= 32_usize {\n 0_usize << b;\n b <<= 1_usize;\n println!(\"{}\", b);\n }\n}\n" }, { "from": "gpt", "value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// Regression test for issue #152.\npub fn main() {\n let mut b: uint = 1_usize;\n while b < std::mem::size_of::<usize>() {\n 0_usize << b;\n b <<= 1_usize;\n println!(\"{}\", b);\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove dead argument code for replacement\n" }, { "from": "human", "value": "use getopts::Options;\nuse std::env::Args;\n\npub struct Arguments {\n pub program_name: String,\n pub exit: bool,\n}\n\nfn print_usage(program: &str, opts: Options) {\n let brief = format!(\"Usage: {} [options]\", program);\n print!(\"{}\", opts.usage(&*brief));\n}\n\npub fn parse_args(arguments: Args) -> Arguments {\n let mut opts = Options::new();\n opts.optflag(\"h\", \"help\", \"print this help menu\");\n\n let matches = match opts.parse(arguments) {\n Ok(m) => { m }\n Err(f) => { panic!(f.to_string()) }\n };\n\n let mut args = Arguments {\n program_name: \"\".to_string(),\n exit: matches.opt_present(\"h\"),\n };\n\n if args.exit {\n print_usage(&*args.program_name, opts);\n }\n\n args.entries = match matches.opt_str(\"n\") {\n Some(s) => match (&*s).parse() {\n Ok(x) => Some(x),\n Err(_) => None,\n },\n None => None,\n };\n\n args.filename = matches.opt_str(\"o\");\n\n args.port = match matches.opt_str(\"s\") {\n Some(s) => match (&*s).parse() {\n Ok(x) => Some(x),\n Err(_) => None,\n },\n None => None,\n };\n\n args\n}\n\n" }, { "from": "gpt", "value": "use getopts::Options;\nuse std::env::Args;\n\npub struct Arguments {\n pub program_name: String,\n pub exit: bool,\n}\n\nfn print_usage(program: &str, opts: Options) {\n let brief = format!(\"Usage: {} [options]\", program);\n print!(\"{}\", opts.usage(&*brief));\n}\n\npub fn parse_args(arguments: Args) -> Arguments {\n let mut opts = Options::new();\n opts.optflag(\"h\", \"help\", \"print this help menu\");\n\n let matches = match opts.parse(arguments) {\n Ok(m) => { m }\n Err(f) => { panic!(f.to_string()) }\n };\n\n let mut args = Arguments {\n program_name: \"\".to_string(),\n exit: matches.opt_present(\"h\"),\n };\n\n if args.exit {\n print_usage(&*args.program_name, opts);\n }\n\n args\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove deprecated mpv option usage.\n" }, { "from": "human", "value": "extern crate gtk;\n\nuse gtk::prelude::*;\n\nuse std::error::Error;\nuse std::io::prelude::*;\nuse std::fs::File;\nuse std::path::Path;\nuse std::env;\n\nfn main() {\n gtk::init().expect(\"Failed to initialize GTK.\");\n\n let window = gtk::Window::new(gtk::WindowType::Toplevel);\n\n window.set_title(\"mpv-rice\");\n window.set_border_width(10);\n // window.set_window_position(gtk::WindowPosition::Center);\n window.set_default_size(350, 70);\n\n window.connect_delete_event(|_, _| {\n gtk::main_quit();\n Inhibit(true)\n });\n\n let button = gtk::Button::new_with_label(\"Write config\");\n button.connect_clicked(move |_| {\n let args: Vec<String> = env::args().collect();\n let path = Path::new(&args[1]);\n let display = path.display();\n\n let mut file = match File::create(&path) {\n Err(why) => panic!(\"couldn't create {}: {}\",\n display,\n Error::description(&why)),\n Ok(file) => file,\n };\n let _ = file.write_all(b\"# generated by mpv-rice\\n\");\n let _ = file.write_all(b\"vo=opengl-hq\\n\");\n });\n window.add(&button);\n\n window.show_all();\n gtk::main();\n}\n" }, { "from": "gpt", "value": "extern crate gtk;\n\nuse gtk::prelude::*;\n\nuse std::error::Error;\nuse std::io::prelude::*;\nuse std::fs::File;\nuse std::path::Path;\nuse std::env;\n\nfn main() {\n gtk::init().expect(\"Failed to initialize GTK.\");\n\n let window = gtk::Window::new(gtk::WindowType::Toplevel);\n\n window.set_title(\"mpv-rice\");\n window.set_border_width(10);\n // window.set_window_position(gtk::WindowPosition::Center);\n window.set_default_size(350, 70);\n\n window.connect_delete_event(|_, _| {\n gtk::main_quit();\n Inhibit(true)\n });\n\n let button = gtk::Button::new_with_label(\"Write config\");\n button.connect_clicked(move |_| {\n let args: Vec<String> = env::args().collect();\n let path = Path::new(&args[1]);\n let display = path.display();\n\n let mut file = match File::create(&path) {\n Err(why) => panic!(\"couldn't create {}: {}\",\n display,\n Error::description(&why)),\n Ok(file) => file,\n };\n let _ = file.write_all(b\"# generated by mpv-rice\\n\");\n let _ = file.write_all(b\"profile=opengl-hq\\n\");\n });\n window.add(&button);\n\n window.show_all();\n gtk::main();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add support for a few base types\n\n- small_integer\n- integer\n- atom\n" }, { "from": "human", "value": "#[macro_use]\nextern crate nom;\n\nuse std::io;\nuse std::io::Read;\n\nstatic BERT_MAGIC_NUMBER: u8 = 131;\n\n#[derive(Debug)]\nenum BertTerm {\n Int(i32),\n Float(f64),\n Atom(String),\n Tuple(Vec<BertTerm>),\n List(Vec<BertTerm>),\n Binary(Vec<u8>)\n}\n\n#[derive(Debug)]\nenum BertError {\n InvalidMagicNumber\n}\n\nfn main() {\n}\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate nom;\n\nuse std::io;\nuse std::io::Read;\n\nuse nom::{IResult, ErrorKind};\n\n\nstatic BERT_MAGIC_NUMBER: u8 = 131;\n\nstatic SMALL_INTEGER_EXT: u8 = 97;\nstatic INTEGER_EXT: u8 = 98;\nstatic ATOM_EXT: u8 = 100;\n\n#[derive(Debug)]\nenum BertTerm {\n Int(i32),\n Float(f64),\n Atom(String),\n Tuple(Vec<BertTerm>),\n List(Vec<BertTerm>),\n Binary(Vec<u8>)\n}\n\n#[derive(Debug)]\nenum BertError {\n Unknown,\n InvalidMagicNumber\n}\n\nnamed!(bert_magic_number, tag!([BERT_MAGIC_NUMBER]));\n\nfn small_integer(i0: &[u8]) -> IResult<&[u8], BertTerm> {\n let (i1, _) = try_parse!(i0, tag!([SMALL_INTEGER_EXT]));\n let (i2, n) = try_parse!(i1, nom::be_u8);\n IResult::Done(i2, BertTerm::Int(n as i32))\n}\n\n\nfn integer(i0: &[u8]) -> IResult<&[u8], BertTerm> {\n let (i1, _) = try_parse!(i0, tag!([INTEGER_EXT]));\n let (i2, n) = try_parse!(i1, nom::be_i32);\n IResult::Done(i2, BertTerm::Int(n))\n}\n\nfn atom(i0: &[u8]) -> IResult<&[u8], BertTerm> {\n let (i1, _) = try_parse!(i0, tag!([ATOM_EXT]));\n let (i2, len) = try_parse!(i1, nom::be_u16);\n let (i3, atom_name) = try_parse!(i2, take_str!(len));\n IResult::Done(i3, BertTerm::Atom(atom_name.to_string()))\n}\n\nnamed!(parse_bert<&[u8], BertTerm>, chain!(\n bert_magic_number ~\n t: alt!(small_integer | integer | atom)\n ,\n || { t }\n));\n\nfn main() {\n let mut stdin = io::stdin();\n let mut buf: Vec<u8> = Vec::new();\n\n stdin.read_to_end(&mut buf);\n println!(\"{:?}\", parse_bert(&buf[..]));\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add proper error handling on wrong numbers\n" }, { "from": "human", "value": "extern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n println!(\"Hello to the guessing game!\");\n\n\n let std_in = io::stdin();\n\n let number_to_guess = rand::thread_rng().gen_range(1, 101);\n\n loop {\n println!(\"Please enter a number: \");\n let mut guess = String::new();\n std_in.read_line(&mut guess).expect(\"Failed to read line.\");\n let guess: u32 = guess.trim().parse().expect(\"Please enter a number!\");\n\n match guess.cmp(&number_to_guess) {\n Ordering::Less => println!(\"Too small\"),\n Ordering::Equal => {\n println!(\"Correct!\");\n break;\n },\n Ordering::Greater => println!(\"Too big\"),\n }\n }\n}\n" }, { "from": "gpt", "value": "extern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n println!(\"Hello to the guessing game!\");\n\n\n let std_in = io::stdin();\n\n let number_to_guess = rand::thread_rng().gen_range(1, 101);\n\n loop {\n println!(\"Please enter a number: \");\n let mut guess = String::new();\n std_in.read_line(&mut guess).expect(\"Failed to read line.\");\n let guess: u32 = match guess.trim().parse() {\n Ok(num) => num,\n Err(_) => {\n println!(\"Please enter a valid number\");\n continue;\n }\n };\n\n match guess.cmp(&number_to_guess) {\n Ordering::Less => println!(\"Too small\"),\n Ordering::Equal => {\n println!(\"Correct!\");\n break;\n },\n Ordering::Greater => println!(\"Too big\"),\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add initial implementation of CLI\n" }, { "from": "human", "value": "fn main() {\n println!(\"Hello, world!\");\n}\n" }, { "from": "gpt", "value": "extern crate getopts;\n\nuse getopts::Options;\n\nuse std::env;\nuse std::fs::File;\nuse std::path::Path;\n\n\nfn print_usage(program: &str, opts: Options) {\n let usage = format!(\"Usage: {} [options] <filename>\", program);\n print!(\"{}\", opts.usage(&usage));\n}\n\nfn main() {\n let args: Vec<String> = env::args().collect();\n let program = args[0].clone();\n\n let mut opts = Options::new();\n opts.optflag(\"h\", \"help\", \"print this help menu\");\n opts.optflag(\"v\", \"version\", \"print version info\");\n\n let matches = match opts.parse(&args[1..]) {\n Ok(m) => m,\n Err(f) => panic!(f.to_string()),\n };\n\n if matches.opt_present(\"version\") {\n println!(\"ghoti {}\", env!(\"CARGO_PKG_VERSION\"));\n return;\n }\n\n if matches.opt_present(\"help\") || matches.free.is_empty() {\n print_usage(&program, opts);\n return;\n }\n\n let filename = matches.free[0].clone();\n\n match File::open(Path::new(&filename)) {\n Ok(_) => println!(\"Hello, {}!\", filename),\n Err(_) => panic!(\"Couldn't open {}.\", filename),\n };\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Print help message when given no arguments.\n" }, { "from": "human", "value": "extern crate clap;\n\nuse clap::{Arg, App};\nuse std::fs::File;\nuse std::io;\n\nfn main() {\n let matches = App::new(env!(\"CARGO_PKG_NAME\"))\n .version(env!(\"CARGO_PKG_VERSION\"))\n .author(\"Scott Olson <scott@solson.me>\")\n .about(env!(\"CARGO_PKG_DESCRIPTION\"))\n .arg(Arg::with_name(\"INPUT\")\n .multiple(true)\n .required(true)\n .help(\"The file(s) to display\"))\n .get_matches();\n\n let files: Vec<&str> = matches.values_of(\"INPUT\").unwrap().collect();\n\n let mut first = true;\n for &filename in &files {\n if first { first = false; } else { println!(\"\"); }\n\n if files.len() > 1 {\n println!(\"# {}\", filename);\n }\n\n io::copy(&mut File::open(filename).unwrap(), &mut io::stdout()).unwrap();\n }\n}\n" }, { "from": "gpt", "value": "extern crate clap;\n\nuse clap::{Arg, App};\nuse std::ffi::OsStr;\nuse std::fs::File;\nuse std::io;\n\nfn main() {\n let app = App::new(env!(\"CARGO_PKG_NAME\"))\n .version(env!(\"CARGO_PKG_VERSION\"))\n .author(\"Scott Olson <scott@solson.me>\")\n .about(env!(\"CARGO_PKG_DESCRIPTION\"))\n .arg(Arg::with_name(\"FILE\")\n .multiple(true)\n .required(true)\n .help(\"The file(s) to display\"));\n\n if std::env::args().len() == 1 {\n app.print_help().unwrap();\n println!(\"\");\n return;\n }\n\n let matches = app.get_matches();\n let files: Vec<&OsStr> = matches.values_of_os(\"FILE\").unwrap().collect();\n\n let mut first = true;\n for &filename in &files {\n if first { first = false; } else { println!(\"\"); }\n\n if files.len() > 1 {\n println!(\"# {}\", filename.to_string_lossy());\n }\n\n io::copy(&mut File::open(filename).unwrap(), &mut io::stdout()).unwrap();\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Exit when ctrl-d is entered\n\nhowever, empty lines (e.g. just newline) do not terminate\n" }, { "from": "human", "value": "use std::io;\nuse std::io::prelude::*;\nuse std::collections::HashMap;\npub mod parser;\n\nfn evaluate(input: &str, env: &mut HashMap<String, f64>) -> Result<f64, String> {\n let mut p = parser::Parser::new(input);\n let ast = try!(p.parse());\n match ast.eval(env) {\n Some(result) => Ok(result),\n None => Err(\"No value for that expression!\".to_string())\n }\n}\n\npub fn main() {\n use std::f64;\n let mut env = HashMap::new();\n env.insert(\"wow\".to_string(), 35.0f64);\n env.insert(\"pi\".to_string(), f64::consts::PI);\n\n let stdin = io::stdin();\n\n\n loop {\n print!(\">> \");\n io::stdout().flush().ok();\n\n let mut input = String::new();\n \n match stdin.read_line(&mut input) {\n Ok(_) => {\n let result = evaluate(&input.trim_right(), &mut env);\n match result {\n Ok(value) => {\n println!(\"=> {}\", value);\n }\n Err(s) => {\n println!(\"Error: {}\", s);\n }\n }\n io::stdout().flush().ok();\n }\n Err(_) => {\n println!(\"\");\n break;\n }\n }\n }\n}\n" }, { "from": "gpt", "value": "use std::io;\nuse std::io::prelude::*;\nuse std::collections::HashMap;\npub mod parser;\n\nfn evaluate(input: &str, env: &mut HashMap<String, f64>) -> Result<f64, String> {\n let mut p = parser::Parser::new(input);\n let ast = try!(p.parse());\n match ast.eval(env) {\n Some(result) => Ok(result),\n None => Err(\"No value for that expression!\".to_string())\n }\n}\n\npub fn main() {\n use std::f64;\n let mut env = HashMap::new();\n env.insert(\"wow\".to_string(), 35.0f64);\n env.insert(\"pi\".to_string(), f64::consts::PI);\n\n let stdin = io::stdin();\n\n\n loop {\n print!(\">> \");\n io::stdout().flush().ok();\n\n let mut input = String::new();\n \n match stdin.read_line(&mut input) {\n Ok(_) => {\n\n if input.len() == 0 {\n println!(\"\");\n return;\n }\n\n let expression_text = input.trim_right();\n\n let result = evaluate(expression_text, &mut env);\n match result {\n Ok(value) => {\n println!(\"=> {}\", value);\n }\n Err(s) => {\n println!(\"Error: {}\", s);\n }\n }\n io::stdout().flush().ok();\n }\n Err(_) => {\n println!(\"\");\n return;\n }\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add a TCP read timeout to network connection\n" }, { "from": "human", "value": "use std::io::{BufReader, Write};\nuse std::net::{TcpListener, TcpStream};\nuse std::thread;\n\nuse birch::network::NetworkConnection;\nuse birch::socket::IRCReader;\n\nfn main() {\n // Hardcoding things for now just to test everything out.\n let mut stream = TcpStream::connect(\"irc.freenode.net:6667\").unwrap();\n thread::spawn(move || {\n let mut reader = BufReader::new(stream.try_clone().unwrap());\n let mut net = NetworkConnection::new(\"ep`\", &mut stream);\n net.initialize().unwrap();\n\n loop {\n let msg = reader.read_message();\n if let Ok(msg) = msg {\n println!(\"[birch <- \\u{1b}[37;1mnet\\u{1b}[0m] {}\", msg);\n net.handle(&msg).expect(\"failed to handle message\");\n } else {\n println!(\"read failed\");\n break;\n }\n }\n });\n\n // TODO: hook this up\n let listener = TcpListener::bind(\"127.0.0.1:9123\").unwrap();\n println!(\"listening started, ready to accept\");\n\n for stream in listener.incoming() {\n thread::spawn(|| {\n let mut stream = stream.unwrap();\n stream.write_all(b\"Hello World\\r\\n\").unwrap();\n });\n }\n}\n" }, { "from": "gpt", "value": "use std::io::{BufReader, Write};\nuse std::net::{TcpListener, TcpStream};\nuse std::thread;\nuse std::time::Duration;\n\nuse birch::network::NetworkConnection;\nuse birch::socket::IRCReader;\n\nfn main() {\n // Hardcoding things for now just to test everything out.\n let mut stream = TcpStream::connect(\"irc.freenode.net:6667\").unwrap();\n stream\n .set_read_timeout(Some(Duration::from_secs(180)))\n .unwrap();\n\n thread::spawn(move || {\n let mut reader = BufReader::new(stream.try_clone().unwrap());\n let mut net = NetworkConnection::new(\"ep`\", &mut stream);\n net.initialize().unwrap();\n\n loop {\n let msg = reader.read_message();\n if let Ok(msg) = msg {\n println!(\"[birch <- \\u{1b}[37;1mnet\\u{1b}[0m] {}\", msg);\n net.handle(&msg).expect(\"failed to handle message\");\n } else {\n println!(\"read failed\");\n break;\n }\n }\n });\n\n // TODO: hook this up\n let listener = TcpListener::bind(\"127.0.0.1:9123\").unwrap();\n println!(\"listening started, ready to accept\");\n\n for stream in listener.incoming() {\n thread::spawn(|| {\n let mut stream = stream.unwrap();\n stream.write_all(b\"Hello World\\r\\n\").unwrap();\n });\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Reimplement IsInDiary for StoreId with StoreId::is_in_collection()\n" }, { "from": "human", "value": "use libimagstore::store::Entry;\nuse libimagstore::storeid::StoreId;\n\npub trait IsInDiary {\n\n fn is_in_diary(&self, name: &str) -> bool;\n\n}\n\nimpl IsInDiary for Entry {\n\n fn is_in_diary(&self, name: &str) -> bool {\n self.get_location().clone().is_in_diary(name)\n }\n\n}\n\nimpl IsInDiary for StoreId {\n\n fn is_in_diary(&self, name: &str) -> bool {\n self.to_str().map(|s| s.contains(name)).unwrap_or(false)\n }\n\n}\n\n" }, { "from": "gpt", "value": "use libimagstore::store::Entry;\nuse libimagstore::storeid::StoreId;\n\npub trait IsInDiary {\n\n fn is_in_diary(&self, name: &str) -> bool;\n\n}\n\nimpl IsInDiary for Entry {\n\n fn is_in_diary(&self, name: &str) -> bool {\n self.get_location().clone().is_in_diary(name)\n }\n\n}\n\nimpl IsInDiary for StoreId {\n\n fn is_in_diary(&self, name: &str) -> bool {\n self.is_in_collection(&[\"diary\", name])\n }\n\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Add tests from rustfmt::skip test file\n" }, { "from": "human", "value": "#![feature(tool_lints)]\n\n#![warn(clippy::deprecated_cfg_attr)]\n\n// This doesn't get linted, see known problems\n#![cfg_attr(rustfmt, rustfmt_skip)]\n\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn main() {\n foo::f();\n}\n\nmod foo {\n #![cfg_attr(rustfmt, rustfmt_skip)]\n\n pub fn f() {}\n}\n" }, { "from": "gpt", "value": "// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(stmt_expr_attributes)]\n\n#![warn(clippy::deprecated_cfg_attr)]\n\n// This doesn't get linted, see known problems\n#![cfg_attr(rustfmt, rustfmt_skip)]\n\n#[rustfmt::skip]\ntrait Foo\n{\nfn foo(\n);\n}\n\nfn skip_on_statements() {\n #[cfg_attr(rustfmt, rustfmt::skip)]\n 5+3;\n}\n\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn main() {\n foo::f();\n}\n\nmod foo {\n #![cfg_attr(rustfmt, rustfmt_skip)]\n\n pub fn f() {}\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Change default port to 8080\n\nPort 80 as a default requires you to run `sudo`. This changes the\ndefault port to 8080 which doesn't require sudo privileges to run.\n" }, { "from": "human", "value": "extern crate iron;\nextern crate staticfile;\n\nuse iron::Iron;\n\nuse staticfile::Static;\n\nuse std::env;\n\nfn main() {\n let port = env::args().nth(1).unwrap_or(\"80\".to_string());\n let addr = format!(\"localhost:{}\", port);\n\n println!(\"Listening on port {}\", port);\n Iron::new(Static::new(\".\")).http(&*addr).unwrap();\n}\n" }, { "from": "gpt", "value": "extern crate iron;\nextern crate staticfile;\n\nuse iron::Iron;\n\nuse staticfile::Static;\n\nuse std::env;\n\nfn main() {\n let default_port = \"8080\".to_string();\n let port = env::args().nth(1).unwrap_or(default_port);\n let addr = format!(\"localhost:{}\", port);\n\n println!(\"Listening on port {}\", port);\n Iron::new(Static::new(\".\")).http(&*addr).unwrap();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Initialize vm on intepreter start\n" }, { "from": "human", "value": "mod vm;\nmod command;\nmod parse;\n\nuse std::io::Write;\n\nfn main() {\n loop {\n print!(\"{}\", \"bf> \");\n std::io::stdout().flush().unwrap();\n\n let mut line = String::new();\n match std::io::stdin().read_line(&mut line) {\n Ok(0) => break,\n Ok(_) => print!(\"{}\", line),\n Err(error) => print!(\"{}\", error),\n }\n }\n}\n" }, { "from": "gpt", "value": "mod vm;\nmod command;\nmod parse;\n\nuse vm::VM;\nuse std::io::Write;\n\nfn main() {\n let mut vm = VM::new();\n loop {\n print!(\"{}\", \"bf> \");\n std::io::stdout().flush().unwrap();\n\n let mut line = String::new();\n match std::io::stdin().read_line(&mut line) {\n Ok(0) => break,\n Ok(_) => print!(\"{}\", line),\n Err(error) => print!(\"{}\", error),\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Disable rustfmt on a line we don't want changed\n" }, { "from": "human", "value": "use std::io;\nuse std::io::prelude::*;\n\npub fn parse_update_count(tag: String) -> u64 {\n tag.split(' ').last().unwrap().parse().unwrap_or(0)\n}\n\npub fn read_all<R: Read>(r: &mut R, mut buf: &mut [u8]) -> io::Result<()> {\n while !buf.is_empty() {\n match r.read(buf) {\n Ok(0) => return Err(io::Error::new(io::ErrorKind::Other, \"unexpected EOF\")),\n Ok(len) => buf = &mut {buf}[len..],\n Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}\n Err(e) => return Err(e),\n }\n }\n Ok(())\n}\n" }, { "from": "gpt", "value": "use std::io;\nuse std::io::prelude::*;\n\npub fn parse_update_count(tag: String) -> u64 {\n tag.split(' ').last().unwrap().parse().unwrap_or(0)\n}\n\npub fn read_all<R: Read>(r: &mut R, mut buf: &mut [u8]) -> io::Result<()> {\n while !buf.is_empty() {\n match r.read(buf) {\n Ok(0) => return Err(io::Error::new(io::ErrorKind::Other, \"unexpected EOF\")),\n #[cfg_attr(rustfmt, rustfmt_skip)]\n Ok(len) => buf = &mut {buf}[len..],\n Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}\n Err(e) => return Err(e),\n }\n }\n Ok(())\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "x86_common: Add initialization of the console\n" }, { "from": "human", "value": "use ::xen::StartInfo;\n\npub mod defs;\npub mod barrier;\npub mod memory;\n\nextern {\n // Start info is not present on all architecture, this is why this\n // was made a global variable only for x86_*\n pub static start_info: *const StartInfo;\n}\n\npub fn init() {\n unsafe {\n memory::map_shared_info();\n }\n}\n" }, { "from": "gpt", "value": "use ::xen::StartInfo;\n\nuse ::xen::console::console;\nuse ::xen::console::ConsoleInterface;\n\npub mod defs;\npub mod barrier;\npub mod memory;\n\nextern {\n // Start info is not present on all architecture, this is why this\n // was made a global variable only for x86_*\n pub static start_info: *const StartInfo;\n}\n\npub fn init() {\n unsafe {\n let console_vaddr: memory::Vaddr;\n\n memory::map_shared_info();\n\n console_vaddr = memory::mfn_to_vaddr((*start_info).domu_console.mfn);\n\n console().set_port((*start_info).domu_console.evtchn);\n console().set_interface(console_vaddr as *mut ConsoleInterface);\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make Opts no longer a record\n" }, { "from": "human", "value": "//! Configuration options for a single run of the servo application. Created\n//! from command line arguments.\n\npub type Opts = {\n urls: ~[~str],\n render_mode: RenderMode\n};\n\npub enum RenderMode {\n Screen,\n Png(~str)\n}\n\n#[allow(non_implicitly_copyable_typarams)]\npub fn from_cmdline_args(args: &[~str]) -> Opts {\n use std::getopts;\n\n let args = args.tail();\n\n let opts = ~[\n getopts::optopt(~\"o\")\n ];\n\n let opt_match = match getopts::getopts(args, opts) {\n result::Ok(m) => { copy m }\n result::Err(f) => { fail getopts::fail_str(copy f) }\n };\n\n let urls = if opt_match.free.is_empty() {\n fail ~\"servo asks that you provide 1 or more URLs\"\n } else {\n copy opt_match.free\n };\n\n let render_mode = match getopts::opt_maybe_str(move opt_match, ~\"o\") {\n Some(move output_file) => { Png(move output_file) }\n None => { Screen }\n };\n\n {\n urls: move urls,\n render_mode: move render_mode\n }\n}\n" }, { "from": "gpt", "value": "//! Configuration options for a single run of the servo application. Created\n//! from command line arguments.\n\npub struct Opts {\n urls: ~[~str],\n render_mode: RenderMode\n}\n\npub enum RenderMode {\n Screen,\n Png(~str)\n}\n\n#[allow(non_implicitly_copyable_typarams)]\npub fn from_cmdline_args(args: &[~str]) -> Opts {\n use std::getopts;\n\n let args = args.tail();\n\n let opts = ~[\n getopts::optopt(~\"o\")\n ];\n\n let opt_match = match getopts::getopts(args, opts) {\n result::Ok(m) => { copy m }\n result::Err(f) => { fail getopts::fail_str(copy f) }\n };\n\n let urls = if opt_match.free.is_empty() {\n fail ~\"servo asks that you provide 1 or more URLs\"\n } else {\n copy opt_match.free\n };\n\n let render_mode = match getopts::opt_maybe_str(move opt_match, ~\"o\") {\n Some(move output_file) => { Png(move output_file) }\n None => { Screen }\n };\n\n Opts {\n urls: move urls,\n render_mode: move render_mode\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use spin::Once to initialize CPU count\n" }, { "from": "human", "value": "use vmx;\nuse collections::vec::Vec;\nuse core::sync::atomic::{ATOMIC_U16_INIT, AtomicU16, Ordering};\n\n\nstatic CPU_COUNT: AtomicU16 = ATOMIC_U16_INIT;\nstatic CPU_ASSIGNMENT: AtomicU16 = ATOMIC_U16_INIT;\n\n\npub fn init(count: u16) {\n CPU_COUNT.store(count, Ordering::Relaxed);\n}\n\n\npub fn bring_core_online() {\n let cpu_num = CPU_ASSIGNMENT.fetch_add(1, Ordering::Relaxed);\n set_number(cpu_num);\n}\n\n\nfn set_number(num: u16) {\n vmx::write_gs(num);\n}\n\n\npub fn get_number() -> u16 {\n vmx::read_gs()\n}\n\n\n#[derive(Default)]\npub struct PerCoreVariable<T> {\n vars: Vec<T>,\n}\n\n\nimpl<T> PerCoreVariable<T> {\n pub fn get(&self) -> &T {\n &self.vars[get_number() as usize]\n }\n}\n" }, { "from": "gpt", "value": "use vmx;\nuse collections::vec::Vec;\nuse core::sync::atomic::{ATOMIC_U16_INIT, AtomicU16, Ordering};\nuse spin;\n\n\nstatic CPU_COUNT: spin::Once<u16> = spin::Once::new();\nstatic CPU_ASSIGNMENT: AtomicU16 = ATOMIC_U16_INIT;\n\n\npub fn init(count: u16) {\n CPU_COUNT.call_once(||{ count });\n}\n\n\npub fn bring_core_online() {\n let cpu_num = CPU_ASSIGNMENT.fetch_add(1, Ordering::Relaxed);\n set_number(cpu_num);\n}\n\n\nfn set_number(num: u16) {\n vmx::write_gs(num);\n}\n\n\npub fn get_number() -> u16 {\n vmx::read_gs()\n}\n\n\n#[derive(Default)]\npub struct PerCoreVariable<T> {\n vars: Vec<T>,\n}\n\n\nimpl<T> PerCoreVariable<T> {\n pub fn get(&self) -> &T {\n &self.vars[get_number() as usize]\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix format trait errors (breaking change)\n" }, { "from": "human", "value": "fn _12_1(){\n println!(\"guide 12-1\");\n\n let a = [1i, 2i, 3i];\n let mut m = [2i, 3i, 4i];\n\n let b = [0i, ..20]; // shorthand for array of 20 elements all initialized to 0\n println!(\"{}\", b);\n m = [5i, 6i, 7i];\n println!(\"{}\", m);\n\n for i in m.iter() {\n println!(\"elem {}\", i);\n }\n\n let names = [\"Emilija\", \"Anzelika\"];\n println!(\"{} -> {}\", names[1], names[0]);\n}\n\nfn _12_2(){\n println!(\"guide 12-2\");\n\n let mut v = vec![1i, 2, 3];\n v.push(4);\n println!(\"{}, len is {}\", v, v.len());\n}\n\nfn _12_3(){\n println!(\"guide 12-3\");\n\n let mut a = vec![0i, 1, 2, 3, 4];\n let middle = a.as_mut_slice(); \n\n middle[0] = 10i;\n\n for e in middle.iter() {\n println!(\"{}\", e);\n }\n\n}\n\nfn main(){\n println!(\"guide 12\");\n _12_1();\n _12_2();\n _12_3();\n}\n" }, { "from": "gpt", "value": "fn _12_1(){\n println!(\"guide 12-1\");\n\n let a = [1i32, 2i32, 3i32];\n let mut m = [2i32, 3i32, 4i32];\n if false {\n println!(\"{:?} {:?}\", a, m);\n }\n\n let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0\n println!(\"{:?}\", b);\n m = [5i32, 6i32, 7i32];\n println!(\"{:?}\", m);\n\n for i in m.iter() {\n println!(\"elem {}\", i);\n }\n\n let names = [\"Emilija\", \"Anzelika\"];\n println!(\"{} -> {}\", names[1], names[0]);\n}\n\nfn _12_2(){\n println!(\"guide 12-2\");\n\n let mut v = vec![1i32, 2, 3];\n v.push(4);\n println!(\"{:?}, len is {}\", v, v.len());\n}\n\nfn _12_3(){\n println!(\"guide 12-3\");\n\n let mut a = vec![0i32, 1, 2, 3, 4];\n let middle = a.as_mut_slice();\n\n middle[0] = 10i32;\n\n for e in middle.iter() {\n println!(\"{}\", e);\n }\n\n}\n\nfn main(){\n println!(\"guide 12\");\n _12_1();\n _12_2();\n _12_3();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix use of the new function signatures\n" }, { "from": "human", "value": "#![feature(plugin)]\n#![plugin(rustlex)]\n#[allow(plugin_as_library)]\nextern crate rustlex;\n#[macro_use] extern crate log;\nextern crate time;\nextern crate term;\n\npub mod frontend;\npub mod backend;\npub use backend::zcode::zfile;\npub mod utils;\n\nuse frontend::codegen;\n\nuse std::io::{Read,Write};\n\n\npub fn compile<R: Read, W: Write>(input: &mut R, output: &mut W) {\n // compile\n\n //screen\n let mut clean_input = frontend::screener::screen(input);\n\n // tokenize\n let tokens = frontend::lexer::lex(&mut clean_input);\n\n debug!(\"\");\n for token in tokens.iter() {\n \tdebug!(\"{:?}\", token);\n }\n\n // parse tokens and create ast\n let ast = frontend::parser::parse_tokens(tokens);\n ast.print();\n\n // create code\n codegen::generate_zcode(ast, output);\n}\n" }, { "from": "gpt", "value": "#![feature(plugin)]\n#![plugin(rustlex)]\n#[allow(plugin_as_library)]\nextern crate rustlex;\n#[macro_use] extern crate log;\nextern crate time;\nextern crate term;\n\npub mod frontend;\npub mod backend;\npub use backend::zcode::zfile;\npub mod utils;\n\nuse frontend::codegen;\n\nuse std::io::{Read,Write};\n\n\npub fn compile<R: Read, W: Write>(input: &mut R, output: &mut W) {\n // compile\n\n //screen\n let mut clean_input = frontend::screener::screen(input);\n\n // tokenize\n let tokens = frontend::lexer::lex(&mut clean_input);\n\n debug!(\"\");\n for token in tokens {\n \tdebug!(\"{:?}\", token);\n }\n\n // parse tokens and create ast\n let ast = frontend::parser::parse_tokens(tokens.collect()); //use collect until we work on iterators directly\n ast.print();\n\n // create code\n codegen::generate_zcode(ast, output);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Stop and think and make it compile first\n" }, { "from": "human", "value": "// The shift characters are stored as nulls, as the conversion code doesn't\n// care what value they have. WRU? maps to ASCII ENQ (\\x05), I think.\nconst Ita2Letters = b\"\\0E\\nA SIU\\rDRJNFCKTZLWHYPQOBG\\0MXV\\0\";\nconst Ita2Figures = b\"\\03\\n- \\x0787\\r\\x054',!:(5\\\")2#6019?&\\0./;\\0\"\n\n\n#[test]\nfn it_works() {\n}\n" }, { "from": "gpt", "value": "// The shift characters are stored as nulls, as the conversion code doesn't\n// care what value they have. WRU? maps to ASCII ENQ (\\x05), I think.\nconst ITA2: (&'static [u8], &'static [u8]) =\n (b\"\\0E\\nA SIU\\rDRJNFCKTZLWHYPQOBG\\0MXV\\0\",\n b\"\\03\\n- \\x0787\\r\\x054',!:(5\\\")2#6019?&\\0./;\\0\");\n\n\n#[test]\nfn it_works() {\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Hide modules from the public API, only the re-exports should be used\n" }, { "from": "human", "value": "pub mod liblz4;\npub mod decoder;\npub mod encoder;\n\npub use decoder::Decoder;\npub use encoder::Encoder;\npub use encoder::EncoderBuilder;\npub use liblz4::BlockSize;\npub use liblz4::BlockMode;\npub use liblz4::ContentChecksum;\npub use liblz4::version;\n" }, { "from": "gpt", "value": "mod liblz4;\nmod decoder;\nmod encoder;\n\npub use decoder::Decoder;\npub use encoder::Encoder;\npub use encoder::EncoderBuilder;\npub use liblz4::BlockSize;\npub use liblz4::BlockMode;\npub use liblz4::ContentChecksum;\npub use liblz4::version;\n" } ]
rust
chosen
[ { "from": "system", "value": "Verify that IcedError is Send + Sync\n" }, { "from": "human", "value": "// SPDX-License-Identifier: MIT\n// Copyright (C) 2018-present iced project and contributors\n\nuse alloc::borrow::Cow;\nuse alloc::string::String;\nuse core::fmt;\n#[cfg(feature = \"std\")]\nuse std::error::Error;\n\n/// iced error\n#[derive(Debug, Clone)]\npub struct IcedError {\n\terror: Cow<'static, str>,\n}\n\nimpl IcedError {\n\t#[allow(dead_code)]\n\tpub(crate) fn new(error: &'static str) -> Self {\n\t\tSelf { error: error.into() }\n\t}\n\n\t#[allow(dead_code)]\n\tpub(crate) fn with_string(error: String) -> Self {\n\t\tSelf { error: error.into() }\n\t}\n}\n\n#[cfg(feature = \"std\")]\nimpl Error for IcedError {\n\t// Required since MSRV < 1.42.0\n\t#[allow(clippy::missing_inline_in_public_items)]\n\tfn description(&self) -> &str {\n\t\t&self.error\n\t}\n}\n\nimpl fmt::Display for IcedError {\n\t#[allow(clippy::missing_inline_in_public_items)]\n\tfn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\t\twrite!(f, \"{}\", &self.error)\n\t}\n}\n" }, { "from": "gpt", "value": "// SPDX-License-Identifier: MIT\n// Copyright (C) 2018-present iced project and contributors\n\nuse alloc::borrow::Cow;\nuse alloc::string::String;\nuse core::fmt;\n#[cfg(feature = \"std\")]\nuse std::error::Error;\n\n/// iced error\n#[derive(Debug, Clone)]\npub struct IcedError {\n\terror: Cow<'static, str>,\n}\n\nstruct _TraitsCheck\nwhere\n\tIcedError: fmt::Debug + Clone + fmt::Display + Send + Sync;\n#[cfg(feature = \"std\")]\nstruct _TraitsCheckStd\nwhere\n\tIcedError: Error;\n\nimpl IcedError {\n\t#[allow(dead_code)]\n\tpub(crate) fn new(error: &'static str) -> Self {\n\t\tSelf { error: error.into() }\n\t}\n\n\t#[allow(dead_code)]\n\tpub(crate) fn with_string(error: String) -> Self {\n\t\tSelf { error: error.into() }\n\t}\n}\n\n#[cfg(feature = \"std\")]\nimpl Error for IcedError {\n\t// Required since MSRV < 1.42.0\n\t#[allow(clippy::missing_inline_in_public_items)]\n\tfn description(&self) -> &str {\n\t\t&self.error\n\t}\n}\n\nimpl fmt::Display for IcedError {\n\t#[allow(clippy::missing_inline_in_public_items)]\n\tfn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\t\twrite!(f, \"{}\", &self.error)\n\t}\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Correct Twelve Days of Christmas Implementation\n\n- The lyrics given on the required page (http://www.lyricsmode.com/lyrics/c/christmas_carols/the_twelve_days_of_christmas.html) make this task much easier than you'd expect\r\n- I've also updated the implementation on the official site (https://rosettacode.org/wiki/The_Twelve_Days_of_Christmas#Rust), along with a Rust Playground link (https://play.rust-lang.org/?gist=4f349c8959b48e804f592e7251e6abbf&version=stable&backtrace=0)" }, { "from": "human", "value": "fn showpresents(count: usize) {\n let days = [\"second\", \"third\", \"fourth\", \"fifth\", \"sixth\", \"seventh\", \"eighth\", \"ninth\",\n \"tenth\", \"eleventh\", \"twelfth\"];\n\n let presents = [\"Two turtle doves\",\n \"Three french hens\",\n \"Four calling birds\",\n \"Five golden rings\",\n \"Six geese a-laying\",\n \"Seven swans a-swimming\",\n \"Eight maids a-milking\",\n \"Nine ladies dancing\",\n \"Ten lords a-leaping\",\n \"Eleven pipers piping\",\n \"Twelve drummers drumming\"];\n\n println!(\"On the {} day of Christmas my true love gave to me {}\",\n days[count - 1],\n presents[count - 1]);\n if count > 0 {\n let mut j = count - 1;\n while j > 0 {\n println!(\"{}\", presents[j - 1]);\n j -= 1;\n\n }\n }\n println!(\"And a partridge in a pear tree \\n\");\n}\n\nfn main() {\n println!(\"On the first day of Christmas my true love gave to me a partridge in a pear tree\\n\");\n\n for count in 1..12 {\n showpresents(count);\n }\n}\n" }, { "from": "gpt", "value": "fn main() {\n let days = [\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\", \"seventh\", \"eighth\",\n \"ninth\", \"tenth\", \"eleventh\", \"twelfth\"];\n\n let gifts = [\"A Patridge in a Pear Tree\",\n \"Two Turtle Doves and\",\n \"Three French Hens\",\n \"Four Calling Birds\",\n \"Five Golden Rings\",\n \"Six Geese a Laying\",\n \"Seven Swans a Swimming\",\n \"Eight Maids a Milking\",\n \"Nine Ladies Dancing\",\n \"Ten Lords a Leaping\",\n \"Eleven Pipers Piping\",\n \"Twelve Drummers Drumming\"];\n\n for i in 0..12 {\n println!(\"On the {} day of Christmas,\", days[i]);\n println!(\"My true love sent to me:\");\n\n for j in (0..i + 1).rev() {\n println!(\"{}\", gifts[j]);\n }\n println!()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix clippy: Derive Eq as well\n\nSigned-off-by: Matthias Beyer <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@beyermatthias.de>\n" }, { "from": "human", "value": "use config::Config;\n#[derive(Debug, Default, serde_derive::Deserialize, PartialEq)]\nstruct AppConfig {\n list: Vec<String>,\n}\n\nfn main() {\n std::env::set_var(\"APP_LIST\", \"Hello World\");\n\n let config = Config::builder()\n .add_source(\n config::Environment::with_prefix(\"APP\")\n .try_parsing(true)\n .separator(\"_\")\n .list_separator(\" \"),\n )\n .build()\n .unwrap();\n\n let app: AppConfig = config.try_deserialize().unwrap();\n\n assert_eq!(app.list, vec![String::from(\"Hello\"), String::from(\"World\")]);\n\n std::env::remove_var(\"APP_LIST\");\n}\n" }, { "from": "gpt", "value": "use config::Config;\n#[derive(Debug, Default, serde_derive::Deserialize, PartialEq, Eq)]\nstruct AppConfig {\n list: Vec<String>,\n}\n\nfn main() {\n std::env::set_var(\"APP_LIST\", \"Hello World\");\n\n let config = Config::builder()\n .add_source(\n config::Environment::with_prefix(\"APP\")\n .try_parsing(true)\n .separator(\"_\")\n .list_separator(\" \"),\n )\n .build()\n .unwrap();\n\n let app: AppConfig = config.try_deserialize().unwrap();\n\n assert_eq!(app.list, vec![String::from(\"Hello\"), String::from(\"World\")]);\n\n std::env::remove_var(\"APP_LIST\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "roman-numerals: Use `iter` instead of `into_iter` when not moving\n\nClippy suggested\nhttps://travis-ci.org/exercism/rust/builds/456432005\nerror: this .into_iter() call is equivalent to .iter() and will not move the array\n = help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.212/index.html#into_iter_on_array\n\n(compare to 75c1bf93b7045bcd25aa178a8cecf1da4bb422fc which was on\nslices. Apparently this is considered a warning for slices but an error\non arrays)\n" }, { "from": "human", "value": "use std::fmt;\n\nstatic ROMAN_MAP: [(usize, &'static str); 13] = [\n (1, \"I\"),\n (4, \"IV\"),\n (5, \"V\"),\n (9, \"IX\"),\n (10, \"X\"),\n (40, \"XL\"),\n (50, \"L\"),\n (90, \"XC\"),\n (100, \"C\"),\n (400, \"CD\"),\n (500, \"D\"),\n (900, \"CM\"),\n (1000, \"M\"),\n];\n\npub struct Roman {\n num: usize,\n}\n\nimpl From<usize> for Roman {\n fn from(i: usize) -> Self {\n Roman::new(i)\n }\n}\n\nimpl fmt::Display for Roman {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n let mut start = self.num.clone();\n let mut result = String::new();\n for &(numeric, roman_string) in ROMAN_MAP.into_iter().rev() {\n while start >= numeric {\n result.push_str(roman_string);\n start -= numeric;\n }\n }\n write!(f, \"{}\", result)\n }\n}\n\nimpl Roman {\n fn new(num: usize) -> Roman {\n Roman { num }\n }\n}\n" }, { "from": "gpt", "value": "use std::fmt;\n\nstatic ROMAN_MAP: [(usize, &'static str); 13] = [\n (1, \"I\"),\n (4, \"IV\"),\n (5, \"V\"),\n (9, \"IX\"),\n (10, \"X\"),\n (40, \"XL\"),\n (50, \"L\"),\n (90, \"XC\"),\n (100, \"C\"),\n (400, \"CD\"),\n (500, \"D\"),\n (900, \"CM\"),\n (1000, \"M\"),\n];\n\npub struct Roman {\n num: usize,\n}\n\nimpl From<usize> for Roman {\n fn from(i: usize) -> Self {\n Roman::new(i)\n }\n}\n\nimpl fmt::Display for Roman {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n let mut start = self.num.clone();\n let mut result = String::new();\n for &(numeric, roman_string) in ROMAN_MAP.iter().rev() {\n while start >= numeric {\n result.push_str(roman_string);\n start -= numeric;\n }\n }\n write!(f, \"{}\", result)\n }\n}\n\nimpl Roman {\n fn new(num: usize) -> Roman {\n Roman { num }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Check if best move in transposition table is valid\n" }, { "from": "human", "value": "use game::{Position, Move, ZobristHash, NumPlies};\n\nuse negamax::Bound;\n\n#[derive(Clone, Debug)]\npub struct Data {\n pub hash: ZobristHash,\n pub depth: NumPlies,\n pub bound: Bound,\n pub best_move_opt: Option<Move>,\n}\n\npub struct TranspositionTable(Vec<Option<Data>>);\nimpl TranspositionTable {\n pub fn with_capacity(capacity: usize) -> Self {\n TranspositionTable(vec![None; capacity])\n }\n pub fn get<'a>(&'a self, pos: &Position) -> Option<&'a Data> {\n let hash = pos.hash();\n let idx = (hash.0 % (self.0.len() as u64)) as usize;\n self.0[idx].as_ref().and_then(|x| if x.hash == hash { Some(x) } else { None })\n }\n // TODO implement a better replacement scheme\n pub fn set(&mut self, pos: &Position, depth: NumPlies, best_move_opt: Option<Move>, bound: Bound) {\n let hash = pos.hash();\n let idx = (hash.0 % (self.0.len() as u64)) as usize;\n self.0[idx] = Some(Data { hash: hash, depth: depth, best_move_opt: best_move_opt, bound: bound });\n }\n}\n" }, { "from": "gpt", "value": "use game::{Position, Move, ZobristHash, NumPlies};\n\nuse negamax::Bound;\n\n#[derive(Clone, Debug)]\npub struct Data {\n pub hash: ZobristHash,\n pub depth: NumPlies,\n pub bound: Bound,\n pub best_move_opt: Option<Move>,\n}\n\npub struct TranspositionTable(Vec<Option<Data>>);\nimpl TranspositionTable {\n pub fn with_capacity(capacity: usize) -> Self {\n TranspositionTable(vec![None; capacity])\n }\n pub fn get<'a>(&'a self, pos: &Position) -> Option<&'a Data> {\n let hash = pos.hash();\n let idx = (hash.0 % (self.0.len() as u64)) as usize;\n self.0[idx].as_ref().and_then(|x| {\n let is_correct_pos = x.hash == hash &&\n x.best_move_opt.as_ref()\n .map_or(true, |y| pos.legal_iter().any(|z| *y == z));\n if is_correct_pos { Some(x) } else { None }\n })\n }\n // TODO implement a better replacement scheme\n pub fn set(&mut self, pos: &Position, depth: NumPlies, best_move_opt: Option<Move>, bound: Bound) {\n let hash = pos.hash();\n let idx = (hash.0 % (self.0.len() as u64)) as usize;\n self.0[idx] = Some(Data { hash: hash, depth: depth, best_move_opt: best_move_opt, bound: bound });\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update to use new for loop protocol, and fix for new `as` binding rules\n" }, { "from": "human", "value": "// Copyright 2013 The noise-rs developers. For a full listing of the authors,\n// refer to the AUTHORS file at the top-level directory of this distribution.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//! An example of using perlin noise\n\nextern mod noise;\n\nuse std::uint::range;\nuse noise::perlin::*;\n\nstatic WIDTH: uint = 100;\nstatic HEIGHT: uint = 100;\n\nstatic GRADIENT: [&'static str, ..6] = [\" \", \"░\", \"▒\", \"▓\", \"█\", \"█\"];\n\nfn main() {\n let ctx = PerlinContext::new::<f32>();\n\n for range(0, HEIGHT) |y| {\n for range(0, WIDTH) |x| {\n let val = [x as f32 * 0.1f32,\n y as f32 * 0.1f32].perlin(&ctx) * 0.5f32 + 0.5f32;\n print(GRADIENT[val / 0.2f32 as int]);\n }\n println(\"\");\n }\n}\n" }, { "from": "gpt", "value": "// Copyright 2013 The noise-rs developers. For a full listing of the authors,\n// refer to the AUTHORS file at the top-level directory of this distribution.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//! An example of using perlin noise\n\nextern mod noise;\n\nuse noise::perlin::*;\n\nstatic WIDTH: uint = 100;\nstatic HEIGHT: uint = 100;\n\nstatic GRADIENT: [&'static str, ..6] = [\" \", \"░\", \"▒\", \"▓\", \"█\", \"█\"];\n\nfn main() {\n let ctx = PerlinContext::new::<f32>();\n\n for y in range(0, HEIGHT) {\n for x in range(0, WIDTH) {\n let val = [x as f32 * 0.1f32,\n y as f32 * 0.1f32].perlin(&ctx) * 0.5f32 + 0.5f32;\n print(GRADIENT[(val / 0.2f32) as int]);\n }\n println(\"\");\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make idiomatic the negemax benchmark's move generation function.\n" }, { "from": "human", "value": "#![feature(test)]\nextern crate minimax;\nextern crate test;\nuse test::Bencher;\nuse minimax::*;\n\n#[derive(Clone)]\npub struct Board;\n\n#[derive(Copy, Clone)]\npub struct Place;\n\npub struct Eval;\n\npub struct Noop;\n\nimpl Move for Place {\n type G = Noop;\n fn apply(&self, _: &mut Board) { }\n fn undo(&self, _: &mut Board) { }\n}\n\nimpl Game for Noop {\n type S = Board;\n type M = Place;\n\n fn generate_moves(_: &Board, _: Player, ms: &mut [Option<Place>]) -> usize {\n ms[0] = Some(Place);\n ms[1] = Some(Place);\n ms[2] = Some(Place);\n ms[3] = Some(Place);\n ms[4] = None;\n 4\n }\n\n fn get_winner(_: &Board) -> Option<Winner> { None }\n}\n\nimpl Evaluator for Eval {\n type G = Noop;\n\n fn evaluate(_: &Board, _: Option<Winner>) -> Evaluation {\n Evaluation::Score(0)\n }\n}\n\n#[bench]\nfn bench_negamax(b: &mut Bencher) {\n let board = Board;\n let mut s = Negamax::<Eval>::new(Options { max_depth: 10 });\n b.iter(|| s.choose_move(&board, Player::Computer));\n}\n" }, { "from": "gpt", "value": "#![feature(test)]\nextern crate minimax;\nextern crate test;\nuse test::Bencher;\nuse minimax::*;\n\n#[derive(Clone)]\npub struct Board;\n\n#[derive(Copy, Clone)]\npub struct Place;\n\npub struct Eval;\n\npub struct Noop;\n\nimpl Move for Place {\n type G = Noop;\n fn apply(&self, _: &mut Board) { }\n fn undo(&self, _: &mut Board) { }\n}\n\nimpl Game for Noop {\n type S = Board;\n type M = Place;\n\n fn generate_moves(_: &Board, _: Player, ms: &mut [Option<Place>]) -> usize {\n const NUM_MOVES: usize = 4;\n for m in ms.iter_mut().take(NUM_MOVES) {\n *m = Some(Place);\n }\n ms[NUM_MOVES] = None;\n NUM_MOVES\n }\n\n fn get_winner(_: &Board) -> Option<Winner> { None }\n}\n\nimpl Evaluator for Eval {\n type G = Noop;\n\n fn evaluate(_: &Board, _: Option<Winner>) -> Evaluation {\n Evaluation::Score(0)\n }\n}\n\n#[bench]\nfn bench_negamax(b: &mut Bencher) {\n let board = Board;\n let mut s = Negamax::<Eval>::new(Options { max_depth: 10 });\n b.iter(|| s.choose_move(&board, Player::Computer));\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Implement RNA Transcription using FromIterator\n" }, { "from": "human", "value": "#[derive(PartialEq, Debug)]\npub struct RibonucleicAcid(String);\n\nimpl RibonucleicAcid {\n pub fn new(rna: &str) -> RibonucleicAcid {\n RibonucleicAcid(rna.into())\n }\n}\n\n#[derive(PartialEq, Debug)]\npub struct DeoxyribonucleicAcid(String);\n\nimpl DeoxyribonucleicAcid {\n pub fn new(dna: &str) -> DeoxyribonucleicAcid {\n DeoxyribonucleicAcid(dna.into())\n }\n\n pub fn to_rna(&self) -> Result<RibonucleicAcid, &'static str> {\n self.0.chars().map(|c| match c {\n 'G' => Ok('C'),\n 'C' => Ok('G'),\n 'T' => Ok('A'),\n 'A' => Ok('U'),\n _ => Err(\"Invalid DNA strand\")\n }).collect::<Result<String, &'static str>>().map(RibonucleicAcid)\n }\n}\n" }, { "from": "gpt", "value": "use std::iter::FromIterator;\n\n#[derive(PartialEq, Debug)]\npub struct RibonucleicAcid(String);\n\nimpl RibonucleicAcid {\n pub fn new(rna: &str) -> RibonucleicAcid {\n RibonucleicAcid(rna.into())\n }\n}\n\nimpl FromIterator<char> for RibonucleicAcid {\n fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> Self {\n let mut rna = String::new();\n\n for c in iter {\n rna.push(c);\n }\n\n RibonucleicAcid(rna)\n }\n}\n\n#[derive(PartialEq, Debug)]\npub struct DeoxyribonucleicAcid(String);\n\nimpl DeoxyribonucleicAcid {\n pub fn new(dna: &str) -> DeoxyribonucleicAcid {\n DeoxyribonucleicAcid(dna.into())\n }\n\n pub fn to_rna(&self) -> Result<RibonucleicAcid, &'static str> {\n self.0.chars().map(|c| match c {\n 'G' => Ok('C'),\n 'C' => Ok('G'),\n 'T' => Ok('A'),\n 'A' => Ok('U'),\n _ => Err(\"Invalid DNA strand\")\n }).collect::<Result<RibonucleicAcid, &'static str>>()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add a note about the similarity to std::process::ExitStatus\n" }, { "from": "human", "value": "use std::process::Command;\n\n\npub struct Output {\n pub status: i32,\n pub stdout: String,\n pub stderr: String,\n}\n\n\n/// Run an AppleScript.\n///\n/// * `script`: The AppleScript code to run.\n///\npub fn run(script: &str) -> Output {\n let cmd_result = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(script)\n .output()\n .expect(\"failed to execute AppleScript\");\n\n Output {\n status: cmd_result.status.code().unwrap_or(1),\n stdout: String::from_utf8(cmd_result.stdout).unwrap(),\n stderr: String::from_utf8(cmd_result.stderr).unwrap(),\n }\n}\n" }, { "from": "gpt", "value": "use std::process::{Command, ExitStatus};\n\n\n/// The output of a finished process.\n///\n/// This varies from Output in std::process in that stdout/stderr are\n/// both strings rather than Vec<u8>.\npub struct Output {\n pub status: ExitStatus,\n pub stdout: String,\n pub stderr: String,\n}\n\n\n/// Run an AppleScript.\n///\n/// * `script`: The AppleScript code to run.\n///\npub fn run(script: &str) -> Output {\n let cmd_result = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(script)\n .output()\n .expect(\"failed to execute AppleScript\");\n\n Output {\n status: cmd_result.status,\n stdout: String::from_utf8(cmd_result.stdout).unwrap(),\n stderr: String::from_utf8(cmd_result.stderr).unwrap(),\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make imageflow_helpers run tests under system alloc\n" }, { "from": "human", "value": "#[macro_use]\nextern crate lazy_static;\n\nextern crate reqwest;\nextern crate hyper_native_tls;\nextern crate regex;\nextern crate hyper;\nextern crate blake2_rfc;\nextern crate twox_hash;\nextern crate chrono;\nextern crate zip;\nextern crate serde;\nextern crate serde_json;\nextern crate libc;\nextern crate backtrace;\n\n\n#[cfg(not(any(target_os = \"windows\", target_os = \"macos\")))]\nextern crate openssl;\n#[cfg(not(any(target_os = \"windows\", target_os = \"macos\")))]\nextern crate hyper_openssl;\n\npub mod identifier_styles;\npub mod preludes;\npub mod filesystem;\npub mod fetching;\npub mod caching;\npub mod hashing;\npub mod process_testing;\npub mod process_capture;\npub mod colors;\npub mod debug;\n\npub mod timeywimey{\n pub fn time_bucket(seconds_per_bucket: u64, bucket_count: u64) -> u64{\n ::std::time::SystemTime::now().duration_since(::std::time::UNIX_EPOCH).unwrap().as_secs() / seconds_per_bucket % bucket_count\n }\n pub use chrono::UTC;\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {\n }\n}\n" }, { "from": "gpt", "value": "#![feature(alloc_system)]\n\nextern crate alloc_system;\n\n\n#[macro_use]\nextern crate lazy_static;\n\nextern crate reqwest;\nextern crate hyper_native_tls;\nextern crate regex;\nextern crate hyper;\nextern crate blake2_rfc;\nextern crate twox_hash;\nextern crate chrono;\nextern crate zip;\nextern crate serde;\nextern crate serde_json;\nextern crate libc;\nextern crate backtrace;\n\n\n#[cfg(not(any(target_os = \"windows\", target_os = \"macos\")))]\nextern crate openssl;\n#[cfg(not(any(target_os = \"windows\", target_os = \"macos\")))]\nextern crate hyper_openssl;\n\npub mod identifier_styles;\npub mod preludes;\npub mod filesystem;\npub mod fetching;\npub mod caching;\npub mod hashing;\npub mod process_testing;\npub mod process_capture;\npub mod colors;\npub mod debug;\n\npub mod timeywimey{\n pub fn time_bucket(seconds_per_bucket: u64, bucket_count: u64) -> u64{\n ::std::time::SystemTime::now().duration_since(::std::time::UNIX_EPOCH).unwrap().as_secs() / seconds_per_bucket % bucket_count\n }\n pub use chrono::UTC;\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Revert \"enable only I/O reactor for async operations\"\n\nThis reverts commit 0b759a47339845cf5dea2097d3c0295bbdfc03c6.\n" }, { "from": "human", "value": "use lazy_static::lazy_static;\nuse std::future::Future;\nuse std::sync::Mutex;\nuse tokio::runtime::{Builder, Runtime};\n\nlazy_static! {\n static ref RUNTIME: Mutex<Runtime> = Mutex::new(\n Builder::new()\n .basic_scheduler() // Do not make a new thread since this runtime is only used for network requests\n .enable_io()\n .build()\n .unwrap()\n );\n}\n\npub fn blocking<F: Future>(future: F) -> F::Output {\n RUNTIME.lock().unwrap().block_on(future)\n}\n" }, { "from": "gpt", "value": "use lazy_static::lazy_static;\nuse std::future::Future;\nuse std::sync::Mutex;\nuse tokio::runtime::{Builder, Runtime};\n\nlazy_static! {\n static ref RUNTIME: Mutex<Runtime> = Mutex::new(\n Builder::new()\n .basic_scheduler() // Do not make a new thread since this runtime is only used for network requests\n .enable_all()\n .build()\n .unwrap()\n );\n}\n\npub fn blocking<F: Future>(future: F) -> F::Output {\n RUNTIME.lock().unwrap().block_on(future)\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make ByteConsumer own its reader\n\nThis is in preparation for making pq multi-threaded; the trait `Read`\nis not `Send` and so with the previous declaration (read: &'a mut\nRead) ByteConsumer was _not_ Send and could not be moved into a\nclosure, i.e., with thread::spawn.\n\nThis commit modifies the API of ByteConsumer by making it take\nownership of a value of type T where T implements the Read trait.\n" }, { "from": "human", "value": "#![deny(missing_docs)]\n\nuse varint::consume_single_varint;\nuse stream::*;\nuse std::io::Read;\n\n/// A consumer for a byte stream\npub struct ByteConsumer<'a> {\n read: &'a mut Read,\n type_: StreamType,\n}\n\nimpl<'a> ByteConsumer<'a> {\n /// Return a ByteConsumer from for single messages, varint or leb128-delimited\n pub fn new(read: &'a mut Read, type_: StreamType) -> ByteConsumer {\n ByteConsumer { read, type_ }\n }\n}\n\nimpl<'a> Iterator for ByteConsumer<'a> {\n type Item = Vec<u8>;\n\n fn next(&mut self) -> Option<Vec<u8>> {\n match self.type_ {\n StreamType::Leb128 | StreamType::Varint => consume_single_varint(self.read),\n StreamType::Single => {\n let ret: Option<Vec<u8>>;\n let mut buf = Vec::new();\n match self.read.read_to_end(&mut buf) {\n Ok(x) => {\n if x > 0 {\n ret = Some(buf);\n } else {\n ret = None\n }\n }\n Err(_) => ret = None,\n }\n ret\n }\n }\n }\n}\n" }, { "from": "gpt", "value": "#![deny(missing_docs)]\n\nuse varint::consume_single_varint;\nuse stream::*;\nuse std::io::Read;\n\n/// A consumer for a byte stream\npub struct ByteConsumer<T: Read> {\n read: T,\n type_: StreamType,\n}\n\nimpl <T: Read> ByteConsumer<T> {\n /// Return a ByteConsumer from for single messages, varint or leb128-delimited\n pub fn new(read: T, type_: StreamType) -> ByteConsumer<T> {\n ByteConsumer { read, type_ }\n }\n}\n\nimpl <T: Read> Iterator for ByteConsumer<T> {\n type Item = Vec<u8>;\n\n fn next(&mut self) -> Option<Vec<u8>> {\n match self.type_ {\n StreamType::Leb128 | StreamType::Varint => consume_single_varint(&mut self.read),\n StreamType::Single => {\n let ret: Option<Vec<u8>>;\n let mut buf = Vec::new();\n match self.read.read_to_end(&mut buf) {\n Ok(x) => {\n if x > 0 {\n ret = Some(buf);\n } else {\n ret = None\n }\n }\n Err(_) => ret = None,\n }\n ret\n }\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add actor + actor ref\n" }, { "from": "human", "value": "extern crate rand;\n\nuse std::sync::mpsc::{Sender, Receiver};\nuse std::sync::mpsc;\nuse std::{thread, time};\nuse rand::Rng;\n\nstatic NTHREADS: i32 = 64;\n\nfn main() {\n // Channels have two endpoints: the `Sender<T>` and the `Receiver<T>`,\n // where `T` is the type of the message to be transferred\n // (type annotation is superfluous)\n let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();\n\n for id in 0..NTHREADS {\n // The sender endpoint can be copied\n let thread_tx = tx.clone();\n\n // Each thread will send its id via the channel\n thread::spawn(move || {\n\n let sleep = rand::thread_rng().gen_range(1, 1001);\n thread::sleep(time::Duration::from_millis(sleep));\n\n // The thread takes ownership over `thread_tx`\n // Each thread queues a message in the channel\n thread_tx.send(id).unwrap();\n\n // Sending is a non-blocking operation, the thread will continue\n // immediately after sending its message\n println!(\"thread {} finished\", id);\n });\n }\n\n // Here, all the messages are collected\n let mut ids = Vec::with_capacity(NTHREADS as usize);\n for _ in 0..NTHREADS {\n // The `recv` method picks a message from the channel\n // `recv` will block the current thread if there no messages available\n ids.push(rx.recv());\n }\n\n // Show the order in which the messages were sent\n println!(\"{:?}\", ids);\n}\n" }, { "from": "gpt", "value": "extern crate rand;\n\nuse std::sync::mpsc::{Sender, Receiver};\nuse std::sync::mpsc;\nuse std::{thread, time};\nuse rand::Rng;\n\n#[derive(Debug)]\nstruct Actor {\n inbox: Receiver<i32>\n}\n\n#[derive(Debug)]\nstruct ActorRef {\n outbox: Sender<i32>\n}\n\nimpl Actor {\n fn new() -> (ActorRef, Actor) {\n let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();\n return (ActorRef{outbox: tx}, Actor{inbox: rx})\n }\n}\n\nfn main() {\n let a = Actor::new();\n println!(\"{:?}\", a);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove return to satisfy clippy\n" }, { "from": "human", "value": "#[derive(Debug)]\npub enum CalculatorInput {\n Add,\n Subtract,\n Multiply,\n Divide,\n Value(i32),\n}\n\npub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {\n let mut operands: Vec<i32> = Vec::new();\n\n for input in inputs {\n match input {\n CalculatorInput::Value(x) => operands.push(*x),\n _ => {\n if operands.len() < 2 {\n return None;\n }\n let operand_b = operands.pop().unwrap();\n let operand_a = operands.pop().unwrap();\n let result: i32 = match input {\n CalculatorInput::Add => operand_a + operand_b,\n CalculatorInput::Subtract => operand_a - operand_b,\n CalculatorInput::Multiply => operand_a * operand_b,\n CalculatorInput::Divide => operand_a / operand_b,\n CalculatorInput::Value(_) => panic!(\"input did not match value\"),\n };\n operands.push(result);\n }\n }\n }\n\n if operands.len() == 1 {\n return Some(operands.pop().unwrap());\n }\n\n return None;\n}\n" }, { "from": "gpt", "value": "#[derive(Debug)]\npub enum CalculatorInput {\n Add,\n Subtract,\n Multiply,\n Divide,\n Value(i32),\n}\n\npub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {\n let mut operands: Vec<i32> = Vec::new();\n\n for input in inputs {\n match input {\n CalculatorInput::Value(x) => operands.push(*x),\n _ => {\n if operands.len() < 2 {\n return None;\n }\n let operand_b = operands.pop().unwrap();\n let operand_a = operands.pop().unwrap();\n let result: i32 = match input {\n CalculatorInput::Add => operand_a + operand_b,\n CalculatorInput::Subtract => operand_a - operand_b,\n CalculatorInput::Multiply => operand_a * operand_b,\n CalculatorInput::Divide => operand_a / operand_b,\n CalculatorInput::Value(_) => panic!(\"input did not match value\"),\n };\n operands.push(result);\n }\n }\n }\n\n if operands.len() == 1 {\n return Some(operands.pop().unwrap());\n }\n None\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use HashMap in JsObj instead of BTreeMap\n" }, { "from": "human", "value": "use std::collections::btree_map::BTreeMap;\nuse js_types::js_type::{JsType, JsThing};\n\npub struct JsObj {\n proto: Option<Box<JsObj>>,\n dict: BTreeMap<JsType, JsType>,\n}\n\nimpl JsThing for JsObj {}\n\nimpl JsObj {\n pub fn new() -> JsObj {\n JsObj {\n proto: None,\n dict: BTreeMap::new(),\n }\n }\n}\n" }, { "from": "gpt", "value": "use std::collections::hash_map::HashMap;\nuse js_types::js_type::{JsType, JsThing};\n\npub struct JsObj {\n proto: Option<Box<JsObj>>,\n dict: HashMap<JsType, JsType>,\n}\n\nimpl JsThing for JsObj {}\n\nimpl JsObj {\n pub fn new() -> JsObj {\n JsObj {\n proto: None,\n dict: HashMap::new(),\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Print log level for info messages\n\nSigned-off-by: Kaustav Das Modak <ba1ce5b1e09413a89404909d8d270942c5dadd14@yahoo.co.in>\n" }, { "from": "human", "value": "//! Console logger\n\nuse log::*;\n\n/// Logs to console\npub struct CLILogger;\n\nimpl CLILogger {\n pub fn init<'a>(level: &'a str) -> Result<(), SetLoggerError> {\n set_logger(|max_log_level| {\n max_log_level.set(match level {\n \"info\" => LogLevelFilter::Info,\n \"debug\" => LogLevelFilter::Debug,\n \"error\" => LogLevelFilter::Error,\n \"warn\" => LogLevelFilter::Warn,\n \"trace\" => LogLevelFilter::Trace,\n _ => LogLevelFilter::Info\n });\n Box::new(CLILogger)\n })\n }\n}\n\nimpl Log for CLILogger {\n fn enabled(&self, metadata: &LogMetadata) -> bool {\n metadata.level() <= max_log_level()\n }\n\n fn log(&self, record: &LogRecord) {\n if self.enabled(record.metadata()) {\n if record.level() == LogLevel::Info {\n println!(\"{}\", record.args());\n } else {\n println!(\"[{}] - {}\", record.level(), record.args());\n }\n }\n }\n}\n" }, { "from": "gpt", "value": "//! Console logger\n\nuse log::*;\n\n/// Logs to console\npub struct CLILogger;\n\nimpl CLILogger {\n pub fn init<'a>(level: &'a str) -> Result<(), SetLoggerError> {\n set_logger(|max_log_level| {\n max_log_level.set(match level {\n \"info\" => LogLevelFilter::Info,\n \"debug\" => LogLevelFilter::Debug,\n \"error\" => LogLevelFilter::Error,\n \"warn\" => LogLevelFilter::Warn,\n \"trace\" => LogLevelFilter::Trace,\n _ => LogLevelFilter::Info\n });\n Box::new(CLILogger)\n })\n }\n}\n\nimpl Log for CLILogger {\n fn enabled(&self, metadata: &LogMetadata) -> bool {\n metadata.level() <= max_log_level()\n }\n\n fn log(&self, record: &LogRecord) {\n if self.enabled(record.metadata()) {\n println!(\"[{}] - {}\", record.level(), record.args());\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Check if stdin is from a tty\n" }, { "from": "human", "value": "#[test]\nfn it_works() {\n}\n" }, { "from": "gpt", "value": "#![feature(libc)]\nextern crate libc;\n\npub fn readline() -> Option<String> {\n // Buffer to hold readline input\n let buffer = String::new();\n\n let isatty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0; \n if isatty {\n println!(\"stdin is a tty\");\n } else {\n println!(\"stdin is not a tty\");\n }\n\n buffer\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix the procedural macro hygiene stuff.\n" }, { "from": "human", "value": "#![feature(proc_macro_non_items)]\n\npub mod app;\npub mod time;\npub mod render;\n" }, { "from": "gpt", "value": "#![feature(proc_macro_hygiene)]\n\npub mod app;\npub mod time;\npub mod render;\n" } ]
rust
chosen
[ { "from": "system", "value": "identity-service-api: Add crate-level docs and warn on missing docs\n" }, { "from": "human", "value": "#![doc(html_favicon_url = \"https://www.ruma.io/favicon.ico\")]\n#![doc(html_logo_url = \"https://www.ruma.io/images/logo.png\")]\n\npub mod authentication;\npub mod keys;\npub mod status;\npub mod tos;\n" }, { "from": "gpt", "value": "#![doc(html_favicon_url = \"https://www.ruma.io/favicon.ico\")]\n#![doc(html_logo_url = \"https://www.ruma.io/images/logo.png\")]\n//! (De)serializable types for the Matrix Identity Service API.\n\n#![warn(missing_docs)]\n\npub mod authentication;\npub mod keys;\npub mod status;\npub mod tos;\n" } ]
rust
chosen
[ { "from": "system", "value": "Add `i` suffix to cfail test so it works after suffix inference\n" }, { "from": "human", "value": "fn f(f: fn@(int) -> bool) -> bool { f(10) }\n\nfn main() {\n assert do f() { |i| i == 10 } == 10; //! ERROR: expected `bool` but found `int`\n}\n" }, { "from": "gpt", "value": "fn f(f: fn@(int) -> bool) -> bool { f(10i) }\n\nfn main() {\n assert do f() { |i| i == 10i } == 10i; //! ERROR: expected `bool` but found `int`\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make layout SizeOverflow test trigger on i686.\n" }, { "from": "human", "value": "fn main() {\n let data: [u8; std::isize::MAX as usize] = [42; std::isize::MAX as usize];\n //~^ ERROR: rustc layout computation failed: SizeOverflow([u8;\n assert_eq!(data.len(), 1024);\n}\n" }, { "from": "gpt", "value": "fn main() {\n let data: [u8; std::usize::MAX] = [42; std::usize::MAX];\n //~^ ERROR: rustc layout computation failed: SizeOverflow([u8;\n assert_eq!(data.len(), 1024);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add field() and field_mut() to FieldWithHeight\n" }, { "from": "human", "value": "use field::{Field, FieldHeight};\n\npub struct FieldWithHeight<F: Field> {\n field: F,\n height: [u16; 8],\n}\n\nimpl<F: Field> FieldWithHeight<F> {\n pub fn new() -> FieldWithHeight<F> {\n FieldWithHeight::<F> {\n field: F::new(),\n height: [0; 8],\n }\n }\n}\n\nimpl<F: Field> FieldHeight for FieldWithHeight<F> {\n #[inline]\n fn height(&self, x: usize) -> usize {\n self.height[x] as usize\n }\n}\n" }, { "from": "gpt", "value": "use field::{Field, FieldHeight};\n\npub struct FieldWithHeight<F: Field> {\n field: F,\n height: [u16; 8],\n}\n\nimpl<F: Field> FieldWithHeight<F> {\n pub fn new() -> FieldWithHeight<F> {\n FieldWithHeight::<F> {\n field: F::new(),\n height: [0; 8],\n }\n }\n\n pub fn field(&self) -> &F {\n &self.field\n }\n\n pub fn field_mut(&mut self) -> &mut F {\n &mut self.field\n }\n}\n\nimpl<F: Field> FieldHeight for FieldWithHeight<F> {\n #[inline]\n fn height(&self, x: usize) -> usize {\n self.height[x] as usize\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove trailing comma that cause the test to fail compiling on stable\n" }, { "from": "human", "value": "use std::io::{BufRead, BufReader};\nuse std::path::PathBuf;\nuse std::process::{Command, Stdio};\n\n#[test]\nfn test() {\n let path = PathBuf::from(::std::env::args().next().unwrap());\n let exe = path.parent()\n .and_then(|path| path.parent())\n .expect(\"server executable\")\n .join(env!(\"CARGO_PKG_NAME\"));\n let mut child = Command::new(exe).stdout(Stdio::piped()).spawn().unwrap();\n {\n let stdout = child.stdout.as_mut().expect(\"stdout missing\");\n if let None = BufReader::new(stdout)\n .lines()\n .find(|line| line.as_ref().unwrap().starts_with(\"Server started\"))\n {\n panic!(\"Expected the server to start\",);\n }\n }\n child.kill().unwrap();\n}\n" }, { "from": "gpt", "value": "use std::io::{BufRead, BufReader};\nuse std::path::PathBuf;\nuse std::process::{Command, Stdio};\n\n#[test]\nfn test() {\n let path = PathBuf::from(::std::env::args().next().unwrap());\n let exe = path.parent()\n .and_then(|path| path.parent())\n .expect(\"server executable\")\n .join(env!(\"CARGO_PKG_NAME\"));\n let mut child = Command::new(exe).stdout(Stdio::piped()).spawn().unwrap();\n {\n let stdout = child.stdout.as_mut().expect(\"stdout missing\");\n if let None = BufReader::new(stdout)\n .lines()\n .find(|line| line.as_ref().unwrap().starts_with(\"Server started\"))\n {\n panic!(\"Expected the server to start\");\n }\n }\n child.kill().unwrap();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove unneccessary 'extern crate' declaration.\n" }, { "from": "human", "value": "extern crate slog;\n\nuse std::time::Instant;\nuse slog::Logger;\n\n// When this struct is dropped, it logs a message stating its name and how long, in seconds,\n// execution time was. Can be used to time functions or other critical areas.\npub struct ExecutionTimer<'a> {\n\tstart_time: Instant,\n\tname: &'a str,\n\tlogger: &'a Logger\n}\n\nimpl<'a> ExecutionTimer<'a> {\n\t// Construct a new ExecutionTimer, silently.\n\t#[allow(dead_code)]\n\tpub fn new(logger: &'a Logger, name: &'a str) -> ExecutionTimer<'a> {\n\t\tExecutionTimer {\n\t\t\tstart_time: Instant::now(),\n\t\t\tlogger: logger,\n\t\t\tname: name\n\t\t}\n\t}\n\n\t// Construct a new ExecutionTimer and prints a message saying execution is starting.\n\t#[allow(dead_code)]\n\tpub fn new2(logger: &'a Logger, name: &'a str) -> ExecutionTimer<'a> {\n\t\tdebug!(logger, \"Execution Started\"; \"Name\" => name);\n\t\tExecutionTimer::new(logger, name)\n\t}\n}\n\nimpl<'a> Drop for ExecutionTimer<'a> {\n\tfn drop(&mut self) {\n\t\tlet elapsed = self.start_time.elapsed();\n let secs = (elapsed.as_secs() as f64) + (elapsed.subsec_nanos() as f64 / 1000_000_000.0);\n\t\tdebug!(self.logger, \"Execution Completed\"; \"Seconds\" => secs, \"Name\" => self.name);\n\t}\n}\n" }, { "from": "gpt", "value": "use std::time::Instant;\nuse slog::Logger;\n\n// When this struct is dropped, it logs a message stating its name and how long, in seconds,\n// execution time was. Can be used to time functions or other critical areas.\npub struct ExecutionTimer<'a> {\n\tstart_time: Instant,\n\tname: &'a str,\n\tlogger: &'a Logger\n}\n\nimpl<'a> ExecutionTimer<'a> {\n\tpub fn new(logger: &'a Logger, name: &'a str) -> ExecutionTimer<'a> {\n\t\tExecutionTimer {\n\t\t\tstart_time: Instant::now(),\n\t\t\tlogger: logger,\n\t\t\tname: name\n\t\t}\n\t}\n\n\t// Construct a new ExecutionTimer and prints a message saying execution is starting.\n\t#[allow(dead_code)]\n\tpub fn new2(logger: &'a Logger, name: &'a str) -> ExecutionTimer<'a> {\n\t\tdebug!(logger, \"Execution Started\"; \"Name\" => name);\n\t\tExecutionTimer::new(logger, name)\n\t}\n}\n\nimpl<'a> Drop for ExecutionTimer<'a> {\n\tfn drop(&mut self) {\n\t\tlet elapsed = self.start_time.elapsed();\n let secs = (elapsed.as_secs() as f64) + (elapsed.subsec_nanos() as f64 / 1000_000_000.0);\n\t\tdebug!(self.logger, \"Execution Completed\"; \"Seconds\" => secs, \"Name\" => self.name);\n\t}\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Rename read_usize_range to read_range and make it generic\n" }, { "from": "human", "value": "use error::InputError;\nuse std::io;\n\npub fn read_line() -> io::Result<String> {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer)?;\n\n // Trim the right side of the buffer to remove the newline character\n Ok(buffer.trim_right().to_string())\n}\n\npub fn read_usize_range(min: usize, max: usize) -> Result<usize, InputError> {\n loop {\n let input = read_line()\n .map_err(InputError::ReadFailed)?\n .parse()\n .map_err(InputError::IntParseFailed)?;\n\n if input >= min && input <= max {\n return Ok(input);\n } else {\n println!(\"input must be between {}-{}\", min, max);\n }\n }\n}\n\n#[derive(Debug)]\npub enum Answer {\n Yes,\n No,\n}\n\nimpl Into<bool> for Answer {\n fn into(self) -> bool {\n match self {\n Answer::Yes => true,\n Answer::No => false,\n }\n }\n}\n\npub fn read_yn(default: Answer) -> io::Result<bool> {\n let line = read_line()?;\n\n let answer = match line.as_str() {\n \"y\" | \"Y\" => true,\n \"n\" | \"N\" => false,\n _ => default.into(),\n };\n\n Ok(answer)\n}\n" }, { "from": "gpt", "value": "use error::InputError;\nuse std::fmt::{Debug, Display};\nuse std::io;\nuse std::str::FromStr;\n\npub fn read_line() -> io::Result<String> {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer)?;\n\n // Trim the right side of the buffer to remove the newline character\n Ok(buffer.trim_right().to_string())\n}\n\npub fn read_range<T>(min: T, max: T) -> Result<T, InputError>\nwhere\n T: Ord + FromStr + Debug + Display,\n <T as FromStr>::Err: Debug,\n{\n loop {\n let input = read_line()\n .map_err(InputError::ReadFailed)?\n .parse()\n .map_err(|e| InputError::ParseFailed(format!(\"{:?}\", e)))?;\n\n if input >= min && input <= max {\n return Ok(input);\n } else {\n println!(\"input must be between {}-{}\", min, max);\n }\n }\n}\n\n#[derive(Debug)]\npub enum Answer {\n Yes,\n No,\n}\n\nimpl Into<bool> for Answer {\n fn into(self) -> bool {\n match self {\n Answer::Yes => true,\n Answer::No => false,\n }\n }\n}\n\npub fn read_yn(default: Answer) -> io::Result<bool> {\n let line = read_line()?;\n\n let answer = match line.as_str() {\n \"y\" | \"Y\" => true,\n \"n\" | \"N\" => false,\n _ => default.into(),\n };\n\n Ok(answer)\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "[Tests] Add failure case for assert_impl\n" }, { "from": "human", "value": "#![no_std]\n\n#[macro_use]\nextern crate static_assertions;\n\nassert_impl!(byte; u8, Send, Sync);\n\n#[test]\nfn str_impl() {\n assert_impl!(str, Send, Sync, AsRef<[u8]>);\n}\n" }, { "from": "gpt", "value": "#![no_std]\n\n#[macro_use]\nextern crate static_assertions;\n\nassert_impl!(byte; u8, Send, Sync);\n\n#[cfg(feature = \"failure\")]\nassert_impl!(ptr; *const u8, Send, Sync);\n\n#[test]\nfn str_impl() {\n assert_impl!(str, Send, Sync, AsRef<[u8]>);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add struct Tweet and implement Summarizable trait for it\n" }, { "from": "human", "value": "pub trait Summarizable {\n fn summary(&self) -> String;\n}\n\npub struct NewsArticle {\n pub headline: String,\n pub location: String,\n pub author: String,\n pub content: String,\n}\n\nimpl Summarizable for NewsArticle {\n fn summary(&self) -> String {\n format!(\"{}, by {} ({})\", self.headline, self.author, self.location)\n }\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {\n }\n}\n" }, { "from": "gpt", "value": "pub trait Summarizable {\n fn summary(&self) -> String;\n}\n\npub struct NewsArticle {\n pub headline: String,\n pub location: String,\n pub author: String,\n pub content: String,\n}\n\nimpl Summarizable for NewsArticle {\n fn summary(&self) -> String {\n format!(\"{}, by {} ({})\", self.headline, self.author, self.location)\n }\n}\n\npub struct Tweet {\n pub username: String,\n pub content: String,\n pub reply: bool,\n pub retweet: bool,\n}\n\nimpl Summarizable for Tweet {\n fn summary(&self) -> String {\n format!(\"{}: {}\", self.username, self.content)\n }\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make quantization functions work for any block size.\n" }, { "from": "human", "value": "extern {\n static dc_qlookup_Q3: [i16; 256];\n static ac_qlookup_Q3: [i16; 256];\n}\n\npub fn dc_q(qindex: usize) -> i16 {\n unsafe {\n dc_qlookup_Q3[qindex]\n }\n}\n\npub fn ac_q(qindex: usize) -> i16 {\n unsafe {\n ac_qlookup_Q3[qindex]\n }\n}\n\npub fn quantize_in_place(qindex: usize, coeffs: &mut [i32]) {\n coeffs[0] /= dc_q(qindex) as i32;\n for c in coeffs[1..].iter_mut() {\n *c /= ac_q(qindex) as i32;\n }\n coeffs[15] = 0;\n}\n\npub fn dequantize(qindex:usize, coeffs: &[i32], rcoeffs: &mut [i32]) {\n rcoeffs[0] = coeffs[0] * dc_q(qindex) as i32;\n for i in 1..16 {\n rcoeffs[i] = coeffs[i] * ac_q(qindex) as i32;\n }\n}\n" }, { "from": "gpt", "value": "extern {\n static dc_qlookup_Q3: [i16; 256];\n static ac_qlookup_Q3: [i16; 256];\n}\n\npub fn dc_q(qindex: usize) -> i16 {\n unsafe {\n dc_qlookup_Q3[qindex]\n }\n}\n\npub fn ac_q(qindex: usize) -> i16 {\n unsafe {\n ac_qlookup_Q3[qindex]\n }\n}\n\npub fn quantize_in_place(qindex: usize, coeffs: &mut [i32]) {\n coeffs[0] /= dc_q(qindex) as i32;\n for c in coeffs[1..].iter_mut() {\n *c /= ac_q(qindex) as i32;\n }\n // workaround for bug in token coder\n *coeffs.last_mut().unwrap() = 0;\n}\n\npub fn dequantize(qindex:usize, coeffs: &[i32], rcoeffs: &mut [i32]) {\n rcoeffs[0] = coeffs[0] * dc_q(qindex) as i32;\n for i in 1..coeffs.len() {\n rcoeffs[i] = coeffs[i] * ac_q(qindex) as i32;\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update NameAndSpan after rustc refactor\n" }, { "from": "human", "value": "use syntax;\nuse syntax::codemap::DUMMY_SP;\nuse syntax::ext::base::ExtCtxt;\nuse syntax::feature_gate::GatedCfg;\n\n/// Create a fake ExtCtxt to perform macro quasiquotes outside of rustc plugins\npub fn with_fake_extctxt<T, F: Fn(&ExtCtxt) -> T>(f: F) -> T {\n let ps = syntax::parse::ParseSess::new();\n let mut fg_cfg = Vec::<GatedCfg>::new();\n\n let mut cx = syntax::ext::base::ExtCtxt::new(&ps, Vec::new(),\n syntax::ext::expand::ExpansionConfig::default(\"rust-peg\".to_string()),\n &mut fg_cfg\n );\n\n cx.bt_push(syntax::codemap::ExpnInfo{\n call_site: DUMMY_SP,\n callee: syntax::codemap::NameAndSpan {\n name: \"\".to_string(),\n format: syntax::codemap::MacroBang,\n span: None,\n allow_internal_unstable: false,\n }\n });\n\n f(&cx)\n}\n" }, { "from": "gpt", "value": "use syntax;\nuse syntax::codemap::DUMMY_SP;\nuse syntax::ext::base::ExtCtxt;\nuse syntax::feature_gate::GatedCfg;\n\n/// Create a fake ExtCtxt to perform macro quasiquotes outside of rustc plugins\npub fn with_fake_extctxt<T, F: Fn(&ExtCtxt) -> T>(f: F) -> T {\n let ps = syntax::parse::ParseSess::new();\n let mut fg_cfg = Vec::<GatedCfg>::new();\n\n let mut cx = syntax::ext::base::ExtCtxt::new(&ps, Vec::new(),\n syntax::ext::expand::ExpansionConfig::default(\"rust-peg\".to_string()),\n &mut fg_cfg\n );\n\n cx.bt_push(syntax::codemap::ExpnInfo{\n call_site: DUMMY_SP,\n callee: syntax::codemap::NameAndSpan {\n format: syntax::codemap::MacroBang(syntax::parse::token::intern(\"\")),\n span: None,\n allow_internal_unstable: false,\n }\n });\n\n f(&cx)\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use 'static lifetime bound to require that geom is a real struct\n\nThis bound requires that the underlying object implementing the trait\nis a real struct, not a reference or etc. See http://stackoverflow.com/questions/26212397/rust-lang-references-to-traits-in-structs/26213294#26213294 for some more info\n" }, { "from": "human", "value": "//! Defines the DifferentialGeometry type which is used to pass information\n//! about the hit piece of geometry back from the intersection to the shading\n\nuse linalg::{Point, Normal};\nuse geometry::{Geometry, Instance};\n\n/// Stores information about a hit piece of geometry of some object in the scene\n#[deriving(Copy)]\npub struct DifferentialGeometry<'a, 'b> {\n /// The hit point \n pub p: Point,\n /// The shading normal\n pub n: Normal,\n /// The geometry normal\n pub ng: Normal,\n /// The geometry that was hit\n pub geom: &'a (Geometry + 'a),\n /// The instance of geometry that was hit\n pub instance: Option<&'b Instance<'b>>,\n}\n\nimpl<'a, 'b> DifferentialGeometry<'a, 'b> {\n /// Initialize the differential geometry with 0 values for all fields\n /// and None for the hit geometry\n pub fn new(p: &Point, n: &Normal, ng: &Normal, geom: &'a (Geometry + 'a),\n instance: Option<&'b Instance<'b>>) -> DifferentialGeometry<'a, 'b> {\n DifferentialGeometry { p: *p, n: *n, ng: *ng, geom: geom, instance: instance }\n }\n}\n\n" }, { "from": "gpt", "value": "//! Defines the DifferentialGeometry type which is used to pass information\n//! about the hit piece of geometry back from the intersection to the shading\n\nuse linalg::{Point, Normal};\nuse geometry::{Geometry, Instance};\n\n/// Stores information about a hit piece of geometry of some object in the scene\n#[deriving(Copy)]\npub struct DifferentialGeometry<'a, 'b> {\n /// The hit point \n pub p: Point,\n /// The shading normal\n pub n: Normal,\n /// The geometry normal\n pub ng: Normal,\n /// The geometry that was hit\n pub geom: &'a (Geometry + 'static),\n /// The instance of geometry that was hit\n pub instance: Option<&'b Instance<'b>>,\n}\n\nimpl<'a, 'b> DifferentialGeometry<'a, 'b> {\n /// Initialize the differential geometry with 0 values for all fields\n /// and None for the hit geometry\n pub fn new(p: &Point, n: &Normal, ng: &Normal, geom: &'a (Geometry + 'static),\n instance: Option<&'b Instance<'b>>) -> DifferentialGeometry<'a, 'b> {\n DifferentialGeometry { p: *p, n: *n, ng: *ng, geom: geom, instance: instance }\n }\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Allow Rectangle to return its own size as well as width/height\n" }, { "from": "human", "value": "use util::units::{Point, Size};\n\npub struct Rectangle {\n location: Point,\n size: Size,\n}\n\nimpl Rectangle {\n\n pub fn new(location: Point, size: Size) -> Rectangle {\n Rectangle { location: location, size: size }\n }\n\n pub fn move_dir(&self, location: Point) -> Rectangle {\n Rectangle { location: self.location + location, size: self.size }\n }\n\n pub fn resize(&self, size: Size) -> Rectangle {\n Rectangle { location: self.location, size: self.size + size }\n }\n\n pub fn location(&self) -> Point {\n return self.location;\n }\n\n pub fn width(&self) -> i32 {\n return self.size.x;\n }\n\n pub fn height(&self) -> i32 {\n return self.size.y;\n }\n\n}\n" }, { "from": "gpt", "value": "use util::units::{Point, Size};\n\npub struct Rectangle {\n location: Point,\n size: Size,\n}\n\nimpl Rectangle {\n\n pub fn new(location: Point, size: Size) -> Rectangle {\n Rectangle { location: location, size: size }\n }\n\n pub fn move_dir(&self, location: Point) -> Rectangle {\n Rectangle { location: self.location + location, size: self.size }\n }\n\n pub fn resize(&self, size: Size) -> Rectangle {\n Rectangle { location: self.location, size: self.size + size }\n }\n\n pub fn location(&self) -> Point {\n return self.location;\n }\n\n pub fn size(&self) -> Size {\n return self.size;\n }\n\n pub fn width(&self) -> i32 {\n return self.size.x;\n }\n\n pub fn height(&self) -> i32 {\n return self.size.y;\n }\n\n}\n" } ]
rust
chosen
[ { "from": "system", "value": ":art: Make possible to take argument in subcommand\n\n" }, { "from": "human", "value": "extern crate clap;\nextern crate hyper;\n#[macro_use]\nextern crate serde_derive;\nextern crate serde_json;\nextern crate toml;\n\nmod config;\nmod issue;\nmod jira_api;\nmod jira_client;\nmod jira_request;\nmod search_command;\nmod search_response;\nmod workflow;\n\nuse clap::{App, SubCommand};\n\nfn main() {\n let workflow = workflow::new();\n let matches = App::new(\"jira\")\n .version(env!(\"CARGO_PKG_VERSION\"))\n .about(\"Alfred JIRA Workflow.\")\n .subcommand(SubCommand::with_name(\"Search\")\n .about(\"Search JIRA issues\"))\n .get_matches();\n\n if let Some(_) = matches.subcommand_matches(\"search\") {\n match workflow.seach().run(&\"\".to_string()) {\n Ok(_) => (),\n Err(e) => {\n println!(\"{}\", e.to_string());\n std::process::exit(1);\n }\n }\n std::process::exit(0);\n };\n std::process::exit(0);\n}\n" }, { "from": "gpt", "value": "extern crate clap;\nextern crate hyper;\n#[macro_use]\nextern crate serde_derive;\nextern crate serde_json;\nextern crate toml;\n\nmod config;\nmod issue;\nmod jira_api;\nmod jira_client;\nmod jira_request;\nmod search_command;\nmod search_response;\nmod workflow;\n\nuse clap::{Arg, App, SubCommand};\n\nfn main() {\n let workflow = workflow::new();\n let matches = App::new(\"jira\")\n .version(env!(\"CARGO_PKG_VERSION\"))\n .about(\"Alfred JIRA Workflow.\")\n .subcommand(SubCommand::with_name(\"search\")\n .about(\"Search JIRA issues\")\n .arg(Arg::with_name(\"keyword\")\n .required(true)))\n .get_matches();\n\n if let Some(matches) = matches.subcommand_matches(\"search\") {\n if let Some(keyword) = matches.value_of(\"keyword\") {\n match workflow.search().run(&keyword.to_string()) {\n Ok(_) => (),\n Err(e) => {\n println!(\"{}\", e.to_string());\n std::process::exit(1);\n }\n }\n }\n std::process::exit(0);\n };\n std::process::exit(0);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Handle return value in example.\n" }, { "from": "human", "value": "extern crate lcm;\n\n// mod exlcm;\nmod exlcm {\n include!(concat!(env!(\"OUT_DIR\"), \"/exlcm/example_t.rs\"));\n}\n\n// mod exlcm_backup;\n// use exlcm_backup as exlcm;\n\nfn main() {\n let mut lcm = lcm::Lcm::new();\n\n let mut my_data = exlcm::ExampleT::new();\n // let mut my_data = exlcm::Example::new();\n my_data.timestamp = 0;\n\n my_data.position[0] = 1.0;\n my_data.position[1] = 2.0;\n my_data.position[2] = 3.0;\n\n my_data.orientation[0] = 1.0;\n my_data.orientation[1] = 0.0;\n my_data.orientation[2] = 0.0;\n my_data.orientation[3] = 0.0;\n\n my_data.num_ranges = 15;\n my_data.ranges = (0..15).collect();\n\n my_data.name = \"example string\".to_string();\n my_data.enabled = true;\n\n lcm.publish(\"EXAMPLE\", &my_data);\n}\n" }, { "from": "gpt", "value": "extern crate lcm;\n\n// mod exlcm;\nmod exlcm {\n include!(concat!(env!(\"OUT_DIR\"), \"/exlcm/example_t.rs\"));\n}\n\n// mod exlcm_backup;\n// use exlcm_backup as exlcm;\n\nfn main() {\n let mut lcm = lcm::Lcm::new();\n\n let mut my_data = exlcm::ExampleT::new();\n // let mut my_data = exlcm::Example::new();\n my_data.timestamp = 0;\n\n my_data.position[0] = 1.0;\n my_data.position[1] = 2.0;\n my_data.position[2] = 3.0;\n\n my_data.orientation[0] = 1.0;\n my_data.orientation[1] = 0.0;\n my_data.orientation[2] = 0.0;\n my_data.orientation[3] = 0.0;\n\n my_data.num_ranges = 15;\n my_data.ranges = (0..15).collect();\n\n my_data.name = \"example string\".to_string();\n my_data.enabled = true;\n\n match lcm.publish(\"EXAMPLE\", &my_data) {\n Ok(()) => println!(\"Sent message.\"),\n Err(e) => println!(\"Failed to send message: {}\", e)\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Print minimum value as 0%" }, { "from": "human", "value": "# Rust solution via @jrick\n\nuse std::cmp;\nuse std::num::{Int, NumCast};\n\nfn percents<T: Int>(input: &Vec<T>) -> Vec<f64> {\n let mul = f64::from(input.iter().fold(T::zero(), |m, &e| cmp::max(m, e))).unwrap();\n input.iter().map(|elem| mul * f64::from(*elem).unwrap()).collect()\n}\n\nfn main() {\n let input = vec![99334, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99991];\n let out = percents(&input);\n println!(\"{:?}\", out);\n}\n" }, { "from": "gpt", "value": "// Rust solution via @jrick\n\nuse std::cmp;\nuse std::num::{Int, NumCast};\n\nfn percents<T: Int>(input: &Vec<T>) -> Vec<f64> {\n let (min, max) = input.iter().fold((T::max_value(), T::min_value()),\n |m, &e| (cmp::min(m.0, e), cmp::max(m.1, e))\n );\n let diff = f64::from(max - min).unwrap();\n input.iter().map(|elem| f64::from(*elem - min).unwrap() / diff).collect()\n}\n\nfn main() {\n let input = vec![99334, 100, 200, 300, 99991];\n let out = percents(&input);\n println!(\"{:?}\", out);\n}\n" } ]
rust
chosen