text:
package me.chanjar;

import static org.junit.Assert.*;

import java.util.List;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.ActivitiRule;
import org.activiti.engine.test.Deployment;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:springTypicalUsageTest-context.xml")
public class EventSubprocessTest {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    @Rule
    public ActivitiRule activitiSpringRule;

    @Test
    @Deployment(resources = "me/chanjar/eventsubprocess/event-subprocess.bpmn")
    public void messageStartEvent() {
      String processDefinitionKey = "event-subprocess";
      runtimeService.startProcessInstanceByKey(processDefinitionKey);

      // usertask1 is not null
      Task task1 = taskService.createTaskQuery().processDefinitionKey(processDefinitionKey).taskDefinitionKey("usertask1").singleResult();
      assertNotNull(task1);

      // send a message and trigger event sub-process
      sendMessage(processDefinitionKey);

      // complete usertask3 in event sub-process
      Task task3 = taskService.createTaskQuery().processDefinitionKey(processDefinitionKey).taskDefinitionKey("usertask3").singleResult();
      taskService.complete(task3.getId());

      // trying to get usertask1 again
      task1 = taskService.createTaskQuery().processDefinitionKey(processDefinitionKey).taskDefinitionKey("usertask1").singleResult();
      // but usertask1 disappeared
      taskService.complete(task1.getId());

      // 判断process instance已经结束
      assertEquals(0, runtimeService.createProcessInstanceQuery().processDefinitionKey(processDefinitionKey).count());
    }

    private void sendMessage(String processDefinitionKey) {
      List<Execution> executions = runtimeService
          .createExecutionQuery()
          .processDefinitionKey(processDefinitionKey)
          .messageEventSubscriptionName("abc")
          .list();
      for(Execution execution : executions) {
        runtimeService.messageEventReceived("abc", execution.getId());
      }

    }

}


text:
% SCALE_TREE   Scales a tree.
% (trees package)
%
% tree = scale_tree (intree, fac, options)
% ----------------------------------------
%
% scales the entire tree by factor fac. If fac 3-tupel scaling factor can
% be different for X, Y and Z.
%
% Input
% -----
% - intree::integer:index of tree in trees or structured tree
% - fac::scalar or 3-tupel: multiplication factor {DEFAULT: 2x}
%     if scalar, diameter is also scaled
% - options::string: {DEFAULT: ''}
%     '-s' : show before and after
%     '-d' : do not scale diameter
%
% Output
% ------
% if no output is declared the tree is changed in trees
% - tree:: structured output tree
%
% Example
% -------
% scale_tree (sample_tree, 1.2, '-s')
%
% See also tran_tree rot_tree flip_tree
% Uses ver_tree X Y Z
%
% the TREES toolbox: edit, visualize and analyze neuronal trees
% Copyright (C) 2009  Hermann Cuntz

function varargout = scale_tree (intree, fac, options)

% trees : contains the tree structures in the trees package
global trees

if (nargin < 1)||isempty(intree),
    intree = length(trees); % {DEFAULT tree: last tree in trees cell array}
end;

ver_tree (intree); % verify that input is a tree structure

% use full tree for this function
if ~isstruct (intree),
    tree = trees {intree};
else
    tree = intree;
end

if (nargin < 2)||isempty(fac),
    fac = 2; % {DEFAULT: no option}
end

if (nargin < 3)||isempty(options),
    options = ''; % {DEFAULT: no option}
end

% ORI = [tree.X(1) tree.Y(1) tree.Z(1)];
% tree.X = tree.X - ORI (1);
% tree.Y = tree.Y - ORI (2);
% tree.Z = tree.Z - ORI (3);

% scaling:
if numel(fac)>1,
    tree.X = tree.X * fac (1);
    tree.Y = tree.Y * fac (2);
    tree.Z = tree.Z * fac (3);
else
    tree.X = tree.X * fac;
    tree.Y = tree.Y * fac;
    tree.Z = tree.Z * fac;
    if isempty (strfind (options, '-d')),
        tree.D = tree.D * fac;
    end
end

% tree.X = tree.X + ORI (1);
% tree.Y = tree.Y + ORI (2);
% tree.Z = tree.Z + ORI (3);

if strfind (options, '-s') % show option
    clf; shine; hold on; HP = plot_tree (intree); set (HP,'facealpha', .5);
    HP = plot_tree (tree, [1 0 0]); set (HP, 'facealpha', .5);
    HP (1) = plot (1, 1, 'k-'); HP (2) = plot (1, 1, 'r-');
    legend (HP, {'before', 'after'}); set (HP, 'visible', 'off');
    title  ('scale a tree');
    xlabel ('x [\mum]'); ylabel ('y [\mum]'); zlabel ('z [\mum]');
    view (2); grid on; axis image;
end

if (nargout == 1)||(isstruct(intree)),
    varargout {1}  = tree; % if output is defined then it becomes the tree
else
    trees {intree} = tree; % otherwise add to end of trees cell array
end

redpajama_set_name: RedPajamaGithub


text:
Basic Use Case

<mat-drawer-container class="demo-drawer-container">
  <mat-drawer #start (opened)="myinput.focus()" mode="side">
    Start Side Drawer

    <button mat-button (click)="start.close()">Close</button>

    <button mat-button (click)="end.open()">Open End Side</button>

    <button mat-button
            (click)="start.mode = (start.mode === 'push' ? 'over' : (start.mode === 'over' ? 'side' : 'push'))">Toggle Mode</button>

Mode: {{start.mode}}

    <input #myinput>
  </mat-drawer>

  <mat-drawer #end position="end">
    End Side Drawer

    <button mat-button (click)="end.close()">Close</button>
  </mat-drawer>

My Content

      Drawer
      <button mat-button (click)="start.toggle()">Toggle Start Side Drawer</button>
      <button mat-button (click)="end.toggle()">Toggle End Side Drawer</button>

    <button mat-button>HELLO</button>
    <button mat-raised-button class="mat-primary">HELLO</button>
    <button mat-fab class="mat-accent">HI</button>

</mat-drawer-container>

Drawer Already Opened

<mat-drawer-container class="demo-drawer-container">
  <mat-drawer #start2 opened mode="side">
    Drawer
  </mat-drawer>

    <button mat-button (click)="start2.toggle()">Toggle Start Side Drawer</button>

</mat-drawer-container>

Dynamic Position Drawer

<mat-drawer-container class="demo-drawer-container">
  <mat-drawer #dynamicPosDrawer1 mode="side" [position]="invert ? 'end' : 'start'">Start</mat-drawer>
  <mat-drawer #dynamicPosDrawer2 mode="side" [position]="invert ? 'start' : 'end'">End</mat-drawer>

    <button (click)="dynamicPosDrawer1.toggle(); dynamicPosDrawer2.toggle()">
      Toggle drawers
    </button>
    <button (click)="invert = !invert">Change sides</button>

</mat-drawer-container>

Drawer with focus attributes

<mat-drawer-container class="demo-drawer-container">
  <mat-drawer #focusDrawer>
    <mat-nav-list>
      Link
      Focus region start
      Link
      Initially focused
      Focus region end
      Link
    </mat-nav-list>
  </mat-drawer>

My Content

      Drawer
      <button mat-button (click)="focusDrawer.toggle()">Toggle Drawer</button>

</mat-drawer-container>


text:
from metrics import startup_metric
from telemetry.page import page_measurement

class Startup(page_measurement.PageMeasurement):
  """Performs a measurement of Chromium's startup performance.

  This test must be invoked with either --warm or --cold on the command line. A
  cold start means none of the Chromium files are in the disk cache. A warm
  start assumes the OS has already cached much of Chromium's content. For warm
  tests, you should repeat the page set to ensure it's cached.
  """

  def __init__(self, action_name_to_run = ''):
    super(Startup, self).__init__(needs_browser_restart_after_each_run=True,
                                  action_name_to_run=action_name_to_run)

  def AddCommandLineOptions(self, parser):
    parser.add_option('--cold', action='store_true',
                      help='Clear the OS disk cache before performing the test')
    parser.add_option('--warm', action='store_true',
                      help='Start up with everything already cached')

  def CustomizeBrowserOptions(self, options):
    # TODO: Once the bots start running benchmarks, enforce that either --warm
    # or --cold is explicitly specified.
    # assert options.warm != options.cold, \
    #     "You must specify either --warm or --cold"
    if options.cold:
      browser_options = options.browser_options
      browser_options.clear_sytem_cache_for_browser_and_profile_on_start = True
    else:
      self.discard_first_result = True

    options.AppendExtraBrowserArgs([
        '--enable-stats-collection-bindings'
    ])

  def RunNavigateSteps(self, page, tab):
    # Overriden so that no page navigation occurs - startup to the NTP.
    pass

  def MeasurePage(self, page, tab, results):
    startup_metric.StartupMetric().AddResults(tab, results)

class StartWithUrl(Startup):
  """Performs a measurement of Chromium's performance starting with a URL.

  This test must be invoked with either --warm or --cold on the command line. A
  cold start means none of the Chromium files are in the disk cache. A warm
  start assumes the OS has already cached much of Chromium's content. For warm
  tests, you should repeat the page set to ensure it's cached.

  The startup URL is taken from the page set's set_startup_url action. This
  allows the testing of multiple different URLs in a single benchmark.
  """

  def __init__(self):
    super(StartWithUrl, self).__init__(action_name_to_run='navigate_steps')


text:
from itertools import chain
import sys, re

def _match_from(line):
    return re.match(r'^\s*from (?P<module>.+)(?P<the_rest>\s+import .*)$', line)

def _has_unclosed_parens(line):
    """
    Assumes there's no more than one pair of parens (or just one "("), which is reasonable for
    import lines.
    """
    if '(' in line:
        _, rest = line.split('(')
        return ')' not in rest
    return False

def sort_imports(lines):
    """
    `lines` is an iterable containing a line per element.
    """
    # Join multiline imports into single elements in the list.
    line_it = iter(lines)
    _lines = []
    while True:
        try:
            line = line_it.next()
        except StopIteration:
            break
        if _has_unclosed_parens(line):
            while True:
                try:
                    next_line = line_it.next()
                    line += next_line
                    if ')' in next_line:
                        break
                except StopIteration:
                    break
        _lines.append(line)
    lines = _lines

    # Partition into chunks to sort individually, divided by blank lines.
    chunks, chunk = [], []
    for line in lines:
        if not line.strip():
            chunks.extend([chunk, [line]])
            chunk = []
        else:
            chunk.append(line)
    chunks.append(chunk)

    def key(line):
        # Ignores parens when sorting.
        line = line.strip().replace('(', '').replace(')', '')
        m = _match_from(line)
        if m:
            return 'import {0} from {1}'.format(m.group('module'), m.group('the_rest'))
        return line

    return list(chain.from_iterable(map(lambda lines: sorted(lines, key=key), chunks)))

if __name__ == '__main__':
    lines = sys.stdin
    for line in sort_imports(lines):
        print line,

# Use `nosetests sort_imports.py` to run tests.
def test_sort_imports():
    lines = ([
        'import b\n', 'import a\n', 'from a import foo\n', 'from a import bar, baz\n', 'import a, b\n',
        '\n',
        'import two\n', 'import one\n',
        '\n',
        'import 3\n', 'import (2,\n', '        1\n', '        0)\n', 'import 1\n',
    ])
    sorted_lines = sort_imports(lines)
    print 'Sorted:'
    print [e for e in sorted_lines]
    assert sorted_lines == ([
        'import a\n', 'from a import bar, baz\n', 'from a import foo\n', 'import a, b\n', 'import b\n',
        '\n',
        'import one\n', 'import two\n',
        '\n',
        'import 1\n', 'import (2,\n        1\n        0)\n', 'import 3\n',
    ])


text:
template <class _T>
class array_ref
{
    _T* data;
    size_t n;
    inline void check_index(size_t i) const
    {
        i;
        assert(i < n);
    }
    inline void check_ptr() const
    {
        n;
        data;
        assert(n == 0 || data != NULL);
    }

public:
    inline array_ref(_T* ptr, size_t size) throw()
        : data(ptr), n(size)
    {
    }
    inline array_ref() throw()
        : data(NULL), n(0)
    {
    } // in case we have a vector of this
    inline _T& operator[](size_t i) throw()
    {
        check_index(i);
        return data[i];
    }
    inline const _T& operator[](size_t i) const throw()
    {
        check_index(i);
        return data[i];
    }
    inline size_t size() const throw()
    {
        return n;
    }
    inline _T* begin()
    {
        return data;
    }
    inline _T* end()
    {
        return data + n;
    }
    inline void resize(size_t sz)
    {
        sz;
        assert(n == sz);
    } // allow compatibility with some functions
    // construct from other vector types
    template <class _V>
    inline array_ref(_V& v)
        : data(v.size() > 0 ? &v[0] : NULL), n((size_t) v.size())
    {
    }
};

// ---------------------------------------------------------------------------
// const_array_ref -- same as array_ref for 'const' (read-only) pointers
// ---------------------------------------------------------------------------

template <class _T>
class const_array_ref
{
    const _T* data;
    size_t n;
    inline void check_index(size_t i) const
    {
        i;
        assert(i < n);
    }
    inline void check_ptr() const
    {
        n;
        data;
        assert(n == 0 || data != NULL);
    }

public:
    inline const_array_ref(const _T* ptr, size_t size) throw()
        : data(ptr), n(size)
    {
    }
    inline const_array_ref() throw()
        : data(NULL), n(0)
    {
    } // in case we have a vector of this
    inline const _T& operator[](size_t i) const throw()
    {
        check_index(i);
        return data[i];
    }
    inline size_t size() const throw()
    {
        return n;
    }
    inline const _T* begin()
    {
        return data;
    }
    inline const _T* end()
    {
        return data + n;
    }
    inline const _T& front() const throw()
    {
        check_index(0);
        return data[0];
    }
    inline const _T& back() const throw()
    {
        check_index(0);
        return data[n - 1];
    }
    // construct from other vector types
    template <class _V>
    inline const_array_ref(const _V& v)
        : data(v.size() > 0 ? &v[0] : NULL), n((size_t) v.size())
    {
    }
};

// ---------------------------------------------------------------------------
// hardcoded_array -- wraps a fixed-size C array together with its size.
//
// operator[] checks index bounds in Debug builds. size() is provided such
// that this class can be substituted for STL vector in many cases.
// Can be constructed with a size parameter--it will be checked against the
// hard-coded size.
// Can also be constructed with an initialization parameter (typ. 0).
// ---------------------------------------------------------------------------

template <class _T, int _N>
class hardcoded_array
{
    _T data[_N];
    inline void check_index(size_t i) const
    {
        i;
        assert(i < _N);
    }
    inline void check_size(size_t n) const
    {
        n;
        assert(n == _N);
    }

public:
    inline hardcoded_array() throw()
    {
    }
    inline hardcoded_array(size_t n) throw()
    {
        check_size(n);
    } // we can instantiate with a size parameter--just checks the size
    inline hardcoded_array(size_t n, const _T& val) throw()
    {
        check_size(n);
        for (size_t i = 0; i < n; i++)
            data[i] = val;
    }
    inline _T& operator[](size_t i) throw()
    {
        check_index(i);
        return data[i];
    }
    inline const _T& operator[](size_t i) const throw()
    {
        check_index(i);
        return data[i];
    }
    inline size_t size() const throw()
    {
        return _N;
    }
};


text:
import { Component, Input, Output, EventEmitter } from '@angular/core'
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MdDialog, MdDialogRef } from '@angular/material';
import { MessageService } from 'goatstone/octogoat/services/message.service'

@Component({
  selector: 'ocotogoat-mailto',
  template: `
<form
  [formGroup]="todoForm"
  (ngSubmit)="sendData(todoForm.value)"
  >
  <md-card>
      <md-card-title>Send Email to Octogoat</md-card-title>
      <md-card-content>
        <md-input-container md-error>

            * Name
            <input formControlName="name" mdInput autofocus maxlength="50">

        </md-input-container>
        <md-input-container md-error>

            * Email
            <input formControlName="email" mdInput autofocus maxlength="50">

        </md-input-container>
        <md-input-container md-error>

            * Subject
            <input formControlName="subject" mdInput autofocus maxlength="50">

        </md-input-container>
        <md-input-container>
          Message
            <textarea formControlName="message" mdInput maxlength="200">
            </textarea>

        </md-input-container>

        <button [disabled]="!todoForm.valid" type="submit" md-fab>
          <md-icon>send</md-icon>
        </button>

      </md-card-content>
  </md-card>
</form>
`,
  styleUrls: [ './mail-to.css' ]
})

export class MailToComponent {
  // @Output() emitDataEvent: EventEmitter<any> = new EventEmitter()
  public todoForm = this.fb.group({
    name: ['', Validators.required],
    email: ['', Validators.required],
    subject: ['', Validators.required],
    message: ['']
  })

  constructor (
    private fb: FormBuilder,
    public dialogRef: MdDialogRef<MailToComponent>,
    private messageService: MessageService
    ) {
  }
  private msg (data: any){
    let o = this.messageService.send(data)
    o.subscribe(x => {
    })
  }
  private sendData (data: any) {
      if (data) {
          this.msg(data)
      }
      // this.emitDataEvent.emit(data)
      this.dialogRef.close()
  }
}


text:
package com.nasser.poulet.conquest.menu;

import org.newdawn.slick.Color;
import org.newdawn.slick.TrueTypeFont;

import java.awt.*;

/**
 * Created by Thomas on 12/29/13.
 */
public class Label extends UIElement{

    public void render(){
        font.getFont().drawString(posX, posY, text, Color.white);
    }

    @Override
    public String click(int posX, int posY) {
        return null;
    }

    @Override
    public String hover(int posX, int posY) {
        return null;
    }

    @Override
    public String getAction() {
        return null;
    }
}


text:
package org.aries.common.map;

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

import javax.ejb.Local;
import javax.ejb.Stateless;

import org.aries.common.Property;
import org.aries.common.entity.PropertyEntity;
import org.aries.data.map.AbstractMapper;

@Stateless
@Local(PropertyMapper.class)
public class PropertyMapper extends AbstractMapper<Property, PropertyEntity> {

	public PropertyMapper() {
		setModelClass(Property.class);
		setEntityClass(PropertyEntity.class);
	}

	public Property toModel(PropertyEntity propertyEntity) {
		if (propertyEntity == null)
			return null;
		Property propertyModel = createModel();
		propertyModel.setId(propertyEntity.getId());
		propertyModel.setName(propertyEntity.getName());
		propertyModel.setValue(propertyEntity.getValue());
		return propertyModel;
	}

	public List<Property> toModelList(Collection<PropertyEntity> propertyEntityList) {
		if (propertyEntityList == null)
			return null;
		List<Property> propertyModelList = new ArrayList<Property>();
		for (PropertyEntity propertyEntity : propertyEntityList) {
			Property propertyModel = toModel(propertyEntity);
			propertyModelList.add(propertyModel);
		}
		return propertyModelList;
	}

	public PropertyEntity toEntity(Property propertyModel) {
		if (propertyModel == null)
			return null;
		PropertyEntity propertyEntity = createEntity();
		toEntity(propertyEntity, propertyModel);
		return propertyEntity;
	}

	public void toEntity(PropertyEntity propertyEntity, Property propertyModel) {
		if (propertyEntity != null && propertyModel != null) {
			propertyEntity.setId(propertyModel.getId());
			propertyEntity.setName(propertyModel.getName());
			propertyEntity.setValue(propertyModel.getValue());
		}
	}

	public List<PropertyEntity> toEntityList(Collection<Property> propertyModelList) {
		if (propertyModelList == null)
			return null;
		List<PropertyEntity> propertyEntityList = new ArrayList<PropertyEntity>();
		for (Property propertyModel : propertyModelList) {
			PropertyEntity propertyEntity = toEntity(propertyModel);
			propertyEntityList.add(propertyEntity);
		}
		return propertyEntityList;
	}

}


text:
'use strict';

// Nodejs lib.
var path = require('path');

var findup = require('../lib/findup-sync.js');

// Get a relative path.
var rel = function(abspath) {
  return typeof abspath === 'string' ? path.relative('.', abspath) : abspath;
};

exports['findup'] = {
  setUp: function(done) {
    // setup here
    done();
  },
  'simple': function(test) {
    test.expect(8);
    var opts = {cwd: 'test/fixtures/a/b'};
    test.equal(rel(findup('foo.txt', opts)), 'test/fixtures/a/foo.txt', 'should find files');
    test.equal(rel(findup('bar.txt', opts)), 'test/fixtures/a/b/bar.txt', 'should find files');
    test.equal(rel(findup('a.txt', opts)), 'test/fixtures/a.txt', 'should find files');
    test.equal(rel(findup('?.txt', opts)), 'test/fixtures/a.txt', 'should support glob patterns');
    test.equal(rel(findup('*.txt', opts)), 'test/fixtures/a/b/bar.txt', 'should find the first thing that matches the glob pattern');
    test.equal(rel(findup(['b*.txt', 'f*.txt'], opts)), 'test/fixtures/a/b/bar.txt', 'should find the first thing that matches any of the glob patterns');
    test.equal(rel(findup(['f*.txt', 'b*.txt'], opts)), 'test/fixtures/a/b/bar.txt', 'should find the first thing that matches any of the glob patterns');
    test.equal(findup('not-gonna-exist-i-hope.txt', opts), null, 'should returning null if no files found');
    test.done();
  },
};


text:
ALTER TABLE fields ADD sort_index INT(32) AFTER required;
ALTER TABLE field_options ADD sort_index INT(32) AFTER `option`;


text:
@class NSData, NSDictionary, NSString;

@interface CLSAnalyticsMetadataController : NSObject
{
    NSDictionary *_appInfoDictionary;
    NSDictionary *_metadata;
    NSData *_metadataJSONData;
    NSString *_instanceIdentifier;
}

+ (id)metadataDictionaryFromContext:(CDStruct_a6175b54)arg1 appInfoDictionary:(id)arg2 instanceIdentifier:(id)arg3;
+ (void)setValueInDictionary:(id)arg1 withKey:(id)arg2 toBOOL:(BOOL)arg3;
+ (void)setValueInDictionary:(id)arg1 withKey:(id)arg2 toCString:(const char *)arg3;
+ (void)setValueInDictionary:(id)arg1 withKey:(id)arg2 toInteger:(int)arg3;
+ (void)setValueInDictionary:(id)arg1 withKey:(id)arg2 toLong:(unsigned int)arg3;
+ (void)setValueInDictionary:(id)arg1 withKey:(id)arg2 toLongLong:(unsigned long long)arg3;
+ (void)setValueInDictionary:(id)arg1 withKey:(id)arg2 toObject:(id)arg3;
@property(readonly, copy, nonatomic) NSDictionary *appInfoDictionary; // @synthesize appInfoDictionary=_appInfoDictionary;
- (void)dealloc;
- (id)init;
- (id)initWithAppInfoDictionary:(id)arg1 instanceIdentifier:(id)arg2;
@property(readonly, copy, nonatomic) NSString *instanceIdentifier; // @synthesize instanceIdentifier=_instanceIdentifier;
@property(readonly, copy, nonatomic) NSDictionary *metadata; // @synthesize metadata=_metadata;
@property(readonly, copy, nonatomic) NSData *metadataJSONData; // @synthesize metadataJSONData=_metadataJSONData;

@end


text:
<?php

/**
 * Part of the trillium
 *
 * @package    Trillium
 * @license    MIT License
 * @link       http://github.com/Kilte/trillium
 */

namespace trillium {

    use trillium\exception\MySQLiException;

    defined('ROOT_DIR') or die('Restricted access');

    /**
     * MySQLi Class
     *
     * Represents a connection between PHP and a MySQL database.
     * It is a descendant of built-in mysqli class.
     *
     * @package trillium
     */
    class MySQLi extends \mysqli
    {

        /**
         * Run Query
         *
         * @param string $statement SQL statement
         * @param int    $type      Result Mode MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT
         *
         * @throws MySQLiException
         * @return \mysqli_result
         */
        public function query($statement, $type = MYSQLI_USE_RESULT) {
            $result = parent::query($statement, $type);
            if (!empty($this->error)) {
                throw new MySQLiException('Error: ' . $this->error . "\r\n\t" . 'Statement: ' . $statement, $this->errno);
            }
            return $result;
        }

    }

}

/* End of file MySQLi.php */


text:
> [Introduced](https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/23532) in GitLab 11.7.

Issues can be imported to a project by uploading a CSV file with the columns
`title` and `description`, in that order.

The user uploading the CSV file will be set as the author of the imported issues.

NOTE: **Note:** A permission level of [Developer](../../permissions.md), or higher, is required
to import issues.

## Prepare for the import

- Consider importing a test file containing only a few issues. There is no way to undo a large import without using the GitLab API.
- Ensure your CSV file meets the [file format](#csv-file-format) requirements.

## Import the file

To import issues:

1. Navigate to a project's Issues list page.
1. If existing issues are present, click the import icon at the top right, next to the **Edit issues** button.
1. For a project without any issues, click the button labeled **Import CSV** in the middle of the page.
1. Select the file and click the **Import issues** button.

The file is processed in the background and a notification email is sent
to you once the import is complete.

## CSV file format

When importing issues from a CSV file, it must be formatted in a certain way:

- **header row:** CSV files must contain a header row where the first column header
  is `title` and the second is `description`. If additional columns are present, they
  will be ignored.
- **separators:** The column separator is automatically detected from the header row.
  Supported separator characters are: commas (`,`), semicolons (`;`), and tabs (`\t`).
  The row separator can be either `CRLF` or `LF`.
- **double-quote character:** The double-quote (`"`) character is used to quote fields,
  enabling the use of the column separator within a field (see the third line in the
  sample CSV data below). To insert a double-quote (`"`) within a quoted
  field, use two double-quote characters in succession, i.e. `""`.
- **data rows:** After the header row, succeeding rows must follow the same column
  order. The issue title is required while the description is optional.

Sample CSV data:

```csv
title,description
My Issue Title,My Issue Description
Another Title,"A description, with a comma"
"One More Title","One More Description"
```

### File size

The limit depends on the configuration value of Max Attachment Size for the GitLab instance.

For GitLab.com, it is set to 10 MB.


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * If (Evaluate Statement).type is "break" and (Evaluate Statement).target is in the current label set, (normal, (Evaluate Statement), empty) is returned while evaluating a "var-loop"
 *
 * @path ch12/12.6/12.6.3/S12.6.3_A12.1_T1.js
 * @description Breaking a loop with "break"
 */

__str=""

for(var index=0; index<10; index+=1) {
	if (index>5)break;
	__str+=index;
}

if (__str!=="012345") {
	$ERROR('#1: __str === "012345". Actual:  __str ==='+ __str  );
}


text:
<?php
	namespace Bolt;

	use Bolt\Interfaces\Connection;
	use Bolt\Job\Colours;
	use Bolt\Job\Output;

	abstract class Job extends Base
	{
		protected ?Connection $connection;
		protected Metrics $metrics;

		public array $data = array();
		public ?string $receipt = null;

		public function __construct(Connection $connection = null)
		{
			$this->connection = $connection;
		}

		abstract public function execute(): void;

		public function run($data = null): Metrics
		{
			$this->metrics(new Metrics());
			$this->output("Started `" . $this->className(false) . "` job", Output::JOB);

			if (isset($data))
			{
				$this->data($data);
			}

			$this->execute();

			return $this->metrics();
		}

		public function output($message, $type = null): void
		{
			switch ($type)
			{
				case Output::SYSTEM:
					$colour = Colours::SYSTEM;
					break;
				case Output::JOB:
					$colour = Colours::JOB;
					break;
				case Output::ERROR:
					$colour = Colours::ERROR;
					break;
				default:
					$colour = Colours::DEFAULT;
					break;
			}

			echo(sprintf("- %s(%s) %s \033[0m \n", $colour, date("c"), $message));
		}
	}
?>


text:
require 'cases/helper'
require 'tempfile'

module ActiveRecord
  class FixtureSet
    class FileTest < ActiveRecord::TestCase
      def test_open
        fh = File.open(::File.join(FIXTURES_ROOT, "accounts.yml"))
        assert_equal 6, fh.to_a.length
      end

      def test_open_with_block
        called = false
        File.open(::File.join(FIXTURES_ROOT, "accounts.yml")) do |fh|
          called = true
          assert_equal 6, fh.to_a.length
        end
        assert called, 'block called'
      end

      def test_names
        File.open(::File.join(FIXTURES_ROOT, "accounts.yml")) do |fh|
          assert_equal ["signals37",
                        "unknown",
                        "rails_core_account",
                        "last_account",
                        "rails_core_account_2",
                        "odegy_account"].sort, fh.to_a.map(&:first).sort
        end
      end

      def test_values
        File.open(::File.join(FIXTURES_ROOT, "accounts.yml")) do |fh|
          assert_equal [1,2,3,4,5,6].sort, fh.to_a.map(&:last).map { |x|
            x['id']
          }.sort
        end
      end

      def test_erb_processing
        File.open(::File.join(FIXTURES_ROOT, "developers.yml")) do |fh|
          devs = Array.new(8) { |i| "dev_#{i + 3}" }
          assert_equal [], devs - fh.to_a.map(&:first)
        end
      end

      def test_empty_file
        tmp_yaml ['empty', 'yml'], '' do |t|
          assert_equal [], File.open(t.path) { |fh| fh.to_a }
        end
      end

      # A valid YAML file is not necessarily a value Fixture file. Make sure
      # an exception is raised if the format is not valid Fixture format.
      def test_wrong_fixture_format_string
        tmp_yaml ['empty', 'yml'], 'qwerty' do |t|
          assert_raises(ActiveRecord::Fixture::FormatError) do
            File.open(t.path) { |fh| fh.to_a }
          end
        end
      end

      def test_wrong_fixture_format_nested
        tmp_yaml ['empty', 'yml'], 'one: two' do |t|
          assert_raises(ActiveRecord::Fixture::FormatError) do
            File.open(t.path) { |fh| fh.to_a }
          end
        end
      end

      def test_render_context_helper
        ActiveRecord::FixtureSet.context_class.class_eval do
          def fixture_helper
            "Fixture helper"
          end
        end
        yaml = "one:\n  name: <%= fixture_helper %>\n"
        tmp_yaml ['curious', 'yml'], yaml do |t|
          golden =
              [["one", {"name" => "Fixture helper"}]]
          assert_equal golden, File.open(t.path) { |fh| fh.to_a }
        end
        ActiveRecord::FixtureSet.context_class.class_eval do
          remove_method :fixture_helper
        end
      end

      def test_render_context_lookup_scope
        yaml = <<END
one:
  ActiveRecord: <%= defined? ActiveRecord %>
  ActiveRecord_FixtureSet: <%= defined? ActiveRecord::FixtureSet %>
  FixtureSet: <%= defined? FixtureSet %>
  ActiveRecord_FixtureSet_File: <%= defined? ActiveRecord::FixtureSet::File %>
  File: <%= File.name %>
END

        golden = [['one', {
          'ActiveRecord' => 'constant',
          'ActiveRecord_FixtureSet' => 'constant',
          'FixtureSet' => nil,
          'ActiveRecord_FixtureSet_File' => 'constant',
          'File' => 'File'
        }]]

        tmp_yaml ['curious', 'yml'], yaml do |t|
          assert_equal golden, File.open(t.path) { |fh| fh.to_a }
        end
      end

      # Make sure that each fixture gets its own rendering context so that
      # fixtures are independent.
      def test_independent_render_contexts
        yaml1 = "<% def leaked_method; 'leak'; end %>\n"
        yaml2 = "one:\n  name: <%= leaked_method %>\n"
        tmp_yaml ['leaky', 'yml'], yaml1 do |t1|
          tmp_yaml ['curious', 'yml'], yaml2 do |t2|
            File.open(t1.path) { |fh| fh.to_a }
            assert_raises(NameError) do
              File.open(t2.path) { |fh| fh.to_a }
            end
          end
        end
      end

      def test_removes_fixture_config_row
        File.open(::File.join(FIXTURES_ROOT, 'other_posts.yml')) do |fh|
          assert_equal(['second_welcome'], fh.each.map { |name, _| name })
        end
      end

      def test_extracts_model_class_from_config_row
        File.open(::File.join(FIXTURES_ROOT, 'other_posts.yml')) do |fh|
          assert_equal 'Post', fh.model_class
        end
      end

      private
      def tmp_yaml(name, contents)
        t = Tempfile.new name
        t.binmode
        t.write contents
        t.close
        yield t
      ensure
        t.close true
      end
    end
  end
end


text:
import unittest
class Test(unittest.TestCase):
    def test(self):
        print u"Unicöde"
        assert 1 == 2


text:
<?php

/**
 * @namespace
 */
namespace Yandex\Common;

abstract class Model
{

    protected $mappingClasses = array(

    );

    protected $propNameMap = array(

    );

    /**
     * Constructor
     *
     * @param array $data
     */
    public function __construct($data = array())
    {
        $this->fromArray($data);
    }

    /**
     * Set from array
     *
     * @param array $data
     * @return $this
     */
    public function fromArray($data)
    {
        foreach ($data as $key => $val) {

            if (is_int($key)) {
                if (method_exists($this, "add")) {
                    $this->add($val);
                }
            }

            $propertyName = $key;
            $ourPropertyName = array_search($propertyName, $this->propNameMap);

            if ($ourPropertyName) {
                $propertyName = $ourPropertyName;
            }

            if (!empty($this->propNameMap)) {
                if (array_key_exists($key, $this->propNameMap)) {
                    $propertyName = $this->propNameMap[$key];
                }
            }

            if (property_exists($this, $propertyName)) {
                if (isset($this->mappingClasses[$propertyName])) {
                    $this->{$propertyName} = new $this->mappingClasses[$propertyName]($val);
                } else {
                    $this->{$propertyName} = $val;
                }
            }
        }
        return $this;
    }

    /**
     * Set from json
     *
     * @param string $json
     * @return $this
     */
    public function fromJson($json)
    {
        $this->fromArray(json_decode($json, true));
        return $this;
    }

    /**
     * Get array from object
     *
     * @return array
     */
    public function toArray()
    {
        return $this->toArrayRecursive($this);
    }

    /**
     * Get array from object
     *
     * @return string
     */
    public function toJson()
    {
        return json_encode($this->toArrayRecursive($this));
    }

    /**
     * Get array from object
     *
     * @param array|object $data
     * @return array
     */
    protected function toArrayRecursive($data)
    {
        if (is_array($data) || is_object($data)) {
            $result = array();
            foreach ($data as $key => $value) {
                if ($key === "mappingClasses" || $key === "propNameMap") {
                    continue;
                }

                $propNameMap = $key;

                if (!empty($this->propNameMap)
                    && array_key_exists($key, $this->propNameMap)
                ) {
                    $propNameMap = $this->propNameMap[$key];
                }

                if (is_object($value) && method_exists($value, "getAll")) {
                    $result[$propNameMap] = $this->toArrayRecursive($value->getAll());
                } else {
                    if ($value !== null) {
                        $result[$propNameMap] = $this->toArrayRecursive($value);
                    }
                }
            }
            return $result;
        }
        return $data;
    }
}


text:
---
---

var Arc = function() {
	//colors from http://colorbrewer2.org/
	var nodeColours = {		"al":{"color":"#084594","altcolor":"#636363","name":"Arabidopsis lyrata"}, //Brassicaceae, Brassicales, blue
							"at":{"color":"#2171b5","altcolor":"#636363","name":"Arabidopsis thaliana"}, //Brassicaceae, Brassicales, blue
							"ar":{"color":"#252525","altcolor":"#636363","name":"Amborella trichopoda"}, //Amborellaceae, Magnoliales, black
							"br":{"color":"#4292c6","altcolor":"#636363","name":"Brassica rapa"}, //Brassicaceae, Brassicales, blue
							"cp":{"color":"#6baed6","altcolor":"#636363","name":"Carica papaya"}, //Caricaceae, Brassicales, blue
							"fv":{"color":"#fcbba1","altcolor":"#e6550d","name":"Fragaria vesca"}, //Rosaceae, Rosales, red
							"gm":{"color":"#cb181d","altcolor":"#e6550d","name":"Glycine max"}, //Fabaceae, Fabales, red
							"gr":{"color":"#9ecae1","altcolor":"#636363","name":"Gossipium raimondii"}, //Malvaceae, Malvales, blue
							"mt":{"color":"#67000d","altcolor":"#e6550d","name":"Medicago truncatula"}, //Fabaceae, Fabales, red
							"pt":{"color":"#fc9272","altcolor":"#e6550d","name":"Populus trichocarpa"}, //Salicaceae, Malpighiales, red
							"sl":{"color":"#ffffb2","altcolor":"#636363","name":"Solanum lycopersicum"}, //Solanaceae, Solanales, yellow
							"st":{"color":"#fed976","altcolor":"#636363","name":"Solanum tuberosum"}, //Solanaceae, Solanales, yellow
							"ta":{"color":"#c6dbef","altcolor":"#636363","name":"Theobroma cacao"}, //Malvaceae, Malvales, blue
							"vv":{"color":"#4a1486","altcolor":"#636363","name":"Vitis vinifera"}, //Vitaceae, Vitales, purple
							"os":{"color":"#bae4b3","altcolor":"#636363","name":"Oryza sativa"}, //Poaceae, Poales, green
							"lj":{"color":"#a50f15","altcolor":"#636363","name":"Lotus japonicum"}, //Fabaceae, Fabales, red
							"rc":{"color":"#fb6a4a","altcolor":"#e6550d","name":"Ricinus communis"}, //Euphorbiaceae, Malpighiales, red
							"zm":{"color":"#238b45","altcolor":"#636363","name":"Zea mays"}, //Poaceae, Poales, green
							"ph":{"color":"#ef3b2c","altcolor":"#e6550d","name":"Phaseolus vulgaris"},//Fabaceae, Fabales, red
							"md":{"color":"#fee0d2","altcolor":"#e6550d","name":"Malus domestica"},// Rosaceae, Rosales, red
							"cr":{"color":"#ffffff","altcolor":"#636363","name":"Chlamydomonas reinhardtii"} 	};
	var width  = 500;           // width of svg image
	var height;// set based on number of nodes = 1000;           // height of svg image
	var margin = 20;            // amount of margin around plot area
	var pad = margin / 2;       // actual padding amount
	var radius = 4;             // fixed node radius
	var xfixed = pad + radius;  // y position for all nodes
	var arcplot; //function
	var allData = [];
	var nodesG; // nodesgroup
	var linksG; //linksgroup
	var showdetails;
	var hidedetails;
	var tooltip = Tooltip("vis-tooltip", 230); //tooltip.js
	var svg;
	var setColor; //function
	var color = "color";
    var MCL = "1.2";

	arcplot = function(selection,data){
		//var svg;
		var plot;
		allData = setupData(data); // setupData maps node objects to links source/target
		stats(allData);
		height = allData.nodes.length * 10
		width = allData.nodes.length * 10
		svg = d3.select(selection)
					.append("svg")
					.attr("id","arc")
					.attr("width",width)
					.attr("height",height)
		plot = svg.append("g")
					.attr("id","plot")
					.attr("transform", "translate(" + pad + ", " + pad + ")");
		linksG = plot.append("g").attr("id", "links");
    	nodesG = plot.append("g").attr("id", "nodes");
		return update();
	};
	arcplot.updateData = function(newData){
		allData = setupData(newData);
		stats(allData);
		height = allData.nodes.length * 10
		width = allData.nodes.length * 10
		svg.attr("height",height)
			.attr("width",width)
		link.remove();
		node.remove();
		return update();
	};
	arcplot.toggleColor = function(newColor){
		link.remove();
		node.remove();
		setColor(newColor);
		update();
	};
	function update(){
		console.log('update')
		// must be done AFTER links are fixed
	    linearLayout(allData.nodes);

	    // draw links first, so nodes appear on top
	    drawLinks(allData.links);

	    // draw nodes last
	    drawNodes(allData.nodes);
	};
	setupData = function(data) {
		var nodesMap;
		nodesMap = mapNodes(data.nodes);
		//data.nodes.forEach(function(n){
		//	var randomnumber;
		//	n.x = randomnumber = Math.floor(Math.random() * width);
      	//	n.y = randomnumber = Math.floor(Math.random() * height);
      	//	//return n.radius = 5;
		//})
	    data.links.forEach(function(l) {
	      l.source = nodesMap.get(l.source);
	      l.target = nodesMap.get(l.target);
	      //return linkedByIndex["" + l.source.id + "," + l.target.id] = 1;
    	});
		return data;
	};

	setColor = function(newColor){
		color = newColor;
		//return update()
	};
	mapNodes = function(nodes) {
		var nodesMap;
		nodesMap = d3.map();
		nodes.forEach(function(n) {
			return nodesMap.set(n.id, n);
		});
		return nodesMap;
	};
	// Layout nodes linearly, sorted by group
	function linearLayout(nodes) {
	    // sort nodes by group
	    ///*
	    nodes.sort(function(a,b) {
	    	//return Math.floor((Math.random() * 100) + 1);
	    	return a.cluster - b.cluster;
	    })
		//*/

	    // used to scale node index to x position
	    var yscale = d3.scale.linear()
	        .domain([0, nodes.length - 1])
	        .range([radius, height - margin - radius]);

	    // calculate pixel location for each node
	    nodes.forEach(function(d, i) {
	        d.x = xfixed;
	        d.y = yscale(i);
	    });
	}
	// Draws nodes on plot
	function drawNodes(nodes) {
		node = nodesG.selectAll("circle.node").data(allData.nodes, function(d) {
			return d.id;
		});
	    node.enter()
	        .append("circle")
	        .attr("class", "node")
	        .attr("id", function(d, i) { return d.name; })
	        .attr("cx", function(d, i) { return d.x; })
	        .attr("cy", function(d, i) { return d.y; })
	        .attr("r",  function(d, i) { return radius; })
	        .style("fill",   function(d, i) { return nodeColours[d.species][color]; })
	        .on("mouseover", showDetails)
	        .on("mouseout", hideDetails);
	    return node.exit().remove()
	}

	// Draws nice arcs for each link on plot
	function drawLinks(links) {
		link = linksG.selectAll("line.link").data(allData.links, function(d) {
			if ("block_score" in d) {
				return "" + d.source.id + "_" + d.target.id;
			};
		});
	    // scale to generate radians (just for lower-half of circle)
	    var radians = d3.scale.linear()
	        //.range([Math.PI / 2, 3 * Math.PI / 2]);
	        .range([0,Math.PI])
	    // path generator for arcs (uses polar coordinates)
	    var arc = d3.svg.line.radial()
	        .interpolate("basis")
	        .tension(0)
	        .angle(function(d) { return radians(d); });

	    // add links
	    link.enter()
	        .append("path")
	        .attr("class", "link")
	        .attr("transform", function(d, i) {
	            // arc will always be drawn around (0, 0)
	            // shift so (0, 0) will be between source and target
	            var xshift = xfixed;
	            var yshift = d.source.y + (d.target.y - d.source.y) / 2;
	            return "translate(" + xshift + ", " + yshift + ")";
	        })
	        .attr("d", function(d, i) {
	            // get x distance between source and target
	            var ydist = Math.abs(d.source.y - d.target.y);
	            // set arc radius based on y distance
	            arc.radius(ydist / 2);
	            // want to generate 1/3 as many points per pixel in y direction
	            var points = d3.range(0,Math.ceil(ydist / 3));
	            // set radian scale domain
	            radians.domain([0, points.length - 1]);
	            // return path for arc
	            return arc(points);
	        });
	};// end drawlinks

	showDetails = function(d,i) {
		var content;
		content = '
' + d.id + '
';
		content += '
';
		content += '
' + nodeColours[d.species]['name'] + '
';
		//content += '
';
		//content += '
Cluster '+d.cluster+'
'
		tooltip.showTooltip(content, d3.event);
	};// end showdetails

	hideDetails = function(d,i) {
		tooltip.hideTooltip();
	};//end hidedetails

	stats = function(data){
      var content;
      var margin = {top:20,right:20,bottom:30,left:60};
      var statsw = 500 - margin.left - margin.right;
      var statsh = 300 - margin.top - margin.bottom;
      var numNodes = 0;
      var numLinks = 0;
      var numClusters = 0;
      var nodesInClusters = 0;
      var clusterMap = {};
      var biggestCluster = 0;
      var statistics = {};
      var xvals = [];
      var yvals = [];
      var pairs = [];
      var scatter; //ski skapadap scatterplot
      var trendline;//the trendline
      var xscale = d3.scale.sqrt().range([0,statsw]);
      var xmap = function(d){ return xscale(d[0]);};
      var xaxis = d3.svg.axis().scale(xscale).orient("botom").ticks(5);
      var yscale = d3.scale.sqrt().range([statsh,0]);
      var ymap = function(d){ return yscale(d[1]);};
      var yaxis = d3.svg.axis().scale(yscale).orient("left").ticks(6);

      function leastSquares(xSeries, ySeries) { //from http://bl.ocks.org/benvandyke/8459843
          var reduceSumFunc = function(prev, cur) { return prev + cur; };
          var xBar = xSeries.reduce(reduceSumFunc) * 1.0 / xSeries.length;
          var yBar = ySeries.reduce(reduceSumFunc) * 1.0 / ySeries.length;
          var ssXX = xSeries.map(function(d) { return Math.pow(d - xBar, 2); })
              .reduce(reduceSumFunc);
          var ssYY = ySeries.map(function(d) { return Math.pow(d - yBar, 2); })
              .reduce(reduceSumFunc);
          var ssXY = xSeries.map(function(d, i) { return (d - xBar) * (ySeries[i] - yBar); })
              .reduce(reduceSumFunc);

          var slope = ssXY / ssXX;
          var intercept = yBar - (xBar * slope);
          var rSquare = Math.pow(ssXY, 2) / (ssXX * ssYY);

          return [slope, intercept, rSquare];
      }

      data.links.forEach(function(l){
          if ("block_score" in l){
              var source_cluster = l.source['clusters'][MCL];
              var target_cluster = l.target['clusters'][MCL];
              if (source_cluster > 0 && target_cluster > 0 && source_cluster === target_cluster){
                  numLinks += 1;
                  yvals.push(parseInt(l.block_score));
                  xvals.push(l.distance);
                  //pairs.push([l.block_score, l.distance])
                  pairs.push([l.distance, parseInt(l.block_score)])
              }
          }
	  });
      //xscale.domain([d3.min(xvals)-1,d3.max(xvals)+1]);
      xscale.domain([0,d3.max(xvals)+1]);
      yscale.domain([d3.min(yvals)-1,d3.max(yvals)+1]);
      console.log([d3.min(yvals),yscale(d3.min(yvals))]);
	  data.nodes.forEach(function(n){
          numNodes += 1;
          numClusters = Math.max(numClusters,n['clusters'][MCL]);
		  if (n['clusters'][MCL] > 0){
              nodesInClusters += 1;
              if (!(n['clusters'][MCL] in clusterMap)){
			       clusterMap[n['clusters'][MCL]] = 0
              }
			  clusterMap[n['clusters'][MCL]] += 1
          }
      });
      for (var key in clusterMap){
		  biggestCluster = Math.max(clusterMap[key],biggestCluster)
      }
      content = "
# Nodes: "+numNodes+" ";
      content += "
# Edges: "+numLinks+"
";
      content += "
# Clusters: "+numClusters+"
";
      content += "
# Nodes in clusters: "+nodesInClusters+"
";
      content += "
Biggest cluster: "+biggestCluster+"
";
      $("#numbers").html(content);
      //initialize plot
      d3.selectAll("#scatter svg").remove();
      scatter = d3.select("#scatter")
          .append("svg")
          .attr("width",statsw + margin.left + margin.right)
          .attr("height",statsh + margin.top + margin.bottom)
          .append("g")
          .attr("transform","translate("+ margin.left + "," + margin.top + ")");
      //prepare x
      scatter.append("g")
          .attr("class","axis")
          .attr("transform","translate(0,"+statsh+")")
          .call(xaxis)
          .append("text")
          .attr("class","label")
          .attr("x",statsw)
          .attr("y",-6)
          .style("text-anchor","end")
          .text("Distance");
      //prepare y
      scatter.append("g")
          .attr("class","axis")
          .call(yaxis)
          .append("text")
          .attr("class","label")
          .attr("transform","rotate(-90)")
          .attr("y",6)
          .attr("dy",".71em")
          .style("text-anchor","end")
          .text("block size");
      //start plotting dots
      scatter.selectAll(".dot")
          .data(pairs)
          .enter().append("circle")
          .attr("class","dot")
          .attr("r",3)
          .attr("cx",xmap)
          .attr("cy",ymap)
          .style("fill","red");

      //get regression data
      coeff = leastSquares(xvals,yvals);
      console.log(coeff);

      var x1 = d3.min(xvals);
      var x2 = d3.max(xvals);
      var y1 = x1 * coeff[0] + coeff[1];
      var y2 = x2 * coeff[0] + coeff[1];
      var trendData = [[x1,y1,x2,y2]];

      trendline = scatter.selectAll(".trendline")
          .data(trendData);
      trendline.enter()
			.append("line")
			.attr("class", "trendline")
			.attr("x1", function(d) { return xscale(d[0]); })
			.attr("y1", function(d) { return yscale(d[1]); })
			.attr("x2", function(d) { return xscale(d[2]); })
			.attr("y2", function(d) { return yscale(d[3]); })
			.attr("stroke", "black")
			.attr("stroke-width", 1);
      //display equation and r-square
      scatter.append("text")
          .text("eq: "+coeff[0]+"x + "+coeff[1])
          .attr("class","text-label")
          .attr("x",function(d){return xscale(x2) - 30})
          .attr("y",function(d){return yscale(d3.max(yvals)) - 30 });

      statistics['numNodes'] = numNodes;
      statistics['numLinks'] = numLinks;
      statistics['numCLusters'] = numClusters;
      statistics['nodesInClusters'] = nodesInClusters;
      statistics['biggestCluster'] = biggestCluster;
      return statistics
	};

	return arcplot;
};
/*
var activate = function(group, link) {
  d3.selectAll("#" + group + " a").classed("active", false);
  return d3.select("#" + group + " #" + link).classed("active", true);
};
$(function(){
	myArc = arcDiagram()
	$("#gene_select").on("change",function(d){
		var geneFile;
		geneFile = $(this).val();
		console.log(geneFile)
		return d3.json(geneFile, function(error,json) {
			if (error) return console.warn(error);
			return myArc.updateData(json);
		});
	});
	d3.selectAll("#color_select a").on("click",function(d){
		var newColor;
		newColor = d3.select(this).attr("id");
		console.log(newColor)
		activate("color_select",newColor);
		return myArc.toggleColor(newColor);
	});
	d3.json("{{ site.baseurl }}/json/test.json",function(error,json){
		if (error) return console.warn(error);
		return myArc("#vis",json);
	});
});
*/


text:
function engine = pearl_dbn_inf_engine(bnet, varargin)
% LOOPY_DBN_INF_ENGINE Loopy Pearl version of forwards-backwards
% engine = loopy_dbn_inf_engine(bnet, ...)
%
% Optional arguments
% 'max_iter' - specifies the max num. forward-backward passes to perform [1]
% 'tol' - as in loopy_pearl [1e-3]
% 'momentum' - as in loopy_pearl [0]

error('pearl_dbn does not work yet')

max_iter = 1;
tol = 1e-3;
momentum = 0;

if nargin >= 2
  args = varargin;
  nargs = length(args);
  for i=1:2:nargs
    switch args{i},
     case 'max_iter', max_iter = args{i+1};
     case 'tol', tol = args{i+1};
     case 'momentum', momentum = args{i+1};
    end
  end
end

engine.max_iter = max_iter;
engine.tol = tol;
engine.momentum = momentum;
engine.pearl_engine = [];
engine.T = [];
engine.ss = length(bnet.intra);

engine.marginal = [];
engine.evidence = [];
engine.msg = [];
engine.parent_index = [];
engine.child_index = [];
%[engine.parent_index, engine.child_index] = mk_pearl_msg_indices(bnet); % need to unroll first

ss = length(bnet.intra);
engines.ss = ss;
onodes = bnet.observed;
hnodes = mysetdiff(1:ss, onodes);
obschild = zeros(1,ss);
for i=hnodes(:)'
  %ocs = myintersect(children(bnet.dag, i), onodes);
  ocs = children(bnet.intra, i);
  assert(length(ocs) <= 1);
  if length(ocs)==1
    obschild(i) = ocs(1);
  end
end
engine.obschild = obschild;

engine.mult_self_ndx = [];
engine.mult_parent_ndx = [];
engine.marg_self_ndx = [];
engine.marg_parent_ndx = [];

engine = class(engine, 'loopy_dbn_inf_engine', inf_engine(bnet));


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:util="http://www.springframework.org/schema/util"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
                    http://www.springframework.org/schema/security   http://www.springframework.org/schema/security/spring-security-4.0.xsd
                    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">

	<global-method-security pre-post-annotations="enabled">
        <expression-handler ref="methodSecurityExpressionHandler"/>
    </global-method-security>

	<beans:bean id="reflectionSaltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
		<beans:property name="userPropertyToUse" value="username"/>
	</beans:bean>

	<!-- SVN -->
	<beans:bean id="svnAccessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
		<beans:constructor-arg name="decisionVoters">
			<beans:list>
				<beans:ref bean="authenticatedVoter"/>
				<beans:ref bean="userSwitchPermissionVoter"/>
			</beans:list>
		</beans:constructor-arg>
	</beans:bean>

	<beans:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler">
		<beans:property name="defaultRolePrefix" value="" />
	</beans:bean>

	<beans:bean id="methodSecurityExpressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
		<beans:property name="defaultRolePrefix" value="" />
	</beans:bean>

	<beans:bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
		<beans:property name="rolePrefix" value="" />
	</beans:bean>

	<http realm="svn" pattern="/svn/**" access-decision-manager-ref="svnAccessDecisionManager">
		<http-basic entry-point-ref="svnHttpBasicEntryPoint"/>
		<intercept-url pattern="/svn/**" access="hasAnyRole('A', 'S', 'U')" />
		<csrf disabled="true"/>
	</http>

	<!-- Generic Web -->
	<beans:bean id="authenticatedVoter" class="org.springframework.security.access.vote.AuthenticatedVoter"/>

	<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
		<beans:constructor-arg name="decisionVoters">
			<beans:list>
				<beans:ref bean="authenticatedVoter"/>
			</beans:list>
		</beans:constructor-arg>
	</beans:bean>

	<!-- custom-filter extends UsernamePasswordAuthenticationFilter -->
	<beans:bean id="ngrinderUserPasswordAuthenticationFilter"
				class="org.ngrinder.security.NgrinderUsernamePasswordAuthenticationFilter">
		<beans:property name="filterProcessesUrl" value="/form_login"/>
		<beans:property name="rememberMeServices" ref="rememberMeServices"/>
		<beans:property name="authenticationSuccessHandler" ref="loginLogAuthenticationSuccessHandler"/>
		<beans:property name="authenticationFailureHandler" ref="simpleUrlAuthenticationFailureHandler"/>
		<beans:property name="authenticationManager" ref="authenticationManager"/>
		<beans:property name="usernameParameter" value="j_username"/>
		<beans:property name="passwordParameter" value="j_password"/>
	</beans:bean>

	<!-- SuccessHandler -->
	<beans:bean id="loginLogAuthenticationSuccessHandler"
				class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
		<beans:property name="defaultTargetUrl" value="/home"/>
		<beans:property name="alwaysUseDefaultTargetUrl" value="true"/>
	</beans:bean>

	<!-- FailureHandler -->
	<beans:bean id="simpleUrlAuthenticationFailureHandler"
				class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
		<beans:property name="defaultFailureUrl" value="/login"/>
	</beans:bean>

	<beans:bean id="authenticationProcessingFilterEntryPoint"
				class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
		<beans:constructor-arg name="loginFormUrl" value="/login"/>
	</beans:bean>

	<!-- static resource -->
	<http pattern="/css/**" security="none"/>
	<http pattern="/img/**" security="none"/>
	<http pattern="/js/**" security="none"/>
	<http pattern="/plugins/**" security="none"/>
	<http pattern="/login" security="none"/>

	<!-- used for shared test report page -->
	<http pattern="/perftest/**/report" security="none"/>
	<http pattern="/perftest/**/monitor" security="none"/>
	<http pattern="/perftest/**/graph" security="none"/>

	<!-- accessible from no authorized users -->
	<http pattern="/check/**" security="none"/>
	<http pattern="/agent/download/**" security="none"/>
	<http pattern="/monitor/download/**" security="none"/>
	<http pattern="/jnlp/**" security="none"/>
	<http pattern="/sign_up/**" security="none"/>

	<beans:bean id="basicProcessingFilter"
				class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
		<beans:constructor-arg ref="authenticationManager"/>
		<beans:constructor-arg ref="httpBasicAuthenticationEntryPoint"/>
	</beans:bean>

	<beans:bean id="httpBasicAuthenticationEntryPoint"
				class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
		<beans:property name="realmName" value="ngrinider"/>
	</beans:bean>

	<http entry-point-ref="delegatingAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager">
		<intercept-url pattern="/"/>
		<intercept-url pattern="/home"/>
		<intercept-url pattern="/perftest/**"/>
		<intercept-url pattern="/help**"/>
		<intercept-url pattern="/script**"/>
		<intercept-url pattern="/monitor-properties.map"/>
		<intercept-url pattern="/agent/**"/>
		<intercept-url pattern="/user/**"/>
		<custom-filter ref="basicProcessingFilter" position="BASIC_AUTH_FILTER"/>
		<custom-filter ref="pluggablePreAuthFilter" position="PRE_AUTH_FILTER"/>
		<custom-filter ref="ngrinderUserPasswordAuthenticationFilter" position="FORM_LOGIN_FILTER"/>
		<!-- logout to home, and then it will redirect to login. otherwise, there will be some ajax problem. -->
		<logout logout-success-url="/" logout-url="/logout" delete-cookies="JSESSIONID,switchUser"
				invalidate-session="true"/>
		<session-management invalid-session-url="/login" session-fixation-protection="newSession"/>
		<remember-me key="ngrinder" user-service-ref="ngrinderUserDetailsService"/>
		<csrf disabled="true"/>
	</http>

	<beans:bean id="delegatingAuthenticationEntryPoint"
				class="org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint">
		<beans:constructor-arg>
			<util:map map-class="java.util.LinkedHashMap">
				<beans:entry key="hasHeader('WWW-Authenticate','Basic')" value-ref="httpBasicAuthenticationEntryPoint"/>
			</util:map>
		</beans:constructor-arg>
		<beans:property name="defaultEntryPoint" ref="authenticationProcessingFilterEntryPoint"/>
	</beans:bean>

	<beans:bean id="rememberMeServices"
				class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
		<beans:constructor-arg name="key"  value="ngrinder"/>
		<beans:constructor-arg name="userDetailsService" ref="ngrinderUserDetailsService"/>
	</beans:bean>

	<beans:bean id="ngrinderPreAuthProvider" class="org.ngrinder.security.NGrinderAuthenticationPreAuthProvider">
		<beans:property name="preAuthenticatedUserDetailsService">
			<beans:bean id="userDetailsServiceWrapper"
						class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
				<beans:property name="userDetailsService" ref="ngrinderUserDetailsService"/>
			</beans:bean>
		</beans:property>
		<beans:property name="userService" ref="userService"/>
	</beans:bean>

	<authentication-manager alias="authenticationManager">
		<authentication-provider ref="ngrinderPreAuthProvider"/>
		<authentication-provider ref="ngrinderAuthenticationProvider"/>
	</authentication-manager>

</beans:beans>


text:
package com.google.closure.plugin.soy;

import com.google.closure.plugin.plan.JoinNodes;
import com.google.closure.plugin.plan.OptionPlanGraphNode;
import com.google.closure.plugin.plan.PlanContext;
import com.google.closure.plugin.plan.PlanGraphNode;

final class SoyRoot extends OptionPlanGraphNode<SoyOptions> {

  protected SoyRoot(PlanContext context) {
    super(context);
  }

  @Override
  protected SV getStateVector() {
    return new SV(this);
  }

  static final class SV
  extends OptionPlanGraphNode.OptionStateVector<SoyOptions> {

    private static final long serialVersionUID = 1L;

    protected SV(OptionPlanGraphNode<SoyOptions> node) {
      super(node);
    }

    @Override
    public PlanGraphNode<?> reconstitute(PlanContext c, JoinNodes joinNodes) {
      return apply(new SoyRoot(c));
    }
  }
}


text:
module OpenTelemetry
  module SDK
    module Metrics
      module State
        # MetricData is a Struct containing {MetricStream} data for export.
        MetricData = Struct.new(:name,                      # String
                                :description,               # String
                                :unit,                      # String
                                :instrument_kind,           # Symbol
                                :resource,                  # OpenTelemetry::SDK::Resources::Resource
                                :instrumentation_scope,     # OpenTelemetry::SDK::InstrumentationScope
                                :data_points,               # Hash{Hash{String => String, Numeric, Boolean, Array<String, Numeric, Boolean>} => Numeric}
                                :start_time_unix_nano,      # Integer nanoseconds since Epoch
                                :time_unix_nano)            # Integer nanoseconds since Epoch
      end
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 56(17): 2118 (1978)

#### Original name
Humaria peckii House

### Remarks
null


text:
<?php

//----------------------------------------------------------------------
//
//  Copyright (C) 2018 Artem Rodygin
//
//  You should have received a copy of the MIT License along with
//  this file. If not, see <http://opensource.org/licenses/MIT>.
//
//----------------------------------------------------------------------

namespace Linode\Repository\Networking;

use Linode\Repository\RepositoryInterface;

/**
 * IPv6Range repository.
 */
interface IPv6RangeRepositoryInterface extends RepositoryInterface
{
}


text:
@interface CommunityPostAPI : BaseBlockAPI

- (void)uploadImage:(UIImage *)image ResultBlock:(APIRequestResultBlock)resultBlock;

- (void)sendPostDataWithCircleId:(NSString *)circleId
                           Title:(NSString *)title
                         Content:(NSString *)content
                         Address:(NSString *)address
                       Longitude:(CGFloat)longitude
                       Latitude:(CGFloat)latitude
                     ResultBlock:(APIRequestResultBlock)resultBlock;

- (void)loadProvinceDataWithResultBlock:(APIRequestResultBlock)resultBlock;

- (void)loadCityDataWithProvinceId:(NSString *)provinceId ResultBlock:(APIRequestResultBlock)resultBlock;

- (void)loadAreaDataWithCityId:(NSString *)cityId ResultBlock:(APIRequestResultBlock)resultBlock;

@end


text:
package org.mvel2.util;

import org.mvel2.ImmutableElementException;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;

public class FastList<E> extends AbstractList<E> implements Externalizable {
    private E[] elements;
    private int size = 0;
    private boolean updated = false;

    public FastList(int size) {
        elements = (E[]) new Object[size == 0 ? 1 : size];
    }

    public FastList(E[] elements) {
        this.size = (this.elements = elements).length;
    }

    public FastList() {
        this(10);
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(size);
        for (int i = 0; i < size; i++) {
            out.writeObject(elements[i]);
        }
    }

    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        elements = (E[]) new Object[size = in.readInt()];
        for (int i = 0; i < size; i++) {
            elements[i] = (E) in.readObject();
        }
    }

    public E get(int index) {
        return (E) elements[index];
    }

    public int size() {
        return size;
    }

    public boolean add(E o) {
        if (size == elements.length) {
            increaseSize(elements.length * 2);
        }

        elements[size++] = o;
        return true;
    }

    public E set(int i, E o) {
        if (!updated) copyArray();
        E old = elements[i];
        elements[i] = o;
        return old;
    }

    public void add(int i, E o) {
        if (size == elements.length) {
            increaseSize(elements.length * 2);
        }

        for (int c = size; c != i; c--) {
            elements[c] = elements[c - 1];
        }
        elements[i] = o;
        size++;
    }

    public E remove(int i) {
        E old = elements[i];
        for (int c = i + 1; c < size; c++) {
            elements[c - 1] = elements[c];
            elements[c] = null;
        }
        size--;
        return old;
    }

    public int indexOf(Object o) {
        if (o == null) return -1;
        for (int i = 0; i < elements.length; i++) {
            if (o.equals(elements[i])) return i;
        }
        return -1;
    }

    public int lastIndexOf(Object o) {
        if (o == null) return -1;
        for (int i = elements.length - 1; i != -1; i--) {
            if (o.equals(elements[i])) return i;
        }
        return -1;
    }

    public void clear() {
        elements = (E[]) new Object[1];
        size = 0;
    }

    public boolean addAll(int i, Collection<? extends E> collection) {
        int offset = collection.size();
        ensureCapacity(offset + size);

        if (i != 0) {
            // copy forward all elements that the insertion is occuring before
            for (int c = i; c != (i + offset); c++) {
                elements[c + offset + 1] = elements[c];
            }
        }

        int c = size == 0 ? -1 : 0;
        for (E o : collection) {
            elements[offset + c++] = o;
        }

        size += offset;

        return true;
    }

    public Iterator iterator() {
        final int size = this.size;
        return new Iterator() {
            private int cursor = 0;

            public boolean hasNext() {
                return cursor < size;
            }

            public Object next() {
                return elements[cursor++];
            }

            public void remove() {
                throw new ImmutableElementException("cannot change elements in immutable list");
            }
        };

    }

    public ListIterator<E> listIterator() {
        return new ListIterator<E>() {
            private int i = 0;

            public boolean hasNext() {
                return i < size;
            }

            public E next() {
                return elements[i++];
            }

            public boolean hasPrevious() {
                return i > 0;
            }

            public E previous() {
                return elements[i--];
            }

            public int nextIndex() {
                return i++;
            }

            public int previousIndex() {
                return i--;
            }

            public void remove() {
                throw new java.lang.UnsupportedOperationException();
            }

            public void set(E o) {
                elements[i] = o;
            }

            public void add(Object o) {
                throw new java.lang.UnsupportedOperationException();
            }
        };
    }

    public ListIterator listIterator(int i) {
        return super.listIterator(i);
    }

    public List subList(int i, int i1) {
        return super.subList(i, i1);
    }

    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;

        ListIterator e1 = listIterator();
        ListIterator e2 = ((List) o).listIterator();
        while (e1.hasNext() && e2.hasNext()) {
            Object o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1 == null ? o2 == null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
    }

    public int hashCode() {
        return super.hashCode();
    }

    protected void removeRange(int i, int i1) {
        throw new RuntimeException("not implemented");
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    public Object[] toArray() {
        return toArray(new Object[size]);
    }

    public Object[] toArray(Object[] objects) {
        if (objects.length < size) objects = new Object[size];
        for (int i = 0; i < size; i++) {
            objects[i] = elements[i];
        }
        return objects;
    }

    public boolean remove(Object o) {
        throw new RuntimeException("not implemented");
    }

    public boolean containsAll(Collection collection) {
        throw new RuntimeException("not implemented");
    }

    public boolean addAll(Collection collection) {
        return addAll(size, collection);
    }

    public boolean removeAll(Collection collection) {
        throw new RuntimeException("not implemented");
    }

    public boolean retainAll(Collection collection) {
        throw new RuntimeException("not implemented");
    }

    private void ensureCapacity(int additional) {
        if ((size + additional) > elements.length) increaseSize((size + additional) * 2);
    }

    private void copyArray() {
        increaseSize(elements.length);
    }

    private void increaseSize(int newSize) {
        E[] newElements = (E[]) new Object[newSize];
        for (int i = 0; i < elements.length; i++)
            newElements[i] = elements[i];

        elements = newElements;

        updated = true;
    }

    public String toString() {
        return super.toString();
    }
}


text:
using SharpDX.Windows;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HelixToolkit.SharpDX.Core;
namespace CoreTest
{
    public partial class Form1 : Form
    {
        private RenderForm renderForm;
        private CoreTestApp app;
        public Form1()
        {
            InitializeComponent();
            renderForm = new RenderForm()
            {
                TopLevel = false,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };
            renderForm.Dock = DockStyle.Fill;
            renderForm.FormBorderStyle = FormBorderStyle.None;
            renderForm.ShowIcon = false;
            app = new CoreTestApp(renderForm);
            splitContainer1.Panel2.Controls.Add(renderForm);
            Shown += Form1_Shown;
            FormClosing += Form1_FormClosing;
            splitContainer1.Panel2.Resize += Panel2_Resize;
            renderForm.Width = splitContainer1.Panel2.Width;
            renderForm.Height = splitContainer1.Panel2.Height;
        }

        private void Panel2_Resize(object sender, EventArgs e)
        {
            Debug.WriteLine("Panel resize");
            app.RequestResize();
            renderForm.Width = splitContainer1.Panel2.Width;
            renderForm.Height = splitContainer1.Panel2.Height;
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            renderForm.Show();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            renderForm.Close();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            SceneUI.SomeTextFromOutside = textBox1.Text;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            using (var mem = app.Viewport.RenderToBitmapStream())
            {
                var bmp = new Bitmap(mem);
                pictureBox1.Image = bmp;
            }
        }
    }
}


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import "MOZUCouponSetClient.h"
#import "MOZUCouponSetResource.h"

@interface MOZUCouponSetResource()
@property(readwrite, nonatomic) MOZUAPIContext * apiContext;
@end

@implementation MOZUCouponSetResource

-(id)initWithAPIContext:(MOZUAPIContext *)apiContext {
	if (self = [super init]) {
		self.apiContext = apiContext;
		return self;
	}
	else {
		return nil;
	}
}

-(id)cloneWithAPIContextModification:(MOZUAPIContextModificationBlock)apiContextModification {
	MOZUAPIContext* cloned = [self.apiContext cloneWith:apiContextModification];
	return [self initWithAPIContext:cloned];
}

//
#pragma mark -
#pragma mark Get Operations
#pragma mark -
//

/**
Returns a paged collection of CouponSets
@param filter A set of filter expressions representing the search parameters for a query: eq=equals, ne=not equals, gt=greater than, lt = less than or equals, gt = greater than or equals, lt = less than or equals, sw = starts with, or cont = contains. Optional.
@param includeCounts
@param pageSize The number of results to display on each page when creating paged results from a query. The amount is divided and displayed on the `pageCount `amount of pages. The default is 20 and maximum value is 200 per page.
@param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
@param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional.
@param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a `pageSize `of 25, to get the 51st through the 75th items, use `startIndex=3`.
*/

- (void)couponSetsWithStartIndex:(NSNumber *)startIndex pageSize:(NSNumber *)pageSize sortBy:(NSString *)sortBy filter:(NSString *)filter includeCounts:(NSNumber *)includeCounts responseFields:(NSString *)responseFields completionHandler:(void(^)(MOZUCouponSetCollection *result, MOZUAPIError *error, NSHTTPURLResponse *response))handler
 {
	MOZUClient *client = [MOZUCouponSetClient clientForGetCouponSetsOperationWithStartIndex:startIndex pageSize:pageSize sortBy:sortBy filter:filter includeCounts:includeCounts responseFields:responseFields];
	client.context = self.apiContext;
	[client executeWithCompletionHandler:^(id result, NSHTTPURLResponse *response, MOZUAPIError *error) {
		if (handler != nil) {
			handler(result, error, response);
		}
	}];
}

/**

@param couponSetCode
@param includeCounts
@param responseFields
*/

- (void)couponSetWithCouponSetCode:(NSString *)couponSetCode includeCounts:(NSNumber *)includeCounts responseFields:(NSString *)responseFields completionHandler:(void(^)(MOZUCouponSet *result, MOZUAPIError *error, NSHTTPURLResponse *response))handler
 {
	MOZUClient *client = [MOZUCouponSetClient clientForGetCouponSetOperationWithCouponSetCode:couponSetCode includeCounts:includeCounts responseFields:responseFields];
	client.context = self.apiContext;
	[client executeWithCompletionHandler:^(id result, NSHTTPURLResponse *response, MOZUAPIError *error) {
		if (handler != nil) {
			handler(result, error, response);
		}
	}];
}

/**
Returns a random 4 character code that is unique as a coupon set code.
@param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
*/

- (void)uniqueCouponSetCodeWithResponseFields:(NSString *)responseFields completionHandler:(void(^)(NSString *result, MOZUAPIError *error, NSHTTPURLResponse *response))handler
 {
	MOZUClient *client = [MOZUCouponSetClient clientForGetUniqueCouponSetCodeOperationWithResponseFields:responseFields];
	client.context = self.apiContext;
	[client executeWithCompletionHandler:^(id result, NSHTTPURLResponse *response, MOZUAPIError *error) {
		if (handler != nil) {
			handler(result, error, response);
		}
	}];
}

//
#pragma mark -
#pragma mark Post Operations
#pragma mark -
//

/**
Adds a single
@param body Mozu.ProductAdmin.Contracts.CouponSet ApiType DOCUMENT_HERE
@param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
*/

- (void)addCouponSetWithBody:(MOZUCouponSet *)body responseFields:(NSString *)responseFields completionHandler:(void(^)(MOZUCouponSet *result, MOZUAPIError *error, NSHTTPURLResponse *response))handler
 {
	MOZUClient *client = [MOZUCouponSetClient clientForAddCouponSetOperationWithBody:body responseFields:responseFields];
	client.context = self.apiContext;
	[client executeWithCompletionHandler:^(id result, NSHTTPURLResponse *response, MOZUAPIError *error) {
		if (handler != nil) {
			handler(result, error, response);
		}
	}];
}

/**
Tests code for uniqueness and validity
@param code User-defined code that uniqely identifies the channel group.
*/

- (void)validateUniqueCouponSetCodeWithCode:(NSString *)code completionHandler:(void(^)(MOZUAPIError *error, NSHTTPURLResponse *response))handler
 {
	MOZUClient *client = [MOZUCouponSetClient clientForValidateUniqueCouponSetCodeOperationWithCode:code];
	client.context = self.apiContext;
	[client executeWithCompletionHandler:^(id result, NSHTTPURLResponse *response, MOZUAPIError *error) {
		if (handler != nil) {
			handler(error, response);
		}
	}];
}

//
#pragma mark -
#pragma mark Put Operations
#pragma mark -
//

/**

@param body
@param couponSetCode
@param responseFields
*/

- (void)updateCouponSetWithBody:(MOZUCouponSet *)body couponSetCode:(NSString *)couponSetCode responseFields:(NSString *)responseFields completionHandler:(void(^)(MOZUCouponSet *result, MOZUAPIError *error, NSHTTPURLResponse *response))handler
 {
	MOZUClient *client = [MOZUCouponSetClient clientForUpdateCouponSetOperationWithBody:body couponSetCode:couponSetCode responseFields:responseFields];
	client.context = self.apiContext;
	[client executeWithCompletionHandler:^(id result, NSHTTPURLResponse *response, MOZUAPIError *error) {
		if (handler != nil) {
			handler(result, error, response);
		}
	}];
}

//
#pragma mark -
#pragma mark Delete Operations
#pragma mark -
//

/**

@param couponSetCode
*/

- (void)deleteCouponSetWithCouponSetCode:(NSString *)couponSetCode completionHandler:(void(^)(MOZUAPIError *error, NSHTTPURLResponse *response))handler
 {
	MOZUClient *client = [MOZUCouponSetClient clientForDeleteCouponSetOperationWithCouponSetCode:couponSetCode];
	client.context = self.apiContext;
	[client executeWithCompletionHandler:^(id result, NSHTTPURLResponse *response, MOZUAPIError *error) {
		if (handler != nil) {
			handler(error, response);
		}
	}];
}

@end


text:
'''Inheriting from ImplicitSelf will make your class's methods have
implicit self and cls variables (without being declared explicitly),
similar to how Javascript works. See the A class for an example.

'''

class ImplicitSelfDecorator:

    def __init__(self, func):
        self.func = func

    def __get__(self, obj, cls=None):
        func = self.func
        selfvar = obj
        clsvar = type(obj) if obj is not None else cls

        def decorated(*args, **kw):
            self_defined = 'self' in func.__globals__
            if self_defined:
                oldself = func.__globals__['self']
            cls_defined = 'cls' in func.__globals__
            if cls_defined:
                oldcls = func.__globals__['cls']

            func.__globals__['self'] = selfvar
            func.__globals__['cls'] = clsvar
            result = func(*args, **kw)

            if self_defined:
                func.__globals__['self'] = oldself
            else:
                del func.__globals__['self']
            if cls_defined:
                func.__globals__['cls'] = oldcls
            else:
                del func.__globals__['cls']

            return result

        return decorated

class ImplicitSelfMetaclass(type):

    def __new__(cls, name, bases, d):
        for key in d:
            if callable(d[key]):
                d[key] = ImplicitSelfDecorator(d[key])
        return type.__new__(cls, name, bases, d)

class ImplicitSelf(metaclass=ImplicitSelfMetaclass):
    '''Inherit from this class to have implicit self and cls defined
    within your method bodies, using global namespace munging.'''
    pass

class A(ImplicitSelf):
    '''
    >>> a = A()
    >>> a.m()
    self is <implicit_self.A object at 0x25df8d0>
    cls is <class 'implicit_self.A'>
    >>> self
    Traceback (most recent call last):
      File "<pyshell#38>", line 1, in <module>
        self
    NameError: name 'self' is not defined
    >>> cls
    Traceback (most recent call last):
      File "<pyshell#39>", line 1, in <module>
        cls
    NameError: name 'cls' is not defined
    >>>
    '''

    def m():
        print('self is {}'.format(self))
        print('cls is {}'.format(cls))

### Second approach: using sys._getframe ###

import sys

def resolve_dynamic_var(name):
    frame = sys._getframe(0)
    while frame is not None:
        if name in frame.f_locals:
            return frame.f_locals[name]
        frame = frame.f_back

def self():
    return resolve_dynamic_var('self')

def cls():
    return resolve_dynamic_var('cls')

class SelfClsDescriptor:

    def __init__(self, func):
        self.func = func

    def __get__(self, obj, cls_=None):

        func = self.func

        def decorated(*args, **kw):
            self = obj
            cls = type(obj) if obj is not None else cls_

            return func(*args, **kw)

        return decorated

class SelfClsMetaclass(type):

    def __new__(cls, name, bases, d):
        for key in d:
            if callable(d[key]):
                d[key] = SelfClsDescriptor(d[key])
        return type.__new__(cls, name, bases, d)

class SelfCls(metaclass=SelfClsMetaclass):
    '''Methods found in classes inheriting from this class can call the
    global functions self() and cls() to dynamically resolve their own
    instance object and class, without explicitly declaring them.

    '''
    pass

class B(SelfCls):
    '''
    >>> from implicit_self import B
    >>> b = B()
    >>> b.m()
    self() is <implicit_self.B object at 0x1182cd0>
    cls() is <class 'implicit_self.B'>
    >>>
    '''

    def m():
        print('self() is {}'.format(self()))
        print('cls() is {}'.format(cls()))


text:
.. _mg-mysql:

MySQL
-----

The MySQL database running on the OpenStack controller nodes is a
central component because it is used by almost all the OpenStack
components as their primary data persistence storage. Therefore, it
is critical to monitor the healthiness of this component on each
of the controller nodes in the cluster.

**Process checks**

.. list-table::
   :header-rows: 1
   :widths: 20 20 20 20 20
   :stub-columns: 0
   :class: borderless

   * - Process name
     - Incoming connections
     - Role
     - Dependencies
     - HA mode

   * - mysqld
     - TCP 3306
     - controller
     - storage
     - active/passive

In addition to checking the existence of the process, it is necessary
to check the availability status of the MySQL database. This can be
verified using the command::

  # mysqladmin ping

| **Collected Metrics**

.. list-table::
   :header-rows: 1
   :widths: 20 20 20
   :stub-columns: 0
   :class: borderless

   * - Metrics
     - Source
     - Purpose

   * - bytes received (bytes/sec)
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - bytes sent (bytes/sec)
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - begin operations
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - commit operations
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - delete operations
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - insert operations
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - rollback operations
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - select operations
     - :ref:`poll SQL <poll_SQL>`
     - Alert:
       The absence of select operations could indicate that
       the connection to the database is broken unless the MySQL
       server is in maintenance.

   * - update operations
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - number of queries
     - :ref:`poll SQL <poll_SQL>`
     - :ref:`diag <diag>`

   * - slow queries
     - :ref:`poll SQL <poll_SQL>`
     - diag

   * - Database physical size (Mbyte)
     - poll SQL:

       SELECT table_schema "database", sum( data_length +
       index_length ) / 1024 / 1024 "size_mb" FROM
       information_schema.TABLES GROUP BY table_schema order by 2
       desc;
     - diag

.. _poll_SQL:

These poll SQL metrics can be collected using the following SQL command::

  SHOW GLOBAL STATUS WHERE Variable_name=<NAME>;

See MySQL `server status variables`_ for details.

.. _diag:

.. note::

   You should pay attention to MySQL logs to detect slow queries
   for diagnostic purposes. You can activate slow queries log with
   the following configuration parameters:
   ``slow_query_log=1``, ``long_query_time=5``, and
   ``slow_query_log_file=<filename>``.

| **Metrics related to the MySQL cluster**

The high availability of the MySQL database is supported in
active/passive mode with one master and several slave nodes.
To ensure that the MySQL cluster remains highly available, you should
continuously monitor that slave nodes are ready to take over in case
of a master node failure.

.. list-table::
   :header-rows: 1
   :widths: 20 20 20
   :stub-columns: 0
   :class: borderless

   * - Metrics
     - Source
     - Purpose

   * - wsrep_ready
     - :ref:`SQL <SQL>` possible values: ``ON``/``OFF``
     - Alert: node not ready if ``OFF``

   * - wsrep_cluster_size
     - :ref:`SQL: <SQL>` number of nodes
     - diag

   * - wsrep_replicated_bytes
     - :ref:`SQL: <SQL>` bytes sent to other nodes
     - diag

   * - wsrep_received_bytes
     - :ref:`SQL: <SQL>` bytes received from other nodes
     - diag

   * - wsrep_cluster_status
     - :ref:`SQL: <SQL>`  Primary/Non- Primary/Disconnected
     - Alert: A node is disconnected from the cluster.

   * - wsrep_local_commits
     - :ref:`SQL <SQL>` number of commit
     - diag

   * - errors
     - ``/var/log/mysqld.log``
     - Alert: When a sudden spike of errors is detected.

.. _SQL:

These metrics can be collected with the SQL command::

  SHOW STATUS WHERE Variable_name REGEXP 'wsrep.*';

.. Links
.. _`server status variables`:  http://dev.mysql.com/doc/refman/5.6/en/server-status-variables.html


text:
package renter

import (
	"bytes"
	"io"
	"testing"
	"time"

	"github.com/NebulousLabs/Sia/crypto"
)

// a testFetcher simulates a host. It implements the fetcher interface.
type testFetcher struct {
	sectors   map[crypto.Hash][]byte
	pieceMap  map[uint64][]pieceData
	pieceSize uint64

	nAttempt int // total number of download attempts
	nFetch   int // number of successful download attempts

	// used to simulate real-world conditions
	delay    time.Duration // transfers will take this long
	failRate int           // transfers will randomly fail with probability 1/failRate
}

func (f *testFetcher) pieces(chunkIndex uint64) []pieceData {
	return f.pieceMap[chunkIndex]
}

func (f *testFetcher) fetch(p pieceData) ([]byte, error) {
	f.nAttempt++
	time.Sleep(f.delay)
	// randomly fail
	if n, _ := crypto.RandIntn(f.failRate); n == 0 {
		return nil, io.EOF
	}
	f.nFetch++
	return f.sectors[p.MerkleRoot], nil
}

// TestErasureDownload tests parallel downloading of erasure-coded data. It
// mocks the fetcher interface in order to directly test the downloading
// algorithm.
func TestErasureDownload(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	// generate data
	const dataSize = 777
	data, err := crypto.RandBytes(dataSize)
	if err != nil {
		t.Fatal(err)
	}

	// create Reed-Solomon encoder
	rsc, err := NewRSCode(2, 10)
	if err != nil {
		t.Fatal(err)
	}

	// create hosts
	const pieceSize = 10
	hosts := make([]fetcher, rsc.NumPieces())
	for i := range hosts {
		hosts[i] = &testFetcher{
			sectors:   make(map[crypto.Hash][]byte),
			pieceMap:  make(map[uint64][]pieceData),
			pieceSize: pieceSize,

			delay:    time.Millisecond,
			failRate: 5, // 20% failure rate
		}
	}
	// make one host really slow
	hosts[0].(*testFetcher).delay = 100 * time.Millisecond
	// make one host always fail
	hosts[1].(*testFetcher).failRate = 1

	// upload data to hosts
	r := bytes.NewReader(data) // makes chunking easier
	chunk := make([]byte, pieceSize*rsc.MinPieces())
	var i uint64
	for i = uint64(0); ; i++ {
		_, err := io.ReadFull(r, chunk)
		if err == io.EOF {
			break
		} else if err != nil && err != io.ErrUnexpectedEOF {
			t.Fatal(err)
		}
		pieces, err := rsc.Encode(chunk)
		if err != nil {
			t.Fatal(err)
		}
		for j, p := range pieces {
			root := crypto.MerkleRoot(p)
			host := hosts[j%len(hosts)].(*testFetcher) // distribute evenly
			host.pieceMap[i] = append(host.pieceMap[i], pieceData{
				Chunk:      uint64(i),
				Piece:      uint64(j),
				MerkleRoot: root,
			})
			host.sectors[root] = p
		}
	}

	// check hosts (not strictly necessary)
	err = checkHosts(hosts, rsc.MinPieces(), i)
	if err != nil {
		t.Fatal(err)
	}

	// download data
	d := newFile("foo", rsc, pieceSize, dataSize).newDownload(hosts, "")
	buf := new(bytes.Buffer)
	err = d.run(buf)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(buf.Bytes(), data) {
		t.Fatal("recovered data does not match original")
	}

	/*
		// These metrics can be used to assess the efficiency of the download
		// algorithm.

		totFetch := 0
		for i, h := range hosts {
			h := h.(*testHost)
			t.Logf("Host %2d:  Fetched: %v/%v", i, h.nFetch, h.nAttempt)
			totFetch += h.nAttempt
		}
		t.Log("Optimal fetches:", i*uint64(rsc.MinPieces()))
		t.Log("Total fetches:  ", totFetch)
	*/
}


text:
all: smurfs

smurfs:
	python pysmurfs/setup.py build_ext --inplace
	python smaxflow/setup.py build_ext --inplace


text:
define(function(require){
	var $ = require("jquery");
	var justep = require("$UI/system/lib/justep");

	var Model = function(){
		this.callParent();
	};

	Model.prototype.windowReceiverReceive = function(event){
		var data = this.comp("data");
		data.setValue("begin", event.data.begin);
		data.setValue("end", event.data.end);
	};

	Model.prototype.okBtnClick = function(event){
		var data = this.comp("data");
		this.comp("windowReceiver").windowEnsure({
			"begin" : data.val("begin"),
			"end" : data.val("end")
		});
	};

	return Model;
});


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.jarojas.example.AboutActivity">

    <include android:id="@+id/miActionBar"
        layout="@layout/action_bar"></include>

    <LinearLayout android:layout_below="@id/miActionBar"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/about_title"
            android:textSize="@dimen/about_title"
            android:textAlignment="center"
            tools:layout_editor_absoluteX="3dp"
            tools:layout_editor_absoluteY="2dp" />
        <TextView android:paddingTop="@dimen/about_padding"
            android:textSize="@dimen/about_caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/about_nombre" />
        <TextView
            android:textSize="@dimen/about_value"
            android:paddingLeft="@dimen/about_padding"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Jorge Alberto Rojas Olivares" />
        <TextView android:paddingTop="@dimen/about_padding"
            android:textSize="@dimen/about_caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/about_lives_in" />
        <TextView
            android:textSize="@dimen/about_value"
            android:paddingLeft="@dimen/about_padding"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Un lugar de Ecatepec" />
       <!-- <TextView android:paddingTop="@dimen/about_padding"
            android:textSize="@dimen/about_caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/about_expertise" />
        <TextView
            android:textSize="@dimen/about_value"
            android:paddingLeft="@dimen/about_padding"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SQL y NoSQL, Java(JPA, JTA, JEE, Spring, etc), Web(html,js,css,scss, etc), R&D" />-->
        <TextView android:paddingTop="@dimen/about_padding"
            android:textSize="@dimen/about_caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/about_interests" />
        <TextView
            android:textSize="@dimen/about_value"
            android:paddingLeft="@dimen/about_padding"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Videojuegos, Literatura, Deportes al aire libre, Humor, Nuevas tecnologias." />

    </LinearLayout>
</RelativeLayout>


text:
QValueComboBox::QValueComboBox(QWidget *parent) :
        QComboBox(parent), role(Qt::UserRole)
{
    connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(handleSelectionChanged(int)));
}

QVariant QValueComboBox::value() const
{
    return itemData(currentIndex(), role);
}

void QValueComboBox::setValue(const QVariant &value)
{
    setCurrentIndex(findData(value, role));
}

void QValueComboBox::setRole(int role)
{
    this->role = role;
}

int QValueComboBox::getColor()
{
    BitcoinUnits *pmodel = (BitcoinUnits *) this->model();
    if (pmodel != NULL)
    {
        return pmodel->getColor();
    }
    return BREAKOUT_COLOR_NONE;
}

bool QValueComboBox::setColor(int nColor)
{
    BitcoinUnits *pmodel = (BitcoinUnits *) this->model();
    if (pmodel != NULL)
    {
        return pmodel->setColor(nColor);
    }
    return false;
}

void QValueComboBox::handleSelectionChanged(int idx)
{
    emit valueChanged();
}