text:
A Guide for Upgrading Ruby on Rails
===================================

This guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails. These steps are also available in individual release guides.

General Advice
--------------

Before attempting to upgrade an existing application, you should be sure you have a good reason to upgrade. You need to balance out several factors: the need for new features, the increasing difficulty of finding support for old code, and your available time and skills, to name a few.

### Test Coverage

The best way to be sure that your application still works after upgrading is to have good test coverage before you start the process. If you don't have automated tests that exercise the bulk of your application, you'll need to spend time manually exercising all the parts that have changed. In the case of a Rails upgrade, that will mean every single piece of functionality in the application. Do yourself a favor and make sure your test coverage is good _before_ you start an upgrade.

### Ruby Versions

Rails generally stays close to the latest released Ruby version when it's released:

* Rails 3 and above require Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially. You should upgrade as early as possible.
* Rails 3.2.x is the last branch to support Ruby 1.8.7.
* Rails 4 prefers Ruby 2.0 and requires 1.9.3 or newer.

TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump straight to 1.9.3 for smooth sailing.

Upgrading from Rails 3.2 to Rails 4.0
-------------------------------------

NOTE: This section is a work in progress.

If your application is currently on any version of Rails older than 3.2.x, you should upgrade to Rails 3.2 before attempting one to Rails 4.0.

The following changes are meant for upgrading your application to Rails 4.0.

### Gemfile

Rails 4.0 removed the `assets` group from Gemfile. You'd need to remove that line from your Gemfile when upgrading.

### vendor/plugins

Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must replace any plugins by extracting them to gems and adding them to your Gemfile. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.

### Active Record

* Rails 4.0 has removed the identity map from Active Record, due to [some inconsistencies with associations](https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6). If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: `config.active_record.identity_map`.

* The `delete` method in collection associations can now receive `Fixnum` or `String` arguments as record ids, besides records, pretty much like the `destroy` method does. Previously it raised `ActiveRecord::AssociationTypeMismatch` for such arguments. From Rails 4.0 on `delete` automatically tries to find the records matching the given ids before deleting them.

* Rails 4.0 has changed how orders get stacked in `ActiveRecord::Relation`. In previous versions of Rails, the new order was applied after the previously defined order. But this is no longer true. Check [Active Record Query guide](active_record_querying.html#ordering) for more information.

* Rails 4.0 has changed `serialized_attributes` and `attr_readonly` to class methods only. You shouldn't use instance methods since it's now deprecated. You should change them to use class methods, e.g. `self.serialized_attributes` to `self.class.serialized_attributes`.

* Rails 4.0 has removed `attr_accessible` and `attr_protected` feature in favor of Strong Parameters. You can use the [Protected Attributes gem](https://github.com/rails/protected_attributes) to a smoothly upgrade path.

* Rails 4.0 requires that scopes use a callable object such as a Proc or lambda:

```ruby
  scope :active, where(active: true)

  # becomes
  scope :active, -> { where active: true }
```

* Rails 4.0 has deprecated `ActiveRecord::Fixtures` in favor of `ActiveRecord::FixtureSet`.
* Rails 4.0 has deprecated `ActiveRecord::TestCase` in favor of `ActiveSupport::TestCase`.

### Active Resource

Rails 4.0 extracted Active Resource to its own gem. If you still need the feature you can add the [Active Resource gem](https://github.com/rails/activeresource) in your Gemfile.

### Active Model

* Rails 4.0 has changed how errors attach with the `ActiveModel::Validations::ConfirmationValidator`. Now when confirmation validations fail, the error will be attached to `:#{attribute}_confirmation` instead of `attribute`.

* Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to `false`. Now, Active Model Serializers and Active Record objects have the same default behaviour. This means that you can comment or remove the following option in the `config/initializers/wrap_parameters.rb` file:

```ruby
# Disable root element in JSON by default.
# ActiveSupport.on_load(:active_record) do
#   self.include_root_in_json = false
# end
```

### Action Pack

* Rails 4.0 introduces `ActiveSupport::KeyGenerator` and uses this as a base from which to generate and verify signed cookies (among other things). Existing signed cookies generated with Rails 3.x will be transparently upgraded if you leave your existing `secret_token` in place and add the new `secret_key_base`.

```ruby
  # config/initializers/secret_token.rb
  Myapp::Application.config.secret_token = 'existing secret token'
  Myapp::Application.config.secret_key_base = 'new secret key base'
```

Please note that you should wait to set `secret_key_base` until you have 100% of your userbase on Rails 4.x and are reasonably sure you will not need to rollback to Rails 3.x. This is because cookies signed based on the new `secret_key_base` in Rails 4.x are not backwards compatible with Rails 3.x. You are free to leave your existing `secret_token` in place, not set the new `secret_key_base`, and ignore the deprecation warnings until you are reasonably sure that your upgrade is otherwise complete.

If you are relying on the ability for external applications or Javascript to be able to read your Rails app's signed session cookies (or signed cookies in general) you should not set `secret_key_base` until you have decoupled these concerns.

* Rails 4.0 encrypts the contents of cookie-based sessions if `secret_key_base` has been set. Rails 3.x signed, but did not encrypt, the contents of cookie-based session. Signed cookies are "secure" in that they are verified to have been generated by your app and are tamper-proof. However, the contents can be viewed by end users, and encrypting the contents eliminates this caveat/concern without a significant performance penalty.

As described above, existing signed cookies generated with Rails 3.x will be transparently upgraded if you leave your existing `secret_token` in place and add the new `secret_key_base`.

```ruby
  # config/initializers/secret_token.rb
  Myapp::Application.config.secret_token = 'existing secret token'
  Myapp::Application.config.secret_key_base = 'new secret key base'
```

The same caveats apply here, too. You should wait to set `secret_key_base` until you have 100% of your userbase on Rails 4.x and are reasonably sure you will not need to rollback to Rails 3.x. You should also take care to make sure you are not relying on the ability to decode signed cookies generated by your app in external applications or Javascript before upgrading.

Please read [Pull Request #9978](https://github.com/rails/rails/pull/9978) for details on the move to encrypted session cookies.

* Rails 4.0 removed the `ActionController::Base.asset_path` option. Use the assets pipeline feature.

* Rails 4.0 has deprecated `ActionController::Base.page_cache_extension` option. Use `ActionController::Base.default_static_extension` instead.

* Rails 4.0 has removed Action and Page caching from Action Pack. You will need to add the `actionpack-action_caching` gem in order to use `caches_action` and the `actionpack-page_caching` to use `caches_pages` in your controllers.

* Rails 4.0 has removed the XML parameters parser. You will need to add the `actionpack-xml_parser` gem if you require this feature.

* Rails 4.0 changes the default memcached client from `memcache-client` to `dalli`. To upgrade, simply add `gem 'dalli'` to your `Gemfile`.

* Rails 4.0 deprecates the `dom_id` and `dom_class` methods in controllers (they are fine in views). You will need to include the `ActionView::RecordIdentifier` module in controllers requiring this feature.

* Rails 4.0 changed how `assert_generates`, `assert_recognizes`, and `assert_routing` work. Now all these assertions raise `Assertion` instead of `ActionController::RoutingError`.

* Rails 4.0 raises an `ArgumentError` if clashing named routes are defined. This can be triggered by explicitly defined named routes or by the `resources` method. Here are two examples that clash with routes named `example_path`:

```ruby
  get 'one' => 'test#example', as: :example
  get 'two' => 'test#example', as: :example
```

```ruby
  resources :examples
  get 'clashing/:id' => 'test#example', as: :example
```

In the first case, you can simply avoid using the same name for multiple
routes. In the second, you can use the `only` or `except` options provided by
the `resources` method to restrict the routes created as detailed in the
[Routing Guide](routing.html#restricting-the-routes-created).

* Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example:

```ruby
get Rack::Utils.escape('こんにちは'), controller: 'welcome', action: 'index'
```

becomes

```ruby
get 'こんにちは', controller: 'welcome', action: 'index'
```

* Rails 4.0 requires that routes using `match` must specify the request method. For example:

```ruby
  # Rails 3.x
  match "/" => "root#index"

  # becomes
  match "/" => "root#index", via: :get

  # or
  get "/" => "root#index"
```

* Rails 4.0 has removed `ActionDispatch::BestStandardsSupport` middleware, `<!DOCTYPE html>` already triggers standards mode per http://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx and ChromeFrame header has been moved to `config.action_dispatch.default_headers`.

Remember you must also remove any references to the middleware from your application code, for example:

```ruby
# Raise exception
config.middleware.insert_before(Rack::Lock, ActionDispatch::BestStandardsSupport)
```

Also check your environment settings for `config.action_dispatch.best_standards_support` and remove it if present.

* In Rails 4.0, precompiling assets no longer automatically copies non-JS/CSS assets from `vendor/assets` and `lib/assets`. Rails application and engine developers should put these assets in `app/assets` or configure `config.assets.precompile`.

* In Rails 4.0, `ActionController::UnknownFormat` is raised when the action doesn't handle the request format. By default, the exception is handled by responding with 406 Not Acceptable, but you can override that now. In Rails 3, 406 Not Acceptable was always returned. No overrides.

* In Rails 4.0, a generic `ActionDispatch::ParamsParser::ParseError` exception is raised when `ParamsParser` fails to parse request params. You will want to rescue this exception instead of the low-level `MultiJson::DecodeError`, for example.

* In Rails 4.0, `SCRIPT_NAME` is properly nested when engines are mounted on an app that's served from a URL prefix. You no longer have to set `default_url_options[:script_name]` to work around overwritten URL prefixes.

* Rails 4.0 deprecated `ActionController::Integration` in favor of `ActionDispatch::Integration`.
* Rails 4.0 deprecated `ActionController::IntegrationTest` in favor of `ActionDispatch::IntegrationTest`.
* Rails 4.0 deprecated `ActionController::PerformanceTest` in favor of `ActionDispatch::PerformanceTest`.
* Rails 4.0 deprecated `ActionController::AbstractRequest` in favor of `ActionDispatch::Request`.
* Rails 4.0 deprecated `ActionController::Request` in favor of `ActionDispatch::Request`.
* Rails 4.0 deprecated `ActionController::AbstractResponse` in favor of `ActionDispatch::Response`.
* Rails 4.0 deprecated `ActionController::Response` in favor of `ActionDispatch::Response`.
* Rails 4.0 deprecated `ActionController::Routing` in favor of `ActionDispatch::Routing`.

### Active Support

Rails 4.0 removes the `j` alias for `ERB::Util#json_escape` since `j` is already used for `ActionView::Helpers::JavaScriptHelper#escape_javascript`.

### Helpers Loading Order

The order in which helpers from more than one directory are loaded has changed in Rails 4.0. Previously, they were gathered and then sorted alphabetically. After upgrading to Rails 4.0, helpers will preserve the order of loaded directories and will be sorted alphabetically only within each directory. Unless you explicitly use the `helpers_path` parameter, this change will only impact the way of loading helpers from engines. If you rely on the ordering, you should check if correct methods are available after upgrade. If you would like to change the order in which engines are loaded, you can use `config.railties_order=` method.

### Active Record Observer and Action Controller Sweeper

Active Record Observer and Action Controller Sweeper have been extracted to the `rails-observers` gem. You will need to add the `rails-observers` gem if you require these features.

### sprockets-rails

* `assets:precompile:primary` has been removed. Use `assets:precompile` instead.

### sass-rails

* `asset_url` with two arguments is deprecated. For example: `asset-url("rails.png", image)` becomes `asset-url("rails.png")`

Upgrading from Rails 3.1 to Rails 3.2
-------------------------------------

If your application is currently on any version of Rails older than 3.1.x, you should upgrade to Rails 3.1 before attempting an update to Rails 3.2.

The following changes are meant for upgrading your application to Rails 3.2.12, the latest 3.2.x version of Rails.

### Gemfile

Make the following changes to your `Gemfile`.

```ruby
gem 'rails', '= 3.2.12'

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'uglifier',     '>= 1.0.3'
end
```

### config/environments/development.rb

There are a couple of new configuration settings that you should add to your development environment:

```ruby
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict

# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
```

### config/environments/test.rb

The `mass_assignment_sanitizer` configuration setting should also be be added to `config/environments/test.rb`:

```ruby
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
```

### vendor/plugins

Rails 3.2 deprecates `vendor/plugins` and Rails 4.0 will remove them completely. While it's not strictly necessary as part of a Rails 3.2 upgrade, you can start replacing any plugins by extracting them to gems and adding them to your Gemfile. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.

Upgrading from Rails 3.0 to Rails 3.1
-------------------------------------

If your application is currently on any version of Rails older than 3.0.x, you should upgrade to Rails 3.0 before attempting an update to Rails 3.1.

The following changes are meant for upgrading your application to Rails 3.1.11, the latest 3.1.x version of Rails.

### Gemfile

Make the following changes to your `Gemfile`.

```ruby
gem 'rails', '= 3.1.11'
gem 'mysql2'

# Needed for the new asset pipeline
group :assets do
  gem 'sass-rails',   "~> 3.1.5"
  gem 'coffee-rails', "~> 3.1.1"
  gem 'uglifier',     ">= 1.0.3"
end

# jQuery is the default JavaScript library in Rails 3.1
gem 'jquery-rails'
```

### config/application.rb

The asset pipeline requires the following additions:

```ruby
config.assets.enabled = true
config.assets.version = '1.0'
```

If your application is using an "/assets" route for a resource you may want change the prefix used for assets to avoid conflicts:

```ruby
# Defaults to '/assets'
config.assets.prefix = '/asset-files'
```

### config/environments/development.rb

Remove the RJS setting `config.action_view.debug_rjs = true`.

Add these settings if you enable the asset pipeline:

```ruby
# Do not compress assets
config.assets.compress = false

# Expands the lines which load the assets
config.assets.debug = true
```

### config/environments/production.rb

Again, most of the changes below are for the asset pipeline. You can read more about these in the [Asset Pipeline](asset_pipeline.html) guide.

```ruby
# Compress JavaScripts and CSS
config.assets.compress = true

# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false

# Generate digests for assets URLs
config.assets.digest = true

# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH

# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )

# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
```

### config/environments/test.rb

You can help test performance with these additions to your test environment:

```ruby
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
```

### config/initializers/wrap_parameters.rb

Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications.

```ruby
# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.

# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
  wrap_parameters format: [:json]
end

# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
  self.include_root_in_json = false
end
```

### config/initializers/session_store.rb

You need to change your session key to something new, or remove all sessions:

```ruby
# in config/initializers/session_store.rb
AppName::Application.config.session_store :cookie_store, key: 'SOMETHINGNEW'
```

or

```bash
$ rake db:sessions:clear
```

### Remove :cache and :concat options in asset helpers references in views

* With the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from your views.


text:
<!--This file was generated from the python source
Please edit the source to make changes
-->
UsersCollector
=====

Collects the number of users logged in and shells per user

#### Dependencies

 * [pyutmp](http://software.clapper.org/pyutmp/)
or
 * [utmp] (python-utmp on Debian and derivatives)

#### Options

Setting | Default | Description | Type
--------|---------|-------------|-----
byte_unit | byte | Default numeric output(s) | str
enabled | False | Enable collecting these metrics | bool
measure_collector_time | False | Collect the collector run time in ms | bool
metrics_blacklist | None | Regex to match metrics to block. Mutually exclusive with metrics_whitelist | NoneType
metrics_whitelist | None | Regex to match metrics to transmit. Mutually exclusive with metrics_blacklist | NoneType

#### Example Output

```
__EXAMPLESHERE__
```

redpajama_set_name: RedPajamaGithub


text:
package io.mewbase.eventsource.impl.http;

import io.mewbase.bson.BsonCodec;
import io.mewbase.eventsource.EventHandler;
import io.mewbase.eventsource.Subscription;

import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;

import io.vertx.core.http.WebSocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;

public class HttpEventSubscription implements Subscription {

    private final static Logger logger = LoggerFactory.getLogger(HttpEventSubscription.class);

    // We use an HTTP Client per subscription such that the client can be closed
    // and the server can then use the disconnect shutdown logic
    private final HttpClient client;

    private final AtomicBoolean clientIsClosed = new AtomicBoolean(false);

    public final CompletableFuture<Subscription> future = new CompletableFuture<>();

    public HttpEventSubscription(final HttpClient httpClient,
                                 final SubscriptionRequest subsRequest,
                                 final EventHandler eventHandler)  {

        client = httpClient;

        client.post(HttpEventSource.SUBSCRIBE_ROUTE, response  -> {
            response.bodyHandler(totalBuffer -> {
                try {
                    // use the subscription UUID to set up a web socket for this
                    String subscriptionURI = totalBuffer.toString();
                    client.websocket("/"+subscriptionURI, new Handler<WebSocket>() {
                        @Override
                        public void handle(WebSocket websocket) {
                            websocket.frameHandler(frame -> {
                                HttpEvent evt = new HttpEvent(frame.binaryData().getBytes());
                                eventHandler.onEvent(evt);
                            });
                            // web socket is open and handler is bound so complete the future
                            future.complete(HttpEventSubscription.this);
                        }
                    });
                 } catch (Exception exp) {
                    logger.error("Websocket subscription failed", exp);
                    future.completeExceptionally(exp);
                    }
                });
            }).end(Buffer.buffer(BsonCodec.bsonObjectToBsonBytes(subsRequest.toBson())));
    }

    @Override
    public void close()  {
        if (!clientIsClosed.get()) {
            client.close();
            clientIsClosed.set(true);
        }
        logger.info("HttpEventSubscription closed");
    }

}


text:
__attribute__((visibility("default"))) static int dummy
    __attribute__((unused, used)) = 0;
#endif  // GCC-ish


text:
"""
A very simple progress bar which keep track of the progress as we consume an
iterator.
"""
import os
import signal
import time

from prompt_toolkit import HTML
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.shortcuts import ProgressBar

def main():
    bottom_toolbar = HTML(
        ' [f] Print "f" [q] Abort  [x] Send Control-C.'
    )

    # Create custom key bindings first.
    kb = KeyBindings()
    cancel = [False]

    @kb.add("f")
    def _(event):
        print("You pressed `f`.")

    @kb.add("q")
    def _(event):
        " Quit by setting cancel flag. "
        cancel[0] = True

    @kb.add("x")
    def _(event):
        " Quit by sending SIGINT to the main thread. "
        os.kill(os.getpid(), signal.SIGINT)

    # Use `patch_stdout`, to make sure that prints go above the
    # application.
    with patch_stdout():
        with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb:
            for i in pb(range(800)):
                time.sleep(0.01)

                if cancel[0]:
                    break

if __name__ == "__main__":
    main()


text:
const path = require('path');
import { dappPath, fileTreeSort } from 'embark-utils';

class API {

  constructor(embark, _options) {
    this.embark = embark;
    this.plugins = embark.config.plugins;
    this.fs = embark.fs;
  }

  registerAPIs() {
    this.embark.registerAPICall(
      'get',
      '/embark-api/file',
      (req, res) => {
        try {
          this.apiGuardBadFile(req.query.path);
        } catch (error) {
          return res.send({ error: error.message });
        }

        const name = path.basename(req.query.path);
        const content = this.fs.readFileSync(req.query.path, 'utf8');
        res.send({ name, content, path: req.query.path });
      }
    );

    this.embark.registerAPICall(
      'post',
      '/embark-api/folders',
      (req, res) => {
        try {
          this.apiGuardBadFile(req.body.path);
        } catch (error) {
          return res.send({ error: error.message });
        }

        this.fs.mkdirpSync(req.body.path);
        const name = path.basename(req.body.path);
        res.send({ name, path: req.body.path });
      }
    );

    this.embark.registerAPICall(
      'post',
      '/embark-api/files',
      (req, res) => {
        try {
          this.apiGuardBadFile(req.body.path);
        } catch (error) {
          return res.send({ error: error.message });
        }

        this.fs.writeFileSync(req.body.path, req.body.content, { encoding: 'utf8' });
        const name = path.basename(req.body.path);
        res.send({ name, path: req.body.path, content: req.body.content });
      }
    );

    this.embark.registerAPICall(
      'delete',
      '/embark-api/file',
      (req, res) => {
        try {
          this.apiGuardBadFile(req.query.path, { ensureExists: true });
        } catch (error) {
          return res.send({ error: error.message });
        }
        this.fs.removeSync(req.query.path);
        res.send();
      }
    );

    this.embark.registerAPICall(
      'get',
      '/embark-api/files',
      (req, res) => {
        const rootPath = dappPath();

        const walk = (dir, filelist = []) => this.fs.readdirSync(dir).map(name => {
          let isRoot = rootPath === dir;
          if (this.fs.statSync(path.join(dir, name)).isDirectory()) {
            return {
              isRoot,
              name,
              dirname: dir,
              path: path.join(dir, name),
              isHidden: (name.indexOf('.') === 0 || name === "node_modules"),
              children: fileTreeSort(walk(path.join(dir, name), filelist))
            };
          }
          return {
            name,
            isRoot,
            path: path.join(dir, name),
            dirname: dir,
            isHidden: (name.indexOf('.') === 0 || name === "node_modules")
          };
        });
        const files = fileTreeSort(walk(dappPath()));
        res.send(files);
      }
    );
  }

  apiGuardBadFile(pathToCheck, options = {ensureExists: false}) {
    const dir = path.dirname(pathToCheck);
    const error = new Error('Path is invalid');
    if (options.ensureExists && !this.fs.existsSync(pathToCheck)) {
      throw error;
    }
    if (!dir.startsWith(dappPath())) {
      throw error;
    }
  }

}

module.exports = API;


text:
class Projects::VariablesController < Projects::ApplicationController
  before_action :authorize_admin_build!

  layout 'project_settings'

  def index
    @variable = Ci::Variable.new
  end

  def show
    @variable = @project.variables.find(params[:id])
  end

  def update
    @variable = @project.variables.find(params[:id])

    if @variable.update_attributes(project_params)
      redirect_to namespace_project_variables_path(project.namespace, project), notice: 'Variable was successfully updated.'
    else
      render action: "show"
    end
  end

  def create
    @variable = Ci::Variable.new(project_params)

    if @variable.valid? && @project.variables << @variable
      redirect_to namespace_project_variables_path(project.namespace, project), notice: 'Variables were successfully updated.'
    else
      render action: "index"
    end
  end

  def destroy
    @key = @project.variables.find(params[:id])
    @key.destroy

    redirect_to namespace_project_variables_path(project.namespace, project), notice: 'Variable was successfully removed.'
  end

  private

  def project_params
    params.require(:variable).permit([:id, :key, :value, :_destroy])
  end
end


text:
shell() {
  echo $SHELL
}
shellvi() {
  sudo vi /etc/shells
}
shellmv() {
  usage $# "SHELL:zsh|bash"
  ## Display Usage and exit if insufficient parameters. Parameters prefix with [ are OPTIONAL.
  if [[ "$?" -ne 0 ]]; then return 1; fi

  local SHELL=$1
  echo "chsh -s \$(which $SHELL)"
  chsh -s $(which $SHELL)
}

hosts() {
  cat /etc/hosts
}
hostsvi() {
  sudo vi /etc/hosts
}
hostsappend() {
  usage $# "IP" "DNS"
  ## Display Usage and exit if insufficient parameters. Parameters prefix with [ are OPTIONAL.
  if [[ "$?" -ne 0 ]]; then return 1; fi

  local IP=$1
  local DNS=$2

  echo "sudo -- sh -c \"echo $IP $DNS >> /etc/hosts\""
  sudo -- sh -c "echo $IP $DNS >> /etc/hosts"
}
hostscn() {
  hostsappend 199.232.28.133 raw.githubusercontent.com
}


text:
<?php

namespace Haven\CmsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Haven\CoreBundle\Repository\LanguageRepository;

class TextContentTranslationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('content', null, array(
                    "required" =>false
                ))
                ->add('trans_lang', null, array(
                    "property" => "name"
                    , "label" => false
                    , 'query_builder' => function(LanguageRepository $er) {
                        return $er->findPublishedOrderedByRank();
                    }
                    , "attr" => array(
                        "class" => "hidden"
                    )
                ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Haven\CmsBundle\Entity\TextContentTranslation'
        ));
    }

    public function getName()
    {
        return 'haven_bundle_cmsbundle_textcontenttranslationtype';
    }
}


text:
// Copyright 2020 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package io.nats.client.api;

import io.nats.client.support.JsonSerializable;
import io.nats.client.support.JsonUtils;

import static io.nats.client.support.ApiConstants.CONFIG;
import static io.nats.client.support.ApiConstants.STREAM_NAME;
import static io.nats.client.support.JsonUtils.*;

/**
 * Object used to make a request to create a consumer. Used Internally
 */
public class ConsumerCreateRequest implements JsonSerializable {
    private final String streamName;
    private final ConsumerConfiguration config;

    public ConsumerCreateRequest(String streamName, ConsumerConfiguration config) {
        this.streamName = streamName;
        this.config = config;
    }

    public String getStreamName() {
        return streamName;
    }

    public ConsumerConfiguration getConfig() {
        return config;
    }

    @Override
    public String toJson() {
        StringBuilder sb = beginJson();

        addField(sb, STREAM_NAME, streamName);
        JsonUtils.addField(sb, CONFIG, config);

        return endJson(sb).toString();
    }

    @Override
    public String toString() {
        return "ConsumerCreateRequest{" +
                "streamName='" + streamName + '\'' +
                ", " + objectString("config", config) +
                '}';
    }
}


text:
package dan200.qcraft.shared;

import cpw.mods.fml.common.FMLCommonHandler;
import dan200.QCraft;
import java.io.File;
import net.minecraft.world.World;
import net.minecraft.world.WorldSavedData;

/**
 *
 * @author Robijnvogel
 */
abstract class QCraftSavedData extends WorldSavedData {

    public QCraftSavedData(String name) {
        super(name);
    }

    public File getSaveLocation(World world) {
        File rootDir = FMLCommonHandler.instance().getMinecraftServerInstance().getFile(".");
        File saveDir;
        if (QCraft.isServer()) {
            saveDir = new File(rootDir, world.getSaveHandler().getWorldDirectoryName());
        } else {
            saveDir = new File(rootDir, "saves/" + world.getSaveHandler().getWorldDirectoryName());
        }
        return new File(saveDir, "quantum/");
    }
}


text:
import unittest
import logging
from unittest import mock

from flask import Flask
from flask_appbuilder import AppBuilder, SQLA, Model, has_access, expose
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.security.sqla import models as sqla_models
from flask_appbuilder.views import ModelView, BaseView

from sqlalchemy import Column, Integer, String, Date, Float

from airflow.exceptions import AirflowException
from airflow.www.security import AirflowSecurityManager

logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
logging.getLogger().setLevel(logging.DEBUG)
log = logging.getLogger(__name__)

class SomeModel(Model):
    id = Column(Integer, primary_key=True)
    field_string = Column(String(50), unique=True, nullable=False)
    field_integer = Column(Integer())
    field_float = Column(Float())
    field_date = Column(Date())

    def __repr__(self):
        return str(self.field_string)

class SomeModelView(ModelView):
    datamodel = SQLAInterface(SomeModel)
    base_permissions = ['can_list', 'can_show', 'can_add', 'can_edit', 'can_delete']
    list_columns = ['field_string', 'field_integer', 'field_float', 'field_date']

class SomeBaseView(BaseView):
    route_base = ''

    @expose('/some_action')
    @has_access
    def some_action(self):
        return "action!"

class TestSecurityManager(AirflowSecurityManager):
    VIEWER_VMS = {
        'Airflow',
    }

class TestSecurity(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
        self.app.config['SECRET_KEY'] = 'secret_key'
        self.app.config['CSRF_ENABLED'] = False
        self.app.config['WTF_CSRF_ENABLED'] = False
        self.db = SQLA(self.app)
        self.appbuilder = AppBuilder(self.app,
                                     self.db.session,
                                     security_manager_class=AirflowSecurityManager)
        self.security_manager = self.appbuilder.sm
        self.appbuilder.add_view(SomeBaseView, "SomeBaseView", category="BaseViews")
        self.appbuilder.add_view(SomeModelView, "SomeModelView", category="ModelViews")
        role_admin = self.security_manager.find_role('Admin')
        self.user = self.appbuilder.sm.add_user('admin', 'admin', 'user', 'admin@fab.org',
                                                role_admin, 'general')
        log.debug("Complete setup!")

    def expect_user_is_in_role(self, user, rolename):
        self.security_manager.init_role(rolename, [], [])
        role = self.security_manager.find_role(rolename)
        if not role:
            self.security_manager.add_role(rolename)
            role = self.security_manager.find_role(rolename)
        user.roles = [role]
        self.security_manager.update_user(user)

    def assert_user_has_dag_perms(self, perms, dag_id):
        for perm in perms:
            self.assertTrue(
                self._has_dag_perm(perm, dag_id),
                "User should have '{}' on DAG '{}'".format(perm, dag_id))

    def assert_user_does_not_have_dag_perms(self, dag_id, perms):
        for perm in perms:
            self.assertFalse(
                self._has_dag_perm(perm, dag_id),
                "User should not have '{}' on DAG '{}'".format(perm, dag_id))

    def _has_dag_perm(self, perm, dag_id):
        return self.security_manager.has_access(
            perm,
            dag_id,
            self.user)

    def tearDown(self):
        self.appbuilder = None
        self.app = None
        self.db = None
        log.debug("Complete teardown!")

    def test_init_role_baseview(self):
        role_name = 'MyRole1'
        role_perms = ['can_some_action']
        role_vms = ['SomeBaseView']
        self.security_manager.init_role(role_name, role_vms, role_perms)
        role = self.appbuilder.sm.find_role(role_name)
        self.assertIsNotNone(role)
        self.assertEqual(len(role_perms), len(role.permissions))

    def test_init_role_modelview(self):
        role_name = 'MyRole2'
        role_perms = ['can_list', 'can_show', 'can_add', 'can_edit', 'can_delete']
        role_vms = ['SomeModelView']
        self.security_manager.init_role(role_name, role_vms, role_perms)
        role = self.appbuilder.sm.find_role(role_name)
        self.assertIsNotNone(role)
        self.assertEqual(len(role_perms), len(role.permissions))

    def test_update_and_verify_permission_role(self):
        role_name = 'Test_Role'
        self.security_manager.init_role(role_name, [], [])
        role = self.security_manager.find_role(role_name)

        perm = self.security_manager.\
            find_permission_view_menu('can_edit', 'RoleModelView')
        self.security_manager.add_permission_role(role, perm)
        role_perms_len = len(role.permissions)

        self.security_manager.init_role(role_name, [], [])
        new_role_perms_len = len(role.permissions)

        self.assertEqual(role_perms_len, new_role_perms_len)

    def test_get_user_roles(self):
        user = mock.MagicMock()
        user.is_anonymous = False
        roles = self.appbuilder.sm.find_role('Admin')
        user.roles = roles
        self.assertEqual(self.security_manager.get_user_roles(user), roles)

    @mock.patch('airflow.www.security.AirflowSecurityManager.get_user_roles')
    def test_get_all_permissions_views(self, mock_get_user_roles):
        role_name = 'MyRole1'
        role_perms = ['can_some_action']
        role_vms = ['SomeBaseView']
        self.security_manager.init_role(role_name, role_vms, role_perms)
        role = self.security_manager.find_role(role_name)

        mock_get_user_roles.return_value = [role]
        self.assertEqual(self.security_manager
                         .get_all_permissions_views(),
                         {('can_some_action', 'SomeBaseView')})

        mock_get_user_roles.return_value = []
        self.assertEqual(len(self.security_manager
                             .get_all_permissions_views()), 0)

    @mock.patch('airflow.www.security.AirflowSecurityManager'
                '.get_all_permissions_views')
    @mock.patch('airflow.www.security.AirflowSecurityManager'
                '.get_user_roles')
    def test_get_accessible_dag_ids(self, mock_get_user_roles,
                                    mock_get_all_permissions_views):
        user = mock.MagicMock()
        role_name = 'MyRole1'
        role_perms = ['can_dag_read']
        role_vms = ['dag_id']
        self.security_manager.init_role(role_name, role_vms, role_perms)
        role = self.security_manager.find_role(role_name)
        user.roles = [role]
        user.is_anonymous = False
        mock_get_all_permissions_views.return_value = {('can_dag_read', 'dag_id')}

        mock_get_user_roles.return_value = [role]
        self.assertEqual(self.security_manager
                         .get_accessible_dag_ids(user), set(['dag_id']))

    @mock.patch('airflow.www.security.AirflowSecurityManager._has_view_access')
    def test_has_access(self, mock_has_view_access):
        user = mock.MagicMock()
        user.is_anonymous = False
        mock_has_view_access.return_value = True
        self.assertTrue(self.security_manager.has_access('perm', 'view', user))

    def test_sync_perm_for_dag_creates_permissions_on_view_menus(self):
        test_dag_id = 'TEST_DAG'
        self.security_manager.sync_perm_for_dag(test_dag_id, access_control=None)
        for dag_perm in self.security_manager.DAG_PERMS:
            self.assertIsNotNone(self.security_manager.
                                 find_permission_view_menu(dag_perm, test_dag_id))

    @mock.patch('airflow.www.security.AirflowSecurityManager._has_perm')
    @mock.patch('airflow.www.security.AirflowSecurityManager._has_role')
    def test_has_all_dag_access(self, mock_has_role, mock_has_perm):
        mock_has_role.return_value = True
        self.assertTrue(self.security_manager.has_all_dags_access())

        mock_has_role.return_value = False
        mock_has_perm.return_value = False
        self.assertFalse(self.security_manager.has_all_dags_access())

        mock_has_perm.return_value = True
        self.assertTrue(self.security_manager.has_all_dags_access())

    def test_access_control_with_non_existent_role(self):
        with self.assertRaises(AirflowException) as context:
            self.security_manager.sync_perm_for_dag(
                dag_id='access-control-test',
                access_control={
                    'this-role-does-not-exist': ['can_dag_edit', 'can_dag_read']
                })
        self.assertIn("role does not exist", str(context.exception))

    def test_access_control_with_invalid_permission(self):
        invalid_permissions = [
            'can_varimport',  # a real permission, but not a member of DAG_PERMS
            'can_eat_pudding',  # clearly not a real permission
        ]
        for permission in invalid_permissions:
            self.expect_user_is_in_role(self.user, rolename='team-a')
            with self.assertRaises(AirflowException) as context:
                self.security_manager.sync_perm_for_dag(
                    'access_control_test',
                    access_control={
                        'team-a': {permission}
                    })
            self.assertIn("invalid permissions", str(context.exception))

    def test_access_control_is_set_on_init(self):
        self.expect_user_is_in_role(self.user, rolename='team-a')
        self.security_manager.sync_perm_for_dag(
            'access_control_test',
            access_control={
                'team-a': ['can_dag_edit', 'can_dag_read']
            })
        self.assert_user_has_dag_perms(
            perms=['can_dag_edit', 'can_dag_read'],
            dag_id='access_control_test',
        )

        self.expect_user_is_in_role(self.user, rolename='NOT-team-a')
        self.assert_user_does_not_have_dag_perms(
            perms=['can_dag_edit', 'can_dag_read'],
            dag_id='access_control_test',
        )

    def test_access_control_stale_perms_are_revoked(self):
        READ_WRITE = {'can_dag_read', 'can_dag_edit'}
        READ_ONLY = {'can_dag_read'}

        self.expect_user_is_in_role(self.user, rolename='team-a')
        self.security_manager.sync_perm_for_dag(
            'access_control_test',
            access_control={'team-a': READ_WRITE})
        self.assert_user_has_dag_perms(
            perms=READ_WRITE,
            dag_id='access_control_test',
        )

        self.security_manager.sync_perm_for_dag(
            'access_control_test',
            access_control={'team-a': READ_ONLY})
        self.assert_user_has_dag_perms(
            perms=['can_dag_read'],
            dag_id='access_control_test',
        )
        self.assert_user_does_not_have_dag_perms(
            perms=['can_dag_edit'],
            dag_id='access_control_test',
        )

    def test_no_additional_dag_permission_views_created(self):
        ab_perm_view_role = sqla_models.assoc_permissionview_role

        self.security_manager.sync_roles()
        num_pv_before = self.db.session().query(ab_perm_view_role).count()
        self.security_manager.sync_roles()
        num_pv_after = self.db.session().query(ab_perm_view_role).count()
        self.assertEqual(num_pv_before, num_pv_after)

    def test_override_role_vm(self):
        test_security_manager = TestSecurityManager(appbuilder=self.appbuilder)
        self.assertEqual(len(test_security_manager.VIEWER_VMS), 1)
        self.assertEqual(test_security_manager.VIEWER_VMS, {'Airflow'})


text:
import test from 'tape'
import nlp from '../_lib.js'
const here = '[two/match] '

test('term-match :', function (t) {
  let arr = [
    ['quick', 'quick', true],
    ['Quick', 'Quick', true],
    ['quick', 's', false],
    ['quick', '#Adjective', true],
    ['quick', '#Noun', false],
    ['quick', '(fun|nice|quick|cool)', true],
    ['quick', '(fun|nice|good)', false],
  ]
  arr.forEach(function (a) {
    const m = nlp(a[0]).match(a[1])
    const msg = a[0] + ' matches ' + a[1] + ' ' + a[2]
    t.equal(m.found, a[2], here + msg)
  })
  t.end()
})

test('sentence-match:', function (t) {
  let arr = [
    ['the dog played', 'the dog', 'the dog'],
    ['the dog played', 'the dog played', 'the dog played'],
    ['the dog played', 'the #Noun', 'the dog'],
    ['the dog played', 'the #Noun played', 'the dog played'],
    ['the dog played', 'the cat played', ''],
    ['the dog played', 'the #Adjective played', ''],
    ['the dog played', 'the (cat|dog|piano) played', 'the dog played'],
    ['the dog played', 'the (cat|piano) played', ''],
    ['the dog played', 'the . played', 'the dog played'],
    //optional
    ['the dog played', 'the dog quickly? played', 'the dog played'],
    ['the dog played', 'the dog #Adverb? played', 'the dog played'],
    ['the dog quickly played', 'the dog #Adverb? played', 'the dog quickly played'],
    ['the dog quickly played', 'the dog #Adverb played', 'the dog quickly played'],
    ['the dog quickly played', 'the dog . played', 'the dog quickly played'],
    ['the dog quickly played', 'the dog .? played', 'the dog quickly played'],
    // ['the dog played', 'the dog .? played', 'the dog played'],

    //leading/trailing logic
    ['the dog played', 'the dog played$', 'the dog played'],
    ['the dog played', 'the dog', 'the dog'],
    ['the dog played', 'the dog$', ''],
    ['the dog played', 'the dog$ played', ''],
    ['the dog played', '^the dog', 'the dog'],
    ['the dog played', 'dog played', 'dog played'],
    ['the dog played', '^dog played', ''],
    ['the dog played', '^played', ''],
    ['the dog played', '^the', 'the'],

    ['john eats glue', 'john eats glue', 'john eats glue'],
    ['john eats glue', 'john eats', 'john eats'],
    ['john eats glue', 'eats glue', 'eats glue'],
    ['john eats glue', 'eats glue all day', ''],

    //test contractions
    // [`if you don't mind`, `you don't mind`, `you don't mind`],
    [`if you don't mind`, `you don't care`, ``],
    // [`if you don't mind`, `you don't`, `you don't`],
    // [`if you don't mind`, `don't mind`, `don't mind`],

    // [`if you didn't care`, `didn't`, `didn't`], //TODO:support me

    // [`if you wouldn't care, i'll eat here`, `i'll eat`, `i'll eat`], //omg hard one

    // [`don't go`, `do not`, `don't`],
    [`do not go`, `do not`, `do not`],
    // [`i dunno`, `do not`, `dunno`],
    //bugs
    // [`really remind me to buy`, '#Adverb? #Infinitive (me|us) (to|for)', `really remind me to`],
  ]
  arr.forEach(function (a) {
    const m = nlp(a[0]).match(a[1])
    if (!m.found) {
      t.equal(a[2], '', here + 'no-match: ' + a[0] + ' - -' + a[1])
    } else {
      const msg = "'" + a[0] + "'  - " + a[1] + " - - have : '" + m.out('normal') + "'"
      t.equal(m.out('normal'), a[2], here + msg)
    }
  })
  t.end()
})

test('tag-match-tag :', function (t) {
  const m = nlp('apple is cool')
  m.match('apple').tag('Person')
  const p = m.match('#Person')
  t.equal(p.out('normal'), 'apple', here + 'apple-tagged')
  t.equal(m.length, 1, here + 'one-result')
  t.end()
})

test('reduced matches', function (t) {
  let doc = nlp(`the donkey's hotel`)
  t.equals(doc.has('donkey'), true, 'apostrophe-s')

  doc = nlp(`the donkeys' hotel`)
  t.equals(doc.has('donkeys'), true, 's-apostrophe')

  t.end()
})

test('slashes-basic', function (t) {
  let doc = nlp(`spencer is/was trying.`)
  t.equal(doc.terms().length, 3, 'three terms')
  t.equal(doc.match('#Person #Verb trying').found, true, 'verb trying')
  // t.equal(doc.match('#Person is trying').found, true, 'is trying')
  t.end()
})

// test('slashes-complex', function (t) {
// doc = nlp(`spencer is/was trying`)
// 1. doc.has('#PresentTense') == true (choose first)
// 2. doc.has('#Verb') (only common tags)
// 3. doc.has('#PastTense') && doc.has('#PresentTense') :/

// doc = nlp(`spencer is/was trying`)
// 1b. doc.has('is') == true (choose first)
// 2b. doc.has('was') == true  (find both)
// 3b. doc.has('is') == false  (find none)
//   t.end()
// })


text:
from __future__ import print_function, division

from .str import StrPrinter
from sympy.utilities import default_sort_key

def _find_first_symbol(expr):
    for atom in expr.atoms():
        if atom.is_Symbol:
            return atom
    raise ValueError('expression must contain a Symbol: %r' % expr)

class LambdaPrinter(StrPrinter):
    """
    This printer converts expressions into strings that can be used by
    lambdify.
    """

    def _print_MatrixBase(self, expr):
        return "%s(%s)" % (expr.__class__.__name__, str(expr.tolist()))

    _print_SparseMatrix = \
        _print_MutableSparseMatrix = \
        _print_ImmutableSparseMatrix = \
        _print_Matrix = \
        _print_DenseMatrix = \
        _print_MutableDenseMatrix = \
        _print_ImmutableMatrix = \
        _print_ImmutableDenseMatrix = \
        _print_MatrixBase

    def _print_Piecewise(self, expr):
        from sympy.core.sets import Interval
        result = []
        i = 0
        for arg in expr.args:
            e = arg.expr
            c = arg.cond
            result.append('((')
            result.append(self._print(e))
            result.append(') if (')
            if isinstance(c, Interval):
                result.append(self._print(c.contains(_find_first_symbol(e))))
            else:
                result.append(self._print(c))
            result.append(') else (')
            i += 1
        result = result[:-1]
        result.append(') else None)')
        result.append(')'*(2*i - 2))
        return ''.join(result)

    def _print_And(self, expr):
        result = ['(']
        for arg in sorted(expr.args, key=default_sort_key):
            result.extend(['(', self._print(arg), ')'])
            result.append(' and ')
        result = result[:-1]
        result.append(')')
        return ''.join(result)

    def _print_Or(self, expr):
        result = ['(']
        for arg in sorted(expr.args, key=default_sort_key):
            result.extend(['(', self._print(arg), ')'])
            result.append(' or ')
        result = result[:-1]
        result.append(')')
        return ''.join(result)

    def _print_Not(self, expr):
        result = ['(', 'not (', self._print(expr.args[0]), '))']
        return ''.join(result)

def lambdarepr(expr, **settings):
    """
    Returns a string usable for lambdifying.
    """
    return LambdaPrinter(settings).doprint(expr)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Campanularius anomalus Murrill

### Remarks
null


text:
/**
 *
 */
package weixin.popular.bean.shakearound.statistics.device;

import com.fasterxml.jackson.annotation.JsonProperty;

import weixin.popular.bean.shakearound.device.DeviceIdentifier;
import weixin.popular.bean.shakearound.statistics.AbstractStatistics;

/**
 * 微信摇一摇周边-以设备为维度的数据统计接口-请求参数
 * @author Moyq5
 * @date 2016年7月31日
 */
public class StatisticsDevice extends AbstractStatistics {

	/**
	 * 指定页面的设备ID

	 * 必填
	 */
	@JsonProperty("device_identifier")
	private DeviceIdentifier deviceIdentifier;

	/**
	 * @return 页面的设备ID
	 */
	public DeviceIdentifier getDeviceIdentifier() {
		return deviceIdentifier;
	}

	/**
	 * 指定页面的设备ID

	 * 必填
	 * @param deviceIdentifier 页面的设备ID
	 */
	public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) {
		this.deviceIdentifier = deviceIdentifier;
	}

}


text:
CKEDITOR.plugins.setLang( 'image', 'es', {
	alt: 'Texto Alternativo',
	border: 'Borde',
	btnUpload: 'Enviar al Servidor',
	button2Img: '¿Desea convertir el botón de imagen en una simple imagen?',
	hSpace: 'Esp.Horiz',
	img2Button: '¿Desea convertir la imagen en un botón de imagen?',
	infoTab: 'Información de Imagen',
	linkTab: 'Vínculo',
	lockRatio: 'Proporcional',
	menu: 'Propiedades de Imagen',
	resetSize: 'Tamaño Original',
	title: 'Propiedades de Imagen',
	titleButton: 'Propiedades de Botón de Imagen',
	upload: 'Cargar',
	urlMissing: 'Debe indicar la URL de la imagen.',
	vSpace: 'Esp.Vert',
	validateBorder: 'El borde debe ser un número.',
	validateHSpace: 'El espaciado horizontal debe ser un número.',
	validateVSpace: 'El espaciado vertical debe ser un número.'
} );


text:
package sample.model.constraints;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.*;

import javax.validation.*;
import javax.validation.constraints.*;

import sample.util.Regex;

/**
 * 各種カテゴリ/区分(必須)を表現する制約注釈。
 */
@Documented
@Constraint(validatedBy = {})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotBlank
@Size
@Pattern(regexp = "")
public @interface Category {
    String message() default "{error.domain.category}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @OverridesAttribute(constraint = Size.class, name = "max")
    int max() default 30;

    @OverridesAttribute(constraint = Pattern.class, name = "regexp")
    String regexp() default Regex.rAscii;

    @OverridesAttribute(constraint = Pattern.class, name = "flags")
    Pattern.Flag[] flags() default {};

    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        Category[] value();
    }
}


text:
namespace Springboard365.Xrm.Core.Test
{
    using Microsoft.Xrm.Sdk;
    using NUnit.Framework;
    using Springboard365.UnitTest.Core;

    [TestFixture]
    public class WhenEntityValidatorReturnsPreImageEntitySuccessfully : SpecificationBase
    {
        private EntityValidatorSpecificationFixture testFixture;
        private Entity result;

        protected override void Context()
        {
            base.Context();

            testFixture = new EntityValidatorSpecificationFixture();
            testFixture.PerformTestSetup();
        }

        protected override void BecauseOf()
        {
            base.BecauseOf();

            result = testFixture.UnderTest.GetValidCrmTargetEntity<Entity>(testFixture.PluginContext.Object, EntityImageType.PreImage);
        }

        [Test]
        public void ShouldReturnValidEntity()
        {
            Assert.IsNotNull(result);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>eu.scasefp7.eclipse</groupId>
	<artifactId>uml-extraction</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<packaging>pom</packaging>

	<parent>
		<groupId>eu.scasefp7</groupId>
		<artifactId>scase-parent</artifactId>
		<version>1.0.24</version>
	</parent>

	<developers>
		<developer>
			<name>Konstantinos Giannoutakis</name>
			<email>kgiannou@iti.gr</email>
			<organization>Information Technologies Institute</organization>
			<organizationUrl>http://www.iti.gr/</organizationUrl>
		</developer>
		<developer>
			<name>Marin Orlic</name>
			<email>marin.orlic@ericsson.com</email>
			<organization>Ericsson Nikola Tesla d.d.</organization>
			<organizationUrl>http://www.ericsson.hr/</organizationUrl>
		</developer>
	</developers>

	<scm>
		<connection>scm:git:git@github.com:s-case/uml-extraction.git</connection>
		<developerConnection>scm:git:git@github.com:s-case/uml-extraction.git</developerConnection>
		<url>https://github.com/s-case/uml-extraction.git</url>
		<tag>HEAD</tag>
	</scm>

	<modules>
		<module>eu.scasefp7.eclipse.umlrec</module>
		<module>eu.scasefp7.eclipse.umlrec.ui</module>
		<module>eu.scasefp7.eclipse.umlrec.papyrus</module>
		<module>eu.scasefp7.eclipse.umlrec.feature</module>
		<module>eu.scasefp7.eclipse.umlrec.papyrus.feature</module>
		<module>eu.scasefp7.eclipse.umlrec.update-site</module>
	</modules>

	<properties>
		<tycho.version>0.23.0</tycho.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<repositories>
		<repository>
			<id>luna</id>
			<layout>p2</layout>
			<url>http://download.eclipse.org/releases/luna</url>
		</repository>
		<repository>
			<id>OSSRH snapshots</id>
			<url>https://oss.sonatype.org/content/repositories/snapshots</url>
			<snapshots>
				<enabled>true</enabled>
				<updatePolicy>always</updatePolicy>
			</snapshots>
		</repository>
		<repository>
			<id>OSSRH releases</id>
			<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
			<releases>
				<enabled>true</enabled>
				<updatePolicy>never</updatePolicy>
			</releases>
		</repository>
		<repository>
			<id>s-case-dev</id>
			<layout>p2</layout>
			<url>http://s-case.github.io/s-case_dev_site_wo_core/</url>
		</repository>
		<repository>
			<id>papyrus</id>
			<layout>p2</layout>
			<url>http://download.eclipse.org/modeling/mdt/papyrus/updates/releases/luna/1.0.2</url>
		</repository>
	</repositories>

        <dependencies>
            <dependency>
                <groupId>eu.scasefp7.eclipse</groupId>
                <artifactId>eu.scasefp7.eclipse.core</artifactId>
                <version>1.2.0-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>eu.scasefp7.eclipse</groupId>
                <artifactId>eu.scasefp7.eclipse.core.ui</artifactId>
                <version>1.2.0-SNAPSHOT</version>
            </dependency>
        </dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.eclipse.tycho</groupId>
				<artifactId>tycho-maven-plugin</artifactId>
				<version>${tycho.version}</version>
				<extensions>true</extensions>
			</plugin>

		<plugin>
				<groupId>org.eclipse.tycho</groupId>
				<artifactId>target-platform-configuration</artifactId>
				<version>${tycho.version}</version>
				<configuration>
                                        <pomDependencies>consider</pomDependencies>
					<environments>
						<environment>
							<os>linux</os>
							<ws>gtk</ws>
							<arch>x86</arch>
						</environment>
						<environment>
							<os>linux</os>
							<ws>gtk</ws>
							<arch>x86_64</arch>
						</environment>
						<environment>
							<os>win32</os>
							<ws>win32</ws>
							<arch>x86</arch>
						</environment>
						<environment>
							<os>win32</os>
							<ws>win32</ws>
							<arch>x86_64</arch>
						</environment>
						<environment>
							<os>macosx</os>
							<ws>cocoa</ws>
							<arch>x86_64</arch>
						</environment>
					</environments>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text: presentation on technology for product management


text:
<?php
declare(strict_types=1);

namespace ManaPHP\Exception;

use ManaPHP\Exception;

class AbortException extends Exception
{
    public function __construct()
    {
        parent::__construct();
    }
}


text:
require 'bushido'
require 'locomotive/hosting/bushido/custom_domain'
require 'locomotive/hosting/bushido/first_installation'

module Locomotive
  module Hosting
    module Bushido

      extend ActiveSupport::Concern

      included do
         class << self
           attr_accessor :bushido_domains
           attr_accessor :bushido_subdomain
        end
      end

      module ClassMethods

        def bushido?
          self.config.hosting == :bushido ||
          (self.config.hosting == :auto && ENV['APP_TLD'] == 'bushi.do')
        end

        def enable_bushido
          self.config.domain = ENV['APP_TLD'] unless self.config.multi_sites?

          self.enhance_site_model_with_bushido

          self.setup_smtp_settings

          self.config.delayed_job = true # force the use of delayed_job

          self.bushido_domains = ::Bushido::App.domains
          self.bushido_subdomain = ::Bushido::App.subdomain
        end

        def enhance_site_model_with_bushido
          Site.send :include, Locomotive::Hosting::Bushido::CustomDomain
          Site.send :include, Locomotive::Hosting::Bushido::FirstInstallation
        end

        def setup_smtp_settings
          ActionMailer::Base.delivery_method = :smtp
          ActionMailer::Base.smtp_settings = {
            :authentication         => ENV['SMTP_AUTHENTICATION'],
            :address                => ENV['SMTP_SERVER'],
            :port                   => ENV['SMTP_PORT'],
            :domain                 => ENV['SMTP_DOMAIN'],
            :user_name              => ENV['SMTP_USER'],
            :password               => ENV['SMTP_PASSWORD'],
            :enable_starttls_auto   => ENV['SMTP_TLS'].to_s == 'true'
          }
        end

        # manage domains

        def add_bushido_domain(name)
          Locomotive.logger "[add bushido domain] #{name}"
          ::Bushido::App.add_domain(name)

          if ::Bushido::Command.last_command_successful?
            self.bushido_domains << name
          end
        end

        def remove_bushido_domain(name)
          Locomotive.logger "[remove bushido domain] #{name}"
          ::Bushido::App.remove_domain(name)

          if ::Bushido::Command.last_command_successful?
            self.bushido_domains.delete(name)
          end
        end

        def set_bushido_subdomain(name)
          Locomotive.logger "[set bushido subdomain] #{name}.bushi.do"
          ::Bushido::App.set_subdomain(name)

          if ::Bushido::Command.last_command_successful?
            self.bushido_subdomain = name
          end
        end

      end
    end
  end
end


text:
Contains a various set of utilities used by the simplic products.

## Template Parser

...

## Plugin System

...

## MEF System

...


text:
def gen_datestr():
    from datetime import datetime
    dt = datetime.now()
    return str(dt.year)+'.'+str(dt.month)+'.'+str(dt.day)+'_'+str(dt.hour)+'.'+str(dt.minute)+'.'+str(dt.second)


text:
package com.jakduk.batch.processor;

import com.jakduk.batch.common.Constants;
import com.jakduk.batch.model.db.ArticleComment;
import com.jakduk.batch.model.embedded.BoardLog;
import com.jakduk.batch.model.embedded.SimpleWriter;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.util.CollectionUtils;

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

@Slf4j
public class BoardFreeCommentAddHistoryProcessor implements ItemProcessor<ArticleComment, ArticleComment> {

    @Override
    public ArticleComment process(ArticleComment item) throws Exception {

        List<BoardLog> histories = item.getLogs();

        if (CollectionUtils.isEmpty(histories))
            histories = new ArrayList<>();

        ObjectId boardFreeCommentId = new ObjectId(item.getId());
        ObjectId historyId = new ObjectId(boardFreeCommentId.getDate());

        histories.add(new BoardLog(historyId.toHexString(), Constants.BOARD_FREE_COMMENT_HISTORY_TYPE.CREATE.name(), new SimpleWriter(item.getWriter())));
        item.setLogs(histories);

        List<Constants.BATCH_TYPE> batchList = Optional.ofNullable(item.getBatch())
                .orElseGet(ArrayList::new);

        if (batchList.stream().noneMatch(batch -> batch.equals(Constants.BATCH_TYPE.BOARD_FREE_COMMENT_ADD_HISTORY_01))) {
            batchList.add(Constants.BATCH_TYPE.BOARD_FREE_COMMENT_ADD_HISTORY_01);
            item.setBatch(batchList);
        }

        log.debug("Item id:{}", item.getId());

        return item;
    }

}


text:
package org.zstack.header.identity;

public interface IdentityRoles {
    public static final String ALL_ACCOUNT_ROLES = "identity:.*";
    public static final String CREATE_ACCOUNT_ROLE = "identity:createAccount";
    public static final String RESET_ACCOUNT_PASSWORD_ROLE = "identity:resetAccountPassword";
    public static final String CREATE_USER_ROLE = "identity:createUser";
    public static final String RESET_USER_PASSWORD_ROLE = "identity:resetUserPassword";
    public static final String CREATE_POLICY_ROLE = "identity:createPolicy";
    public static final String ATTACH_POLICY_TO_USER_ROLE = "identity:attachPolicyToUser";
    public static final String CREATE_USER_GROUP_ROLE = "identity:createUserGroup";
    public static final String ATTACH_POLICY_TO_USER_GROUP_ROLE = "identity:attachPolicyToUserGroup";
    public static final String ATTACH_USER_TO_USER_GROUP_ROLE = "identity:attachUserToUserGroup";
    public static final String SEARCH_USER_ROLE = "identity:searchUser";
    public static final String SEARCH_POLICY_ROLE = "identity:searchPolicy";
    public static final String SEARCH_USER_GROUP_ROLE = "identity:searchUserGroup";
}


text:
    {{wallet.name || wallet.id}}
     1">
      {{wallet.m}}-of-{{wallet.n}}

      {{'Incomplete' | translate}}


text:
"""Python console command to invoke TOCO from serialized protos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.platform import app

FLAGS = None

def execute(unused_args):
  """Runs the converter."""
  with open(FLAGS.model_proto_file, "rb") as model_file:
    model_str = model_file.read()

  with open(FLAGS.toco_proto_file, "rb") as toco_file:
    toco_str = toco_file.read()

  with open(FLAGS.model_input_file, "rb") as input_file:
    input_str = input_file.read()

  debug_info_str = ""
  if FLAGS.debug_proto_file:
    with open(FLAGS.debug_proto_file, "rb") as debug_info_file:
      debug_info_str = debug_info_file.read()

  enable_mlir_converter = FLAGS.enable_mlir_converter

  output_str = pywrap_tensorflow.TocoConvert(
      model_str,
      toco_str,
      input_str,
      False,  # extended_return
      debug_info_str,
      enable_mlir_converter)
  open(FLAGS.model_output_file, "wb").write(output_str)
  sys.exit(0)

def main():
  global FLAGS
  parser = argparse.ArgumentParser(
      description="Invoke toco using protos as input.")
  parser.add_argument(
      "model_proto_file",
      type=str,
      help="File containing serialized proto that describes the model.")
  parser.add_argument(
      "toco_proto_file",
      type=str,
      help="File containing serialized proto describing how TOCO should run.")
  parser.add_argument(
      "model_input_file", type=str, help="Input model is read from this file.")
  parser.add_argument(
      "model_output_file",
      type=str,
      help="Result of applying TOCO conversion is written here.")
  parser.add_argument(
      "--debug_proto_file",
      type=str,
      default="",
      help=("File containing serialized `GraphDebugInfo` proto that describes "
            "logging information."))
  parser.add_argument(
      "--enable_mlir_converter",
      action="store_true",
      help=("Boolean indiciating whether to enable the MLIR converter instead "
            "of TOCO converter. (default False)"))

  FLAGS, unparsed = parser.parse_known_args()

  app.run(main=execute, argv=[sys.argv[0]] + unparsed)

if __name__ == "__main__":
  main()


text:
@interface MPObjectSelector : NSObject

@property (nonatomic, strong, readonly) NSString *string;

+ (MPObjectSelector *)objectSelectorWithString:(NSString *)string;
- (instancetype)initWithString:(NSString *)string;

- (NSArray *)selectFromRoot:(id)root;
- (NSArray *)fuzzySelectFromRoot:(id)root;

- (BOOL)isLeafSelected:(id)leaf fromRoot:(id)root;
- (BOOL)fuzzyIsLeafSelected:(id)leaf fromRoot:(id)root;

- (Class)selectedClass;
- (NSString *)description;

@end


text:
@interface ControllerAddUserController () {
 @public
  ModelUser *currentUser_;
}

@end

J2OBJC_FIELD_SETTER(ControllerAddUserController, currentUser_, ModelUser *)

@implementation ControllerAddUserController

- (instancetype)initWithViewAddUserView:(id<ViewAddUserView>)view {
  ControllerAddUserController_initWithViewAddUserView_(self, view);
  return self;
}

- (NSString *)getTitle {
  return @"Add User";
}

- (void)addUser {
  ModelUser *newUser = new_ModelUser_init();
  if (currentUser_ != nil) [newUser setIdWithInt:[currentUser_ getId]];
  [newUser setUsernameWithNSString:[((id<ViewAddUserView>) nil_chk(view_)) getUsernameAsString]];
  [newUser setFirstNameWithNSString:[((id<ViewAddUserView>) view_) getFirstnameAsString]];
  [newUser setLastNameWithNSString:[((id<ViewAddUserView>) view_) getSurnameAsString]];
  [newUser setEmailWithNSString:[((id<ViewAddUserView>) view_) getEmailAsString]];
  [newUser setPhoneWithLong:[((id<ViewAddUserView>) view_) getPhoneAsLong]];
  [newUser setPermissionWithNSString:[((id<ViewAddUserView>) view_) getPermissionAsString]];
  [newUser setRoleWithNSString:[((id<ViewAddUserView>) view_) getRoleAsString]];
  NSString *password = [((id<ViewAddUserView>) view_) getPasswordAsString];
  ServiceService_updateOrSaveUserWithModelUser_withNSString_(newUser, password);
  [((id<ViewAddUserView>) view_) closeDialog];
}

- (void)deleteUser {
  if (currentUser_ != nil) ServiceService_deleteUserWithInt_([currentUser_ getId]);
  [((id<ViewAddUserView>) nil_chk(view_)) closeDialog];
}

- (void)onActionCompleteWithEventActionCompleteEvent:(EventActionCompleteEvent *)event {
}

- (void)onStop {
  [super onStop];
  EventEvent_unsubscribeWithEventEventType_withEventEventHandler_(JreLoadStatic(EventActionCompleteEvent, TYPE_), self);
}

+ (const J2ObjcClassInfo *)__metadata {
  static const J2ObjcMethodInfo methods[] = {
    { "initWithViewAddUserView:", "AddUserController", NULL, 0x1, NULL, NULL },
    { "getTitle", NULL, "Ljava.lang.String;", 0x0, NULL, NULL },
    { "addUser", NULL, "V", 0x1, NULL, NULL },
    { "deleteUser", NULL, "V", 0x1, NULL, NULL },
    { "onActionCompleteWithEventActionCompleteEvent:", "onActionComplete", "V", 0x1, NULL, NULL },
    { "onStop", NULL, "V", 0x1, NULL, NULL },
  };
  static const J2ObjcFieldInfo fields[] = {
    { "currentUser_", NULL, 0x2, "Lrtdc.core.model.User;", NULL, NULL, .constantValue.asLong = 0 },
  };
  static const char *superclass_type_args[] = {"Lrtdc.core.view.AddUserView;"};
  static const J2ObjcClassInfo _ControllerAddUserController = { 2, "AddUserController", "rtdc.core.controller", NULL, 0x1, 6, methods, 1, fields, 1, superclass_type_args, 0, NULL, NULL, "Lrtdc/core/controller/Controller<Lrtdc/core/view/AddUserView;>;Lrtdc/core/event/ActionCompleteEvent$Handler;" };
  return &_ControllerAddUserController;
}

@end

void ControllerAddUserController_initWithViewAddUserView_(ControllerAddUserController *self, id<ViewAddUserView> view) {
  (void) ControllerController_initWithViewView_(self, view);
  EventEvent_subscribeWithEventEventType_withEventEventHandler_(JreLoadStatic(EventActionCompleteEvent, TYPE_), self);
  self->currentUser_ = (ModelUser *) check_class_cast([((UtilCache *) nil_chk(UtilCache_getInstance())) retrieveWithNSString:@"user"], [ModelUser class]);
  if (self->currentUser_ != nil) {
    [((id<ViewAddUserView>) nil_chk(view)) setTitleWithNSString:@"Edit User"];
    [view setUsernameAsStringWithNSString:[self->currentUser_ getUsername]];
    [view setEmailAsStringWithNSString:[self->currentUser_ getEmail]];
    [view setFirstnameAsStringWithNSString:[self->currentUser_ getFirstName]];
    [view setSurnameAsStringWithNSString:[self->currentUser_ getLastName]];
    [view setPhoneAsLongWithLong:[self->currentUser_ getPhone]];
    [view setRoleAsStringWithNSString:[self->currentUser_ getRole]];
    [view setPermissionAsStringWithNSString:[self->currentUser_ getPermission]];
  }
  else {
    [((id<ViewAddUserView>) nil_chk(view)) hideDeleteButton];
  }
}

ControllerAddUserController *new_ControllerAddUserController_initWithViewAddUserView_(id<ViewAddUserView> view) {
  ControllerAddUserController *self = [ControllerAddUserController alloc];
  ControllerAddUserController_initWithViewAddUserView_(self, view);
  return self;
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(ControllerAddUserController)


text:
typedef struct
{
    uint32_t signature;
    void *config;
    size_t size;
    void *init_config;

} twr_config_t;

twr_config_t _twr_config;

#pragma pack(push, 1)

typedef struct
{
    uint64_t signature;
    uint8_t version;
    uint16_t length;
    uint8_t hash[6];

} config_header_t;

#pragma pack(pop)

static void _config_eeprom_read(uint32_t address, void *buffer, size_t length);
static void _config_eeprom_write(uint32_t address, const void *buffer, size_t length);

void twr_config_init(uint64_t signature, void *config, size_t size, void *init_config)
{
    _twr_config.signature = signature;
    _twr_config.config = config;
    _twr_config.size = size;
    _twr_config.init_config = init_config;

    if (!twr_config_load())
    {
        twr_config_reset();
        twr_config_save();
    }
}

void twr_config_reset(void)
{
    if (!_twr_config.init_config)
    {
        // Initialize to zero if init_config is not set
        memset(_twr_config.config, 0, _twr_config.size);
    }
    else
    {
        memcpy(_twr_config.config, _twr_config.init_config, _twr_config.size);
    }
}

bool twr_config_load(void)
{
    config_header_t header;

    _config_eeprom_read(_CONFIG_ADDRESS_HEADER, &header, _CONFIG_SIZEOF_HEADER);

    if (header.signature != _twr_config.signature ||
        header.length != _twr_config.size)
    {
        return false;
    }

    _config_eeprom_read(_CONFIG_ADDRESS_CONFIG, _twr_config.config, _twr_config.size);

    static twr_sha256_t sha256;
    static uint8_t hash[32];

    twr_sha256_init(&sha256);
    twr_sha256_update(&sha256, _twr_config.config, _twr_config.size);
    twr_sha256_final(&sha256, hash, false);

    if (memcmp(header.hash, hash, sizeof(header.hash)) != 0)
    {
        return false;
    }

    return true;
}

bool twr_config_save(void)
{
    static twr_sha256_t sha256;
    static uint8_t hash[32];

    twr_sha256_init(&sha256);
    twr_sha256_update(&sha256, _twr_config.config, _twr_config.size);
    twr_sha256_final(&sha256, hash, false);

    config_header_t header;

    header.signature = _twr_config.signature;
    header.length = _twr_config.size;

    memcpy(header.hash, hash, sizeof(header.hash));

    _config_eeprom_write(_CONFIG_ADDRESS_HEADER, &header, _CONFIG_SIZEOF_HEADER);
    _config_eeprom_write(_CONFIG_ADDRESS_CONFIG, _twr_config.config, _twr_config.size);

    return true;
}

static void _config_eeprom_read(uint32_t address, void *buffer, size_t length)
{
    uint8_t *p = buffer;

    for (size_t i = 0; i < length; i++)
    {
        uint8_t a, b, c;

        uint32_t offset_bank_a = 0;
        uint32_t offset_bank_b = offset_bank_a + _CONFIG_SIZEOF_HEADER + _twr_config.size;
        uint32_t offset_bank_c = offset_bank_b + _CONFIG_SIZEOF_HEADER + _twr_config.size;

        if (!twr_eeprom_read(offset_bank_a + address + i, &a, 1) ||
            !twr_eeprom_read(offset_bank_b + address + i, &b, 1) ||
            !twr_eeprom_read(offset_bank_c + address + i, &c, 1))
        {
            //app_error(APP_ERROR);
        }

        *p++ = (a & b) | (a & c) | (b & c);
    }
}

static void _config_eeprom_write(uint32_t address, const void *buffer, size_t length)
{
    uint32_t offset_bank_a = 0;
    uint32_t offset_bank_b = offset_bank_a + _CONFIG_SIZEOF_HEADER + _twr_config.size;
    uint32_t offset_bank_c = offset_bank_b + _CONFIG_SIZEOF_HEADER + _twr_config.size;

    if (!twr_eeprom_write(offset_bank_a + address, buffer, length) ||
        !twr_eeprom_write(offset_bank_b + address, buffer, length) ||
        !twr_eeprom_write(offset_bank_c + address, buffer, length))
    {
        //app_error(APP_ERROR_EEPROM);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

    <title>DeleteCallback</title>
    <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.parse

Class DeleteCallback

Object

com.parse.DeleteCallback

public abstract class DeleteCallback
extends Object

A DeleteCallback is used to run code after saving a ParseObject
                    in a background thread.

                        The easiest way to use a DeleteCallback is through an anonymous inner class.
                        Override the
                        done function to specify what the callback should do after the
                        delete is complete.
                        The done function will be run in the UI thread, while the
                        delete happens in a
                        background thread. This ensures that the UI does not freeze while the delete
                        happens.

                        For example, this sample code deletes the object myObject and
                        calls a different
                        function depending on whether the save succeeded or not.

 myObject.deleteInBackground(new DeleteCallback() {
   public void done(ParseException e) {
     if (e == null) {
       myObjectWasDeletedSuccessfully();
     } else {
       myObjectDeleteDidNotSucceed();
     }
   }
 });

Constructor Summary

Constructors

                                Constructor and Description

                                DeleteCallback()

Method Summary

Methods

                                Modifier and Type
                                Method and Description

                                abstract void
                                done(ParseException e)

Override this function with the code you want
                                        to run after the delete is complete.

Methods inherited from class Object

                                clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DeleteCallback

public DeleteCallback()

Method Detail

done

public abstract void done(ParseException e)

Override this function with the code you want to
                                    run after the delete is complete.

Parameters:

e - The exception raised by the delete, or null
                                        if it succeeded.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<component name="libraryTable">
  <library name="scala-library">
    <CLASSES>
      <root url="jar://C:/Program Files/scala/lib/scala-library.jar!/" />
      <root url="jar://C:/Program Files/scala/lib/scala-swing.jar!/" />
      <root url="jar://C:/Program Files/scala/lib/scala-dbc.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="file://C:/Program Files/scala/doc/scala-devel-docs/api" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://C:/Program Files/scala/src/scala-library-src.jar!/" />
      <root url="jar://C:/Program Files/scala/src/scala-swing-src.jar!/" />
      <root url="jar://C:/Program Files/scala/src/scala-dbc-src.jar!/" />
    </SOURCES>
  </library>
</component>


text:
using System;
using System.Collections;

/// <summary>
/// System.Math.Max(System.SByte,System.SByte)
/// </summary>
public class MathMax7
{
    public static int Main(string[] args)
    {
        MathMax7 max7 = new MathMax7();
        TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Max(System.SByte,System.SByte)...");

        if (max7.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }

    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;

        return retVal;
    }

    public bool PosTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify ");

        try
        {
            SByte var1 = (SByte)TestLibrary.Generator.GetByte(-55);
            SByte var2 = (SByte)TestLibrary.Generator.GetByte(-55);

            if (var1 < var2)
            {
                if (Math.Max(var1, var2) != var2)
                {
                    TestLibrary.TestFramework.LogError("001", "The return value should be var2!");
                    retVal = false;
                }
            }
            else
            {
                if (Math.Max(var1, var2) != var1)
                {
                    TestLibrary.TestFramework.LogError("002","The return value should be var1!");
                    retVal = false;
                }
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003","Unexpected exception occurs: " + e);
            retVal = false;
        }

        return retVal;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <RelativeLayout
        android:id="@+id/frag_home_title"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_alignParentTop="true"
        android:layout_centerVertical="true"
        android:background="@color/color_white">

        <ImageView
            android:id="@+id/frag_home_img"
            android:layout_width="100dp"
            android:layout_height="25dp"
            android:layout_centerInParent="true"
            android:src="@drawable/frag_home_title" />
    </RelativeLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/frag_home_viewpager"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:layout_below="@+id/frag_home_title">

    </android.support.v4.view.ViewPager>

    <LinearLayout
        android:id="@+id/frag_home_index_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/frag_home_viewpager"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="center_horizontal"
        android:layout_marginEnd="34dp"
        android:layout_marginRight="34dp"
        android:orientation="horizontal"
        android:padding="8dp">

    </LinearLayout>

    <LinearLayout
        android:id="@+id/frag_home_layout01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/frag_home_viewpager"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/frag_home_btn01"
            android:layout_width="wrap_content"
            android:layout_height="75dp"
            android:layout_marginLeft="20dp"
            android:background="@drawable/frag_home_img01"
            android:layout_weight="1"
            android:layout_marginRight="10dp"/>

        <Button
            android:id="@+id/frag_home_btn02"
            android:layout_width="wrap_content"
            android:layout_height="75dp"
            android:layout_marginRight="20dp"
            android:background="@drawable/frag_home_img02"
            android:layout_weight="1"/>
    </LinearLayout>
    <Button
        android:id="@+id/frag_home_btn03"
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:layout_below="@id/frag_home_layout01"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/frag_home_img03"
        />
    <Button
        android:id="@+id/frag_home_btn04"
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:layout_below="@id/frag_home_btn03"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/frag_home_img04"
        />
    <Button
        android:id="@+id/frag_home_btn05"
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:layout_below="@id/frag_home_btn04"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/frag_home_img05"
        />

</RelativeLayout>


text:
import { OutgoingSocketEvents } from "../socket-messages";
import * as ClickEvent from "./ClickEvent";
import { Inputs } from "../index";
import { pluck } from "rxjs/operators/pluck";
import { filter } from "rxjs/operators/filter";
import { map } from "rxjs/operators/map";
import { Observable } from "rxjs/Observable";
import { withLatestFrom } from "rxjs/operators/withLatestFrom";
import { setElementValue } from "../effects/set-element-value.effect";

export interface Payload {
    value: any;
    tagName: string;
    index: number;
}

export type OutgoingPayload = Payload;

export interface IncomingPayload extends OutgoingPayload {
    pathname: string;
}

export function outgoing(
    element: ClickEvent.ElementData,
    value: any
): [OutgoingSocketEvents.Keyup, OutgoingPayload] {
    return [
        OutgoingSocketEvents.Keyup,
        {
            ...element,
            value
        }
    ];
}

export function incomingKeyupHandler(
    xs: Observable<IncomingPayload>,
    inputs: Inputs
) {
    return xs.pipe(
        withLatestFrom(
            inputs.option$.pipe(pluck("ghostMode", "forms", "inputs")),
            inputs.window$.pipe(pluck("location", "pathname"))
        ),
        filter(([event, canKeyup, pathname]) => {
            return canKeyup && event.pathname === pathname;
        }),
        map(([event]) => setElementValue(event))
    );
}


text:
#-------------------------------------------------------------------------
# Copyright (c) Microsoft.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
import json
import os
import random
import sys
import time
import unittest
from contextlib import contextmanager

if sys.version_info < (3,):
    from exceptions import RuntimeError

#------------------------------------------------------------------------------

class Credentials(object):

    '''
    Azure credentials needed to run Azure client tests.
    '''

    def __init__(self):
        credentialsFilename = "azurecredentials.json"
        tmpName = os.path.join(os.getcwd(), credentialsFilename)
        if not os.path.exists(tmpName):
            if "USERPROFILE" in os.environ:
                tmpName = os.path.join(os.environ["USERPROFILE"],
                                       credentialsFilename)
            elif "HOME" in os.environ:
                tmpName = os.path.join(os.environ["HOME"],
                                       credentialsFilename)
        if not os.path.exists(tmpName):
            errMsg = "Cannot run Azure tests when the expected config file containing Azure credentials, '{0}', does not exist!".format(
                tmpName)
            raise RuntimeError(errMsg)

        with open(tmpName, "r") as f:
            self.ns = json.load(f)

    def getManagementCertFile(self):
        return self.ns[u'managementcertfile']

    def getSubscriptionId(self):
        return self.ns[u'subscriptionid']

    def getServiceBusAuthenticationType(self):
        return self.ns[u'servicebusauthenticationtype']

    def getServiceBusKey(self):
        return self.ns[u'servicebuskey']

    def getServiceBusNamespace(self):
        return self.ns[u'servicebusns']

    def getServiceBusSasKeyName(self):
        return self.ns[u'servicebussaskeyname']

    def getServiceBusSasKeyValue(self):
        return self.ns[u'servicebussaskeyvalue']

    def getEventHubNamespace(self):
        return self.ns[u'eventhubns']

    def getEventHubSasKeyName(self):
        return self.ns[u'eventhubsaskeyname']

    def getEventHubSasKeyValue(self):
        return self.ns[u'eventhubsaskeyvalue']

    def getStorageServicesKey(self):
        return self.ns[u'storageserviceskey']

    def getStorageServicesName(self):
        return self.ns[u'storageservicesname']

    def getRemoteStorageServicesKey(self):
        ''' Key for remote storage account (different location). '''
        if u'remotestorageserviceskey' in self.ns:
            return self.ns[u'remotestorageserviceskey']
        return None

    def getRemoteStorageServicesName(self):
        ''' Name for remote storage account (different location). '''
        if u'remotestorageservicesname' in self.ns:
            return self.ns[u'remotestorageservicesname']
        return None

    def getLinuxOSVHD(self):
        ''' URL to a blob of a linux .vhd in storageservicesname account'''
        return self.ns[u'linuxosvhd']

    def getProxyHost(self):
        ''' Optional. Address of the proxy server. '''
        if u'proxyhost' in self.ns:
            return self.ns[u'proxyhost']
        return None

    def getUseRequestsLibrary(self):
        if u'userequestslibrary' in self.ns:
            return self.ns[u'userequestslibrary'].lower() == 'true'
        return None

    def getLinuxVMImageName(self):
        ''' Name of a Linux VM image in the current subscription.'''
        if u'linuxvmimagename' in self.ns:
            return self.ns[u'linuxvmimagename']
        return None

    def getLinuxVMRemoteSourceImageLink(self):
        ''' Link to a .vhd in a public blob in separate storage account
        Make sure to use a storage account in West US to avoid timeout'''
        if u'linuxvmremotesourceimagelink' in self.ns:
            return self.ns[u'linuxvmremotesourceimagelink']
        return None

    def getProxyPort(self):
        ''' Optional. Port of the proxy server. '''
        if u'proxyport' in self.ns:
            return self.ns[u'proxyport']
        return None

    def getProxyUser(self):
        ''' Optional. User name for proxy server authentication. '''
        if u'proxyuser' in self.ns:
            return self.ns[u'proxyuser']
        return None

    def getProxyPassword(self):
        ''' Optional. Password for proxy server authentication. '''
        if u'proxypassword' in self.ns:
            return self.ns[u'proxypassword']
        return None

    def getUseHttplibOverride(self):
        ''' Optional. When specified, it will override the value of
        use_httplib that is set by the auto-detection in httpclient.py.
        When testing management APIs, make sure to specify a value that is
        compatible with the value of 'managementcertfile' ie. True for a .pem
        certificate file path, False for a Windows Certificate Store path.
        '''
        if u'usehttpliboverride' in self.ns:
            return self.ns[u'usehttpliboverride'].lower() != 'false'
        return None

credentials = Credentials()

def getUniqueName(base_name):
    '''
    Returns a unique identifier for this particular test run so
    parallel test runs using the same Azure keys do not interfere
    with one another.
    '''
    cur_time = str(time.time())
    for bad in ["-", "_", " ", "."]:
        cur_time = cur_time.replace(bad, "")
    cur_time = cur_time.lower().strip()
    return base_name + str(random.randint(10, 99)) + cur_time[:12]

def create_service_management(service_class):
    if credentials.getUseRequestsLibrary():
        from requests import Session
        session = Session()
        session.cert = credentials.getManagementCertFile()
        service = service_class(credentials.getSubscriptionId(),
                            request_session=session)
    else:
        service = service_class(credentials.getSubscriptionId(),
                            credentials.getManagementCertFile())
    set_service_options(service)
    return service

def create_storage_service(service_class, name, key):
    session = None
    if credentials.getUseRequestsLibrary():
        from requests import Session
        session = Session()

    service = service_class(name, key, request_session=session)
    set_service_options(service)
    return service

def set_service_options(service):
    useHttplibOverride = credentials.getUseHttplibOverride()
    if useHttplibOverride is not None:
        # Override the auto-detection of what type of connection to create.
        # This allows testing of both httplib and winhttp on Windows.
        service._httpclient.use_httplib = useHttplibOverride

    service.set_proxy(credentials.getProxyHost(),
                      credentials.getProxyPort(),
                      credentials.getProxyUser(),
                      credentials.getProxyPassword())

class AzureTestCase(unittest.TestCase):

    def assertNamedItemInContainer(self, container, item_name, msg=None):
        for item in container:
            if item.name == item_name:
                return

        standardMsg = '{0} not found in {1}'.format(
            repr(item_name), repr(container))
        self.fail(self._formatMessage(msg, standardMsg))

    def assertNamedItemNotInContainer(self, container, item_name, msg=None):
        for item in container:
            if item.name == item_name:
                standardMsg = '{0} unexpectedly found in {1}'.format(
                    repr(item_name), repr(container))
                self.fail(self._formatMessage(msg, standardMsg))

    if sys.version_info < (2,7):
        def assertIsNone(self, obj):
            self.assertEqual(obj, None)

        def assertIsNotNone(self, obj):
            self.assertNotEqual(obj, None)

        def assertIsInstance(self, obj, type):
            self.assertTrue(isinstance(obj, type))

        def assertGreater(self, a, b):
            self.assertTrue(a > b)

        def assertGreaterEqual(self, a, b):
            self.assertTrue(a >= b)

        def assertLess(self, a, b):
            self.assertTrue(a < b)

        def assertLessEqual(self, a, b):
            self.assertTrue(a <= b)

        def assertIn(self, member, container):
            if member not in container:
                self.fail('{0} not found in {1}.'.format(
                    safe_repr(member), safe_repr(container)))

        @contextmanager
        def _assertRaisesContextManager(self, excClass):
            try:
                yield
                self.fail('{0} was not raised'.format(safe_repr(excClass)))
            except excClass:
                pass

        def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
            if callableObj:
                super(AzureTestCase, self).assertRaises(
                    excClass,
                    callableObj,
                    *args,
                    **kwargs
                )
            else:
                return self._assertRaisesContextManager(excClass)


text:
var autoFocus = function ($timeout) {
  return function(scope, element, attrs) {
    scope.$watch(attrs.autoFocus, function(val) {
      if(val){
        $timeout( function () {
          element[0].focus();
          element[0].select();
        }, 0);
      }
    })
  }
};

autoFocus.$inject = ['$timeout'];

module.exports = autoFocus;