text:
require 'test_helper'

class LevelsControllerTest < ActionController::TestCase
  include Devise::TestHelpers

  setup do
    Rails.application.config.stubs(:levelbuilder_mode).returns true
    Level.any_instance.stubs(:write_to_file?).returns(false) # don't write to level files

    @level = create(:level)
    @user = create(:admin)
    sign_in(@user)
    @program = '<hey/>'

    @not_admin = create(:user)
  end

  test "should get index" do
    get :index, game_id: @level.game
    assert_response :success
    assert_not_nil assigns(:levels)
  end

  test "should get new" do
    get :new, game_id: @level.game
    assert_response :success
  end

  test "should get new maze" do
    get :new, game_id: @level.game, type: "Maze"
    assert_response :success
  end

  test "should get new karel" do
    get :new, type: 'Karel'

    css = css_select "#level_type"
    assert_equal "Karel", css.first.attributes['value'].to_s
    assert_response :success
  end

  test "should get new of all types" do
    Level.descendants.each do |klass|
      get :new, type: klass.name

      assert_response :success
    end
  end

  test "should alphanumeric order custom levels on new" do
    Level.where(user_id: @user.id).map(&:destroy)
    level_1 = create(:level, user: @user, name: "BBBB")
    level_2 = create(:level, user: @user, name: "AAAA")
    level_3 = create(:level, user: @user, name: "Z1")
    level_4 = create(:level, user: @user, name: "Z10")
    level_5 = create(:level, user: @user, name: "Z2")

    get :new, game_id: @level.game

    assert_equal [level_2, level_1, level_3, level_5, level_4], assigns(:levels)
  end

  test "should not get builder if not admin" do
    sign_in @not_admin
    get :new, game_id: @level.game
    assert_response :forbidden
  end

  test "should create maze level" do
    maze = fixture_file_upload("maze_level.csv", "r")
    game = Game.find_by_name("CustomMaze")

    assert_difference('Level.count') do
      post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :type => 'Maze'}, :game_id => game.id, :program => @program, :maze_source => maze, :size => 8
    end

    assert assigns(:level)
    assert assigns(:level).game
    assert_equal edit_level_path(assigns(:level)), JSON.parse(@response.body)["redirect"]
  end

  test "should create maze levels with step mode" do
    maze = fixture_file_upload("maze_level.csv", "r")
    game = Game.find_by_name("CustomMaze")

    assert_difference('Level.count') do
      post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :step_mode => 1, :type => 'Maze'}, :game_id => game.id, :program => @program, :maze_source => maze, :size => 8
    end

    assert assigns(:level)
    assert assigns(:level).step_mode
  end

  test "should create maze levels with k1 on" do
    maze = fixture_file_upload("maze_level.csv", "r")
    game = Game.find_by_name("CustomMaze")

    assert_difference('Level.count') do
      post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :step_mode => 1, :type => 'Maze', :is_k1 => true}, :game_id => game.id, :program => @program, :maze_source => maze, :size => 8
    end

    assert assigns(:level)
    assert assigns(:level).is_k1
  end

  test "should create maze levels with k1 off" do
    maze = fixture_file_upload("maze_level.csv", "r")
    game = Game.find_by_name("CustomMaze")

    assert_difference('Level.count') do
      post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :step_mode => 1, :type => 'Maze', :is_k1 => false}, :game_id => game.id, :program => @program, :maze_source => maze, :size => 8
    end

    assert assigns(:level)
    assert !assigns(:level).is_k1
  end

  test "should not create invalid maze level" do
    maze = fixture_file_upload("maze_level_invalid.csv", "r")
    game = Game.find_by_name("CustomMaze")

    assert_no_difference('Level.count') do
      post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :type => 'Maze'}, :game_id => game.id, :program => @program, :maze_source => maze, :size => 8
    end

    assert_response :not_acceptable
  end

  test "should create karel level" do
    karel = fixture_file_upload("karel_level.csv", "r")
    game = Game.find_by_name("CustomMaze")

    assert_difference('Level.count') do
      post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :type => 'Karel'}, :game_id => game.id, :program => @program, :maze_source => karel, :size => 8
    end

    assert assigns(:level)
    assert assigns(:level).game
    assert_equal @user, assigns(:level).user

    assert_equal edit_level_path(assigns(:level)), JSON.parse(@response.body)["redirect"]
  end

  test "should not create invalid karel level" do
    karel = fixture_file_upload("karel_level_invalid.csv", "r")
    game = Game.find_by_name("CustomMaze")

    assert_no_difference('Level.count') do
      post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :type => 'Karel'}, :game_id => game.id, :program => @program, :maze_source => karel, :size => 8
    end

    assert_response :not_acceptable
  end

  test "should create artist level" do
    game = Game.find_by_name("Custom")
    assert_difference('Level.count') do
      post :create, :level => { :name => "NewCustomLevel", :type => 'Artist' }, :game_id => game.id, :program => @program
    end

    assert_equal edit_level_path(assigns(:level)), JSON.parse(@response.body)["redirect"]
  end

  test "should create studio level" do
    game = Game.find_by_name("CustomStudio")
    assert_difference('Level.count') do
      post :create, :level => { :name => "NewCustomLevel", :type => 'Studio' }, :game_id => game.id, :program => @program
    end

    assert_equal edit_level_path(assigns(:level)), JSON.parse(@response.body)["redirect"]
  end

  test "should create and destroy custom level with level file" do
    # Enable writing custom level to file for this specific test only
    Level.any_instance.stubs(:write_to_file?).returns(true)

    level_name = 'TestCustomLevel'
    begin
      post :create, :level => { :name => level_name, :type => 'Artist', :published => true }, :game_id => Game.find_by_name("Custom").id, :program => @program
      level = Level.find_by(name: level_name)
      file_path = LevelLoader.level_file_path(level.name)
      assert_equal true, file_path && File.exist?(file_path)
      delete :destroy, id: level
      assert_equal false, file_path && File.exist?(file_path)
    ensure
      file_path = LevelLoader.level_file_path(level_name)
      File.delete(file_path) if file_path && File.exist?(file_path)
    end
  end

  test "should not create invalid artist level" do
    game = Game.find_by_name("Custom")
    assert_no_difference('Level.count') do
      post :create, :level => { :name => '', :type => 'Artist' }, :game_id => game.id, :program => @program
    end
    assert_response :not_acceptable
  end

  test "should update blocks" do
    post :update_blocks, :level_id => @level.id, :game_id => @level.game.id, :type => 'toolbox_blocks', :program => @program
    assert_response :success
    level = assigns(:level)
    assert_equal level.properties[:toolbox_blocks.to_s], @program
  end

  test "should not update blocks if not admin" do
    sign_in @not_admin
    post :update_blocks, :level_id => @level.id, :game_id => @level.game.id, :type => 'toolbox_blocks', :program => @program
    assert_response :forbidden
  end

  test "should not edit level if not custom level" do
    level = Script.twenty_hour_script.levels.first
    can_edit =  Ability.new(@user).can? :edit, level
    assert_equal false, can_edit

    post :update_blocks, :level_id => level.id, :game_id => level.game.id, :type => 'toolbox_blocks', :program => @program
    assert_response :forbidden
  end

  test "should not create level if not admin" do
    sign_in @not_admin
    assert_no_difference('Level.count') do
      post :create, :name => "NewCustomLevel", :program => @program
    end

    assert_response :forbidden
  end

  # This should represent the behavior on production.
  test "should not modify level if not in levelbuilder mode" do
    Rails.application.config.stubs(:levelbuilder_mode).returns false

    post :create, :name => "NewCustomLevel", :program => @program
    assert_response :forbidden
  end

  test "should show level" do
    get :show, id: @level
    assert_response :success
  end

  test "should show level on test env" do
    Rails.env = "test"
    get :show, id: @level
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @level
    assert_response :success
  end

  test "should get edit blocks" do
    @level.update(toolbox_blocks: @program)
    get :edit_blocks, level_id: @level.id, type: 'toolbox_blocks'
    assert_equal @program, assigns[:level_view_options][:start_blocks]
  end

  test "should load file contents when editing a dsl defined level" do
    level_path = 'config/scripts/test_demo_level.external'
    data, _ = External.parse_file level_path
    External.setup data

    level = Level.find_by_name 'Test Demo Level'
    get :edit, id: level.id

    assert_equal level_path, assigns(:level).filename
    assert_equal "name 'test demo level'", assigns(:level).dsl_text.split("\n").first
  end

  test "should load encrypted file contents when editing a dsl defined level with the wrong encryption key" do
    CDO.stubs(:properties_encryption_key).returns("thisisafakekeyyyyyyyyyyyyyyyyyyyyy")
    level = Level.find_by_name 'Test External Markdown'
    get :edit, id: level.id

    assert_equal 'config/scripts/test_external_markdown.external', assigns(:level).filename
    assert_equal "name", assigns(:level).dsl_text.split("\n").first.split(" ").first
    assert_equal "encrypted", assigns(:level).dsl_text.split("\n")[1].split(" ").first
  end

  test "should update level" do
    patch :update, id: @level, level: {  }
    # Level update now uses AJAX callback, returns a 200 JSON response instead of redirect
    assert_response :success
  end

  test "update sends JSON::ParserError to user" do
    level = create(:applab)
    invalid_json = "{,}"
    patch :update, id: level, level: {"code_functions" => invalid_json}
    # Level update now uses AJAX callback, returns a 200 JSON response instead of redirect
    assert_response :unprocessable_entity

    expected = {'code_functions' => ["JSON::ParserError: 757: unexpected token at '{,}'"]}
    assert_equal expected, JSON.parse(@response.body)
  end

  test "should destroy level" do
    assert_difference('Level.count', -1) do
      delete :destroy, id: @level
    end

    assert_redirected_to levels_path
  end

  test "should route new to levels" do
    assert_routing({method: "post", path: "/levels"}, {controller: "levels", action: "create"})
  end

  test "should use level for route helper" do
    level = create(:artist)
    get :edit, id: level
    css = css_select "form[action=\"#{level_path(level)}\"]"
    assert_not css.empty?
  end

  test "should use first skin as default" do
    maze = fixture_file_upload("maze_level.csv", "r")
    game = Game.find_by_name("CustomMaze")

    post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :type => 'Maze'}, :game_id => game.id, :program => @program, :maze_source => maze, :size => 8
    assert_equal Maze.skins.first, assigns(:level).skin
  end

  test "should use skin from params on create" do
    maze = fixture_file_upload("maze_level.csv", "r")
    game = Game.find_by_name("CustomMaze")

    post :create, :level => {:skin => Maze.skins.last, :name => "NewCustomLevel", :instructions => "Some Instructions", :type => 'Maze'}, :game_id => game.id, :program => @program, :maze_source => maze, :size => 8
    assert_equal Maze.skins.last, assigns(:level).skin
  end

  test "edit form should include skins" do
    level = create(:artist)
    skins = level.class.skins
    get :edit, id: level, game_id: level.game
    skin_select = css_select "#level_skin option"
    values = skin_select.map { |option| option.attributes["value"].to_s }
    assert_equal skins, values
  end

  test "should populate artist start direction with current value" do
    level = create(:artist, :start_direction => 180)
    get :edit, id: level, game_id: level.game
    assert_select "#level_start_direction[value='180']"
  end

  test "should populate maze start direction with current value" do
    level = create(:maze, :start_direction => 2)
    get :edit, id: level, game_id: level.game
    assert_select "#level_start_direction option[value='2'][selected='selected']"
  end

  test "should populate level skin with current value" do
    level = create(:maze, :skin => 'pvz')
    get :edit, id: level, game_id: level.game
    assert_select "#level_skin option[value='pvz'][selected='selected']"
  end

  test 'should render level num in title' do
    get :show, id: @level, game_id: @level.game
    assert_match /#{Regexp.quote(@level.level_num)}/, Nokogiri::HTML(@response.body).css('title').text.strip
  end

  test "should update maze data properly" do
    game = Game.find_by_name("CustomMaze")
    post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :type => 'Maze'},
      :game_id => game.id, :maze_source => fixture_file_upload("maze_level.csv", "r"), :size => 8

    my_level = Level.where(name: 'NewCustomLevel').first
    maze_json = JSON.parse(my_level.maze)
    maze_json[0][0] = '2'
    maze_json[2][0] = 3

    patch :update, :level => {:maze_data => maze_json.to_json}, id: my_level, game_id: game.id

    new_maze = JSON.parse(Level.where(name: 'NewCustomLevel').first.maze)
    maze_json[0][0] = 2
    assert_equal maze_json, new_maze
  end

  test "should update karel data properly" do
    game = Game.find_by_name("CustomMaze")
    maze_array = [
      [{"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}],
      [{"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}],
      [{"tileType": 0}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 0}],
      [{"tileType": 0}, {"tileType": 2}, {"tileType": 1, "featureType": 2, "value": 1, "cloudType": 1, "range": 1}, {"tileType": 1, "featureType": 2, "value": 1, "cloudType": 2, "range": 1}, {"tileType": 1, "featureType": 2, "value": 1, "cloudType": 3, "range": 1}, {"tileType": 1, "featureType": 1, "value": 1, "cloudType": 4, "range": 1}, {"tileType": 1}, {"tileType": 0}],
      [{"tileType": 0}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 0}],
      [{"tileType": 0}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 1}, {"tileType": 0}],
      [{"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}],
      [{"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}, {"tileType": 0}]
    ]
    post :create, :level => {:name => "NewCustomLevel", :instructions => "Some Instructions", :type => 'Karel'}, :game_id => game.id, :size => 8
    my_level = Level.find_by(name: 'NewCustomLevel')

    patch :update, :level => {:maze_data => maze_array.to_json}, id: my_level, game_id: game.id
    new_maze = Level.find_by(name: 'NewCustomLevel').serialized_maze
    assert_equal maze_array.to_json, new_maze
  end

  test 'should show match level' do
    my_level = create :match, name: 'MatchLevel', type: 'Match'
    get :show, id: my_level, game_id: my_level.game
  end

  test 'should show legacy unplugged level' do
    level = create :unplugged, name: 'OldUnplugged', type: 'Unplugged'
    get :show, id: level, game_id: level.game
    assert_select 'div.unplugged > h2', 'Test title'
    assert_select 'div.unplugged > p', 'Test description'
  end

  test 'should hide legacy unplugged pdf download button for students' do
    level = create :unplugged, name: 'OldUnplugged', type: 'Unplugged'
    teacher = create(:teacher)
    sign_out(@user)
    sign_in(teacher)
    get :show, id: level, game_id: level.game
    assert_select '.pdf-button'

    @controller = LevelsController.new
    student = create(:student)
    sign_out(teacher)
    sign_in(student)
    get :show, id: level, game_id: level.game
    assert_select '.pdf-button', false, "Students shouldn't see PDF download button"
  end

  test 'should show new style unplugged level' do
    level = create :unplugged, name: 'NewUnplugged', type: 'Unplugged'
    get :show, id: level, game_id: level.game

    assert_select 'div.unplugged > h2', 'Test title'
    assert_select 'div.unplugged > p', 'Test description'
  end

  test 'should hide unplugged pdf download section for students' do
    level = create :unplugged, name: 'NewUnplugged', type: 'Unplugged'
    teacher = create(:teacher)
    sign_out(@user)
    sign_in(teacher)
    get :show, id: level, game_id: level.game
    assert_select '.pdf-button'

    @controller = LevelsController.new
    student = create(:student)
    sign_out(teacher)
    sign_in(student)
    get :show, id: level, game_id: level.game
    assert_select '.lesson-plan', false, "Students shouldn't see lesson plan"
  end

  test "should clone" do
    game = Game.find_by_name("Custom")
    old = create(:level, game_id: game.id, name: "Fun Level")
    assert_difference('Level.count') do
      post :clone, level_id: old.id, name: "Fun Level (copy 1)"
    end

    new_level = assigns(:level)
    assert_equal new_level.game, old.game
    assert_equal new_level.name, "Fun Level (copy 1)"
    assert_equal "/levels/#{new_level.id}/edit", URI(JSON.parse(@response.body)['redirect']).path
  end

  test 'cannot update level name with just a case change' do
    level = create :level, name: 'original name'

    post :update, id: level.id, level: {name: 'ORIGINAL NAME'}

    assert_response 422

    # error message
    assert assigns(:level).errors[:name]

    level = level.reload
    # same name
    assert_equal 'original name', level.name
  end

  test 'no error message when not actually changing level name' do
    level = create :level, name: 'original name'

    post :update, id: level.id, level: {name: 'original name'}

    assert_response 200

    # no error message
    assert assigns(:level).errors[:name].blank?

    level = level.reload
    # same name
    assert_equal 'original name', level.name
  end

  test 'can update level name' do
    level = create :level, name: 'original name'

    post :update, id: level.id, level: {name: 'different name'}

    level = level.reload
    # same name
    assert_equal 'different name', level.name
  end

  test 'trailing spaces in level name get stripped' do
    level = create :level, name: 'original name '
    assert_equal 'original name', level.name

    post :update, id: level.id, level: {name: 'different name  '}

    level = level.reload
    # same name
    assert_equal 'different name', level.name
  end

  test 'can show level when not signed in' do
    set_env :test

    level = create :artist
    sign_out @user

    get :edit, id: level
    assert_response :redirect

    get :show, id: level
    assert_response :success
  end

  test 'can show embed level when not signed in' do
    set_env :test

    level = create :artist
    sign_out @user

    get :embed_level, level_id: level
    assert_response :success
  end

  test 'can show embed blocks when not signed in' do
    set_env :test

    level = create :artist
    sign_out @user

    get :embed_blocks, level_id: level, block_type: :solution_blocks
    assert_response :success
  end
end


text:
.Modal {
  position: fixed;
  opacity: 1;
  z-index: 1001;
  max-width: 500px;
  top: 30%;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  transform: translateX(-50%);
}

/**
 * So transitions actually work
 */

.Modal.hidden {
  display: block;
}

/**
 * Default show/hide effect
 */

.Modal[effect="toggle"].hidden {
  display: none;
}

/**
 * Slide in from the bottom
 */

.Modal[effect="slide-in-bottom"] {
  top: 30%;
  left: 50%;
  -webkit-transform: translateX(-50%) translateY(0);
  -moz-transform: translateX(-50%) translateY(0);
  transform: translateX(-50%) translateY(0);
  transition: all .4s cubic-bezier(0.560, 0.185, 0.315, 1.150);
}

.Modal[effect="slide-in-bottom"].hidden {
  -webkit-transform: translateX(-50%) translateY(30%);
  -moz-transform: translateX(-50%) translateY(30%);
  transform: translateX(-50%) translateY(30%);
  opacity: 0;
}

/**
 * Sticky-up
 */

.Modal[effect="sticky-up"] {
  top: 0;
  left: 50%;
  -webkit-transform: translateX(-50%) translateY(0);
  -moz-transform: translateX(-50%) translateY(0);
  transform: translateX(-50%) translateY(0);
  transition: all .4s ease-in-out;
}

.Modal[effect="sticky-up"].hidden {
  -webkit-transform: translateX(-50%) translateY(-100%);
  -moz-transform: translateX(-50%) translateY(-100%);
  transform: translateX(-50%) translateY(-100%);
}

/**
 * Fade in and scale up from the middle
 */

.Modal[effect="fade-and-scale"] {
  top: 30%;
  left: 50%;
  -webkit-transform: translateX(-50%) translateY(0) scale(1);
  -moz-transform: translateX(-50%) translateY(0) scale(1);
  transform: translateX(-50%) translateY(0) scale(1);
  transition: all .4s cubic-bezier(0.560, 0.185, 0.315, 1.150);
}

.Modal[effect="fade-and-scale"].hidden {
  -webkit-transform: translateX(-50%) translateY(0%) scale(0.5);
  -moz-transform: translateX(-50%) translateY(0%) scale(0.5);
  transform: translateX(-50%) translateY(0%) scale(0.5);
  opacity: 0;
}

redpajama_set_name: RedPajamaGithub


text:
import { Injectable } from "@angular/core";
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
import { Support } from '../models/index';

@Injectable()
export class SupportService {

  support: FirebaseObjectObservable<Support>;

  supportList: FirebaseListObservable<Support[]>;

  constructor(private af: AngularFireDatabase) {
    this.supportList = this.af.list('/support');
  }

  getSupportTickets(): FirebaseListObservable<Support[]> {
    return this.af.list('/support');
  }

  addSupportTicket(ticket: Support): void {
    this.supportList.push(ticket);
  }

  getTicket(id: string): FirebaseObjectObservable<Support> {
    return this.af.object('/support/' + id);
  }

  removeSupportTicket(key?: string): void {
    this.supportList.remove(key);
  }

  updateSupportTicket(key: string, updateInfo: string): void {
    this.supportList.update(key, updateInfo);
  }
}


text:
require 'spec'

require 'isolated/require_spec'
require 'dm-core/spec/setup'

# To really test this behavior, this spec needs to be run in isolation and not
# as part of the typical rake spec run, which requires dm-transactions upfront

if %w[ postgres mysql sqlite oracle sqlserver ].include?(ENV['ADAPTER'])

  describe "require 'dm-migrations' after calling DataMapper.setup" do

    before(:all) do

      @adapter = DataMapper::Spec.adapter
      require 'dm-migrations'

      class ::Person
        include DataMapper::Resource
        property :id, Serial
      end

      @model   = Person

    end

    it_should_behave_like "require 'dm-migrations'"

  end

end


text:
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _

from easy_thumbnails.fields import ThumbnailerImageField
from easy_thumbnails.files import get_thumbnailer

class Profile(models.Model):
    """
    Profile information for uploaded content
    """
    full_name = models.CharField(
        _("full name"),
        max_length=255,
        blank=False,
        null=False,
        help_text=("The full name."),
    )
    email = models.EmailField(
        _("email"),
        max_length=255,
        blank=False,
        null=False,
        help_text=_("The email."),
    )
    phone = models.CharField(
        _("phone number"),
        blank=True,
        max_length=30,
        help_text=_("The phone number."),
    )

    copyright = models.TextField(
        _("copyright"),
        max_length=1000,
        help_text=_("The copyright information."),
    )

    def __unicode__(self):
        return u"{}".format(self.full_name)

    class Meta:
        verbose_name = _("profile")
        verbose_name_plural = _("profiles")

class Event(models.Model):
    """
    Event information for uploading photos.
    """
    title = models.CharField(
        _("title"),
        max_length=255,
        blank=False,
        null=False,
        help_text=_("The name of the event."),
    )
    slug = models.SlugField(
        _("slug"),
        help_text=_("Used for URLs, auto-generated from title if blank"),
        blank=True,
        null=True,
    )
    event_date = models.DateField(
        _("date"),
        blank=True,
        null=True,
    )

    def save(self, **kwargs):
        if self.title and not self.slug:
            self.slug = slugify(self.title)

        super(Event, self).save(**kwargs)

    @models.permalink
    def get_absolute_url(self):
        return False

    def __unicode__(self):
        return u"{}".format(self.title)

    class Meta:
        verbose_name = _("event")
        verbose_name_plural = _("events")

def photo_upload_to(instance, filename):
    return '{}/{}/{}'.format('photo_upload', instance.event, filename)

class Photo(models.Model):
    photo = ThumbnailerImageField(
        _("photo"),
        upload_to=photo_upload_to,
        blank=True,
        null=True,
    )
    event = models.ForeignKey(
        Event,
        blank=True,
        null=True,
    )
    profile = models.ForeignKey(
        Profile,
        blank=True,
        null=True,
    )

    @models.permalink
    def get_absolute_url(self):
        return reverse('photo_thumb', kwargs={'photo_id': self.id})

    def get_thumbnail(self, height=100, width=100):
        thumbnailer = get_thumbnailer(self.photo)
        thumbnail_options = {'size': (height, width)}
        return thumbnailer.get_thumbnail(thumbnail_options)


text:
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/dp_10">

        <TextView
            android:id="@+id/tv_oval"
            style="@style/UIShapeHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ShapeType" />

        <com.ddu.icore.ui.view.ShapeTextView
            android:id="@+id/tv_oval_xml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_5"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="XML_OVAL"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/tv_oval_code"
            app:layout_constraintTop_toBottomOf="@id/tv_oval"
            app:normalBackgroundColor="@color/c_4897fa"
            app:normalStrokeColor="@color/c_ff4141"
            app:normalStrokeWidth="0.5dp"
            app:shapeType="oval" />

        <TextView
            android:id="@+id/tv_oval_code"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="CODE_OVAL"
            app:layout_constraintBottom_toBottomOf="@id/tv_oval_xml"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toRightOf="@id/tv_oval_xml"
            app:layout_constraintRight_toRightOf="parent" />

        <com.ddu.icore.ui.view.ShapeTextView
            android:id="@+id/tv_round_xml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="XML_ROUND"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/tv_oval_code"
            app:layout_constraintTop_toBottomOf="@id/tv_oval_xml"
            app:normalStrokeColor="@color/c_4897fa"
            app:normalStrokeWidth="0.5dp"
            app:shapeType="round" />

        <Button
            android:id="@+id/tv_round_code"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="CODE_ROUND"
            app:layout_constraintBottom_toBottomOf="@id/tv_round_xml"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toRightOf="@id/tv_round_xml"
            app:layout_constraintRight_toRightOf="parent" />

        <com.ddu.icore.ui.view.ShapeTextView
            android:id="@+id/tv_round_rect_xml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:clickable="true"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="XML_ROUND_RECT"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/tv_round_rect_code"
            app:layout_constraintTop_toBottomOf="@id/tv_round_xml"
            app:normalBackgroundColor="@color/c_46b942"
            app:normalStrokeColor="@color/c_4897fa"
            app:normalStrokeWidth="0.5dp"
            app:pressedBackgroundColor="@color/c_9934c749"
            app:shapeType="round_rect" />

        <TextView
            android:id="@+id/tv_round_rect_code"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="CODE_ROUND_RECT"
            app:layout_constraintBottom_toBottomOf="@id/tv_round_rect_xml"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toRightOf="@id/tv_round_rect_xml"
            app:layout_constraintRight_toRightOf="parent" />

        <com.ddu.icore.ui.view.ShapeTextView
            android:id="@+id/tv_segment_xml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:clickable="true"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="XML_SEGMENT"
            app:direction="right"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/tv_segment_code"
            app:layout_constraintTop_toBottomOf="@id/tv_round_rect_xml"
            app:normalStrokeColor="@color/c_f7b218"
            app:normalStrokeWidth="0.5dp"
            app:pressedStrokeColor="@color/c_ef163f"
            app:shapeType="segment" />

        <TextView
            android:id="@+id/tv_segment_code"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="CODE_SEGMENT"
            app:layout_constraintBottom_toBottomOf="@id/tv_segment_xml"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toRightOf="@id/tv_segment_xml"
            app:layout_constraintRight_toRightOf="parent" />

        <com.ddu.icore.ui.view.ShapeTextView
            android:id="@+id/tv_radius_xml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:clickable="true"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="XML_RADIUS_10"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/tv_radius_code"
            app:layout_constraintTop_toBottomOf="@id/tv_segment_xml"
            app:normalBackgroundColor="@color/c_f7b218"
            app:normalStrokeColor="@color/c_ff00ff"
            app:normalStrokeWidth="0.5dp"
            app:pressedStrokeColor="@color/c_00ff00"
            app:shapeRadius="@dimen/dp_10" />

        <TextView
            android:id="@+id/tv_radius_code"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="CODE_RADIUS_10"
            app:layout_constraintBottom_toBottomOf="@id/tv_radius_xml"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toRightOf="@id/tv_radius_xml"
            app:layout_constraintRight_toRightOf="parent" />

        <com.ddu.icore.ui.view.ShapeTextView
            android:id="@+id/tv_dash_gap_xml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:clickable="true"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="XML_DASH_GAP"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/tv_dash_gap_code"
            app:layout_constraintTop_toBottomOf="@id/tv_radius_code"
            app:normalStrokeColor="@color/c_000000"
            app:normalStrokeWidth="0.5dp"
            app:pressedStrokeColor="@color/c_00ffff"
            app:shapeRadius="@dimen/dp_5"
            app:strokeDashGap="5dp"
            app:strokeDashWidth="5dp" />

        <TextView
            android:id="@+id/tv_dash_gap_code"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="CODE_DASH_GAP"
            app:layout_constraintBottom_toBottomOf="@id/tv_dash_gap_xml"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toRightOf="@id/tv_dash_gap_xml"
            app:layout_constraintRight_toRightOf="parent" />

        <com.ddu.icore.ui.view.ShapeTextView
            android:id="@+id/tv_all_xml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:clickable="true"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="XML_ALL"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/ll_all_code"
            app:layout_constraintTop_toBottomOf="@id/tv_dash_gap_code"
            app:normalBackgroundColor="@color/c_ff4141"
            app:normalStrokeColor="@color/c_4897fa"
            app:normalStrokeWidth="2dp"
            app:normalTextColor="@color/c_34c749"
            app:pressedBackgroundColor="@color/c_4897fa"
            app:pressedStrokeColor="@color/c_ff4141"
            app:pressedTextColor="@color/c_fdbc40"
            app:shapeRadius="@dimen/dp_5" />

        <LinearLayout
            android:id="@+id/ll_all_code"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:gravity="center"
            android:padding="@dimen/dp_5"
            android:text="CODE_ALL"
            app:layout_constraintBottom_toBottomOf="@id/tv_all_xml"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toRightOf="@id/tv_all_xml"
            app:layout_constraintRight_toRightOf="parent">

            <TextView
                android:id="@+id/tv_all_code"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="CODE_ALL" />
        </LinearLayout>

        <com.ddu.icore.ui.view.ShapeButton
            android:id="@+id/sb_search"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/dp_40"
            android:layout_marginTop="@dimen/dp_20"
            android:text="搜索"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/stv_search"
            app:layout_constraintTop_toBottomOf="@id/tv_all_xml"
            app:normalBackgroundColor="@color/c_4897fa"
            app:shapeRadius="@dimen/dp_20" />

        <com.ddu.icore.ui.view.ShapeTextView
            android:id="@+id/stv_search"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/dp_40"
            android:layout_marginTop="@dimen/dp_20"
            android:gravity="center"
            android:text="搜索"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintLeft_toRightOf="@id/sb_search"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tv_all_xml"
            app:normalBackgroundColor="@color/c_4897fa"
            app:shapeRadius="@dimen/dp_20" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class DefaultCS : System.Web.UI.Page
{
	protected void Page_Init(object sender, EventArgs e)
	{
		string[] embeddedIcons = new string[] { "rbAdd", "rbRemove", "rbOk", "rbCancel", "rbUpload", "rbDownload", "rbPrevious", "rbNext", "rbOpen", "rbAttach",
"rbSave", "rbConfig", "rbPrint", "rbRefresh", "rbSearch", "rbHelp", "rbCart", "rbEdit", "rbRSS", "rbMail", "rbFB", "rbTwitter", "rbLinkedIn", "rbPinterest",
"rbYouTube", "rbVimeo", "rbBehance", "rbDribble", "rbGooglePlus"};

		for (int i = 0; i < embeddedIcons.Length; i++)
		{
			string currIcon = embeddedIcons[i];

			HtmlTableRow row1 = new HtmlTableRow();

			//Add class name for icons:
			AddRowIconClassName(currIcon, table1, row1);

			//Add RadLinkButton with icons, Default skin:
			AddRadLinkButtonWithIcon("1" + i.ToString(), currIcon, "Silk", null, null, table1, row1);

			//Add RadLinkButton with icons, Glow skin:
			AddRadLinkButtonWithIcon("2" + i.ToString(), currIcon, "Glow", null, null, table1, row1);

		}
	}

	protected void AddRowIconClassName(string icon, HtmlTable table, HtmlTableRow row)
	{
		HtmlTableCell cell1 = new HtmlTableCell();
		cell1.InnerHtml = icon;
		row.Cells.Add(cell1);
		table.Rows.Add(row);
	}

	protected void AddRadLinkButtonWithIcon(string ID, string IconName, string Skin, int? Height, int? Top, HtmlTable table, HtmlTableRow row)
	{
		HtmlTableCell cell = new HtmlTableCell();
		RadLinkButton RadLinkButton1 = new RadLinkButton()
		{
			ID = "RadLinkButton1" + ID,
			Text = IconName,
			Skin = Skin,
		};
		if (Height != null)
			RadLinkButton1.Height = Unit.Pixel((int)Height);

		RadLinkButton1.Icon.CssClass = IconName;
		if (Top != null)
			RadLinkButton1.Icon.Top = Unit.Pixel((int)Top);

		cell.Controls.Add(RadLinkButton1);
		row.Cells.Add(cell);
		table.Rows.Add(row);
	}
}


text:
package com.agna.ferro.sample.ui.screen.catalog.grid;

import com.agna.ferro.sample.domain.Book;

public interface BookItemListener {
    void onDownloadClick(Book book);
    void onReadClick(Book book);
    void onClick(Book book);
}


text:
<!DOCTYPE html>

    <title>TextToSpeech Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

 Docs

View on GitHub

         Reference

        TextToSpeech Class Reference

            Classes

                TextToSpeech

            Enums

                AudioFormat

                PhonemeFormat

                SynthesisVoice

            Structs

                CustomVoiceUpdate

                Customization

                CustomizationID

                CustomizationWords

                Pronunciation

                Translation

                Voice

                Word

TextToSpeech

public class TextToSpeech

The Text to Speech service provides an API that uses IBM’s speech-synthesis capabilities to
synthesize text into natural-sounding speech in a variety of languages, accents, and voices. The
service supports at least one male or female voice, sometimes both, for each language. The audio
is streamed back to the client with minimal delay.

                    serviceURL

The base URL to use when contacting the service.

Declaration

Swift

public var serviceURL = "https://stream.watsonplatform.net/text-to-speech/api"

                    defaultHeaders

The default HTTP headers for all requests to the service.

Declaration

Swift

public var defaultHeaders = [String: String]()

                    init(username:password:)

Create a TextToSpeech object.

Declaration

Swift

public init(username: String, password: String)

Parameters

                                username

The username used to authenticate with the service.

                                password

The password used to authenticate with the service.

                    getVoices(failure:success:)

Retrieve information about all available voices.

Declaration

Swift

public func getVoices(
        failure: ((Error) -> Void)? = nil,
        success: @escaping ([Voice]) -> Void)

Parameters

                                failure

A function executed if an error occurs.

                                success

A function executed with the available voices.

                    getVoice(_:customizationID:failure:success:)

Get information about the given voice.

Specify a customizationID to obtain information for that custom voice model of the specified
voice. To see information about all available voices, use the getVoices() method.

Declaration

Swift

public func getVoice(
        _ voice: String,
        customizationID: String? = nil,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (Voice) -> Void)

Parameters

                                voice

The voice about which information is to be returned.

                                customizationID

The GUID of a custom voice model about which information is to be returned. You must make the request with the service credentials of the model's owner. Omit the parameter to see information about the voice with no customization.

                                failure

A function executed if an error occurs.

                                success

A function executed with information about the given voice.

                    getPronunciation(of:voice:format:failure:success:)

Get the phonetic pronunciation for the given text.

You can request the pronunciation for a specific format. You can also request the pronunciation
for a specific voice to see the default translation of the language of that voice.

Declaration

Swift

public func getPronunciation(
        of text: String,
        voice: String? = nil,
        format: PhonemeFormat? = nil,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (Pronunciation) -> Void)

Parameters

                                of

The word for which the pronunciation is requested.

                                voice

The voice in which the pronunciation for the specified word is to be returned. Specify a voice to obtain the pronunciation for the specified word in the language of that voice. Omit the parameter to obtain the pronunciation in the language of the default voice. Retrieve available voices with the getVoices() function.

                                format

Specify the phoneme set in which to return the pronunciation. Omit the parameter to obtain the pronunciation in the default format.

                                failure

A function executed if an error occurs.

                                success

A function executed with a Pronunciation object found based on input criteria.

                    synthesize(_:voice:customizationID:audioFormat:failure:success:)

Synthesize text to spoken audio.

Declaration

Swift

public func synthesize(
        _ text: String,
        voice: String? = nil,
        customizationID: String? = nil,
        audioFormat: AudioFormat = .wav,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (Data) -> Void)

Parameters

                                text

The text to be synthesized. Can be plain text or a subset of SSML.

                                voice

The voice to be used for synthesis.

                                customizationID

The GUID of a custom voice model to be used for the synthesis. If you specify a custom voice model, it is guaranteed to work only if it matches the language of the indicated voice. You must make the request with the service credentials of the model's owner. Omit the parameter to use the specified voice with no customization.

                                audioFormat

The audio format in which the synthesized text should be returned.

                                failure

A function executed if an error occurs.

                                success

A function executed with the spoken audio.

Customizations

                    getCustomizations(language:failure:success:)

Lists metadata, such as name and description, for the custom voice models that you own.

You can use the language query parameter to list voice models for the specified language. If
you leave language as nil, this will list all custom voice models you own for all languages.

Declaration

Swift

public func getCustomizations(
        language: String? = nil,
        failure: ((Error) -> Void)? = nil,
        success: @escaping ([Customization]) -> Void)

Parameters

                                language

The language of the voice models that you want listed.

                                failure

A function executed if an error occurs.

                                success

A function executed with an array of information about your custom voice models.

                    createCustomization(withName:language:description:failure:success:)

Creates a new empty custom voice model that is owned by the requesting user.

Declaration

Swift

public func createCustomization(
        withName name: String,
        language: String? = nil,
        description: String? = nil,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (CustomizationID) -> Void)

Parameters

                                withName

The name of the new custom voice model.

                                language

The language of the new custom voice model. 'en-US' is the default.

                                description

A description of the new custom voice model.

                                failure

A function executed if an error occurs.

                                success

A function executed with a customization ID.

                    deleteCustomization(withID:failure:success:)

Deletes the custom voice model with the specified customizationID.

Declaration

Swift

public func deleteCustomization(
        withID customizationID: String,
        failure: ((Error) -> Void)? = nil,
        success: ((Void) -> Void)? = nil)

Parameters

                                withID

The ID of the custom voice model to be deleted.

                                failure

A function executed if an error occurs.

                                success

A function executed if no error occurs.

                    getCustomization(withID:failure:success:)

Lists all information about the custom voice model with the specified customizationID.

Declaration

Swift

public func getCustomization(
        withID customizationID: String,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (CustomizationWords) -> Void)

Parameters

                                withID

The ID of the custom voice model.

                                failure

A function executed if an error occurs.

                                success

A function executed with a CustomizationWords object.

                    updateCustomization(withID:name:description:words:failure:success:)

Updates information for the custom voice model with the specified customizationID.

You can update metadata of the custom voice model, such as the name and description of the
voice model. You can also update or add words and translations in the model.

Declaration

Swift

public func updateCustomization(
        withID customizationID: String,
        name: String? = nil,
        description: String? = nil,
        words: [Word] = [],
        failure: ((Error) -> Void)? = nil,
        success: ((Void) -> Void)? = nil)

Parameters

                                withID

The ID of the custom voice model to be updated.

                                name

An updated name for the custom voice model.

                                description

A new description for the custom voice model.

                                words

An array of Word objects to be added to or updated in the custom voice model.

                                failure

A function executed if an error occurs.

                                success

A function executed if no error occurs.

                    getWords(forCustomizationID:failure:success:)

Lists all of the words and their translations for the custom voice model with the specified
customizationID.

Declaration

Swift

public func getWords(
        forCustomizationID customizationID: String,
        failure: ((Error) -> Void)? = nil,
        success: @escaping ([Word]) -> Void)

Parameters

                                forCustomizationID

The ID of the custom voice model.

                                failure

A function executed if an error occurs.

                                success

A function executed with an array of Word objects.

                    addWords(toCustomizationID:fromArray:failure:success:)

Adds one or more words and their translations to the custom voice model with the specified
customizationID.

Declaration

Swift

public func addWords(
        toCustomizationID customizationID: String,
        fromArray words: [Word],
        failure: ((Error) -> Void)? = nil,
        success: ((Void) -> Void)? = nil)

Parameters

                                toCustomizationID

The ID of the custom voice model to be updated.

                                words

An array of Word objects to be added to the custom voice model.

                                failure

A function executed if an error occurs.

                                success

A function executed if no error occurs.

                    deleteWord(_:fromCustomizationID:failure:success:)

Deletes the specified word from custom voice model.

Declaration

Swift

public func deleteWord(
        _ word: String,
        fromCustomizationID customizationID: String,
        failure: ((Error) -> Void)? = nil,
        success: ((Void) -> Void)? = nil)

Parameters

                                word

The word to be deleted from the custom voice model.

                                customizationID

The ID of the custom voice model to be updated.

                                failure

A function executed if an error occurs.

                                success

A function executed if no error occurs.

                    getTranslation(for:withCustomizationID:failure:success:)

Lists the translation for a single word from the custom model with the specified customizationID.

Declaration

Swift

public func getTranslation(
        for word: String,
        withCustomizationID customizationID: String,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (Translation) -> Void)

Parameters

                                for

The word in the custom voice model whose translation should be listed.

                                withCustomizationID

The ID of the custom voice model.

                                failure

A function executed if an error occurs.

                                success

A function executed with a Translation object.

                    addWord(_:toCustomizationID:withTranslation:failure:success:)

Adds a single word and its translation to the custom voice model with the specified customizationID.

Declaration

Swift

public func addWord(
        _ word: String,
        toCustomizationID customizationID: String,
        withTranslation translation: String,
        failure: ((Error) -> Void)? = nil,
        success: ((Void) -> Void)? = nil)

Parameters

                                word

The new word to be added to the custom voice model.

                                toCustomizationID

The ID of the custom voice model to be updated.

                                translation

The translation of the new word.

                                failure

A function executed if an error occurs.

                                success

A function executed if no error occurs.

© 2017 . All rights reserved. (Last updated: 2017-03-02)

Generated by jazzy ♪♫ v0.7.3, a Realm project.


text:
using System;
using System.Data;

namespace Nohros.Data
{
  /// <summary>
  /// An implementation of the <see cref="IDataField{T}"/> that maps a
  /// <see cref="Decimal"/> data type to a concrete <see cref="IDataField{T}"/>
  /// object.
  /// </summary>
  public class DataFieldDecimal: DataField<decimal>
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="DataFieldDecimal"/> class by
    /// using the specified field name and position.
    /// </summary>
    /// <param name="name">
    /// THe name of the field.
    /// </param>
    /// <param name="position">
    /// The zero based ordinal position of the field within an
    /// <see cref="IDataReader"/>.
    /// </param>
    public DataFieldDecimal(string name, int position)
      : base(name, position) {
    }

    /// <summary>
    /// Gets the value of the field as a <see cref="Decimal"/>
    /// </summary>
    /// <param name="reader">
    /// A <see cref="IDataReader"/> that can be used to extract a
    /// <see cref="Decimal"/> at the field position.
    /// </param>
    public override decimal GetValue(IDataReader reader) {
      return reader.GetDecimal(position);
    }
  }
}


text:
namespace blink {

namespace {
constexpr char kOtpCredentialType[] = "otp";
}

Credential::~Credential() = default;

Credential::Credential(const String& id, const String& type)
    : id_(id), type_(type) {
  DCHECK(!id_.IsEmpty() || type == kOtpCredentialType);
  DCHECK(!type_.IsEmpty());
}

KURL Credential::ParseStringAsURLOrThrow(const String& url,
                                         ExceptionState& exception_state) {
  if (url.IsEmpty())
    return KURL();
  KURL parsed_url = KURL(NullURL(), url);
  if (!parsed_url.IsValid()) {
    exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
                                      "'" + url + "' is not a valid URL.");
  }
  return parsed_url;
}

void Credential::Trace(Visitor* visitor) {
  ScriptWrappable::Trace(visitor);
}

}  // namespace blink


text:
// This file was automatically generated by the code gen tool - do not modify.

using System ;
using scg = System.Collections.Generic ;
using sd = System.Data ;
using sds = System.Data.SqlClient ;
using sr = System.Reflection ;
using mst = Microsoft.SqlServer.Types ;
using mss = Microsoft.SqlServer.Server ;
using acr = alby.codegen.runtime ;

namespace alby.northwind.codegen.table
{
	public partial class Suppliers : acr.RowBase
	{
		public const string column٠SupplierID  = "SupplierID" ;
		public const string column٠CompanyName  = "CompanyName" ;
		public const string column٠ContactName  = "ContactName" ;
		public const string column٠ContactTitle  = "ContactTitle" ;
		public const string column٠Address  = "Address" ;
		public const string column٠City  = "City" ;
		public const string column٠Region  = "Region" ;
		public const string column٠PostalCode  = "PostalCode" ;
		public const string column٠Country  = "Country" ;
		public const string column٠Phone  = "Phone" ;
		public const string column٠Fax  = "Fax" ;
		public const string column٠HomePage  = "HomePage" ;

		public int? SupplierID
		{
			get
			{
				return base.GetValueˡ<int?>( _dicˡ, column٠SupplierID ) ;
			}
			set
			{
				base.SetValueˡ<int?>( _dicˡ, column٠SupplierID, value, ref _dirtyˡ ) ;
			}
		}

		public string CompanyName
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠CompanyName ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠CompanyName, value, ref _dirtyˡ ) ;
			}
		}

		public string ContactName
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠ContactName ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠ContactName, value, ref _dirtyˡ ) ;
			}
		}

		public string ContactTitle
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠ContactTitle ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠ContactTitle, value, ref _dirtyˡ ) ;
			}
		}

		public string Address
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠Address ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠Address, value, ref _dirtyˡ ) ;
			}
		}

		public string City
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠City ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠City, value, ref _dirtyˡ ) ;
			}
		}

		public string Region
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠Region ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠Region, value, ref _dirtyˡ ) ;
			}
		}

		public string PostalCode
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠PostalCode ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠PostalCode, value, ref _dirtyˡ ) ;
			}
		}

		public string Country
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠Country ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠Country, value, ref _dirtyˡ ) ;
			}
		}

		public string Phone
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠Phone ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠Phone, value, ref _dirtyˡ ) ;
			}
		}

		public string Fax
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠Fax ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠Fax, value, ref _dirtyˡ ) ;
			}
		}

		public string HomePage
		{
			get
			{
				return base.GetValueˡ<string>( _dicˡ, column٠HomePage ) ;
			}
			set
			{
				base.SetValueˡ<string>( _dicˡ, column٠HomePage, value, ref _dirtyˡ ) ;
			}
		}

		public Suppliers() : base()
		{
			base._dicˡ[ column٠SupplierID ] = null ;
			base._dicˡ[ column٠CompanyName ] = null ;
			base._dicˡ[ column٠ContactName ] = null ;
			base._dicˡ[ column٠ContactTitle ] = null ;
			base._dicˡ[ column٠Address ] = null ;
			base._dicˡ[ column٠City ] = null ;
			base._dicˡ[ column٠Region ] = null ;
			base._dicˡ[ column٠PostalCode ] = null ;
			base._dicˡ[ column٠Country ] = null ;
			base._dicˡ[ column٠Phone ] = null ;
			base._dicˡ[ column٠Fax ] = null ;
			base._dicˡ[ column٠HomePage ] = null ;

			base._dicPKˡ[ column٠SupplierID ] = null ;

		}

	}

}


text:
(function() {

// Protects views where angular is not loaded from errors
if ( typeof angular == 'undefined' ) {
	return;
};

var module = angular.module('RecipeModel', ['restangular']);

module.factory('RecipeRestangular', function(Restangular) {

  return Restangular.withConfig(function(RestangularConfigurer) {

    RestangularConfigurer.setBaseUrl('http://localhost/data');
    RestangularConfigurer.setRequestSuffix('.json');
    RestangularConfigurer.setRestangularFields({
      id: "recipe_id"
    });

  });

});

})();


text:
namespace Shop.Core.Interfaces
{
    public interface IDirty
    {
        bool IsDirty { get; set; }
        void MarkClean();
    }
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<script>
onload = () => {
  document.designMode = 'on';
  getSelection().selectAllChildren(document.body);
  getSelection().modify('extend', 'backward', 'character');
};
</script>
<audio controls>


text:
                        76.1k
                followers,
                943k questions
                rss

JavaScript (not to be confused with Java) is a dynamic, weakly-typed language typically used for client-side scripting. Use this tag for questions regarding ECMAScript and its various dialects/implementations (excluding ActionScript). Unless a tag for a framework/library is also included, a pure JavaScript answer is expected.

    frequent
    info
    top users


text:
define(function (require) {
  'use strict';

  var modules = require('modules');
  var _ = require('lodash');

  require('scripts/common/services/properties_services');

  modules.get('a4c-common', ['pascalprecht.translate']).controller('PropertiesCtrl', ['$scope', 'propertiesServices', '$translate',
    function($scope, propertiesServices, $translate) {

      $scope.propertySave = function(data, unit) {
        delete $scope.unitError;
        if (_.undefined(data) || data.toString() === '') {
          data = null;
        } else if (_.defined($scope.definitionObject.units)) {
          if (_.undefined(unit)) {
            unit = $scope.definitionObject.uiUnit;
          }
          data += ' ' + unit;
        }
        // check constraint here
        var propertyRequest = {
          propertyDefinition: $scope.definition,
          propertyValue: data
        };
        var saveResult = $scope.onSave(propertyRequest);
        // If the callback return a promise
        if (_.defined(saveResult) && _.defined(saveResult.then)) {
          return saveResult.then(function(saveResult) {
            if (saveResult.error !== null) {
              // Constraint error display + translation
              var constraintInfo = saveResult.data;
              // Error message handled by x-editable
              if (saveResult.error.code === 800) {
                return $translate('ERRORS.' + saveResult.error.code + '.' + constraintInfo.name, constraintInfo);
              } else {
                return $translate('ERRORS.' + saveResult.error.code, constraintInfo);
              }
            }
          });
        }
      };

      $scope.saveUnit = function(unit) {
        $scope.definitionObject.uiUnit = unit;
        if (_.defined($scope.definitionObject.uiValue)) {
          var savePromise = $scope.propertySave($scope.definitionObject.uiValue, unit);
          if (_.defined(savePromise)) {
            savePromise.then(function(error) {
              if (_.defined(error)) {
                $scope.unitError = error;
              }
            });
          }
        }
      };

      // specific wrapper for boolean type to handle "css checkbox"
      $scope.propertySaveBoolean = function(propertyValue) {
        $scope.propertySave(propertyValue);
        $scope.definitionObject.uiValue = propertyValue;
      };

      /**
       * Return the property constraint identifier to represent it in the UI
       * We can define the représentation regardint the property "type" or "constraint"
       * Managed identifier / constraint :
       *  - validValues => select
       *  - date => date picker (standby)
       *  - boolean => checkbox
       *  - string => input text / password handled
       *  - inRange => slider
       */
      $scope.definitionObject = {};

      $scope.init = function() {
        $scope.$watch('propertyValue', function() {
          $scope.initScope();
        }, true);

        $scope.$watch('definition', function() {
          $scope.initScope();
        }, true);
        $scope.initScope();
      };

      $scope.initScope = function() {
        // Define properties
        if (!_.defined($scope.definition)) {
          return;
        }
        // Now a property is an AbstractPropertyValue : (Scalar or Function)
        var shownValue = $scope.propertyValue;
        if (_.defined($scope.propertyValue) && $scope.propertyValue.definition === false) {
          if ($scope.propertyValue.hasOwnProperty('value')) {
            // Here handle scalar value
            shownValue = $scope.propertyValue.value;
          } else if ($scope.propertyValue.hasOwnProperty('function') && $scope.propertyValue.hasOwnProperty('parameters') && $scope.propertyValue.parameters.length > 0) {
            shownValue = $scope.propertyValue.function + ': ' + _($scope.propertyValue.parameters).toString();
          }
        }

        // handeling default value
        shownValue = shownValue || $scope.definition.default;
        $scope.definitionObject.hasDefaultValue = _.defined($scope.definition.default);

        // Second phase : regarding constraints
        if (_.defined($scope.definition.constraints)) {
          for (var i = 0; i < $scope.definition.constraints.length; i++) {

            if ($scope.definition.constraints[i].hasOwnProperty('validValues')) {
              $scope.definitionObject.uiName = 'select';
              $scope.definitionObject.uiValue = shownValue;
              $scope.definitionObject.uiSelectValues = $scope.definition.constraints[i].validValues;
              return $scope.definitionObject;
            }

            if ($scope.definition.constraints[i].hasOwnProperty('inRange')) {
              $scope.definitionObject.uiName = 'range';
              $scope.definitionObject.uiValue = shownValue;
              $scope.definitionObject.uiValueMax = $scope.definition.constraints[i].rangeMaxValue;
              $scope.definitionObject.uiValueMin = $scope.definition.constraints[i].rangeMinValue;
              return $scope.definitionObject;
            }

          }
        }

        var splitScalarUnitValue = function(upperCase) {
          if (_.defined(shownValue)) {
            var shownValueTokens = shownValue.split(/\s+/);
            $scope.definitionObject.uiValue = shownValueTokens[0];
            if (upperCase) {
              $scope.definitionObject.uiUnit = shownValueTokens[1].toUpperCase();
            } else {
              $scope.definitionObject.uiUnit = shownValueTokens[1].toLowerCase();
            }
          } else {
            $scope.definitionObject.uiUnit = $scope.definitionObject.units[0];
            $scope.definitionObject.uiValue = shownValue;
          }
        };

        // Second phase : regardless constraints
        switch ($scope.definition.type) {
          case 'boolean':
            $scope.definitionObject.uiName = 'checkbox';
            if(_.undefined(shownValue)) {
              $scope.definitionObject.uiValue = false;
            } else if(typeof shownValue === 'boolean') {
              $scope.definitionObject.uiValue = shownValue;
            } else {
              $scope.definitionObject.uiValue = (shownValue === 'true');
            }
            break;
          case 'timestamp':
            $scope.definitionObject.uiName = 'date';
            $scope.definitionObject.uiValue = shownValue;
            break;
          case 'scalar-unit.size':
            $scope.definitionObject.uiName = 'scalar-unit';
            $scope.definitionObject.units = ['B', 'KB', 'KIB', 'MB', 'MIB', 'GB', 'GIB', 'TB', 'TIB'];
            splitScalarUnitValue(true);
            break;
          case 'scalar-unit.time':
            $scope.definitionObject.uiName = 'scalar-unit';
            $scope.definitionObject.units = ['d', 'h', 'm', 's', 'ms', 'us', 'ns'];
            splitScalarUnitValue(false);
            break;
          default:
            $scope.definitionObject.uiName = 'string';
            $scope.definitionObject.uiValue = shownValue;
            $scope.definitionObject.uiPassword = $scope.definition.password;
            break;
        }

        // Phase one valid or not ?
        if (!_.isEmpty($scope.definitionObject)) {
          return $scope.definitionObject;
        }
      };

      /** Reset the property to the default value if any */
      $scope.resetProperty = function resetPropertyToDefault() {
        $scope.initScope();
        $scope.propertySave($scope.definition.default, $scope.definitionObject.uiUnit);
        if ($scope.propertyValue.hasOwnProperty('value')) {
          $scope.propertyValue.value = $scope.definition.default; // if same value affected, no watch applied
        } else {
          $scope.propertyValue = $scope.definition.default;
        }
      };

      // Init managed property
      $scope.init();
    }
  ]); // controller
}); // define


text:
<?php

class Out extends API{

	public function Out($data_handler){
		parent::setDataHandler($data_handler);
	}

	public function init($params){

	}

	public function execute($params){

	}

	public function destroy($params){

	}

	public function GET($params){

		$dh= $this->getDataHandler();

		$dh->join("users", "users.id=access_out.user_id", "INNER");
		$dh->where("users.username", $params);
		$dh->orderBy("access_out.hour_exit", "desc");
		return $dh->getOne ("access_out","access_out.hour_exit");

	}

	public function PUT($params){

		$dh= $this->getDataHandler();

		$dh->where('username', $params);
		$user= $dh->getOne('users');

		$data= array('user_id' => $user['id']);
		return $dh->insert('access_out', $data);

	}

}

?>


text:
<?php

declare(strict_types = 1);

namespace Techworker\Ssml\Tests\Traits;

use Techworker\Ssml\Element\SayAs;
use Techworker\Ssml\SsmlBuilder;
use Techworker\Ssml\Tests\TestCase;

class SayAsTraitTest extends TestCase
{
    public function testAdd()
    {
        $speak = SsmlBuilder::factory()->sayAs('date', 'foobar', 'd');
        $sayAs = $this->access($speak, 'children')[0];
        self::assertInstanceOf(SayAs::class, $sayAs);
        self::assertEquals('date', $sayAs->interpretAs);
        self::assertEquals('foobar', $sayAs->content);
        self::assertEquals('d', $sayAs->format);
    }
}


text:
<?php
namespace Itgalaxy\Pillar\Tests;

use Itgalaxy\Pillar\Base\FeatureFactory;
use Itgalaxy\Pillar\Feature\NormalizeFileExtensionFeature;

class NormalizeFileExtensionFeatureTest extends \WP_UnitTestCase
{
    public function setUp()
    {
        parent::setUp();

        FeatureFactory::loadFeature(NormalizeFileExtensionFeature::class);
    }

    public function tearDown()
    {
        FeatureFactory::unloadFeature(NormalizeFileExtensionFeature::class);

        parent::tearDown();
    }

    public function testShouldRenameFileExtension()
    {
        $this->assertEquals('jpg', pathinfo(sanitize_file_name('foo.jpeg'))['extension']);
    }

    public function testShouldNotRenameFileExtension()
    {
        $this->assertEquals('png', pathinfo(sanitize_file_name('foo.png'))['extension']);
    }
}


text:
import ast
import jsonpatch
from oslo_utils import uuidutils
import pecan
import wsme

from magnum.common import exception
from magnum.common import utils
import magnum.conf
from magnum.i18n import _
from magnum import objects

CONF = magnum.conf.CONF

JSONPATCH_EXCEPTIONS = (jsonpatch.JsonPatchException,
                        jsonpatch.JsonPointerException,
                        KeyError)

DOCKER_MINIMUM_MEMORY = 4 * 1024 * 1024

def validate_limit(limit):
    if limit is not None and limit <= 0:
        raise wsme.exc.ClientSideError(_("Limit must be positive"))

    if limit is not None:
        return min(CONF.api.max_limit, limit)
    else:
        return CONF.api.max_limit

def validate_sort_dir(sort_dir):
    if sort_dir not in ['asc', 'desc']:
        raise wsme.exc.ClientSideError(_("Invalid sort direction: %s. "
                                         "Acceptable values are "
                                         "'asc' or 'desc'") % sort_dir)
    return sort_dir

def validate_docker_memory(mem_str):
    """Docker require that Minimum memory limit >= 4M."""
    try:
        mem = utils.get_docker_quantity(mem_str)
    except exception.UnsupportedDockerQuantityFormat:
        raise wsme.exc.ClientSideError(_("Invalid docker memory specified. "
                                         "Acceptable values are format: "
                                         "<number>[<unit>],"
                                         "where unit = b, k, m or g"))
    if mem < DOCKER_MINIMUM_MEMORY:
        raise wsme.exc.ClientSideError(_("Docker Minimum memory limit "
                                         "allowed is %d B.")
                                       % DOCKER_MINIMUM_MEMORY)

def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            attr = p['path'].lstrip('/')
            if attr not in doc:
                msg = _("Adding a new attribute %s to the root of "
                        "the resource is not allowed.") % p['path']
                raise wsme.exc.ClientSideError(msg)
            if doc[attr] is not None:
                msg = _("The attribute %s has existed, please use "
                        "'replace' operation instead.") % p['path']
                raise wsme.exc.ClientSideError(msg)

        if (p['op'] == 'replace' and (p['path'] == '/labels' or
                                      p['path'] == '/health_status_reason')):
            try:
                val = p['value']
                dict_val = val if type(val) == dict else ast.literal_eval(val)
                p['value'] = dict_val
            except (SyntaxError, ValueError, AssertionError) as e:
                raise exception.PatchError(patch=patch, reason=e)
    return jsonpatch.apply_patch(doc, patch)

def get_resource(resource, resource_ident):
    """Get the resource from the uuid or logical name.

    :param resource: the resource type.
    :param resource_ident: the UUID or logical name of the resource.

    :returns: The resource.
    """
    resource = getattr(objects, resource)

    if uuidutils.is_uuid_like(resource_ident):
        return resource.get_by_uuid(pecan.request.context, resource_ident)

    return resource.get_by_name(pecan.request.context, resource_ident)

def get_openstack_resource(manager, resource_ident, resource_type):
    """Get the openstack resource from the uuid or logical name.

    :param manager: the resource manager class.
    :param resource_ident: the UUID or logical name of the resource.
    :param resource_type: the type of the resource

    :returns: The openstack resource.
    :raises: ResourceNotFound if the openstack resource is not exist.
             Conflict if multi openstack resources have same name.
    """
    if uuidutils.is_uuid_like(resource_ident):
        resource_data = manager.get(resource_ident)
    else:
        filters = {'name': resource_ident}
        matches = list(manager.list(filters=filters))
        if len(matches) == 0:
            raise exception.ResourceNotFound(name=resource_type,
                                             id=resource_ident)
        if len(matches) > 1:
            msg = ("Multiple %(resource_type)s exist with same name "
                   "%(resource_ident)s. Please use the resource id "
                   "instead." % {'resource_type': resource_type,
                                 'resource_ident': resource_ident})
            raise exception.Conflict(msg)
        resource_data = matches[0]
    return resource_data

def get_labels_diff(parent_labels, labels):
    # Overriddent are the labels that exist in both the parent and the object
    # but have a different value.
    labels_overridden = {}
    # Added are the labels that exist in the object and not in the parent.
    labels_added = {}
    # We consider as skipped, the labels that exist in the parent but not in
    # the object's labels.
    labels_skipped = {
        k: v for k, v in parent_labels.items() if k not in labels
    }
    for key, value in labels.items():
        try:
            parent_value = parent_labels[key]
            if parent_value != value:
                labels_overridden[key] = parent_value
        except KeyError:
            labels_added[key] = value
    return labels_overridden, labels_added, labels_skipped