text:
  <TITLE>
  EMBOSS: union
  </TITLE>

union

Wiki

The master copies of EMBOSS documentation are available
at
http://emboss.open-bio.org/wiki/Appdocs
on the EMBOSS Wiki.

Please help by correcting and extending the Wiki pages.

    Function

Concatenate multiple sequences into a single sequence

    Description

union reads in several sequences, concatenates them and writes
them out as a single sequence.  The input is typically a list file
containing references to multiple sequences or subsequences (regions
of a sequence). Optionally, feature information will be used.

The output can have source features generated which document composite
sequences in the EMBL/GenBank feature table. The -findoverlap optin
checks for overlaps between adjacent joined regions and reports them
in the overlap file.

    Usage

Here is a sample session with union

The file 'cds.list' contains a list of the regions making up the coding sequence of 'embl:x65923':

% union
Concatenate multiple sequences into a single sequence
Input (gapped) sequence(s): @cds.list
output sequence [x65921.fasta]:

Go to the input files for this example
Go to the output files for this example

    Command line arguments

Concatenate multiple sequences into a single sequence
Version: EMBOSS:6.6.0.0

   Standard (Mandatory) qualifiers:
  [-sequence]          seqall     (Gapped) sequence(s) filename and optional
                                  format, or reference (input USA)
  [-outseq]            seqout     [<sequence>.<format>] Sequence filename and
                                  optional format (output USA)

   Additional (Optional) qualifiers:
   -overlapfile        outfile    [*.union] Sequence overlaps output file
                                  (optional)

   Advanced (Unprompted) qualifiers:
   -feature            boolean    [N] Use feature information
   -source             boolean    [N] Create source features
   -findoverlap        boolean    [N] Look for overlaps when joining

   Associated qualifiers:

   "-sequence" associated qualifiers
   -sbegin1            integer    Start of each sequence to be used
   -send1              integer    End of each sequence to be used
   -sreverse1          boolean    Reverse (if DNA)
   -sask1              boolean    Ask for begin/end/reverse
   -snucleotide1       boolean    Sequence is nucleotide
   -sprotein1          boolean    Sequence is protein
   -slower1            boolean    Make lower case
   -supper1            boolean    Make upper case
   -scircular1         boolean    Sequence is circular
   -squick1            boolean    Read id and sequence only
   -sformat1           string     Input sequence format
   -iquery1            string     Input query fields or ID list
   -ioffset1           integer    Input start position offset
   -sdbname1           string     Database name
   -sid1               string     Entryname
   -ufo1               string     UFO features
   -fformat1           string     Features format
   -fopenfile1         string     Features file name

   "-outseq" associated qualifiers
   -osformat2          string     Output seq format
   -osextension2       string     File name extension
   -osname2            string     Base file name
   -osdirectory2       string     Output directory
   -osdbname2          string     Database name to add
   -ossingle2          boolean    Separate file for each entry
   -oufo2              string     UFO features
   -offormat2          string     Features format
   -ofname2            string     Features file name
   -ofdirectory2       string     Output directory

   "-overlapfile" associated qualifiers
   -odirectory         string     Output directory

   General qualifiers:
   -auto               boolean    Turn off prompts
   -stdout             boolean    Write first file to standard output
   -filter             boolean    Read first file from standard input, write
                                  first file to standard output
   -options            boolean    Prompt for standard and additional values
   -debug              boolean    Write debug output to program.dbg
   -verbose            boolean    Report some/full command line options
   -help               boolean    Report command line options and exit. More
                                  information on associated and general
                                  qualifiers can be found with -help -verbose
   -warning            boolean    Report warnings
   -error              boolean    Report errors
   -fatal              boolean    Report fatal errors
   -die                boolean    Report dying program messages
   -version            boolean    Report version number and exit

Qualifier
Type
Description
Allowed values
Default

Standard (Mandatory) qualifiers

[-sequence]
(Parameter 1)
seqall
(Gapped) sequence(s) filename and optional format, or reference (input USA)
Readable sequence(s)
Required

[-outseq]
(Parameter 2)
seqout
Sequence filename and optional format (output USA)
Writeable sequence
<*>.format

Additional (Optional) qualifiers

-overlapfile
outfile
Sequence overlaps output file (optional)
Output file
<*>.union

Advanced (Unprompted) qualifiers

-feature
boolean
Use feature information
Boolean value Yes/No
No

-source
boolean
Create source features
Boolean value Yes/No
No

-findoverlap
boolean
Look for overlaps when joining
Boolean value Yes/No
No

Associated qualifiers

"-sequence" associated seqall qualifiers

 -sbegin1
-sbegin_sequence
integer
Start of each sequence to be used
Any integer value
0

 -send1
-send_sequence
integer
End of each sequence to be used
Any integer value
0

 -sreverse1
-sreverse_sequence
boolean
Reverse (if DNA)
Boolean value Yes/No
N

 -sask1
-sask_sequence
boolean
Ask for begin/end/reverse
Boolean value Yes/No
N

 -snucleotide1
-snucleotide_sequence
boolean
Sequence is nucleotide
Boolean value Yes/No
N

 -sprotein1
-sprotein_sequence
boolean
Sequence is protein
Boolean value Yes/No
N

 -slower1
-slower_sequence
boolean
Make lower case
Boolean value Yes/No
N

 -supper1
-supper_sequence
boolean
Make upper case
Boolean value Yes/No
N

 -scircular1
-scircular_sequence
boolean
Sequence is circular
Boolean value Yes/No
N

 -squick1
-squick_sequence
boolean
Read id and sequence only
Boolean value Yes/No
N

 -sformat1
-sformat_sequence
string
Input sequence format
Any string

 -iquery1
-iquery_sequence
string
Input query fields or ID list
Any string

 -ioffset1
-ioffset_sequence
integer
Input start position offset
Any integer value
0

 -sdbname1
-sdbname_sequence
string
Database name
Any string

 -sid1
-sid_sequence
string
Entryname
Any string

 -ufo1
-ufo_sequence
string
UFO features
Any string

 -fformat1
-fformat_sequence
string
Features format
Any string

 -fopenfile1
-fopenfile_sequence
string
Features file name
Any string

"-outseq" associated seqout qualifiers

 -osformat2
-osformat_outseq
string
Output seq format
Any string

 -osextension2
-osextension_outseq
string
File name extension
Any string

 -osname2
-osname_outseq
string
Base file name
Any string

 -osdirectory2
-osdirectory_outseq
string
Output directory
Any string

 -osdbname2
-osdbname_outseq
string
Database name to add
Any string

 -ossingle2
-ossingle_outseq
boolean
Separate file for each entry
Boolean value Yes/No
N

 -oufo2
-oufo_outseq
string
UFO features
Any string

 -offormat2
-offormat_outseq
string
Features format
Any string

 -ofname2
-ofname_outseq
string
Features file name
Any string

 -ofdirectory2
-ofdirectory_outseq
string
Output directory
Any string

"-overlapfile" associated outfile qualifiers

 -odirectory
string
Output directory
Any string

General qualifiers

 -auto
boolean
Turn off prompts
Boolean value Yes/No
N

 -stdout
boolean
Write first file to standard output
Boolean value Yes/No
N

 -filter
boolean
Read first file from standard input, write first file to standard output
Boolean value Yes/No
N

 -options
boolean
Prompt for standard and additional values
Boolean value Yes/No
N

 -debug
boolean
Write debug output to program.dbg
Boolean value Yes/No
N

 -verbose
boolean
Report some/full command line options
Boolean value Yes/No
Y

 -help
boolean
Report command line options and exit. More information on associated and general qualifiers can be found with -help -verbose
Boolean value Yes/No
N

 -warning
boolean
Report warnings
Boolean value Yes/No
Y

 -error
boolean
Report errors
Boolean value Yes/No
Y

 -fatal
boolean
Report fatal errors
Boolean value Yes/No
Y

 -die
boolean
Report dying program messages
Boolean value Yes/No
Y

 -version
boolean
Report version number and exit
Boolean value Yes/No
N

    Input file format

The input can be any set of sequences in a file of multiple sequence
entries or in a List file.  The sequences are concatenated in the
order in which they appear in the file.

Input files for usage example

File: cds.list

tembl-id:X65921[782:856]
tembl-id:X65921[951:1095]
tembl-id:X65921[1557:1612]
tembl-id:X65921[1787:1912]

You may find the program yank useful for creating List files.

    Output file format

Output files for usage example

File: x65921.fasta

>X65921 X65921.1 H.sapiens fau 1 gene
atgcagctctttgtccgcgcccaggagctacacaccttcgaggtgaccggccaggaaacg
gtcgcccagatcaaggctcatgtagcctcactggagggcattgccccggaagatcaagtc
gtgctcctggcaggcgcgcccctggaggatgaggccactctgggccagtgcggggtggag
gccctgactaccctggaagtagcaggccgcatgcttggaggtaaagtccatggttccctg
gcccgtgctggaaaagtgagaggtcagactcctaaggtggccaaacaggagaagaagaag
aagaagacaggtcgggctaagcggcggatgcagtacaaccggcgctttgtcaacgttgtg
cccacctttggcaagaagaagggccccaatgccaactcttaa

The result is a normal sequence file containing a single sequence
resulting from the concatenation of the input sequences.

    Data files

None.

    Notes

union is most useful when the input sequences are specified in a "list file". A list file contain references to any number of sequences which are retrieved from some other file or database.  Each sequence reference is a Uniform Sequence Address (USA) which can include the specification of sub-regions of the sequence, eg. <tt>em:x65923[20:55]</tt>). Specifying several such subregions in a sequence or sequences allows you to enter disjoint sequences to be joined.

    References

None.

    Warnings

None.

    Diagnostic Error Messages

None.

    Exit status

It always exits with status 0.

    Known bugs

None.

See also

Program name
Description

aligncopy
Read and write alignments

aligncopypair
Read and write pairs from alignments

biosed
Replace or delete sequence sections

codcopy
Copy and reformat a codon usage table

cutseq
Remove a section from a sequence

degapseq
Remove non-alphabetic (e.g. gap) characters from sequences

descseq
Alter the name or description of a sequence

entret
Retrieve sequence entries from flatfile databases and files

extractalign
Extract regions from a sequence alignment

extractfeat
Extract features from sequence(s)

extractseq
Extract regions from a sequence

featcopy
Read and write a feature table

featmerge
Merge two overlapping feature tables

featreport
Read and write a feature table

feattext
Return a feature table original text

listor
Write a list file of the logical OR of two sets of sequences

makenucseq
Create random nucleotide sequences

makeprotseq
Create random protein sequences

maskambignuc
Mask all ambiguity characters in nucleotide sequences with N

maskambigprot
Mask all ambiguity characters in protein sequences with X

maskfeat
Write a sequence with masked features

maskseq
Write a sequence with masked regions

newseq
Create a sequence file from a typed-in sequence

nohtml
Remove mark-up (e.g. HTML tags) from an ASCII text file

noreturn
Remove carriage return from ASCII files

nospace
Remove whitespace from an ASCII text file

notab
Replace tabs with spaces in an ASCII text file

notseq
Write to file a subset of an input stream of sequences

nthseq
Write to file a single sequence from an input stream of sequences

nthseqset
Read and write (return) one set of sequences from many

pasteseq
Insert one sequence into another

revseq
Reverse and complement a nucleotide sequence

seqcount
Read and count sequences

seqret
Read and write (return) sequences

seqretsetall
Read and write (return) many sets of sequences

seqretsplit
Read sequences and write them to individual files

sizeseq
Sort sequences by size

skipredundant
Remove redundant sequences from an input set

skipseq
Read and write (return) sequences, skipping first few

splitsource
Split sequence(s) into original source sequences

splitter
Split sequence(s) into smaller sequences

trimest
Remove poly-A tails from nucleotide sequences

trimseq
Remove unwanted characters from start and end of sequence(s)

trimspace
Remove extra whitespace from an ASCII text file

vectorstrip
Remove vectors from the ends of nucleotide sequence(s)

yank
Add a sequence reference (a full USA) to a list file

You may find the program yank useful for creating List files.

    Author(s)

Peter Rice

European Bioinformatics Institute, Wellcome Trust Genome Campus, Hinxton, Cambridge CB10 1SD, UK

Please report all bugs to the EMBOSS bug team (emboss-bug © emboss.open-bio.org) not to the original author.

    History

Written (March 2002) - Peter Rice.

    Target users

This program is intended to be used by everyone and everything, from naive users to embedded scripts.

    Comments

None


text:
package nextStep.springMVC;

import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

import org.mockito.Mockito;
import static org.mockito.Mockito.when;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

import java.nio.charset.Charset;
import java.util.Arrays;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.nextsteps.model.Student;
import com.nextsteps.util.IUtil;

@ActiveProfiles("testing")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"classpath:springConfig/appconfig-root.xml"})
@WebAppConfiguration
public class SpringTestFrameworkAndSpringSecurityTestFrameworkExample {

	public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8")
            );

    private MockMvc mockMvc;

    /* to use spring application context */
    @Autowired
    private IUtil utilMock;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp(){

        /* to use spring application context */
    	Mockito.reset(utilMock);
    	mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
				    			 .apply(springSecurity())
				    			 .build();

//		Authentication authentication = new TestingAuthenticationToken("mkyong", "112233","ROLE_USER");
//		SecurityContext context =  SecurityContextHolder.getContext();
//		context.setAuthentication(authentication);
//		SecurityContextHolder.setContext(context);

    }

    @Test
    @WithMockUser(roles={"USER","ADMIN"})
    public void findAll_ShouldAddTodoEntriesToModelAndRenderTodoListView() throws Exception {

    	Student student = new Student();
        student.setId(2);
        student.setFirstName("hamcrestwithspringtestframework");
    	when(utilMock.getStudent()).thenReturn(student);

		Student student1 = new Student();
		student1.setId(1);
		student1.setFirstName("Saeb");
		student1.setLastName("Ali");

		Student student2 = new Student();
		student2.setId(2);
		student2.setFirstName("Saeb2");
		student2.setLastName("Ali2");

		when(utilMock.getStudents()).thenReturn(Arrays.asList(student1,student2));

		mockMvc.perform(post("/save").param("firstName", "s").param("title", "t"));

        mockMvc.perform(get("/"))
			        .andExpect(status().isOk())
			        	.andExpect(view().name("enroll"))
			        	.andExpect(model().attribute("student", hasProperty("id", is(2))))
			        	.andExpect(model().attribute("student", hasProperty("firstName", is("hamcrestwithspringtestframework"))));

//      mockMvc.perform(post("/")
//                  .contentType(MediaType.APPLICATION_FORM_URLENCODED)
//                  .param("firstName", "s")
//                  .param("title", "t")
//    		  ).andExpect(status().isOk())
//	        	.andExpect(view().name("enroll"))
//	        	.andExpect(model().attributeHasFieldErrors("student", "section"));

        mockMvc.perform(get("/rest/getStudentsData").with(csrf()))
		        .andExpect(status().isOk())
		        .andExpect(content().contentType(APPLICATION_JSON_UTF8))
		        .andExpect(jsonPath("$", hasSize(1)))
		        .andExpect(jsonPath("$[0].id", is(nullValue())))
		        .andExpect(jsonPath("$[0].firstName", is("Saeb Najim 200")))
		        .andExpect(jsonPath("$[0].lastName", is("Abdradhi")));

        mockMvc.perform(post("/").param("firstName", "Saeb Najim").with(csrf())).andExpect(status().isOk());

        //Restful testing
//        mockMvc.perform(get("/rest/getStudentsData").with(csrf()))
//		        .andExpect(status().isOk())
//		        .andExpect(content().contentType(APPLICATION_JSON_UTF8))
//		        .andExpect(jsonPath("$", hasSize(2)))
//		        .andExpect(jsonPath("$[0].id", is(1)))
//		        .andExpect(jsonPath("$[0].firstName", is("Saeb")))
//		        .andExpect(jsonPath("$[0].lastName", is("Ali")))
//		        .andExpect(jsonPath("$[1].id", is(2)))
//		        .andExpect(jsonPath("$[1].firstName", is("Saeb2")))
//		        .andExpect(jsonPath("$[1].lastName", is("Ali2")));

    }
}

redpajama_set_name: RedPajamaGithub


text:
- [font awesome 中文网](http://www.fontawesome.com.cn/)
- [教程案例](http://www.fontawesome.com.cn/examples/#navigation-main)


text:
#import "GPUImageFilterGroup.h"

@interface GPUImageAdaptiveThresholdFilter : GPUImageFilterGroup

/** A multiplier for the background averaging blur radius in pixels, with a default of 4
 */
@property(readwrite, nonatomic) CGFloat blurRadiusInPixels;

@end


text:
        <form action="" method="post">

Sisteme Giriş

                        <?php echo $this->alert->flash('error') ?>

                            <input type="text" class="form-control" placeholder="Kullanıcı adı" name="username" value="<?php echo set_value('username') ?>">

                            <input type="password" class="form-control" placeholder="Parola" name="password">

                    <button class="btn btn-success btn-sm" type="submit">Giriş Yap</button>

        </form>


text:
"""Main entry point; starts the server."""

from app import app, db
import views  # routes, etc
import models  # database models

from items.blueprint import items
app.register_blueprint(items, url_prefix='/items')

# only start if this script is being run explicitly
if __name__ == '__main__':
    app.run()


text:
namespace {
// Whether to use the process start time for startup metrics.
BASE_FEATURE(kUseProcessStartTimeForMetrics,
             "UseProcessStartTimeForMetrics",
             base::FEATURE_DISABLED_BY_DEFAULT);
}  // namespace

// ChromeMainDelegateAndroid is created when the library is loaded. It is always
// done in the process' main Java thread. But for a non-browser process, e.g.
// renderer process, it is not the native Chrome's main thread.
ChromeMainDelegateAndroid::ChromeMainDelegateAndroid() = default;
ChromeMainDelegateAndroid::~ChromeMainDelegateAndroid() = default;

absl::optional<int> ChromeMainDelegateAndroid::BasicStartupComplete() {
  TRACE_EVENT0("startup", "ChromeMainDelegateAndroid::BasicStartupComplete");
  policy::android::AndroidCombinedPolicyProvider::SetShouldWaitForPolicy(true);
  SetChromeSpecificCommandLineFlags();

  return ChromeMainDelegate::BasicStartupComplete();
}

void ChromeMainDelegateAndroid::PreSandboxStartup() {
  ChromeMainDelegate::PreSandboxStartup();

  // Start the sampling profiler after crashpad initialization.
  sampling_profiler_ = std::make_unique<MainThreadStackSamplingProfiler>();
}

void ChromeMainDelegateAndroid::SecureDataDirectory() {
  // By default, Android creates the directory accessible by others.
  // We'd like to tighten security and make it accessible only by
  // the browser process.
  // TODO(crbug.com/832388): Remove this once minsdk >= 21,
  // at which point this will be handled by PathUtils.java.
  base::FilePath data_path;
  bool ok = base::PathService::Get(base::DIR_ANDROID_APP_DATA, &data_path);
  if (ok) {
    ok = base::SetPosixFilePermissions(data_path,
                                       base::FILE_PERMISSION_USER_MASK);
  }
  if (!ok) {
    LOG(ERROR) << "Failed to set data directory permissions";
  }
}

absl::variant<int, content::MainFunctionParams>
ChromeMainDelegateAndroid::RunProcess(
    const std::string& process_type,
    content::MainFunctionParams main_function_params) {
  TRACE_EVENT0("startup", "ChromeMainDelegateAndroid::RunProcess");
  // Defer to the default main method outside the browser process.
  if (!process_type.empty())
    return std::move(main_function_params);

  SecureDataDirectory();

  // Because the browser process can be started asynchronously as a series of
  // UI thread tasks a second request to start it can come in while the
  // first request is still being processed. Chrome must keep the same
  // browser runner for the second request.
  // Also only record the start time the first time round, since this is the
  // start time of the application, and will be same for all requests.
  if (!browser_runner_) {
    base::TimeTicks process_start_time = chrome::android::GetProcessStartTime();
    base::TimeTicks application_start_time =
        chrome::android::GetApplicationStartTime();
    if (!process_start_time.is_null()) {
      startup_metric_utils::RecordStartupProcessCreationTime(
          process_start_time);
      // TODO(crbug.com/1127482): Perf bots should add support for measuring
      // Startup.LoadTime.ProcessCreateToApplicationStart, then the
      // kUseProcessStartTimeForMetrics feature can be removed.
      if (base::FeatureList::IsEnabled(kUseProcessStartTimeForMetrics))
        application_start_time = process_start_time;
    }
    startup_metric_utils::RecordApplicationStartTime(application_start_time);
    browser_runner_ = content::BrowserMainRunner::Create();
  }

  int exit_code = browser_runner_->Initialize(std::move(main_function_params));
  // On Android we do not run BrowserMain(), so the above initialization of a
  // BrowserMainRunner is all we want to occur. Preserve any error codes > 0.
  if (exit_code > 0)
    return exit_code;
  return 0;
}


text:
<?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=busaracenter',
    'username' => 'Database usernae',
    'password' => 'database password',
    'charset' => 'utf8',
];


text:
class Array

  def shift_each
    while !self.empty?
      yield self.shift
    end
  end

end
module CommitCallback

  def commit_callback(named = false, &block)
    conn = self.connection
    unless conn.respond_to?(:commit_callbacks)
      conn.instance_eval do
        class << self
          unless method_defined?(:commit_db_transaction_original_for_commit_callback_hook)
            attr_accessor :commit_callbacks
            attr_accessor :named_commit_callbacks
            alias commit_db_transaction_original_for_commit_callback_hook commit_db_transaction
            def commit_db_transaction
              commit_db_transaction_original_for_commit_callback_hook
              (self.commit_callbacks || []).shift_each(&:call)
              self.commit_callbacks = []
              self.named_commit_callbacks = {}
            end
            alias rollback_db_transaction_original_for_commit_callback_hook rollback_db_transaction
            def rollback_db_transaction
              rollback_db_transaction_original_for_commit_callback_hook
              self.commit_callbacks = []
              self.named_commit_callbacks = {}
            end
          end
        end
      end
    end
    conn.named_commit_callbacks ||= {}
    conn.commit_callbacks ||= []
    if named
      unless conn.named_commit_callbacks[named]
        conn.named_commit_callbacks[named] = true
        conn.commit_callbacks << block
      end
    else
      conn.commit_callbacks << block
    end
  end

  def self.adapt_for_transactional_test!(connection)
    unless RAILS_ENV == "test"
      raise ArgumentError, "Use this only in tests please!"
    end
    connection.instance_eval do
      class << self
        attr_accessor :num_transactions_open_to_start
        def release_savepoint
          if self.open_transactions == num_transactions_open_to_start &&
             self.respond_to?(:commit_callbacks)
          then
            (self.commit_callbacks || []).shift_each(&:call)
            self.commit_callbacks = []
            self.named_commit_callbacks = []
          end
          super
        end
        def rollback_to_savepoint
          if self.open_transactions == num_transactions_open_to_start &&
             self.respond_to?(:commit_callbacks)
          then
            self.commit_callbacks = []
            self.named_commit_callbacks = []
          end
          super
        end
      end
    end
    connection.num_transactions_open_to_start = connection.open_transactions
  end

end


text:
Project to store Veterans' plot locations and to track the number of wreaths ordered for each Veteran.

Using
Vue.js
Node.js
webpack


text:
[redirect](e-original.md)
[redirect](redirect.md)
[redirect](redirect-2.md)


text:
module Rescuetime::CoreExtensions
  module Object
    # Includes methods that check the presence or blankness of an object.
    # @since v0.4.0
    module Blank
      # Returns true if the associated object is empty or falsey. Based on
      # Rails' ActiveSupport method Object#blank?
      #
      # @example
      #   module Rescuetime
      #     # ...
      #
      #     def format(report)
      #       # Guard: report presence
      #       report.extend CoreExtensions::Object::Blank
      #       report.blank? && return false
      #       # ...
      #     end
      #   end
      #
      # @return [Boolean]  true if the object is empty or falsey
      # @see #present?
      def blank?
        respond_to?(:empty?) ? !!empty? : !self
      end

      # Returns true if an object is truthy and is not empty (is not blank).
      # Based on Rails' ActiveSupport method Object#present?
      #
      # @example
      #   module Rescuetime
      #     # ...
      #
      #     def api_key?
      #       api_key.extend CoreExtensions::Object::Blank
      #       api_key.present?
      #     end
      #   end
      #
      # @return [Boolean]  true if the object is not blank
      # @see #blank?
      def present?
        !blank?
      end
    end
  end
end


text:
#include "..\..\..\YaizuComLib\src\stkpl\StkPl.h"
#include "MyMsgProc.h"
#include "..\Global.h"
#include "ApiGetSystem.h"

ApiGetSystem::ApiGetSystem()
{
	GetLocalTimeWStr();
}

void ApiGetSystem::GetLocalTimeWStr()
{
	int Year, MonA, Day, Hour, Min, Sec;
	StkPlGetTime(&Year, &MonA, &Day, &Hour, &Min, &Sec, true);
	wchar_t *Mon[] = {L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun", L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec"};
	StkPlSwPrintf(LocalTimeStr, 32, L"%ls %d %d %02d:%02d:%02d", Mon[MonA - 1], Day, Year, Hour, Min, Sec);
}

void ApiGetSystem::SetNumOfThreads(int Num)
{
	NumOfThreads = Num;
}

StkObject* ApiGetSystem::ExecuteImpl(StkObject* ReqObj, int Method, wchar_t UrlPath[StkWebAppExec::URL_PATH_LENGTH], int* ResultCode, wchar_t Locale[3], wchar_t* Token)
{
	StkObject* ResObj = new StkObject(L"");
	wchar_t YourName[Global::MAXLEN_OF_USERNAME] = L"";
	int YourId = -1;
	if (!CheckCredentials(Token, YourName, &YourId)) {
		AddCodeAndMsg(ResObj, MyMsgProc::CMDFRK_AUTH_ERROR, MyMsgProc::GetMsgEng(MyMsgProc::CMDFRK_AUTH_ERROR), MyMsgProc::GetMsgJpn(MyMsgProc::CMDFRK_AUTH_ERROR));
		*ResultCode = 401;
		return ResObj;
	}

	AddCodeAndMsg(ResObj, 0, L"", L"");
	StkObject* DatObj = new StkObject(L"Data");
	DatObj->AppendChildElement(new StkObject(L"ProductName", L"CmdFreak"));
	DatObj->AppendChildElement(new StkObject(L"Version", L"1.2.0"));
	wchar_t BuildDate[32];
	char BuildDateCh[32];
	StkPlSPrintf(BuildDateCh, 32, "%s  %s", __DATE__, __TIME__);
	StkPlConvUtf8ToWideChar(BuildDate, 32, BuildDateCh);
	DatObj->AppendChildElement(new StkObject(L"BuildTime", BuildDate));
	DatObj->AppendChildElement(new StkObject(L"StartTime", LocalTimeStr));
	DatObj->AppendChildElement(new StkObject(L"NumOfThreads", NumOfThreads));
	ResObj->AppendChildElement(DatObj);
	*ResultCode = 200;

	return ResObj;
}


text:
```bash
npm install evo-garage -g
```

Create a containing folder for your cluster, e.g. `$HOME/myCluster`.
Create a simple YAML file `$HOME/myCluster/cluster.yml` with

```yaml
---
script: lxc
env:
    ROOTFS: full-path-to-your-rootfs.squashfs
```

You can use [stemcell](https://github.com/evo-cloud/stemcell) to build a rootfs.

Now start server (remeber to use sudo as lxc requires root privilege):

```bash
sudo garage-server --clusters=$HOME/myCluster
```

Use the following command to list all clusters:

```bash
garage clusters
```

Or you can add a new cluster on the fly:

```bash
garage add-cluster path-to-dir-which-contains-cluster.yml
```

Let's get excited now!

```bash
garage start myCluster 1-16
```

It will create and start 16 nodes with IDs from 1 to 16.
You can also create nodes with any IDs you like:

```bash
garage start myCluster 20 25 46-50
```

Use `lxc-console` to attach to a node:

```bash
sudo lxc-console -n "myCluster-20" -t 1
```

You can check the nodes status:

```bash
garage nodes myCluster
```

You can stop any nodes in the cluster as simple as `start`

```bash
garage stop myCluster 1 5 7 9 10-20
```

### Special configuration for Linux Container

The default Linux Container support requires something to be pre-configured.

- One bridge for accessing external network with DHCP, NAT enabled, the name should be `lxcbr0`
- One bridge for cluster private network, no DHCP configured on host, the name should be `evobr0`

## Supported Containers

It only supports Linux Container at present,
but it is very easy to add other containers like QEMU,
VirtualBox etc if you can build rootfs in virtual disk files.
There are only 4 script files you need to add:

- `nodes`  it prints created node IDs one per line
- `status` it accepts one parameter as node ID and displays node status as one `key:value` pair per line
- `start`  it accepts one parameter as node ID for starting the node
- `stop`   it accepts one parameter as node ID for stopping the node

## License

MIT


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;

namespace Greatbone.Web
{
    /// <summary>
    /// An embedded web server that wraps around the kestrel HTTP engine.
    /// </summary>
    public sealed class WebServer : IHttpApplication<HttpContext>
    {
        readonly string[] addrs;

        // the embedded server
        readonly KestrelServer server;

        // cache of responses
        readonly ConcurrentDictionary<string, Response> cache;

        // the response cache cleaner thread
        Thread cleaner;

        // dbset operation areas keyed by service id
//        readonly ConcurrentDictionary<string, DbArea> areas;

        internal WebServer(AppConfig.Web cfg, ILoggerProvider logprov)
        {
            // init the embedded server
            var options = new KestrelServerOptions();
            ITransportFactory TransportFactory = new SocketTransportFactory(Options.Create(new SocketTransportOptions()), App.Lifetime, NullLoggerFactory.Instance);

            var logfac = new LoggerFactory();
            logfac.AddProvider(logprov);
            server = new KestrelServer(Options.Create(options), TransportFactory, logfac);

            ICollection<string> addrcoll = server.Features.Get<IServerAddressesFeature>().Addresses;
            this.addrs = cfg.addrs ?? throw new WebException("missing 'addrs'");
            foreach (string a in addrs)
            {
                addrcoll.Add(a.Trim());
            }

            int factor = (int) Math.Log(Environment.ProcessorCount, 2) + 1;
            // create the response cache
            if (cfg.cache)
            {
                cache = new ConcurrentDictionary<string, Response>(factor * 4, 1024);
            }
        }

        public WebWork RootWork { get; internal set; }

        /// <summary>
        /// To asynchronously process the request.
        /// </summary>
        public async Task ProcessRequestAsync(HttpContext context)
        {
            WebContext wc = (WebContext) context;

            string path = wc.Path;
            int dot = path.LastIndexOf('.');
            if (dot != -1) // the resource is a static file
            {
                if (!TryGiveFromCache(wc))
                {
                    GiveFile(path, path.Substring(dot), wc);
                    TryAddToCache(wc);
                }
            }
            else if (RootWork != null)
            {
                try
                {
                    await RootWork.HandleAsync(path.Substring(1), wc);
                }
                catch (Exception e)
                {
                    wc.Give(500, e.Message);
                }
            }
            else
            {
                wc.Give(404, "not found");
                return;
            }

            // sending
            try
            {
                await wc.SendAsync();
            }
            catch (Exception e)
            {
                wc.Give(500, e.Message);
            }
        }

        public void GiveFile(string filename, string ext, WebContext wc)
        {
            if (!StaticContent.TryGetType(ext, out var ctyp))
            {
                wc.Give(415); // unsupported media type
                return;
            }

            string path = "web" + filename;
            if (!File.Exists(path))
            {
                wc.Give(404); // not found
                return;
            }

            // load file content
            DateTime modified = File.GetLastWriteTime(path);
            byte[] bytes;
            bool gzip = false;
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                int len = (int) fs.Length;
                if (len > 2048)
                {
                    var ms = new MemoryStream(len);
                    using (GZipStream gzs = new GZipStream(ms, CompressionMode.Compress))
                    {
                        fs.CopyTo(gzs);
                    }
                    bytes = ms.ToArray();
                    gzip = true;
                }
                else
                {
                    bytes = new byte[len];
                    fs.Read(bytes, 0, len);
                }
            }

            StaticContent cnt = new StaticContent(bytes, bytes.Length)
            {
                Key = filename,
                Type = ctyp,
                Modified = modified,
                GZip = gzip
            };
            wc.Give(200, cnt, shared: true, maxage: 60 * 15);
        }

        ///
        /// Returns a framework custom context.
        ///
        public HttpContext CreateContext(IFeatureCollection features)
        {
            return new WebContext(features)
            {
                Service = this
            };
        }

        public void DisposeContext(HttpContext context, Exception excep)
        {
            // dispose the context
            ((WebContext) context).Dispose();
        }

        internal async Task StopAsync(CancellationToken token)
        {
            await server.StopAsync(token);

            // close logger
//            logWriter.Flush();
//            logWriter.Dispose();
        }

        internal async Task StartAsync(CancellationToken token)
        {
            await server.StartAsync(this, token);

            Console.WriteLine(" started at " + addrs[0]);

            // create and start the cleaner thread
            if (cache != null)
            {
                cleaner = new Thread(() =>
                {
                    while (!token.IsCancellationRequested)
                    {
                        // cleaning cycle
                        Thread.Sleep(30000); // every 30 seconds
                        // loop to clear or remove each expired items
                        int now = Environment.TickCount;
                        foreach (var re in cache)
                        {
                            if (!re.Value.TryClean(now))
                            {
                                cache.TryRemove(re.Key, out _);
                            }
                        }
                    }
                });
                cleaner.Start();
            }
        }

        //
        // RESPONSE CACHE

        internal void TryAddToCache(WebContext wc)
        {
            if (wc.IsGet)
            {
                if (!wc.IsInCache && wc.Shared == true && Response.IsCacheable(wc.StatusCode))
                {
                    var re = new Response(wc.StatusCode, wc.Content, wc.MaxAge, Environment.TickCount);
                    cache.AddOrUpdate(wc.Uri, re, (k, old) => re.MergeWith(old));
                    wc.IsInCache = true;
                }
            }
        }

        internal bool TryGiveFromCache(WebContext wc)
        {
            if (wc.IsGet)
            {
                if (cache.TryGetValue(wc.Uri, out var resp))
                {
                    return resp.TryGive(wc, Environment.TickCount);
                }
            }
            return false;
        }

        /// <summary>
        /// A prior response for caching that might be cleared but not removed, for better reusability.
        /// </summary>
        public class Response
        {
            // response status, 0 means cleared, otherwise one of the cacheable status
            short code;

            // can be set to null
            IContent content;

            // maxage in seconds
            int maxage;

            // time ticks when entered or cleared
            int stamp;

            int hits;

            internal Response(short code, IContent content, int maxage, int stamp)
            {
                this.code = code;
                this.content = content;
                this.maxage = maxage;
                this.stamp = stamp;
            }

            /// <summary>
            ///  RFC 7231 cacheable status codes.
            /// </summary>
            public static bool IsCacheable(int code)
            {
                return code == 200 || code == 203 || code == 204 || code == 206 || code == 300 || code == 301 || code == 404 || code == 405 || code == 410 || code == 414 || code == 501;
            }

            public int Hits => hits;

            public bool IsCleared => code == 0;

            /// <summary>
            ///
            /// </summary>
            /// <param name="now"></param>
            /// <returns>false to indicate a removal of the entry</returns>
            internal bool TryClean(int now)
            {
                lock (this)
                {
                    int pass = now - (stamp + maxage * 1000);

                    if (code == 0) return pass < 900 * 1000; // 15 minutes

                    if (pass >= 0) // to clear this reply
                    {
                        code = 0; // set to cleared
                        content = null; // NOTE: the buffer won't return to the pool
                        maxage = 0;
                        stamp = now; // time being cleared
                    }
                    return true;
                }
            }

            internal bool TryGive(WebContext wc, int now)
            {
                lock (this)
                {
                    if (code == 0)
                    {
                        return false;
                    }
                    short remain = (short) (((stamp + maxage * 1000) - now) / 1000); // remaining in seconds
                    if (remain > 0)
                    {
                        wc.IsInCache = true;
                        wc.Give(code, content, true, remain);
                        Interlocked.Increment(ref hits);
                        return true;
                    }
                    return false;
                }
            }

            internal Response MergeWith(Response old)
            {
                Interlocked.Add(ref hits, old.Hits);
                return this;
            }
        }
    }
}


text:
name: Wizard
---

1Add friends

2Find friends

3Profile information

4Join a network


text:
export { fetchResultsIfNeeded, pageResults } from './results';
export { requestFormOptions, requestTradeFlowSubgroups, requestReporterSubgroups } from './form_options';


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2016 The Netty Project
  ~
  ~ The Netty Project licenses this file to you 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.
  -->
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>io.netty</groupId>
    <artifactId>netty-parent</artifactId>
    <version>4.1.14.Final</version>
  </parent>
  <artifactId>netty-transport-native-unix-common-tests</artifactId>

  <name>Netty/Transport/Native/Unix/Common/Tests</name>
  <packaging>jar</packaging>
  <description>
    Tests for the static library which contains common unix utilities.
  </description>

  <dependencies>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-transport-native-unix-common</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>


text:
---
sidebar_postion: 3
---

# Navigation

Found provides a high-level abstractions such as a link component for controlling browser navigation. Under the hood, it delegates to [Farce](https://github.com/4Catalyzer/farce) for implementation, and as such can also be controlled directly via the Redux store.

#### Links

The `<Link>` component renders a link with optional active state indication.

```js
const link1 = (
  <Link to="/widgets/foo" activeClassName="active">
    Foo widget
  </Link>
);

const link2 = (
  <Link
    as={CustomAnchor}
    to={{
      pathname: '/widgets/bar',
      query: { the: query },
    }}
    activePropName="active"
  >
    Bar widget with query
  </Link>
);

const link3 = (
  <Link
    to={{
      pathname: '/widgets/bar',
      query: { the: query },
    }}
  >
    {({ href, active, onClick }) => (
      <CustomButton href={href} active={active} onClick={onClick} />
    )}
  </Link>
);
```

`<Link>` accepts the following props:

- `to`: a [location descriptor](https://github.com/4Catalyzer/farce#locations-and-location-descriptors) for the link's destination
- `exact`: if specified, the link will only render as active if the current location exactly matches the `to` location descriptor; by default, the link also will render as active on subpaths of the `to` location descriptor
- `activeClassName`: if specified, a CSS class to append to the component's CSS classes when the link is active
- `activeStyle`: if specified, a style object to append merge with the component's style object when the link is active
- `activePropName`: if specified, a prop to inject with a boolean value with the link's active state
- `as`: if specified, the custom element type to use for the link; by default, the link will render an `<a>` element

A link will navigate per its `to` location descriptor when clicked. You can prevent this navigation by providing an `onClick` handler that calls `event.preventDefault()`.

`<Link>` accepts a function for `children`. If `children` is a function, then `<Link>` will render the return value of that function, and will ignore `activeClassName`, `activeStyle`, `activePropName`, and `as` above. The function will be called with an object with the following properties:

- `href`: the URL for the link
- `active`: whether the link is active
- `onClick`: the click event handler for the link element

Otherwise, `<Link>` forwards additional props to the child element.

#### Programmatic navigation

The `withRouter` HOC wraps an existing component class or function and injects `match` and `router` props, as on route components above. You can use this HOC to create components that navigate programmatically in event handlers.

```js
const propTypes = {
  match: matchShape.isRequired,
  router: routerShape.isRequired,
};

class MyButton extends React.Component {
  onClick = () => {
    this.props.router.replace('/widgets');
  };

  render() {
    return (
      <button onClick={this.onClick}>
        Current widget: {this.props.match.params.widgetId}
      </button>
    );
  }
}

MyButton.propTypes = propTypes;

export default withRouter(MyButton);
```

The `useRouter` Hook provides the same capabilities.

```js
function MyButton() {
  const { match, router } = useRouter();

  const onClick = useCallback(() => {
    router.replace('/widgets');
  }, [router]);

  return (
    <button onClick={onClick}>Current widget: {match.params.widgetId}</button>
  );
}
```

#### Blocking navigation

The `router.addNavigationListener` method adds a [navigation listener](https://github.com/4Catalyzer/farce#navigation-listeners) that can block navigation. This method accepts a navigation listener function and an optional options object. It returns a function that removes the navigation listener.

```js
function MyForm(props) {
  const [dirty, setDirty] = useState(false);
  const { router } = useRouter();

  useEffect(
    () =>
      dirty
        ? router.addNavigationListener(
            () =>
              'You have unsaved input. Are you sure you want to leave this page?',
          )
        : undefined,
    [dirty],
  );

  /* ... */
}
```

The navigation listener function receives the location to which the user is attempting to navigate as its argument. Return `true` or `false` from this function to allow or block navigation respectively. Return a string to display a default confirmation dialog to the user. Return a nully value to use the next navigation listener if present, or else allow navigation. Return a promise to defer allowing or blocking navigation until the promise resolves; you can use this to display a custom confirmation dialog.

If you want to run your navigation listeners when the user attempts to leave the page, set `beforeUnload` in the options object. If this option is enabled, your navigation listeners will be called with a `null` location when the user attempts to leave the page. In this scenario, the navigation listener must return a non-promise value.

```js
router.addNavigationListener(
  (location) => {
    if (!location) {
      return false;
    }

    return asyncConfirm(location);
  },
  { beforeUnload: true },
);
```

The [navigation listener usage example](https://github.com/4Catalyzer/found/tree/master/examples/navigation-listener) demonstrates the use of navigation listeners in more detail, including the use of the `beforeUnload` option.


text:
package io.opencensus.scala.doobie

import cats.effect.{ContextShift, IO}
import io.opencensus.scala.Tracing
import io.opencensus.scala.http.testSuite.MockTracing
import io.opencensus.trace.{BlankSpan, Status}
import org.scalatest.{OptionValues, Outcome}

import scala.concurrent.ExecutionContext.global
import scala.util.Try
import org.scalatest.flatspec
import org.scalatest.matchers.should.Matchers

class FTracingSpec
    extends flatspec.FixtureAnyFlatSpec
    with Matchers
    with OptionValues {

  implicit val cs: ContextShift[IO] = IO.contextShift(global)

  case class TestInput(fTracing: FTracing[IO], mock: MockTracing)
  override protected def withFixture(test: OneArgTest): Outcome =
    test(clientTracingWithMock())

  override type FixtureParam = TestInput

  behavior of "FTracingSpec"

  it should "start with the correct name" in { f =>
    f.fTracing.traceF(IO(()), "testSpan", None).unsafeRunSync()
    f.mock.startedSpans should have size 1
    f.mock.startedSpans.head.name shouldBe "testSpan"
  }

  it should "trace with parent Span" in { f =>
    val parentSpan = BlankSpan.INSTANCE

    f.fTracing.traceF(IO(()), "testSpan", Some(parentSpan)).unsafeRunSync()
    f.mock.startedSpans should have size 1
    f.mock.startedSpans.head.parentContext.value shouldBe parentSpan.getContext
  }

  it should "stop after normal exit" in { f =>
    f.fTracing.traceF(IO(()), "testSpan", None).unsafeRunSync()
    f.mock.endedSpans should have size 1
    f.mock.endedSpans.head._2.value.getCanonicalCode shouldBe Status.OK.getCanonicalCode
  }

  it should "stop after error" in { f =>
    Try(
      f.fTracing
        .traceF(IO.raiseError(new Exception("TEST")), "testSpan", None)
        .unsafeRunSync()
    )
    f.mock.endedSpans should have size 1
    f.mock.endedSpans.head._2.value.getCanonicalCode shouldBe Status.INTERNAL.getCanonicalCode
  }

  def clientTracingWithMock() = {
    val mockTracing = new MockTracing
    val fTracing = new FTracing[IO] {
      override protected val tracing: Tracing = mockTracing
    }
    TestInput(fTracing, mockTracing)
  }
}


text:
layout: post
author: Yeolar
date: 2015-12-21 13:19
title: 异常控制流
category: Linux
tag: [linux,exception]
---

本文转自[网页](http://www.yeolar.com/note/2012/03/22/linux-ecf/#id6)

![Exception Control Flow](/public/img/linux/exception_control_flow.png)


text:
Using LocalTunnel on Macintosh
==============================

We no longer recommmend the use of LocalTunnel - please user ngrok.


text:
<main>
    <section class="main">
        <Headers></Headers>
        <Search></Search>
        <Todos></Todos>
        <Footers></Footers>
    </section>
    <transition name="editor">
        <TodoEditor v-if="todoEditing"></TodoEditor>
    </transition>
    <transition name="editor">
        <TagEditor v-if="tagEditing"></TagEditor>
    </transition>
</main>


text:
/*
 * @title: Animation
 * @description:
 * This sample shows how to load multiple animations and build an animation controller hierarchy.
 * An animation transition controller is used to blend between two animations.
 * You can enable drawing of debug information to see the animation bounding box, the skeleton,
 * and the mesh wireframe.
 * You can also click on the rendering windows to move and rotate the camera around.
*/

/*{{ javascript("jslib/aabbtree.js") }}*/
/*{{ javascript("jslib/camera.js") }}*/
/*{{ javascript("jslib/geometry.js") }}*/
/*{{ javascript("jslib/material.js") }}*/
/*{{ javascript("jslib/light.js") }}*/
/*{{ javascript("jslib/scenenode.js") }}*/
/*{{ javascript("jslib/scene.js") }}*/
/*{{ javascript("jslib/vmath.js") }}*/
/*{{ javascript("jslib/effectmanager.js") }}*/
/*{{ javascript("jslib/shadermanager.js") }}*/
/*{{ javascript("jslib/texturemanager.js") }}*/
/*{{ javascript("jslib/animationmanager.js") }}*/
/*{{ javascript("jslib/renderingcommon.js") }}*/
/*{{ javascript("jslib/defaultrendering.js") }}*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/resourceloader.js") }}*/
/*{{ javascript("jslib/animation.js") }}*/
/*{{ javascript("jslib/scenedebugging.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/vertexbuffermanager.js") }}*/
/*{{ javascript("jslib/indexbuffermanager.js") }}*/
/*{{ javascript("jslib/services/turbulenzservices.js") }}*/
/*{{ javascript("jslib/services/turbulenzbridge.js") }}*/
/*{{ javascript("jslib/services/gamesession.js") }}*/
/*{{ javascript("jslib/services/mappingtable.js") }}*/

/*{{ javascript("scripts/sceneloader.js") }}*/
/*{{ javascript("scripts/motion.js") }}*/
/*{{ javascript("scripts/htmlcontrols.js") }}*/

/*global TurbulenzEngine: true */
/*global TurbulenzServices: false */
/*global RequestHandler: false */
/*global TextureManager: false */
/*global ShaderManager: false */
/*global EffectManager: false */
/*global Scene: false */
/*global SceneLoader: false */
/*global ResourceLoader: false */
/*global Camera: false */
/*global HTMLControls: false */
/*global AnimationManager: false */
/*global CameraController: false */
/*global DefaultRendering: false */
/*global SkinnedNode: false */
/*global VMath: false */
/*global GPUSkinController: false */
/*global InterpolatorController: false */
/*global ReferenceController: false */
/*global NodeTransformController: false */
/*global TransitionController: false */

// We put some custom data onto Scene
class CustomScene extends Scene
{
    skinnedNodes: SkinnedNode[];
};

TurbulenzEngine.onload = function onloadFn()
{
    var errorCallback = function errorCallback(msg)
    {
        window.alert(msg);
    };
    TurbulenzEngine.onerror = errorCallback;

    var graphicsDeviceParameters = { };
    var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters);

    if (!graphicsDevice.shadingLanguageVersion)
    {
        errorCallback("No shading language support detected.\nPlease check your graphics drivers are up to date.");
        graphicsDevice = null;
        return;
    }

    // Clear the background color of the engine window
    var clearColor = [0.5, 0.5, 0.5, 1.0];
    if (graphicsDevice.beginFrame())
    {
        graphicsDevice.clear(clearColor);
        graphicsDevice.endFrame();
    }

    var mathDeviceParameters = { };
    var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters);

    var inputDeviceParameters = { };
    var inputDevice = TurbulenzEngine.createInputDevice(inputDeviceParameters);

    var requestHandlerParameters = { };
    var requestHandler = RequestHandler.create(requestHandlerParameters);

    var textureManager = TextureManager.create(graphicsDevice, requestHandler, null, errorCallback);
    var shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback);
    var effectManager = EffectManager.create();
    var animationManager = AnimationManager.create(errorCallback);
    var mappingTable;

    var resourceLoader = ResourceLoader.create();

    // Setup world space
    var worldUp = mathDevice.v3Build(0.0, 1.0, 0.0);

    // Bounds are red, interpolatorColor is updated per animation
    var boundsColor = [1, 0, 0];
    var interpolatorColor = [0, 0, 0];

    // Setup a camera to view a close-up object
    var camera = Camera.create(mathDevice);
    camera.nearPlane = 0.05;
    camera.updateViewMatrix();

    var animMinExtent, animMaxExtent;

    var cameraController = CameraController.create(graphicsDevice, inputDevice, camera);
    var maxSpeed = cameraController.maxSpeed;
    var cameraDistanceFactor = 1.0;
    var cameraDir = [1, 1, 1]; // The +/- direction the camera is moved from the scene in each axis

    // Settings for the animation
    var settings = {
        animScale: 1,
        defaultRate: 1,
        drawDebug: false,
        drawInterpolators: false,
        drawWireframe: false,
        loopAnimation: true,
        blendAnimation: false,
        transitionLength: 1
    };

    // The default animation to start with
    var defaultAnimIndex = 0;

    // The current playing animation
    var curAnimIndex = 0;

    // The controller references by index
    var controllerMap = [];

    // This is our base asset that includes a character and animations
    var assetToLoad = "models/Seymour.dae";

    // The list of animations to load pre-scene load (by reference)
    // This is only for animations that are not included in the default scene
    // e.g. "animations/default_walking.anim"
    var addAnimations = ["models/Seymour_anim2_rot90_anim_only.dae"];

    // The list of animations to be remove from the scene data pre-load
    // This is for undesired animations that are packed in the scene
    // All these animations are not required for this sample
    var removeAnimations = ["default_astroboy_w_skel02_gog_polySurface5",
                            "default_astroboy_w_skel02_polySurface5",
                            "default_astroboy_w_skel02c_gog_polySurface5",
                            "default_astroboy_w_skel02c_polySurface5",
                            "default_gog_polySurface5",
                            "default_polySurface5"];

    // The controller to blend the transisitions between animations, that don't have a matching key frame
    var transitionController = null;
    var transitionStartColor = [0, 0, 0];
    var transitionEndColor = [0, 0, 0];

    // Reference controller for the whole animation
    var currentReferenceController = null;
    var currentNodeController = null;

    var animationsLoaded;
    // When the JSON is loaded, add a prefix to uniquely identify that set of animation data
    var animationsLoadedCallback = function animationsLoadedCallbackFn(jsonData) {
        var addAnimNum = (addAnimations.length - animationsLoaded);
        animationManager.loadData(jsonData, "AnimExtra" + addAnimNum + "-");
        animationsLoaded -= 1;
    };

    var addAnimationsToScene = function addAnimationsToSceneFn()
    {
        // Attach additional animations to the scene (specify by path)
        // The animations are added by reference and the resourceLoader will attempt to load them using request
        animationsLoaded = addAnimations.length;
        for (var i = 0; i < addAnimations.length; i += 1)
        {
            var path = addAnimations[i];
            resourceLoader.load(mappingTable.getURL(path), {
                append : true,
                onload : animationsLoadedCallback,
                requestHandler: requestHandler
            });
        }
    };

    var removeAnimationsFromScene = function removeAnimationsFromSceneFn(sceneData)
    {
        // Remove unrequired animations from scene, if they exist before load
        var anims = sceneData.animations;
        var animationRef;

        if (anims)
        {
            for (var i = 0; i < removeAnimations.length; i += 1)
            {
                animationRef = removeAnimations[i];
                if (anims[animationRef])
                {
                    delete anims[animationRef];
                }
            }
        }

    };

    // Sets the next animation to play
    var nextAnimation = function nextAnimationFn(nextAnimIndex)
    {
        var controllers, interpStart, interpEnd, startColor, endColor, startSkinnedNode, endSkinnedNode, startNodes, endNodes;

        controllers = controllerMap[curAnimIndex];
        if (controllers)
        {
            interpStart = controllers.interpController;
            startColor = controllers.color;
            startSkinnedNode = controllers.skinnedNode;
            startNodes = controllers.nodeCount;
        }

        controllers = controllerMap[nextAnimIndex];
        if (controllers)
        {
            interpEnd = controllers.interpController;
            endColor = controllers.color;
            endSkinnedNode = controllers.skinnedNode;
            endNodes = controllers.nodeCount;
        }

        if (interpEnd)
        {
            interpEnd.setTime(0);

            // Set active on start skinned node to false
            if (startSkinnedNode && (startSkinnedNode !== endSkinnedNode))
            {
                startSkinnedNode.active = false;
                startSkinnedNode.setInputController(interpStart);
            }

            // Use the transition controller instead on this node
            // Don't blend if the interpControllers are the same
            // Don't blend if the number of nodes is different
            if ((settings.blendAnimation || !interpStart) &&
                (interpStart !== interpEnd) &&
                (startNodes === endNodes))
            {
                if (!transitionController)
                {
                    transitionController = TransitionController.create(interpStart, interpEnd, settings.transitionLength);
                    transitionController.onFinishedTransitionCallback = function onFinishedTransitionCallbackFn(/* transition */)
                    {
                        var controllers = controllerMap[curAnimIndex];
                        if (controllers)
                        {
                            var skinnedNode = controllers.skinnedNode;
                            currentReferenceController.setReferenceController(controllers.interpController);
                            currentReferenceController.setTime(0);
                            interpolatorColor = controllers.color;
                            if (skinnedNode)
                            {
                                skinnedNode.setInputController(currentReferenceController);
                                skinnedNode.active = true;
                            }
                        }
                        // Callback return value of 'false' tells the controller not to continue operating
                        // This is because we have decided to set a different controller to be used instead
                        return false;
                    };
                    transitionController.onUpdateCallback = function onUpdateCallbackFn(transition)
                    {
                        var delta = (transition.transitionTime / transition.transitionLength);
                        interpolatorColor = VMath.v3Add(VMath.v3ScalarMul(transitionStartColor, 1 - delta), VMath.v3ScalarMul(transitionEndColor, delta));
                    };
                }
                else
                {
                    transitionController.setEndController(interpEnd);
                    transitionController.setStartController(interpStart);
                    transitionController.setTransitionLength(settings.transitionLength);
                }

                currentReferenceController.setReferenceController(transitionController);
                transitionStartColor = startColor;
                transitionEndColor = endColor;
            }
            else
            {
                // Set the node controller to be the reference controller
                currentReferenceController.setReferenceController(interpEnd);
                interpolatorColor = endColor;
            }

            // Reset the animation about to play
            currentReferenceController.setTime(0);

            if (endSkinnedNode)
            {
                endSkinnedNode.setInputController(currentReferenceController);
                endSkinnedNode.active = true;
            }
            curAnimIndex = nextAnimIndex;
        }

    };

    // Update the settings for an existing animation controller
    var updateAnimations = function updateAnimationsFn(/* scene */)
    {
        var i, controllers, interp;
        var length = controllerMap.length;

        for (i = 0; i < length; i += 1)
        {
            controllers = controllerMap[i];
            if (controllers)
            {
                interp = controllers.interpController;
                if (interp)
                {
                    interp.setAnimation(interp.currentAnim, settings.loopAnimation);
                    interp.setRate(settings.defaultRate);
                }
            }
        }
    };

    function calcAnimationExtents(scene, animationIndex)
    {
        // Calculate the extents from the animation
        var controllers = controllerMap[animationIndex];
        if (controllers)
        {
            var maxValue = Number.MAX_VALUE;
            var animExtentMin0 = maxValue;
            var animExtentMin1 = maxValue;
            var animExtentMin2 = maxValue;
            var animExtentMax0 = -maxValue;
            var animExtentMax1 = -maxValue;
            var animExtentMax2 = -maxValue;

            var bounds = controllers.animation.bounds;
            var numFrames = bounds.length;
            for (var i = 0; i < numFrames; i = i + 1)
            {
                var bound = bounds[i];
                var center = bound.center;
                var halfExtent = bound.halfExtent;
                var c0 = center[0];
                var c1 = center[1];
                var c2 = center[2];
                var h0 = halfExtent[0];
                var h1 = halfExtent[1];
                var h2 = halfExtent[2];
                var min0 = (c0 - h0);
                var min1 = (c1 - h1);
                var min2 = (c2 - h2);
                var max0 = (c0 + h0);
                var max1 = (c1 + h1);
                var max2 = (c2 + h2);
                animExtentMin0 = (animExtentMin0 < min0 ? animExtentMin0 : min0);
                animExtentMin1 = (animExtentMin1 < min1 ? animExtentMin1 : min1);
                animExtentMin2 = (animExtentMin2 < min2 ? animExtentMin2 : min2);
                animExtentMax0 = (animExtentMax0 > max0 ? animExtentMax0 : max0);
                animExtentMax1 = (animExtentMax1 > max1 ? animExtentMax1 : max1);
                animExtentMax2 = (animExtentMax2 > max2 ? animExtentMax2 : max2);
            }

            animMinExtent = mathDevice.v3Build(animExtentMin0, animExtentMin1, animExtentMin2);
            animMaxExtent = mathDevice.v3Build(animExtentMax0, animExtentMax1, animExtentMax2);
        }
        else
        {
            // Use the scene extents
            var sceneExtents = scene.getExtents();
            animMinExtent = mathDevice.v3Build(sceneExtents[0], sceneExtents[1], sceneExtents[2]);
            animMaxExtent = mathDevice.v3Build(sceneExtents[3], sceneExtents[4], sceneExtents[5]);
        }

    }

    // Calculates a position for the camera to lookAt
    var resetCamera = function resetCameraFn(camera, scene)
    {
        calcAnimationExtents(scene, curAnimIndex);

        // Update the camera to scale to the size of the scene
        var center = mathDevice.v3ScalarMul(mathDevice.v3Add(animMaxExtent, animMinExtent), 0.5);
        var extent = mathDevice.v3Sub(center, animMinExtent);

        camera.lookAt(center,
                      worldUp,
                      mathDevice.v3Build(center[0] + extent[0] * cameraDistanceFactor * cameraDir[0] * 2,
                                         center[1] + extent[1] * cameraDistanceFactor * cameraDir[1],
                                         center[2] + extent[2] * cameraDistanceFactor * cameraDir[2] * 2));
        camera.updateViewMatrix();

        // Calculates the appropriate nearPlane for the animation extents
        var len = VMath.v3Length(extent);
        if (len < 4.0)
        {
            camera.nearPlane = len * 0.1;
        }
        else
        {
            camera.nearPlane = 1.0;
        }
        camera.farPlane = Math.ceil(len) * 100.0;
        camera.updateProjectionMatrix();

        // Calculates the speed to move around the animation
        maxSpeed = (len < 100 ? (len * 2) : (len * 0.5));
    };

    // Create object using scene loader
    var scene = <CustomScene>(Scene.create(mathDevice));
    var sceneLoader = SceneLoader.create();

    var renderer;
    var loadAssets = function loadAssets()
    {
        // Renderer for the scene (requires shader assets).
        renderer = DefaultRendering.create(graphicsDevice,
                                           mathDevice,
                                           shaderManager,
                                           effectManager);

        renderer.setGlobalLightPosition(mathDevice.v3Build(0.5, 100.0, 0.5));
        renderer.setAmbientColor(mathDevice.v3Build(0.3, 0.3, 0.4));
        renderer.setDefaultTexture(textureManager.get("default"));

        sceneLoader.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix);
        sceneLoader.load({
            scene : scene,
            assetPath : assetToLoad,
            graphicsDevice : graphicsDevice,
            mathDevice : mathDevice,
            textureManager : textureManager,
            effectManager : effectManager,
            shaderManager : shaderManager,
            animationManager : animationManager,
            requestHandler: requestHandler,
            keepVertexData : true,
            preSceneLoadFn : function (sceneData)
            {
                // Apply the modifications to the data from assetPath
                addAnimationsToScene();
                removeAnimationsFromScene(sceneData);
            },
            keepLights : true,
            append : true
        });
    };

    var mappingTableReceived = function mappingTableReceivedFn(mappingTable)
    {
        textureManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix);
        shaderManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix);
        sceneLoader.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix);

        loadAssets();
    };

    var gameSessionCreated = function gameSessionCreatedFn(gameSession)
    {
        var defaultMappingSettings = {
            mappingTablePrefix: "staticmax/",
            assetPrefix: "missing/",
            mappingTableURL: "mapping_table.json"
        };
        mappingTable = TurbulenzServices.createMappingTable(requestHandler,
                                                            gameSession,
                                                            mappingTableReceived,
                                                            defaultMappingSettings);
    };
    var gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated);

    // Controls
    var htmlControls = HTMLControls.create();

    htmlControls.addButtonControl({
        id: "button01",
        value: "Next",
        fn: function ()
        {
            nextAnimation((curAnimIndex + 1) % controllerMap.length);
        }
    });

    htmlControls.addButtonControl({
        id: "button02",
        value: "Previous",
        fn: function ()
        {
            var index = (curAnimIndex - 1);
            index = (index === -1) ? (controllerMap.length - 1) : index;
            nextAnimation(index);
        }
    });

    htmlControls.addButtonControl({
        id: "button03",
        value: "Reset Camera",
        fn: function ()
        {
            resetCamera(camera, scene);
        }
    });

    htmlControls.addCheckboxControl({
        id: "checkbox01",
        value: "loopAnimation",
        isSelected: settings.loopAnimation,
        fn: function ()
        {
            settings.loopAnimation = !settings.loopAnimation;
            updateAnimations();
            return settings.loopAnimation;
        }
    });

    htmlControls.addCheckboxControl({
        id: "checkbox02",
        value: "blendAnimation",
        isSelected: settings.blendAnimation,
        fn: function ()
        {
            settings.blendAnimation = !settings.blendAnimation;
            return settings.blendAnimation;
        }
    });

    htmlControls.addCheckboxControl({
        id: "checkbox03",
        value: "drawDebug",
        isSelected: settings.drawDebug,
        fn: function ()
        {
            settings.drawDebug = !settings.drawDebug;
            settings.drawWireframe = settings.drawDebug;
            settings.drawInterpolators = settings.drawDebug;
            return settings.drawDebug;
        }
    });

    htmlControls.register();

    // Provides a distinct array of colors to use for each controller
    // Does not use red, black or white as they are reserved
    var colorArray = [
        [0.5, 1, 0.5],
        [0.5, 1, 1],
        [1, 1, 0.5],
        [1, 0.5, 1],
        [0.5, 0.5, 1]
    ];
    var lastColor = (colorArray.length - 1);
    var getControllerColor = function getControllerColorFn()
    {
        lastColor = (lastColor + 1) % colorArray.length;
        return colorArray[lastColor];
    };

    // Initialise all animations with InterpolatorControllers set to start time
    var initAnimations = function initAnimationsFn(scene: CustomScene)
    {
        var a, n, anim, interp, tempNode, skinnedNode, node, hierarchy;
        var nodeHasSkeleton = animationManager.nodeHasSkeleton;
        var sceneNodes = scene.rootNodes;
        var numNodes = sceneNodes.length;
        scene.skinnedNodes = [];

        // For each node find which ones have skeletons
        for (n = 0; n < numNodes; n += 1)
        {
            node = sceneNodes[n];
            var skeleton = nodeHasSkeleton(node);
            if (skeleton && skeleton.numNodes)
            {
                skinnedNode = SkinnedNode.create(graphicsDevice, mathDevice,
                                                 node, skeleton);
                scene.skinnedNodes.push(skinnedNode);
            }
        }

        numNodes = scene.skinnedNodes.length;

        // For each animation, create an interpolation controller
        var animations = animationManager.getAll();
        for (a in animations)
        {
            if (animations.hasOwnProperty(a))
            {
                anim = animations[a];
                hierarchy = anim.hierarchy;

                // Create an interpolator controller for each animation
                interp = InterpolatorController.create(hierarchy);
                interp.setAnimation(anim, settings.loopAnimation);
                interp.setTime(0);
                interp.setRate(settings.defaultRate);

                skinnedNode = null;
                if (numNodes !== 0)
                {
                    for (n = 0; n < numNodes; n += 1)
                    {
                        tempNode = scene.skinnedNodes[n];
                        if (tempNode && (anim.numNodes === tempNode.skinController.skeleton.numNodes))
                        {
                            skinnedNode = tempNode;
                        }
                    }
                }

                // Controller map used for every interp controller
                controllerMap.push({
                    interpController : interp,
                    animation : anim,
                    nodeCount : hierarchy.numNodes,
                    skinnedNode : skinnedNode,
                    color : getControllerColor()
                });

            }
        }

        var index = (controllerMap.length - 1);
        if (index === -1)
        {
            // Couldn't find any animations on the scene
            return false;
        }

        var controllers = controllerMap[defaultAnimIndex];
        if (!controllers)
        {
            // Pick the last added as a default
            controllers = controllerMap[index];
        }
        else
        {
            index = defaultAnimIndex;
        }

        var defaultInterp = controllers.interpController;
        currentReferenceController = ReferenceController.create(defaultInterp);
        hierarchy = currentReferenceController.getHierarchy();

        // Assumes hierarchy is the same for all anims
        // If different hierarchies are used, create a new controller
        currentNodeController = NodeTransformController.create(hierarchy, scene);
        currentNodeController.setInputController(currentReferenceController);
        currentNodeController.active = true;

        // Set the initial animation
        nextAnimation(index);

        return true;
    };

    // Callback to draw extra debug information
    function drawDebugCB()
    {
        // Draws the interpolators for debugging
        if (currentNodeController.active)
        {
            if (settings.drawInterpolators)
            {
                var interp = currentNodeController.inputController;
                var hierarchy = interp.getHierarchy();
                scene.drawAnimationHierarchy(graphicsDevice, shaderManager, camera,
                                             hierarchy,
                                             hierarchy.numNodes,
                                             interp,
                                             null,
                                             interpolatorColor,
                                             boundsColor);
            }
        }
    }

    // Initialize the previous frame time
    var previousFrameTime = TurbulenzEngine.time;

    var renderFrame = function renderFrameFn()
    {
        var skinnedNodes, numSkins, skinnedNode, skin;

        var currentTime = TurbulenzEngine.time;
        var deltaTime = (currentTime - previousFrameTime);
        if (deltaTime > 0.1)
        {
            deltaTime = 0.1;
        }
        cameraController.maxSpeed = (maxSpeed * deltaTime);

        // Update input
        inputDevice.update();

        cameraController.update();

        var deviceWidth = graphicsDevice.width;
        var deviceHeight = graphicsDevice.height;
        var aspectRatio = (deviceWidth / deviceHeight);
        if (aspectRatio !== camera.aspectRatio)
        {
            camera.aspectRatio = aspectRatio;
            camera.updateProjectionMatrix();
        }
        camera.updateViewProjectionMatrix();

        // Update the current animation by using the node controller
        // The node controller input is the referenceNodeController
        currentNodeController.addTime(deltaTime * settings.animScale);

        skinnedNodes = scene.skinnedNodes;
        numSkins = skinnedNodes.length;

        // Create an array to insert the list of update nodes
        for (skin = 0; skin < numSkins; skin += 1)
        {
            skinnedNode = skinnedNodes[skin];
            if (skinnedNode.active)
            {
                // The skinned node will peform the update
                skinnedNode.update();
            }
        }

        scene.update();

        renderer.update(graphicsDevice, camera, scene, currentTime);

        if (graphicsDevice.beginFrame())
        {
            // Only draw the skin if active
            if (skinnedNode.active)
            {
                renderer.setWireframe(settings.drawWireframe);

                if (renderer.updateBuffers(graphicsDevice, deviceWidth, deviceHeight))
                {
                    renderer.draw(graphicsDevice, clearColor, null, null, drawDebugCB);
                }
            }

            graphicsDevice.endFrame();
        }

        previousFrameTime = currentTime;
    };

    var intervalID;
    var loadingLoop = function loadingLoopFn()
    {
        if (sceneLoader.complete() && animationsLoaded === 0)
        {
            TurbulenzEngine.clearInterval(intervalID);

            // Init the animations from the scene
            initAnimations(scene);

            // Intial reset of the camera
            resetCamera(camera, scene);

            // Scene loading is complete, now update the loaded shaders
            renderer.updateShader(shaderManager);

            intervalID = TurbulenzEngine.setInterval(renderFrame, 1000 / 60);
        }
    };
    intervalID = TurbulenzEngine.setInterval(loadingLoop, 1000 / 10);

    // Create a scene destroy callback to run when the window is closed
    TurbulenzEngine.onunload = function destroyScene()
    {
        TurbulenzEngine.clearInterval(intervalID);

        if (gameSession)
        {
            gameSession.destroy();
            gameSession = null;
        }

        if (scene)
        {
            scene.destroy();
            scene = null;
        }

        requestHandler = null;
        sceneLoader = null;

        htmlControls = null;

        transitionController = null;
        transitionStartColor = [];
        transitionEndColor = [];

        currentReferenceController = null;
        currentNodeController = null;

        if (renderer)
        {
            renderer.destroy();
            renderer = null;
        }

        addAnimations = [];
        removeAnimations = [];

        settings = null;

        cameraController = null;
        camera = null;
        cameraDir = [];

        mappingTable = null;

        animMinExtent = [];
        animMaxExtent = [];

        boundsColor = [];
        interpolatorColor = [];

        clearColor = [];
        worldUp = null;

        if (textureManager)
        {
            textureManager.destroy();
            textureManager = null;
        }

        if (shaderManager)
        {
            shaderManager.destroy();
            shaderManager = null;
        }

        effectManager = null;

        TurbulenzEngine.flush();
        graphicsDevice = null;
        mathDevice = null;
        inputDevice = null;
    };

};


text:
/*
This example aims to demonstrate the usage of lambdas.

[=] ( ) mutable throw() -> int { return 42; }
--- --- ------- ------- ------ --------------
 1   2     3       4       5         6

1. lambda-introducer (Also known as the capture clause)
2. lambda declarator (Also known as the parameter list). Optional!
3. mutable (Also known as the mutable specification). Optional!
4. exception-specification (Also known as the exception specification). Optional!
5. trailing-return-type (Also known as the return type). Optional!
6. compound-statement (Also known as the lambda body)
*/
#include <iostream>
#include <string>
#include <cstdint>
#include <cassert>
#include <functional>

void CaptureNothing()
{
	int x = 0;

	[]
	{
		//Will this work?
		//int y = x;
	}();
}

void CaptureAll()
{
	int x = 42;

	std::cout << "Capture all by value:\n";
	//by default, variables captured by value are non-modifiable, so the mutable specification is required
	[=] () mutable
	{
		x = 3;
	}();

	std::cout << x << '\n';

	std::cout << "Capture all by reference:\n";
	[&]
	{
		x = 3;
	}();

	std::cout << "x: " << x << '\n';
}

void SelectiveCaptureMixed()
{
	int x = 1;
	int y = 2;
	int z = 3;

	std::cout << "Capture x by value and y by reference:\n";
	[x, &y] () mutable
	{
		y = x;
		x = 42;
		//Will this work?
		//z = 42;
	}();

	std::cout << "x: " << x << '\n';
	std::cout << "y: " << y << '\n';
}

void AutomaticReturnTypeDeduction()
{
	auto value = []{ return 42; }();

	std::cout << "Deduced type is " << typeid(value).name() << '\n';
}

void RecursiveLambda()
{
	/*
	- the auto keyword infers its type from whatever it's initialized with, but, in this case,
		the expression that we are using to initialize it with depends on the type, so we need to break this circular dependency by specifying the type explicitly
	- note that we capture the functor object in the lambda-introducer by reference
	*/
	std::function<uint64_t(uint64_t)> fibonacci = [&fibonacci](uint64_t n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); };

	assert(fibonacci(1) == 1);
	assert(fibonacci(2) == 1);
	assert(fibonacci(3) == 2);
	assert(fibonacci(4) == 3);
	assert(fibonacci(5) == 5);
}

int main()
{
	CaptureNothing();
	CaptureAll();
	SelectiveCaptureMixed();
	AutomaticReturnTypeDeduction();

	RecursiveLambda();

	return 0;
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>用户特权</title>
	<meta name=viewport content="width=device-width, initial-scale=1,maximum-scale=1">
	<link rel="stylesheet" href="css/font-awesome.min.css">
	<link rel="stylesheet" href="css/reset.css">
	<link rel="stylesheet" href="css/component.css">
	<link rel="stylesheet" href="css/utils.css">
</head>
<body style="background: #0f0f0f">
	<img style="margin-top:5%" src="images/userservice/anywhere@3x.png">
</body>
</html>


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <assert.h>
#include <math.h>
#include <string.h>

#include "intl.h"
#include "object.h"
#include "element.h"
#include "diarenderer.h"
#include "attributes.h"
#include "text.h"
#include "properties.h"

#include "pixmaps/state_term.xpm"

#define NUM_CONNECTIONS 9

typedef struct _State State;
struct _State {
  Element element;

  ConnectionPoint connections[NUM_CONNECTIONS];

  int is_final;

  Color line_color;
  Color fill_color;
};

#define STATE_WIDTH  4
#define STATE_HEIGHT 3
#define STATE_RATIO 1
#define STATE_ENDRATIO 1.5
#define STATE_LINEWIDTH 0.1
#define STATE_MARGIN_X 0.5
#define STATE_MARGIN_Y 0.5

static real state_distance_from(State *state, Point *point);
static void state_select(State *state, Point *clicked_point,
			DiaRenderer *interactive_renderer);
static ObjectChange* state_move_handle(State *state, Handle *handle,
				       Point *to, ConnectionPoint *cp,
				       HandleMoveReason reason, ModifierKeys modifiers);
static ObjectChange* state_move(State *state, Point *to);
static void state_draw(State *state, DiaRenderer *renderer);
static DiaObject *state_create(Point *startpoint,
			   void *user_data,
			   Handle **handle1,
			   Handle **handle2);
static void state_destroy(State *state);
static DiaObject *state_load(ObjectNode obj_node, int version,
			    const char *filename);
static PropDescription *state_describe_props(State *state);
static void state_get_props(State *state, GPtrArray *props);
static void state_set_props(State *state, GPtrArray *props);
static void state_update_data(State *state);

void
draw_rounded_rectangle(DiaRenderer *renderer, Point p1, Point p2, real radio);

static ObjectTypeOps state_type_ops =
{
  (CreateFunc) state_create,
  (LoadFunc)   state_load,/*using_properties*/     /* load */
  (SaveFunc)   object_save_using_properties,      /* save */
  (GetDefaultsFunc)   NULL,
  (ApplyDefaultsFunc) NULL
};

DiaObjectType state_term_type =
{
  "UML - State Term",   /* name */
  0,                      /* version */
  (char **) state_term_xpm,  /* pixmap */

  &state_type_ops       /* ops */
};

static ObjectOps state_ops = {
  (DestroyFunc)         state_destroy,
  (DrawFunc)            state_draw,
  (DistanceFunc)        state_distance_from,
  (SelectFunc)          state_select,
  (CopyFunc)            object_copy_using_properties,
  (MoveFunc)            state_move,
  (MoveHandleFunc)      state_move_handle,
  (GetPropertiesFunc)   object_create_props_dialog,
  (ApplyPropertiesDialogFunc) object_apply_props_from_dialog,
  (ObjectMenuFunc)      NULL,
  (DescribePropsFunc)   state_describe_props,
  (GetPropsFunc)        state_get_props,
  (SetPropsFunc)        state_set_props,
  (TextEditFunc) 0,
  (ApplyPropertiesListFunc) object_apply_props,
};

static PropDescription state_props[] = {
  ELEMENT_COMMON_PROPERTIES,
  PROP_STD_LINE_COLOUR_OPTIONAL,
  PROP_STD_FILL_COLOUR_OPTIONAL,
  { "is_final", PROP_TYPE_BOOL, PROP_FLAG_VISIBLE,
  N_("Is final"), NULL, NULL },
  PROP_DESC_END
};

static PropDescription *
state_describe_props(State *state)
{
  if (state_props[0].quark == 0) {
    prop_desc_list_calculate_quarks(state_props);
  }
  return state_props;
}

static PropOffset state_offsets[] = {
  ELEMENT_COMMON_PROPERTIES_OFFSETS,
  { "line_colour",PROP_TYPE_COLOUR,offsetof(State, line_color) },
  { "fill_colour",PROP_TYPE_COLOUR,offsetof(State, fill_color) },
  { "is_final", PROP_TYPE_BOOL, offsetof(State, is_final) },

  { NULL, 0, 0 },
};

static void
state_get_props(State * state, GPtrArray *props)
{
  object_get_props_from_offsets(&state->element.object,
                                state_offsets,props);
}

static void
state_set_props(State *state, GPtrArray *props)
{
  object_set_props_from_offsets(&state->element.object,
                                state_offsets,props);
  state_update_data(state);
}

static real
state_distance_from(State *state, Point *point)
{
  DiaObject *obj = &state->element.object;
  return distance_rectangle_point(&obj->bounding_box, point);
}

static void
state_select(State *state, Point *clicked_point,
	       DiaRenderer *interactive_renderer)
{
  element_update_handles(&state->element);
}

static ObjectChange*
state_move_handle(State *state, Handle *handle,
		  Point *to, ConnectionPoint *cp,
		  HandleMoveReason reason, ModifierKeys modifiers)
{
  assert(state!=NULL);
  assert(handle!=NULL);
  assert(to!=NULL);

  assert(handle->id < 8);

  return NULL;
}

static ObjectChange*
state_move(State *state, Point *to)
{
  state->element.corner = *to;
  state_update_data(state);

  return NULL;
}

static void
state_draw(State *state, DiaRenderer *renderer)
{
  DiaRendererClass *renderer_ops = DIA_RENDERER_GET_CLASS (renderer);
  Element *elem;
  real x, y, w, h, r;
  Point p1;

  assert(state != NULL);
  assert(renderer != NULL);

  elem = &state->element;

  x = elem->corner.x;
  y = elem->corner.y;
  w = elem->width;
  h = elem->height;

  renderer_ops->set_fillstyle(renderer, FILLSTYLE_SOLID);
  renderer_ops->set_linewidth(renderer, STATE_LINEWIDTH);
  renderer_ops->set_linestyle(renderer, LINESTYLE_SOLID);

   p1.x = x + w/2;
   p1.y = y + h/2;
   if (state->is_final==1) {
      r = STATE_ENDRATIO;
      renderer_ops->fill_ellipse(renderer,
				  &p1,
				  r, r,
				  &state->fill_color);

      renderer_ops->draw_ellipse(renderer,
				  &p1,
				  r, r,
				  &state->line_color);
   }
   r = STATE_RATIO;
   renderer_ops->fill_ellipse(renderer,
			       &p1,
			       r, r,
			       &state->line_color); /* line_color not a typo! */
}

static void
state_update_data(State *state)
{
  real w, h;

  Element *elem = &state->element;
  ElementBBExtras *extra = &elem->extra_spacing;
  DiaObject *obj = &elem->object;

  w = h = (state->is_final) ? STATE_ENDRATIO: STATE_RATIO;

  elem->width = w;
  elem->height = h;
  extra->border_trans = STATE_LINEWIDTH / 2.0;

 /* Update connections: */
  element_update_connections_rectangle(elem, state->connections);

  element_update_boundingbox(elem);

  obj->position = elem->corner;

  element_update_handles(elem);
}

static DiaObject *
state_create(Point *startpoint,
	       void *user_data,
  	       Handle **handle1,
	       Handle **handle2)
{
  State *state;
  Element *elem;
  DiaObject *obj;
  Point p;
  int i;

  state = g_malloc0(sizeof(State));
  elem = &state->element;
  obj = &elem->object;

  obj->type = &state_term_type;
  obj->ops = &state_ops;
  elem->corner = *startpoint;
  elem->width = STATE_WIDTH;
  elem->height = STATE_HEIGHT;

  p = *startpoint;
  p.x += STATE_WIDTH/2.0;
  p.y += STATE_HEIGHT/2.0;

  state->line_color = attributes_get_foreground();
  state->fill_color = attributes_get_background();
  state->is_final = 0;
  element_init(elem, 8, NUM_CONNECTIONS);

  for (i=0;i<NUM_CONNECTIONS;i++) {
    obj->connections[i] = &state->connections[i];
    state->connections[i].object = obj;
    state->connections[i].connected = NULL;
  }
  state->connections[8].flags = CP_FLAGS_MAIN;
  elem->extra_spacing.border_trans = 0.0;
  state_update_data(state);

  for (i=0;i<8;i++) {
    obj->handles[i]->type = HANDLE_NON_MOVABLE;
  }

  *handle1 = NULL;
  *handle2 = NULL;
  return &state->element.object;
}

static void
state_destroy(State *state)
{
  element_destroy(&state->element);
}

static DiaObject *
state_load(ObjectNode obj_node, int version, const char *filename)
{
  return object_load_using_properties(&state_term_type,
                                      obj_node,version,filename);
}