Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix bug with wrong variable name in Hero.cr | module Dota
module API
class Hero
include Utilities::Mapped
extend Utilities::Mapped
getter id : Int8 | Int32, name : String
private getter internalName : String
def self.find(id)
if mapping[id]?
new(id)
else
raise Exception.new("Hero does not ex... | module Dota
module API
class Hero
include Utilities::Mapped
extend Utilities::Mapped
getter id : Int8 | Int32, name : String
private getter internalName : String
def self.find(id)
if mapping[id]?
new(id)
else
raise Exception.new("Hero does not ex... |
Add missing require in Amber integration | module Raven
# ```
# require "raven/integrations/amber"
# ```
#
# It's recommended to enable `Configuration#async` when using Amber.
#
# ```
# Raven.configure do |config|
# # ...
# config.async = true
# config.current_environment = Amber.env.to_s
# end
# ```
module Amber
# Returns ... | require "amber"
module Raven
# ```
# require "raven/integrations/amber"
# ```
#
# It's recommended to enable `Configuration#async` when using Amber.
#
# ```
# Raven.configure do |config|
# # ...
# config.async = true
# config.current_environment = Amber.env.to_s
# end
# ```
module Amb... |
Fix for the 031aff... commit | require "./nekogirls-cr/*"
require "kemal"
Kemal.config.port = 8080
Kemal.config.public_folder = "./src/public/"
Kemal.config.host_binding = "localhost"
module Nekogirls
get "/" do
"Hello World"
end
get "/upload" do
render "src/views/form.ecr"
end
post "/upload" do |env|
file = env.params.file... | require "./nekogirls-cr/*"
require "kemal"
Kemal.config.port = 8080
Kemal.config.public_folder = "./src/public/"
Kemal.config.host_binding = "localhost"
module Nekogirls
get "/" do
"Hello World"
end
get "/upload" do
render "src/views/form.ecr"
end
post "/upload" do |env|
file = env.params.file... |
Add type requirements to all the endpoint methods | require "http/client"
require "openssl/ssl/context"
require "./mappings/*"
require "./version"
module Discord
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
USER_AGENT = "DiscordBot (https://github.com/meew0/discordcr, #{Discord::VERSION})"
API_BASE = "https://discordapp.com/api/v6"
d... | require "http/client"
require "openssl/ssl/context"
require "./mappings/*"
require "./version"
module Discord
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
USER_AGENT = "DiscordBot (https://github.com/meew0/discordcr, #{Discord::VERSION})"
API_BASE = "https://discordapp.com/api/v6"
d... |
Fix compatibility with Crystal 0.34 stdlib | module Scry
module EnvironmentConfig
private enum EnvVars
CRYSTAL_CACHE_DIR
CRYSTAL_PATH
CRYSTAL_VERSION
CRYSTAL_LIBRARY_PATH
CRYSTAL_OPTS
end
def self.run
initialize_from_crystal_env.each_with_index do |v, i|
e = EnvVars.from_value(i).to_s
ENV[e] = v
... | module Scry
module EnvironmentConfig
enum EnvVars
CRYSTAL_CACHE_DIR
CRYSTAL_PATH
CRYSTAL_VERSION
CRYSTAL_LIBRARY_PATH
CRYSTAL_OPTS
end
def self.run
initialize_from_crystal_env.each_with_index do |v, i|
e = EnvVars.from_value(i).to_s
ENV[e] = v
end... |
Add session and flash handlers | require "./app"
server = HTTP::Server.new("127.0.0.1", 8080, [
LuckyWeb::HttpMethodOverrideHandler.new,
HTTP::LogHandler.new,
LuckyWeb::ErrorHandler.new(action: Errors::Show),
LuckyWeb::RouteHandler.new,
HTTP::StaticFileHandler.new("./public", false),
])
puts "Listening on http://127.0.0.1:8080..."
server.... | require "./app"
server = HTTP::Server.new("127.0.0.1", 8080, [
LuckyWeb::HttpMethodOverrideHandler.new,
HTTP::LogHandler.new,
LuckyWeb::SessionHandler.new,
LuckyWeb::Flash::Handler.new,
LuckyWeb::ErrorHandler.new(action: Errors::Show),
LuckyWeb::RouteHandler.new,
HTTP::StaticFileHandler.new("./public", f... |
Set to development before_each spec | require "spec"
require "../src/kemal/*"
include Kemal
| require "spec"
require "../src/kemal/*"
include Kemal
Spec.before_each do
Kemal.config.env = "development"
end
|
Improve messaging when SEND_GRID_KEY is missing | BaseEmail.configure do
if Lucky::Env.production?
send_grid_key = ENV.fetch("SEND_GRID_KEY")
settings.adapter = Carbon::SendGridAdapter.new(api_key: send_grid_key)
else
settings.adapter = Carbon::DevAdapter.new
end
end
| BaseEmail.configure do
if Lucky::Env.production?
# If you don't need to send emails, set the adapter to DevAdapter instead:
#
# settings.adapter = Carbon::DevAdapter.new
#
# If you do need emails, get a key from SendGrid and set an ENV variable
send_grid_key = send_grid_key_from_env
sett... |
Disable query logging for `crystal spec` | require "spec"
module GraniteExample
ADAPTERS = ["pg","mysql","sqlite"]
@@model_classes = [] of Granite::ORM::Base.class
extend self
def model_classes
@@model_classes
end
end
require "../src/granite_orm"
require "./spec_models"
GraniteExample.model_classes.each do |model|
model.drop_and_create
end
| require "spec"
module GraniteExample
ADAPTERS = ["pg","mysql","sqlite"]
@@model_classes = [] of Granite::ORM::Base.class
extend self
def model_classes
@@model_classes
end
end
require "../src/granite_orm"
require "./spec_models"
Granite::ORM.settings.logger = ::Logger.new(nil)
GraniteExample.model_cl... |
Write a test for SnowflakeArrayConverter | require "./spec_helper"
struct StructWithSnowflake
JSON.mapping(
data: {type: UInt64, converter: Discord::SnowflakeConverter}
)
end
struct StructWithMaybeSnowflake
JSON.mapping(
data: {type: UInt64 | Nil, converter: Discord::MaybeSnowflakeConverter}
)
end
describe Discord do
describe Discord::Snowf... | require "./spec_helper"
struct StructWithSnowflake
JSON.mapping(
data: {type: UInt64, converter: Discord::SnowflakeConverter}
)
end
struct StructWithMaybeSnowflake
JSON.mapping(
data: {type: UInt64 | Nil, converter: Discord::MaybeSnowflakeConverter}
)
end
struct StructWithSnowflakeArray
JSON.mappin... |
Clean up code and add comments | ch1 = Channel(String).new(16)
gcfile = File.new("Homo_sapiens.GRCh37.67.dna_rm.chromosome.Y.fa")
spawn do
gcfile.each_line() do |line|
ch1.send(line)
end
ch1.close
end
at = 0
gc = 0
while line = ch1.receive?
if line.starts_with?('>')
next
end
line.each_byte() do |chr|
case chr
when 'A', ... | lines_chan = Channel(String).new(16)
# ------------------------------------------------------------------------------
# Loop over the input file in a separate fiber (and thread, if you set the
# CRYSTAL_WORKERS count to something larger than 1), and send its output on a
# channel
# ------------------------------------... |
Implement a very basic request method | module Discordcr
module REST
end
end
| require "http/client"
module Discordcr
module REST
def request(endpoint_key : Symbol, method : String, url: String | URI, headers : HTTP::Headers | Nil, body : String | Nil)
HTTP::Client.exec(method: method, url: url, headers: headers, body: body, tls: true)
end
end
end
|
Handle PUT and DELETE methods | require "./app"
require "colorize"
server = HTTP::Server.new("127.0.0.1", 8080, [
HTTP::ErrorHandler.new,
HTTP::LogHandler.new,
LuckyWeb::RouteHandler.new,
HTTP::StaticFileHandler.new("./public", false),
])
puts "Listening on http://127.0.0.1:8080..."
server.listen
| require "./app"
server = HTTP::Server.new("127.0.0.1", 8080, [
LuckyWeb::HttpMethodOverrideHandler.new,
HTTP::ErrorHandler.new,
HTTP::LogHandler.new,
LuckyWeb::RouteHandler.new,
HTTP::StaticFileHandler.new("./public", false),
])
puts "Listening on http://127.0.0.1:8080..."
server.listen
|
Add a REST method to send a message | require "http/client"
require "openssl/ssl/context"
require "./mappings"
module Discordcr
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
def request(endpoint_key : Symbol, method : String, url : String | URI, headers : HTTP::Headers | Nil, body : String | Nil)
HTTP::Client.exec(method: m... | require "http/client"
require "openssl/ssl/context"
require "./mappings"
module Discordcr
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
def request(endpoint_key : Symbol, method : String, url : String | URI, headers : HTTP::Headers | Nil, body : String | Nil)
HTTP::Client.exec(method: m... |
Set Content-Type after call_next in Kemal::InitHandler | module Kemal
# Kemal::InitHandler is the first handler thus initializes the context with default values such as
# Content-Type, X-Powered-By.
class InitHandler < HTTP::Handler
INSTANCE = new
def call(context)
context.response.content_type = "text/html"
context.response.headers.add "X-Powered-... | module Kemal
# Kemal::InitHandler is the first handler thus initializes the context with default values such as
# Content-Type, X-Powered-By.
class InitHandler < HTTP::Handler
INSTANCE = new
def call(context)
context.response.headers.add "X-Powered-By", "Kemal"
call_next context
context... |
Send username provided by kemalcr/kemal-basic-auth | require "http"
module Raven
module Kemal
# Exception handler capturing all unhandled `Exception`s.
# After capturing exception is re-raised.
#
# ```
# Kemal.config.add_handler(Raven::Kemal::ExceptionHandler.new)
# # ...
# Kemal.run
# ```
class ExceptionHandler
include HTTP::... | require "http"
module Raven
module Kemal
# Exception handler capturing all unhandled `Exception`s.
# After capturing exception is re-raised.
#
# ```
# Kemal.config.add_handler(Raven::Kemal::ExceptionHandler.new)
# # ...
# Kemal.run
# ```
class ExceptionHandler
include HTTP::... |
Remove accidentally included webpack dep | class LuckyCli::Generators::AssetCompiler
include LuckyCli::GeneratorHelpers
def initialize(@project_name : String)
@project_dir = File.join(@project_name)
@template_dir = File.join(__DIR__, "templates")
end
def self.run(project_name : String)
puts "Adding brunch config and static asset directorie... | class LuckyCli::Generators::AssetCompiler
include LuckyCli::GeneratorHelpers
def initialize(@project_name : String)
@project_dir = File.join(@project_name)
@template_dir = File.join(__DIR__, "templates")
end
def self.run(project_name : String)
puts "Adding brunch config and static asset directorie... |
Add <, > and to_byte_ptr functions to Pointer | struct Pointer(T)
def +(other : Int)
self + other.to_i64
end
def -(other : Int)
self - other.to_i64
end
def ==(other : Int)
self == other.to_i64
end
def ==(other : Pointer(_))
self == other
end
def [](offset : Int) : T
(self + offset).value
end
def []=(offset : Int, value : T)
... | struct Pointer(T)
def +(other : Int)
self + other.to_i64
end
def -(other : Int)
self - other.to_i64
end
def <(other : Pointer(_))
self < other
end
def >(other : Pointer(_))
self > other
end
def ==(other : Int)
self == other.to_i64
end
def ==(other : Pointer(_))
self == othe... |
Add a nilable email field to the User mapping (for OAuth2) | require "./converters"
module Discord
struct User
JSON.mapping(
username: String,
id: {type: UInt64, converter: SnowflakeConverter},
discriminator: String,
avatar: String
)
end
struct UserGuild
JSON.mapping(
id: {type: UInt64, converter: SnowflakeConverter},
name:... | require "./converters"
module Discord
struct User
JSON.mapping(
username: String,
id: {type: UInt64, converter: SnowflakeConverter},
discriminator: String,
avatar: String,
email: String?
)
end
struct UserGuild
JSON.mapping(
id: {type: UInt64, converter: SnowflakeC... |
Fix Pointer(T).null? and add Pointer(T).null | struct Pointer(T)
def +(other : Int)
self + other.to_i64
end
def -(other : Int)
self - other.to_i64
end
def <(other : Pointer(_))
self < other
end
def >(other : Pointer(_))
self > other
end
def ==(other : Int)
self == other.to_i64
end
def ==(other : Pointer(_))
self == othe... | struct Pointer(T)
def self.null
new(0_u64)
end
def +(other : Int)
self + other.to_i64
end
def -(other : Int)
self - other.to_i64
end
def <(other : Pointer(_))
self < other
end
def >(other : Pointer(_))
self > other
end
def ==(other : Int)
self == other.to_i64
end
def ==... |
Change endpoints in the app to use the /public directory | #require "./redis2ws/*"
require "kemal"
require "redis"
module Redis2ws
SOCKETS = [] of HTTP::WebSocket
#run redis subscriber in its own fiber
spawn do
redis = Redis.new
redis.subscribe("mychannel") do |on|
on.message do |channel, message|
puts message
SOCKETS.each { |socket| soc... | #require "./redis2ws/*"
require "kemal"
require "redis"
module Redis2ws
SOCKETS = [] of HTTP::WebSocket # which type are the objects in this empty list :O
#run redis subscriber in its own fiber
spawn do
redis = Redis.new
redis.subscribe("mychannel") do |on|
on.message do |channel, message|
... |
Add a nilable bot field to User (for bot accounts) | require "./converters"
module Discord
struct User
JSON.mapping(
username: String,
id: {type: UInt64, converter: SnowflakeConverter},
discriminator: String,
avatar: String,
email: String?
)
end
struct UserGuild
JSON.mapping(
id: {type: UInt64, converter: SnowflakeC... | require "./converters"
module Discord
struct User
JSON.mapping(
username: String,
id: {type: UInt64, converter: SnowflakeConverter},
discriminator: String,
avatar: String,
email: String?,
bot: Bool?
)
end
struct UserGuild
JSON.mapping(
id: {type: UInt64, con... |
Make sure to put the User initializer at the correct place... | require "./converters"
module Discord
# :nodoc:
def initialize(partial : PartialUser)
@username = partial.username.not_nil!
@id = partial.id
@discriminator = partial.discriminator.not_nil!
@avatar = partial.avatar
@email = partial.email
@bot = partial.bot
end
struct User
JSON.mappi... | require "./converters"
module Discord
struct User
# :nodoc:
def initialize(partial : PartialUser)
@username = partial.username.not_nil!
@id = partial.id
@discriminator = partial.discriminator.not_nil!
@avatar = partial.avatar
@email = partial.email
@bot = partial.bot
e... |
Return HTTP error 400 if the filename is broken | require "./nekogirls-cr/*"
require "kemal"
Kemal.config.port = 8080
Kemal.config.public_folder = "./src/public/"
module Nekogirls
get "/" do
"Hello World"
end
get "/upload" do
render "src/views/form.ecr"
end
post "/upload" do |env|
file = env.params.files["file_to_upload"]
filename = file.... | require "./nekogirls-cr/*"
require "kemal"
Kemal.config.port = 8080
Kemal.config.public_folder = "./src/public/"
module Nekogirls
get "/" do
"Hello World"
end
get "/upload" do
render "src/views/form.ecr"
end
post "/upload" do |env|
file = env.params.files["file_to_upload"]
filename = file.... |
Check if next handler is present before calling it or a 404 will be triggered by Crystal | module Soil
module Http
module Handlers
class MainHandler
include HTTP::Handler
def initialize(app_class : App.class)
@app_class = app_class
end
def call(raw_context)
context = build_context(raw_context)
@app_class
.find(context.req... | module Soil
module Http
module Handlers
class MainHandler
include HTTP::Handler
def initialize(app_class : App.class)
@app_class = app_class
end
def call(raw_context)
context = build_context(raw_context)
@app_class
.find(context.re... |
Fix wrong filter name in filter documentation | require "./base"
module Liquid::Filters
# strip_newlines
#
# Removes any newline characters (line breaks) from a string.
#
# Input
# {% capture string_with_newlines %}
# Hello
# there
# {% endcapture %}
#
# {{ string_with_newlines | newline_to_br }}
#
# Output
# Hellothere
class StripNe... | require "./base"
module Liquid::Filters
# strip_newlines
#
# Removes any newline characters (line breaks) from a string.
#
# Input
# {% capture string_with_newlines %}
# Hello
# there
# {% endcapture %}
#
# {{ string_with_newlines | strip_newlines }}
#
# Output
# Hellothere
class StripN... |
Add a TODO to remind me of the body_io problem | require "http/client"
require "openssl/ssl/context"
require "./mappings"
module Discordcr
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
def request(endpoint_key : Symbol, method : String, url : String | URI, headers : HTTP::Headers | Nil, body : String | Nil)
HTTP::Client.exec(method: m... | require "http/client"
require "openssl/ssl/context"
require "./mappings"
module Discordcr
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
def request(endpoint_key : Symbol, method : String, url : String | URI, headers : HTTP::Headers | Nil, body : String | Nil)
HTTP::Client.exec(method: m... |
Make sure to convert the heartbeat_interval to an int | require "http/web_socket"
require "json"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = URI.parse(gateway.url)
@websocket = websocket = HTTP::WebSocket.new(
host: url.host.not_nil!,
path... | require "http/web_socket"
require "json"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = URI.parse(gateway.url)
@websocket = websocket = HTTP::WebSocket.new(
host: url.host.not_nil!,
path... |
Use localhost for the RouteHelper | # This is used when generating URLs for your application
Lucky::RouteHelper.configure do |settings|
if Lucky::Env.production?
# Example: https://my_app.com
settings.base_uri = ENV.fetch("APP_DOMAIN")
else
# Set domain to the default host/port in development/test
settings.base_uri = "http://#{Lucky::... | # This is used when generating URLs for your application
Lucky::RouteHelper.configure do |settings|
if Lucky::Env.production?
# Example: https://my_app.com
settings.base_uri = ENV.fetch("APP_DOMAIN")
else
# Set domain to the default host/port in development/test
settings.base_uri = "http://localhost... |
Append newline after nodes with children | require "./TreeVisitor.cr"
module Charly::AST
# Dump a human-readable version of the AST
class DumpVisitor < TreeVisitor
# Catch all rule
visit ASTNode do
io.puts name node
rest children
end
visit StringLiteral do
io << name node
io << " | "
io.puts "\"#{node.value}... | require "./TreeVisitor.cr"
module Charly::AST
# Dump a human-readable version of the AST
class DumpVisitor < TreeVisitor
# Catch all rule
visit ASTNode do
io.puts name node
rest children
end
visit StringLiteral do
io << name node
io << " | "
io.puts "\"#{node.value}... |
Fix `Logger.deansify` not accepting types other than String | require "logger"
class Logger
private LOGGER_BREADCRUMB_LEVELS = {
Severity::DEBUG => Raven::Breadcrumb::Severity::DEBUG,
Severity::INFO => Raven::Breadcrumb::Severity::INFO,
Severity::WARN => Raven::Breadcrumb::Severity::WARNING,
Severity::ERROR => Raven::Breadcrumb::Severity::ERROR,
Severity:... | require "logger"
class Logger
private LOGGER_BREADCRUMB_LEVELS = {
Severity::DEBUG => Raven::Breadcrumb::Severity::DEBUG,
Severity::INFO => Raven::Breadcrumb::Severity::INFO,
Severity::WARN => Raven::Breadcrumb::Severity::WARNING,
Severity::ERROR => Raven::Breadcrumb::Severity::ERROR,
Severity:... |
Include the REST module in Client | module Discordcr
class Client
def initialize(@token : String, @client_id : UInt64)
end
def run
end
end
end
| require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
end
end
end
|
Fix RemoveCircularReferences to play nice with types | module Raven
class Processor::RemoveCircularReferences < Processor
def process(data, visited = [] of UInt64)
return data unless data.responds_to? :object_id
return "(...)" if visited.includes? data.object_id
case data
when AnyHash::JSON
visited << data.to_h.object_id
data.... | module Raven
class Processor::RemoveCircularReferences < Processor
def process(data, visited = [] of UInt64)
return data unless data.responds_to? :object_id
return "(...)" if visited.includes? data.object_id
case data
when AnyHash::JSON
visited << data.to_h.object_id
data.... |
Fix wrong argument usage in HTTPExceptions | module Amethyst
module Exceptions
class HttpException < AmethystException
getter :status
getter :msg
def initialize(@status, @msg)
super()
end
end
class UnknownContentType < AmethystException
def initialize(@ext)
super("Unknown content-type for file extensi... | module Amethyst
module Exceptions
class HttpException < AmethystException
getter :status
getter :msg
def initialize(@status, @msg)
super()
end
end
class UnknownContentType < AmethystException
def initialize(@ext : String)
super("Unknown content-type for fil... |
Add version information on errors | require "./franklin"
require "option_parser"
config_path = Franklin::Config::DEFAULT_FILE_LOCATION
filter_type = nil
parser = OptionParser.parse! { |parser|
parser.banner = "Usage: frankling [options] search_term1 search_term2..."
parser.on("-h", "--help", "Prints this help") do
puts parser
puts "Frankli... | require "./franklin"
require "option_parser"
config_path = Franklin::Config::DEFAULT_FILE_LOCATION
filter_type = nil
parser = OptionParser.parse! { |parser|
parser.banner = "Usage: frankling [options] search_term1 search_term2..."
parser.on("-h", "--help", "Prints this help") do
puts parser
puts "Frankli... |
Add CSRF meta tags to layout | abstract class MainLayout
include Lucky::HTMLPage
include Shared::FieldErrorsComponent
include Shared::FlashComponent
# You can put things here that all pages need
#
# Example:
# needs current_user : User
needs flash : Lucky::Flash::Store
abstract def inner
def render
html_doctype
html... | abstract class MainLayout
include Lucky::HTMLPage
include Shared::FieldErrorsComponent
include Shared::FlashComponent
# You can put things here that all pages need
#
# Example:
# needs current_user : User
needs flash : Lucky::Flash::Store
abstract def inner
def render
html_doctype
html... |
Make the type field possibly be nil (apparently it is sometimes) | require "json"
require "time/format"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
str = parser.read_string_or_null
str.not_nil!.to_u64
end
def self.to_json(value : UInt64, io : IO)
io.puts(value.to_s)
end
end
module REST
#... | require "json"
require "time/format"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
str = parser.read_string_or_null
str.not_nil!.to_u64
end
def self.to_json(value : UInt64, io : IO)
io.puts(value.to_s)
end
end
module REST
#... |
Add colours to log messages | require "logger"
# Logger #######################################################################
LOG = Logger.new(STDOUT)
LOG.level = Logger::INFO
LOG.formatter = Logger::Formatter.new do |severity, _datetime, _progname, message, io|
io << case severity
when "DEBUG"
":: "
when "INFO"
">> "
when "WARN... | require "logger"
require "colorize"
# Logger #######################################################################
LOG = Logger.new(STDOUT)
LOG.level = Logger::INFO
LOG.formatter = Logger::Formatter.new do |severity, _datetime, _progname, message, io|
io << case severity
when "DEBUG"
":: ".colorize.white
... |
Use Hash composition over inheritance in ValueHash | module Optarg
# :nodoc:
abstract class ValueHash(V) < Hash(String, V)
@fallbacked = {} of String => Bool
@parser : Parser
def initialize(@parser)
super()
end
def [](key)
fallback key
super
end
def []?(key)
fallback key
super
end
def fallback(key)... | module Optarg
# :nodoc:
abstract class ValueHash(V)
@raw = {} of String => V
forward_missing_to @raw
@fallbacked = {} of String => Bool
@parser : Parser
def initialize(@parser)
end
def ==(other : Hash)
@raw == other
end
def [](key)
fallback key
@raw[key]
... |
Add AddReactions value (1<<6) to Permissions enum | module Discord
@[Flags]
enum Permissions : UInt64
CreateInstantInvite = 1
KickMembers = 1 << 1
BanMembers = 1 << 2
Administrator = 1 << 3
ManageChannels = 1 << 4
ManageGuild = 1 << 5
ReadMessages = 1 << 10
SendMessages = 1 << 11
S... | module Discord
@[Flags]
enum Permissions : UInt64
CreateInstantInvite = 1
KickMembers = 1 << 1
BanMembers = 1 << 2
Administrator = 1 << 3
ManageChannels = 1 << 4
ManageGuild = 1 << 5
AddReactions = 1 << 6
ReadMessages = 1 << 10
Se... |
Use the correct method for the request | require "http/client"
require "openssl/ssl/context"
require "./mappings"
module Discordcr
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
def request(endpoint_key : Symbol, method : String, url : String | URI, headers : HTTP::Headers | Nil, body : String | Nil)
HTTP::Client.exec(method: m... | require "http/client"
require "openssl/ssl/context"
require "./mappings"
module Discordcr
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
def request(endpoint_key : Symbol, method : String, url : String | URI, headers : HTTP::Headers | Nil, body : String | Nil)
HTTP::Client.exec(method: m... |
Use `Crystal::DESCRIPTION` instead of spawning `crystal -v` | module Raven
class Context
# FIXME
# @[ThreadLocal]
@@current : self?
def self.current
@@current ||= new
end
def self.clear!
@@current = nil
end
class_getter os_context : AnyHash::JSON do
{
name: Raven.sys_command("uname -s"),
version: ... | module Raven
class Context
# FIXME
# @[ThreadLocal]
@@current : self?
def self.current
@@current ||= new
end
def self.clear!
@@current = nil
end
class_getter os_context : AnyHash::JSON do
{
name: Raven.sys_command("uname -s"),
version: ... |
Add a mapping for the GUILD_INTEGRATIONS_UPDATE dispatch payload | require "./converters"
require "./user"
require "./channel"
require "./guild"
module Discord
module Gateway
struct ReadyPayload
JSON.mapping(
v: UInt8,
user: User,
private_channels: Array(PrivateChannel),
guilds: Array(UnavailableGuild),
session_id: String
)
... | require "./converters"
require "./user"
require "./channel"
require "./guild"
module Discord
module Gateway
struct ReadyPayload
JSON.mapping(
v: UInt8,
user: User,
private_channels: Array(PrivateChannel),
guilds: Array(UnavailableGuild),
session_id: String
)
... |
Fix receive on closed chan error | ch1 = Channel(String).new(16)
gcfile = File.new("Homo_sapiens.GRCh37.67.dna_rm.chromosome.Y.fa")
spawn do
gcfile.each_line() do |line|
ch1.send(line)
end
ch1.close
end
at = 0
gc = 0
while line = ch1.receive
if line.starts_with?('>')
next
end
line.each_byte() do |chr|
case chr
when 'A', '... | ch1 = Channel(String).new(16)
gcfile = File.new("Homo_sapiens.GRCh37.67.dna_rm.chromosome.Y.fa")
spawn do
gcfile.each_line() do |line|
ch1.send(line)
end
ch1.close
end
at = 0
gc = 0
while line = ch1.receive?
if line.starts_with?('>')
next
end
line.each_byte() do |chr|
case chr
when 'A', ... |
Simplify logic just a bit | require "any_hash"
require "./raven/ext/*"
require "./raven/mixins/*"
require "./raven/*"
module Raven
# `Raven.instance` delegators.
module Delegators
delegate :context, :configuration, :client,
:report_status, :configure, :send_feedback, :send_event,
:capture, :last_event_id, :annotate_exception... | require "any_hash"
require "./raven/ext/*"
require "./raven/mixins/*"
require "./raven/*"
module Raven
# `Raven.instance` delegators.
module Delegators
delegate :context, :configuration, :client,
:report_status, :configure, :send_feedback, :send_event,
:capture, :last_event_id, :annotate_exception... |
Add a newline to separate text from example code | abstract class LuckyCli::Task
macro inherited
LuckyCli::Runner.tasks << self.new
def name
"{{@type.name.gsub(/::/, ".").underscore}}"
end
end
macro banner(banner_text)
def banner
{{banner_text}}
end
end
# Set a custom title for the task
#
# By default the name is derived... | abstract class LuckyCli::Task
macro inherited
LuckyCli::Runner.tasks << self.new
def name
"{{@type.name.gsub(/::/, ".").underscore}}"
end
end
macro banner(banner_text)
def banner
{{banner_text}}
end
end
# Sets a custom title for the task
#
# By default the name is derive... |
Add a rudimentary close handler | require "http/web_socket"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = gateway.url
url += "?v=6&encoding=json"
@websocket = websocket = HTTP::WebSocket.new(URI.parse(url))
websocket.on_mes... | require "http/web_socket"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = gateway.url
url += "?v=6&encoding=json"
@websocket = websocket = HTTP::WebSocket.new(URI.parse(url))
websocket.on_mes... |
Clarify what '4' represents in encryption cost | require "./server"
Authentic.configure do
settings.secret_key = Lucky::Server.settings.secret_key_base
unless Lucky::Env.production?
settings.encryption_cost = 4
end
end
| require "./server"
Authentic.configure do
settings.secret_key = Lucky::Server.settings.secret_key_base
unless Lucky::Env.production?
fastest_encryption_possible = 4
settings.encryption_cost = fastest_encryption_possible
end
end
|
Write a test for MaybeSnowflakeConverter | require "./spec_helper"
struct StructWithSnowflake
JSON.mapping(
data: {type: UInt64, converter: Discord::SnowflakeConverter}
)
end
describe Discord do
describe Discord::SnowflakeConverter do
it "converts a string to u64" do
json = %({"data":"10000000000"})
obj = StructWithSnowflake.from_js... | require "./spec_helper"
struct StructWithSnowflake
JSON.mapping(
data: {type: UInt64, converter: Discord::SnowflakeConverter}
)
end
struct StructWithMaybeSnowflake
JSON.mapping(
data: {type: UInt64 | Nil, converter: Discord::MaybeSnowflakeConverter}
)
end
describe Discord do
describe Discord::Snowf... |
Clean up code and comments | #require "./redis2ws/*"
require "kemal"
require "redis"
module Redis2ws
SOCKETS = [] of HTTP::WebSocket
puts "now here"
get "/" do |ctx|
send_file ctx, "src/web/index.html"
end
get "/app.js" do |ctx|
send_file ctx, "src/web/app.js"
end
ws "/eventstream/" do |socket|
# Add the client to ... | #require "./redis2ws/*"
require "kemal"
require "redis"
module Redis2ws
SOCKETS = [] of HTTP::WebSocket
#run redis subscriber in its own fiber
spawn do
redis = Redis.new
redis.subscribe("mychannel") do |on|
on.message do |channel, message|
puts message
SOCKETS.each { |socket| soc... |
Replace cut command with Crystal code | require "ecr/macros"
module Artanis
# TODO: render views in subpaths (eg: views/blog/posts/show.ecr => render_blog_posts_show_ecr)
module Render
macro ecr(name, layout = "layout")
render {{ name }}, "ecr", layout: {{ layout }}
end
macro render(name, engine, layout = "layout")
{% if layout ... | require "ecr/macros"
module Artanis
# TODO: render views in subpaths (eg: views/blog/posts/show.ecr => render_blog_posts_show_ecr)
module Render
macro ecr(name, layout = "layout")
render {{ name }}, "ecr", layout: {{ layout }}
end
macro render(name, engine, layout = "layout")
{% if layout ... |
Optimize CommonLogHandler to directly use the handler instead of string interpolation | require "http"
class Kemal::CommonLogHandler < Kemal::BaseLogHandler
@handler : IO::FileDescriptor
getter handler
def initialize(@env)
@handler = if @env == "production"
handler = File.new("kemal.log", "a")
handler.flush_on_newline = true
handler
... | require "http"
class Kemal::CommonLogHandler < Kemal::BaseLogHandler
@handler : IO::FileDescriptor
getter handler
def initialize(@env)
@handler = if @env == "production"
handler = File.new("kemal.log", "a")
handler.flush_on_newline = true
handler
... |
Replace -v flag with version in CLI | require "commander"
require "logger"
require "./crow.cr"
cli = Commander::Command.new do |cmd|
cmd.use = "crow"
cmd.long = "Transpile Crystal to Flow (JS) code."
cmd.flags.add do |flag|
flag.name = "verbose"
flag.short = "-v"
flag.long = "--verbose"
flag.default = false
flag.description = "... | require "commander"
require "logger"
require "./crow.cr"
cli = Commander::Command.new do |cmd|
cmd.use = "crow"
cmd.long = "Transpile Crystal to Flow (JS) code."
cmd.flags.add do |flag|
flag.name = "version"
flag.short = "-v"
flag.long = "--version"
flag.default = false
flag.description = "... |
Add a method to PartialUser to check whether it has all data | require "./converters"
module Discord
struct User
JSON.mapping(
username: String,
id: {type: UInt64, converter: SnowflakeConverter},
discriminator: String,
avatar: {type: String, nilable: true},
email: {type: String, nilable: true},
bot: {type: Bool, nilable: true}
)
end... | require "./converters"
module Discord
struct User
JSON.mapping(
username: String,
id: {type: UInt64, converter: SnowflakeConverter},
discriminator: String,
avatar: {type: String, nilable: true},
email: {type: String, nilable: true},
bot: {type: Bool, nilable: true}
)
end... |
Add basic READY handling to the dispatch handler | require "http/web_socket"
require "json"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = URI.parse(gateway.url)
@websocket = websocket = HTTP::WebSocket.new(
host: url.host.not_nil!,
path... | require "http/web_socket"
require "json"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = URI.parse(gateway.url)
@websocket = websocket = HTTP::WebSocket.new(
host: url.host.not_nil!,
path... |
Add instance types for Crystal 0.16.0 | module Kemal::Exceptions
class RouteNotFound < Exception
def initialize(context)
super "Requested path: '#{context.request.override_method as String}:#{context.request.path}' was not found."
end
end
class CustomException < Exception
getter context
def initialize(@context)
super "Rend... | module Kemal::Exceptions
class RouteNotFound < Exception
def initialize(context)
super "Requested path: '#{context.request.override_method as String}:#{context.request.path}' was not found."
end
end
class CustomException < Exception
def initialize(context)
super "Rendered error with #{co... |
Create a mapping for the gateway request response | require "json"
module Discordcr
module Mappings
end
end
| require "json"
module Discordcr
module REST
# A response to the Get Gateway REST API call.
class GatewayResponse
JSON.mapping (
url: String
)
end
end
end
|
Fix the typing for on_message | require "http/web_socket"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = gateway.url
url += "?v=6&encoding=json"
@websocket = HTTP::WebSocket.new(URI.parse(url))
@websocket.not_nil!.on_messa... | require "http/web_socket"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = gateway.url
url += "?v=6&encoding=json"
@websocket = HTTP::WebSocket.new(URI.parse(url))
@websocket.not_nil!.on_messa... |
Add support for exception messages | class Exception
def self.new(message) : NoReturn
panic
end
end
class TypeCastError < Exception
def self.new(message) : NoReturn
super message
end
end
| class Exception
def self.new(message, __file__ = __FILE__, __line__ = __LINE__) : NoReturn
panic message, __file__, __line__
end
end
class TypeCastError < Exception
def self.new(message, __file__ = __FILE__, __line__ = __LINE__) : NoReturn
super message, __file__, __line__
end
end
|
Fix bug in Crystal code | gcfile = File.new("Homo_sapiens.GRCh37.67.dna_rm.chromosome.Y.fa")
at = 0
gc = 0
a = 65_u8
t = 84_u8
g = 71_u8
c = 67_u8
gcfile.each_line() do |line|
if line.starts_with?('>')
next
end
line.each_byte() do |c|
case c
when a, t
at += 1
next
when g, c
gc += 1
next
end
... | gcfile = File.new("Homo_sapiens.GRCh37.67.dna_rm.chromosome.Y.fa")
at = 0
gc = 0
a = 65_u8
t = 84_u8
g = 71_u8
c = 67_u8
gcfile.each_line() do |line|
if line.starts_with?('>')
next
end
line.each_byte() do |chr|
case chr
when a, t
at += 1
next
when g, c
gc += 1
next
e... |
Return nil from on_message to satisfy the compiler | require "http/web_socket"
require "json"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = URI.parse(gateway.url)
@websocket = websocket = HTTP::WebSocket.new(
host: url.host.not_nil!,
path... | require "http/web_socket"
require "json"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = URI.parse(gateway.url)
@websocket = websocket = HTTP::WebSocket.new(
host: url.host.not_nil!,
path... |
Fix naming warning raised by crystal compiler about positional names being mismatched | module Amber::Router::Session
# All Session Stores should implement the following API
abstract class AbstractStore
abstract def id
abstract def destroy
abstract def update(other_hash : Hash(String | Symbol, String))
abstract def set_session
abstract def current_session
end
end
| module Amber::Router::Session
# All Session Stores should implement the following API
abstract class AbstractStore
abstract def id
abstract def destroy
abstract def update(hash : Hash(String | Symbol, String))
abstract def set_session
abstract def current_session
end
end
|
Add a mapping for permission overwrites | require "json"
require "time/format"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
str = parser.read_string_or_null
str.not_nil!.to_u64
end
def self.to_json(value : UInt64, io : IO)
io.puts(value.to_s)
end
end
module REST
#... | require "json"
require "time/format"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
str = parser.read_string_or_null
str.not_nil!.to_u64
end
def self.to_json(value : UInt64, io : IO)
io.puts(value.to_s)
end
end
module REST
#... |
Fix Client::State exponential backoff logic | module Raven
class Client::State
enum Status
ONLINE
ERROR
end
@status : Status
@retry_number : Int32
@last_check : Time?
@retry_after : Time::Span?
def initialize
@status = Status::ONLINE
@retry_number = 0
end
def should_try?
return true if @status.... | module Raven
class Client::State
enum Status
ONLINE
ERROR
end
@status : Status
@retry_number : Int32
@last_check : Time?
@retry_after : Time::Span?
def initialize
@status = Status::ONLINE
@retry_number = 0
end
def should_try?
return true if @status.... |
Sort platform repos and add aliases | module Mnd
PLATFORMS = {
"prime" => [
Repo.new("mynewsdesk", color: :cyan),
Repo.new("social-media-monitor", color: :green),
Repo.new("mnd-audience", color: :light_cyan, alias: "audience"),
Repo.new("mnd-langdetect", color: :light_yellow),
Repo.new("audience-api", color: :yellow),
... | module Mnd
PLATFORMS = {
"prime" => [
Repo.new("audience-api", color: :yellow),
Repo.new("mnd-audience", color: :light_cyan, alias: "audience"),
Repo.new("mnd-events-api", color: :yellow, alias: "events-api"),
Repo.new("mnd-langdetect", color: :light_yellow, alias: "langdetect"),
Rep... |
Fix [] operator on Pointer(T) | struct Pointer(T)
def +(other : Int)
self + other.to_i64
end
def [](offset : Int) : T
self.value
end
def []=(offset : Int, value : T)
(self + offset).value = value
end
end | struct Pointer(T)
def +(other : Int)
self + other.to_i64
end
def [](offset : Int) : T
(self + offset).value
end
def []=(offset : Int, value : T)
(self + offset).value = value
end
end |
Change the PIT struct to a module | private PIT_CH0_DATA = 0x40_u16
private PIT_CH1_DATA = 0x41_u16
private PIT_CH2_DATA = 0x42_u16
private PIT_COMMAND = 0x43_u16
private PIT_FREQ = 1193182_u32
struct PIT
@@ticks = 0_u64
@@divisor = 0_u32
@@frequency = 0_u32
def self.setup(frequency : Int)
divisor = PIT_FREQ / frequency
outb PIT_COMMAND... | private PIT_CH0_DATA = 0x40_u16
private PIT_CH1_DATA = 0x41_u16
private PIT_CH2_DATA = 0x42_u16
private PIT_COMMAND = 0x43_u16
private PIT_FREQ = 1193182_u32
module PIT
extend self
@@ticks = 0_u64
@@divisor = 0_u32
@@frequency = 0_u32
def setup(frequency : Int)
divisor = PIT_FREQ / frequency
outb P... |
Add missing `.new` call in Lucky::ErrorHandler docs | require "http"
require "../http/*"
module Raven
module Lucky
# Exception handler capturing all unhandled `Exception`s.
# After capturing exception is re-raised.
#
# ```
# server = HTTP::Server.new([
# # ...
# Lucky::ErrorHandler.new(action: Errors::Show),
# Raven::Lucky::ErrorHa... | require "http"
require "../http/*"
module Raven
module Lucky
# Exception handler capturing all unhandled `Exception`s.
# After capturing exception is re-raised.
#
# ```
# server = HTTP::Server.new([
# # ...
# Lucky::ErrorHandler.new(action: Errors::Show),
# Raven::Lucky::ErrorHa... |
Include the responsive_meta_tag by default in the main layout | abstract class MainLayout
include Lucky::HTMLPage
include Shared::FieldErrorsComponent
include Shared::FlashComponent
# You can put things here that all pages need
#
# Example:
# needs current_user : User
abstract def content
def render
html_doctype
html lang: "en" do
head do
... | abstract class MainLayout
include Lucky::HTMLPage
include Shared::FieldErrorsComponent
include Shared::FlashComponent
# You can put things here that all pages need
#
# Example:
# needs current_user : User
abstract def content
def render
html_doctype
html lang: "en" do
head do
... |
Fix the typing of the on_message call | require "http/web_socket"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = gateway.url
url += "?v=6&encoding=json"
@websocket = HTTP::WebSocket.new(URI.parse(url))
end
private def on_messag... | require "http/web_socket"
require "./rest"
module Discordcr
class Client
include REST
def initialize(@token : String, @client_id : UInt64)
end
def run
url = gateway.url
url += "?v=6&encoding=json"
@websocket = HTTP::WebSocket.new(URI.parse(url))
@websocket.on_message(->on_m... |
Print Graph API error in rescue block | module Messenger::Bot
# A wrapper for Facebook's Graph API
class GraphAPI
# Build an API instance with which you can send messages.
# Pass *api_version* (current is 2.6) an *access_token*, which you need to
# authenticate yourself to the Graph API
def initialize(@api_version : String, @access_token ... | module Messenger::Bot
# A wrapper for Facebook's Graph API
class GraphAPI
# Build an API instance with which you can send messages.
# Pass *api_version* (current is 2.6) an *access_token*, which you need to
# authenticate yourself to the Graph API
def initialize(@api_version : String, @access_token ... |
Hide GC warnings in all builds | lib LibGC
alias WarnProc = LibC::Char*, Word ->
fun set_warn_proc = GC_set_warn_proc(WarnProc)
$warn_proc = GC_current_warn_proc : WarnProc
end
LibGC.set_warn_proc ->(msg, word) {
# Ignore the message in production builds
{% unless flag?(:release) %}
puts String.new(msg)
{% end %}
}
| lib LibGC
alias WarnProc = LibC::Char*, Word ->
fun set_warn_proc = GC_set_warn_proc(WarnProc)
$warn_proc = GC_current_warn_proc : WarnProc
end
LibGC.set_warn_proc ->(msg, word) {
# Ignore the message
}
|
Install turbolinks and rails-ujs by default | class LuckyCli::Generators::Webpack
include LuckyCli::GeneratorHelpers
def initialize(@project_name : String)
@project_dir = File.join(@project_name)
@template_dir = File.join(__DIR__, "templates")
end
def self.run(project_name : String)
puts "Adding webpacker config and asset directories"
new... | class LuckyCli::Generators::Webpack
include LuckyCli::GeneratorHelpers
def initialize(@project_name : String)
@project_dir = File.join(@project_name)
@template_dir = File.join(__DIR__, "templates")
end
def self.run(project_name : String)
puts "Adding webpacker config and asset directories"
new... |
Add % override to Int | struct Int
def <<(count) unsafe_shl count end
def >>(count) unsafe_shr count end
def ===(other : Int) self == other end
def /(other : Int)
if other == 0
self
end
unsafe_div other
end
def times
i = 0
while i < self
yield i
... | struct Int
def <<(count) unsafe_shl count end
def >>(count) unsafe_shr count end
def ===(other : Int) self == other end
def /(other : Int)
if other == 0
self
end
unsafe_div other
end
def %(other : Int)
if other == 0
self
end
... |
Order default by id for now | require "kemal"
require "kemal-session"
module Vulnsearch
class HomeController
get "/" do |env|
query = env.params.query.fetch("q", "")
render_default "home/index"
end
get "/search" do |env|
query = env.params.query.fetch("q", "")
like_query = "%#{query}%"
cves = Cve.from_r... | require "kemal"
require "kemal-session"
module Vulnsearch
class HomeController
get "/" do |env|
query = env.params.query.fetch("q", "")
render_default "home/index"
end
get "/search" do |env|
query = env.params.query.fetch("q", "")
like_query = "%#{query}%"
cves = Cve.from_r... |
Upgrade to a newer version of matcher protocol | module Mocks
class HaveReceivedExpectation
def initialize(@receive)
end
def match(@target)
method.received?(oid, @receive.args)
end
def failure_message
"expected: #{expected}\n got: #{got}"
end
def negative_failure_message
"expected: receive != #{expected}\n go... | module Mocks
class HaveReceivedExpectation
def initialize(@receive)
end
def match(@target)
method.received?(oid, @receive.args)
end
def failure_message
"expected: #{expected}\n got: #{got}"
end
def failure_message(_ignored)
failure_message
end
def negative... |
Fix method type spec so it returns the correct error. | def accepts_int(int: Int)
puts int
end
accepts_int("Not a String.")
| def accepts_int(int : Int)
puts int
end
accepts_int("Not a String.")
|
Add a method for the get channel endpoint | require "http/client"
require "openssl/ssl/context"
require "./mappings/*"
require "./version"
module Discord
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
USER_AGENT = "DiscordBot (https://github.com/meew0/discordcr, #{Discord::VERSION})"
API_BASE = "https://discordapp.com/api/v6"
d... | require "http/client"
require "openssl/ssl/context"
require "./mappings/*"
require "./version"
module Discord
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
USER_AGENT = "DiscordBot (https://github.com/meew0/discordcr, #{Discord::VERSION})"
API_BASE = "https://discordapp.com/api/v6"
d... |
Add a mapping for the payload used by dispatches dealing with bans | require "./converters"
require "./user"
require "./channel"
module Discord
module Gateway
struct ReadyPayload
JSON.mapping(
v: UInt8,
user: User,
private_channels: Array(PrivateChannel),
guilds: Array(UnavailableGuild),
session_id: String
)
end
struct ... | require "./converters"
require "./user"
require "./channel"
module Discord
module Gateway
struct ReadyPayload
JSON.mapping(
v: UInt8,
user: User,
private_channels: Array(PrivateChannel),
guilds: Array(UnavailableGuild),
session_id: String
)
end
struct ... |
Use unique email address in UserBox | class UserBox < Avram::Box
def initialize
email "test@example.com"
encrypted_password Authentic.generate_encrypted_password("password")
end
end
| class UserBox < Avram::Box
def initialize
email "#{sequence("test-email")}@example.com"
encrypted_password Authentic.generate_encrypted_password("password")
end
end
|
Simplify GetAllStream: channel is never null | require "./stream"
require "./row_value"
require "../../storage/*"
module ReQL
struct GetAllStream < Stream
class InternalData
property channels = [] of Channel(RowValue?)
end
def reql_type
"STREAM"
end
def initialize(@table : Storage::AbstractTable, @keys : Array(Datum) | Set(Datum... | require "./stream"
require "./row_value"
require "../../storage/*"
module ReQL
struct GetAllStream < Stream
class InternalData
property channels = [] of Channel(RowValue?)
end
def reql_type
"STREAM"
end
def initialize(@table : Storage::AbstractTable, @keys : Array(Datum) | Set(Datum... |
Use progress reporter for tests | require "../src/microtest"
require "./helpers"
include Microtest::DSL
include Helpers
COLOR_REGEX = %r{\e\[\d\d?(;\d)?m}
def uncolor(str)
str.gsub(COLOR_REGEX, "")
end
macro microtest_test(&block)
{%
c = <<-CRYSTAL
require "./src/microtest"
include Microtest::DSL
#{block.body.id}
... | require "../src/microtest"
require "./helpers"
include Microtest::DSL
include Helpers
COLOR_REGEX = %r{\e\[\d\d?(;\d)?m}
def uncolor(str)
str.gsub(COLOR_REGEX, "")
end
macro microtest_test(&block)
{%
c = <<-CRYSTAL
require "./src/microtest"
include Microtest::DSL
#{block.body.id}
... |
Use Amber::Pipe::Static handler to set http response cache headers | Amber::Server.instance.config do |app|
pipeline :web do
# Plug is the method to use connect a pipe (middleware)
# A plug accepts an instance of HTTP::Handler
plug Amber::Pipe::Logger.new unless app.env == "test"
plug Amber::Pipe::Flash.new
plug Amber::Pipe::Session.new
plug Amber::Pipe::CSRF.n... | Amber::Server.instance.config do |app|
pipeline :web do
# Plug is the method to use connect a pipe (middleware)
# A plug accepts an instance of HTTP::Handler
plug Amber::Pipe::Logger.new unless app.env == "test"
plug Amber::Pipe::Flash.new
plug Amber::Pipe::Session.new
plug Amber::Pipe::CSRF.n... |
Add Int64 to Jennifer::Migration::TableBuilder::Base::AllowedTypes alias | module Jennifer
module Migration
module TableBuilder
abstract class Base
# Base allowed types for migration DSL option values
alias AllowedTypes = String | Int32 | Bool | Float32 | Float64 | JSON::Any | Nil
# Allowed types for migration DSL + Symbol
alias EAllowedTypes = Allo... | module Jennifer
module Migration
module TableBuilder
abstract class Base
# Base allowed types for migration DSL option values
alias AllowedTypes = String | Int32 | Int64 | Bool | Float32 | Float64 | JSON::Any | Nil
# Allowed types for migration DSL + Symbol
alias EAllowedType... |
Update spec helper to use global before and after hooks | require "spec"
require "mocks"
require "../src/active_record"
require "../src/null_adapter"
require "../src/criteria_helper"
require "./fake_adapter"
# Use this after next release of Crystal
#Spec.before_each do
# ActiveRecord::NullAdapter.reset
#end
#
#Spec.after_each do
# ActiveRecord::NullAdapter.reset
#end
# No... | require "spec"
require "mocks"
require "../src/active_record"
require "../src/null_adapter"
require "../src/criteria_helper"
require "./fake_adapter"
def _specs_reset
ActiveRecord::NullAdapter.reset
FakeAdapter._reset
end
Spec.before_each do
_specs_reset
end
Spec.after_each do
_specs_reset
end
class SameQue... |
Define a very basic mapping for the READY payload | require "json"
module Discordcr
module REST
# A response to the Get Gateway REST API call.
struct GatewayResponse
JSON.mapping(
url: String
)
end
end
module Gateway
struct MessageCreatePayload
JSON.mapping(
type: UInt8,
content: String,
id: Strin... | require "json"
module Discordcr
module REST
# A response to the Get Gateway REST API call.
struct GatewayResponse
JSON.mapping(
url: String
)
end
end
module Gateway
# TODO: Expand this
struct ReadyPayload
JSON.mapping(
v: UInt8
)
end
struct Me... |
Remove debug message mistakenly committed in 14f84ae52 | require "./patches/**"
require "./caoutchouc/**"
module Caoutchouc
class CLI
include Shell
def initialize(args)
debug "Observing cluster at: #{args.inspect}"
puts STDIN.tty?
if args.size == 0
location = "http://localhost:9200"
else
location = args.first
end
... | require "./patches/**"
require "./caoutchouc/**"
module Caoutchouc
class CLI
include Shell
def initialize(args)
debug "Observing cluster at: #{args.inspect}"
if args.size == 0
location = "http://localhost:9200"
else
location = args.first
end
Caoutchouc::Elastics... |
Validate presence of line between the header and the rest (96948a8) | require "./../spec_helper"
describe M3U8::Playlist do
context "when creating a playlist" do
let(playlist) { M3U8::Playlist.new }
it "inserts the header" do
expect(playlist.to_s).to match(/#EXTM3U\n/)
end
it "accepts new segments" do
playlist.add_segment("S01E01-1080-0001.ts", 9.003)
... | require "./../spec_helper"
describe M3U8::Playlist do
context "when creating a playlist" do
let(playlist) { M3U8::Playlist.new }
it "inserts the header" do
expect(playlist.to_s).to match(/#EXTM3U\n/)
end
it "inserts an empty line between the header and rest" do
expect(playlist.to_s.line... |
Use direct string literals instead of constants for HTTP methods | require "http/client"
require "openssl/ssl/context"
require "./mappings"
require "./version"
module Discord
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
USER_AGENT = "DiscordBot (https://github.com/meew0/discordcr, #{Discord::VERSION})"
def request(endpoint_key : Symbol, method : String... | require "http/client"
require "openssl/ssl/context"
require "./mappings"
require "./version"
module Discord
module REST
SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
USER_AGENT = "DiscordBot (https://github.com/meew0/discordcr, #{Discord::VERSION})"
def request(endpoint_key : Symbol, method : String... |
Move Gateway::MessageCreatePayload to simply Message | require "json"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
str = parser.read_string_or_null
str.not_nil!.to_u64
end
def self.to_json(value : UInt64, io : IO)
io.puts(value.to_s)
end
end
module REST
# A response to the Get... | require "json"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
str = parser.read_string_or_null
str.not_nil!.to_u64
end
def self.to_json(value : UInt64, io : IO)
io.puts(value.to_s)
end
end
module REST
# A response to the Get... |
Add a run method to Client | module Discordcr
class Client
def initialize(@token : String, @client_id : UInt64)
end
end
end
| module Discordcr
class Client
def initialize(@token : String, @client_id : UInt64)
end
def run
end
end
end
|
Revert "Expriment with a Let class to hold setup" | require "../spec_helper"
module Franklin
class ConsoleReportLet
property subject : ConsoleReport
property result : String
property availability_description : AvailabilityDescription
property search_terms : String
property item : Item
def initialize(@search_terms = "crime and punishment")
... | require "../spec_helper"
module Franklin
describe ConsoleReport do
subject { ConsoleReport.new(search_terms, collated_results) }
let(:search_terms) { "crime and punishment" }
let(:collated_results) { {item => [availability]} }
let(:result) { subject.to_s(io).to_s }
let(:io) { IO::Memory.new }
... |
Add some more fields to Message | require "json"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
str = parser.read_string_or_null
str.not_nil!.to_u64
end
def self.to_json(value : UInt64, io : IO)
io.puts(value.to_s)
end
end
module REST
# A response to the Get... | require "json"
require "time/format"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
str = parser.read_string_or_null
str.not_nil!.to_u64
end
def self.to_json(value : UInt64, io : IO)
io.puts(value.to_s)
end
end
module REST
#... |
Print requests to the console | require "./cartel/*"
require "http/server"
module Cartel
view_handler = ViewHandler.new(File.join(__DIR__, "views"))
server = HTTP::Server.new(8080) do |request|
case request.path
when "/"
HTTP::Response.ok "text/html", view_handler.load("index.html")
else
HTTP:... | require "./cartel/*"
require "http/server"
module Cartel
view_handler = ViewHandler.new(File.join(__DIR__, "views"))
server = HTTP::Server.new(8080) do |request|
puts "[#{request.method}] #{request.path}"
case request.path
when "/"
HTTP::Response.ok "text/html", view_handl... |
Add status to controller helpers | module ControllerHelpers
private def html(body : String)
@response.set(200, body)
@response.header("Content-Type", "text/html")
end
private def text(body : String)
@response.set(200, body)
@response.header("Content-Type", "text/plain")
end
private def json(body : String)
@response.set(20... | module ControllerHelpers
private def html(body : String, status=200)
@response.set(status, body)
@response.header("Content-Type", "text/html")
end
private def text(body : String, status=200)
@response.set(status, body)
@response.header("Content-Type", "text/plain")
end
private def json(body ... |
Add current lib to CRYSTAL_PATH | require "./workspace"
module Scry
class Initialize
private getter workspace : Workspace
def initialize(params : InitializeParams, @msg_id : Int32)
@workspace = Workspace.new(
root_path: params.root_path,
process_id: params.process_id,
max_number_of_problems: 100
)
e... | require "./workspace"
module Scry
class Initialize
private getter workspace : Workspace
def initialize(params : InitializeParams, @msg_id : Int32)
@workspace = Workspace.new(
root_path: params.root_path,
process_id: params.process_id,
problems_limit: 100
)
ENV["CR... |
Fix CrystalLang implementation on latest version | require "./world"
class Play
# @@ makes this a private class variable
@@World_Width = 150
@@World_Height = 40
def self.run
world = World.new(
width: @@World_Width,
height: @@World_Height,
)
puts world.render
total_tick = 0
total_render = 0
while true
tick_start =... | require "./world"
class Play
# @@ makes this a private class variable
@@World_Width = 150
@@World_Height = 40
def self.run
world = World.new(
width: @@World_Width,
height: @@World_Height,
)
puts world.render
total_tick = 0
total_render = 0
while true
tick_start =... |
Create a converter to convert strings to and from snowflakes | require "json"
module Discord
module REST
# A response to the Get Gateway REST API call.
struct GatewayResponse
JSON.mapping(
url: String
)
end
end
module Gateway
# TODO: Expand this
struct ReadyPayload
JSON.mapping(
v: UInt8
)
end
struct Mess... | require "json"
module Discord
module SnowflakeConverter
def self.from_json(parser : JSON::PullParser) : UInt64
end
def self.to_json(value : String, io : IO)
end
end
module REST
# A response to the Get Gateway REST API call.
struct GatewayResponse
JSON.mapping(
url: String
... |
Handle message send exceptions, speculative deferred send | module Messenger::Bot
# A wrapper for Facebook's Graph API
class GraphAPI
# Build an API instance with which you can send messages.
# Pass *api_version* (current is 2.6) an *access_token*, which you need to
# authenticate yourself to the Graph API
def initialize(@api_version : String, @access_token ... | module Messenger::Bot
# A wrapper for Facebook's Graph API
class GraphAPI
# Build an API instance with which you can send messages.
# Pass *api_version* (current is 2.6) an *access_token*, which you need to
# authenticate yourself to the Graph API
def initialize(@api_version : String, @access_token ... |
Use IO::Memory instead of MemoryIO | module Toro
def self.drive(router)
Driver.new(router)
end
def self.drive(router, method, path)
drive(router).call(method, path)
end
class Driver
getter router : Toro::Router.class
def initialize(@router)
end
def call(req : HTTP::Request)
io = MemoryIO.new
res = HTTP::S... | module Toro
def self.drive(router)
Driver.new(router)
end
def self.drive(router, method, path)
drive(router).call(method, path)
end
class Driver
getter router : Toro::Router.class
def initialize(@router)
end
def call(req : HTTP::Request)
io = IO::Memory.new
res = HTTP:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.