text:
import scrapy
from alibb.items import SupItem
import urllib
from scrapy import log
import sys
from json import decoder
from alibb import pooled
reload(sys)
sys.setdefaultencoding('utf-8')
class SupSpider(scrapy.Spider):
    name = 'sup'
    allowed_domains = ['1688.com']
    start_urls = ["http://s.1688.com"]
    zjCity = ['杭州','宁波','温州','绍兴','台州','嘉兴','金华','丽水','湖州','衢州','舟山']
    gzCity = ['广州','深圳','珠海','潮州','中山','东莞','佛山','惠州','汕头','汕尾','韶关','湛江','肇庆','河源','江门','揭阳','茂名','梅州','清远','阳江','云浮']
    provinces = ['广东','浙江','江苏','山东','河北','河南','福建','辽宁','安徽','广西','山西','海南','内蒙','吉林','黑龙','湖北','湖南','江西','宁夏','新疆','青海','陕西','甘肃','四川','云南','贵州','西藏','台湾','香港','澳门']
    conn = pooled.conn

    def parse(self, response):
        print sys.path[0]
        words = []
        with open('words.txt','r') as f:
            for line in f.readlines():
                words.append(line.strip().decode('utf-8'))

        webformat = "http://s.1688.com/selloffer/offer_search.htm?uniqfield=userid&from=marketSearch&n=y&filt=y&sortType=pop"
        params = "&city=%s&province=%s&keywords=%s"

        print '^^^^^^^^^^^', words
        for word in words:
            print u'开始处理word:', word
            for province in self.provinces:
                if province == '浙江':
                    for city in self.zjCity:
                        provinceParam = urllib.quote(u'浙江'.encode('gbk'))
                        cityParam = urllib.quote(city.decode('utf-8').encode('gbk'))
                        wordParam = urllib.quote(word.encode('gbk'))
                        web = params % (cityParam, provinceParam, wordParam)
                        web = webformat + web
                        url = web + "&biztype=1"
                        print '########################################hz 1'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                        url = web + "&biztype=2"
                        print '##################################hz 2'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                        url = web + "&biztype=4"
                        print '#######################################hz 4'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                        url = web + "&biztype=8"
                        print '#############################################hz 8'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                        url = web
                        print '############################################hz all'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                elif province == '广州':
                    for city in self.gzCity:
                        provinceParam = urllib.quote(u'广州'.encode('gbk'))
                        cityParam = urllib.quote(city.decode('utf-8').encode('gbk'))
                        wordParam = urllib.quote(word.decode('utf-8').encode('gbk'))
                        web = params % cityParam, provinceParam, wordParam
                        web = webformat + web
                        url = web + "&biztype=1"
                        print '$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$gz 1'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                        url = web + "&biztype=2"
                        print '$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$gz 2'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                        url = web + "&biztype=4"
                        print '$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$gz 4'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                        url = web + "&biztype=8"
                        print '$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$gz 8'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                        url = web
                        print '$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$gz all'
                        yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)
                else:
                    provinceParam = urllib.quote(province.decode('utf-8').encode('gbk'))
                    wordParam = urllib.quote(word.encode('gbk'))
                    web = "&province=%s&keywords=%s" % (provinceParam, wordParam)
                    web = webformat + web
                    url = web
                    yield scrapy.Request(url, meta={'word':word}, callback=self.parse_search_page)

    def parse_search_page(self, response):
        sel = scrapy.Selector(response)
        links = sel.xpath("//div[@class='sm-offerShopwindow-company fd-clr']").xpath("a[@class='sm-previewCompany sw-mod-previewCompanyInfo']/attribute::href")
        for link in links:
            url = link.extract()
            print 'begin select link ----------------------------', url
            row = SupSpider.conn.get('select * from alibb where website=%s', url)
            if row:
                print u'已经存在该记录,不再处理------------------------------------------->'
                continue
            print '查询详情<<<<<<<<<<<<<<<<<<<<<<<<<<<<'.decode('utf-8'), url, ',word:', response.meta['word']
            yield scrapy.Request(url + "/page/creditdetail.htm", meta={'word':response.meta['word'], 'link': url},callback=self.parse_detail)
            print '11111111111111111111111111111111111111111'
            yield scrapy.Request(url + "/page/creditdetail_remark.htm" , meta={'word':response.meta['word'], 'link':url}, callback=self.parse_exchange_detail)
            print '2222222222222222222222'
        page_max = sel.xpath("//form[@id='sw_mod_pagination_form']//input[@name='beginPage']/@data-max").extract()
        print '\n\n3333333333333333333333333333333pageMax:', page_max

        if page_max:
            print '\n\n\n\n\n翻页\n'.decode('utf-8'),'word:', response.meta['word']
            page_no = response.meta['pageNo'] if 'pageNo' in response.meta else 0
            page_max = int(page_max[0])
            print '\n\npageno:',page_no, '\n\npagemax:',page_max
            if not page_no:
                print '@@@@@@@@@@@@@@@@@@@2打印第二页'.decode('utf-8')
                url = response.url + '&beginPage=2'
                yield scrapy.Request(url, meta={'word': response.meta['word'], 'url': response.url, 'pageNo': 2}, callback=self.parse_search_page)
            elif page_no < page_max:
                print '@@@@@@@@@@@@@@@@@@2222打印下一页'.decode('utf-8'), page_no
                url = response.meta['url']
                page_no += 1
                url = url + '&beginPage=' + str(page_no)
                yield scrapy.Request(url, meta={'word': response.meta['word'], 'url': response.meta['url'], 'pageNo': page_no}, callback=self.parse_search_page)
        else:
            print '\n\n\n444444444444444444444444444444444444'

    def parse_detail(self, response):
        """
        处理详情页
        :param response:
        :return:
        """

        print 'deal with detail page>>>>>>>>>>>>>>>>>>>>>>>>>>>,word:',response.meta['word']

        item = SupItem()
        item['word'] = response.meta['word']

        sel = scrapy.Selector(response)
        name = sel.xpath("//div[@class='archive-base-info fd-clr']//dl/dd[1]/@title").extract()
        # print 'name:', name
        mobile = sel.xpath("//div[@class='archive-base-info fd-clr']//dl/dd[2]/text()").extract()
        # print 'mobile:', mobile
        tel = sel.xpath("//div[@class='archive-base-info fd-clr']//dl/dd[3]/text()").extract()
        # print 'tel:', tel
        level = sel.xpath("//div[@class='medal']/a/img/@src").extract()
        # print 'level:', level
        honest = sel.xpath("//span[@class='state-cxt']/em/text()").extract()
        # print 'honest:', honest
        buildDate = sel.xpath("//div[@class='company-info fd-clr']/ul[1]/li[1]/text()").extract()
        # print buildDate
        area = sel.xpath("//div[@class='company-info fd-clr']/ul[1]/li[2]/span[2]/@title").extract()
        # print area
        address = sel.xpath("//div[@class='company-info fd-clr']/ul[2]/li[2]/text()").extract()
        # print 'address:', address
        company = sel.xpath("//div[@id='archive-base-info']//h2[@class='company-title']/span[1]/@title").extract()
        # print 'company:', company

        item['website'] = response.meta['link'] #str(response.url).encode('utf-8')
        if name:
            item['name'] = name[0]
        if mobile:
            item['mobile'] = mobile[0]
        if tel:
            item['tel'] = tel[0]
        if level:
            item['level'] = level[0]
        if honest:
            item['honest'] = honest[0]
        if buildDate:
            item['buildDate'] = buildDate[0]
        if area:
            item['area'] = area[0]
        if address:
            item['address'] = address[0]
        if company:
            item['company'] = company[0]

        return item

    def parse_exchange_detail(self, response):
        sel = scrapy.Selector(response)
        memberId = sel.xpath("//input[@id='feedbackUid']/@value").extract()
        if not memberId:
            return
        url = """http://rate.1688.com/remark/viewPubRemark/view.json?callback=f&_input_charset=UTF-8&memberId=%s&tradeType=ALL&memberRole=seller&needDsr=false&showList=false"""
        url = url % memberId[0]
        yield scrapy.Request(url, meta={'word': response.meta['word'], 'link': response.meta['link']}, callback=self.parse_rate)

        # sel = scrapy.Selector(response)
        #
        # tr = sel.xpath("//dd[@class='pj-score-right module-a']//table/tbody/tr[6]")
        # lastOneWeek = tr.xpath("td[2]/a/text()").extract()
        # lastOneMonth = tr.xpath("td[3]/a/text()").extract()
        # lastSixMonth = tr.xpath("td[4]/a/text()").extract()
        # beforeHalfYear = tr.xpath("td[5]/a/text()").extract()
        # total = tr.xpath("td[6]/a/text()").extract()
        #
        # item = SupItem()
        # item['website'] = response.meta['link']
        # item['word'] = response.meta['word']
        # if lastOneWeek:
        #     item['lastOneWeek'] = lastOneWeek[0]
        # if lastOneMonth:
        #     item['lastOneMonth'] = lastOneMonth[0]
        # if lastSixMonth:
        #     item['lastSixMonth'] = lastSixMonth[0]
        # if beforeHalfYear:
        #     item['beforeHalfYear'] = beforeHalfYear[0]
        # if total:
        #     item['total'] = total
        #
        # return item
        # print "查看交易记录".decode('utf-8')

    def parse_rate(self, response):
        item = SupItem()
        item['website'] = response.meta['link']
        item['word'] = response.meta['word']
        json = response.body[response.body.find('{'):-2]
        print 'json->>>>>>>>>>>>>>>>>>>>>>>', json
        jsonD = decoder.JSONDecoder()
        djson = jsonD.decode(json)
        item['lastOneWeek'] = djson['data']['starStatisticsList'][5]['weekly']
        item['lastOneMonth'] = djson['data']['starStatisticsList'][5]['monthly']
        item['lastSixMonth'] = djson['data']['starStatisticsList'][5]['halfYearly']
        item['beforeHalfYear'] = djson['data']['starStatisticsList'][5]['halfYearBefore']
        item['total'] = djson['data']['starStatisticsList'][5]['totals']
        return item


text:
// Author: morlovich@google.com (Maksim Orlovich)
//
// A fetcher that talks to mod_spdy for requests matching a certain
// domain (and passes the rest to fallthrough fetcher).

#ifndef NET_INSTAWEB_APACHE_MOD_SPDY_FETCHER_H_
#define NET_INSTAWEB_APACHE_MOD_SPDY_FETCHER_H_

#include "net/instaweb/http/public/url_async_fetcher.h"

#include "httpd.h"

#include "net/instaweb/apache/interface_mod_spdy.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"

struct request_rec;
struct spdy_slave_connection_factory;

namespace net_instaweb {

class AsyncFetch;
class MessageHandler;
class ModSpdyFetchController;
class RewriteDriver;
class Statistics;

class ModSpdyFetcher : public UrlAsyncFetcher {
 public:
  ModSpdyFetcher(ModSpdyFetchController* controller,
                 StringPiece url, RewriteDriver* driver,
                 spdy_slave_connection_factory* connection_factory);
  virtual ~ModSpdyFetcher();

  // Initializes various filters this fetcher needs for operation.
  // This must be from within a register hooks implementation.
  static void Initialize();

  // This must be called for every statistics object in use before using this.
  static void InitStats(Statistics* statistics);

  virtual void Fetch(const GoogleString& url,
                     MessageHandler* message_handler,
                     AsyncFetch* fetch);

  // Returns true if a ModSpdyFetcher should be installed as a session fetcher
  // on a given connection.
  static bool ShouldUseOn(request_rec* req);

  // TODO(morlovich): Implement virtual void ShutDown(),
  // and give a good story on session fetchers and fetcher shutdowns in general.

 private:
  friend class ModSpdyFetchController;

  // The actual implementation of fetching code, normally called by
  // ModSpdyFetchController.
  void BlockingFetch(const GoogleString& url,
                     ModSpdyFetchController* controller,
                     Statistics* stats,
                     MessageHandler* message_handler,
                     AsyncFetch* fetch);

  ModSpdyFetchController* controller_;
  UrlAsyncFetcher* fallback_fetcher_;
  Statistics* stats_;
  GoogleString own_origin_;  // empty if we couldn't figure it out.
  spdy_slave_connection_factory* connection_factory_;

  DISALLOW_COPY_AND_ASSIGN(ModSpdyFetcher);
};

}  // namespace net_instaweb

#endif  // NET_INSTAWEB_APACHE_MOD_SPDY_FETCHER_H_

redpajama_set_name: RedPajamaGithub


text:
package software.amazon.awssdk.codegen.model.service;

public class ContextParam {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v11/services/batch_job_service.proto

package com.google.ads.googleads.v11.services;

public interface MutateBatchJobResponseOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v11.services.MutateBatchJobResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * The result for the mutate.
   *

   *
   * .google.ads.googleads.v11.services.MutateBatchJobResult result = 1;
   * @return Whether the result field is set.
   */
  boolean hasResult();
  /**
   *

   * The result for the mutate.
   *

   *
   * .google.ads.googleads.v11.services.MutateBatchJobResult result = 1;
   * @return The result.
   */
  com.google.ads.googleads.v11.services.MutateBatchJobResult getResult();
  /**
   *

   * The result for the mutate.
   *

   *
   * .google.ads.googleads.v11.services.MutateBatchJobResult result = 1;
   */
  com.google.ads.googleads.v11.services.MutateBatchJobResultOrBuilder getResultOrBuilder();
}


text:
<?php

namespace Cecil\Assets;

use Cecil\Builder;
use Cecil\Collection\Page\Page;
use Cecil\Config;
use Cecil\Renderer\Page as PageRenderer;
use Cecil\Util;
use Cocur\Slugify\Slugify;

class Url
{
    /** @var Builder */
    protected $builder;

    /** @var Config */
    protected $config;

    /** @var Page|Asset|string|null */
    protected $value;

    /** @var array */
    protected $options;

    /** @var string */
    protected $baseurl;

    /** @var string */
    protected $url;

    /** @var Slugify */
    private static $slugifier;

    /**
     * Creates an URL from string, Page or Asset.
     *
     * $options[
     *     'canonical' => true,
     *     'format'    => 'json',
     * ];
     *
     * @param Builder                $builder
     * @param Page|Asset|string|null $value
     * @param array|null             $options
     */
    public function __construct(Builder $builder, $value, array $options = null)
    {
        $this->builder = $builder;
        $this->config = $builder->getConfig();
        if (!self::$slugifier instanceof Slugify) {
            self::$slugifier = Slugify::create(['regexp' => Page::SLUGIFY_PATTERN]);
        }
        $this->baseurl = (string) $this->config->get('baseurl');

        // handles options
        $canonical = null;
        $format = null;
        extract(is_array($options) ? $options : [], EXTR_IF_EXISTS);

        // canonical URL?
        $base = '';
        if ((bool) $this->config->get('canonicalurl') || $canonical === true) {
            $base = rtrim($this->baseurl, '/');
        }
        if ($canonical === false) {
            $base = '';
        }

        // value is empty (ie: `url()`)
        if (is_null($value) || empty($value) || $value == '/') {
            $this->url = $base.'/';

            return;
        }

        switch (true) {
            // Page
            case $value instanceof Page:
                if (!$format) {
                    $format = $value->getVariable('output');
                    if (is_array($value->getVariable('output'))) {
                        $format = $value->getVariable('output')[0];
                    }
                    if (!$format) {
                        $format = 'html';
                    }
                }
                $this->url = $base.'/'.ltrim((new PageRenderer($this->config))->getUrl($value, $format), '/');
                break;
            // Asset
            case $value instanceof Asset:
                $asset = $value;
                $this->url = $base.'/'.ltrim($asset['path'], '/');
                break;
            // string
            case is_string($value):
                // potential Page ID
                $pageId = self::$slugifier->slugify($value);
                switch (true) {
                    // External URL
                    case Util\Url::isUrl($value):
                        $this->url = $value;
                        break;
                    // Page ID as string
                    case $this->builder->getPages()->has($pageId):
                        $page = $this->builder->getPages()->get($pageId);
                        $this->url = new self($this->builder, $page, $options);
                        break;
                    // asset as string
                    case false !== strpos($value, '.') ? true : false:
                        $this->url = $base.'/'.ltrim($value, '/');
                        break;
                    // others cases?
                    default:
                        // others cases
                        $this->url = $base.'/'.$value;
                }
        }
    }

    /**
     * Returns URL.
     */
    public function __toString(): string
    {
        return $this->url;
    }

    /**
     * Returns URL.
     */
    public function getUrl(): string
    {
        return $this->__toString();
    }
}


text:
install:
	npm install
	./node_modules/component/bin/component install --dev

test:
	npm test
	./node_modules/component/bin/component build --dev

.PHONY: install


text:
class AppListControllerDelegate;
class Profile;

namespace app_list {
class AppContextMenuDelegate;
}

class ArcAppContextMenu : public app_list::AppContextMenu {
 public:
  ArcAppContextMenu(app_list::AppContextMenuDelegate* delegate,
                    Profile* profile,
                    const std::string& app_id,
                    AppListControllerDelegate* controller);
  ~ArcAppContextMenu() override;

  // AppListContextMenu overrides:
  void BuildMenu(ui::SimpleMenuModel* menu_model) override;

  // ui::SimpleMenuModel::Delegate overrides:
  void ExecuteCommand(int command_id, int event_flags) override;

 private:
  void IsAppOpen();
  void UninstallPackage();
  void ShowPackageInfo();

  bool CanBeUninstalled() const;
  bool IsShortcut() const;

  DISALLOW_COPY_AND_ASSIGN(ArcAppContextMenu);
};

#endif  // CHROME_BROWSER_UI_APP_LIST_ARC_ARC_APP_CONTEXT_MENU_H_


text:
[![Build Status][ci-img]][ci] [![BrowserStack Status][browserstack-img]][browserstack]

Style file input element.

## Install

```sh
npm install style-file-input --save
```

## Usage

**Markup**

```html
<input type="file" />
```

**Style**

```css
@import url('style-file-input');
```

If you use [PostCSS](https://github.com/postcss/postcss) and [postcss-import](https://github.com/postcss/postcss-import) plugin, it will automatically use provided [default styling](https://github.com/niksy/style-file-input/blob/master/index.css).

**Client-side functionality**

```js
const stylefileinput = require('style-file-input');
const element = document.querySelector('input[type="file"]');
const instance = stylefileinput(element);
```

## API

### stylefileinput(element[, options])

Returns: `Object`

#### element

Type: `Element`

Element on which to apply changes.

#### options

Type: `Object`

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `browseButtonLabel` | `String` | `'Browse'` | Button label for browse action. |
| `changeButtonLabel` | `String` | `'Change'` | Button label for change action. |
| `noFileSelectedText` | `String` | `'No file selected'` | Default input value placeholder. |
| `wrapperClass` | `String` | `'kist-Stylefileinput'` | Wrapper class. |
| `inputClass` | `String` | `'kist-Stylefileinput-input'` | Input class. |
| `buttonClass` | `String` | `'kist-Stylefileinput-button'` | Browse/change button class. |
| `textClass` | `String` | `'kist-Stylefileinput-text'` | Input value placeholder class. |

### instance.destroy()

Destroy instance.

## Browser support

Tested in IE9+ and all modern browsers.

## Caveats

* Opera Mini doesn't fire `change` event when input value is changed so it won're replace default text.

## Acknowledgments

* Based on [Filament Group's jQuery Custom File Input](https://github.com/filamentgroup/jQuery-Custom-File-Input).

## Test

For local automated tests, run `npm run test:automated:local` (append `:watch` for watcher support).

For local integration tests, run `npm run test:integration:local` (append `:watch` for watcher support).

For manual tests, run `npm run test:manual:local` and open <http://localhost:9000/> in your browser.

## License

MIT © [Ivan Nikolić](http://ivannikolic.com)
MIT © [Filament Group](http://www.filamentgroup.com/)

[ci]: https://travis-ci.org/niksy/style-file-input
[ci-img]: https://travis-ci.org/niksy/style-file-input.svg?branch=master
[browserstack]: https://www.browserstack.com/
[browserstack-img]: https://www.browserstack.com/automate/badge.svg?badge_key=OGNwUys4NUZVNVJleUpHTDNORGVxamhuZitSVk9zbEVJa2pCajFnS2FVOD0tLXdxTW16Nm1WTGphS1dLQXE1aW1EUmc9PQ==--0088ec8799d554c805b2d93c5aa56cc24d2d592d


text:
package nl.talsmasoftware.context.clearable;

import nl.talsmasoftware.context.Context;
import nl.talsmasoftware.context.ContextManager;

public class DummyManagerOfClearableContext implements ContextManager<String> {
    private static final ThreadLocal<DummyContext> CTX = new ThreadLocal<DummyContext>();

    public Context<String> getActiveContext() {
        return CTX.get();
    }

    public Context<String> initializeNewContext(String value) {
        return new DummyContext(value);
    }

    private static class DummyContext implements Context<String>, Clearable {
        private final DummyContext previous;
        private String value;

        private DummyContext(String value) {
            this.previous = CTX.get();
            this.value = value;
            CTX.set(this);
        }

        public String getValue() {
            return value;
        }

        /**
         * Only for testing! DO NOT COPY! This is not a safe implementation.
         * <p>
         * Please see AbstractThreadLocalContext for reference code if you wish manage a stack of contexts!
         */
        public void close() {
            CTX.set(previous);
            this.value = null;
        }

        public void clear() {
            CTX.remove();
        }

    }
}


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueState;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;

import java.util.HashMap;
import java.util.Map;

public class CapacitySchedulerConfiguration extends Configuration {

  private static final Log LOG =
      LogFactory.getLog(CapacitySchedulerConfiguration.class);

  private static final String CS_CONFIGURATION_FILE = "capacity-scheduler.xml";

  @Private
  public static final String PREFIX = "yarn.scheduler.capacity.";

  @Private
  public static final String DOT = ".";

  @Private
  public static final String MAXIMUM_APPLICATIONS_SUFFIX =
      "maximum-applications";

  @Private
  public static final String MAXIMUM_SYSTEM_APPLICATIONS =
      PREFIX + MAXIMUM_APPLICATIONS_SUFFIX;

  @Private
  public static final String MAXIMUM_AM_RESOURCE_SUFFIX =
      "maximum-am-resource-percent";

  @Private
  public static final String MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT =
      PREFIX + MAXIMUM_AM_RESOURCE_SUFFIX;

  @Private
  public static final String QUEUES = "queues";

  @Private
  public static final String CAPACITY = "capacity";

  @Private
  public static final String MAXIMUM_CAPACITY = "maximum-capacity";

  @Private
  public static final String USER_LIMIT = "minimum-user-limit-percent";

  @Private
  public static final String USER_LIMIT_FACTOR = "user-limit-factor";

  @Private
  public static final String STATE = "state";

  @Private
  public static final int DEFAULT_MAXIMUM_SYSTEM_APPLICATIIONS = 10000;

  @Private
  public static final float
      DEFAULT_MAXIMUM_APPLICATIONMASTERS_RESOURCE_PERCENT = 0.1f;

  @Private
  public static final float UNDEFINED = -1;

  @Private
  public static final float MINIMUM_CAPACITY_VALUE = 0;

  @Private
  public static final float MAXIMUM_CAPACITY_VALUE = 100;

  @Private
  public static final float DEFAULT_MAXIMUM_CAPACITY_VALUE = -1.0f;

  @Private
  public static final int DEFAULT_USER_LIMIT = 100;

  @Private
  public static final float DEFAULT_USER_LIMIT_FACTOR = 1.0f;

  @Private
  public static final String ALL_ACL = "*";

  @Private
  public static final String NONE_ACL = " ";

  @Private
  public static final String ENABLE_USER_METRICS =
      PREFIX + "user-metrics.enable";
  @Private
  public static final boolean DEFAULT_ENABLE_USER_METRICS = false;

  /**
   * ResourceComparator for scheduling.
   */
  @Private
  public static final String RESOURCE_CALCULATOR_CLASS =
      PREFIX + "resource-calculator";

  @Private
  public static final Class<? extends ResourceCalculator>
      DEFAULT_RESOURCE_CALCULATOR_CLASS = DefaultResourceCalculator.class;

  @Private
  public static final String ROOT = "root";

  @Private
  public static final String NODE_LOCALITY_DELAY =
      PREFIX + "node-locality-delay";

  @Private
  public static final int DEFAULT_NODE_LOCALITY_DELAY = -1;

  @Private
  public static final String SCHEDULE_ASYNCHRONOUSLY_PREFIX =
      PREFIX + "schedule-asynchronously";

  @Private
  public static final String SCHEDULE_ASYNCHRONOUSLY_ENABLE =
      SCHEDULE_ASYNCHRONOUSLY_PREFIX + ".enable";

  @Private
  public static final boolean DEFAULT_SCHEDULE_ASYNCHRONOUSLY_ENABLE = false;

  public CapacitySchedulerConfiguration() {
    this(new Configuration());
  }

  public CapacitySchedulerConfiguration(Configuration configuration) {
    this(configuration, true);
  }

  public CapacitySchedulerConfiguration(Configuration configuration,
      boolean useLocalConfigurationProvider) {
    super(configuration);
    if (useLocalConfigurationProvider) {
      addResource(CS_CONFIGURATION_FILE);
    }
  }

  private String getQueuePrefix(String queue) {
    String queueName = PREFIX + queue + DOT;
    return queueName;
  }

  public int getMaximumSystemApplications() {
    int maxApplications = getInt(MAXIMUM_SYSTEM_APPLICATIONS,
        DEFAULT_MAXIMUM_SYSTEM_APPLICATIIONS);
    return maxApplications;
  }

  public float getMaximumApplicationMasterResourcePercent() {
    return getFloat(MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT,
        DEFAULT_MAXIMUM_APPLICATIONMASTERS_RESOURCE_PERCENT);
  }

  /**
   * Get the maximum applications per queue setting.
   *
   * @param queue
   *     name of the queue
   * @return setting specified or -1 if not set
   */
  public int getMaximumApplicationsPerQueue(String queue) {
    int maxApplicationsPerQueue =
        getInt(getQueuePrefix(queue) + MAXIMUM_APPLICATIONS_SUFFIX,
            (int) UNDEFINED);
    return maxApplicationsPerQueue;
  }

  /**
   * Get the maximum am resource percent per queue setting.
   *
   * @param queue
   *     name of the queue
   * @return per queue setting or defaults to the global am-resource-percent
   * setting if per queue setting not present
   */
  public float getMaximumApplicationMasterResourcePerQueuePercent(
      String queue) {
    return getFloat(getQueuePrefix(queue) + MAXIMUM_AM_RESOURCE_SUFFIX,
        getMaximumApplicationMasterResourcePercent());
  }

  public float getCapacity(String queue) {
    float capacity = queue.equals("root") ? 100.0f :
        getFloat(getQueuePrefix(queue) + CAPACITY, UNDEFINED);
    if (capacity < MINIMUM_CAPACITY_VALUE ||
        capacity > MAXIMUM_CAPACITY_VALUE) {
      throw new IllegalArgumentException("Illegal " +
          "capacity of " + capacity + " for queue " + queue);
    }
    LOG.debug("CSConf - getCapacity: queuePrefix=" + getQueuePrefix(queue) +
        ", capacity=" + capacity);
    return capacity;
  }

  public void setCapacity(String queue, float capacity) {
    if (queue.equals("root")) {
      throw new IllegalArgumentException(
          "Cannot set capacity, root queue has a fixed capacity of 100.0f");
    }
    setFloat(getQueuePrefix(queue) + CAPACITY, capacity);
    LOG.debug("CSConf - setCapacity: queuePrefix=" + getQueuePrefix(queue) +
        ", capacity=" + capacity);
  }

  public float getMaximumCapacity(String queue) {
    float maxCapacity = getFloat(getQueuePrefix(queue) + MAXIMUM_CAPACITY,
        MAXIMUM_CAPACITY_VALUE);
    maxCapacity = (maxCapacity == DEFAULT_MAXIMUM_CAPACITY_VALUE) ?
        MAXIMUM_CAPACITY_VALUE : maxCapacity;
    return maxCapacity;
  }

  public void setMaximumCapacity(String queue, float maxCapacity) {
    if (maxCapacity > MAXIMUM_CAPACITY_VALUE) {
      throw new IllegalArgumentException("Illegal " +
          "maximum-capacity of " + maxCapacity + " for queue " + queue);
    }
    setFloat(getQueuePrefix(queue) + MAXIMUM_CAPACITY, maxCapacity);
    LOG.debug("CSConf - setMaxCapacity: queuePrefix=" + getQueuePrefix(queue) +
        ", maxCapacity=" + maxCapacity);
  }

  public int getUserLimit(String queue) {
    int userLimit =
        getInt(getQueuePrefix(queue) + USER_LIMIT, DEFAULT_USER_LIMIT);
    return userLimit;
  }

  public void setUserLimit(String queue, int userLimit) {
    setInt(getQueuePrefix(queue) + USER_LIMIT, userLimit);
    LOG.debug("here setUserLimit: queuePrefix=" + getQueuePrefix(queue) +
        ", userLimit=" + getUserLimit(queue));
  }

  public float getUserLimitFactor(String queue) {
    float userLimitFactor = getFloat(getQueuePrefix(queue) + USER_LIMIT_FACTOR,
        DEFAULT_USER_LIMIT_FACTOR);
    return userLimitFactor;
  }

  public void setUserLimitFactor(String queue, float userLimitFactor) {
    setFloat(getQueuePrefix(queue) + USER_LIMIT_FACTOR, userLimitFactor);
  }

  public QueueState getState(String queue) {
    String state = get(getQueuePrefix(queue) + STATE);
    return (state != null) ? QueueState.valueOf(state.toUpperCase()) :
        QueueState.RUNNING;
  }

  private static String getAclKey(QueueACL acl) {
    return "acl_" + acl.toString().toLowerCase();
  }

  public AccessControlList getAcl(String queue, QueueACL acl) {
    String queuePrefix = getQueuePrefix(queue);
    // The root queue defaults to all access if not defined
    // Sub queues inherit access if not defined
    String defaultAcl = queue.equals(ROOT) ? ALL_ACL : NONE_ACL;
    String aclString = get(queuePrefix + getAclKey(acl), defaultAcl);
    return new AccessControlList(aclString);
  }

  public void setAcl(String queue, QueueACL acl, String aclString) {
    String queuePrefix = getQueuePrefix(queue);
    set(queuePrefix + getAclKey(acl), aclString);
  }

  public Map<QueueACL, AccessControlList> getAcls(String queue) {
    Map<QueueACL, AccessControlList> acls =
        new HashMap<QueueACL, AccessControlList>();
    for (QueueACL acl : QueueACL.values()) {
      acls.put(acl, getAcl(queue, acl));
    }
    return acls;
  }

  public void setAcls(String queue, Map<QueueACL, AccessControlList> acls) {
    for (Map.Entry<QueueACL, AccessControlList> e : acls.entrySet()) {
      setAcl(queue, e.getKey(), e.getValue().getAclString());
    }
  }

  public String[] getQueues(String queue) {
    LOG.debug(
        "CSConf - getQueues called for: queuePrefix=" + getQueuePrefix(queue));
    String[] queues = getStrings(getQueuePrefix(queue) + QUEUES);
    LOG.debug("CSConf - getQueues: queuePrefix=" + getQueuePrefix(queue) +
        ", queues=" +
        ((queues == null) ? "" : StringUtils.arrayToString(queues)));
    return queues;
  }

  public void setQueues(String queue, String[] subQueues) {
    set(getQueuePrefix(queue) + QUEUES, StringUtils.arrayToString(subQueues));
    LOG.debug("CSConf - setQueues: qPrefix=" + getQueuePrefix(queue) +
        ", queues=" + StringUtils.arrayToString(subQueues));
  }

  public Resource getMinimumAllocation() {
    int minimumMemory =
        getInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB,
            YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB);
    int minimumCores =
        getInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES,
            YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES);
    return Resources.createResource(minimumMemory, minimumCores);
  }

  public Resource getMaximumAllocation() {
    int maximumMemory =
        getInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB,
            YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB);
    int maximumCores =
        getInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES,
            YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES);
    return Resources.createResource(maximumMemory, maximumCores);
  }

  public boolean getEnableUserMetrics() {
    return getBoolean(ENABLE_USER_METRICS, DEFAULT_ENABLE_USER_METRICS);
  }

  public int getNodeLocalityDelay() {
    int delay = getInt(NODE_LOCALITY_DELAY, DEFAULT_NODE_LOCALITY_DELAY);
    return (delay == DEFAULT_NODE_LOCALITY_DELAY) ? 0 : delay;
  }

  public ResourceCalculator getResourceCalculator() {
    return ReflectionUtils.newInstance(
        getClass(RESOURCE_CALCULATOR_CLASS, DEFAULT_RESOURCE_CALCULATOR_CLASS,
            ResourceCalculator.class), this);
  }

  public boolean getUsePortForNodeName() {
    return getBoolean(YarnConfiguration.RM_SCHEDULER_INCLUDE_PORT_IN_NODE_NAME,
        YarnConfiguration.DEFAULT_RM_SCHEDULER_USE_PORT_FOR_NODE_NAME);
  }

  public void setResourceComparator(
      Class<? extends ResourceCalculator> resourceCalculatorClass) {
    setClass(RESOURCE_CALCULATOR_CLASS, resourceCalculatorClass,
        ResourceCalculator.class);
  }

  public boolean getScheduleAynschronously() {
    return getBoolean(SCHEDULE_ASYNCHRONOUSLY_ENABLE,
        DEFAULT_SCHEDULE_ASYNCHRONOUSLY_ENABLE);
  }

  public void setScheduleAynschronously(boolean async) {
    setBoolean(SCHEDULE_ASYNCHRONOUSLY_ENABLE, async);
  }

}


text:
namespace fst::ui {
namespace detail {
  template <typename _Tp>
  class rect {
  public:
    using value_type = _Tp;
    static_assert(std::is_arithmetic<value_type>::value, "value_type is not arithmetic");
    using size_type = detail::size<value_type>;
    using point_type = detail::point<value_type>;

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnested-anon-types"
#pragma clang diagnostic ignored "-Wgnu-anonymous-struct"
#endif

    union {
      point_type position;
      struct {
        value_type x, y;
      };
    };

    union {
      size_type size;
      struct {
        value_type width, height;
      };
    };

#if defined(__clang__)
#pragma clang diagnostic pop
#endif

    inline constexpr rect(const point_type& pt_ = point_type(0, 0), const size_type& size_ = size_type(0, 0))
        : position(pt_)
        , size(size_) {}

    inline constexpr rect(value_type x, value_type y, value_type w, value_type h)
        : position(x, y)
        , size(w, h) {}

    inline constexpr rect(value_type x, value_type y, const size_type& size_)
        : position(x, y)
        , size(size_) {}

    inline constexpr rect(const rect& r)
        : position(r.position)
        , size(r.size) {}

    template <typename T>
    inline constexpr rect(const rect<T>& r)
        : position(r.position.template cast<value_type>())
        , size(r.size.template cast<value_type>()) {}

    inline constexpr rect& operator=(const rect& r) {
      position = r.position;
      size = r.size;
      return *this;
    }

    inline constexpr static rect from_bottom_left(value_type x, value_type y, value_type w, value_type h) {
      return rect(x, y - h, w, h);
    }

    template <typename P>
    inline constexpr rect<P> cast() const {
      return rect<P>(position.template cast<P>(), size.template cast<P>());
    }

    inline constexpr rect operator+(const rect& rect) const {
      return rect(position.x + rect.position.x, position.y + rect.position.y, size.width + rect.size.width,
          size.height + rect.size.height);
    }

    inline constexpr rect operator-(const rect& rect) const {
      return rect(position.x - rect.position.x, position.y - rect.position.y, size.width - rect.size.width,
          size.height - rect.size.height);
    }

    inline constexpr bool operator==(const rect& rect) const { return position == rect.position && size == rect.size; }
    inline constexpr bool operator!=(const rect& rect) const { return !operator==(rect); }

    inline constexpr value_type left() const { return position.x; }
    inline constexpr value_type right() const { return position.x + size.width; }
    inline constexpr value_type top() const { return position.y; }

    inline constexpr value_type bottom() const { return position.y + size.height; }

    inline constexpr bool intersect(const rect& r) const {
      return left() > r.right() || r.left() > right() || top() < r.bottom() || r.top() < bottom();
    }

    template <typename _PointValueType>
    inline constexpr bool contains(const detail::point<_PointValueType>& pos) const {
      return pos.x >= position.x && pos.x <= position.x + size.width && pos.y >= position.y
          && pos.y <= position.y + size.height;
    }

    inline constexpr rect get_interior_rect(const point_type& point) const {
      return rect(position.x + point.x, position.y + point.y, size.width - (value_type)(2.0 * point.x),
          size.height - (value_type)(2.0 * point.y));
    }

     inline constexpr rect get_exterior_rect(const point_type& point) const {
      return rect(position.x - point.x, position.y - point.y, size.width + (value_type)(2.0 * point.x),
          size.height + (value_type)(2.0 * point.y));
    }

    inline constexpr void reduce(const point_type& point) {
      position.x += point.x;
      position.y += point.y;
      size.width -= (value_type)(2.0 * point.x);
      size.height -= (value_type)(2.0 * point.y);
    }

    inline constexpr rect reduced(const point_type& point) const {
      return rect(x + point.x, y + point.y, width - (value_type)(2.0 * point.x), height - (value_type)(2.0 * point.y));
    }

    inline constexpr rect reduced_from_left_percent(float v) const { return reduced_from_left(width * (float)v); }
    inline constexpr rect reduced_from_right_percent(float v) const { return reduced_from_right(width * (float)v); }

    inline constexpr rect reduced_from_left(value_type x) const {
      return rect(position.x + x, position.y, size.width - x, size.height);
    }
    inline constexpr rect reduced_from_right(value_type x) const {
      return rect(position.x, position.y, size.width - x, size.height);
    }
    inline constexpr rect reduced_from_top(value_type y) const {
      return rect(position.x, position.y + y, size.width, size.height - y);
    }
    inline constexpr rect reduced_from_bottom(value_type y) const {
      return rect(position.x, position.y, size.width, size.height - y);
    }

    inline constexpr point_type in_middle(const size_type& s) const {
      return point_type(x + (width - s.width) * 0.5, y + (height - s.height) * 0.5);
    }

    inline constexpr point_type top_left() const { return position; }
    //  point_type top_right() const { return point_type(position.x + size.width, position.y); }
    inline constexpr point_type top_right(value_type dx = 0, value_type dy = 0) const {
      return point_type(position.x + size.width + dx, position.y + dy);
    }
    inline constexpr point_type bottom_left() const { return point_type(position.x, position.y + size.height); }
    inline constexpr point_type bottom_right() const {
      return point_type(position.x + size.width, position.y + size.height);
    }
    inline constexpr point_type middle() const {
      return point_type(position.x + size.width * 0.5, position.y + size.height * 0.5);
    }
    inline constexpr point_type next_left(value_type delta) const { return point_type(position.x, position.y - delta); }
    inline constexpr point_type next_right(value_type delta) const {
      return point_type(position.x + size.width + delta, position.y);
    }
    inline constexpr point_type next_down(value_type delta) const {
      return point_type(position.x, position.y + size.height + delta);
    }
    inline constexpr point_type next_up(value_type delta) const { return point_type(position.x, position.y - delta); }

    inline constexpr void clip_to(const rect& rect) {
      x = fst::maximum(rect.x, x);
      y = fst::maximum(rect.y, y);
      width = fst::minimum(rect.width, width);
      height = fst::minimum(rect.height, height);
    }

    friend std::ostream& operator<<(std::ostream& stream, const rect& rect) {
      stream << rect.position.x << ", " << rect.position.y << ", " << rect.size.width << ", " << rect.size.height;
      return stream;
    }
  };
} // namespace detail.

using rect = detail::rect<int>;
using frect = detail::rect<float>;
} // namespace fst::ui.


text:
import requests
import csv
import os
import logging
from dateutil import parser
from lxml import etree
from suds.transport import TransportError
from suds.client import Client
from xml.sax._exceptions import SAXParseException
import matplotlib.pyplot as plt

from hs_core import hydroshare
from owslib.waterml.wml11 import WaterML_1_1 as wml11
from owslib.waterml.wml10 import WaterML_1_0 as wml10

logger = logging.getLogger(__name__)
logging.getLogger('suds').setLevel(logging.INFO)
BLANK_FIELD_STRING = ""

def wmlParse(response, ver=11):
    if ver == 11:
        return wml11(response).response
    elif ver == 10:
        return wml10(response).response
    else:
        raise Exception("This wml version is not supported by OWSLib")

def wmlVersionFromSoapURL(wsdl_url):
    ver = -1
    if "1_0." in wsdl_url.lower():
        ver = 10
    elif "1_1." in wsdl_url.lower():
        ver = 11
    elif "2_0." in wsdl_url.lower():
        ver = 20
    else:
        ver = -1
    return ver

def check_url_and_version(wsdl_url):
    if not wsdl_url.lower().endswith('.asmx?wsdl'):
        if not wsdl_url.lower().endswith('.php?wsdl'):
            raise Exception("invalid soap endpoint")
    return wmlVersionFromSoapURL(wsdl_url)

def connect_wsdl_url(wsdl_url):
    try:
        client = Client(wsdl_url)
    except TransportError:
        raise Exception('Url not found')
    except ValueError:
        raise Exception('Invalid url')  # ought to be a 400, but no page implemented for that
    except SAXParseException:
        raise Exception("The correct url format ends in '.asmx?WSDL'.")
    except:
        raise Exception("Unexpected error")
    return client

def get_wml_version_from_xml_tag(root):
    wml_version = -1
    for element in root.iter():
        if '{http://www.opengis.net/waterml/2.0}collection' in element.tag.lower():
            wml_version = 20
            break
        elif '{http://www.cuahsi.org/waterml/1.1/}timeseriesresponse' in element.tag.lower():
            wml_version = 11
            break
        elif '{http://www.cuahsi.org/waterml/1.0/}timeseriesresponse' in element.tag.lower():
            wml_version = 10
            break
    return wml_version

def sites_from_soap(wsdl_url, locations='[:]'):
    try:
        client = connect_wsdl_url(wsdl_url)
        wml_ver = check_url_and_version(wsdl_url)
        response = None
        if wml_ver == 11:
            response = client.service.GetSites(locations)
        elif wml_ver == 10:
            response = client.service.GetSitesXml(locations)
        response = response.encode('utf-8')
        wml_sites = wmlParse(response, wml_ver)
        counter = 0
        sites_list = []
        for site in wml_sites.sites:
            siteName = site.name
            siteCode = site.codes[0]
            # netWork = site.site_info.net_work
            counter += 1
            # sites_list.append("%s. %s [%s:%s]" % (str(counter), siteName, netWork, siteCode))
            sites_list.append("%s. %s [network:%s]" % (str(counter), siteName, siteCode))
    except Exception as e:
        logger.exception("sites_from_soap: %s" % (e.message))
        raise e
    return sites_list

# get variable name list
def site_info_from_soap(wsdl_url, **kwargs):
    try:
        site = kwargs['site']
        index = site.rfind(" [")
        site = site[index+2:len(site)-1]
        wml_ver = check_url_and_version(wsdl_url)
        client = connect_wsdl_url(wsdl_url)
        variables_list = []

        response = client.service.GetSiteInfo(site)
        response = response.encode('utf-8')
        wml_siteinfo = wmlParse(response, wml_ver)
        counter = 0
        for series in wml_siteinfo.sites[0].series_catalogs[0].series:
            wml_variable = series.variable
            variable_name = wml_variable.variable_name
            variable_code = wml_variable.variable_code
            method_id = series.method_id if series.method_id is not None else "Unknown"
            source_id = series.source_id if series.source_id is not None else "Unknown"
            value_count = series.value_count
            quality_control_level_id = series.quality_control_level_id if series.quality_control_level_id is not None else "Unknown"
            start_date = series.begin_date_time
            end_date = series.end_date_time
            counter += 1
            variables_list.append("%s. %s (Count:%s, ID:%s, methodCode:%s, sourceCode:%s, qualityControlLevelCode:%s)\
             [network:%s:methodCode=%s:sourceCode=%s:qualityControlLevelCode=%s]" %
                                 (str(counter), variable_name, str(value_count), variable_code, method_id, \
                                  source_id, quality_control_level_id, \
                                  variable_code, method_id, source_id, quality_control_level_id))

        return variables_list
    except Exception as e:
        logger.exception("site_info_from_soap: %s" % (e.message))
        raise e

def parse_1_0_and_1_1_owslib(wml_string, wml_ver):

    try:
        wml_str, variable_code, variable_name, net_work, site_name, site_code, elevation, vertical_datum,\
        longitude, latitude, projection, srs, noDataValue, unit_abbr, unit_code, unit_name, unit_type,\
        method_code, method_id, method_description, source_code, source_id, quality_control_level_code,\
        quality_control_level_definition, data, method_code_query, source_code_query,  \
        quality_control_level_code_query, start_date, end_date = \
        None, None, None, None, None, None, None, None,  None, None, None, None, None, None,\
        None, None, None, None, None, None, None, None, None, None,  None, None, None, None, None, None

        wmlValues = wmlParse(wml_string, wml_ver)

        variable_query = wmlValues.query_info.criteria.variable_param
        if variable_query is None:
            for p in wmlValues.query_info.criteria.parameters:
                if p[0].lower() == "variable":
                    variable_query = p[1]
        if variable_query is not None:
            params = variable_query.split(':')
            for param in params:
                if "methodcode" in param.lower():
                    method_code_query = (param.split('='))[1]
                elif "sourcecode" in param.lower():
                    source_code_query = (param.split('='))[1]
                elif "qualitycontrollevelcode" in param.lower():
                    quality_control_level_code_query = (param.split('='))[1]

        wml_str = wml_string
        variable_code = wmlValues.variable_codes[0]
        variable_name = wmlValues.variable_names[0]

        if hasattr(wmlValues.time_series[0], "source_info"):
            sourceInfo_obj = wmlValues.time_series[0].source_info
            if sourceInfo_obj:
                # net_work = sourceInfo_obj.net_work if hasattr(sourceInfo_obj, "net_work") else None
                site_name = sourceInfo_obj.site_name if hasattr(sourceInfo_obj, "site_name") else None
                site_codes = sourceInfo_obj.site_codes if hasattr(sourceInfo_obj, "site_codes") else None
                if site_codes and len(site_codes) > 0:
                    site_code = site_codes[0]
                elevation = sourceInfo_obj.elevation if hasattr(sourceInfo_obj, "elevation") else None
                vertical_datum = sourceInfo_obj.vertical_datum if hasattr(sourceInfo_obj, "vertical_datum") else None
                loc_obj = sourceInfo_obj.location if hasattr(sourceInfo_obj, "location") else None
                if loc_obj:
                    geo_coords_tuple_list = loc_obj.geo_coords if hasattr(loc_obj, "geo_coords") else None
                    if geo_coords_tuple_list and len(geo_coords_tuple_list) > 0:
                        longitude = geo_coords_tuple_list[0][0]
                        latitude = geo_coords_tuple_list[0][1]

                    local_coords_tuple_list = loc_obj.local_sites if hasattr(loc_obj, "local_sites") else None
                    if local_coords_tuple_list and len(local_coords_tuple_list) > 0:
                        local_coords_x = local_coords_tuple_list[0][0]
                        local_coords_y = local_coords_tuple_list[0][1]
                    projection_list = loc_obj.projections if hasattr(loc_obj, "projections") else None
                    if projection_list and len(projection_list) > 0:
                       projection = projection_list[0]
                    srs_list = loc_obj.srs if hasattr(loc_obj, "srs") else None
                    if srs_list and len(srs_list) > 0:
                        srs = srs_list[0]

        variable_obj = wmlValues.time_series[0].variable if hasattr(wmlValues.time_series[0], "variable") else None
        noDataValue = variable_obj.no_data_value if hasattr(variable_obj, "no_data_value") else None
        unit_obj = variable_obj.unit if hasattr(variable_obj, "unit") else None
        if unit_obj:
            unit_abbr = unit_obj.abbreviation if hasattr(unit_obj, "abbreviation") else None
            unit_code = unit_obj.code if hasattr(unit_obj, "code") else None
            unit_name = unit_obj.name if hasattr(unit_obj, "name") else None
            unit_type = unit_obj.unit_type if hasattr(unit_obj, "unit_type") else None

        value_obj = wmlValues.time_series[0].values[0]
        value_list = value_obj.values if hasattr(value_obj, "values") else None
        x = []
        y = []
        data = {"x": x, "y": y}
        if value_list:
            for val in value_list:
                t = val.date_time
                t_str = t.isoformat() # convert to datetime string
                x.append(t_str)
                y.append(float(val.value))

        start_date = value_list[0].date_time.isoformat()
        end_date = value_list[len(value_list)-1].date_time.isoformat()
        method_list = value_obj.methods if hasattr(value_obj, "methods") else None
        if method_list and len(method_list) > 0:
            method_obj = method_list[0]
            method_code = method_obj.code if hasattr(method_obj, "code") else None
            method_id = method_obj.id if hasattr(method_obj, "id") else None
            method_description = method_obj.description if hasattr(method_obj, "description") else None
            if type(method_description) is unicode:
                method_description = method_description.encode('ascii', 'ignore')
        if method_code is None:
            method_code = method_code_query

        source_list = value_obj.sources if hasattr(value_obj, "sources") else None
        if source_list and len(source_list) > 0:
            source_code = source_list[0].code if hasattr(source_list[0], "code") else None
            source_id = source_list[0].code if hasattr(source_list[0], "id") else None
        if source_code is None:
            source_code = source_code_query

        quality_control_level_list = value_obj.quality_control_levels if \
            hasattr(value_obj, "quality_control_levels") else None
        if quality_control_level_list and len(quality_control_level_list) > 0:
            quality_control_level_obj = quality_control_level_list[0]
            quality_control_level_code = quality_control_level_obj.code if \
                hasattr(quality_control_level_obj, "code") else None
            quality_control_level_definition = quality_control_level_obj.definition if \
                hasattr(quality_control_level_obj, "definition") else None

        if quality_control_level_code is None:
            quality_control_level_code = quality_control_level_code_query

        if quality_control_level_definition is None:
            if quality_control_level_code is None or quality_control_level_code == "0":
                quality_control_level_definition = "Raw Data"
            elif quality_control_level_code == "1":
                quality_control_level_definition = "Quality Controlled Data"
            elif quality_control_level_code == "2":
                quality_control_level_definition = "Derived Products"
            elif quality_control_level_code == "3":
                quality_control_level_definition = "Interpreted Products"
            elif quality_control_level_code == "4":
                quality_control_level_definition = "Knowledge Products"
            else:
                quality_control_level_definition = 'Unknown'

        return {'wml_str': wml_str,
                'variable_code': variable_code,
                'variable_name': variable_name,
                "net_work": net_work,
                'site_name': site_name,
                'site_code': site_code,
                'elevation': elevation,
                'vertical_datum': vertical_datum,
                'latitude': latitude,
                'longitude': longitude,
                'projection': projection,
                'srs': srs,
                'noDataValue': noDataValue,
                'unit_abbr': unit_abbr,
                'unit_code': unit_code,
                'unit_name': unit_name,
                'unit_type': unit_type,
                'method_code': method_code,
                'method_id': method_id,
                'method_description': method_description,
                'source_code': source_code,
                'source_id': source_id,
                'quality_control_level_code': quality_control_level_code,
                'quality_control_level_definition': quality_control_level_definition,
                'data': data,
                "start_date": start_date,
                "end_date": end_date
                }
    except Exception as e:
        logger.exception("parse_1_0_and_1_1_owslib: %s" % (e.message))
        raise e

def getAttributeValueFromElement(ele, a_name, exactmatch=False):
    for a in ele.attrib:
        if not exactmatch:
            if a_name in a:
               return ele.attrib.get(a, None)
        else:
             if a_name == a:
               return ele.attrib.get(a, None)
    return None

def parse_featureOfInterest(OM_Observation_element):
    site_name = None

    for featureOfInterest_element in OM_Observation_element.iter():
        if "featureOfInterest" in featureOfInterest_element.tag:
            site_name = getAttributeValueFromElement(featureOfInterest_element, "title")
    return {"site_name": site_name}

def parse_observedProperty(OM_Observation_element):
    variable_name = None
    for observedProperty_element in OM_Observation_element.iter():
        if "observedProperty" in observedProperty_element.tag:
            variable_name = getAttributeValueFromElement(observedProperty_element, "title")
            if variable_name.lower() == "unmapped":
                variable_name = getAttributeValueFromElement(observedProperty_element, "href")
                if "#" in variable_name:
                    variable_name = variable_name.replace("#", "")
    return {"variable_name": variable_name}

def parse_uom(OM_Observation_element):
    unit_name = None

    for uom_element in OM_Observation_element.iter():
        if "uom" in uom_element.tag:
            unit_name = getAttributeValueFromElement(uom_element, "title")
            if unit_name is None:
               unit_name = getAttributeValueFromElement(uom_element, "code")
               if unit_name is None:
                    unit_name = getAttributeValueFromElement(uom_element, "uom")
    return {"unit_name": unit_name}

def parse_qualifier(OM_Observation_element):
    qualifier_name = None
    qualifier_value = None
    for qualifier_element in OM_Observation_element.iter():
        if "qualifier" in qualifier_element.tag:
            qualifier_name = getAttributeValueFromElement(qualifier_element, "title")
            if qualifier_name is None:
                for ele in qualifier_element.iter():
                    if "text" in ele.tag.lower():
                        qualifier_name = getAttributeValueFromElement(ele, "definition")
                    if "value" in ele.tag.lower():
                        qualifier_value = ele.text
    return {"qualifier_name": qualifier_name, "qualifier_value": qualifier_value}

def parse_value(OM_Observation_element):
    x = []
    y = []
    for point_element in OM_Observation_element.iter():
        if "MeasurementTVP" in point_element.tag:
            for ele in point_element.iter():
                if "time" in ele.tag:
                    x.append(ele.text)
                elif "value" in ele.tag:
                    y.append(ele.text)
    return {"x": x, "y": y}

def parse_2_0(wml_string):

    wml_str, variable_code, variable_name, net_work, site_name, site_code, elevation, vertical_datum,\
    longitude, latitude, projection, srs, noDataValue, unit_abbr, unit_code, unit_name, unit_type,\
    method_code, method_id, method_description, source_code, source_id, quality_control_level_code,\
    quality_control_level_definition, data, method_code_query, source_code_query,  \
    quality_control_level_code_query, start_date, end_date = \
    None, None, None, None, None, None, None, None,  None, None, None, None, None, None,\
    None, None, None, None, None, None, None, None, None, None,  None, None, None, None, None, None

    wml_str = wml_string
    data = {"x": [], "y": []}
    root = etree.XML(wml_string)

    try:
        for ele in root.iter():
            if "OM_Observation" in ele.tag:
                ele_OM_Observation = ele
                site_name = parse_featureOfInterest(ele_OM_Observation)["site_name"]
                variable_name = parse_observedProperty(ele_OM_Observation)["variable_name"]
                unit_name = parse_uom(ele_OM_Observation)["unit_name"]
                qualifier = parse_qualifier(ele_OM_Observation)
                quality_control_level_code = qualifier["qualifier_name"]
                quality_control_level_definition = qualifier["qualifier_value"]

                x_y_dict = parse_value(ele)
                x = x_y_dict['x']
                y = x_y_dict['y']
                data['x'] = x
                data['y'] = y

            elif "localDictionary" in ele.tag:
                pass
            elif "samplingFeatureMember" in ele.tag:
                ele_samplingFeatureMember =ele
                for ele2 in ele_samplingFeatureMember.iter():
                    if "pos" in ele2.tag:
                        lat_lon_array = ele2.text.split(" ")
                        latitude = lat_lon_array[0]
                        longitude = lat_lon_array[1]
            elif "ObservationProcess" in ele.tag:
                ele_ObservationProcess = ele
                for ele2 in ele_ObservationProcess.iter():
                    if "NamedValue" in ele2.tag:
                        ele_NamedValue = ele2
                        if getAttributeValueFromElement(ele_NamedValue.getchildren()[0], "title") == "noDataValue":
                            noDataValue = ele_NamedValue.getchildren()[1].text

                return {'wml_str': wml_str,
                        'variable_code': variable_code,
                        'variable_name': variable_name,
                        "net_work": net_work,
                        'site_name': site_name,
                        'site_code': site_code,
                        'elevation': elevation,
                        'vertical_datum': vertical_datum,
                        'latitude': latitude,
                        'longitude': longitude,
                        'projection': projection,
                        'srs': srs,
                        'noDataValue': noDataValue,
                        'unit_abbr': unit_abbr,
                        'unit_code': unit_code,
                        'unit_name': unit_name,
                        'unit_type': unit_type,
                        'method_code': method_code,
                        'method_id': method_id,
                        'method_description': method_description,
                        'source_code': source_code,
                        'source_id': source_id,
                        'quality_control_level_code': quality_control_level_code,
                        'quality_control_level_definition': quality_control_level_definition,
                        'data': data,
                        "start_date": start_date,
                        "end_date": end_date
                        }
    except Exception as ex:
        logger.error(ex.message)
        raise Exception("parse 2.0 error")

def time_str_to_datetime(t):
    try:
        t_datetime=parser.parse(t)
        return t_datetime
    except ValueError:
        logger.exception("time_str_to_datetime error: " + t)
        raise Exception("time_str_to_datetime error: " + t)

# get values
def QueryHydroServerGetParsedWML(service_url, soap_or_rest, site_code=None, variable_code=None, start_date='', end_date='', auth_token=''):
    # http://icewater.usu.edu/littlebearriver/cuahsi_1_1.asmx/GetValuesObject?
    # location=LittleBearRiver:USU-LBR-SFLower&
    # variable=LittleBearRiver:USU6:methodCode=2:sourceCode=2:qualityControlLevelCode=0&
    # startDate=2007-07-26&
    # endDate=2007-08-26&
    # authToken=

    try:
        if soap_or_rest == 'soap':
            client = connect_wsdl_url(service_url)
            response = client.service.GetValues(site_code, variable_code, start_date, end_date, auth_token)
        elif soap_or_rest == 'rest':
            r = requests.get(service_url, verify=False)
            if r.status_code != 200:
                raise Exception("Query REST endpoint failed")
            response = r.text.encode('utf-8')
        root = etree.XML(response)
        wml_version_xml_tag = get_wml_version_from_xml_tag(root)
        if wml_version_xml_tag == 10 or wml_version_xml_tag == 11:
            ts = parse_1_0_and_1_1_owslib(response, wml_version_xml_tag)
        elif wml_version_xml_tag == 20:
            ts = parse_2_0(response)
         # some hydrosevers may return wml without having version info in tags (http://worldwater.byu.edu/interactive/gill_lab/services/index.php/cuahsi_1_1.asmx?WSDL)
        else:
            raise Exception("no version info found in wml")
        ts["wml_version"] = wml_version_xml_tag
        return ts
    except Exception as e:
        logger.exception("QueryHydroServerGetParsedWML: %s" % (e.message))
        raise e

def create_vis_2(path, data, xlabel, variable_name, units, noDataValue, predefined_name=None):
    try:
        x_list = data["x"]
        y_list = data["y"]
        x_list_draw = []
        y_list_draw = []

        for i in range(len(x_list)):
            if noDataValue is not None and (y_list[i]) == float(noDataValue):
               continue # skip nodatavalue
            x_list_draw.append(time_str_to_datetime(x_list[i]))
            y_list_draw.append(y_list[i])

        fig, ax = plt.subplots()
        ax.plot_date(x_list_draw, y_list_draw, 'b-', color='g')
        ax.set_xlabel(xlabel)
        ax.xaxis_date()
        ax.set_ylabel(variable_name + "(" + units + ")")
        ax.grid(True)
        fig.autofmt_xdate()

        if predefined_name is None:
            vis_name = 'preview.png'
        else:
            vis_name = predefined_name
        vis_path = path + "/" + vis_name
        plt.savefig(vis_path, bbox_inches='tight')
        return {"fname": vis_name, "fullpath": vis_path}
    except Exception as e:
        logger.exception("create_vis_2: %s" % (e.message))
        raise e

def generate_resource_files(shortkey, tempdir):

    res = hydroshare.get_resource_by_shortkey(shortkey)

    if res.metadata.referenceURLs.all()[0].type == 'rest':
        ts = QueryHydroServerGetParsedWML(res.metadata.referenceURLs.all()[0].value,
                                          res.metadata.referenceURLs.all()[0].type)
    else:
        site_code = res.metadata.sites.all()[0].code
        # net_work = res.metadata.sites.all()[0].net_work
        variable_code = res.metadata.variables.all()[0].code
        method_code = res.metadata.methods.all()[0].code
        source_code = res.metadata.datasources.all()[0].code
        quality_control_level_code = res.metadata.quality_levels.all()[0].code

        site_code_query = "%s:%s" % ("network", site_code)
        variable_code_query = "%s:%s:methodCode=%s:sourceCode=%s:qualityControlLevelCode=%s" % \
        ("network", variable_code, method_code, source_code, quality_control_level_code)

        ts = QueryHydroServerGetParsedWML(service_url=res.metadata.referenceURLs.all()[0].value,
                                  soap_or_rest=res.metadata.referenceURLs.all()[0].type,
                                  site_code=site_code_query,
                                  variable_code=variable_code_query)

    files = save_ts_to_files(res, tempdir, ts)
    return files

def save_ts_to_files(res, tempdir, ts):
    res_file_info_array = []

    # save preview figure
    data = ts['data']
    units = ts['unit_abbr']
    if units is None:
        units = ts['unit_name']
        if units is None:
            units = "Unknown"
    variable_name = ts['variable_name']
    noDataValue = ts['noDataValue']

    preview_file_info = create_vis_2(path=tempdir, data=data, xlabel='Date',
                                      variable_name=variable_name, units=units, noDataValue=noDataValue)
    res_file_info_array.append(preview_file_info)

    # csv wml1 wml2 file name base
    # file_name_base = title.replace(" ", "_")
    file_name_base = "res_" + str(res.short_id)
    # save csv file
    csv_name = '{0}.{1}'.format(file_name_base, 'csv')
    csv_name_full_path = tempdir + "/" + csv_name
    with open(csv_name_full_path, 'w') as csv_file:
        w = csv.writer(csv_file)
        x_data = ts['data']['x']
        y_data = ts['data']['y']
        for i in range(len(x_data)):
            row_str = [x_data[i], y_data[i]]
            w.writerow(row_str)
    res_file_info_array.append({"fname": csv_name, "fullpath": csv_name_full_path})

    wml_1_0_name = '{0}_wml_1_0.xml'.format(file_name_base)
    wml_1_0_full_path = tempdir + "/" + wml_1_0_name

    wml_1_1_name = '{0}_wml_1_1.xml'.format(file_name_base)
    wml_1_1_full_path = tempdir + "/" + wml_1_1_name

    wml_2_0_name = '{0}_wml_2_0.xml'.format(file_name_base)
    wml_2_0_full_path = tempdir + "/" + wml_2_0_name

    if ts["wml_version"] == 10 or ts["wml_version"] == 11:
        module_dir = os.path.dirname(__file__)
        if ts["wml_version"] == 11:
            xml_1011_name = wml_1_1_name
            xml_1011_full_path = wml_1_1_full_path
            xsl_location = os.path.join(module_dir, "static/ref_ts/xslt/WaterML1_1_timeSeries_to_WaterML2.xsl")
        else: # 1.0
            xml_1011_name = wml_1_0_name
            xml_1011_full_path = wml_1_0_full_path
            xsl_location = os.path.join(module_dir, "static/ref_ts/xslt/WaterML1_timeSeries_to_WaterML2.xsl")

        root_wml_1 = etree.fromstring(ts['wml_str'])
        with open(xml_1011_full_path, 'w') as xml_1_file:
            xml_1_file.write(etree.tostring(root_wml_1, pretty_print=True))
        res_file_info_array.append({"fname": xml_1011_name, "fullpath": xml_1011_full_path})

        try:
            # convert to wml 2
            xslt = etree.parse(xsl_location)
            transform =etree.XSLT(xslt)
            tree_wml_2 = transform(root_wml_1)

            tree_wml_2.write(wml_2_0_full_path, pretty_print=True)
            res_file_info_array.append({"fname": wml_2_0_name, "fullpath": wml_2_0_full_path})
        except Exception as e:
            logger.exception("convert to wml2 error: %s".format(e.message))

    elif ts["wml_version"] == 20:
        with open(wml_2_0_full_path, 'w') as xml_2_file:
            xml_2_file.write(ts['wml_str'])
        res_file_info_array.append({"fname": wml_2_0_name, "fullpath": wml_2_0_full_path})

    return res_file_info_array

def prepare_metadata_list(metadata, ts_dict, url, reference_type):

    if ts_dict["longitude"] is not None and ts_dict["latitude"] is not None:
        coverage_point = {"Coverage": {"type": "point",
                          "value": {"east": ts_dict["longitude"],
                                    "north": ts_dict["latitude"],
                                    "units": "WGS 84 EPSG:4326"}
                                    }
                          }
        metadata.append(coverage_point)

    if ts_dict["start_date"] is not None and ts_dict["end_date"] is not None:
        coverage_period ={"Coverage": {"type": "period",
                              "value": {"start": ts_dict["start_date"],
                                        "end": ts_dict["end_date"]}
                             }
                }
        metadata.append(coverage_period)

    metadata += [{"ReferenceURL": {"value": url, "type": reference_type}},
                {"Site": {"name": ts_dict['site_name'] if ts_dict['site_name'] is not None else BLANK_FIELD_STRING,
                          "code": ts_dict['site_code'] if ts_dict['site_code'] is not None else BLANK_FIELD_STRING,
                          "net_work": ts_dict['net_work'] if ts_dict['net_work'] is not None else BLANK_FIELD_STRING,
                          "latitude": ts_dict['latitude'],
                          "longitude": ts_dict['longitude']
                          }
                },
                {"Variable": {"name": ts_dict['variable_name'] if ts_dict['variable_name'] is not None else BLANK_FIELD_STRING,
                              "code": ts_dict['variable_code'] if ts_dict['variable_code'] is not None else BLANK_FIELD_STRING
                              }
                },
                {"DataSource": {"code": ts_dict['source_code'] if ts_dict['source_code'] is not None else BLANK_FIELD_STRING}},
                {"Method": {"code": ts_dict['method_code'] if ts_dict['method_code'] is not None else BLANK_FIELD_STRING,
                            "description": ts_dict['method_description'] if ts_dict['method_description'] is not None else BLANK_FIELD_STRING
                           }
                },
                {"QualityControlLevel": {
                    "code": ts_dict['quality_control_level_code'] if ts_dict['quality_control_level_code'] is not None else BLANK_FIELD_STRING,
                    "definition": ts_dict['quality_control_level_definition'] if ts_dict['quality_control_level_definition'] is not None else BLANK_FIELD_STRING
                                         }
                }]


text:
  Rouves est
       un village
       géographiquement positionné dans le département de Meurthe-et-Moselle en Lorraine. Elle totalisait 96 habitants en 2008.

À coté de Rouves sont positionnées géographiquement les villes de
Morville-sur-Seille située à 4 km, 121 habitants,
Nomeny située à 1 km, 1 127 habitants,
Saint-Jure située à 5 km, 300 habitants,
Abaucourt localisée à 3 km, 290 habitants,
Mailly-sur-Seille à 3 km, 245 habitants,
Clémery à 1 km, 495 habitants,
 entre autres. De plus, Rouves est située à seulement 24 km de Metz.

Si vous pensez emmenager à Rouves, vous pourrez facilement trouver une maison à vendre.

Le parc de logements, à Rouves, était réparti en 2011 en deux appartements et 35 maisons soit
 un marché relativement équilibré.

La ville offre quelques  aménagements, elle propose entre autres un terrain de sport.


text:
function equals(o) {
  if (is$(o,{t:AppliedMemberClassCallableConstructor$jsint}) && this.tipo===o.tipo) {
    return this.container.equals(o.container) && this.typeArguments.equals(o.typeArguments);
  }
  return false;
}


text:
#ifndef IZK_NEURON_H
#define IZK_NEURON_H

#ifdef __cplusplus
extern "C" {
#endif

#include <stdbool.h>

/** Neuron.h
 *
 * An abstract interface for defining neurons.  This uses function pointers
 * to define virtual functions -- defining them is equivalent to implementing
 * a subclass.
 *
 * @author Eric 'Siggy' Scott
 */

// Data for parent type
typedef struct Neuron {
    double voltage;
    bool isSpiking;
    const struct NeuronFunctionTable * const funcTable;
    void * const implementationData; // Subclass-specific data
} Neuron;

// Dispatch vector providing pointers to virtual methods
typedef struct NeuronFunctionTable {
    void (* const step)(Neuron * obj, double inputCurrent, double stepSize); // Execute an Euler step of the simulation
    bool (* const repOK)(const Neuron * obj); // Representation invariant
    Neuron* (* const copy)(const Neuron * obj); // Copy constructor
    void (* const free)(const Neuron * obj); // Destructor
} NeuronFunctionTable;

// Default implementation of virtual method -- should be used like a call to "super.free()" in Java
void izk_Neuron_free(const Neuron* obj);

#ifdef __cplusplus
}
#endif

#endif /* IZK_NEURON_H */


text:
import jinja2
from flask import Flask
from flask_admin import Admin
from wtforms import HiddenField

from . import config as default_config
from .ext import db, security, migrate, mail, cache, debug_toolbar
from .models import user_datastore
from .views import (SpkrepoConfirmRegisterForm, api, frontend, nas, IndexView, UserView, ArchitectureView,
                    FirmwareView, ScreenshotView, PackageView, BuildView, VersionView)

def create_app(config=None, register_blueprints=True, init_admin=True):
    """Create a Flask app"""
    app = Flask('spkrepo')

    # Configuration
    app.config.from_object(default_config)
    app.config.from_envvar('SPKREPO_CONFIG', silent=True)
    if config is not None:
        app.config.from_object(config)

    # Extra template path
    if app.config['TEMPLATE_PATH'] is not None:
        app.jinja_loader = jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(app.config['TEMPLATE_PATH']),
            app.jinja_loader
        ])

    # Blueprints
    if register_blueprints:
        app.register_blueprint(frontend)
        app.register_blueprint(api, url_prefix='/api')
        app.register_blueprint(nas, url_prefix='/nas')

    # Admin
    if init_admin:
        admin = Admin(index_view=IndexView())
        admin.add_view(UserView())
        admin.add_view(ArchitectureView())
        admin.add_view(FirmwareView())
        admin.add_view(ScreenshotView())
        admin.add_view(PackageView())
        admin.add_view(VersionView())
        admin.add_view(BuildView())
        admin.init_app(app)

    # SQLAlchemy
    db.init_app(app)

    # Security
    security.init_app(app, user_datastore, confirm_register_form=SpkrepoConfirmRegisterForm)

    # Migrate
    migrate.init_app(app, db, directory=app.config['MIGRATE_DIRECTORY'])

    # Mail
    mail.init_app(app)

    # Cache
    cache.init_app(app)

    # Debug Toolbar
    debug_toolbar.init_app(app)

    # Jinja2 helpers
    @app.template_filter()
    def is_hidden_field(field):
        return isinstance(field, HiddenField)

    @app.template_filter()
    def sort_fields(form, field_names=None):
        fields = []
        for field in form:
            if field.name in field_names:
                fields.insert(field_names.index(field.name), field)
            else:
                fields.append(field)
        return fields

    return app


text:
@charset "UTF-8";
body {
  font-family: "Droid Sans", helvetica, arial, sans-serif;
  margin: 0;
  -webkit-font-smoothing: antialiased;
  font-size: 15px;
}

a {
  color: #82BD36; }

.sidebar {
  position: fixed;
  left: 15px;
  top: 140px;
  width: 80px;
  font-family: Helvetica, sans-serif; }
  .sidebar a {
    text-decoration: none; }
  .sidebar img {
    padding: 0 3px;
    border: 0; }
  .sidebar .avatar {
    padding: 0;
    margin-left: 2px;
    border-radius: 5px; }
  .sidebar .name {
    text-transform: uppercase;
    margin: 10px 0 20px 0; }
    .sidebar .name #fname {
      padding-left: 1px;
      font-size: 23px;
      letter-spacing: 5px;
      color: black; }
    .sidebar .name #lname {
      font-size: 17px;
      font-weight: bold;
      letter-spacing: 1px;
      color: black; }
  .sidebar .meta a {
    margin-left: 0px;
    color: black; }
    .sidebar .meta a:hover {
      color: #227ce8; }
  .sidebar .sections {
    margin: 15px 0 0 0; }
    .sidebar .sections a {
      padding: 3px 0;
      color: black;
      font-weight: bold;
      font-size: 12px;
      display: block; }
      .sidebar .sections a:hover {
        color: #227ce8; }
    .sidebar .sections ul {
      margin: 0;
      padding: 0; }
    .sidebar .sections li {
      list-style: none;
      margin-bottom: 7px; }

.content{  margin-bottom: 50px; }
  .content h1 {
    color: #fff;
    font-family: "Yanone Kaffeesatz", Helvetica, sans-serif;
    font-weight: 400; }
  .content h1 a {
    color: #111;
    text-decoration: none; }
  .content h2 {
    color: #fff;
    font-family: "Yanone Kaffeesatz", Helvetica, sans-serif;
    font-weight: 400; }
  .content h2 a {
    color: #111;
    text-decoration: none; }
  .content h3 {
    color: #333;
    font-family: "Yanone Kaffeesatz", Helvetica, sans-serif;
    font-weight: 400; }
  .content h3 a {
    color: #111;
    text-decoration: none; }
  .content h4 {
    color: #333;
    font-family: "Yanone Kaffeesatz", Helvetica, sans-serif;
    font-weight: 400; }
  .content h4 a {
    color: #111;
    text-decoration: none; }
  .content h1 {
    font-size: 36px;
    margin: 18px 0 5px 0; }
  .content h2 {
    font-size: 30px;
    margin-bottom: 15px; }
  .content h3 {
    color: #777;
    font-size: 25px;
    padding-bottom: 5px;
    margin-bottom: 10px; }
  .content p {
    font-size: 16px;
    margin-top: 0;
    margin-bottom: 1.2em;
    line-height: 1.7em; }
    .content p code {
      font-size: 12px;
      background-color: #eeeeee;
      border: 1px solid #777777;
      border-radius: 3px;
      padding: 2px 3px; }
  .content img {
    padding: 3px;
    border: 1px solid #eeeeee;
    max-width: 100%; }
  .content hr {
    border: 0;
    height: 6px;
    background-image: url("/images/hr.png");
    background-repeat: repeat-x;
    margin: 2em 3em; }
  .content li {
    margin-bottom: 10px;
    line-height: 1.4em; }
  .content blockquote {
    font-style: italic;
    font-size: 14px;
    padding: .25em 1em;
    margin: 1em 1em 0 1em;
    color: #444; }
    .content blockquote cite:before {
      content: '— '; }
    .content blockquote cite {
      display: block;
      margin-top: .5em;
      text-align: right;
      color: #111;
      font-style: normal; }
  .content .byline {
    margin-bottom: 17px;
    font-family: "Yanone Kaffeesatz", Helvetica, sans-serif;
    padding-left: 0px;
    font-size: 17px;
    color: #777; }
  .content .aside {
    background-color: #eeeeee;
    padding: 14px;
    font-size: 14px;
    margin: 5px 0 15px 0;
    font-family: Helvetica, sans-serif;
    line-height: 1.6em; }
  .content .listing {
    margin: 10px 0 0 0;
    padding: 0;
    font-family: Helvetica, sans-serif; }
    .content .listing ul {
      margin: 0;
      padding: 0; }
    .content .listing li {
      font-size: 13px;
      list-style: none;
      padding: 5px 3px;
      margin: 0;
      color: #777777;
      border-bottom: 1px solid #eee; }
    .content .listing li span {
      float: right; }
    .content .listing a {
      text-decoration: none; }
      .content .listing a:hover {
        text-decoration: underline; }
  .content .meta {
    margin: 30px 0;
    padding: 10px 0;
    font-family: Helvetica, sans-serif; }
    .content .meta p {
      line-height: 1.4;
      font-size: 14px;
      margin-top: 0px; }
    .content .meta img {
      position: relative;
      float: left;
      margin-top: 0px;
      margin-right: 10px;
      margin-left: -60px;
      border-radius: 4px; }
    .content .meta .copy {
      padding-left: 60px; }
    .content .meta iframe {
      padding-left: 5px; }
  .content .talk-design .color div {
    float: left;
    margin-right: 10px;
    padding: 5px 15px;
    border: 1px solid #000;
    font-family: Helvetica, sans-serif;
    font-size: 12px;
    font-weight: bold; }
  .content .talk-design .color .white {
    color: #fff; }

/*-------*/

.table-declare{width: 100%; color: #000;}

table{border-spacing: 0;}

.table{margin-bottom: 30px; border-collapse: separate;}

.table th, .table td {
  padding: 8px;
  line-height: 20px;
  text-align: left;
  vertical-align: top;
  border-top: 1px solid #dddddd;
  background-color: #F8F8F8;
}
.table th {
font-weight: bold;
}

.table thead th {
  vertical-align: bottom;
  background-color: #fff;
}

.table-striped tbody > tr:nth-child(odd) > td, .table-striped tbody > tr:nth-child(odd) > th {
  background-color: #ECECEC;
}

.table-bordered th, .table-bordered td {
border-left: 1px solid #dddddd;

}
.table-bordered th:last-child, .table-bordered td:last-child  {
  border-right: 1px solid #dddddd;
}

/* TABLE  border-radius */

.table-bordered thead:first-child tr:first-child > th:last-child, .table-bordered tbody:first-child tr:first-child > td:last-child, .table-bordered tbody:first-child tr:first-child > th:last-child {
-webkit-border-top-right-radius: 4px;
border-top-right-radius: 4px;
-moz-border-radius-topright: 4px;
}

.table-bordered thead:last-child tr:last-child > th:last-child, .table-bordered tbody:last-child tr:last-child > td:last-child, .table-bordered tbody:last-child tr:last-child > th:last-child, .table-bordered tfoot:last-child tr:last-child > td:last-child, .table-bordered tfoot:last-child tr:last-child > th:last-child {
-webkit-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px;
-moz-border-radius-bottomright: 4px;
}

.table-bordered thead:last-child tr:last-child > th:first-child, .table-bordered tbody:last-child tr:last-child > td:first-child, .table-bordered tbody:last-child tr:last-child > th:first-child, .table-bordered tfoot:last-child tr:last-child > td:first-child, .table-bordered tfoot:last-child tr:last-child > th:first-child {
-webkit-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px;
-moz-border-radius-bottomleft: 4px;
}
.table-bordered thead:first-child tr:first-child > th:first-child, .table-bordered tbody:first-child tr:first-child > td:first-child, .table-bordered tbody:first-child tr:first-child > th:first-child {
-webkit-border-top-left-radius: 4px;
border-top-left-radius: 4px;
-moz-border-radius-topleft: 4px;
}

/* ----- */

.well{
  min-height: 20px;
  padding: 19px;
  margin-bottom: 20px;
  background-color: #ECEBEB;
  border: 1px solid #e3e3e3;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
  -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
.oneAction{margin-top: 10px;}


text:
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef GFX_PLATFORM_MAC_H
#define GFX_PLATFORM_MAC_H

#include "nsTArray.h"
#include "gfxPlatform.h"

#define MAC_OS_X_VERSION_10_4_HEX 0x00001040
#define MAC_OS_X_VERSION_10_5_HEX 0x00001050
#define MAC_OS_X_VERSION_10_6_HEX 0x00001060
#define MAC_OS_X_VERSION_10_7_HEX 0x00001070

#define MAC_OS_X_MAJOR_VERSION_MASK 0xFFFFFFF0U

class gfxTextRun;
class gfxFontFamily;

namespace mozilla { namespace gfx { class DrawTarget; } }

class THEBES_API gfxPlatformMac : public gfxPlatform {
public:
    gfxPlatformMac();
    virtual ~gfxPlatformMac();

    static gfxPlatformMac *GetPlatform() {
        return (gfxPlatformMac*) gfxPlatform::GetPlatform();
    }

    already_AddRefed<gfxASurface> CreateOffscreenSurface(const gfxIntSize& size,
                                                         gfxASurface::gfxContentType contentType);
    virtual already_AddRefed<gfxASurface>
      CreateOffscreenImageSurface(const gfxIntSize& aSize,
                                  gfxASurface::gfxContentType aContentType);

    already_AddRefed<gfxASurface> OptimizeImage(gfxImageSurface *aSurface,
                                                gfxASurface::gfxImageFormat format);

    mozilla::TemporaryRef<mozilla::gfx::ScaledFont>
      GetScaledFontForFont(mozilla::gfx::DrawTarget* aTarget, gfxFont *aFont);

    nsresult ResolveFontName(const nsAString& aFontName,
                             FontResolverCallback aCallback,
                             void *aClosure, bool& aAborted);

    nsresult GetStandardFamilyName(const nsAString& aFontName, nsAString& aFamilyName);

    gfxFontGroup *CreateFontGroup(const nsAString &aFamilies,
                                  const gfxFontStyle *aStyle,
                                  gfxUserFontSet *aUserFontSet);

    virtual gfxFontEntry* LookupLocalFont(const gfxProxyFontEntry *aProxyEntry,
                                          const nsAString& aFontName);

    virtual gfxPlatformFontList* CreatePlatformFontList();

    virtual gfxFontEntry* MakePlatformFont(const gfxProxyFontEntry *aProxyEntry,
                                           const uint8_t *aFontData,
                                           uint32_t aLength);

    bool IsFontFormatSupported(nsIURI *aFontURI, uint32_t aFormatFlags);

    nsresult GetFontList(nsIAtom *aLangGroup,
                         const nsACString& aGenericFamily,
                         nsTArray<nsString>& aListOfFonts);
    nsresult UpdateFontList();

    virtual void GetCommonFallbackFonts(const uint32_t aCh,
                                        int32_t aRunScript,
                                        nsTArray<const char*>& aFontList);

    // Returns the OS X version as returned from Gestalt(gestaltSystemVersion, ...)
    // Ex: Mac OS X 10.4.x ==> 0x104x
    int32_t OSXVersion();

    bool UseAcceleratedCanvas();

    // lower threshold on font anti-aliasing
    uint32_t GetAntiAliasingThreshold() { return mFontAntiAliasingThreshold; }

    virtual already_AddRefed<gfxASurface>
    GetThebesSurfaceForDrawTarget(mozilla::gfx::DrawTarget *aTarget);

    virtual already_AddRefed<gfxASurface>
    CreateThebesSurfaceAliasForDrawTarget_hack(mozilla::gfx::DrawTarget *aTarget);
private:
    virtual qcms_profile* GetPlatformCMSOutputProfile();

    // read in the pref value for the lower threshold on font anti-aliasing
    static uint32_t ReadAntiAliasingThreshold();

    int32_t mOSXVersion;
    uint32_t mFontAntiAliasingThreshold;
};

#endif /* GFX_PLATFORM_MAC_H */


text:
import { endpoints, models, errors } from '@r/api-client';
const { ResponseError, ValidationError } = errors;
const { SavedEndpoint, HiddenEndpoint, EditUserTextEndpoint } = endpoints;

import { apiOptionsFromState } from 'lib/apiOptionsFromState';

import { getEventTracker } from 'lib/eventTracker';
import { getBasePayload, buildSubredditData, getListingName, getUserInfoOrLoid } from 'lib/eventUtils';

export const TOGGLE_EXPANDED = 'POSTS__TOGGLE_EXPANDED';
export const toggleExpanded = postId => ({
  type: TOGGLE_EXPANDED,
  postId,
});

export const toggleExpandPost = (postId, clickTarget) => async (dispatch, getState) => {
  dispatch(toggleExpanded(postId));
  trackExpandToggle(getState(), postId, clickTarget);
};

function trackExpandToggle(state, postId, clickTarget) {
  const eventType = state.expandedPosts[postId] ? 'cs.expand_user' : 'cs.collapse_user';
  getEventTracker().track('expando_events', eventType, {
    ...getBasePayload(state),
    ...buildSubredditData(state),
    ...getListingName(state),
    ...getPostInfo(state, postId),
    ...getUserInfoOrLoid(state),
    'click_target': clickTarget,
  });
}

function getPostInfo(state, postId) {
  const post = state.posts[postId];
  return {
    'target_author_id': post.id,
    'target_created_ts': post.createdUTC,
    'target_id': post.id,
    'target_url_domain': post.domain,
    'target_url': post.cleanUrl,
    'target_type': post.isSelf ? 'self' : 'link',
    'nsfw': post.over18,
  };
}

export const TOGGLE_NSFW_BLUR = 'POSTS__TOGGLE_NSFW_BLUR';
export const toggleNSFWBlur = postId => ({
  type: TOGGLE_NSFW_BLUR,
  postId,
});

export const TOGGLE_SAVE_RECEIVED = 'POSTS__TOGGLE_SAVED_RECEIVED';
export const toggleSavedReceived = post => ({
  post,
  type: TOGGLE_SAVE_RECEIVED,
});

export const TOGGLE_HIDE_RECEIVED = 'POSTS__TOGGLE_HIDE_RECEIVED';
export const toggleHideReceived = post => ({
  post,
  type: TOGGLE_HIDE_RECEIVED,
});

export const toggleSavePost = postId => async (dispatch, getState) => {
  const state = getState();
  const post = state.posts[postId];
  const apiOptions = apiOptionsFromState(state);
  const method = post.saved ? 'del' : 'post';

  try {
    await SavedEndpoint[method](apiOptions, { id: post.uuid });
    // the response doesn't actually give us anything back, so we'll just emit
    // a new model on the frontend if the call succeeeds.
    const newPost = models.PostModel.fromJSON({ ...post.toJSON(), saved: !post.saved });
    dispatch(toggleSavedReceived(newPost));
  } catch (e) {
    // TODO: handle these errors in the toaster
    console.error(e);
  }
};

export const toggleHidePost = postId => async (dispatch, getState) => {
  const state = getState();
  const post = state.posts[postId];
  const apiOptions = apiOptionsFromState(state);
  const method = post.hidden ? 'del' : 'post';

  try {
    await HiddenEndpoint[method](apiOptions, { id: post.uuid });
    // the response doesn't actually give us anything back, so we'll just emit
    // a new model on the frontend if the call succeeeds.
    const newPost = models.PostModel.fromJSON({ ...post.toJSON(), hidden: !post.hidden });
    dispatch(toggleHideReceived(newPost));
  } catch (e) {
    // TODO: handle these errors in the toaster
    console.error(e);
  }
};

export const TOGGLE_EDIT = 'POSTS__TOGGLE_EDIT';
export const toggleEdit = postId => ({
  type: TOGGLE_EDIT,
  thingId: postId,
});

export const START_PLAYING = 'POSTS__START_PLAYING';
export const startPlaying = postId => ({
  type: START_PLAYING,
  thingId: postId,
});

export const STOP_PLAYING = 'POSTS__STOP_PLAYING';
export const stopPlaying = postId => ({
  type: STOP_PLAYING,
  thingId: postId,
});

export const UPDATING_SELF_TEXT = 'POSTS__UPDATING_SELF_TEXT';
export const updatingSelfText = postId => ({
  type: UPDATING_SELF_TEXT,
  thingId: postId,
});

export const UPDATED_SELF_TEXT = 'POSTS__UPDATED_SELF_TEXT';
export const updatedSelfText = post => ({
  type: UPDATED_SELF_TEXT,
  model: post,
});

export const FAILED_UPDATE_SELF_TEXT = 'POSTS__FAILED_UPDATE_SELF_TEXT';
export const failedUpdateSelfText = (postId, error) => ({
  type: FAILED_UPDATE_SELF_TEXT,
  thingId: postId,
  error,
  message: 'Sorry, something went wrong with updating your post.',
});

export const updateSelfText = (postId, newSelfText) => async (dispatch, getState) => {
  dispatch(updatingSelfText(postId));

  const apiOptions = apiOptionsFromState(getState());

  try {
    const post = await EditUserTextEndpoint.post(apiOptions, {
      thingId: postId,
      text: newSelfText,
    });

    dispatch(updatedSelfText(post));
  } catch (e) {
    if (e instanceof ValidationError || e instanceof ResponseError) {
      dispatch(failedUpdateSelfText(postId, e));
    } else {
      throw e;
    }
  }
};


text:
<manifest package="net.grandcentrix.thirtyinch.android">

    <application />

</manifest>


text:
UCLASS(BlueprintType)
class URealSenseFacePose : public UObject
{
	GENERATED_UCLASS_BODY()
public:

	//pose Euler angles
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "RealSense Face Pose")
	FRotator Rotation;

	//pose rotation as a quaternion
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "RealSense Face Pose")
	FQuat Quaternion;

	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "RealSense Face Pose")
	FVector HeadPosition;

	UFUNCTION(BlueprintPure, Category = "RealSense Face Pose")
	FMatrix RotationMatrix();

	//position(angle) confidence
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "RealSense Face Pose")
	int32 Confidence;

	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "RealSense Face Pose")
	int32 HeadConfidence;

	void setFromRealSenseFacePose(void* facePosePointer);

private:
	void* facePosePtr;
};


text:
describe GephiImport do
  subject { GephiImport }

  describe '.process_file' do

    let(:file_path) { File.join(__dir__, '..', 'files', 'gephi_export.csv') }
    let(:name) { 'Nematostella transcripts' }

    before(:each) { truncate_db }

    it 'processes csv file' do
      expect(GephiImport.count).to eq 0
      expect(Trace.count).to eq 0
      expect(GephiRecord.count).to eq 0
      gi = subject.process_file(file_path, name)
      expect(GephiImport.count).to eq 1
      expect(Trace.count).to eq 7
      expect(GephiRecord.count).to eq 102
      expect(gi).to be_kind_of(GephiImport)
    end

  end

end


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/common'
require File.dirname(__FILE__) + '/shared/glob'

describe "Dir.glob" do
  before :all do
    DirSpecs.create_mock_dirs
  end

  after :all do
    DirSpecs.delete_mock_dirs
  end

  it_behaves_like :dir_glob, :glob
end

describe "Dir.glob" do
  before :all do
    DirSpecs.create_mock_dirs
  end

  after :all do
    DirSpecs.delete_mock_dirs
  end

  it_behaves_like :dir_glob_recursive, :[]
end

describe "Dir.glob" do
  before :all do
    DirSpecs.create_mock_dirs

    @cwd = Dir.pwd
    Dir.chdir DirSpecs.mock_dir
  end

  after :all do
    Dir.chdir @cwd

    DirSpecs.delete_mock_dirs
  end

  it "matches both dot and non-dotfiles with '*' and option File::FNM_DOTMATCH" do
    Dir.glob('*', File::FNM_DOTMATCH).sort.should == DirSpecs.expected_paths
  end

  it "matches files with any beginning with '*<non-special characters>' and option File::FNM_DOTMATCH" do
    Dir.glob('*file', File::FNM_DOTMATCH).sort.should == %w|.dotfile nondotfile|.sort
  end

  it "matches any files in the current directory with '**' and option File::FNM_DOTMATCH" do
    Dir.glob('**', File::FNM_DOTMATCH).sort.should == DirSpecs.expected_paths
  end

  it "recursively matches any subdirectories except './' or '../' with '**/' and option File::FNM_DOTMATCH" do
    expected = %w[
      .dotsubdir/
      deeply/
      deeply/nested/
      deeply/nested/directory/
      deeply/nested/directory/structure/
      dir/
      special/
      subdir_one/
      subdir_two/
    ]

    Dir.glob('**/', File::FNM_DOTMATCH).sort.should == expected
  end

  platform_is_not(:windows) do
    it "matches the literal character '\\' with option File::FNM_NOESCAPE" do
      Dir.mkdir 'foo?bar'

      begin
        Dir.glob('foo?bar', File::FNM_NOESCAPE).should == %w|foo?bar|
        Dir.glob('foo\?bar', File::FNM_NOESCAPE).should == []
      ensure
        Dir.rmdir 'foo?bar'
      end

      Dir.mkdir 'foo\?bar'

      begin
        Dir.glob('foo\?bar', File::FNM_NOESCAPE).should == %w|foo\\?bar|
      ensure
        Dir.rmdir 'foo\?bar'
      end
    end

    it "returns nil for directories current user has no permission to read" do
      Dir.mkdir('no_permission')
      File.chmod(0, 'no_permission')

      begin
        Dir.glob('no_permission/*').should == []
      ensure
        Dir.rmdir('no_permission')
      end
    end
  end
end