text:
.class public abstract Landroid/service/wallpaper/WallpaperService;
.super Landroid/app/Service;
.source "WallpaperService.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/service/wallpaper/WallpaperService$IWallpaperServiceWrapper;,
        Landroid/service/wallpaper/WallpaperService$IWallpaperEngineWrapper;,
        Landroid/service/wallpaper/WallpaperService$Engine;,
        Landroid/service/wallpaper/WallpaperService$WallpaperCommand;
    }
.end annotation

# static fields
.field static final DEBUG:Z = false

.field private static final DO_ATTACH:I = 0xa

.field private static final DO_DETACH:I = 0x14

.field private static final DO_SET_DESIRED_SIZE:I = 0x1e

.field private static final MSG_REPORT_VISIBILITY:I = 0x4e2a

.field private static final MSG_TOUCH_EVENT:I = 0x2738

.field private static final MSG_UPDATE_SURFACE:I = 0x2710

.field private static final MSG_VISIBILITY_CHANGED:I = 0x271a

.field private static final MSG_WALLPAPER_COMMAND:I = 0x2729

.field private static final MSG_WALLPAPER_OFFSETS:I = 0x2724

.field private static final MSG_WINDOW_RESIZED:I = 0x272e

.field public static final SERVICE_INTERFACE:Ljava/lang/String; = "android.service.wallpaper.WallpaperService"

.field public static final SERVICE_META_DATA:Ljava/lang/String; = "android.service.wallpaper"

.field static final TAG:Ljava/lang/String; = "WallpaperService"

# instance fields
.field private final mActiveEngines:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Landroid/service/wallpaper/WallpaperService$Engine;",
            ">;"
        }
    .end annotation
.end field

.field private mCallbackLooper:Landroid/os/Looper;

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 84
    invoke-direct {p0}, Landroid/app/Service;-><init>()V

    .line 119
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/service/wallpaper/WallpaperService;->mActiveEngines:Ljava/util/ArrayList;

    .line 1219
    return-void
.end method

.method static synthetic access$200(Landroid/service/wallpaper/WallpaperService;)Landroid/os/Looper;
    .locals 1
    .parameter "x0"

    .prologue
    .line 84
    iget-object v0, p0, Landroid/service/wallpaper/WallpaperService;->mCallbackLooper:Landroid/os/Looper;

    return-object v0
.end method

.method static synthetic access$300(Landroid/service/wallpaper/WallpaperService;)Ljava/util/ArrayList;
    .locals 1
    .parameter "x0"

    .prologue
    .line 84
    iget-object v0, p0, Landroid/service/wallpaper/WallpaperService;->mActiveEngines:Ljava/util/ArrayList;

    return-object v0
.end method

# virtual methods
.method protected dump(Ljava/io/FileDescriptor;Ljava/io/PrintWriter;[Ljava/lang/String;)V
    .locals 3
    .parameter "fd"
    .parameter "out"
    .parameter "args"

    .prologue
    .line 1280
    const-string v2, "State of wallpaper "

    invoke-virtual {p2, v2}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-virtual {p2, p0}, Ljava/io/PrintWriter;->print(Ljava/lang/Object;)V

    const-string v2, ":"

    invoke-virtual {p2, v2}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V

    .line 1281
    const/4 v1, 0x0

    .local v1, i:I
    :goto_0
    iget-object v2, p0, Landroid/service/wallpaper/WallpaperService;->mActiveEngines:Ljava/util/ArrayList;

    invoke-virtual {v2}, Ljava/util/ArrayList;->size()I

    move-result v2

    if-ge v1, v2, :cond_0

    .line 1282
    iget-object v2, p0, Landroid/service/wallpaper/WallpaperService;->mActiveEngines:Ljava/util/ArrayList;

    invoke-virtual {v2, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/service/wallpaper/WallpaperService$Engine;

    .line 1283
    .local v0, engine:Landroid/service/wallpaper/WallpaperService$Engine;
    const-string v2, "  Engine "

    invoke-virtual {p2, v2}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-virtual {p2, v0}, Ljava/io/PrintWriter;->print(Ljava/lang/Object;)V

    const-string v2, ":"

    invoke-virtual {p2, v2}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V

    .line 1284
    const-string v2, "    "

    invoke-virtual {v0, v2, p1, p2, p3}, Landroid/service/wallpaper/WallpaperService$Engine;->dump(Ljava/lang/String;Ljava/io/FileDescriptor;Ljava/io/PrintWriter;[Ljava/lang/String;)V

    .line 1281
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 1286
    .end local v0           #engine:Landroid/service/wallpaper/WallpaperService$Engine;
    :cond_0
    return-void
.end method

.method public final onBind(Landroid/content/Intent;)Landroid/os/IBinder;
    .locals 1
    .parameter "intent"

    .prologue
    .line 1254
    new-instance v0, Landroid/service/wallpaper/WallpaperService$IWallpaperServiceWrapper;

    invoke-direct {v0, p0, p0}, Landroid/service/wallpaper/WallpaperService$IWallpaperServiceWrapper;-><init>(Landroid/service/wallpaper/WallpaperService;Landroid/service/wallpaper/WallpaperService;)V

    return-object v0
.end method

.method public onCreate()V
    .locals 0

    .prologue
    .line 1236
    invoke-super {p0}, Landroid/app/Service;->onCreate()V

    .line 1237
    return-void
.end method

.method public abstract onCreateEngine()Landroid/service/wallpaper/WallpaperService$Engine;
.end method

.method public onDestroy()V
    .locals 2

    .prologue
    .line 1241
    invoke-super {p0}, Landroid/app/Service;->onDestroy()V

    .line 1242
    const/4 v0, 0x0

    .local v0, i:I
    :goto_0
    iget-object v1, p0, Landroid/service/wallpaper/WallpaperService;->mActiveEngines:Ljava/util/ArrayList;

    invoke-virtual {v1}, Ljava/util/ArrayList;->size()I

    move-result v1

    if-ge v0, v1, :cond_0

    .line 1243
    iget-object v1, p0, Landroid/service/wallpaper/WallpaperService;->mActiveEngines:Ljava/util/ArrayList;

    invoke-virtual {v1, v0}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/service/wallpaper/WallpaperService$Engine;

    invoke-virtual {v1}, Landroid/service/wallpaper/WallpaperService$Engine;->detach()V

    .line 1242
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 1245
    :cond_0
    iget-object v1, p0, Landroid/service/wallpaper/WallpaperService;->mActiveEngines:Ljava/util/ArrayList;

    invoke-virtual {v1}, Ljava/util/ArrayList;->clear()V

    .line 1246
    return-void
.end method

.method public setCallbackLooper(Landroid/os/Looper;)V
    .locals 0
    .parameter "looper"

    .prologue
    .line 1267
    iput-object p1, p0, Landroid/service/wallpaper/WallpaperService;->mCallbackLooper:Landroid/os/Looper;

    .line 1268
    return-void
.end method


text:
require 'Octokit'

token = ENV['OCTOKIT_ACCESS_TOKEN']

if token.nil? || token.empty? then
  puts "You need to set a personal access token to continue"
  puts "For example:"
  puts "> export OCTOKIT_ACCESS_TOKEN='<some value here>'"
  exit
end

client = Octokit::Client.new(:access_token => token)

puts "Press CTRL+C at any time to cancel..."
puts

puts "Which repository (specify owner/repository format):"
STDOUT.flush
repository = gets.chomp

begin
  found_repository = client.repository(repository)
rescue
  puts "Could not find repository " + repository
  puts "Exiting..."
  exit
end

puts "Found the repository!\n\n"

puts "Enter the commit SHA you want to update:"
STDOUT.flush
commit_sha = gets.chomp

begin
  found_commit = client.commit(repository, commit_sha)
rescue
  puts "Could not find commit " + commit_sha
  puts "Exiting..."
  exit
end

puts "Found the commit!\n\n"

valid_statuses = [ 'pending', 'success', 'error', 'failure' ]

puts "What status to use (pending|success|error|failure):"
STDOUT.flush
status = gets.chomp

if !valid_statuses.any? { |s| s == status } then
  puts "Text entered is not a valid status: " + status
  puts "Exiting..."
  exit
end

begin
  info = {
    :target_url => 'http://github.com'
  }
  status = client.create_status(repository, found_commit.sha, status, info)
rescue
  puts "Unable to create status\n"
  raise
end

puts "Great success!!!"

redpajama_set_name: RedPajamaGithub


text:
You have to set the application for handling links.
In Windows 7 to this:

- Through the Windows main menu open `Default Programs`/`Standardprogramme`
- Select `Set your default programs`/`Standardprogramme festlegen`
- Select your browser, e.g. `Firefox` and press the button `Set this program as default`/`Diese Programm als Standard festlegen`

--

[back to main page](index.md)


text:
<?php

namespace Codesleeve\LaravelStapler\Exceptions;

use Exception;

class InvalidClassException extends Exception
{
}


text:
#ifdef _WIN32
#include <direct.h>
#define getcwd _getcwd
#define PATH_SEP ';'
#else
#include <unistd.h>
#define PATH_SEP ':'
#endif

#ifndef SASS_AST
#include "ast.hpp"
#endif

#include "context.hpp"
#include "constants.hpp"
#include "parser.hpp"
#include "file.hpp"
#include "inspect.hpp"
#include "output_nested.hpp"
#include "output_compressed.hpp"
#include "expand.hpp"
#include "eval.hpp"
#include "contextualize.hpp"
#include "extend.hpp"
#include "copy_c_str.hpp"
#include "color_names.hpp"
#include "functions.hpp"
#include "backtrace.hpp"

#ifndef SASS_PRELEXER
#include "prelexer.hpp"
#endif

#include <iomanip>
#include <iostream>
#include <cstring>
#include <sstream>

namespace Sass {
  using namespace Constants;
  using namespace File;
  using std::cerr;
  using std::endl;

  Context::Context(Context::Data initializers)
  : mem(Memory_Manager<AST_Node>()),
    source_c_str         (initializers.source_c_str()),
    sources              (vector<const char*>()),
    include_paths        (initializers.include_paths()),
    queue                (vector<pair<string, const char*> >()),
    style_sheets         (map<string, Block*>()),
    source_map           (resolve_relative_path(initializers.output_path(), initializers.source_map_file(), get_cwd())),
    c_functions          (vector<Sass_C_Function_Descriptor>()),
    image_path           (initializers.image_path()),
    output_path          (make_canonical_path(initializers.output_path())),
    source_comments      (initializers.source_comments()),
    source_maps          (initializers.source_maps()),
    output_style         (initializers.output_style()),
    source_map_file      (make_canonical_path(initializers.source_map_file())),
    omit_source_map_url  (initializers.omit_source_map_url()),
    names_to_colors      (map<string, Color*>()),
    colors_to_names      (map<int, string>()),
    precision            (initializers.precision()),
    extensions           (multimap<Compound_Selector, Complex_Selector*>()),
    subset_map           (Subset_Map<string, pair<Complex_Selector*, Compound_Selector*> >())
  {
    cwd = get_cwd();

    collect_include_paths(initializers.include_paths_c_str());
    collect_include_paths(initializers.include_paths_array());

    setup_color_map();

    string entry_point = initializers.entry_point();
    if (!entry_point.empty()) {
      string result(add_file(entry_point));
      if (result.empty()) {
        throw entry_point;
      }
    }
  }

  Context::~Context()
  { for (size_t i = 0; i < sources.size(); ++i) delete[] sources[i]; }

  void Context::setup_color_map()
  {
    size_t i = 0;
    while (color_names[i]) {
      string name(color_names[i]);
      Color* value = new (mem) Color("[COLOR TABLE]", Position(),
                                     color_values[i*3],
                                     color_values[i*3+1],
                                     color_values[i*3+2]);
      names_to_colors[name] = value;
      int numval = color_values[i*3]*0x10000;
      numval += color_values[i*3+1]*0x100;
      numval += color_values[i*3+2];
      colors_to_names[numval] = name;
      ++i;
    }
  }

  void Context::collect_include_paths(const char* paths_str)
  {
    include_paths.push_back(cwd);

    if (paths_str) {
      const char* beg = paths_str;
      const char* end = Prelexer::find_first<PATH_SEP>(beg);

      while (end) {
        string path(beg, end - beg);
        if (!path.empty()) {
          if (*path.rbegin() != '/') path += '/';
          include_paths.push_back(path);
        }
        beg = end + 1;
        end = Prelexer::find_first<PATH_SEP>(beg);
      }

      string path(beg);
      if (!path.empty()) {
        if (*path.rbegin() != '/') path += '/';
        include_paths.push_back(path);
      }
    }
  }

  void Context::collect_include_paths(const char* paths_array[])
  {
    include_paths.push_back(get_cwd());
    if (*include_paths.back().rbegin() != '/') include_paths.back() += '/';

    // if (paths_array) {
    //   for (size_t i = 0; paths_array[i]; ++i) {
    //     string path(paths_array[i]);
    //     if (!path.empty()) {
    //       if (*path.rbegin() != '/') path += '/';
    //       include_paths.push_back(path);
    //     }
    //   }
    // }
  }

  string Context::add_file(string path)
  {
    using namespace File;
    char* contents = 0;
    string real_path;
    path = make_canonical_path(path);
    for (size_t i = 0, S = include_paths.size(); i < S; ++i) {
      string full_path(join_paths(include_paths[i], path));
      included_files.push_back(full_path);
      if (style_sheets.count(full_path)) return full_path;
      contents = resolve_and_load(full_path, real_path);
      if (contents) {
        sources.push_back(contents);
        included_files.push_back(real_path);
        queue.push_back(make_pair(full_path, contents));
        source_map.files.push_back(resolve_relative_path(real_path, source_map_file, cwd));
        style_sheets[full_path] = 0;
        return full_path;
      }
    }
    return string();
  }

  string Context::add_file(string dir, string rel_filepath)
  {
    using namespace File;
    char* contents = 0;
    string real_path;
    rel_filepath = make_canonical_path(rel_filepath);
    string full_path(join_paths(dir, rel_filepath));
    if (style_sheets.count(full_path)) return full_path;
    contents = resolve_and_load(full_path, real_path);
    if (contents) {
      sources.push_back(contents);
      included_files.push_back(real_path);
      queue.push_back(make_pair(full_path, contents));
      source_map.files.push_back(resolve_relative_path(real_path, source_map_file, cwd));
      style_sheets[full_path] = 0;
      return full_path;
    }
    for (size_t i = 0, S = include_paths.size(); i < S; ++i) {
      string full_path(join_paths(include_paths[i], rel_filepath));
      if (style_sheets.count(full_path)) return full_path;
      contents = resolve_and_load(full_path, real_path);
      if (contents) {
        sources.push_back(contents);
        included_files.push_back(real_path);
        queue.push_back(make_pair(full_path, contents));
        source_map.files.push_back(resolve_relative_path(real_path, source_map_file, cwd));
        style_sheets[full_path] = 0;
        return full_path;
      }
    }
    return string();
  }

  void register_function(Context&, Signature sig, Native_Function f, Env* env);
  void register_function(Context&, Signature sig, Native_Function f, size_t arity, Env* env);
  void register_overload_stub(Context&, string name, Env* env);
  void register_built_in_functions(Context&, Env* env);
  void register_c_functions(Context&, Env* env, Sass_C_Function_Descriptor*);
  void register_c_function(Context&, Env* env, Sass_C_Function_Descriptor);

  char* Context::compile_file()
  {
    Block* root = 0;
    for (size_t i = 0; i < queue.size(); ++i) {
      Parser p(Parser::from_c_str(queue[i].second, *this, queue[i].first, Position(1 + i, 1, 1)));
      Block* ast = p.parse();
      if (i == 0) root = ast;
      style_sheets[queue[i].first] = ast;
    }
    Env tge;
    Backtrace backtrace(0, "", Position(), "");
    register_built_in_functions(*this, &tge);
    for (size_t i = 0, S = c_functions.size(); i < S; ++i) {
    	register_c_function(*this, &tge, c_functions[i]);
    }
    Eval eval(*this, &tge, &backtrace);
    Contextualize contextualize(*this, &eval, &tge, &backtrace);
    Expand expand(*this, &eval, &contextualize, &tge, &backtrace);
    // Inspect inspect(this);
    // Output_Nested output_nested(*this);

    root = root->perform(&expand)->block();
    if (!extensions.empty()) {
      Extend extend(*this, extensions, subset_map, &backtrace);
      root->perform(&extend);
    }
    char* result = 0;
    switch (output_style) {
      case COMPRESSED: {
        Output_Compressed output_compressed(this);
        root->perform(&output_compressed);
        string output = output_compressed.get_buffer();
        if (source_map_file != "" && !omit_source_map_url) {
          output += format_source_mapping_url(source_map_file);
        }
        result = copy_c_str(output.c_str());
      } break;

      default: {
        Output_Nested output_nested(source_comments, this);
        root->perform(&output_nested);
        string output = output_nested.get_buffer();
        if (source_map_file != "" && !omit_source_map_url) {
          output += "\n" + format_source_mapping_url(source_map_file);
        }
        result = copy_c_str(output.c_str());

      } break;
    }

    return result;
  }

  string Context::format_source_mapping_url(const string& file) const
  {
    return "/*# sourceMappingURL=" + resolve_relative_path(file, output_path, cwd) + " */";
  }

  char* Context::generate_source_map()
  {
    if (!source_maps) return 0;
    char* result = 0;
    string map = source_map.generate_source_map();
    result = copy_c_str(map.c_str());
    return result;
  }

  char* Context::compile_string()
  {
    if (!source_c_str) return 0;
    queue.clear();
    queue.push_back(make_pair("source string", source_c_str));
    // mimic google closure compiler
    source_map.files.push_back("stdin");
    return compile_file();
  }

  std::vector<std::string> Context::get_included_files()
  {
      std::sort(included_files.begin(), included_files.end());
      included_files.erase( std::unique( included_files.begin(), included_files.end() ), included_files.end());
      return included_files;
  }

  string Context::get_cwd()
  {
    const size_t wd_len = 1024;
    char wd[wd_len];
    string cwd = getcwd(wd, wd_len);
#ifdef _WIN32
    //convert backslashes to forward slashes
    replace(cwd.begin(), cwd.end(), '\\', '/');
#endif
    if (cwd[cwd.length() - 1] != '/') cwd += '/';
    return cwd;
  }

  void register_function(Context& ctx, Signature sig, Native_Function f, Env* env)
  {
    Definition* def = make_native_function(sig, f, ctx);
    def->environment(env);
    (*env)[def->name() + "[f]"] = def;
  }

  void register_function(Context& ctx, Signature sig, Native_Function f, size_t arity, Env* env)
  {
    Definition* def = make_native_function(sig, f, ctx);
    stringstream ss;
    ss << def->name() << "[f]" << arity;
    def->environment(env);
    (*env)[ss.str()] = def;
  }

  void register_overload_stub(Context& ctx, string name, Env* env)
  {
    Definition* stub = new (ctx.mem) Definition("[built-in function]",
                                            Position(),
                                            0,
                                            name,
                                            0,
                                            0,
                                            true);
    (*env)[name + "[f]"] = stub;
  }

  void register_built_in_functions(Context& ctx, Env* env)
  {
    using namespace Functions;
    // RGB Functions
    register_function(ctx, rgb_sig, rgb, env);
    register_overload_stub(ctx, "rgba", env);
    register_function(ctx, rgba_4_sig, rgba_4, 4, env);
    register_function(ctx, rgba_2_sig, rgba_2, 2, env);
    register_function(ctx, red_sig, red, env);
    register_function(ctx, green_sig, green, env);
    register_function(ctx, blue_sig, blue, env);
    register_function(ctx, mix_sig, mix, env);
    // HSL Functions
    register_function(ctx, hsl_sig, hsl, env);
    register_function(ctx, hsla_sig, hsla, env);
    register_function(ctx, hue_sig, hue, env);
    register_function(ctx, saturation_sig, saturation, env);
    register_function(ctx, lightness_sig, lightness, env);
    register_function(ctx, adjust_hue_sig, adjust_hue, env);
    register_function(ctx, lighten_sig, lighten, env);
    register_function(ctx, darken_sig, darken, env);
    register_function(ctx, saturate_sig, saturate, env);
    register_function(ctx, desaturate_sig, desaturate, env);
    register_function(ctx, grayscale_sig, grayscale, env);
    register_function(ctx, complement_sig, complement, env);
    register_function(ctx, invert_sig, invert, env);
    // Opacity Functions
    register_function(ctx, alpha_sig, alpha, env);
    register_function(ctx, opacity_sig, alpha, env);
    register_function(ctx, opacify_sig, opacify, env);
    register_function(ctx, fade_in_sig, opacify, env);
    register_function(ctx, transparentize_sig, transparentize, env);
    register_function(ctx, fade_out_sig, transparentize, env);
    // Other Color Functions
    register_function(ctx, adjust_color_sig, adjust_color, env);
    register_function(ctx, scale_color_sig, scale_color, env);
    register_function(ctx, change_color_sig, change_color, env);
    register_function(ctx, ie_hex_str_sig, ie_hex_str, env);
    // String Functions
    register_function(ctx, unquote_sig, sass_unquote, env);
    register_function(ctx, quote_sig, sass_quote, env);
    register_function(ctx, str_length_sig, str_length, env);
    register_function(ctx, str_insert_sig, str_insert, env);
    register_function(ctx, str_index_sig, str_index, env);
    register_function(ctx, str_slice_sig, str_slice, env);
    register_function(ctx, to_upper_case_sig, to_upper_case, env);
    register_function(ctx, to_lower_case_sig, to_lower_case, env);
    // Number Functions
    register_function(ctx, percentage_sig, percentage, env);
    register_function(ctx, round_sig, round, env);
    register_function(ctx, ceil_sig, ceil, env);
    register_function(ctx, floor_sig, floor, env);
    register_function(ctx, abs_sig, abs, env);
    register_function(ctx, min_sig, min, env);
    register_function(ctx, max_sig, max, env);
    // List Functions
    register_function(ctx, length_sig, length, env);
    register_function(ctx, nth_sig, nth, env);
    register_function(ctx, index_sig, index, env);
    register_function(ctx, join_sig, join, env);
    register_function(ctx, append_sig, append, env);
    register_function(ctx, compact_sig, compact, env);
    register_function(ctx, zip_sig, zip, env);
    // Introspection Functions
    register_function(ctx, type_of_sig, type_of, env);
    register_function(ctx, unit_sig, unit, env);
    register_function(ctx, unitless_sig, unitless, env);
    register_function(ctx, comparable_sig, comparable, env);
    register_function(ctx, variable_exists_sig, variable_exists, env);
    register_function(ctx, global_variable_exists_sig, global_variable_exists, env);
    register_function(ctx, function_exists_sig, function_exists, env);
    register_function(ctx, mixin_exists_sig, mixin_exists, env);
    // Boolean Functions
    register_function(ctx, not_sig, sass_not, env);
    register_function(ctx, if_sig, sass_if, env);
    // Path Functions
    register_function(ctx, image_url_sig, image_url, env);
  }

  void register_c_functions(Context& ctx, Env* env, Sass_C_Function_Descriptor* descrs)
  {
    while (descrs->signature && descrs->function) {
      register_c_function(ctx, env, *descrs);
      ++descrs;
    }
  }
  void register_c_function(Context& ctx, Env* env, Sass_C_Function_Descriptor descr)
  {
    Definition* def = make_c_function(descr.signature, descr.function, descr.cookie, ctx);
    def->environment(env);
    (*env)[def->name() + "[f]"] = def;
  }

}


text:
void random_test_start(random_t random);
void random_test_final(random_t random);
void random_test_add_number(random_t random, mpz_t number);
void random_test_add_number_ul(random_t random, unsigned long number);
void random_test_add_bytes(random_t random, uint8_t *bytes, size_t length);

#endif


text:
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;

namespace Kooboo.HealthMonitoring
{
    /// <summary>
    ///
    /// </summary>
    public class Log
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Log" /> class.
        /// </summary>
        /// <param name="e">The e.</param>
        public static Action<Exception> Logger = (Exception e) =>
        {
            var webEvent = new WebRequestErrorEventWrapper(e.Message, null, 100000, e);
            webEvent.Raise();
        };
        /// <summary>
        /// Logs the exception.
        /// </summary>
        /// <param name="e">The e.</param>
        public static void LogException(Exception e)
        {
            Logger(e);
        }
    }
}


text:
class DatasetFile < ApplicationRecord

	require 'csvlint'

  belongs_to :dataset
  belongs_to :dataset_file_schema

  validate :check_schema, if: :content_or_schema_changed?
  validate :check_csv, if: :content_or_schema_changed?
  validates_presence_of :title
  validates_presence_of :storage_key, on: :create

  after_validation :set_filename

  default_scope { order(:created_at) }

  attr_accessor :file

  def self.file_from_url(file)
    Rails.logger.info "DatasetFile: In file_from_url"
    tempfile = Tempfile.new 'uploaded'
    tempfile.write read_file_with_utf_8(file)
    tempfile.rewind
    ActionDispatch::Http::UploadedFile.new filename: File.basename(file),
                                           # content_type: 'text/csv',
                                           tempfile: tempfile
  end

  def self.file_from_url_with_storage_key(file, storage_key)
    Rails.logger.info "DatasetFile: In file_from_url_with_storage_key"

    fs_file = FileStorageService.get_string_io(storage_key)
    ActionDispatch::Http::UploadedFile.new filename: File.basename(file),
                                           # content_type: 'text/csv',
                                           tempfile: fs_file
  end

  def self.read_file_with_utf_8(file)
    open(URI.escape(file)).read.force_encoding("UTF-8")
  end

  def self.create(dataset_file_creation_hash)
    Rails.logger.info "DatasetFile: In create"
    # allow use of hashes or strings for keys
    dataset_file_creation_hash = get_file_from_the_right_place(dataset_file_creation_hash)
    Rails.logger.info "Dataset file created using new file #{dataset_file_creation_hash[:file]} key: #{dataset_file_creation_hash[:storage_key]}"
    # Do the actual create here
    super(
      title: dataset_file_creation_hash[:title],
      description: dataset_file_creation_hash[:description],
      file: dataset_file_creation_hash[:file],
      storage_key: dataset_file_creation_hash[:storage_key],
      dataset_file_schema_id: dataset_file_creation_hash[:dataset_file_schema_id]
    )
  end

  def self.get_file_from_the_right_place(dataset_file_hash)
    dataset_file_hash = ActiveSupport::HashWithIndifferentAccess.new(dataset_file_hash)
    if dataset_file_hash[:file].class == String
      if dataset_file_hash[:storage_key]
        # File already uploaded so fetch from S3
        dataset_file_hash[:file] = file_from_url_with_storage_key(dataset_file_hash[:file], dataset_file_hash[:storage_key])
      else
        dataset_file_hash[:file] = file_from_url(dataset_file_hash[:file])
      end
    end
    dataset_file_hash
  end

  def github_url
    "#{dataset.github_url}/data/#{filename}"
  end

  def gh_pages_url
    "#{dataset.gh_pages_url}/data/#{filename}"
  end

  def schema_name
    dataset_file_schema.name if dataset_file_schema
  end

	def file_type
		file_extension
	end

  def update_file(file_update_hash)
    Rails.logger.info "DatasetFile: In update_file"
    file_update_hash = DatasetFile.get_file_from_the_right_place(file_update_hash)

    update_hash = {
      description: file_update_hash[:description],
      file: file_update_hash[:file],
      dataset_file_schema_id: file_update_hash[:dataset_file_schema_id],
      storage_key: file_update_hash[:storage_key]
    }.delete_if { |_k,v| v.nil? }

    self.update(update_hash)
  end

  private

    def content_or_schema_changed?
      # We only need to validate if the file itself or the schema has changed
      new_record? ||
      dataset_file_schema_id_changed? ||
      storage_key_changed?
    end

    def check_schema
      Rails.logger.info "DatasetFile: In check schema"
      if dataset_file_schema && is_csv?
        if dataset_file_schema.is_schema_valid?
          if dataset_file_schema.csv_on_the_web_schema
            validate_schema_cotw
          else
            validate_schema_non_cotw
          end
        else
          errors.add(:schema, 'is not valid')
        end
      end
    end

    def validate_schema_cotw
      Rails.logger.info "DatasetFile: we have COTW schema and schema is valid, so validate"

      schema = Csvlint::Schema.load_from_string(URI.escape(dataset_file_schema.url), dataset_file_schema.schema)
      tempfile = get_file_for_validation_from_file

      if schema.respond_to? :tables
        schema.tables["file:#{tempfile.path}"] = schema.tables.delete(schema.tables.keys.first)
      end
      validation = Csvlint::Validator.new(tempfile, {}, schema)
			update_database_attribute(validation)

			Rails.logger.info "DatasetFile: check schema, number of errors #{errors.count}"
      errors
    end

    def validate_schema_non_cotw
      Rails.logger.info "DatasetFile: we have non COTW schema and schema is valid, so validate"

      schema = Csvlint::Schema.load_from_string(URI.escape(dataset_file_schema.url), dataset_file_schema.schema)

      validation = Csvlint::Validator.new(file_content, {}, schema)
			update_database_attribute(validation)

			Rails.logger.info "DatasetFile: check schema, number of errors #{errors.count}"
      errors
    end

    def get_file_for_validation_from_file
      File.new(file.tempfile)
    end

		def update_database_attribute(validation)
			validation.valid? ? self.update_attribute(:validation, true) : self.update_attribute(:validation, false)
		end

    def check_csv
      if is_csv?
        content = file_content
        unless content.nil?
          begin
            CSV.parse(content.read)
          rescue CSV::MalformedCSVError
            errors.add(:file, 'does not appear to be a valid CSV. Please check your file and try again.')
          rescue
            errors.add(:file, 'had some problems trying to upload. Please check your file and try again.')
          ensure
            file_content.rewind
          end
        end
      end
    end

		def is_csv?
			file_extension == '.csv'
		end

    def file_extension
      file = self.storage_key || self.file.original_filename || ''
      File.extname(file)
    end

    def set_filename
      self.filename = "#{title.parameterize}" << file_extension rescue nil
    end

    def file_content
      # Try to load from the storage key first.
      if storage_key
        # This might fail if the S3 content has gone away.
        begin
          return FileStorageService.get_string_io(storage_key)
        rescue Aws::S3::Errors::NoSuchKey
          # OK, the S3 content disappeared. Carry on.
        end
      end
      # If that didn't help, we try to load from the pubished version on GitHub
      if dataset && dataset.github_public?
        begin
          return open(gh_pages_url)
        rescue OpenURI::HTTPError => ex
          # Absorb 404s, but throw anything else up the stack
          throw unless ex.message === "404 Not Found"
        end
      end
      # Nothing worked. Ah well. We did our best.
      nil
    end

end


text:
package edu.wustl.common.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import junit.framework.TestCase;

public class TreeTest extends TestCase {
    public void testBasic() {
        Tree<Integer, String> tree;
        try {
            tree = newTree(null);
            fail();
        } catch (NullPointerException e) {

        }
        tree = newTree(1);
        assertTrue(tree.containsNode(1));
        assertFalse(tree.containsNode(2));
        assertEquals(integer(1), tree.getRoot());
        assertTrue(tree.getChildren(1).isEmpty());
        assertNull(tree.getLabel(1));
        assertNull(tree.getParent(1));
        assertTrue(tree.isRoot(1));
        assertTrue(tree.isLeaf(1));
        tree.setLabel(1, "1");
        assertNull(tree.getLabel(1));

        assertNull(tree.putChild(1, 2, "12"));
        assertTrue(tree.containsNode(1));
        assertTrue(tree.containsNode(2));
        assertEquals(integer(1), tree.getRoot());
        assertEquals(asSet(2), tree.getChildren(1));
        assertNull(tree.getLabel(1));
        assertNull(tree.getParent(1));
        assertEquals("12", tree.getLabel(2));
        assertEquals(integer(1), tree.getParent(2));
        assertTrue(tree.getChildren(2).isEmpty());
        assertTrue(tree.isRoot(1));
        assertFalse(tree.isLeaf(1));
        assertFalse(tree.isRoot(2));
        assertTrue(tree.isLeaf(2));

        Tree<Integer, String> temp = tree.clone();

        assertEquals("12", tree.setLabel(2, "21"));
        assertEquals("21", tree.getLabel(2));

        assertEquals("21", tree.putChild(1, 2, "12"));
        assertEquals(temp, tree);
    }

    public void testPivot() {
        Tree<Integer, String> tree = newTree(1);
        tree.pivot(1);
        tree.putChild(1, 2, "12");

        Tree<Integer, String> orig = tree.clone();
        tree.pivot(1);

        Tree<Integer, String> expected = newTree(2);
        expected.putChild(2, 1, "12");
        tree.pivot(2);
        assertEquals(expected, tree);

        tree.pivot(1);
        assertEquals(orig, tree);

        tree.putChild(1, 3, "13"); // 1(2, 3)
        expected.putChild(1, 3, "13");
        tree.pivot(1);
        tree.pivot(2);
        assertEquals(expected, tree); // 2(1(3))

        expected = newTree(3); // 3(1(2))
        expected.putChild(3, 1, "13");
        expected.putChild(1, 2, "12");
        tree.pivot(3);
        assertEquals(expected, tree);

        tree = expected.clone();
        expected = newTree(1);
        expected.putChild(1, 2, "12");
        expected.putChild(1, 3, "13");
        tree.pivot(1);
        assertEquals(expected, tree);
    }

    public void testSetRoot() {
        Tree<Integer, String> tree = newTree(1);
        Tree<Integer, String> expected = newTree(1);
        tree.setRoot(1, "12");
        assertEquals(expected, tree);

        tree.putChild(1, 2, "12");
        expected = newTree(2);
        expected.putChild(2, 1, "21");
        tree.setRoot(2, "21");
        assertEquals(expected, tree);

        expected.putChild(2, 3, "32");
        expected.pivot(3);
        tree.setRoot(3, "32");
        assertEquals(expected, tree);

        expected = newTree(1);
        expected.putChild(1, 3, "13");
        expected.putChild(3, 2, "32");
        tree.setRoot(1, "13");
        assertEquals(expected, tree);

        tree.putChild(1, 4, "14");
        expected = newTree(3);
        expected.putChild(3, 2, "32");
        expected.putChild(3, 1, "31");
        expected.putChild(1, 4, "14");
        tree.setRoot(3, "31");
        assertEquals(expected, tree);

        Tree<Integer, String> temp = tree.clone();
        expected = newTree(2);
        expected.putChild(2, 3, "23");
        expected.putChild(3, 1, "31");
        expected.putChild(1, 4, "14");
        tree.setRoot(2, "23");
        assertEquals(expected, tree);

        tree = temp;
        expected = newTree(4);
        expected.putChild(4, 3, "43");
        expected.putChild(3, 1, "31");
        expected.putChild(3, 2, "32");
        tree.setRoot(4, "43");
        assertEquals(expected, tree);

    }

    public void testSubTree() {
        Tree<Integer, String> tree = newTree(1);
        assertEquals(tree, tree.subTree(1));

        tree.putChild(1, 2, "12");
        assertEquals(tree, tree.subTree(1));
        assertEquals(newTree(2), tree.subTree(2));

        tree.putChild(1, 3, "13");
        assertEquals(tree, tree.subTree(1));
        assertEquals(newTree(2), tree.subTree(2));
        assertEquals(newTree(3), tree.subTree(3));

        tree.putChild(2, 4, "24");
        assertEquals(tree, tree.subTree(1));
        assertEquals(newTree(3), tree.subTree(3));
        assertEquals(newTree(4), tree.subTree(4));
        Tree<Integer, String> subTree2 = newTree(2);
        subTree2.putChild(2, 4, "24");
        assertEquals(subTree2, tree.subTree(2));

        tree.putChild(2, 5, "25");
        subTree2.putChild(2, 5, "25");
        assertEquals(tree, tree.subTree(1));
        assertEquals(subTree2, tree.subTree(2));
    }

    public void testAddSubTree() {
        Tree<Integer, String> tree = newTree(1);
        Tree<Integer, String> expected = newTree(1);

        tree.addSubTree(1, newTree(2), "12");
        expected.putChild(1, 2, "12");

        assertEquals(expected, tree);

        Tree<Integer, String> subTree = newTree(3);
        subTree.putChild(3, 4, "34");
        subTree.putChild(3, 5, "35");

        expected.putChild(1, 3, "13");
        expected.putChild(3, 4, "34");
        expected.putChild(3, 5, "35");

        tree.addSubTree(1, subTree, "13");
        assertEquals(expected, tree);

        subTree = newTree(6);
        subTree.putChild(6, 7, "67");
        subTree.putChild(7, 8, "78");
        subTree.putChild(6, 9, "69");

        expected.putChild(2, 6, "26");
        expected.putChild(6, 7, "67");
        expected.putChild(7, 8, "78");
        expected.putChild(6, 9, "69");

        tree.addSubTree(2, subTree, "26");
        assertEquals(expected, tree);
    }

    public void testRemoveSubtree() {
        Tree<Integer, String> tree = newTree(1);
        assertEquals(tree, tree.removeSubTree(1));

        Tree<Integer, String> removed = newTree(2);
        Tree<Integer, String> remaining = newTree(1);

        tree.putChild(1, 2, "12");
        checkRemoval(tree, 2, removed, remaining);

        tree.putChild(1, 2, "12");
        tree.putChild(1, 3, "13");
        remaining.putChild(1, 3, "13");
        checkRemoval(tree, 2, removed, remaining);

        tree.putChild(1, 2, "12");
        tree.putChild(2, 4, "24");
        tree.putChild(2, 5, "25");

        removed.putChild(2, 4, "24");
        removed.putChild(2, 5, "25");
        checkRemoval(tree, 2, removed, remaining);

        tree.putChild(1, 2, "12");
        tree.putChild(2, 4, "24");
        tree.putChild(2, 5, "25");
        tree.putChild(4, 6, "46");

        removed = newTree(4);
        removed.putChild(4, 6, "46");

        remaining.putChild(1, 2, "12");
        remaining.putChild(2, 5, "25");
        checkRemoval(tree, 4, removed, remaining);

        remaining = newTree(1);
        remaining.putChild(1, 2, "12");
        remaining.putChild(2, 5, "25");
        removed = newTree(3);
        checkRemoval(tree, 3, removed, remaining);
    }

    private void checkRemoval(Tree<Integer, String> tree, int nodeToRemove, Tree<Integer, String> removed,
            Tree<Integer, String> remaining) {
        assertEquals(removed, tree.removeSubTree(nodeToRemove));
        assertEquals(remaining, tree);
    }

    public void testContainsAnyNode() {
        Tree<Integer, String> tree1 = newTree(1);
        Tree<Integer, String> tree2 = newTree(1);
        checkContainsAnyNode(tree1, tree2);
        tree2 = newTree(2);
        checkDoesNotContainsAnyNode(tree1, tree2);
        tree2.putChild(2, 1, "21");
        checkContainsAnyNode(tree1, tree2);

        tree1 = newTree(3);
        checkDoesNotContainsAnyNode(tree1, tree2);
        tree1.putChild(3, 4, "34");
        checkDoesNotContainsAnyNode(tree1, tree2);
        Tree<Integer, String> tempTree1 = tree1.clone();

        tree1.putChild(3, 2, "32");
        checkContainsAnyNode(tree1, tree2);
        tree1 = tempTree1;
        tree1.putChild(3, 1, "31");
        checkContainsAnyNode(tree1, tree2);
        tree1 = tempTree1;
        tree1.putChild(4, 1, "41");
        checkContainsAnyNode(tree1, tree2);
        tree1.putChild(3, 2, "32");
        checkContainsAnyNode(tree1, tree2);
    }

    private void checkContainsAnyNode(Tree<Integer, String> tree1, Tree<Integer, String> tree2) {
        assertTrue(tree1.containsAnyNode(tree2));
        assertTrue(tree2.containsAnyNode(tree1));
    }

    private void checkDoesNotContainsAnyNode(Tree<Integer, String> tree1, Tree<Integer, String> tree2) {
        assertFalse(tree1.containsAnyNode(tree2));
        assertFalse(tree2.containsAnyNode(tree1));
    }

    public void testPaths() {
        Tree<Integer, String> tree = newTree(1);
        assertNull(tree.getNodesPath(1));
        tree.putChild(1, 2, "12");
        assertEquals(asList(1, 2), tree.getNodesPath(2));

        tree.putChild(1, 3, "13");
        assertEquals(asList(1, 2), tree.getNodesPath(2));
        assertEquals(asList(1, 3), tree.getNodesPath(3));
        assertNull(tree.getNodesPath(2, 3));
        assertNull(tree.getNodesPath(3, 2));

        tree.putChild(2, 4, "24");
        assertEquals(asList(1, 2, 4), tree.getNodesPath(4));
        assertEquals(asList(2, 4), tree.getNodesPath(2, 4));
        assertNull(tree.getNodesPath(4, 3));
        assertNull(tree.getNodesPath(3, 4));
    }

    private Tree<Integer, String> newTree(Integer root) {
        return new Tree<Integer, String>(root);
    }

    private Integer integer(int i) {
        return new Integer(i);
    }

    private static <T> Set<T> asSet(T... elems) {
        Set<T> res = new HashSet<T>();
        for (T elem : elems) {
            res.add(elem);
        }
        return res;
    }

    private static <T> List<T> asList(T... elems) {
        List<T> res = new ArrayList<T>();
        for (T elem : elems) {
            res.add(elem);
        }
        return res;
    }
}


text:
This is a prototype of a serverless platform built in C#/.NET using Microsoft Azure and Windows containers. The goals of this implementation are to improve the performance of serverless platforms and explore platform designs while maintaining a simple implementation.

## Implementation Overview

The platform depends upon Azure Storage for data persistence and for its messaging layer. Besides Azure Storage services, the implementation is comprised of two components: a web service which exposes the platform's public REST API, and a worker service which manages and executes function containers. The web service discovers available workers through a messaging layer consisting of various Azure Storage queues. Function metadata is stored in Azure Storage tables, and function code is stored in Azure Storage blobs.

A in-depth discussion of the current platform and its limitations is available here.

## Performance Measurements

Performance measurements of this prototype and other serverless platform was taken using a performance tool created to compare serverless offerings. Example performance measurements are available there, and in the paper linked above.

## Getting Started

Coming soon :)


text:
- added seo_identifier helper, in case you don't want to use URL

## version 0.1.2
- add noindex and nofollow
- show 'more options' link
- improved UI

## version 0.1.1
- improved UI

## version 0.0.9
- improved UI
- read defaults from YAML file

## version 0.0.8
- updated README
- added option to create default description and default keywords

## version 0.0.5
- copy locale files to config folder upon installation
- the button is now included in the same view helper as the dialog. Only use `<%= edit_seo_dialog %>` now


text:
#ifndef DFGSafeToExecute_h
#define DFGSafeToExecute_h

#include <wtf/Platform.h>

#if ENABLE(DFG_JIT)

#include "DFGGraph.h"

namespace JSC { namespace DFG {

template<typename AbstractStateType>
class SafeToExecuteEdge {
public:
    SafeToExecuteEdge(AbstractStateType& state)
        : m_state(state)
        , m_result(true)
    {
    }

    void operator()(Node*, Edge edge)
    {
        switch (edge.useKind()) {
        case UntypedUse:
        case Int32Use:
        case RealNumberUse:
        case NumberUse:
        case BooleanUse:
        case CellUse:
        case ObjectUse:
        case FinalObjectUse:
        case ObjectOrOtherUse:
        case StringIdentUse:
        case StringUse:
        case StringObjectUse:
        case StringOrStringObjectUse:
        case NotCellUse:
        case OtherUse:
        case MachineIntUse:
            return;

        case KnownInt32Use:
            if (m_state.forNode(edge).m_type & ~SpecInt32)
                m_result = false;
            return;

        case KnownNumberUse:
            if (m_state.forNode(edge).m_type & ~SpecFullNumber)
                m_result = false;
            return;

        case KnownCellUse:
            if (m_state.forNode(edge).m_type & ~SpecCell)
                m_result = false;
            return;

        case KnownStringUse:
            if (m_state.forNode(edge).m_type & ~SpecString)
                m_result = false;
            return;

        case LastUseKind:
            RELEASE_ASSERT_NOT_REACHED();
            break;
        }
        RELEASE_ASSERT_NOT_REACHED();
    }

    bool result() const { return m_result; }
private:
    AbstractStateType& m_state;
    bool m_result;
};

// Determines if it's safe to execute a node within the given abstract state. This may
// return false conservatively. If it returns true, then you can hoist the given node
// up to the given point and expect that it will not crash. This doesn't guarantee that
// the node will produce the result you wanted other than not crashing.
template<typename AbstractStateType>
bool safeToExecute(AbstractStateType& state, Graph& graph, Node* node)
{
    SafeToExecuteEdge<AbstractStateType> safeToExecuteEdge(state);
    DFG_NODE_DO_TO_CHILDREN(graph, node, safeToExecuteEdge);
    if (!safeToExecuteEdge.result())
        return false;

    switch (node->op()) {
    case JSConstant:
    case WeakJSConstant:
    case Identity:
    case ToThis:
    case CreateThis:
    case GetCallee:
    case SetCallee:
    case GetLocal:
    case SetLocal:
    case MovHintAndCheck:
    case MovHint:
    case ZombieHint:
    case GetArgument:
    case Phantom:
    case Upsilon:
    case Phi:
    case Flush:
    case PhantomLocal:
    case GetLocalUnlinked:
    case SetArgument:
    case InlineStart:
    case BitAnd:
    case BitOr:
    case BitXor:
    case BitLShift:
    case BitRShift:
    case BitURShift:
    case ValueToInt32:
    case UInt32ToNumber:
    case Int32ToDouble:
    case DoubleAsInt32:
    case ArithAdd:
    case ArithSub:
    case ArithNegate:
    case ArithMul:
    case ArithIMul:
    case ArithDiv:
    case ArithMod:
    case ArithAbs:
    case ArithMin:
    case ArithMax:
    case ArithSqrt:
    case ValueAdd:
    case GetById:
    case GetByIdFlush:
    case PutById:
    case PutByIdDirect:
    case CheckStructure:
    case CheckExecutable:
    case GetButterfly:
    case CheckArray:
    case Arrayify:
    case ArrayifyToStructure:
    case GetScope:
    case GetMyScope:
    case SetMyScope:
    case SkipTopScope:
    case SkipScope:
    case GetClosureRegisters:
    case GetClosureVar:
    case PutClosureVar:
    case GetGlobalVar:
    case PutGlobalVar:
    case GlobalVarWatchpoint:
    case VarInjectionWatchpoint:
    case CheckFunction:
    case AllocationProfileWatchpoint:
    case RegExpExec:
    case RegExpTest:
    case CompareLess:
    case CompareLessEq:
    case CompareGreater:
    case CompareGreaterEq:
    case CompareEq:
    case CompareEqConstant:
    case CompareStrictEq:
    case CompareStrictEqConstant:
    case Call:
    case Construct:
    case NewObject:
    case NewArray:
    case NewArrayWithSize:
    case NewArrayBuffer:
    case NewRegexp:
    case Breakpoint:
    case CheckHasInstance:
    case InstanceOf:
    case IsUndefined:
    case IsBoolean:
    case IsNumber:
    case IsString:
    case IsObject:
    case IsFunction:
    case TypeOf:
    case LogicalNot:
    case ToPrimitive:
    case ToString:
    case NewStringObject:
    case MakeRope:
    case In:
    case CreateActivation:
    case TearOffActivation:
    case CreateArguments:
    case PhantomArguments:
    case TearOffArguments:
    case GetMyArgumentsLength:
    case GetMyArgumentByVal:
    case GetMyArgumentsLengthSafe:
    case GetMyArgumentByValSafe:
    case CheckArgumentsNotCreated:
    case NewFunctionNoCheck:
    case NewFunction:
    case NewFunctionExpression:
    case Jump:
    case Branch:
    case Switch:
    case Return:
    case Throw:
    case ThrowReferenceError:
    case CountExecution:
    case ForceOSRExit:
    case CheckWatchdogTimer:
    case StringFromCharCode:
    case NewTypedArray:
    case Unreachable:
    case ExtractOSREntryLocal:
    case CheckTierUpInLoop:
    case CheckTierUpAtReturn:
    case CheckTierUpAndOSREnter:
    case LoopHint:
    case Int52ToDouble:
    case Int52ToValue:
        return true;

    case GetByVal:
    case GetIndexedPropertyStorage:
    case GetArrayLength:
    case ArrayPush:
    case ArrayPop:
    case StringCharAt:
    case StringCharCodeAt:
        return node->arrayMode().alreadyChecked(graph, node, state.forNode(node->child1()));

    case GetTypedArrayByteOffset:
        return !(state.forNode(node->child1()).m_type & ~(SpecTypedArrayView));

    case PutByVal:
    case PutByValAlias:
        return node->arrayMode().modeForPut().alreadyChecked(
            graph, node, state.forNode(graph.varArgChild(node, 0)));

    case StructureTransitionWatchpoint:
        return state.forNode(node->child1()).m_futurePossibleStructure.isSubsetOf(
            StructureSet(node->structure()));

    case PutStructure:
    case PhantomPutStructure:
    case AllocatePropertyStorage:
    case ReallocatePropertyStorage:
        return state.forNode(node->child1()).m_currentKnownStructure.isSubsetOf(
            StructureSet(node->structureTransitionData().previousStructure));

    case GetByOffset:
    case PutByOffset:
        return state.forNode(node->child1()).m_currentKnownStructure.isValidOffset(
            graph.m_storageAccessData[node->storageAccessDataIndex()].offset);

    case LastNodeType:
        RELEASE_ASSERT_NOT_REACHED();
        return false;
    }

    RELEASE_ASSERT_NOT_REACHED();
    return false;
}

} } // namespace JSC::DFG

#endif // ENABLE(DFG_JIT)

#endif // DFGSafeToExecute_h


text:
#ifndef __ECORE_MCP_H__
#define __ECORE_MCP_H__

#include "bcm_osal.h"
#include "mcp_public.h"
#include "ecore.h"
#include "ecore_mcp_api.h"
#include "ecore_dev_api.h"

/* Using hwfn number (and not pf_num) is required since in CMT mode,
 * same pf_num may be used by two different hwfn
 * TODO - this shouldn't really be in .h file, but until all fields
 * required during hw-init will be placed in their correct place in shmem
 * we need it in ecore_dev.c [for readin the nvram reflection in shmem].
 */
#define MCP_PF_ID_BY_REL(p_hwfn, rel_pfid) (ECORE_IS_BB((p_hwfn)->p_dev) ? \
					    ((rel_pfid) | \
					     ((p_hwfn)->abs_pf_id & 1) << 3) : \
					     rel_pfid)
#define MCP_PF_ID(p_hwfn)	MCP_PF_ID_BY_REL(p_hwfn, (p_hwfn)->rel_pf_id)

struct ecore_mcp_info {
	/* List for mailbox commands which were sent and wait for a response */
	osal_list_t cmd_list;

	/* Spinlock used for protecting the access to the mailbox commands list
	 * and the sending of the commands.
	 */
	osal_spinlock_t cmd_lock;

	/* Flag to indicate whether sending a MFW mailbox command is blocked */
	bool b_block_cmd;

	/* Spinlock used for syncing SW link-changes and link-changes
	 * originating from attention context.
	 */
	osal_spinlock_t link_lock;

	/* Address of the MCP public area */
	u32 public_base;
	/* Address of the driver mailbox */
	u32 drv_mb_addr;
	/* Address of the MFW mailbox */
	u32 mfw_mb_addr;
	/* Address of the port configuration (link) */
	u32 port_addr;

	/* Current driver mailbox sequence */
	u16 drv_mb_seq;
	/* Current driver pulse sequence */
	u16 drv_pulse_seq;

	struct ecore_mcp_link_params       link_input;
	struct ecore_mcp_link_state	   link_output;
	struct ecore_mcp_link_capabilities link_capabilities;

	struct ecore_mcp_function_info	   func_info;

	u8 *mfw_mb_cur;
	u8 *mfw_mb_shadow;
	u16 mfw_mb_length;
	u32 mcp_hist;

	/* Capabilties negotiated with the MFW */
	u32 capabilities;
};

struct ecore_mcp_mb_params {
	u32 cmd;
	u32 param;
	void *p_data_src;
	void *p_data_dst;
	u32 mcp_resp;
	u32 mcp_param;
	u8 data_src_size;
	u8 data_dst_size;
	u32 flags;
#define ECORE_MB_FLAG_CAN_SLEEP         (0x1 << 0)
#define ECORE_MB_FLAG_AVOID_BLOCK       (0x1 << 1)
#define ECORE_MB_FLAGS_IS_SET(params, flag) \
	((params) != OSAL_NULL && ((params)->flags & ECORE_MB_FLAG_##flag))
};

struct ecore_drv_tlv_hdr {
	u8 tlv_type;	/* According to the enum below */
	u8 tlv_length;	/* In dwords - not including this header */
	u8 tlv_reserved;
#define ECORE_DRV_TLV_FLAGS_CHANGED 0x01
	u8 tlv_flags;
};

/**
 * @brief Initialize the interface with the MCP
 *
 * @param p_hwfn - HW func
 * @param p_ptt - PTT required for register access
 *
 * @return enum _ecore_status_t
 */
enum _ecore_status_t ecore_mcp_cmd_init(struct ecore_hwfn *p_hwfn,
					struct ecore_ptt *p_ptt);

/**
 * @brief Initialize the port interface with the MCP
 *
 * @param p_hwfn
 * @param p_ptt
 * Can only be called after `num_ports_in_engine' is set
 */
void ecore_mcp_cmd_port_init(struct ecore_hwfn *p_hwfn,
			     struct ecore_ptt *p_ptt);
/**
 * @brief Releases resources allocated during the init process.
 *
 * @param p_hwfn - HW func
 * @param p_ptt - PTT required for register access
 *
 * @return enum _ecore_status_t
 */

enum _ecore_status_t ecore_mcp_free(struct ecore_hwfn *p_hwfn);

/**
 * @brief This function is called from the DPC context. After
 * pointing PTT to the mfw mb, check for events sent by the MCP
 * to the driver and ack them. In case a critical event
 * detected, it will be handled here, otherwise the work will be
 * queued to a sleepable work-queue.
 *
 * @param p_hwfn - HW function
 * @param p_ptt - PTT required for register access
 * @return enum _ecore_status_t - ECORE_SUCCESS - operation
 * was successul.
 */
enum _ecore_status_t ecore_mcp_handle_events(struct ecore_hwfn *p_hwfn,
					     struct ecore_ptt *p_ptt);

/**
 * @brief When MFW doesn't get driver pulse for couple of seconds, at some
 * threshold before timeout expires, it will generate interrupt
 * through a dedicated status block (DPSB - Driver Pulse Status
 * Block), which the driver should respond immediately, by
 * providing keepalive indication after setting the PTT to the
 * driver-MFW mailbox. This function is called directly from the
 * DPC upon receiving the DPSB attention.
 *
 * @param p_hwfn - hw function
 * @param p_ptt - PTT required for register access
 * @return enum _ecore_status_t - ECORE_SUCCESS - operation
 * was successful.
 */
enum _ecore_status_t ecore_issue_pulse(struct ecore_hwfn *p_hwfn,
				       struct ecore_ptt *p_ptt);

enum ecore_drv_role {
	ECORE_DRV_ROLE_OS,
	ECORE_DRV_ROLE_KDUMP,
};

struct ecore_load_req_params {
	/* Input params */
	enum ecore_drv_role drv_role;
	u8 timeout_val; /* 1..254, '0' - default value, '255' - no timeout */
	bool avoid_eng_reset;
	enum ecore_override_force_load override_force_load;

	/* Output params */
	u32 load_code;
};

/**
 * @brief Sends a LOAD_REQ to the MFW, and in case the operation succeeds,
 *        returns whether this PF is the first on the engine/port or function.
 *
 * @param p_hwfn
 * @param p_ptt
 * @param p_params
 *
 * @return enum _ecore_status_t - ECORE_SUCCESS - Operation was successful.
 */
enum _ecore_status_t ecore_mcp_load_req(struct ecore_hwfn *p_hwfn,
					struct ecore_ptt *p_ptt,
					struct ecore_load_req_params *p_params);

/**
 * @brief Sends a LOAD_DONE message to the MFW
 *
 * @param p_hwfn
 * @param p_ptt
 *
 * @return enum _ecore_status_t - ECORE_SUCCESS - Operation was successful.
 */
enum _ecore_status_t ecore_mcp_load_done(struct ecore_hwfn *p_hwfn,
					 struct ecore_ptt *p_ptt);

/**
 * @brief Sends a UNLOAD_REQ message to the MFW
 *
 * @param p_hwfn
 * @param p_ptt
 *
 * @return enum _ecore_status_t - ECORE_SUCCESS - Operation was successful.
 */
enum _ecore_status_t ecore_mcp_unload_req(struct ecore_hwfn *p_hwfn,
					  struct ecore_ptt *p_ptt);

/**
 * @brief Sends a UNLOAD_DONE message to the MFW
 *
 * @param p_hwfn
 * @param p_ptt
 *
 * @return enum _ecore_status_t - ECORE_SUCCESS - Operation was successful.
 */
enum _ecore_status_t ecore_mcp_unload_done(struct ecore_hwfn *p_hwfn,
					   struct ecore_ptt *p_ptt);

/**
 * @brief Read the MFW mailbox into Current buffer.
 *
 * @param p_hwfn
 * @param p_ptt
 */
void ecore_mcp_read_mb(struct ecore_hwfn *p_hwfn,
		       struct ecore_ptt *p_ptt);

/**
 * @brief Ack to mfw that driver finished FLR process for VFs
 *
 * @param p_hwfn
 * @param p_ptt
 * @param vfs_to_ack - bit mask of all engine VFs for which the PF acks.
 *
 * @param return enum _ecore_status_t - ECORE_SUCCESS upon success.
 */
enum _ecore_status_t ecore_mcp_ack_vf_flr(struct ecore_hwfn *p_hwfn,
					  struct ecore_ptt *p_ptt,
					  u32 *vfs_to_ack);

/**
 * @brief - calls during init to read shmem of all function-related info.
 *
 * @param p_hwfn
 *
 * @param return ECORE_SUCCESS upon success.
 */
enum _ecore_status_t ecore_mcp_fill_shmem_func_info(struct ecore_hwfn *p_hwfn,
						    struct ecore_ptt *p_ptt);

/**
 * @brief - Reset the MCP using mailbox command.
 *
 * @param p_hwfn
 * @param p_ptt
 *
 * @param return ECORE_SUCCESS upon success.
 */
enum _ecore_status_t ecore_mcp_reset(struct ecore_hwfn *p_hwfn,
				     struct ecore_ptt *p_ptt);

/**
 * @brief indicates whether the MFW objects [under mcp_info] are accessible
 *
 * @param p_hwfn
 *
 * @return true iff MFW is running and mcp_info is initialized
 */
bool ecore_mcp_is_init(struct ecore_hwfn *p_hwfn);

/**
 * @brief request MFW to configure MSI-X for a VF
 *
 * @param p_hwfn
 * @param p_ptt
 * @param vf_id - absolute inside engine
 * @param num_sbs - number of entries to request
 *
 * @return enum _ecore_status_t
 */
enum _ecore_status_t ecore_mcp_config_vf_msix(struct ecore_hwfn *p_hwfn,
					      struct ecore_ptt *p_ptt,
					      u8 vf_id, u8 num);

/**
 * @brief - Halt the MCP.
 *
 * @param p_hwfn
 * @param p_ptt
 *
 * @param return ECORE_SUCCESS upon success.
 */
enum _ecore_status_t ecore_mcp_halt(struct ecore_hwfn *p_hwfn,
				    struct ecore_ptt *p_ptt);

/**
 * @brief - Wake up the MCP.
 *
 * @param p_hwfn
 * @param p_ptt
 *
 * @param return ECORE_SUCCESS upon success.
 */
enum _ecore_status_t ecore_mcp_resume(struct ecore_hwfn *p_hwfn,
				      struct ecore_ptt *p_ptt);
int __ecore_configure_pf_max_bandwidth(struct ecore_hwfn *p_hwfn,
				       struct ecore_ptt *p_ptt,
				       struct ecore_mcp_link_state *p_link,
				       u8 max_bw);
int __ecore_configure_pf_min_bandwidth(struct ecore_hwfn *p_hwfn,
				       struct ecore_ptt *p_ptt,
				       struct ecore_mcp_link_state *p_link,
				       u8 min_bw);
enum _ecore_status_t ecore_mcp_mask_parities(struct ecore_hwfn *p_hwfn,
					     struct ecore_ptt *p_ptt,
					     u32 mask_parities);
/**
 * @brief - Sends crash mdump related info to the MFW.
 *
 * @param p_hwfn
 * @param p_ptt
 *
 * @param return ECORE_SUCCESS upon success.
 */
enum _ecore_status_t ecore_mcp_mdump_set_values(struct ecore_hwfn *p_hwfn,
						struct ecore_ptt *p_ptt,
						u32 epoch);

/**
 * @brief - Triggers a MFW crash dump procedure.
 *
 * @param p_hwfn
 * @param p_ptt
 * @param epoch
 *
 * @param return ECORE_SUCCESS upon success.
 */
enum _ecore_status_t ecore_mcp_mdump_trigger(struct ecore_hwfn *p_hwfn,
					     struct ecore_ptt *p_ptt);

struct ecore_mdump_retain_data {
	u32 valid;
	u32 epoch;
	u32 pf;
	u32 status;
};

/**
 * @brief - Gets the mdump retained data from the MFW.
 *
 * @param p_hwfn
 * @param p_ptt
 * @param p_mdump_retain
 *
 * @param return ECORE_SUCCESS upon success.
 */
enum _ecore_status_t
ecore_mcp_mdump_get_retain(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt,
			   struct ecore_mdump_retain_data *p_mdump_retain);

/**
 * @brief - Sets the MFW's max value for the given resource
 *
 *  @param p_hwfn
 *  @param p_ptt
 *  @param res_id
 *  @param resc_max_val
 *  @param p_mcp_resp
 *
 * @return enum _ecore_status_t - ECORE_SUCCESS - operation was successful.
 */
enum _ecore_status_t
ecore_mcp_set_resc_max_val(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt,
			   enum ecore_resources res_id, u32 resc_max_val,
			   u32 *p_mcp_resp);

/**
 * @brief - Gets the MFW allocation info for the given resource
 *
 *  @param p_hwfn
 *  @param p_ptt
 *  @param res_id
 *  @param p_mcp_resp
 *  @param p_resc_num
 *  @param p_resc_start
 *
 * @return enum _ecore_status_t - ECORE_SUCCESS - operation was successful.
 */
enum _ecore_status_t
ecore_mcp_get_resc_info(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt,
			enum ecore_resources res_id, u32 *p_mcp_resp,
			u32 *p_resc_num, u32 *p_resc_start);

/**
 * @brief - Initiates PF FLR
 *
 * @param p_hwfn
 * @param p_ptt
 *
 * @param return ECORE_SUCCESS upon success.
 */
enum _ecore_status_t ecore_mcp_initiate_pf_flr(struct ecore_hwfn *p_hwfn,
					       struct ecore_ptt *p_ptt);

#define ECORE_MCP_RESC_LOCK_MIN_VAL	RESOURCE_DUMP /* 0 */
#define ECORE_MCP_RESC_LOCK_MAX_VAL	31

enum ecore_resc_lock {
	ECORE_RESC_LOCK_DBG_DUMP = ECORE_MCP_RESC_LOCK_MIN_VAL,
	/* Locks that the MFW is aware of should be added here downwards */

	/* Ecore only locks should be added here upwards */
	ECORE_RESC_LOCK_RESC_ALLOC = ECORE_MCP_RESC_LOCK_MAX_VAL,

	/* A dummy value to be used for auxiliary functions in need of
	 * returning an 'error' value.
	 */
	ECORE_RESC_LOCK_RESC_INVALID,
};

struct ecore_resc_lock_params {
	/* Resource number [valid values are 0..31] */
	u8 resource;

	/* Lock timeout value in seconds [default, none or 1..254] */
	u8 timeout;
#define ECORE_MCP_RESC_LOCK_TO_DEFAULT	0
#define ECORE_MCP_RESC_LOCK_TO_NONE	255

	/* Number of times to retry locking */
	u8 retry_num;
#define ECORE_MCP_RESC_LOCK_RETRY_CNT_DFLT	10

	/* The interval in usec between retries */
	u16 retry_interval;
#define ECORE_MCP_RESC_LOCK_RETRY_VAL_DFLT	10000

	/* Use sleep or delay between retries */
	bool sleep_b4_retry;

	/* Will be set as true if the resource is free and granted */
	bool b_granted;

	/* Will be filled with the resource owner.
	 * [0..15 = PF0-15, 16 = MFW, 17 = diag over serial]
	 */
	u8 owner;
};

/**
 * @brief Acquires MFW generic resource lock
 *
 *  @param p_hwfn
 *  @param p_ptt
 *  @param p_params
 *
 * @return enum _ecore_status_t - ECORE_SUCCESS - operation was successful.
 */
enum _ecore_status_t
ecore_mcp_resc_lock(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt,
		    struct ecore_resc_lock_params *p_params);

struct ecore_resc_unlock_params {
	/* Resource number [valid values are 0..31] */
	u8 resource;

	/* Allow to release a resource even if belongs to another PF */
	bool b_force;

	/* Will be set as true if the resource is released */
	bool b_released;
};

/**
 * @brief Releases MFW generic resource lock
 *
 *  @param p_hwfn
 *  @param p_ptt
 *  @param p_params
 *
 * @return enum _ecore_status_t - ECORE_SUCCESS - operation was successful.
 */
enum _ecore_status_t
ecore_mcp_resc_unlock(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt,
		      struct ecore_resc_unlock_params *p_params);

/**
 * @brief - default initialization for lock/unlock resource structs
 *
 * @param p_lock - lock params struct to be initialized; Can be OSAL_NULL
 * @param p_unlock - unlock params struct to be initialized; Can be OSAL_NULL
 * @param resource - the requested resource
 * @paral b_is_permanent - disable retries & aging when set
 */
void ecore_mcp_resc_lock_default_init(struct ecore_resc_lock_params *p_lock,
				      struct ecore_resc_unlock_params *p_unlock,
				      enum ecore_resc_lock resource,
				      bool b_is_permanent);

/**
 * @brief Learn of supported MFW features; To be done during early init
 *
 * @param p_hwfn
 * @param p_ptt
 */
enum _ecore_status_t ecore_mcp_get_capabilities(struct ecore_hwfn *p_hwfn,
						struct ecore_ptt *p_ptt);

/**
 * @brief Inform MFW of set of features supported by driver. Should be done
 * inside the contet of the LOAD_REQ.
 *
 * @param p_hwfn
 * @param p_ptt
 */
enum _ecore_status_t ecore_mcp_set_capabilities(struct ecore_hwfn *p_hwfn,
						struct ecore_ptt *p_ptt);

enum ecore_mcp_drv_attr_cmd {
	ECORE_MCP_DRV_ATTR_CMD_READ,
	ECORE_MCP_DRV_ATTR_CMD_WRITE,
	ECORE_MCP_DRV_ATTR_CMD_READ_CLEAR,
	ECORE_MCP_DRV_ATTR_CMD_CLEAR,
};

struct ecore_mcp_drv_attr {
	enum ecore_mcp_drv_attr_cmd attr_cmd;
	u32 attr_num;

	/* R/RC - will be set with the read value
	 * W - should hold the required value to be written
	 * C - DC
	 */
	u32 val;

	/* W - mask/offset to be applied on the given value
	 * R/RC/C - DC
	 */
	u32 mask;
	u32 offset;
};

/**
 * @brief Handle the drivers' attributes that are kept by the MFW.
 *
 * @param p_hwfn
 * @param p_ptt
 * @param p_drv_attr
 */
enum _ecore_status_t
ecore_mcp_drv_attribute(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt,
			struct ecore_mcp_drv_attr *p_drv_attr);

/**
 * @brief Read ufp config from the shared memory.
 *
 * @param p_hwfn
 * @param p_ptt
 */
void
ecore_mcp_read_ufp_config(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt);

void ecore_mcp_wol_wr(struct ecore_hwfn *p_hwfn, struct ecore_ptt *p_ptt,
		      u32 offset, u32 val);

/**
 * @brief Get the engine affinity configuration.
 *
 * @param p_hwfn
 * @param p_ptt
 */
enum _ecore_status_t ecore_mcp_get_engine_config(struct ecore_hwfn *p_hwfn,
						 struct ecore_ptt *p_ptt);

/**
 * @brief Get the PPFID bitmap.
 *
 * @param p_hwfn
 * @param p_ptt
 */
enum _ecore_status_t ecore_mcp_get_ppfid_bitmap(struct ecore_hwfn *p_hwfn,
						struct ecore_ptt *p_ptt);

#endif /* __ECORE_MCP_H__ */


text:
Flot plugin to create bubble charts

## Example

* [Open Demo](http://mojoaxel.github.io/flot-bubbles/example/)
* [Show example source](https://github.com/mojoaxel/flot-bubbles/blob/master/example/index.html)

## Docs

```JavaScript
var d1 = [[20,20,10], [40,50,20], [70,10,5], [80,80,15]];
var d2 = [[60,25,15], [70,40,6], [30,80,4]];
var options = {
	series: {
		//color: '#CCC',
		color: function(x, y, value) {
			var red = 55 + value * 10;
			return 'rgba('+red+',50,50,1)';
		},
		bubbles: {
			active: true,
			show: true,
			fill: true,
			linewidth: 2,
			bubblelabel: { show: true }
		}
	},
	grid:{
		hoverable: true,
		clickable: true
	}
};
var p4 = $.plot( $("#plot"), [ d1, { color: '#AAA', data: d2 }], options );
```

* **data:** Data Array specific for Bubbles chart
   * **[0]:** first data entry
      * **[0]:** Y-value, location of bubble
      * **[1]:** X-value, location of value
      * **[2]:** Size of bubble

* **options:** options for bubbles
   * **series:** series options for bubbles
   * **bubbles:** bubbles only options
      * **active:** activate the plugin (false)
      * **show:** show specific serie. this needs to be overwritten in data (false)
      * **fill:** Fill bubbles (true)
      * **lineWidth:** Line width of circle if fill is false (2)
      * **highlight:** Used to highlight in case of HOVER
         * **opacity:** only Opacity is supported for Highlighting (yet) (0.5)
      * **drawbubble:** Function call which is used for drawing of one bar for Bubble. This can be replaced by user defined function. Take a closer look to source of examples to see more. (drawbubbleDefault(ctx,serie,x,y,v,r,c,overlay))
      * **bubblelabel:** Specific options how to show label in bubbles
         * **show:** Switches labels on (or off) (false)
         * **fillStyle:** Color of text (black)
      * **editMode:** Default Editmode for bandwidth. See mouse plugin for more information.
      * **nearBy:** data used to support findItem for hover, click etc.
         * **distance:** distance in pixel to find nearest bubble (6)
         * **findMode:** Defines how find happens. (circle)
         * **findItem:** Function call to find item under Cursor. Is overwritten during processRawData hook. This would be the place to add your own find function, which will not be overwritten. (findNearbyItemDefault(mouseX,mouseY,i,serie))
         * **drawEdit:** function to draw edit marker. It is defined in jquery.flot.mouse plugin, and is overwritten in plugin to support specific editmarkers (drawEditDefault(octx,x,y,serie))
         * **drawHover:** Function to draw overlay in case of hover a item. Is overwritten during processRawData hook. This would be the place to add your own hover drawing function. (drawHoverDefault(octx,serie,dataIndex))
      * **findMode:** Choose between selecting either the most nearby bubble, or the first one that is encountered. (nearby)

### Options

#### Simple

* **series**
   * **bubbles**
      * **active:** [true] boolean
      * **show:** [true] boolean
      * **fill:** [true] boolean
      * **lineWidth:** [2] number
* **grid**
   * **hoverable:** [true] boolean
   * **clickable:** [true] boolean

#### With Label

* **series**
   * **bubbles**
      * **active** [true] boolean
      * **show** [true] boolean
      * **fill** [true] boolean
      * **linewidth** [2] number
      * **bubblelabel:** object
         * **show** [true] boolean
* **grid**
   * **hoverable** [true] boolean
   * **clickable** [true] boolean

#### Userdefined Drawing

* **series**
   * **bubbles**
      * **active** [true] boolean
      * **show** [true] boolean
      * **fill** [true] boolean
      * **lineWidth** [2] number
      * **drawbubble** function
* **grid**
   * **hoverable** [true] boolean
   * **clickable** [true] boolean

#### Editing

* **series**
   * **bubbles**
      * **active** [true] boolean
      * **show** [true] boolean
      * **linewidth** [2] number
      * **editMode** [xy] string
      * **editable** [true] boolean
* **grid**
   * **hoverable** [true] boolean
   * **clickable** [true] boolean
   * **editable** [true] boolean

## License

Licensed under [MIT](http://opensource.org/licenses/MIT)

This plugin is based on a [plugin](https://github.com/jumjum123/JUMFlot/blob/gh-pages/javascripts/jquery.flot.bubbles.js) by [Juergen Marsch](https://github.com/jumjum123)

## Versions

### 0.3.0
* first release of Juergen Marsch's original code

### 0.3.1
* removed dependency to JUMlib

### 0.3.2
* code cleanup

### 0.3.3
* `series.color` can be of type `function` (thx @stesie)

### 0.4.0
* support 'plothover' events; (issue #2)
* support the `jquery.flot.tooltip` plugin
* code cleanup

### 0.4.1
* bugfix if x or y == 0; (issue #2)

### 0.4.2
* bugfix: only load plugin if options.series.bubbles.active is set; (issue #3)


text:
package org.jetbrains.idea.maven.importing;

import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.idea.maven.MavenMultiVersionImportingTestCase;
import org.junit.Test;

import java.io.File;

public class SnapshotDependenciesImportingTest extends MavenMultiVersionImportingTestCase {
  private File remoteRepoDir;

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    // disable local mirrors
    updateSettingsXmlFully("<settings></settings>");
  }

  @Override
  protected void setUpInWriteAction() throws Exception {
    super.setUpInWriteAction();

    remoteRepoDir = new File(myDir, "remote");
    remoteRepoDir.mkdirs();
  }

  @Test
  public void testSnapshotVersionDependencyToModule() throws Exception {
    performTestWithDependencyVersion("1-SNAPSHOT");
  }

  @Test
  public void testSnapshotRangeDependencyToModule() throws Exception {
    performTestWithDependencyVersion("SNAPSHOT");
  }

  private void performTestWithDependencyVersion(String version) throws Exception {
    if (!hasMavenInstallation()) return;

    createProjectPom("<groupId>test</groupId>" +
                     "<artifactId>project</artifactId>" +
                     "<packaging>pom</packaging>" +
                     "<version>1</version>" +

                     "<modules>" +
                     "  <module>m1</module>" +
                     "  <module>m2</module>" +
                     "</modules>");

    createModulePom("m1", "<groupId>test</groupId>" +
                          "<artifactId>m1</artifactId>" +
                          "<version>1</version>" +

                          repositoriesSection() +

                          "<dependencies>" +
                          "  <dependency>" +
                          "    <groupId>test</groupId>" +
                          "    <artifactId>m2</artifactId>" +
                          "    <version>" + version + "</version>" +
                          "  </dependency>" +
                          "</dependencies>");

    createModulePom("m2", "<groupId>test</groupId>" +
                          "<artifactId>m2</artifactId>" +
                          "<version>" + version + "</version>" +

                          distributionManagementSection());

    importProject();
    assertModules("project", "m1", "m2");
    assertModuleModuleDeps("m1", "m2");

    // in order to force maven to resolve dependency into remote one we have to
    // clean up local repository.
    deploy("m2");
    removeFromLocalRepository("test");

    importProject();

    assertModules("project", "m1", "m2");
    assertModuleModuleDeps("m1", "m2");
  }

  @Test
  public void testNamingLibraryTheSameWayRegardlessAvailableSnapshotVersion() throws Exception {
    if (!hasMavenInstallation()) return;

    deployArtifact("test", "foo", "1-SNAPSHOT");

    importProject("<groupId>test</groupId>" +
                  "<artifactId>project</artifactId>" +
                  "<version>1</version>" +

                  repositoriesSection() +

                  "<dependencies>" +
                  "  <dependency>" +
                  "    <groupId>test</groupId>" +
                  "    <artifactId>foo</artifactId>" +
                  "    <version>1-SNAPSHOT</version>" +
                  "  </dependency>" +
                  "</dependencies>");
    assertModuleLibDeps("project", "Maven: test:foo:1-SNAPSHOT");

    removeFromLocalRepository("test");

    importProject();
    assertModuleLibDeps("project", "Maven: test:foo:1-SNAPSHOT");
  }

  @Test
  public void testAttachingCorrectJavaDocsAndSources() throws Exception {
    if (!hasMavenInstallation()) return;

    deployArtifact("test", "foo", "1-SNAPSHOT",
                   "<build>" +
                   "  <plugins>" +
                   "    <plugin>" +
                   "      <artifactId>maven-source-plugin</artifactId>" +
                   "      <executions>" +
                   "        <execution>" +
                   "          <goals>" +
                   "            <goal>jar</goal>" +
                   "          </goals>" +
                   "        </execution>" +
                   "      </executions>" +
                   "    </plugin>" +
                   "    <plugin>" +
                   "      <artifactId>maven-javadoc-plugin</artifactId>" +
                   "      <executions>" +
                   "        <execution>" +
                   "          <goals>" +
                   "            <goal>jar</goal>" +
                   "          </goals>" +
                   "        </execution>" +
                   "      </executions>" +
                   "    </plugin>" +
                   "  </plugins>" +
                   "</build>");

    removeFromLocalRepository("test");

    importProject("<groupId>test</groupId>" +
                  "<artifactId>project</artifactId>" +
                  "<version>1</version>" +

                  repositoriesSection() +

                  "<dependencies>" +
                  "  <dependency>" +
                  "    <groupId>test</groupId>" +
                  "    <artifactId>foo</artifactId>" +
                  "    <version>1-SNAPSHOT</version>" +
                  "  </dependency>" +
                  "</dependencies>");
    assertModuleLibDeps("project", "Maven: test:foo:1-SNAPSHOT");

    resolveDependenciesAndImport();
    downloadArtifacts();

    assertModuleLibDep("project",
                       "Maven: test:foo:1-SNAPSHOT",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT.jar!/",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT-sources.jar!/",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT-javadoc.jar!/");

    assertTrue(new File(getRepositoryFile(), "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT.jar").exists());
    assertTrue(new File(getRepositoryFile(), "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT-sources.jar").exists());
    assertTrue(new File(getRepositoryFile(), "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT-javadoc.jar").exists());
  }

  @Test
  public void testCorrectlryUpdateRootEntriesWithActualPathForSnapshotDependencies() throws Exception {
    if (!hasMavenInstallation()) return;

    deployArtifact("test", "foo", "1-SNAPSHOT",
                   "<build>" +
                   "  <plugins>" +
                   "    <plugin>" +
                   "      <artifactId>maven-source-plugin</artifactId>" +
                   "      <executions>" +
                   "        <execution>" +
                   "          <goals>" +
                   "            <goal>jar</goal>" +
                   "          </goals>" +
                   "        </execution>" +
                   "      </executions>" +
                   "    </plugin>" +
                   "    <plugin>" +
                   "      <artifactId>maven-javadoc-plugin</artifactId>" +
                   "      <executions>" +
                   "        <execution>" +
                   "          <goals>" +
                   "            <goal>jar</goal>" +
                   "          </goals>" +
                   "        </execution>" +
                   "      </executions>" +
                   "    </plugin>" +
                   "  </plugins>" +
                   "</build>");
    removeFromLocalRepository("test");

    importProject("<groupId>test</groupId>" +
                  "<artifactId>project</artifactId>" +
                  "<version>1</version>" +

                  repositoriesSection() +

                  "<dependencies>" +
                  "  <dependency>" +
                  "    <groupId>test</groupId>" +
                  "    <artifactId>foo</artifactId>" +
                  "    <version>1-SNAPSHOT</version>" +
                  "  </dependency>" +
                  "</dependencies>");
    assertModuleLibDeps("project", "Maven: test:foo:1-SNAPSHOT");

    resolveDependenciesAndImport();
    downloadArtifacts();

    assertModuleLibDep("project",
                       "Maven: test:foo:1-SNAPSHOT",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT.jar!/",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT-sources.jar!/",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT-javadoc.jar!/");

    deployArtifact("test", "foo", "1-SNAPSHOT",
                   "<build>" +
                   "  <plugins>" +
                   "    <plugin>" +
                   "      <artifactId>maven-source-plugin</artifactId>" +
                   "      <executions>" +
                   "        <execution>" +
                   "          <goals>" +
                   "            <goal>jar</goal>" +
                   "          </goals>" +
                   "        </execution>" +
                   "      </executions>" +
                   "    </plugin>" +
                   "    <plugin>" +
                   "      <artifactId>maven-javadoc-plugin</artifactId>" +
                   "      <executions>" +
                   "        <execution>" +
                   "          <goals>" +
                   "            <goal>jar</goal>" +
                   "          </goals>" +
                   "        </execution>" +
                   "      </executions>" +
                   "    </plugin>" +
                   "  </plugins>" +
                   "</build>");
    removeFromLocalRepository("test");

    scheduleResolveAll();
    resolveDependenciesAndImport();

    assertModuleLibDep("project",
                       "Maven: test:foo:1-SNAPSHOT",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT.jar!/",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT-sources.jar!/",
                       "jar://" + getRepositoryPath() + "/test/foo/1-SNAPSHOT/foo-1-SNAPSHOT-javadoc.jar!/");
  }

  private void deployArtifact(String groupId, String artifactId, String version) throws Exception {
    deployArtifact(groupId, artifactId, version, "");
  }

  private void deployArtifact(String groupId, String artifactId, String version, String tail) throws Exception {
    String moduleName = "___" + artifactId;

    createProjectSubFile(moduleName + "/src/main/java/Foo.java",
                         "/**\n" +
                         " * some doc\n" +
                         " */\n" +
                         "public class Foo { }");

    VirtualFile m = createModulePom(moduleName,
                                    "<groupId>" + groupId + "</groupId>" +
                                    "<artifactId>" + artifactId + "</artifactId>" +
                                    "<version>" + version + "</version>" +

                                    distributionManagementSection() +

                                    tail);

    deploy(moduleName);
    FileUtil.delete(new File(m.getParent().getPath()));
  }

  private void deploy(String modulePath) throws Exception {
    executeGoal(modulePath, "deploy");
  }

  private String repositoriesSection() {
    return "<repositories>" +
           "  <repository>" +
           "    <id>internal</id>" +
           "    <url>file:///" + FileUtil.toSystemIndependentName(remoteRepoDir.getPath()) + "</url>" +
           "    <snapshots>" +
           "      <enabled>true</enabled>" +
           "      <updatePolicy>always</updatePolicy>" +
           "    </snapshots>" +
           "  </repository>" +
           "</repositories>";
  }

  private String distributionManagementSection() {
    return "<distributionManagement>" +
           "  <snapshotRepository>" +
           "    <id>internal</id>" +
           "    <url>file:///" + FileUtil.toSystemIndependentName(remoteRepoDir.getPath()) + "</url>" +
           "  </snapshotRepository>" +
           "</distributionManagement>";
  }
}


text:
using System;

namespace Aspose.Cells.Examples.CSharp.Articles
{
    class SettingScaleCropAndLinksUpToDateProperties
    {
        public static void Run()
        {
            //Output directory
            string outputDir = RunExamples.Get_OutputDirectory();

            // Instantiating a Workbook object
            Workbook workbook = new Workbook();

            // Setting ScaleCrop and LinksUpToDate BuiltIn Document Properties
            workbook.BuiltInDocumentProperties.ScaleCrop = true;
            workbook.BuiltInDocumentProperties.LinksUpToDate = true;

            // Saving the Excel file
            workbook.Save(outputDir + "outputSettingScaleCropAndLinksUpToDateProperties.xlsx", SaveFormat.Xlsx);

            Console.WriteLine("SettingScaleCropAndLinksUpToDateProperties executed successfully.");
        }
    }
}


text:
import unittest

from vodem.api import unlock_nck_time

class TestUnlockNckTime(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.valid_response = {
            'unlock_nck_time': '',
        }

    def test_call(self):
        resp = unlock_nck_time()
        self.assertEqual(self.valid_response, resp)


text:
#   # we know what the max number is overall

#   hash_list.each {|key, value| new_list << key if (value == max_num) }

#   new_list
# end

# p mode(["who", "what", "where", "who"])

# 3. Refactored Solution

def mode(list)
  hash_list =  Hash.new(0)
  list.each {|x| hash_list[x] += 1 }

  p hash_list

  new_list = []

  # max_num = hash_list.max_by { |key, value| value }[1]
  # hash_list.each { |key, value|
  #   new_list << key if (value == max_num)
  # }

  max_num = hash_list.max_by { |key, value| value }[1]

  # parition returns an array where element 0 = array of true matches
  # element 1 = array of false matches
  # In addition, each key-value pair is in a two-element array (not a hash)
  # with key as first element, value as second element.
  # Since we only care about array of keys with true value matches == max_num,
  # we then create an array of keys (element 0 of the key-value array) using "map"
  return hash_list.partition { |key, value|
    value == max_num
  }[0].map{|arr| arr[0] }

end

p mode(["who", "what", "where", "who"])

# # 4. Reflection

# * Which data structure did you and your pair decide to implement and why?

# We used hash because we needed to maintain a counter for each item in the list, since it could be repeated.

# * Were you more successful breaking this problem down into implementable pseudocode than the last with a pair?

# Yes. Having had more practice with pseudo-code by this time, it made this implementation easier.

# * What issues/successes did you run into when translating your pseudocode to code?

# We didn't really run into issues during the pseudo-code to code translation. Rather we had difficulty in refactoring to find the correct, most-efficient built-in methods.

# * What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement?

# We used several including partition, map, max_by and each. We did find some good ones, like max_by and partition. We had difficulty trying to create an array from "each" only to later realize what we needed was "map".


text:
package com.pivotal.gemfirexd.internal.engine.distributed.metadata;

import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils;
import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.sql.compile.Visitable;
import com.pivotal.gemfirexd.internal.impl.sql.compile.AndNode;
import com.pivotal.gemfirexd.internal.impl.sql.compile.DeleteNode;
import com.pivotal.gemfirexd.internal.impl.sql.compile.FromBaseTable;
import com.pivotal.gemfirexd.internal.impl.sql.compile.ProjectRestrictNode;
import com.pivotal.gemfirexd.internal.impl.sql.compile.ResultColumn;

public class DeleteQueryInfo extends DMLQueryInfo {

  private boolean isDeleteWithReferencedKeys;
  private int deleteTargetTableNum = -1;
  public DeleteQueryInfo(QueryInfoContext qic) throws StandardException {
    super(qic);
    qic.setRootQueryInfo(this);
    //By default assume that it is primary key based & we will negate it later in the init
    this.queryType = GemFireXDUtils.set(this.queryType, IS_PRIMARY_KEY_TYPE);
  }

  @Override
  public void init() throws StandardException {
    super.init();
//    Iterator<PredicateList>  itr = this.wherePredicateList.iterator();
//    while(itr.hasNext()) {
//      this.handlePredicateList(itr.next());
//      itr.remove();
//    }
    TableQueryInfo tqi = null;
    // Is Convertible to get
    if (this.tableQueryInfoList.size() != 1
        || !(tqi = this.tableQueryInfoList.get(0)).isPrimaryKeyBased()
        || !isWhereClauseSatisfactory(tqi) ) {
      this.queryType = GemFireXDUtils
          .clear(this.queryType, IS_PRIMARY_KEY_TYPE);
    }

    final GemFireContainer container = (GemFireContainer)getTargetRegion()
        .getUserAttribute();
    if(!container.isTemporaryContainer()) {
      this.isDeleteWithReferencedKeys = container.getExtraTableInfo()
      .getReferencedKeyColumns() != null;
    }
    else {
      this.isDeleteWithReferencedKeys = false;
    }
  }

  @Override
  public Visitable visit(Visitable node) throws StandardException {
    if( node instanceof DeleteNode) {
      DeleteNode dn = (DeleteNode)node;
      this.deleteTargetTableNum = dn.getTargetTableID();
      this.visit(dn.getResultSetNode());

    }
    else if(node instanceof ProjectRestrictNode) {
      this.handleProjectRestrictNode((ProjectRestrictNode)node);
    }else {
      super.visit(node);
    }
    return node;
  }

  public boolean skipChildren(Visitable node) throws StandardException {
    return node instanceof ProjectRestrictNode || node instanceof FromBaseTable
        || node instanceof AndNode || node instanceof ResultColumn;
  }

  public boolean stopTraversal() {
    // TODO Auto-generated method stub
    return false;
  }

  @Override
  public final boolean isDelete() {
    return true;
  }

  public final boolean isDeleteWithReferencedKeys() {
    return this.isDeleteWithReferencedKeys;
  }

  public LocalRegion getTargetRegion() {
    return this.tableQueryInfoList.get(this.deleteTargetTableNum).getRegion();
  }

//  @Override
//  public LocalRegion getRegion() {
//    return this.tableQueryInfoList.get(0).getRegion();
//  }
}


text:
package at.ameise.moodtracker.app.util;

import android.os.AsyncTask;

import java.util.ArrayList;
import java.util.List;

import at.ameise.moodtracker.app.Setting;

/**
 * AsyncTask which retries {@link AsyncTask#doInBackground(Object[])}
 * {@link Setting#BACKEND_CALL_TRIES} times.
 *
 * Created by Mario Gastegger <mario DOT gastegger AT gmail DOT com> on 05.12.15.
 */
abstract class RetryingAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

    public static final String TAG = "RetryingAsyncTask";

    /**
     * Contains the throwables which occurred during the attempts.
     */
    private List<Throwable> errors = new ArrayList<Throwable>();

    /**
     * True if one attempt succeeded.
     */
    private boolean succeeded;

    /**
     * This method is being retried {@link Setting#BACKEND_CALL_TRIES} times in case an exception was thrown.
     * @param params the parameters.
     * @return the result or null if {@link RetryingAsyncTask#doRetryInBackground(Object[])} failed.
     * @see AsyncTask#doInBackground(Object[])
     */
    protected abstract Result doRetryInBackground(Params... params) throws Throwable;

    /**
     * Returns an array of the messages returned by the error's {@link Throwable#getMessage()} method.
     * @param errors The errors returned by {@link RetryingAsyncTask#onPostExecuteSuccess(Object, List)} or {@link RetryingAsyncTask#onPostExecuteFailure(List)}.
     * @return an array of the {@link Throwable#getMessage()}.
     */
    public static String[] getErrorsMessages(List<Throwable> errors) {

        String[] errorMessages = new String[errors.size()];

        for(int i = 0; i < errors.size(); i++) {
            errorMessages[i] = errors.get(i).getMessage();
        }

        return errorMessages;
    }

    @Override
    protected Result doInBackground(Params... params) {

        Result result = null;

        int tryCnt = 1;
        int maxTries = Setting.BACKEND_CALL_TRIES;

        while(tryCnt <= maxTries) {

            try {

                result = doRetryInBackground(params);

                succeeded = true;
                break;

            } catch (Throwable e) {

                succeeded = false;
                errors.add(e);
                Logger.warn(TAG, "Try " + tryCnt + " failed! Cause:" + e.getMessage(), e);
                Logger.debug(TAG, "Try " + tryCnt + " of " + maxTries + " failed!");
            }

            tryCnt++;
        }

        return result;
    }

    @Override
    protected void onPostExecute(Result result) {

        if(succeeded) {

            onPostExecuteSuccess(result, errors);

        } else {

            onPostExecuteFailure(errors);
        }

        super.onPostExecute(result);
    }

    /**
     * Called if the task failed.
     *
     * @param errors The list of the errors of each attempt.
     */
    protected abstract void onPostExecuteFailure(List<Throwable> errors);

    /**
     * Called if the task succeeded.
     *
     * @param result The result of the task.
     * @param errors The list of errors. One for each failed attempt(which preceded the successful attempt).
     */
    protected abstract void onPostExecuteSuccess(Result result, List<Throwable> errors);
}


text:
Register form

            <form class="ui form" method="POST" action="/sign/rent" accept-charset="UTF-8" enctype="multipart/form-data">
                <input type="hidden" name="_token" value="{{ csrf_token() }}" />

                    Person

                            <input type="text" name="first" placeholder="First Name" />

                            <input type="text" name="last" placeholder="Last Name">

                            <input type="number" name="age" placeholder="Age">

                    Contacts

                            <input type="text" name="phone" placeholder="Phone number" />

                            <input type="text" name="address" placeholder="Home address" />

                            <input type="number" name="zip" placeholder="Zip-code" />

                    Numbers

                            <input type="number" name="license" placeholder="Driver license number" />

                            <input type="number" name="social" placeholder="Social security number" />

                            <input type="number" name="bank" placeholder="Bank account number" />

                        Driver license photo

                            <input type="text" readonly placeholder="Image">
                            <input name="image" type="file" id="image">

Remains private - never shared

No credit check - credit won't be affected

Information is safe & secure

                            <input type="checkbox" name="agree">
                            I agree to the Terms and Conditions

                <button class="ui button" type="submit">Submit</button>

            </form>


text:
def make_change(amount, coins = [25, 10, 5, 1])
 coins.sort! { |a, b| b <=> a }

 # memoize solutions
 optimal_change = Hash.new do |hash, key|
   hash[key] = if key < coins.min
     []
   elsif coins.include?(key)
     [key]
   else
     coins.
       # prune unhelpful coins
       reject { |coin| coin > key }.

       # prune coins that are factors of larger coins
       inject([]) {|mem, var| mem.any? {|c| c%var == 0} ? mem : mem+[var]}.

       # recurse
       map { |coin| [coin] + hash[key - coin] }.

       # prune unhelpful solutions
       reject { |change| change.sum != key }.

       # pick the smallest, empty if none
       min { |a, b| a.size <=> b.size } || []
   end
 end

 optimal_change[amount]
end


text: Math.hasOwnProperty();


text:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://www.netbeans.org/ns/project/1">
    <type>com.microchip.mplab.nbide.embedded.makeproject</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/make-project/1">
            <name>14pin_fun</name>
            <creation-uuid>7c153a5c-2ec7-4a39-b94b-5a320506d536</creation-uuid>
            <make-project-type>0</make-project-type>
            <c-extensions>c</c-extensions>
            <cpp-extensions/>
            <header-extensions/>
            <asminc-extensions/>
            <sourceEncoding>ISO-8859-1</sourceEncoding>
            <make-dep-projects/>
        </data>
    </configuration>
</project>


text:
class Note < Content
  require 'twitter'
  require 'json'
  require 'uri'
  include PublifyGuid
  include ConfigManager

  serialize :settings, Hash

  setting :twitter_id, :string, ''
  setting :in_reply_to_status_id, :string, ''
  setting :in_reply_to_protected, :boolean, false
  setting :in_reply_to_message, :string, ''

  validates :body, presence: true
  validates :permalink, :guid, uniqueness: true

  after_create :set_permalink, :shorten_url
  before_create :create_guid

  default_scope { order('published_at DESC') }

  TWITTER_FTP_URL_LENGTH = 19
  TWITTER_HTTP_URL_LENGTH = 20
  TWITTER_HTTPS_URL_LENGTH = 21
  TWITTER_LINK_LENGTH = 22

  def set_permalink
    self.permalink = "#{id}-#{body.to_permalink[0..79]}" if permalink.blank?
    save
  end

  def categories
    []
  end

  def tags
    []
  end

  def html_preprocess(_field, html)
    PublifyApp::Textfilter::Twitterfilter.filtertext(html)
  end

  def truncate(message, length)
    if message[length + 1] == ' '
      message[0..length]
    else
      message[0..(message[0..length].rindex(' ') - 1)]
    end
  end

  def twitter_message
    base_message = body.strip_html
    if too_long?("#{base_message} (#{short_link})")
      max_length = 140 - "... (#{redirect.from_url})".length - 1
      "#{truncate(base_message, max_length)}... (#{redirect.from_url})"
    else
      "#{base_message} (#{short_link})"
    end
  end

  # FIXME: This breaks if the user changes or deletes their handle.
  def twitter_url
    File.join('https://twitter.com', user.twitter, 'status', twitter_id)
  end

  def send_to_twitter
    return false unless blog.has_twitter_configured?
    return false unless user.has_twitter_configured?

    twitter = Twitter::REST::Client.new do |config|
      config.consumer_key = blog.twitter_consumer_key
      config.consumer_secret = blog.twitter_consumer_secret
      config.access_token = user.twitter_oauth_token
      config.access_token_secret = user.twitter_oauth_token_secret
    end

    begin
      options = {}
      if in_reply_to_status_id && in_reply_to_status_id != ''
        options = { in_reply_to_status_id: in_reply_to_status_id }
        self.in_reply_to_message = twitter.status(in_reply_to_status_id).to_json
      end
      tweet = twitter.update(twitter_message, options)
      self.twitter_id = tweet.attrs[:id_str]
      save
      user.update_twitter_profile_image(tweet.attrs[:user][:profile_image_url])
      true
    rescue StandardError => e
      Rails.logger.error("Error while sending to twitter: #{e}")
      errors.add(:message, e)
      false
    end
  end

  content_fields :body

  def password_protected?
    false
  end

  def access_by?(user)
    user.admin? || user_id == user.id
  end

  def permalink_url(anchor = nil, only_path = false)
    blog.url_for(
      controller: '/notes',
      action: 'show',
      permalink: permalink,
      anchor: anchor,
      only_path: only_path
    )
  end

  def short_link
    path = redirect.from_path
    "#{prefix} #{path}"
  end

  def prefix
    blog.shortener_url.sub(/^https?\:\/\//, '')
  end

  private

  def too_long?(message)
    uris = URI.extract(message, %w(http https ftp))
    uris << prefix
    uris.each do |uri|
      payload = case uri.split(':')[0]
                when 'https'
                  '-' * TWITTER_HTTPS_URL_LENGTH
                when 'ftp'
                  '-' * TWITTER_FTP_URL_LENGTH
                else
                  '-' * TWITTER_HTTP_URL_LENGTH
                end
      message = message.gsub(uri, payload)
    end
    message.length > 140
  end
end