answer
stringlengths
15
1.25M
#pragma once #include <memory> #include "kernel/expr.h" namespace lean { /** \brief Functional object for creating expressions with maximally shared sub-expressions. */ class max_sharing_fn { struct imp; friend expr max_sharing(expr const & a); std::unique_ptr<imp> m_ptr; public: max_sharing_fn(); ~max_sharing_fn(); expr operator()(expr const & a); /** \brief Clear the cache. */ void clear(); }; /** \brief The resultant expression is structurally identical to the input one, but it uses maximally shared sub-expressions. */ expr max_sharing(expr const & a); }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace ExemploEFCrud { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.<API key>(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
\hypertarget{<API key>}{\section{jamms Directory Reference} \label{<API key>}\index{jamms Directory Reference@{jamms Directory Reference}} } Directory dependency graph for jamms\+:\nopagebreak \begin{figure}[H] \begin{center} \leavevmode \includegraphics[width=262pt]{<API key>} \end{center} \end{figure} \subsection*{Directories} \begin{DoxyCompactItemize} \item directory \hyperlink{<API key>}{Tower\+Defense} \end{DoxyCompactItemize}
# AUTOGENERATED FILE FROM balenalib/<API key>:3.12-run # remove several traces of python RUN apk del python* # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apk add --no-cache ca-certificates libffi \ && apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 # point Python at a system-provided certificate database. Otherwise, we might hit <API key>. ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt ENV PYTHON_VERSION 3.8.12 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.3.1 ENV SETUPTOOLS_VERSION 60.5.4 RUN set -x \ && buildDeps=' \ curl \ gnupg \ ' \ && apk add --no-cache --virtual .build-deps $buildDeps \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.<API key>.3.tar.gz" \ && echo "<SHA256-like> Python-$PYTHON_VERSION.<API key>.3.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.<API key>.3.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.<API key>.3.tar.gz" \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/<SHA1-like>/get-pip.py" \ && echo "<SHA256-like> get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/<SHA1-like>/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https: RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && ln -f /bin/sh /bin/sh.real \ && ln -f /bin/sh-shim /bin/sh
# coding=utf-8 from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--<API key>', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def <API key>(cls): return (super(GoThriftGen, cls).<API key>() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): <API key> = self.get_options().<API key> thrift_imports = self.context.resolve(<API key>) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def <API key>(self, target, target_workdir): for source in target.<API key>(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def <API key>(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.<API key>()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def <API key>(self): """Override `<API key>` to exclude `provides`.""" return [a for a in super(GoThriftGen, self).<API key> if a != 'provides'] def <API key>(self, target, target_workdir): all_sources = list(target.<API key>()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep))
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_25) on Tue Feb 07 22:52:55 CET 2012 --> <TITLE> S-Index </TITLE> <META NAME="date" CONTENT="2012-02-07"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="S-Index"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../com/osbcp/cssparser/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-8.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <A HREF="index-1.html">A</A> <A HREF="index-2.html">C</A> <A HREF="index-3.html">E</A> <A HREF="index-4.html">G</A> <A HREF="index-5.html">H</A> <A HREF="index-6.html">I</A> <A HREF="index-7.html">P</A> <A HREF="index-8.html">R</A> <A HREF="index-9.html">S</A> <A HREF="index-10.html">T</A> <A HREF="index-11.html">V</A> <HR> <A NAME="_S_"></A><H2> <B>S</B></H2> <DL> <DT><A HREF="../com/osbcp/cssparser/Selector.html" title="class in com.osbcp.cssparser"><B>Selector</B></A> - Class in <A HREF="../com/osbcp/cssparser/package-summary.html">com.osbcp.cssparser</A><DD>Represents a CSS selector.<DT><A HREF="../com/osbcp/cssparser/Selector.html#Selector(java.lang.String)"><B>Selector(String)</B></A> - Constructor for class com.osbcp.cssparser.<A HREF="../com/osbcp/cssparser/Selector.html" title="class in com.osbcp.cssparser">Selector</A> <DD>Creates a new selector. </DL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../com/osbcp/cssparser/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-8.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <A HREF="index-1.html">A</A> <A HREF="index-2.html">C</A> <A HREF="index-3.html">E</A> <A HREF="index-4.html">G</A> <A HREF="index-5.html">H</A> <A HREF="index-6.html">I</A> <A HREF="index-7.html">P</A> <A HREF="index-8.html">R</A> <A HREF="index-9.html">S</A> <A HREF="index-10.html">T</A> <A HREF="index-11.html">V</A> <HR> </BODY> </HTML>
# Github pages for DHGMS Solutions ## Introduction This is the branch for the [Github pages for the DHGMS Solutions project documentation](http://dhgms-solutions.github.io/). ## Viewing the documentation The documentation can be found at http://dhgms-solutions.github.io/ ## Contributing to the documentation It is likely you won't want to contribute to this repository, but one of the [actual project repositories](https://github.com/DHGMS-Solutions/). 1\. Fork the documentation See the [github help page for instructions on how to create a fork](http://help.github.com/fork-a-repo/). 2\. Write desired content Use your preffered method for carrying out work. 3\. Send a pull request See the [github help page for instructions on how to send pull requests](http://help.github.com/send-pull-requests/)
var gplay = require('google-play-scraper'); var fs = require('fs') var Promise = require('promise'); var myArgs = process.argv.slice(2); var passed_appid = myArgs[0]; var passed_appcount = myArgs[1]; console.log(passed_appid); var read = Promise.denodeify(fs.readFile); var write = Promise.denodeify(fs.writeFile); var dir = './dataset/' + passed_appcount; gplay.app({appId: passed_appid}) .then(function (str) { if(JSON.stringify(str, null, ' ').indexOf("title") > -1) { if (!fs.existsSync(dir)){ fs.mkdirSync(dir); } return write(dir + '/meta.json', JSON.stringify(str, null, ' '), 'utf8') } else { console.log('app doesnt exist'); return false } }) .then(function (){process.exit()});
import unittest, re from rexp.compiler import PatternCompiler class CompilerTestMethods(unittest.TestCase): def test_compile_1(self): compiler = PatternCompiler(pattern_set=dict( TEST=r'\w+' )) try: c1 = compiler.compile('$1{TEST}') except Exception as exc: self.assertTrue(1) c1 = compiler.compile('$1{TEST}', ['test']) self.assertEqual(c1, r'(?:(?P<test>(\w+)))') def test_compile_2(self): compiler = PatternCompiler(pattern_set=dict( TEST=r'\w+' )) try: c1 = compiler.compile('$1{TEST}') except: self.assertTrue(1) c1 = compiler.compile('$1{TEST}', ['test']) self.assertEqual(c1, r'(?:(?P<test>(\w+)))')
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Thu Sep 17 01:48:29 IST 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Class org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery (Solr 5.3.1 API)</title> <meta name="date" content="2015-09-17"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery (Solr 5.3.1 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/solr/client/solrj/request/CoreAdminRequest.RequestRecovery.html" title="class in org.apache.solr.client.solrj.request">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/solr/client/solrj/request/class-use/CoreAdminRequest.RequestRecovery.html" target="_top">Frames</a></li> <li><a href="CoreAdminRequest.RequestRecovery.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery" class="title">Uses of Class<br>org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery</h2> </div> <div class="classUseContainer">No usage of org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/solr/client/solrj/request/CoreAdminRequest.RequestRecovery.html" title="class in org.apache.solr.client.solrj.request">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/solr/client/solrj/request/class-use/CoreAdminRequest.RequestRecovery.html" target="_top">Frames</a></li> <li><a href="CoreAdminRequest.RequestRecovery.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2015 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
// Models app.SearchModel = Backbone.Model.extend({ idAttribute: "session_token", urlRoot: function() { var u = '/search/' + this.id; return u; } }); // Collections app.SearchCollection = Backbone.Collection.extend({ model: app.SearchModel, url: function() { if (typeof this.id === 'undefined') return '/search'; else return '/search/' + this.id; }, initialize: function(options) { if (typeof options != 'undefined') this.id = options.session_token; } }); // Views app.cardList = Backbone.View.extend({ el: '#cardList' }); app.cardView = Backbone.View.extend({ tagName: 'div', initialize: function(card) { this.card = card; }, template: _.template($("#card-template").html()), render: function(cardList) { this.$el.html(this.template({ card: this.card })); this.$el.addClass('card'); cardList.$el.append(this.el); return this; } });
layout: post title: "383. Ransom Note-" subtitle: " \"LeetCode\"" date: 2016-9-13 10:08:36 author: "Zering" header-img: "img/road.jpg" catalog: true tags: - LeetCode https://leetcode.com/problems/ransom-note/ Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note: You may assume that both strings contain only lowercase letters. canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true 1. 2. ransomNotemagazinebytemagazine00 ransomNotemagazineransomNotemagazinemagazinemagazineransomNote LeetCode DiscussmagazineransomNote java public boolean canConstruct(String ransomNote, String magazine) { boolean ret = true; byte[] bytes = new byte[magazine.length()]; for (int i = 0; i < ransomNote.length(); i++) { char c = ransomNote.charAt(i); boolean found = false; for (int j = 0; j < magazine.length(); j++) { if (bytes[j] == 0 && magazine.charAt(j) == c) { bytes[j]++; found = true; break; } } if (!found) { ret = false; break; } } return ret; } public boolean canConstruct(String ransomNote, String magazine) { boolean ret = true; char[] ra = ransomNote.toCharArray(); Arrays.sort(ra); char[] ma = magazine.toCharArray(); Arrays.sort(ma); int index = 0; boolean found = true; for (int i = 0; i < ra.length && ret; i++) { char ri = ra[i]; found = false; for (int j = index; j < ma.length; j++) { if (ma[j] > ri) { ret = false; break; } else if (ma[j] == ri) { index++; found = true; break; } else { index++; } } if (!found) { ret = false; break; } } return ret; } public boolean canConstruct(String ransomNote, String magazine) { int[] arr = new int[26]; for (int i = 0; i < magazine.length(); i++) { arr[magazine.charAt(i) - 'a']++; } for (int i = 0; i < ransomNote.length(); i++) { if(--arr[ransomNote.charAt(i)-'a'] < 0) { return false; } } return true; } [https:
package com.yuzhou.viewer.service; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.google.common.eventbus.EventBus; import com.loopj.android.http.<API key>; import com.loopj.android.http.SyncHttpClient; import com.yuzhou.viewer.R; import com.yuzhou.viewer.model.GoogleImage; import com.yuzhou.viewer.model.GoogleImageFactory; import org.apache.http.Header; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class GoogleApiTask extends AsyncTask<ApiParam, Integer, List<GoogleImage>> { private final SyncHttpClient client = new SyncHttpClient(); private final List<GoogleImage> items = new ArrayList<>(); private final EventBus eventBus; private final Context context; private int errorResource; public GoogleApiTask(EventBus eventBus, Context context) { this.eventBus = eventBus; this.context = context; } private List<GoogleImage> interExecute(ApiParam request) { Log.d("VIEWER", request.toString()); client.get(request.getUrl(), request.getParams(), new <API key>() { @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject response) { Log.i("VIEWER", "status code=" + statusCode + ", response=" + response + ", error=" + throwable.getMessage()); errorResource = R.string.<API key>; } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { if (response == null) { Log.i("VIEWER", "Response no context"); errorResource = R.string.error_server_side; return; } try { int httpCode = response.getInt("responseStatus"); if (httpCode == 400) { errorResource = R.string.<API key>; Log.d("VIEWER", "response=" + response.getString("responseDetails")); return; } if (httpCode != 200) { errorResource = R.string.error_server_side; Log.d("VIEWER", "response=" + response.getString("responseDetails")); return; } List<GoogleImage> images = GoogleImageFactory.create(response); if (images.isEmpty()) { Log.i("VIEWER", "Can not parse JSON"); Log.d("VIEWER", "response=" + response.toString()); errorResource = R.string.error_server_side; return; } items.addAll(images); } catch (JSONException e) { Log.i("VIEWER", "Can not parse JSON"); e.printStackTrace(); } } }); return items; } @Override protected List<GoogleImage> doInBackground(ApiParam... requests) { ApiParam request = requests[0]; return interExecute(request); } @Override protected void onPreExecute() { items.clear(); } @Override protected void onPostExecute(List<GoogleImage> googleImages) { if (errorResource > 0) { Toast.makeText(context, errorResource, Toast.LENGTH_LONG).show(); } eventBus.post(items); } }
<?php /** * Smarty Internal Plugin Compile Insert * * Compiles the {insert} tag * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Insert Class * * @package Smarty * @subpackage Compiler */ class <API key> extends <API key> { /** * Attribute definition: Overwrites base class. * * @var array * @see <API key> */ public $required_attributes = array('name'); /** * Attribute definition: Overwrites base class. * * @var array * @see <API key> */ public $shorttag_order = array('name'); /** * Attribute definition: Overwrites base class. * * @var array * @see <API key> */ public $optional_attributes = array('_any'); /** * Compiles code for the {insert} tag * * @param array $args array with attributes from parser * @param object $compiler compiler object * * @return string compiled code */ public function compile($args, $compiler) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); // never compile as nocache code $compiler-><API key> = true; $compiler->tag_nocache = true; $_smarty_tpl = $compiler->template; $_name = null; $_script = null; $_output = '<?php '; // save posible attributes eval('$_name = ' . $_attr['name'] . ';'); if (isset($_attr['assign'])) { // output will be stored in a smarty variable instead of being displayed $_assign = $_attr['assign']; // create variable to make shure that the compiler knows about its nocache status $compiler->template->tpl_vars[trim($_attr['assign'], "'")] = new Smarty_Variable(null, true); } if (isset($_attr['script'])) { // script which must be included $_function = "smarty_insert_{$_name}"; $_smarty_tpl = $compiler->template; $_filepath = false; eval('$_script = ' . $_attr['script'] . ';'); if (!isset($compiler->smarty->security_policy) && file_exists($_script)) { $_filepath = $_script; } else { if (isset($compiler->smarty->security_policy)) { $_dir = $compiler->smarty->security_policy->trusted_dir; } else { $_dir = $compiler->smarty->trusted_dir; } if (!empty($_dir)) { foreach ((array)$_dir as $_script_dir) { $_script_dir = rtrim($_script_dir, '/\\') . DS; if (file_exists($_script_dir . $_script)) { $_filepath = $_script_dir . $_script; break; } } } } if ($_filepath == false) { $compiler-><API key>("{insert} missing script file '{$_script}'", $compiler->lex->taglineno); } // code for script file loading $_output .= "require_once '{$_filepath}' ;"; require_once $_filepath; if (!is_callable($_function)) { $compiler-><API key>(" {insert} function '{$_function}' is not callable in script file '{$_script}'", $compiler->lex->taglineno); } } else { $_filepath = 'null'; $_function = "insert_{$_name}"; // function in PHP script ? if (!is_callable($_function)) { // try plugin if (!$_function = $compiler->getPlugin($_name, 'insert')) { $compiler-><API key>("{insert} no function or plugin found for '{$_name}'", $compiler->lex->taglineno); } } } // delete {insert} standard attributes unset($_attr['name'], $_attr['assign'], $_attr['script'], $_attr['nocache']); // convert attributes into parameter array string $_paramsArray = array(); foreach ($_attr as $_key => $_value) { $_paramsArray[] = "'$_key' => $_value"; } $_params = 'array(' . implode(", ", $_paramsArray) . ')'; // call insert if (isset($_assign)) { if ($_smarty_tpl->caching) { $_output .= "echo <API key>::compile ('{$_function}',{$_params}, \$_smarty_tpl, '{$_filepath}',{$_assign});?>"; } else { $_output .= "\$_smarty_tpl->assign({$_assign} , {$_function} ({$_params},\$_smarty_tpl), true);?>"; } } else { $compiler->has_output = true; if ($_smarty_tpl->caching) { $_output .= "echo <API key>::compile ('{$_function}',{$_params}, \$_smarty_tpl, '{$_filepath}');?>"; } else { $_output .= "echo {$_function}({$_params},\$_smarty_tpl);?>"; } } return $_output; } } ?>
function htmlEncode(value){ return $('<div/>').text(value).html(); } var app = angular.module("oasassets",[]).controller("snippetsController",function($scope){ $scope.snippet = function(item){ var elem = $("#"+item); var contents = elem.html().trim(); elem.html(htmlEncode(contents)); $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }; $scope.loadMenu = function(){ $('#side-menu').metisMenu(); }; });
package org.tuxdevelop.spring.batch.lightmin.server.cluster.configuration; import lombok.Data; import org.springframework.boot.context.properties.<API key>; import org.springframework.boot.context.properties.<API key>; @Data @<API key>(prefix = "spring.batch.lightmin.server.cluster.infinispan") public class <API key> { @<API key> private <API key> repository = new <API key>(); @Data static class <API key> { private Boolean <API key> = Boolean.FALSE; private Boolean <API key> = Boolean.FALSE; } }
<?php $this->Nm_lang_conf_region = array(); $this->Nm_lang_conf_region['en_us;en_us'] = "English (United States)"; $this->Nm_lang_conf_region['es;es_es'] = "Spanish (Spain)"; $this->Nm_lang_conf_region['pt_br;pt_br'] = "Portuguese (Brazil)"; ksort($this->Nm_lang_conf_region); ?>
<?php // Make sure we're being called from the command line, not a web interface if (PHP_SAPI !== 'cli') { die('This is a command line only application.'); } // We are a valid entry point. const _JEXEC = 1; error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', 1); // Load system defines if (file_exists(dirname(__DIR__) . '/defines.php')) { require_once dirname(__DIR__) . '/defines.php'; } if (!defined('_JDEFINES')) { define('JPATH_BASE', dirname(__DIR__)); require_once JPATH_BASE . '/includes/defines.php'; } require_once JPATH_LIBRARIES . '/import.legacy.php'; require_once JPATH_LIBRARIES . '/cms.php'; // Load the configuration require_once JPATH_CONFIGURATION . '/configuration.php'; class InsertCatExampleCli extends JApplicationCli { public function __construct() { parent::__construct(); $this->config = new JConfig(); $this->dbo = JDatabase::getInstance( array( 'driver' => $this->config->dbtype, 'host' => $this->config->host, 'user' => $this->config->user, 'password' => $this->config->password, 'database' => $this->config->db, 'prefix' => $this->config->dbprefix, ) ); // important for storing several rows JFactory::$application = $this; } public function doExecute() { $category_titles = array("Test Title 1", "Test Title 2", "Test Title 3"); // add categories to database for ($i=0; $i<count($category_titles); $i++) { $this->insertCategory($category_titles[$i]); } } private function insertCategory($cat_title) { $tbl_cat = JTable::getInstance("Category"); // get existing aliases from categories table $tab = $this->dbo->quoteName($this->config->dbprefix . "categories"); $conditions = array( $this->dbo->quoteName("extension") . " LIKE 'com_content'" ); $query = $this->dbo->getQuery(true); $query ->select($this->dbo->quoteName("alias")) ->from($tab) ->where($conditions); $this->dbo->setQuery($query); $cat_from_db = $this->dbo->loadObjectList(); $category_existing = False; $new_cat_alias = JFilterOutput::stringURLSafe($cat_title); foreach ($cat_from_db as $cdb) { if ($cdb->alias == $new_cat_alias) { $category_existing = True; echo "category already existing: " . $new_cat_alias . "\n"; } } if (!$category_existing) { $values = [ "id" => null, "title" => $cat_title, "path" => $new_cat_alias, "access" => 1, "extension" => "com_content", "published" => 1, "language" => "*", "created_user_id" => 0, "params" => array ( "category_layout" => "", "image" => "", ), "metadata" => array ( "author" => "", "robots" => "", ), ]; $tbl_cat->setLocation(1, "last-child"); if (!$tbl_cat->bind($values)) { JError::raiseWarning(500, $row->getError()); return FALSE; } if (!$tbl_cat->check()) { JError::raiseError(500, $article->getError()); return FALSE; } if (!$tbl_cat->store(TRUE)) { JError::raiseError(500, $article->getError()); return FALSE; } $tbl_cat->rebuildPath($tbl_cat->id); echo "category inserted: " . $tbl_cat->id . " - " . $new_cat_alias . "\n"; } } } try { JApplicationCli::getInstance('InsertCatExampleCli')->execute(); } catch (Exception $e) { // An exception has been caught, just echo the message. fwrite(STDOUT, $e->getMessage() . "\n"); exit($e->getCode()); } ?>
module <API key> # Container for common args, mainly to have stricter validation on # inputs. Tried to use GetoptLong but could not write solid unit # tests around it... so we have our own internal simple implementation. class Args if !defined?(<API key>) <API key> = { :artifact_name => "Specifies the name of the artifact. Tag will be appended to this name", :user => "Connect to the database as this username instead of the default", :host => "Specifies the host name of the machine on which the server is running", :port => "Specifies the port on which the server is running", :name => "Specifies the name of the database to which to connect", :url => "The connection string for the psql database", :dir => "Path to a directory", :tag => "A git tag (e.g. 0.0.1)", :prefix => "Configure installer to use this prefix", :set => "Passthrough for postgresql --set argument" } FLAGS_NO_ARGUMENTS = { :password => "Prompt user to enter password for the database user. Password is stored for the duration of the process", :dry_run => "Include flag to echo commands that will run without actually executing them", :help => "Display help", :verbose => "Enable verbose logging of all system calls", } end attr_reader :artifact_name, :host, :port, :name, :prefix, :url, :user, :dir, :dry_run, :tag, :password, :set # args: Actual string arguments # :required => list of parameters that are required # :optional => list of parameters that are optional def initialize(args, opts={}) Preconditions.assert_class_or_nil(args, String) required = (opts.delete(:required) || []).map { |flag| format_flag(flag) } optional = (opts.delete(:optional) || []).map { |flag| format_flag(flag) } Preconditions.assert_class(required, Array) Preconditions.assert_class(optional, Array) Preconditions.assert_empty_opts(opts) Preconditions.check_state(optional.size + required.size > 0, "Must have at least 1 optional or required parameter") if !optional.include?(:help) optional << :help end if !optional.include?(:verbose) optional << :verbose end found_arguments = <API key>(args) missing = required.select { |field| blank?(found_arguments[field]) } @artifact_name = found_arguments.delete(:artifact_name) @host = found_arguments.delete(:host) @port = found_arguments.delete(:port) @name = found_arguments.delete(:name) @prefix = found_arguments.delete(:prefix) @url = found_arguments.delete(:url) @user = found_arguments.delete(:user) @dir = found_arguments.delete(:dir) @tag = found_arguments.delete(:tag) @set = found_arguments.delete(:set) @dry_run = found_arguments.delete(:dry_run) @password = found_arguments.delete(:password) @help = found_arguments.delete(:help) @verbose = found_arguments.delete(:verbose) Preconditions.check_state(found_arguments.empty?, "Did not handle all flags: %s" % found_arguments.keys.join(" ")) if @help RdocUsage.printAndExit(0) end if @verbose Library.set_verbose(true) end if !missing.empty? <API key>(required, optional, missing) end end # Hack to minimize bleeding from STDIN. Returns an instance of Args class def Args.from_stdin(opts) values = ARGV.join(" ") Args.new(values, opts) end private def blank?(value) value.to_s.strip == "" end def <API key>(required, optional, fields) Preconditions.assert_class(fields, Array) Preconditions.check_state(!fields.empty?, "Missing fields cannot be empty") title = fields.size == 1 ? "Missing parameter" : "Missing parameters" sorted = fields.sort_by { |f| f.to_s } puts "**************************************************" puts "ERROR: #{title}: #{sorted.join(", ")}" puts "**************************************************" puts help_parameters("Required parameters", required) puts help_parameters("Optional parameters", optional) exit(1) end def help_parameters(title, parameters) docs = [] if !parameters.empty? docs << "" docs << title docs << " parameters.each do |flag| documentation = <API key>[flag] || FLAGS_NO_ARGUMENTS[flag] Preconditions.check_not_null(documentation, "No documentation found for flag[%s]" % flag) docs << " --#{flag}" docs << " " + documentation docs << "" end end docs.join("\n") end def <API key>(args) Preconditions.assert_class_or_nil(args, String) found = {} index = 0 values = args.to_s.strip.split(/\s+/) while index < values.length do flag = format_flag(values[index]) index += 1 if <API key>.has_key?(flag) found[flag] = values[index] index += 1 elsif FLAGS_NO_ARGUMENTS.has_key?(flag) found[flag] = true else raise "Unknown flag[%s]" % flag end end found end # Strip leading dashes and convert to symbol def format_flag(flag) Preconditions.assert_class(flag, String) flag.sub(/^\-\-/, '').to_sym end end end
<?php namespace Ajax\semantic\components\validation; use Ajax\service\AjaxCall; use Ajax\JsUtils; /** * @author jc * @version 1.001 * Generates a JSON Rule for the validation of a field */ class Rule implements \JsonSerializable{ /** * @var string */ private $type; /** * @var string */ private $prompt; /** * @var string */ private $value; public function __construct($type,$prompt=NULL,$value=NULL){ $this->type=$type; $this->prompt=$prompt; $this->value=$value; } public function getType() { return $this->type; } public function setType($type) { $this->type=$type; return $this; } public function getPrompt() { return $this->prompt; } public function setPrompt($prompt) { $this->prompt=$prompt; return $this; } public function getValue() { return $this->value; } public function setValue($value) { $this->value=$value; return $this; } #[\<API key>] public function jsonSerialize() { $result= ["type"=>$this->type]; if(isset($this->prompt)) $result["prompt"]=$this->prompt; if(isset($this->value)) $result["value"]=$this->value; return $result; } /** * A field should match the value of another validation field, for example to confirm passwords * @param string $name * @param string $prompt * @return \Ajax\semantic\components\validation\Rule */ public static function match($name,$prompt=NULL){ return new Rule("match[".$name."]",$prompt); } /** * A field should be different than another specified field * @param string $name * @param string $prompt * @return \Ajax\semantic\components\validation\Rule */ public static function different($name,$prompt=NULL){ return new Rule("different[".$name."]",$prompt); } /** * A field is an integer value, or matches an integer range * @param int|NULL $min * @param int|NULL $max * @param string $prompt * @return \Ajax\semantic\components\validation\Rule */ public static function integer($min=NULL,$max=NULL,$prompt=NULL){ if(\is_int($min) && \is_int($max)) return new Rule("integer[{$min}..{$max}]",$prompt); return new Rule("integer",$prompt); } public static function decimal($prompt=NULL){ return new Rule("decimal",$prompt); } public static function number($prompt=NULL){ return new Rule("number",$prompt); } public static function is($value,$prompt=NULL){ return new Rule("is[".$value."]",$prompt); } public static function isExactly($value,$prompt=NULL){ return new Rule("isExactly[".$value."]",$prompt); } public static function not($value,$prompt=NULL){ return new Rule("not[".$value."]",$prompt); } public static function notExactly($value,$prompt=NULL){ return new Rule("notExactly[".$value."]",$prompt); } public static function contains($value,$prompt=NULL){ return new Rule("contains[".$value."]",$prompt); } public static function containsExactly($value,$prompt=NULL){ return new Rule("containsExactly[".$value."]",$prompt); } public static function doesntContain($value,$prompt=NULL){ return new Rule("doesntContain[".$value."]",$prompt); } public static function <API key>($value,$prompt=NULL){ return new Rule("<API key>[".$value."]",$prompt); } public static function minCount($value,$prompt=NULL){ return new Rule("minCount[".$value."]",$prompt); } public static function maxCount($value,$prompt=NULL){ return new Rule("maxCount[".$value."]",$prompt); } public static function exactCount($value,$prompt=NULL){ return new Rule("exactCount[".$value."]",$prompt); } public static function email($prompt=NULL){ return new Rule("email",$prompt); } public static function url($prompt=NULL){ return new Rule("url",$prompt); } public static function regExp($value,$prompt=NULL){ return new Rule("regExp",$prompt,$value); } public static function custom($name,$jsFunction){ return "$.fn.form.settings.rules.".$name." =".$jsFunction ; } public static function ajax(JsUtils $js,$name,$url,$params,$jsCallback,$method="post",$parameters=[]){ $parameters=\array_merge(["async"=>false,"url"=>$url,"params"=>$params,"hasLoader"=>false,"jsCallback"=>$jsCallback,"dataType"=>"json","stopPropagation"=>false,"preventDefault"=>false,"responseElement"=>null],$parameters); $ajax=new AjaxCall($method, $parameters); return self::custom($name, "function(value,ruleValue){var result=true;".$ajax->compile($js)."return result;}"); } }
import torch from deluca.lung.core import Controller, LungEnv class PIDCorrection(Controller): def __init__(self, base_controller: Controller, sim: LungEnv, pid_K=[0.0, 0.0], decay=0.1, **kwargs): self.base_controller = base_controller self.sim = sim self.I = 0.0 self.K = pid_K self.decay = decay self.reset() def reset(self): self.base_controller.reset() self.sim.reset() self.I = 0.0 def compute_action(self, state, t): u_in_base, u_out = self.base_controller(state, t) err = self.sim.pressure - state self.I = self.I * (1 - self.decay) + err * self.decay pid_correction = self.K[0] * err + self.K[1] * self.I u_in = torch.clamp(u_in_base + pid_correction, min=0.0, max=100.0) self.sim(u_in, u_out, t) return u_in, u_out
# Numulariola mucronata (Mont.) P.M.D. Martin, 1976 SPECIES # Status SYNONYM # According to The Catalogue of Life, 3rd January 2011 # Published in S. Afr. J. Bot. 42(1): 78 (1976) # Original name Camillea mucronata Mont., 1855 Remarks null
package org.ngrinder.home.controller; import lombok.<API key>; import org.ngrinder.common.constant.ControllerConstants; import org.ngrinder.home.model.PanelEntry; import org.ngrinder.home.service.HomeService; import org.ngrinder.infra.config.Config; import org.ngrinder.script.handler.ScriptHandler; import org.ngrinder.script.handler.<API key>; import org.ngrinder.user.service.UserContext; import org.springframework.context.MessageSource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import java.util.*; import static java.util.Comparator.comparing; import static org.ngrinder.common.constant.ControllerConstants.*; import static org.ngrinder.common.util.CollectionUtils.buildMap; import static org.ngrinder.common.util.NoOp.noOp; /** * Home index page api controller. * * @since 3.5.0 */ @RestController @RequestMapping("/home/api") @<API key> public class HomeApiController { private static final String <API key> = "^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*"; private final HomeService homeService; private final <API key> <API key>; private final UserContext userContext; private final Config config; private final MessageSource messageSource; private List<TimeZone> timeZones = null; @PostConstruct public void init() { timeZones = new ArrayList<>(); final String[] timeZoneIds = TimeZone.getAvailableIDs(); for (final String id : timeZoneIds) { if (id.matches(<API key>) && !TimeZone.getTimeZone(id).getDisplayName().contains("GMT")) { timeZones.add(TimeZone.getTimeZone(id)); } } timeZones.sort(comparing(TimeZone::getID)); } @GetMapping("/handlers") public List<ScriptHandler> getHandlers() { return <API key>.getVisibleHandlers(); } @GetMapping("/panel") public Map<String, Object> getPanelEntries() { return buildMap("leftPanelEntries", getLeftPanelEntries(), "rightPanelEntries", <API key>()); } @GetMapping("/timezones") public List<TimeZone> getTimezones() { return timeZones; } @GetMapping("/config") public Map<String, Object> getCommonHomeConfig() { return buildMap( "askQuestionUrl", config.<API key>().getProperty(<API key>, getMessages(<API key>)), "seeMoreQuestionUrl", config.<API key>().getProperty(<API key>, getMessages(<API key>)), "seeMoreResourcesUrl", config.<API key>().getProperty(<API key>), "userLanguage", config.<API key>().getProperty(ControllerConstants.<API key>)); } private List<PanelEntry> <API key>() { if (config.<API key>().getPropertyBoolean(<API key>)) { // Get nGrinder Resource RSS String rightPanelRssURL = config.<API key>().getProperty(<API key>); return homeService.<API key>(rightPanelRssURL); } return Collections.emptyList(); } private List<PanelEntry> getLeftPanelEntries() { if (config.<API key>().getPropertyBoolean(<API key>)) { // Make the i18n applied QnA panel. Depending on the user language, show the different QnA panel. String leftPanelRssURLKey = getMessages(<API key>); // Make admin configure the QnA panel. String leftPanelRssURL = config.<API key>().getProperty(<API key>, leftPanelRssURLKey); return homeService.getLeftPanelEntries(leftPanelRssURL); } return Collections.emptyList(); } @GetMapping("/messagesources/{locale}") public Map<String, String> <API key>(@PathVariable String locale) { return homeService.<API key>(locale); } /** * Get the message from messageSource by the given key. * * @param key key of message * @return the found message. If not found, the error message will return. */ private String getMessages(String key) { String userLanguage = "en"; try { userLanguage = userContext.getCurrentUser().getUserLanguage(); } catch (Exception e) { noOp(); } Locale locale = new Locale(userLanguage); return messageSource.getMessage(key, null, locale); } }
package com.huawei.esdk.fusionmanager.local.model.system; import com.huawei.esdk.fusionmanager.local.model.FMSDKResponse; /** * * <p> * @since eSDK Cloud V100R003C30 */ public class <API key> extends FMSDKResponse { private ScheduleTask scheduleTask; public ScheduleTask getScheduleTask() { return scheduleTask; } public void setScheduleTask(ScheduleTask scheduleTask) { this.scheduleTask = scheduleTask; } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_74) on Mon Jan 02 20:06:46 EET 2017 --> <title>Uses of Class com.complet.DatabaseConnection</title> <meta name="date" content="2017-01-02"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.complet.DatabaseConnection"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../com/complet/package-summary.html">Package</a></li> <li><a href="../../../com/complet/DatabaseConnection.html" title="class in com.complet">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/complet/class-use/DatabaseConnection.html" target="_top">Frames</a></li> <li><a href="DatabaseConnection.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h2 title="Uses of Class com.complet.DatabaseConnection" class="title">Uses of Class<br>com.complet.DatabaseConnection</h2> </div> <div class="classUseContainer">No usage of com.complet.DatabaseConnection</div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../com/complet/package-summary.html">Package</a></li> <li><a href="../../../com/complet/DatabaseConnection.html" title="class in com.complet">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/complet/class-use/DatabaseConnection.html" target="_top">Frames</a></li> <li><a href="DatabaseConnection.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
package net.disy.eenvplus.tfes.modules.sparql.expression; import com.hp.hpl.jena.sparql.expr.E_LogicalAnd; import com.hp.hpl.jena.sparql.expr.E_LogicalOr; import com.hp.hpl.jena.sparql.expr.Expr; import com.hp.hpl.jena.sparql.syntax.ElementFilter; // NOT_PUBLISHED public class <API key> { private Expr current; private <API key>(Expr expression) { this.current = expression; } public static <API key> use(Expr expression) { return new <API key>(expression); } public Expr toExpr() { return current; } public ElementFilter toElementFilter() { return new ElementFilter(current); } public <API key> and(Expr expression) { if (expression != null) { current = new E_LogicalAnd(current, expression); } return this; } public <API key> and(Expr expression, boolean condition) { if (condition) { return and(expression); } return this; } public <API key> or(Expr expression) { if (expression != null) { current = new E_LogicalOr(current, expression); } return this; } }
(function (chaiJquery) { // Module systems magic dance. if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { // NodeJS module.exports = chaiJquery; } else if (typeof define === "function" && define.amd) { // AMD define(function () { return chaiJquery; }); } else { // Other environment (usually <script> tag): pass into global chai var global = (false || eval)("this"); global.chai.use(chaiJquery); } }(function (chai, utils) { var inspect = utils.inspect, flag = utils.flag; jQuery.fn.inspect = function (depth) { var el = jQuery('<div />').append(this.clone()); if (depth) { var children = el.children(); while (depth children = children.children(); children.html('...'); } return el.html(); }; chai.Assertion.addMethod('attr', function (name, val) { var actual = flag(this, 'object').attr(name); if (!flag(this, 'negate') || undefined === val) { this.assert( undefined !== actual , 'expected #{this} to have a #{exp} attribute' , 'expected #{this} not to have a #{exp} attribute' , name ); } if (undefined !== val) { this.assert( val === actual , 'expected #{this} to have a ' + inspect(name) + ' attribute with the value #{exp}, but the value was #{act}' , 'expected #{this} not to have a ' + inspect(name) + ' attribute with the value #{act}' , val , actual ); } flag(this, 'object', actual); }); chai.Assertion.addMethod('data', function (name, val) { if (flag(this, 'negate') && undefined !== val && undefined === flag(this, 'object').data(name)) { return; } var assertion = new chai.Assertion(flag(this, 'object').data()); if (flag(this, 'negate')) assertion = assertion.not; assertion.property(name, val); }); chai.Assertion.addMethod('class', function (className) { this.assert( flag(this, 'object').hasClass(className) , 'expected #{this} to have class #{exp}' , 'expected #{this} not to have class #{exp}' , className ); }); chai.Assertion.addMethod('id', function (id) { this.assert( flag(this, 'object').attr('id') === id , 'expected #{this} to have id #{exp}' , 'expected #{this} not to have id #{exp}' , id ); }); chai.Assertion.addMethod('html', function (html) { this.assert( flag(this, 'object').html() === html , 'expected #{this} to have HTML #{exp}' , 'expected #{this} not to have HTML #{exp}' , html ); }); chai.Assertion.addMethod('text', function (text) { this.assert( flag(this, 'object').text() === text , 'expected #{this} to have text #{exp}' , 'expected #{this} not to have text #{exp}' , text ); }); chai.Assertion.addMethod('value', function (value) { this.assert( flag(this, 'object').val() === value , 'expected #{this} to have value #{exp}' , 'expected #{this} not to have value #{exp}' , value ); }); jQuery.each(['visible', 'hidden', 'selected', 'checked', 'disabled'], function (i, attr) { chai.Assertion.addProperty(attr, function () { this.assert( flag(this, 'object').is(':' + attr) , 'expected #{this} to be ' + attr , 'expected #{this} not to be ' + attr); }); }); chai.Assertion.overwriteProperty('exist', function (_super) { return function () { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( obj.length > 0 , 'expected ' + inspect(obj.selector) + ' to exist' , 'expected ' + inspect(obj.selector) + ' not to exist'); } else { _super.apply(this, arguments); } }; }); chai.Assertion.overwriteProperty('be', function (_super) { return function () { var be = function (selector) { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( obj.is(selector) , 'expected #{this} to be #{exp}' , 'expected #{this} not to be #{exp}' , selector ); } else { _super.apply(this, arguments); } }; be.__proto__ = this; return be; } }); chai.Assertion.overwriteMethod('match', function (_super) { return function (selector) { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( obj.is(selector) , 'expected #{this} to match #{exp}' , 'expected #{this} not to match #{exp}' , selector ); } else { _super.apply(this, arguments); } } }); chai.Assertion.overwriteProperty('contain', function (_super) { return function () { _super.call(this); var contain = function (text) { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( obj.is(':contains(\'' + text + '\')') , 'expected #{this} to contain #{exp}' , 'expected #{this} not to contain #{exp}' , text ); } else { Function.prototype.apply.call(_super.call(this), this, arguments); } }; contain.__proto__ = this; return contain; } }); chai.Assertion.overwriteProperty('have', function (_super) { return function () { _super.call(this); var have = function (selector) { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( // Using find() rather than has() to work around a jQuery bug: obj.find(selector).length > 0 , 'expected #{this} to have #{exp}' , 'expected #{this} not to have #{exp}' , selector ); } }; have.__proto__ = this; return have; } }); }));
package util import "errors" var ( // ErrNotFound Import or Version was not found. ErrNotFound = errors.New("Requested resource was not found") // ErrAlreadyExists Import or Version already exists and cannot be overwritten. ErrAlreadyExists = errors.New("Resource already exists and cannot be overritten") // ErrDisabled Import or Version has been disabled and cannot be downloaded. ErrDisabled = errors.New("Resource disabled") )
using System; using System.Numerics; namespace IllyriadGames.ByteArrayExtensions { public static class <API key> { private static readonly int _vectorSpan = Vector<byte>.Count; private static readonly int _vectorSpan2 = Vector<byte>.Count + Vector<byte>.Count; private static readonly int _vectorSpan3 = Vector<byte>.Count + Vector<byte>.Count + Vector<byte>.Count; private static readonly int _vectorSpan4 = Vector<byte>.Count + Vector<byte>.Count + Vector<byte>.Count + Vector<byte>.Count; private const int _longSpan = sizeof(long); private const int _longSpan2 = sizeof(long) + sizeof(long); private const int _longSpan3 = sizeof(long) + sizeof(long) + sizeof(long); private const int _intSpan = sizeof(int); <summary> Copies a specified number of bytes from a source array starting at a particular offset to a destination array starting at a particular offset, not safe for overlapping data. </summary> <param name="src">The source buffer</param> <param name="srcOffset">The zero-based byte offset into src</param> <param name="dst">The destination buffer</param> <param name="dstOffset">The zero-based byte offset into dst</param> <param name="count">The number of bytes to copy</param> <exception cref="<API key>"><paramref name="src"/> or <paramref name="dst"/> is null</exception> <exception cref="<API key>"><paramref name="srcOffset"/>, <paramref name="dstOffset"/>, or <paramref name="count"/> is less than 0</exception> <exception cref="ArgumentException"> The number of bytes in src is less than srcOffset plus count.-or- The number of bytes in dst is less than dstOffset plus count. </exception> <remarks> Code must be optimized, in release mode and <see cref="Vector"/>.<API key> must be true for the performance benefits. </remarks> public unsafe static void VectorizedCopy(this byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) { #if !DEBUG // Tests need to check even if <API key> == false if (Vector.<API key>) { #endif if (count > 512 + 64) { // In-built copy faster for large arrays (vs repeated bounds checks on Vector.ctor?) Array.Copy(src, srcOffset, dst, dstOffset, count); return; } if (src == null) throw new <API key>(nameof(src)); if (dst == null) throw new <API key>(nameof(dst)); if (count < 0 || srcOffset < 0 || dstOffset < 0) throw new <API key>(nameof(count)); if (count == 0) return; if (srcOffset + count > src.Length) throw new ArgumentException(nameof(src)); if (dstOffset + count > dst.Length) throw new ArgumentException(nameof(dst)); while (count >= _vectorSpan4) { new Vector<byte>(src, srcOffset).CopyTo(dst, dstOffset); new Vector<byte>(src, srcOffset + _vectorSpan).CopyTo(dst, dstOffset + _vectorSpan); new Vector<byte>(src, srcOffset + _vectorSpan2).CopyTo(dst, dstOffset + _vectorSpan2); new Vector<byte>(src, srcOffset + _vectorSpan3).CopyTo(dst, dstOffset + _vectorSpan3); if (count == _vectorSpan4) return; count -= _vectorSpan4; srcOffset += _vectorSpan4; dstOffset += _vectorSpan4; } if (count >= _vectorSpan2) { new Vector<byte>(src, srcOffset).CopyTo(dst, dstOffset); new Vector<byte>(src, srcOffset + _vectorSpan).CopyTo(dst, dstOffset + _vectorSpan); if (count == _vectorSpan2) return; count -= _vectorSpan2; srcOffset += _vectorSpan2; dstOffset += _vectorSpan2; } if (count >= _vectorSpan) { new Vector<byte>(src, srcOffset).CopyTo(dst, dstOffset); if (count == _vectorSpan) return; count -= _vectorSpan; srcOffset += _vectorSpan; dstOffset += _vectorSpan; } if (count > 0) { fixed (byte* srcOrigin = src) fixed (byte* dstOrigin = dst) { var pSrc = srcOrigin + srcOffset; var dSrc = dstOrigin + dstOffset; if (count >= _longSpan) { var lpSrc = (long*)pSrc; var ldSrc = (long*)dSrc; if (count < _longSpan2) { count -= _longSpan; pSrc += _longSpan; dSrc += _longSpan; *ldSrc = *lpSrc; } else if (count < _longSpan3) { count -= _longSpan2; pSrc += _longSpan2; dSrc += _longSpan2; *ldSrc = *lpSrc; *(ldSrc + 1) = *(lpSrc + 1); } else { count -= _longSpan3; pSrc += _longSpan3; dSrc += _longSpan3; *ldSrc = *lpSrc; *(ldSrc + 1) = *(lpSrc + 1); *(ldSrc + 2) = *(lpSrc + 2); } } if (count >= _intSpan) { var ipSrc = (int*)pSrc; var idSrc = (int*)dSrc; count -= _intSpan; pSrc += _intSpan; dSrc += _intSpan; *idSrc = *ipSrc; } while (count > 0) { count *dSrc = *pSrc; dSrc += 1; pSrc += 1; } } } #if !DEBUG } else { Array.Copy(src, srcOffset, dst, dstOffset, count); return; } #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; #if USE_FASTQUANT namespace FastQuant.Tests #else namespace SmartQuant.Tests #endif { public class TickSeriesTest { [Fact] public void TestGetIndex() { var ts = new TickSeries("test"); for (int i = 0; i < 10; ++i) ts.Add(new Tick { DateTime = new DateTime(2000, 1, 1, 10, i, 30) }); var firstDt = new DateTime(2000, 1, 1, 10, 3, 30); var firstTick = new Tick { DateTime = firstDt }; var lastDt = new DateTime(2000, 1, 1, 10, 9, 30); var lastTick = new Tick { DateTime = lastDt }; // DateTime is in the middle; Assert.Equal(3, ts.GetIndex(firstDt, IndexOption.Null)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Null)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Null)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Prev)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Next)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Null)); Assert.Equal(3, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Prev)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Next)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Null)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Prev)); Assert.Equal(5, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Next)); // DateTime > LastDateTime Assert.Equal(5, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Next)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Null)); Assert.Equal(9, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Prev)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Next)); // DateTime < FirstDateTime Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Null)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Prev)); Assert.Equal(0, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Next)); } } }
package com.sectong.util; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; public class HttpUtil { private static Logger logger = Logger.getLogger(HttpUtil.class); private final static int CONNECT_TIMEOUT = 5000; // in milliseconds private final static String DEFAULT_ENCODING = "UTF-8"; public static String postData(String urlStr, String data){ return postData(urlStr, data, null); } public static String postData(String urlStr, String data, String contentType){ BufferedReader reader = null; try { URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(CONNECT_TIMEOUT); if(contentType != null) conn.setRequestProperty("content-type", contentType); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING); if(data == null) data = ""; writer.write(data); writer.flush(); writer.close(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\r\n"); } return sb.toString(); } catch (IOException e) { logger.error("Error connecting to " + urlStr + ": " + e.getMessage()); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } return null; } }
# AUTOGENERATED FILE FROM balenalib/qemux86-64-alpine:3.13-run ENV GO_VERSION 1.16.3 # set up nsswitch.conf for Go's "netgo" implementation # - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf # gcc for cgo RUN apk add --no-cache git gcc ca-certificates RUN fetchDeps='curl' \ && set -x \ && apk add --no-cache $fetchDeps \ && mkdir -p /usr/local/go \ && curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-amd64.tar.gz" \ && echo "<SHA256-like> go$GO_VERSION.linux-alpine-amd64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-alpine-amd64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-alpine-amd64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/<SHA1-like>/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https: RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && ln -f /bin/sh /bin/sh.real \ && ln -f /bin/sh-shim /bin/sh
'use strict'; viewModel.MonitoringAlarm = new Object(); var ma = viewModel.MonitoringAlarm; ma.minDatetemp = new Date(); ma.maxDatetemp = new Date(); ma.minDateRet = new Date(); ma.maxDateRet = new Date(); vm.currentMenu('Alarm Data'); vm.currentTitle('Alarm Data'); vm.<API key>(false); vm.breadcrumb([ { title: "Monitoring", href: ' { title: 'Alarm Data', href: viewModel.appName + 'page/monitoringalarm' }]); var intervalTurbine = null; ma.UpdateProjectList = function(project) { setTimeout(function(){ $('#projectList').data('kendoDropDownList').value(project); $("#projectList").data("kendoDropDownList").trigger("change"); },1000) } ma.UpdateTurbineList = function(turbineList) { if(turbineList.length == 0){ $("#turbineList").multiselect('selectAll', false).multiselect("refresh"); }else{ $('#turbineList').multiselect("deselectAll", false).multiselect("refresh"); $('#turbineList').multiselect('select', turbineList); } } ma.CreateGrid = function(gridType) { app.loading(true); $.when(fa.LoadData()).done(function () { var COOKIES = {}; var cookieStr = document.cookie; var param = { period: fa.period, dateStart: fa.dateStart, dateEnd: fa.dateEnd, turbine: [], project: "", tipe: gridType, }; if(localStorage.getItem("projectname") !== null && localStorage.getItem("turbine") !== null) { var locTurbine = localStorage.getItem("turbine"); param.turbine = locTurbine == "" ? [] : [locTurbine]; param.project = localStorage.getItem("projectname"); var tabActive = localStorage.getItem("tabActive"); $.when(ma.UpdateProjectList(param.project)).done(function () { setTimeout(function(){ ma.UpdateTurbineList(param.turbine); setTimeout(function() { ma.LoadDataAvail(param.project, gridType); if(tabActive !== null){ if(tabActive == "alarmRaw" ){ $("#alarmrawTab a:first-child").trigger('click'); }else{ ma.CreateGridAlarm(gridType, param); } } },500); app.resetLocalStorage(); }, 1500); }); } else { param.turbine = fa.turbine(); param.project = fa.project; ma.CreateGridAlarm(gridType, param); } }); } ma.buildParentFilter = function(filters, additionalFilter) { $.each(filters, function(idx, val){ if(val.filter !== undefined) { ma.buildParentFilter(val.filter.filters, additionalFilter) } additionalFilter.push(val); }); } ma.CreateGridAlarm = function(gridType, param) { var gridName = "#alarmGrid" var dt = new Date(); var time = dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds(); var nameFile = "Monitoring Alarm Down_"+ moment(new Date()).format("Y-M-D")+"_"+time; var defaultsort = [ { field: "TimeStart", dir: "desc" }, { field: "TimeEnd", dir: "asc" } ] var url = viewModel.appName + "monitoringrealtime/getdataalarm"; if(gridType == "warning") { gridName = "#warningGrid" nameFile = "Monitoring Alarm Warning"; } if(gridType == "alarmraw"){ gridName = "#alarmRawGrid" nameFile = "Monitoring Alarm Raw"; defaultsort = [ { field: "TimeStamp", dir: "desc" } ] } var columns = [{ field: "turbine", title: "Turbine", attributes: { style: "text-align:center;" }, filterable: false, width: 90 }, { field: "timestart", title: "Time Start", width: 170, filterable: false, attributes: { style: "text-align:center;" }, template: "#= moment.utc(data.timestart).format('DD-MMM-YYYY') # &nbsp; &nbsp; &nbsp; #=moment.utc(data.timestart).format('HH:mm:ss')#" }, { field: "timeend", title: "Time End", width: 170, filterable: false, attributes: { style: "text-align:center;" }, template: "#= (moment.utc(data.timeend).format('DD-MM-YYYY') == '01-01-0001'?'Not yet finished' : (moment.utc(data.timeend).format('DD-MMM-YYYY') # &nbsp; &nbsp; &nbsp; #=moment.utc(data.timeend).format('HH:mm:ss')))#" }, { field: "duration", title: "Duration (hh:mm:ss)", width: 120, attributes: { style: "text-align:center;" }, filterable: false, //template: "#= time(data.duration) #" template: '#= kendo.toString(secondsToTime(data.duration)) #', }, { field: "alarmcode", title: "Alarm Code", attributes: { style: "text-align:center;" }, filterable: { operators: { string: { eq: "Is equal to" } }, ui: function(element) { var form = element.closest("form"); form.find(".k-filter-help-text:first").text("Show items equal to:"); form.find("select").remove(); $("form").find("[data-bind='value:filters[0].value']").addClass('k-textbox'); } }, width: 90, },{ field: "alarmdesc", title: "Description", width: 330, }]; if(gridType == "alarm"){ columns.push({ field: "reduceavailability", title: "Reduce Avail.", attributes: { style: "text-align:center;" }, filterable: false, width: 90, }); } if(gridType == "alarmraw"){ columns = [{ field: "turbine", title: "Turbine", attributes: { style: "text-align:center;" }, filterable: false, width: 70 }, { field: "timestamp", title: "Timestamp", width: 120, attributes: { style: "text-align:center;" }, filterable: false, template: "#= moment.utc(data.timestamp).format('DD-MMM-YYYY') # &nbsp; &nbsp; &nbsp; #=moment.utc(data.timestamp).format('HH:mm:ss')#" }, { field: "tag", title: "Tag", width: 120, filterable: false, attributes: { style: "text-align:center;" }, }, { field: "value", title: "Value", attributes: { style: "text-align:center;" }, filterable: false, width: 70, // template: "#= kendo.toString(data.Timestamp,'n2') #" }, { field: "description", title: "Description", width: 200 }, { field: "addinfo", title: "Note", filterable: false, width: 250 }]; } $(gridName).html(''); $(gridName).kendoGrid({ dataSource: { serverPaging: true, serverSorting: true, serverFiltering: true, transport: { read: { url: url, type: "POST", data: param, dataType: "json", contentType: "application/json; charset=utf-8", }, parameterMap: function(options) { var additionalFilter = []; if(options.filter !== undefined && options.filter != null) { ma.buildParentFilter(options.filter.filters, additionalFilter) } if (additionalFilter.length > 0) { options["filter"] = additionalFilter; } return JSON.stringify(options); } }, schema: { data: function data(res) { if (!app.isFine(res)) { return; } var totalFreq = res.data.Total; var totalHour = res.data.Duration; ma.minDateRet = new Date(res.data.mindate); ma.maxDateRet = new Date(res.data.maxdate); ma.checkCompleteDate() $('#alarm_duration').text((totalHour/3600).toFixed(2)); $('#alarm_frequency').text(totalFreq); setTimeout(function(){ app.loading(false); }, 300) return res.data.Data; }, total: function data(res) { return res.data.Total; } }, pageSize: 10, sort: defaultsort, }, // toolbar: ["excel"], excel: { fileName: nameFile+".xlsx", filterable: true, allPages: true }, // pdf: { // fileName: nameFile+".pdf", sortable: true, pageable: { refresh: true, pageSizes: true, buttonCount: 5 }, filterable: { extra: false, operators: { string: { contains: "Contains", eq: "Is equal to" }, } }, columns: columns }); }; function secondsToTime(d) { d = Number(d); var h = Math.floor(d / 3600); var m = Math.floor(d % 3600 / 60); var s = Math.floor(d % 3600 % 60); var res = (h > 0 ? (h < 10 ? "0" + h : h) : "00") + ":" + (m > 0 ? (m < 10 ? "0" + m : m) : "00") + ":" + (s > 0 ? s : "00") return res; } function time(s) { return new Date(s * 1e3).toISOString().slice(-13, -5); } ma.InitDateValue = function () { var maxDateData = new Date(); var lastStartDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0)); var lastEndDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0)); $('#dateStart').data('kendoDatePicker').value(lastStartDate); $('#dateEnd').data('kendoDatePicker').value(lastEndDate); } ma.LoadDataAvail = function(projectname, gridType){ //fa.LoadData(); var payload = { project: projectname, tipe: gridType }; toolkit.ajaxPost(viewModel.appName + "monitoringrealtime/<API key>", payload, function (res) { if (!app.isFine(res)) { return; } if (res.data.Data.length == 0) { res.data.Data = []; } else { if (res.data.Data.length > 0) { ma.minDatetemp = new Date(res.data.Data[0]); ma.maxDatetemp = new Date(res.data.Data[1]); app.currentDateData = new Date(res.data.Data[1]); $('#availabledatestart').html(kendo.toString(moment.utc(ma.minDatetemp).format('DD-MMMM-YYYY'))); $('#availabledateend').html(kendo.toString(moment.utc(ma.maxDatetemp).format('DD-MMMM-YYYY'))); // $('#dateStart').data('kendoDatePicker').value( new Date(Date.UTC(moment( ma.maxDatetemp).get('year'), ma.maxDatetemp.getMonth(), ma.maxDatetemp.getDate() - 7, 0, 0, 0, 0))); // $('#dateEnd').data('kendoDatePicker').value(kendo.toString(moment.utc(res.data.Data[1]).format('DD-MMM-YYYY'))); ma.checkCompleteDate(); } } }); } ma.checkCompleteDate = function () { var currentDateData = moment.utc(ma.maxDatetemp).format('YYYY-MM-DD'); var prevDateData = moment.utc(ma.minDatetemp).format('YYYY-MM-DD'); var dateStart = moment.utc(ma.minDateRet).format('YYYY-MM-DD'); var dateEnd = moment.utc(ma.maxDateRet).format('YYYY-MM-DD'); if ((dateEnd > currentDateData) || (dateStart > currentDateData)) { fa.infoPeriodIcon(true); } else if ((dateEnd < prevDateData) || (dateStart < prevDateData)) { fa.infoPeriodIcon(true); } else { fa.infoPeriodIcon(false); fa.infoPeriodRange(""); } } ma.ToByProject = function(){ setTimeout(function(){ app.loading(true); app.resetLocalStorage(); var project = $('#projectList').data('kendoDropDownList').value(); localStorage.setItem('projectname', project); if(localStorage.getItem("projectname")){ window.location = viewModel.appName + "page/monitoringbyproject"; } },1500); } ma.exportToExcel = function(id){ $("#"+id).getKendoGrid().saveAsExcel(); } $(document).ready(function(){ $('#btnRefresh').on('click', function () { fa.checkTurbine(); if($('.nav').find('li.active').find('a.tab-custom').text() == "Alarm Down") { ma.CreateGrid("alarm"); } else if($('.nav').find('li.active').find('a.tab-custom').text() == "Alarm Warning") { ma.CreateGrid("warning"); }else{ ma.CreateGrid("alarmraw"); } }); //setTimeout(function() { $.when(ma.InitDateValue()).done(function () { setTimeout(function() { ma.CreateGrid("alarm"); ma.LoadDataAvail(fa.project, "alarm"); }, 100); }); //}, 300); $('#projectList').kendoDropDownList({ change: function () { var project = $('#projectList').data("kendoDropDownList").value(); fa.populateTurbine(project); ma.LoadDataAvail(project, "alarm"); } }); });
package com.emc.ecs.servicebroker.repository; import com.emc.ecs.servicebroker.exception.<API key>; import com.emc.ecs.servicebroker.service.s3.S3Service; import com.emc.ecs.servicebroker.model.Constants; import com.emc.object.s3.bean.GetObjectResult; import com.emc.object.s3.bean.ListObjectsResult; import com.emc.object.s3.bean.S3Object; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.<API key>; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.module.SimpleModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.servicebroker.model.binding.SharedVolumeDevice; import org.springframework.cloud.servicebroker.model.binding.VolumeDevice; import org.springframework.cloud.servicebroker.model.binding.VolumeMount; import javax.annotation.PostConstruct; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import static java.lang.String.format; @SuppressWarnings("unused") public class <API key> { static final Logger logger = LoggerFactory.getLogger(<API key>.class); public static final String FILENAME_PREFIX = "<API key>"; private final ObjectMapper objectMapper = new ObjectMapper(); { // NOTE -- ideally we would not need this code, but for now, the VolumeMount class has // custom serialization that is not matched with corresponding deserialization, so // deserializing serialized volume mounts doesn't work OOTB. SimpleModule module = new SimpleModule(); module.addDeserializer(VolumeMount.DeviceType.class, new <API key>()); module.addDeserializer(VolumeMount.Mode.class, new ModeDeserializer()); module.addDeserializer(VolumeDevice.class, new <API key>()); objectMapper.registerModule(module); } @Autowired private S3Service s3; private static String getFilename(String id) { return FILENAME_PREFIX + "/" + id + ".json"; } private static boolean isCorrectFilename (String filename) { return filename.matches(FILENAME_PREFIX + "/.*\\.json"); } private <API key> findByFilename(String filename) throws IOException { if (!isCorrectFilename(filename)) { String errorMessage = format("Invalid filename of service instance binding provided: %s", filename); throw new IOException(errorMessage); } logger.debug("Loading service instance binding from repository file {}", filename); GetObjectResult<InputStream> input = s3.getObject(filename); return objectMapper.readValue(input.getObject(), <API key>.class); } <API key> <API key>(<API key> binding) { Map<String, Object> credentials = binding.getCredentials(); credentials.remove(Constants.S3_URL); credentials.remove(Constants.<API key>); binding.setCredentials(credentials); return binding; } @PostConstruct public void initialize() throws <API key> { logger.info("Service binding file prefix: {}", FILENAME_PREFIX); } public void save(<API key> binding) throws IOException { String filename = getFilename(binding.getBindingId()); String serialized = objectMapper.writeValueAsString(binding); s3.putObject(filename, serialized); } public <API key> find(String id) throws IOException { String filename = getFilename(id); return findByFilename(filename); } public <API key> <API key>(String marker, int pageSize) throws IOException { if (pageSize < 0) { throw new IOException("Page size could not be negative number"); } List<<API key>> bindings = new ArrayList<>(); ListObjectsResult list = marker != null ? s3.listObjects(FILENAME_PREFIX + "/", getFilename(marker), pageSize) : s3.listObjects(FILENAME_PREFIX + "/", null, pageSize); for (S3Object s3Object: list.getObjects()) { String filename = s3Object.getKey(); if (isCorrectFilename(filename)) { <API key> binding = findByFilename(filename); bindings.add(<API key>(binding)); } } <API key> response = new <API key>(bindings); response.setMarker(list.getMarker()); response.setPageSize(list.getMaxKeys()); response.setNextMarker(list.getNextMarker()); return response; } public void delete(String id) { String filename = getFilename(id); s3.deleteObject(filename); } public static class ModeDeserializer extends StdDeserializer<VolumeMount.Mode> { ModeDeserializer() { this(null); } ModeDeserializer(Class<?> vc) { super(vc); } @Override public VolumeMount.Mode deserialize(JsonParser jp, <API key> ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String s = node.asText(); if (s.equals("rw")) { return VolumeMount.Mode.READ_WRITE; } else { return VolumeMount.Mode.READ_ONLY; } } } public static class <API key> extends StdDeserializer<VolumeMount.DeviceType> { <API key>() { this(null); } <API key>(Class<?> vc) { super(vc); } @Override public VolumeMount.DeviceType deserialize(JsonParser jp, <API key> ctxt) throws IOException { return VolumeMount.DeviceType.SHARED; } } public static class <API key> extends StdDeserializer<VolumeDevice> { <API key>() { this(null); } <API key>(Class<?> vc) { super(vc); } @Override public VolumeDevice deserialize(JsonParser jp, <API key> ctxt) throws IOException { return jp.getCodec().readValue(jp, SharedVolumeDevice.class); } } }
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>RepositoryAttribute Constructor (String)</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">RepositoryAttribute Constructor (String)</h1> </div> </div> <div id="nstext"> <p> Initialize a new instance of the <a href="log4net.Config.RepositoryAttribute.html">RepositoryAttribute</a> class with the name of the repository. </p> <div class="syntax"> <span class="lang">[Visual Basic]</span> <br />Overloads Public Sub New( _<br />   ByVal <i>name</i> As <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/<API key>.htm">String</a> _<br />)</div> <div class="syntax"> <span class="lang">[C#]</span> <br />public RepositoryAttribute(<br />   <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/<API key>.htm">string</a> <i>name</i><br />);</div> <h4 class="dtH4">Parameters</h4> <dl> <dt> <i>name</i> </dt> <dd>The name of the repository.</dd> </dl> <h4 class="dtH4">Remarks</h4> <p> Initialize the attribute with the name for the assembly's repository. </p> <h4 class="dtH4">See Also</h4><p><a href="log4net.Config.RepositoryAttribute.html">RepositoryAttribute Class</a> | <a href="log4net.Config.html">log4net.Config Namespace</a> | <a href="log4net.Config.<API key>.html">RepositoryAttribute Constructor Overload List</a></p><hr /><div id="footer"><a href='http: </body> </html>
# -*- coding: UTF-8 -*- from __future__ import unicode_literals, print_function, division
package com.snowplowanalytics.kinesistee.config import java.util import awscala.dynamodbv2.{AttributeValue, DynamoDB} import com.amazonaws.services.dynamodbv2.model.{QueryRequest, QueryResult} import org.specs2.mock.Mockito import org.specs2.mutable.Specification class <API key> extends Specification with Mockito { val sampleGoodConfig = scala.io.Source.fromURL(getClass.getResource("/<API key>.json")).mkString val sampleConfig = Configuration(name = "My Kinesis Tee example", targetStream = TargetStream("my-target-stream", None), transformer = Some(Transformer(BuiltIn.<API key>)), filter = None) "A valid configuration" should { "generate the correct case class" in { <API key>.build(sampleGoodConfig) mustEqual sampleConfig } } "An invalid JSON configuration" should { "throw an exception" in { <API key>.build("banana") must throwA[<API key>] } } "A configuration that doesn't match the given schema" should { "throw an exception" in { <API key>.build( """ |{ | "schema": "com.thing", | "data": { "foo":"bar" } |} """.stripMargin) must throwA(new <API key>("Invalid configuration")) } } "Loading from DynamoDB" should { val <API key> = "<API key>" "load a configuration using dynamodb and the specified table name" in { implicit val dynamoDB = mock[DynamoDB] val res = mock[QueryResult] val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList() val one:util.Map[String,com.amazonaws.services.dynamodbv2.model.AttributeValue] = new util.HashMap() one.put("id", new AttributeValue(Some("with-id"))) one.put("configuration", new AttributeValue(Some(sampleGoodConfig))) items.add(one) res.getItems returns items dynamoDB.query(any[QueryRequest]) returns res <API key>.build(<API key>, "with-id") mustEqual sampleConfig } "give a good error if the table doesn't have a matching entry" in { implicit val dynamoDB = mock[DynamoDB] val res = mock[QueryResult] val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList() res.getItems returns items dynamoDB.query(any[QueryRequest]) returns res <API key>.build(<API key>, "with-id") must throwA(new <API key>(s"No configuration in table '$<API key>' for lambda 'with-id'!")) } "give a good error if the table doesn't have the right keys (id and configuration)" in { implicit val dynamoDB = mock[DynamoDB] val res = mock[QueryResult] val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList() val one:util.Map[String,com.amazonaws.services.dynamodbv2.model.AttributeValue] = new util.HashMap() one.put("id", new AttributeValue(Some("with-id"))) one.put("this-is-not-config", new AttributeValue(Some("abc"))) items.add(one) res.getItems returns items dynamoDB.query(any[QueryRequest]) returns res <API key>.build(<API key>, "with-id") must throwA(new <API key>(s"Config table '${<API key>}' for lambda 'with-id' is missing a 'configuration' field!")) } "do something reasonable if ddb errors" in { implicit val dynamoDB = mock[DynamoDB] val exception = new <API key>("Query exploded") dynamoDB.query(any[QueryRequest]) throws exception // NB <API key> is rethrown as <API key> <API key>.build(<API key>, "with-id") must throwA[<API key>](message = "Query exploded") } } }
/** * @file chheap.c * @brief Heaps code. * * @addtogroup heaps * @details Heap Allocator related APIs. * <h2>Operation mode</h2> * The heap allocator implements a first-fit strategy and its APIs * are functionally equivalent to the usual @p malloc() and @p free() * library functions. The main difference is that the OS heap APIs * are guaranteed to be thread safe.<br> * @pre In order to use the heap APIs the @p CH_CFG_USE_HEAP option must * be enabled in @p chconf.h. * @{ */ #include "ch.h" #if CH_CFG_USE_HEAP || defined(__DOXYGEN__) /* Module local definitions. */ /* * Defaults on the best synchronization mechanism available. */ #if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__) #define H_LOCK(h) chMtxLock(&(h)->h_mtx) #define H_UNLOCK(h) chMtxUnlock(&(h)->h_mtx) #else #define H_LOCK(h) chSemWait(&(h)->h_sem) #define H_UNLOCK(h) chSemSignal(&(h)->h_sem) #endif /* Module exported variables. */ /* Module local types. */ /* Module local variables. */ /** * @brief Default heap descriptor. */ static memory_heap_t default_heap; /* Module local functions. */ /* Module exported functions. */ /** * @brief Initializes the default heap. * * @notapi */ void _heap_init(void) { default_heap.h_provider = chCoreAlloc; default_heap.h_free.h.u.next = (union heap_header *)NULL; default_heap.h_free.h.size = 0; #if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__) chMtxObjectInit(&default_heap.h_mtx); #else chSemObjectInit(&default_heap.h_sem, 1); #endif } /** * @brief Initializes a memory heap from a static memory area. * @pre Both the heap buffer base and the heap size must be aligned to * the @p stkalign_t type size. * * @param[out] heapp pointer to the memory heap descriptor to be initialized * @param[in] buf heap buffer base * @param[in] size heap size * * @init */ void chHeapObjectInit(memory_heap_t *heapp, void *buf, size_t size) { union heap_header *hp; chDbgCheck(MEM_IS_ALIGNED(buf) && MEM_IS_ALIGNED(size)); heapp->h_provider = (memgetfunc_t)NULL; heapp->h_free.h.u.next = hp = buf; heapp->h_free.h.size = 0; hp->h.u.next = NULL; hp->h.size = size - sizeof(union heap_header); #if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__) chMtxObjectInit(&heapp->h_mtx); #else chSemObjectInit(&heapp->h_sem, 1); #endif } /** * @brief Allocates a block of memory from the heap by using the first-fit * algorithm. * @details The allocated block is guaranteed to be properly aligned for a * pointer data type (@p stkalign_t). * * @param[in] heapp pointer to a heap descriptor or @p NULL in order to * access the default heap. * @param[in] size the size of the block to be allocated. Note that the * allocated block may be a bit bigger than the requested * size for alignment and fragmentation reasons. * @return A pointer to the allocated block. * @retval NULL if the block cannot be allocated. * * @api */ void *chHeapAlloc(memory_heap_t *heapp, size_t size) { union heap_header *qp, *hp, *fp; if (heapp == NULL) heapp = &default_heap; size = MEM_ALIGN_NEXT(size); qp = &heapp->h_free; H_LOCK(heapp); while (qp->h.u.next != NULL) { hp = qp->h.u.next; if (hp->h.size >= size) { if (hp->h.size < size + sizeof(union heap_header)) { /* Gets the whole block even if it is slightly bigger than the requested size because the fragment would be too small to be useful.*/ qp->h.u.next = hp->h.u.next; } else { /* Block bigger enough, must split it.*/ fp = (void *)((uint8_t *)(hp) + sizeof(union heap_header) + size); fp->h.u.next = hp->h.u.next; fp->h.size = hp->h.size - sizeof(union heap_header) - size; qp->h.u.next = fp; hp->h.size = size; } hp->h.u.heap = heapp; H_UNLOCK(heapp); return (void *)(hp + 1); } qp = hp; } H_UNLOCK(heapp); /* More memory is required, tries to get it from the associated provider else fails.*/ if (heapp->h_provider) { hp = heapp->h_provider(size + sizeof(union heap_header)); if (hp != NULL) { hp->h.u.heap = heapp; hp->h.size = size; hp++; return (void *)hp; } } return NULL; } #define LIMIT(p) (union heap_header *)((uint8_t *)(p) + \ sizeof(union heap_header) + \ (p)->h.size) /** * @brief Frees a previously allocated memory block. * * @param[in] p pointer to the memory block to be freed * * @api */ void chHeapFree(void *p) { union heap_header *qp, *hp; memory_heap_t *heapp; chDbgCheck(p != NULL); hp = (union heap_header *)p - 1; heapp = hp->h.u.heap; qp = &heapp->h_free; H_LOCK(heapp); while (true) { chDbgAssert((hp < qp) || (hp >= LIMIT(qp)), "within free block"); if (((qp == &heapp->h_free) || (hp > qp)) && ((qp->h.u.next == NULL) || (hp < qp->h.u.next))) { /* Insertion after qp.*/ hp->h.u.next = qp->h.u.next; qp->h.u.next = hp; /* Verifies if the newly inserted block should be merged.*/ if (LIMIT(hp) == hp->h.u.next) { /* Merge with the next block.*/ hp->h.size += hp->h.u.next->h.size + sizeof(union heap_header); hp->h.u.next = hp->h.u.next->h.u.next; } if ((LIMIT(qp) == hp)) { /* Merge with the previous block.*/ qp->h.size += hp->h.size + sizeof(union heap_header); qp->h.u.next = hp->h.u.next; } break; } qp = qp->h.u.next; } H_UNLOCK(heapp); return; } /** * @brief Reports the heap status. * @note This function is meant to be used in the test suite, it should * not be really useful for the application code. * * @param[in] heapp pointer to a heap descriptor or @p NULL in order to * access the default heap. * @param[in] sizep pointer to a variable that will receive the total * fragmented free space * @return The number of fragments in the heap. * * @api */ size_t chHeapStatus(memory_heap_t *heapp, size_t *sizep) { union heap_header *qp; size_t n, sz; if (heapp == NULL) heapp = &default_heap; H_LOCK(heapp); sz = 0; for (n = 0, qp = &heapp->h_free; qp->h.u.next; n++, qp = qp->h.u.next) sz += qp->h.u.next->h.size; if (sizep) *sizep = sz; H_UNLOCK(heapp); return n; } #endif /* CH_CFG_USE_HEAP */
# AUTOGENERATED FILE FROM balenalib/jetson-tx1-debian:bullseye-run # remove several traces of debian python RUN apt-get purge -y python.* # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --<API key> \ ca-certificates \ netbase \
char *my_strcpy(char *dest, char *src) { char *adrr; for (adrr = dest; *src; *dest++ = *src++); *dest++ = '\0'; return (adrr); }
# AUTOGENERATED FILE FROM balenalib/surface-go-debian:bullseye-build ENV NODE_VERSION 17.6.0 ENV YARN_VERSION 1.22.4 RUN for key in \ <API key> \ ; do \ gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$<API key>.tar.gz" \ && echo "<SHA256-like> node-v$<API key>.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$<API key>.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$<API key>.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \
This plugin inserts a table of content (TOC) section into your GitBook page. It is powered by the [markdown-toc](https://github.com/jonschlinkert/markdown-toc) library. ## Usage Installation Add the plugin to your `book.json`: { "plugins" : [ "simple-page-toc" ] } Create TOC Place a `<!-- toc -->` code comment somewhere into your text. Generating your GitBook inserts a table of contents immediately after this comment. Optional configuration You can add the following configuration params to your `book.json`: { "plugins" : [ "simple-page-toc" ], "pluginsConfig": { "simple-page-toc": { "maxDepth": 3, "skipFirstH1": true   } } } Name | Type | Default | Description maxDepth | Number | 3 | Use headings whose depth is at most maxdepth. skipFirstH1 | Boolean | true | Exclude the first h1-level heading in a file. ## Changelog * 0.1.0 Releases: * 0.1.0 First release * 0.1.1 Fixed invalid config example in README (thanks at15) * 0.1.2 Fixed bug: Titles with hyphen builds with wrong anchor link
package com.quakearts.webapp.facelets.bootstrap.renderers; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.faces.component.UIColumn; import javax.faces.component.UIComponent; import javax.faces.component.UIData; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import com.quakearts.webapp.facelets.bootstrap.components.BootTable; import com.quakearts.webapp.facelets.bootstrap.renderkit.Attribute; import com.quakearts.webapp.facelets.bootstrap.renderkit.AttributeManager; import com.quakearts.webapp.facelets.bootstrap.renderkit.html_basic.HtmlBasicRenderer; import com.quakearts.webapp.facelets.util.UtilityMethods; import static com.quakearts.webapp.facelets.bootstrap.renderkit.RenderKitUtils.*; public class BootTableRenderer extends HtmlBasicRenderer { private static final Attribute[] ATTRIBUTES = AttributeManager.getAttributes(AttributeManager.Key.DATATABLE); @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (!shouldEncode(component)) { return; } BootTable data = (BootTable) component; data.setRowIndex(-1); ResponseWriter writer = context.getResponseWriter(); writer.startElement("table", component); writer.writeAttribute("id", component.getClientId(context), "id"); String styleClass = data.get("styleClass"); writer.writeAttribute("class","table "+(styleClass !=null?" "+styleClass:""), "styleClass"); <API key>(context, component); <API key>(context, writer, component, ATTRIBUTES); writer.writeText("\n", component, null); UIComponent caption = getFacet(component, "caption"); if (caption != null) { String captionClass = data.get("captionClass"); String captionStyle = data.get("captionStyle"); writer.startElement("caption", component); if (captionClass != null) { writer.writeAttribute("class", captionClass, "captionClass"); } if (captionStyle != null) { writer.writeAttribute("style", captionStyle, "captionStyle"); } encodeRecursive(context, caption); writer.endElement("caption"); } UIComponent colGroups = getFacet(component, "colgroups"); if (colGroups != null) { encodeRecursive(context, colGroups); } BootMetaInfo info = getMetaInfo(context, component); UIComponent header = getFacet(component, "header"); if (header != null || info.hasHeaderFacets) { String headerClass = data.get("headerClass"); writer.startElement("thead", component); writer.writeText("\n", component, null); if (header != null) { writer.startElement("tr", header); writer.startElement("th", header); if (headerClass != null) { writer.writeAttribute("class", headerClass, "headerClass"); } if (info.columns.size() > 1) { writer.writeAttribute("colspan", String.valueOf(info.columns.size()), null); } writer.writeAttribute("scope", "colgroup", null); encodeRecursive(context, header); writer.endElement("th"); writer.endElement("tr"); writer.write("\n"); } if (info.hasHeaderFacets) { writer.startElement("tr", component); writer.writeText("\n", component, null); for (UIColumn column : info.columns) { String columnHeaderClass = info.<API key>(); writer.startElement("th", column); if (columnHeaderClass != null) { writer.writeAttribute("class", columnHeaderClass, "columnHeaderClass"); } else if (headerClass != null) { writer.writeAttribute("class", headerClass, "headerClass"); } writer.writeAttribute("scope", "col", null); UIComponent facet = getFacet(column, "header"); if (facet != null) { encodeRecursive(context, facet); } writer.endElement("th"); writer.writeText("\n", component, null); } writer.endElement("tr"); writer.write("\n"); } writer.endElement("thead"); writer.writeText("\n", component, null); } } @Override public void encodeChildren(FacesContext context, UIComponent component) throws IOException { if (!<API key>(component)) { return; } UIData data = (UIData) component; ResponseWriter writer = context.getResponseWriter(); BootMetaInfo info = getMetaInfo(context, data); if(info.columns.isEmpty()) { writer.startElement("tbody", component); renderEmptyTableRow(writer, component); writer.endElement("tbody"); return; } int processed = 0; int rowIndex = data.getFirst() - 1; int rows = data.getRows(); List<Integer> bodyRows = getBodyRows(context.getExternalContext().getApplicationMap(), data); boolean hasBodyRows = (bodyRows != null && !bodyRows.isEmpty()); boolean wroteTableBody = false; if (!hasBodyRows) { writer.startElement("tbody", component); writer.writeText("\n", component, null); } boolean renderedRow = false; while (true) { if ((rows > 0) && (++processed > rows)) { break; } data.setRowIndex(++rowIndex); if (!data.isRowAvailable()) { break; } if (hasBodyRows && bodyRows.contains(data.getRowIndex())) { if (wroteTableBody) { writer.endElement("tbody"); } writer.startElement("tbody", data); wroteTableBody = true; } writer.startElement("tr", component); if (info.rowClasses.length > 0) { writer.writeAttribute("class", info.getCurrentRowClass(), "rowClasses"); } writer.writeText("\n", component, null); info.newRow(); for (UIColumn column : info.columns) { boolean isRowHeader = Boolean.TRUE.equals(column.getAttributes() .get("rowHeader")); if (isRowHeader) { writer.startElement("th", column); writer.writeAttribute("scope", "row", null); } else { writer.startElement("td", column); } String columnClass = info.<API key>(); if (columnClass != null) { writer.writeAttribute("class", columnClass, "columnClasses"); } for (Iterator<UIComponent> gkids = getChildren(column); gkids .hasNext();) { encodeRecursive(context, gkids.next()); } if (isRowHeader) { writer.endElement("th"); } else { writer.endElement("td"); } writer.writeText("\n", component, null); } writer.endElement("tr"); writer.write("\n"); renderedRow = true; } if(!renderedRow) { renderEmptyTableRow(writer, data); } writer.endElement("tbody"); writer.writeText("\n", component, null); data.setRowIndex(-1); } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { if (!shouldEncode(component)) { return; } ResponseWriter writer = context.getResponseWriter(); BootMetaInfo info = getMetaInfo(context, component); UIComponent footer = getFacet(component, "footer"); if (footer != null || info.hasFooterFacets) { String footerClass = (String) component.getAttributes().get("footerClass"); writer.startElement("tfoot", component); writer.writeText("\n", component, null); if (info.hasFooterFacets) { writer.startElement("tr", component); writer.writeText("\n", component, null); for (UIColumn column : info.columns) { String columnFooterClass = (String) column.getAttributes().get( "footerClass"); writer.startElement("td", column); if (columnFooterClass != null) { writer.writeAttribute("class", columnFooterClass, "columnFooterClass"); } else if (footerClass != null) { writer.writeAttribute("class", footerClass, "footerClass"); } UIComponent facet = getFacet(column, "footer"); if (facet != null) { encodeRecursive(context, facet); } writer.endElement("td"); writer.writeText("\n", component, null); } writer.endElement("tr"); writer.write("\n"); } if (footer != null) { writer.startElement("tr", footer); writer.startElement("td", footer); if (footerClass != null) { writer.writeAttribute("class", footerClass, "footerClass"); } if (info.columns.size() > 1) { writer.writeAttribute("colspan", String.valueOf(info.columns.size()), null); } encodeRecursive(context, footer); writer.endElement("td"); writer.endElement("tr"); writer.write("\n"); } writer.endElement("tfoot"); writer.writeText("\n", component, null); } clearMetaInfo(context, component); ((UIData) component).setRowIndex(-1); writer.endElement("table"); writer.writeText("\n", component, null); } private List<Integer> getBodyRows(Map<String, Object> appMap, UIData data) { List<Integer> result = null; String bodyRows = (String) data.getAttributes().get("bodyrows"); if (bodyRows != null) { String [] rows = UtilityMethods.split(appMap, bodyRows, ","); if (rows != null) { result = new ArrayList<Integer>(rows.length); for (String curRow : rows) { result.add(Integer.valueOf(curRow)); } } } return result; } private void renderEmptyTableRow(final ResponseWriter writer, final UIComponent component) throws IOException { writer.startElement("tr", component); writer.startElement("td", component); writer.endElement("td"); writer.endElement("tr"); } protected BootTableRenderer.BootMetaInfo getMetaInfo(FacesContext context, UIComponent table) { String key = createKey(table); Map<Object, Object> attributes = context.getAttributes(); BootMetaInfo info = (BootMetaInfo) attributes .get(key); if (info == null) { info = new BootMetaInfo(table); attributes.put(key, info); } return info; } protected void clearMetaInfo(FacesContext context, UIComponent table) { context.getAttributes().remove(createKey(table)); } protected String createKey(UIComponent table) { return BootMetaInfo.KEY + '_' + table.hashCode(); } private static class BootMetaInfo { private static final UIColumn PLACE_HOLDER_COLUMN = new UIColumn(); private static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final String KEY = BootMetaInfo.class.getName(); public final String[] rowClasses; public final String[] columnClasses; public final String[] headerClasses; public final List<UIColumn> columns; public final boolean hasHeaderFacets; public final boolean hasFooterFacets; public final int columnCount; public int columnStyleCounter; public int headerStyleCounter; public int rowStyleCounter; public BootMetaInfo(UIComponent table) { rowClasses = getRowClasses(table); columnClasses = getColumnClasses(table); headerClasses = getHeaderClasses(table); columns = getColumns(table); columnCount = columns.size(); hasHeaderFacets = hasFacet("header", columns); hasFooterFacets = hasFacet("footer", columns); } public void newRow() { columnStyleCounter = 0; headerStyleCounter = 0; } public String <API key>() { String style = null; if (columnStyleCounter < columnClasses.length && columnStyleCounter <= columnCount) { style = columnClasses[columnStyleCounter++]; } return ((style != null && style.length() > 0) ? style : null); } public String <API key>() { String style = null; if (headerStyleCounter < headerClasses.length && headerStyleCounter <= columnCount) { style = headerClasses[headerStyleCounter++]; } return ((style != null && style.length() > 0) ? style : null); } public String getCurrentRowClass() { String style = rowClasses[rowStyleCounter++]; if (rowStyleCounter >= rowClasses.length) { rowStyleCounter = 0; } return style; } private static String[] getColumnClasses(UIComponent table) { String values = ((BootTable) table).get("columnClasses"); if (values == null) { return EMPTY_STRING_ARRAY; } Map<String, Object> appMap = FacesContext.getCurrentInstance() .getExternalContext().getApplicationMap(); return UtilityMethods.split(appMap, values.trim(), ","); } private static String[] getHeaderClasses(UIComponent table) { String values = ((BootTable) table).get("headerClasses"); if (values == null) { return EMPTY_STRING_ARRAY; } Map<String, Object> appMap = FacesContext.getCurrentInstance() .getExternalContext().getApplicationMap(); return UtilityMethods.split(appMap, values.trim(), ","); } private static List<UIColumn> getColumns(UIComponent table) { if (table instanceof UIData) { int childCount = table.getChildCount(); if (childCount > 0) { List<UIColumn> results = new ArrayList<UIColumn>(childCount); for (UIComponent kid : table.getChildren()) { if ((kid instanceof UIColumn) && kid.isRendered()) { results.add((UIColumn) kid); } } return results; } else { return Collections.emptyList(); } } else { int count; Object value = table.getAttributes().get("columns"); if ((value != null) && (value instanceof Integer)) { count = ((Integer) value); } else { count = 2; } if (count < 1) { count = 1; } List<UIColumn> result = new ArrayList<UIColumn>(count); for (int i = 0; i < count; i++) { result.add(PLACE_HOLDER_COLUMN); } return result; } } private static boolean hasFacet(String name, List<UIColumn> columns) { if (!columns.isEmpty()) { for (UIColumn column : columns) { if (column.getFacetCount() > 0) { if (column.getFacets().containsKey(name)) { return true; } } } } return false; } private static String[] getRowClasses(UIComponent table) { String values = ((BootTable) table).get("rowClasses"); if (values == null) { return (EMPTY_STRING_ARRAY); } Map<String, Object> appMap = FacesContext.getCurrentInstance() .getExternalContext().getApplicationMap(); return UtilityMethods.split(appMap, values.trim(), ","); } } }
<?php namespace BumbalClient; /** * <API key> Class Doc Comment * * @category Class */ // * @description <API key> class <API key> extends \<API key> { /** * Setup before running any test case */ public static function setUpBeforeClass() { } /** * Setup before running each test case */ public function setUp() { } /** * Clean up after running each test case */ public function tearDown() { } /** * Clean up after running all test cases */ public static function tearDownAfterClass() { } /** * Test "<API key>" */ public function <API key>() { } /** * Test attribute "items" */ public function testPropertyItems() { } /** * Test attribute "count_filtered" */ public function <API key>() { } /** * Test attribute "count_unfiltered" */ public function <API key>() { } /** * Test attribute "count_limited" */ public function <API key>() { } }
using Foundation.Data.Hibernate; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NHibernate; using NHibernate.Context; using NHibernate.Engine; namespace Foundation.Tests.Data.Hibernate { [TestClass] public class <API key> { [TestMethod] public void <API key>() { var session = new Mock<ISession>(); var context = new Mock<<API key>>(); var sessionFactory = new Mock<<API key>>(); sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object); sessionFactory.Setup(implementor => implementor.<API key>).Returns(context.Object); session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object); new HibernateUnitOfWork(sessionFactory.Object); sessionFactory.Verify(factory1 => factory1.OpenSession()); } [TestMethod] public void <API key>() { var session = new Mock<ISession>(); var context = new Mock<<API key>>(); var sessionFactory = new Mock<<API key>>(); sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object); sessionFactory.Setup(implementor => implementor.<API key>).Returns(context.Object); session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object); var flushMode = FlushMode.Auto; session.SetupSet(session2 => session2.FlushMode).Callback(mode => flushMode = mode); new HibernateUnitOfWork(sessionFactory.Object); session.VerifySet( session1 => session1.FlushMode, Times.Once()); Assert.AreEqual(FlushMode.Commit, flushMode); } [TestMethod] public void <API key>() { var session = new Mock<ISession>(); var context = new Mock<<API key>>(); var sessionFactory = new Mock<<API key>>(); sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object); sessionFactory.Setup(implementor => implementor.<API key>).Returns(context.Object); session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object); new HibernateUnitOfWork(sessionFactory.Object); session.Verify(session1 => session1.BeginTransaction()); } [TestMethod] public void <API key>() { var session = new Mock<ISession>(); var context = new Mock<<API key>>(); var sessionFactory = new Mock<<API key>>(); sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object); session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object); sessionFactory.Setup(implementor => implementor.<API key>).Returns(context.Object); var work = new HibernateUnitOfWork(sessionFactory.Object); work.Dispose(); session.Verify(session1 => session1.Dispose()); } [TestMethod] public void <API key>() { var session = new Mock<ISession>(); var transaction = new Mock<ITransaction>(); var context = new Mock<<API key>>(); var sessionFactory = new Mock<<API key>>(); sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object); session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object); session.Setup(session3 => session3.BeginTransaction()).Returns(transaction.Object); sessionFactory.Setup(implementor => implementor.<API key>).Returns(context.Object); var work = new HibernateUnitOfWork(sessionFactory.Object); work.Dispose(); transaction.Verify(transaction1 => transaction1.Dispose()); } [TestMethod] public void <API key>() { var session = new Mock<ISession>(); var transaction = new Mock<ITransaction>(); var context = new Mock<<API key>>(); var sessionFactory = new Mock<ISessionFactory>().As<<API key>>(); session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object); session.Setup(session3 => session3.BeginTransaction()).Returns(transaction.Object); sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object); sessionFactory.Setup(implementor => implementor.<API key>).Returns(context.Object); var work = new HibernateUnitOfWork(sessionFactory.Object); work.Commit(); transaction.Verify(transaction1 => transaction1.Commit()); } } }
package info.pupcode.model.repo.test; import org.junit.Before; import org.springframework.context.support.<API key>; public class <API key> { protected SpringConfigTest springConfigTest; protected <API key> applicationContext; @Before public void setUp() { applicationContext = new <API key>("classpath*:applicationContext.xml"); if (springConfigTest == null) { springConfigTest = (SpringConfigTest) applicationContext.getBean(SpringConfigTest.class.getName()); } } }
package alicloud import ( "fmt" "testing" "github.com/alibaba/terraform-provider/alicloud/connectivity" "github.com/aliyun/<API key>/services/vpc" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func <API key>(t *testing.T) { var sslVpnClientCert vpc.<API key> resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, // module name IDRefreshName: "<API key>.foo", Providers: testAccProviders, CheckDestroy: <API key>, Steps: []resource.TestStep{ resource.TestStep{ Config: <API key>, Check: resource.<API key>( <API key>("<API key>.foo", &sslVpnClientCert), resource.<API key>( "<API key>.foo", "name", "<API key>"), resource.<API key>( "<API key>.foo", "ssl_vpn_server_id"), ), }, }, }) } func <API key>(t *testing.T) { var sslVpnClientCert vpc.<API key> resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: <API key>, Steps: []resource.TestStep{ resource.TestStep{ Config: <API key>, Check: resource.<API key>( <API key>("<API key>.foo", &sslVpnClientCert), resource.<API key>( "<API key>.foo", "name", "<API key>"), resource.<API key>( "<API key>.foo", "ssl_vpn_server_id"), ), }, resource.TestStep{ Config: <API key>, Check: resource.<API key>( <API key>("<API key>.foo", &sslVpnClientCert), resource.<API key>( "<API key>.foo", "name", "<API key>"), resource.<API key>( "<API key>.foo", "ssl_vpn_server_id"), ), }, }, }) } func <API key>(n string, vpn *vpc.<API key>) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No VPN ID is set") } client := testAccProvider.Meta().(*connectivity.AliyunClient) vpnGatewayService := VpnGatewayService{client} instance, err := vpnGatewayService.<API key>(rs.Primary.ID) if err != nil { return err } *vpn = instance return nil } } func <API key>(s *terraform.State) error { client := testAccProvider.Meta().(*connectivity.AliyunClient) vpnGatewayService := VpnGatewayService{client} for _, rs := range s.RootModule().Resources { if rs.Type != "<API key>" { continue } instance, err := vpnGatewayService.<API key>(rs.Primary.ID) if err != nil { if NotFoundError(err) { continue } return err } if instance.SslVpnClientCertId != "" { return fmt.Errorf("Ssl VPN client cert %s still exist", instance.SslVpnClientCertId) } } return nil } const <API key> = ` variable "name" { default = "<API key>" } resource "alicloud_vpc" "foo" { cidr_block = "172.16.0.0/12" name = "${var.name}" } data "alicloud_zones" "default" { "<API key>"= "VSwitch" } resource "alicloud_vswitch" "foo" { vpc_id = "${alicloud_vpc.foo.id}" cidr_block = "172.16.0.0/21" availability_zone = "${data.alicloud_zones.default.zones.0.id}" name = "${var.name}" } resource "<API key>" "foo" { name = "${var.name}" vpc_id = "${alicloud_vpc.foo.id}" bandwidth = "10" enable_ssl = true <API key> = "PostPaid" description = "<API key>" } resource "<API key>" "foo" { name = "${var.name}" vpn_gateway_id = "${<API key>.foo.id}" client_ip_pool = "192.168.0.0/16" local_subnet = "172.16.0.0/21" protocol = "UDP" cipher = "AES-128-CBC" port = "1194" compress = "false" } resource "<API key>" "foo" { ssl_vpn_server_id = "${<API key>.foo.id}" name = "${var.name}" } ` const <API key> = ` variable "name" { default = "<API key>" } resource "alicloud_vpc" "foo" { cidr_block = "172.16.0.0/12" name = "${var.name}" } data "alicloud_zones" "default" { "<API key>"= "VSwitch" } resource "alicloud_vswitch" "foo" { vpc_id = "${alicloud_vpc.foo.id}" cidr_block = "172.16.0.0/21" availability_zone = "${data.alicloud_zones.default.zones.0.id}" name = "${var.name}" } resource "<API key>" "foo" { name = "${var.name}" vpc_id = "${alicloud_vpc.foo.id}" bandwidth = "10" enable_ssl = true <API key> = "PostPaid" description = "<API key>" } resource "<API key>" "foo" { name = "${var.name}" vpn_gateway_id = "${<API key>.foo.id}" client_ip_pool = "192.168.0.0/16" local_subnet = "172.16.0.0/21" protocol = "UDP" cipher = "AES-128-CBC" port = "1194" compress = "false" } resource "<API key>" "foo" { ssl_vpn_server_id = "${<API key>.foo.id}" name = "${var.name}" } `
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Mon Apr 29 15:10:36 CEST 2013 --> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE> Uses of Class org.apache.solr.cloud.Overseer (Solr 4.3.0 API) </TITLE> <META NAME="date" CONTENT="2013-04-29"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.cloud.Overseer (Solr 4.3.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/solr/cloud//class-useOverseer.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Overseer.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.solr.cloud.Overseer</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.solr.cloud"><B>org.apache.solr.cloud</B></A></TD> <TD> Classes for dealing with ZooKeeper when operating in <a href="http://wiki.apache.org/solr/SolrCloud">SolrCloud</a> mode.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.solr.cloud"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A> in <A HREF="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</A> declared as <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;<A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></CODE></FONT></TD> <TD><CODE><B>ZkController.</B><B><A HREF="../../../../../org/apache/solr/cloud/ZkController.html#overseer">overseer</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/solr/cloud//class-useOverseer.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Overseer.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> <i>Copyright &copy; 2000-2013 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </BODY> </HTML>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_11) on Mon Apr 07 19:10:16 CEST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class at.irian.ankor.big.json.BigListSerializer (Ankor - Project 0.2-SNAPSHOT API)</title> <meta name="date" content="2014-04-07"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class at.irian.ankor.big.json.BigListSerializer (Ankor - Project 0.2-SNAPSHOT API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../at/irian/ankor/big/json/BigListSerializer.html" title="class in at.irian.ankor.big.json">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?at/irian/ankor/big/json/class-use/BigListSerializer.html" target="_top">Frames</a></li> <li><a href="BigListSerializer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class at.irian.ankor.big.json.BigListSerializer" class="title">Uses of Class<br>at.irian.ankor.big.json.BigListSerializer</h2> </div> <div class="classUseContainer">No usage of at.irian.ankor.big.json.BigListSerializer</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../at/irian/ankor/big/json/BigListSerializer.html" title="class in at.irian.ankor.big.json">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?at/irian/ankor/big/json/class-use/BigListSerializer.html" target="_top">Frames</a></li> <li><a href="BigListSerializer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
using System; using Windows.ApplicationModel.Resources; namespace Okra.Data.Helpers { internal static class ResourceHelper { private const string RESOURCEMAP_ERROR = "Okra.Data/Errors"; private const string <API key> = "<API key>"; private static ResourceLoader errorResourceLoader; public static string GetErrorResource(string resourceName) { if (errorResourceLoader == null) errorResourceLoader = ResourceLoader.<API key>(RESOURCEMAP_ERROR); string errorResource = errorResourceLoader.GetString(resourceName); if (string.IsNullOrEmpty(errorResource) && resourceName != <API key>) throw new ArgumentException(GetErrorResource(<API key>)); return errorResource; } } }
package pro.luxun.luxunanimation.presenter.adapter; import android.support.annotation.UiThread; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; public abstract class BaseRecyclerAdapter<T, V extends View> extends RecyclerView.Adapter<BaseRecyclerAdapter.BaseViewHolder<V>> { protected List<T> mItems = new ArrayList<>(); @Override public BaseViewHolder<V> onCreateViewHolder(ViewGroup parent, int viewType) { return new BaseViewHolder<>(onCreateItemView(parent, viewType)); } @Override public int getItemCount() { return mItems.size(); } @UiThread public void refresh(List<T> datas){ mItems.clear(); add(datas); } @UiThread public void add(List<T> datas){ mItems.addAll(datas); <API key>(); } @Override public void onBindViewHolder(BaseViewHolder holder, int position) { V v = (V) holder.itemView; onBindView(v, mItems.get(position)); } protected abstract V onCreateItemView(ViewGroup parent, int viewType); protected abstract void onBindView(V v, T t); public static class BaseViewHolder<V extends View> extends RecyclerView.ViewHolder{ public BaseViewHolder(V itemView) { super(itemView); } } }
package cn.xmut.experiment.service.impl; import java.util.List; import org.apache.commons.fileupload.FileItem; import cn.xmut.experiment.dao.IExperimentDao; import cn.xmut.experiment.dao.impl.jdbc.ExperimentDaoImpl; import cn.xmut.experiment.domain.Experiment; import cn.xmut.experiment.domain.ShowExperiment; import cn.xmut.experiment.service.IExperimentService; public class <API key> implements IExperimentService { IExperimentDao experimentDao = new ExperimentDaoImpl(); public boolean addExperiment(Experiment experiment, String docName,String dirPath, FileItem fileItem) { return experimentDao.addExperiment(experiment, docName, dirPath, fileItem); } public boolean updateExperiment(Experiment experiment) { return experimentDao.updateExperiment(experiment); } public String getDocPath(int experimentId) { return experimentDao.getDocPath(experimentId); } public Experiment getExperiment(int experimentId) { return experimentDao.getExperiment(experimentId); } public List<ShowExperiment> queryPass(Experiment experiment) { return experimentDao.queryPass(experiment); } public List<ShowExperiment> queryNodistribute(Experiment experiment) { return experimentDao.queryNodistribute(experiment); } public List<ShowExperiment> <API key>(Experiment experiment, String expertId) { return experimentDao.<API key>(experiment, expertId); } public List<ShowExperiment> <API key>(Experiment experiment) { return experimentDao.<API key>(experiment); } public List<ShowExperiment> managerQueryNoPass(Experiment experiment) { return experimentDao.managerQueryNoPass(experiment); } public boolean delExperiment(Experiment experiment) { return experimentDao.delExperiment(experiment); } public List<ShowExperiment> headmanQueryNoPass(Experiment experiment) { return experimentDao.headmanQueryNoPass(experiment); } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_121) on Sun Oct 15 23:06:23 CEST 2017 --> <title>Class Hierarchy</title> <meta name="date" content="2017-10-15"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> <script type="text/javascript" src="script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Class Hierarchy"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-files/index-1.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?overview-tree.html" target="_top">Frames</a></li> <li><a href="overview-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h1 class="title">Hierarchy For All Packages</h1> <span class="<API key>">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="org/shanerx/faketrollplus/core/package-tree.html">org.shanerx.faketrollplus.core</a>, </li> <li><a href="org/shanerx/faketrollplus/core/data/package-tree.html">org.shanerx.faketrollplus.core.data</a>, </li> <li><a href="org/shanerx/faketrollplus/utils/function/package-tree.html">org.shanerx.faketrollplus.utils.function</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/GuiUser.html" title="class in org.shanerx.faketrollplus.core"><span class="typeNameLink">GuiUser</span></a></li> <li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/LocalUserCache.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">LocalUserCache</span></a> (implements org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data">UserCache</a>)</li> <li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/RemoteUserCache.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">RemoteUserCache</span></a> (implements org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data">UserCache</a>)</li> <li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/TrollPlayer.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">TrollPlayer</span></a></li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">org.shanerx.faketrollplus.utils.function.<a href="org/shanerx/faketrollplus/utils/function/EmptyConsumer.html" title="interface in org.shanerx.faketrollplus.utils.function"><span class="typeNameLink">EmptyConsumer</span></a></li> <li type="circle">org.shanerx.faketrollplus.utils.function.<a href="org/shanerx/faketrollplus/utils/function/Test.html" title="interface in org.shanerx.faketrollplus.utils.function"><span class="typeNameLink">Test</span></a></li> <li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">UserCache</span></a></li> </ul> <h2 title="Enum Hierarchy">Enum Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">java.lang.Enum&lt;E&gt; (implements java.lang.Comparable&lt;T&gt;, java.io.Serializable) <ul> <li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/TrollEffect.html" title="enum in org.shanerx.faketrollplus.core"><span class="typeNameLink">TrollEffect</span></a> (implements java.io.Serializable)</li> <li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/GuiType.html" title="enum in org.shanerx.faketrollplus.core"><span class="typeNameLink">GuiType</span></a></li> </ul> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-files/index-1.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?overview-tree.html" target="_top">Frames</a></li> <li><a href="overview-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
#ifndef <API key> #define <API key> /** * \file * \internal */ #include "LETypes.h" #include "MorphTables.h" U_NAMESPACE_BEGIN class LEGlyphStorage; class SubtableProcessor2 : public UMemory { public: virtual void process(LEGlyphStorage &glyphStorage) = 0; virtual ~SubtableProcessor2(); protected: SubtableProcessor2(const <API key> *morphSubtableHeader); SubtableProcessor2(); le_uint32 length; SubtableCoverage2 coverage; FeatureFlags subtableFeatures; const <API key> *subtableHeader; private: SubtableProcessor2(const SubtableProcessor2 &other); // forbid copying of this class SubtableProcessor2 &operator=(const SubtableProcessor2 &other); // forbid copying of this class }; U_NAMESPACE_END #endif
{%extends "base.html"%} {% block breadcrumb %} {% endblock %} {%block about_this_page %} <h2>Attachments for Site {{site.number}}</h2> {% if user.staff %} <p> <a href="{{ webapp2.uri_for('SiteView', id=site.key.integer_id()) }}"> Go back to Site #{{ site.number }}. </a> </p> {% endif %} {% if user.captain %} <p> <a href="{{ webapp2.uri_for('CaptainHome') }}"> Go back to your Captain home page. </a> </p> {% endif %} {% endblock %} {% block body %} {% include "site_attachments.html" %} {% endblock %}
body { overflow-x: hidden; font-family: "Roboto Slab", "Helvetica Neue", Helvetica, Arial, sans-serif; } .text-muted { color: #777; } .text-primary { color: #fed136; } p { font-size: 14px; line-height: 1.75; font-family: "Merriweather", serif; } p.large { font-size: 16px; } a, a:hover, a:focus, a:active, a.active { outline: 0; } a { color: #fed136; } a:hover, a:focus, a:active, a.active { color: #fed136; } h1, h2, h3, h4, h5, h6 { text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 700; } .img-centered { margin: 0 auto; } .bg-light-gray { background-color: #f7f7f7; } .bg-darkest-gray { background-color: #222; } .btn-primary { border-color: #fed136; text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 700; color: #fff; background-color: #fed136; } .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary { border-color: #f6bf01; color: #fff; background-color: #fec503; } .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary { background-image: none; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { border-color: #fed136; background-color: #fed136; } .btn-primary .badge { color: #fed136; background-color: #fff; } .btn-xl { padding: 20px 40px; border-color: #fed136; border-radius: 3px; text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 18px; font-weight: 700; color: #fff; background-color: #fed136; } .btn-xl:hover, .btn-xl:focus, .btn-xl:active, .btn-xl.active, .open .dropdown-toggle.btn-xl { border-color: #f6bf01; color: #fff; background-color: #fec503; } .btn-xl:active, .btn-xl.active, .open .dropdown-toggle.btn-xl { background-image: none; } .btn-xl.disabled, .btn-xl[disabled], fieldset[disabled] .btn-xl, .btn-xl.disabled:hover, .btn-xl[disabled]:hover, fieldset[disabled] .btn-xl:hover, .btn-xl.disabled:focus, .btn-xl[disabled]:focus, fieldset[disabled] .btn-xl:focus, .btn-xl.disabled:active, .btn-xl[disabled]:active, fieldset[disabled] .btn-xl:active, .btn-xl.disabled.active, .btn-xl[disabled].active, fieldset[disabled] .btn-xl.active { border-color: #fed136; background-color: #fed136; } .btn-xl .badge { color: #fed136; background-color: #fff; } .navbar-default { border-color: transparent; background-color: #222; } .navbar-default .navbar-brand { font-family: "Jockey One", "Helvetica Neue", Helvetica, Arial, sans-serif; color: #fed136; } .navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus, .navbar-default .navbar-brand:active, .navbar-default .navbar-brand.active { color: #fed136; } .navbar-default .navbar-collapse { border-color: rgba(255, 255, 255, 0.02); } .navbar-default .navbar-toggle { border-color: #fed136; background-color: #fed136; } .navbar-default .navbar-toggle .icon-bar { background-color: #fff; } .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus { background-color: #fed136; } .navbar-default .nav li a { text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 400; letter-spacing: 1px; color: #fff; } .navbar-default .nav li a:hover, .navbar-default .nav li a:focus { outline: 0; color: #fed136; } .navbar-default .navbar-nav > .active > a { border-radius: 0; color: #fff; background-color: #fed136; } .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus { color: #fff; background-color: #fec503; } @media (min-width: 768px) { .navbar-default { padding: 25px 0; border: 0; background-color: transparent; -webkit-transition: padding .3s; -moz-transition: padding .3s; transition: padding .3s; } .navbar-default .navbar-brand { font-size: 2em; -webkit-transition: all .3s; -moz-transition: all .3s; transition: all .3s; } .navbar-default .navbar-nav > .active > a { border-radius: 3px; } .navbar-default.navbar-shrink { padding: 10px 0; background-color: #222; } .navbar-default.navbar-shrink .navbar-brand { font-size: 1.5em; } } header { text-align: center; color: #fff; <API key>: scroll; background-image: url('../img/globe2.jpg'); background-position: center center; background-repeat: none; -<API key>: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } header .intro-text { padding-top: 100px; padding-bottom: 50px; } header .intro-text .intro-lead-in { margin-bottom: 25px; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 22px; font-style: normal; line-height: 22px; } header .intro-text .intro-heading { text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 50px; font-weight: 700; line-height: 50px; margin-bottom: 0px; } @media (min-width: 768px) { header .intro-text { padding-top: 300px; padding-bottom: 200px; } header .intro-text .intro-lead-in { margin-bottom: 25px; font-family: "Merriweather", serif; font-size: 40px; font-style: italic; line-height: 40px; } header .intro-text .intro-heading { margin-bottom: 50px; text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 75px; font-weight: 700; line-height: 75px; } } section { padding: 100px 0; } section h2.section-heading { margin-top: 0; margin-bottom: 15px; font-size: 40px; } section h3.section-subheading { margin-bottom: 75px; text-transform: none; font-size: 16px; font-style: italic; font-weight: 400; font-family: "Merriweather", serif; } @media (min-width: 768px) { section { padding: 150px 0; } } .service-heading { margin: 15px 0; text-transform: none; } #portfolio .portfolio-item { right: 0; margin: 0 0 15px; } #portfolio .portfolio-item .portfolio-link { display: block; position: relative; margin: 0 auto; max-width: 400px; } #portfolio .portfolio-item .portfolio-link .portfolio-hover { position: absolute; width: 100%; height: 100%; opacity: 0; background: rgba(254, 209, 54, 0.9); -webkit-transition: all ease .5s; -moz-transition: all ease .5s; transition: all ease .5s; } #portfolio .portfolio-item .portfolio-link .portfolio-hover:hover { opacity: 1; } #portfolio .portfolio-item .portfolio-link .portfolio-hover .<API key> { position: absolute; top: 50%; width: 100%; height: 20px; margin-top: -12px; text-align: center; font-size: 20px; color: #fff; } #portfolio .portfolio-item .portfolio-link .portfolio-hover .<API key> i { margin-top: -12px; } #portfolio .portfolio-item .portfolio-link .portfolio-hover .<API key> h3, #portfolio .portfolio-item .portfolio-link .portfolio-hover .<API key> h4 { margin: 0; } #portfolio .portfolio-item .portfolio-caption { margin: 0 auto; padding: 25px; max-width: 400px; text-align: center; background-color: #fff; } #portfolio .portfolio-item .portfolio-caption h4 { margin: 0; text-transform: none; } #portfolio .portfolio-item .portfolio-caption p { margin: 0; font-family: "Droid Serif", "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; font-style: italic; } #portfolio * { z-index: 2; } @media (min-width: 767px) { #portfolio .portfolio-item { margin: 0 0 30px; } } .timeline { position: relative; padding: 0; list-style: none; } .timeline:before { content: ""; position: absolute; top: 0; bottom: 0; left: 40px; width: 2px; margin-left: -1.5px; background-color: #f1f1f1; } .timeline > li { position: relative; margin-bottom: 50px; min-height: 50px; } .timeline > li:before, .timeline > li:after { content: " "; display: table; } .timeline > li:after { clear: both; } .timeline > li .timeline-panel { float: right; position: relative; width: 100%; padding: 0 20px 0 100px; text-align: left; } .timeline > li .timeline-panel:before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } .timeline > li .timeline-panel:after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } .timeline > li .timeline-image { z-index: 100; position: absolute; left: 0; width: 80px; height: 80px; margin-left: 0; border: 7px solid #f1f1f1; border-radius: 100%; text-align: center; color: #fff; background-color: #fed136; } .timeline > li .timeline-image h4 { margin-top: 12px; font-size: 10px; line-height: 14px; } .timeline > li.timeline-inverted > .timeline-panel { float: right; padding: 0 20px 0 100px; text-align: left; } .timeline > li.timeline-inverted > .timeline-panel:before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } .timeline > li.timeline-inverted > .timeline-panel:after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } .timeline > li:last-child { margin-bottom: 0; } .timeline .timeline-heading h4 { margin-top: 0; color: inherit; } .timeline .timeline-heading h4.subheading { text-transform: none; } .timeline .timeline-body > p, .timeline .timeline-body > ul { margin-bottom: 0; } @media (min-width: 768px) { .timeline:before { left: 50%; } .timeline > li { margin-bottom: 100px; min-height: 100px; } .timeline > li .timeline-panel { float: left; width: 41%; padding: 0 20px 20px 30px; text-align: right; } .timeline > li .timeline-image { left: 50%; width: 100px; height: 100px; margin-left: -50px; } .timeline > li .timeline-image h4 { margin-top: 16px; font-size: 13px; line-height: 18px; } .timeline > li.timeline-inverted > .timeline-panel { float: right; padding: 0 30px 20px 20px; text-align: left; } } @media (min-width: 992px) { .timeline > li { min-height: 150px; } .timeline > li .timeline-panel { padding: 0 20px 20px; } .timeline > li .timeline-image { width: 150px; height: 150px; margin-left: -75px; } .timeline > li .timeline-image h4 { margin-top: 30px; font-size: 18px; line-height: 26px; } .timeline > li.timeline-inverted > .timeline-panel { padding: 0 20px 20px; } } @media (min-width: 1200px) { .timeline > li { min-height: 170px; } .timeline > li .timeline-panel { padding: 0 20px 20px 100px; } .timeline > li .timeline-image { width: 170px; height: 170px; margin-left: -85px; } .timeline > li .timeline-image h4 { margin-top: 40px; } .timeline > li.timeline-inverted > .timeline-panel { padding: 0 100px 20px 20px; } } .team-member { text-align: center; margin-bottom: -10px; } .team-member img { margin: 0 auto; border: 5px solid #fff; } .team-member h4 { margin-top: 25px; margin-bottom: 0; text-transform: none; } .team-member p { margin-top: 0; background-color: #fed136; padding: 15px; } aside.clients img { margin: 50px auto; } section#contact { background-color: #222; background-image: url(../img/map-image.png); background-position: center; background-repeat: no-repeat; padding-top: 50px; padding-bottom: 50px; } section#contact .section-heading { color: #fff; } section#contact .form-group { margin-bottom: 25px; } section#contact .form-group input, section#contact .form-group textarea { padding: 20px; } section#contact .form-group input.form-control { height: auto; } section#contact .form-group textarea.form-control { height: 236px; } section#contact .form-control:focus { border-color: #fed136; box-shadow: none; } section#contact::-<API key> { text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 700; color: #bbb; } section#contact:-moz-placeholder { text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 700; color: #bbb; } section#contact::-moz-placeholder { text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 700; color: #bbb; } section#contact:-<API key> { text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 700; color: #bbb; } section#contact .text-danger { color: #e74c3c; } footer { padding: 25px 0; text-align: center; } footer span.copyright { text-transform: none; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 40px; text-align: left; } footer ul.quicklinks { margin-bottom: 0; text-transform: uppercase; text-transform: none; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 40px; } ul.social-buttons { margin-bottom: 0; } ul.social-buttons li a { display: block; width: 40px; height: 40px; border-radius: 100%; font-size: 20px; line-height: 40px; outline: 0; color: #fff; background-color: #222; -webkit-transition: all .3s; -moz-transition: all .3s; transition: all .3s; } ul.social-buttons li a:hover, ul.social-buttons li a:focus, ul.social-buttons li a:active { background-color: #fed136; } .btn:focus, .btn:active, .btn.active, .btn:active:focus { outline: 0; } .portfolio-modal .modal-content { padding: 100px 0; min-height: 100%; border: 0; border-radius: 0; text-align: center; background-clip: border-box; -webkit-box-shadow: none; box-shadow: none; } .portfolio-modal .modal-content h2 { margin-bottom: 15px; font-size: 3em; } .portfolio-modal .modal-content p { margin-bottom: 30px; } .portfolio-modal .modal-content p.item-intro { margin: 20px 0 30px; font-family: "Droid Serif", "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; font-style: italic; } .portfolio-modal .modal-content ul.list-inline { margin-top: 0; margin-bottom: 30px; } .portfolio-modal .modal-content img { margin-bottom: 30px; } .portfolio-modal .close-modal { position: absolute; top: 25px; right: 25px; width: 75px; height: 75px; background-color: transparent; cursor: pointer; } .portfolio-modal .close-modal:hover { opacity: .3; } .portfolio-modal .close-modal .lr { z-index: 1051; width: 1px; height: 75px; margin-left: 35px; background-color: #222; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } .portfolio-modal .close-modal .lr .rl { z-index: 1052; width: 1px; height: 75px; background-color: #222; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .portfolio-modal .modal-backdrop { display: none; opacity: 0; } ::-moz-selection { text-shadow: none; background: #fed136; } ::selection { text-shadow: none; background: #fed136; } img::selection { background: 0 0; } img::-moz-selection { background: 0 0; } body { <API key>: #fed136; } .margins { margin-left: 60px; margin-right: 60px; } .photo { margin-bottom: 0px; margin-top: 0px; padding-top: 70px; padding-left: 0px; margin-right: 0px; left: 0px; } .professor { padding-top: 100px; padding-bottom: 0; } .biografia { padding-bottom: 0px; margin-bottom: 50px; } .depoimento { margin-top: 30px; } .testemunho { margin-top: 17px; } .testemunho h4 { margin-bottom: 0; } section#pacotes { background-color: #222; } section#pacotes .section-heading { color: #fff; } section#contact h3 { color: #fff; } section#contact p { color: #fff; } .demo { margin-left: 50px; padding: 20px 40px; border-color: #c6ccd2; border-radius: 3px; text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 18px; font-weight: 700; color: #fff; background-color: #c6ccd2; } .demo:hover { color: #fff; background-color: #767676; } .email { line-height: 30px; font-weight: 400; height: 65px; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 22px; } section#demo { padding-top: 55px; padding-bottom: 55px; background-color: #fed136; } .enviar { margin-left: 0px; padding: 20px 40px; border-color: #c6ccd2; border-radius: 3px; text-transform: uppercase; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 18px; font-weight: 700; color: #fff; background-color: #3996cc; } .enviar:hover { color: #fff; background-color: #3386b7; } section#demo p { color: #222; margin-top: 10px; font-size: 14px; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; } section#demo h3 { text-transform: none; margin-top: 0; } .logo { color: #fed136; text-transform: none; font-size: 21px; font-family: "Jockey One", "Helvetica Neue", Helvetica, Arial, sans-serif; } .glyphicon { color: #fff; } section#contact .col-md-10, .col-lg-10 { margin-left: 0px; padding-left: 3px; } .fa { color: #222; border: 10px; background-color: #fff; padding: 3px 6px 2px 5px; border-radius: 9px; margin-right: 0px; margin-left: -3px; } .pacote { background-color: #3996cc; padding: 14px 8px 13px; color: #fff; text-align: center; margin: 0; } section#pacotes p { color: #222; margin-top: 0; font-size: 14px; font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif; padding: 8px; font-weight: 200; text-align: center; border-top: 0; border-bottom: 1px; border-style: solid; border-color: #ddd; border-left: 0; border-right: 0; margin-bottom: 0; } section#pacotes h4 { padding: 18px 8px; color: #fff; text-align: center; background-color: #767676; text-transform: none; font-size: 35px; margin: 0; } section#pacotes h5 { padding: 15px 8px; color: #222; text-align: center; background-color: #f6f6f6; text-transform: none; margin: 0; font-size: 17px; } section#pacotes p.large { color: #f7f7f7; border: none; text-align: left; font-weight: 100; font-size: 12px; margin-top: 5px; } section#pacotes .col-md-10 { padding-right: 0; padding-left: 0; } .super { border: 15px; color: #e52323; border-color: #fed136; background-color: #df9898; } .pacote-coluna { background-color: #fff; padding-left: 0; padding-right: 0; border: 0.5px; border-style: solid; border-color: #ddd; } .pacote-max { background-color: #fff; padding-left: 0; padding-right: 0; border: 9px; border-style: solid; border-color: #fed136; margin-top: -9px; <API key>: 0; <API key>: 0; <API key>: 7px; <API key>: 7px; } .valor { background-color: #fed136; padding-left: 0; padding-right: 0; border: 9px; border-style: solid; border-color: #fed136; margin-top: -9px; <API key>: 7px; <API key>: 7px; <API key>: 0; <API key>: 0; height: 29px; } .valor h5 { background-color: #fed136; font-size: 14px; } .valor h6 { margin-top: 0; text-align: center; margin-bottom: 0; } header h1 { text-transform: none; font-style: normal; font-weight: 100; margin-top: -26px; margin-bottom: 0px; } header .row { margin-top: 0px; } section#portfolio p { margin-bottom: 67px; } section#portfolio { padding-bottom: 68px; } section#about strong { text-align: right; text-transform: none; font-size: 18px; font-style: italic; font-family: "Merriweather", serif; } section#services img { border: 5px; border-color: #f7f7f7; border-style: solid; border-radius: 52px; }
/** * @file * Declares the any type. */ #pragma once #include "../values/forward.hpp" #include <ostream> namespace puppet { namespace runtime { namespace types { // Forward declaration of recursion_guard struct recursion_guard; /** * Represents the Puppet Any type. */ struct any { /** * Gets the name of the type. * @return Returns the name of the type (i.e. Any). */ static char const* name(); /** * Creates a generalized version of the type. * @return Returns the generalized type. */ values::type generalize() const; /** * Determines if the given value is an instance of this type. * @param value The value to determine if it is an instance of this type. * @param guard The recursion guard to use for aliases. * @return Returns true if the given value is an instance of this type or false if not. */ bool is_instance(values::value const& value, recursion_guard& guard) const; /** * Determines if the given type is assignable to this type. * @param other The other type to check for assignability. * @param guard The recursion guard to use for aliases. * @return Returns true if the given type is assignable to this type or false if the given type is not assignable to this type. */ bool is_assignable(values::type const& other, recursion_guard& guard) const; /** * Writes a representation of the type to the given stream. * @param stream The stream to write to. * @param expand True to specify that type aliases should be expanded or false if not. */ void write(std::ostream& stream, bool expand = true) const; }; /** * Stream insertion operator for any type. * @param os The output stream to write the type to. * @param type The type to write. * @return Returns the given output stream. */ std::ostream& operator<<(std::ostream& os, any const& type); /** * Equality operator for any. * @param left The left type to compare. * @param right The right type to compare. * @return Always returns true (Any type is always equal to Any). */ bool operator==(any const& left, any const& right); /** * Inequality operator for any. * @param left The left type to compare. * @param right The right type to compare. * @return Always returns false (Any type is always equal to Any). */ bool operator!=(any const& left, any const& right); /** * Hashes the any type. * @param type The any type to hash. * @return Returns the hash value for the type. */ size_t hash_value(any const& type); }}} // namespace puppet::runtime::types
<!doctype html public "- <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : Function Reference: <API key>()</title> <link rel="stylesheet" href="../sample.css" type="text/css"> <link rel="stylesheet" href="../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 --> <script src="../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <! ext='.html'; relbase='../'; subdir='_functions'; filename='index.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); logFunction('<API key>'); </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> [<a href="../index.html">Top level directory</a>]<br> <script language="JavaScript" type="text/javascript"> <! document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <h3>Function and Method Cross Reference</h3> <h2><a href="index.html#<API key>"><API key>()</a></h2> <b>Defined at:</b><ul> <li><a href="../tests/simpletest/test/acceptance_test.php.html#<API key>">/tests/simpletest/test/acceptance_test.php</a> -> <a onClick="logFunction('<API key>', '/tests/simpletest/test/acceptance_test.php.source.html#l185')" href="../tests/simpletest/test/acceptance_test.php.source.html#l185"> line 185</a></li> </ul> <b>No references found.</b><br><br> </ul> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Thu Oct 23 18:57:41 2014</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
package server import ( "bytes" "context" "encoding/json" "io/ioutil" "log" "net/http" "strings" "sync" "sync/atomic" "text/template" "time" "github.com/TV4/graceful" "github.com/gogap/config" "github.com/gogap/go-wkhtmltox/wkhtmltox" "github.com/gorilla/mux" "github.com/phyber/negroni-gzip/gzip" "github.com/rs/cors" "github.com/spf13/cast" "github.com/urfave/negroni" ) const ( defaultTemplateText = `{"code":{{.Code}},"message":"{{.Message}}"{{if .Result}},"result":{{.Result|jsonify}}{{end}}}` ) var ( htmlToX *wkhtmltox.WKHtmlToX renderTmpls = make(map[string]*template.Template) defaultTmpl *template.Template ) type ConvertData struct { Data []byte `json:"data"` } type ConvertArgs struct { To string `json:"to"` Fetcher wkhtmltox.FetcherOptions `json:"fetcher"` Converter json.RawMessage `json:"converter"` Template string `json:"template"` } type TemplateArgs struct { To string ConvertResponse Response *RespHelper } type ConvertResponse struct { Code int `json:"code"` Message string `json:"message"` Result interface{} `json:"result"` } type serverWrapper struct { tls bool certFile string keyFile string reqNumber int64 addr string n *negroni.Negroni timeout time.Duration } func (p *serverWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) { atomic.AddInt64(&p.reqNumber, 1) defer atomic.AddInt64(&p.reqNumber, -1) p.n.ServeHTTP(w, r) } func (p *serverWrapper) ListenAndServe() (err error) { if p.tls { err = http.ListenAndServeTLS(p.addr, p.certFile, p.keyFile, p) } else { err = http.ListenAndServe(p.addr, p) } return } func (p *serverWrapper) Shutdown(ctx context.Context) error { num := atomic.LoadInt64(&p.reqNumber) schema := "HTTP" if p.tls { schema = "HTTPS" } beginTime := time.Now() for num > 0 { time.Sleep(time.Second) timeDiff := time.Now().Sub(beginTime) if timeDiff > p.timeout { break } } log.Printf("[%s] Shutdown finished, Address: %s\n", schema, p.addr) return nil } type WKHtmlToXServer struct { conf config.Configuration servers []*serverWrapper } func New(conf config.Configuration) (srv *WKHtmlToXServer, err error) { serviceConf := conf.GetConfig("service") wkHtmlToXConf := conf.GetConfig("wkhtmltox") htmlToX, err = wkhtmltox.New(wkHtmlToXConf) if err != nil { return } // init templates defaultTmpl, err = template.New("default").Funcs(funcMap).Parse(defaultTemplateText) if err != nil { return } err = loadTemplates( serviceConf.GetConfig("templates"), ) if err != nil { return } // init http server c := cors.New( cors.Options{ AllowedOrigins: serviceConf.GetStringList("cors.allowed-origins"), AllowedMethods: serviceConf.GetStringList("cors.allowed-methods"), AllowedHeaders: serviceConf.GetStringList("cors.allowed-headers"), ExposedHeaders: serviceConf.GetStringList("cors.exposed-headers"), AllowCredentials: serviceConf.GetBoolean("cors.allow-credentials"), MaxAge: int(serviceConf.GetInt64("cors.max-age")), OptionsPassthrough: serviceConf.GetBoolean("cors.options-passthrough"), Debug: serviceConf.GetBoolean("cors.debug"), }, ) r := mux.NewRouter() pathPrefix := serviceConf.GetString("path", "/") r.PathPrefix(pathPrefix).Path("/convert"). Methods("POST"). HandlerFunc(handleHtmlToX) r.PathPrefix(pathPrefix).Path("/ping"). Methods("GET", "HEAD").HandlerFunc( func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("Content-Type", "text/plain; charset=utf-8") rw.Write([]byte("pong")) }, ) n := negroni.Classic() n.Use(c) // use cors if serviceConf.GetBoolean("gzip-enabled", true) { n.Use(gzip.Gzip(gzip.DefaultCompression)) } n.UseHandler(r) gracefulTimeout := serviceConf.GetTimeDuration("graceful.timeout", time.Second*3) enableHTTP := serviceConf.GetBoolean("http.enabled", true) enableHTTPS := serviceConf.GetBoolean("https.enabled", false) var servers []*serverWrapper if enableHTTP { listenAddr := serviceConf.GetString("http.address", "127.0.0.1:8080") httpServer := &serverWrapper{ n: n, timeout: gracefulTimeout, addr: listenAddr, } servers = append(servers, httpServer) } if enableHTTPS { listenAddr := serviceConf.GetString("http.address", "127.0.0.1:443") certFile := serviceConf.GetString("https.cert") keyFile := serviceConf.GetString("https.key") httpsServer := &serverWrapper{ n: n, timeout: gracefulTimeout, addr: listenAddr, tls: true, certFile: certFile, keyFile: keyFile, } servers = append(servers, httpsServer) } srv = &WKHtmlToXServer{ conf: conf, servers: servers, } return } func (p *WKHtmlToXServer) Run() (err error) { wg := sync.WaitGroup{} wg.Add(len(p.servers)) for i := 0; i < len(p.servers); i++ { go func(srv *serverWrapper) { defer wg.Done() shcema := "HTTP" if srv.tls { shcema = "HTTPS" } log.Printf("[%s] Listening on %s\n", shcema, srv.addr) graceful.ListenAndServe(srv) }(p.servers[i]) } wg.Wait() return } func writeResp(rw http.ResponseWriter, convertArgs ConvertArgs, resp ConvertResponse) { var tmpl *template.Template if len(convertArgs.Template) == 0 { tmpl = defaultTmpl } else { var exist bool tmpl, exist = renderTmpls[convertArgs.Template] if !exist { tmpl = defaultTmpl } } respHelper := newRespHelper(rw) args := TemplateArgs{ To: convertArgs.To, ConvertResponse: resp, Response: respHelper, } buf := bytes.NewBuffer(nil) err := tmpl.Execute(buf, args) if err != nil { log.Println(err) } if !respHelper.Holding() { rw.Write(buf.Bytes()) } } func handleHtmlToX(rw http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) decoder.UseNumber() args := ConvertArgs{} err := decoder.Decode(&args) if err != nil { writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil}) return } if len(args.Converter) == 0 { writeResp(rw, args, ConvertResponse{http.StatusBadRequest, "converter is nil", nil}) return } to := strings.ToUpper(args.To) var opts wkhtmltox.ConvertOptions if to == "IMAGE" { opts = &wkhtmltox.ToImageOptions{} } else if to == "PDF" { opts = &wkhtmltox.ToPDFOptions{} } else { writeResp(rw, args, ConvertResponse{http.StatusBadRequest, "argument of to is illegal (image|pdf)", nil}) return } err = json.Unmarshal(args.Converter, opts) if err != nil { writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil}) return } var convData []byte convData, err = htmlToX.Convert(args.Fetcher, opts) if err != nil { writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil}) return } writeResp(rw, args, ConvertResponse{0, "", ConvertData{Data: convData}}) return } func loadTemplates(tmplsConf config.Configuration) (err error) { if tmplsConf == nil { return } tmpls := tmplsConf.Keys() for _, name := range tmpls { file := tmplsConf.GetString(name + ".template") tmpl := template.New(name).Funcs(funcMap) var data []byte data, err = ioutil.ReadFile(file) if err != nil { return } tmpl, err = tmpl.Parse(string(data)) if err != nil { return } renderTmpls[name] = tmpl } return } type RespHelper struct { rw http.ResponseWriter hold bool } func newRespHelper(rw http.ResponseWriter) *RespHelper { return &RespHelper{ rw: rw, hold: false, } } func (p *RespHelper) SetHeader(key, value interface{}) error { k := cast.ToString(key) v := cast.ToString(value) p.rw.Header().Set(k, v) return nil } func (p *RespHelper) Hold(v interface{}) error { h := cast.ToBool(v) p.hold = h return nil } func (p *RespHelper) Holding() bool { return p.hold } func (p *RespHelper) Write(data []byte) error { p.rw.Write(data) return nil } func (p *RespHelper) WriteHeader(code interface{}) error { c, err := cast.ToIntE(code) if err != nil { return err } p.rw.WriteHeader(c) return nil }
package org.neo4j.collection.primitive; public interface <API key><E extends Exception> { /** * Visit the given entry. * * @param key The key of the entry. * @param value The value of the entry. * @return 'true' to signal that the iteration should be stopped, 'false' to signal that the iteration should * continue if there are more entries to look at. * @throws E any thrown exception of type 'E' will bubble up through the 'visit' method. */ boolean visited( long key, int value ) throws E; }
package org.anyline.entity; import com.fasterxml.jackson.databind.JsonNode; import org.anyline.util.*; import org.anyline.util.regular.Regular; import org.anyline.util.regular.RegularUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.math.BigDecimal; import java.util.*; public class DataSet implements Collection<DataRow>, Serializable { private static final long serialVersionUID = <API key>; protected static final Logger log = LoggerFactory.getLogger(DataSet.class); private boolean result = true; private Exception exception = null; private String message = null; private PageNavi navi = null; private List<String> head = null; private List<DataRow> rows = null; private List<String> primaryKeys = null; private String datalink = null; private String dataSource = null; // (||XMLSQL) private String schema = null; private String table = null; private long createTime = 0; private long expires = -1; //() expires private boolean isFromCache = false; private boolean isAsc = false; private boolean isDesc = false; private Map<String, Object> queryParams = new HashMap<String, Object>(); /** * * * @param key key * @return return * crateIndex("ID"); * crateIndex("ID:ASC"); */ public DataSet creatIndex(String key) { return this; } public DataSet() { rows = new ArrayList<DataRow>(); createTime = System.currentTimeMillis(); } public DataSet(List<Map<String, Object>> list) { rows = new ArrayList<DataRow>(); if (null == list) return; for (Map<String, Object> map : list) { DataRow row = new DataRow(map); rows.add(row); } } public static DataSet build(Collection<?> list, String ... fields) { return parse(list, fields); } /** * listDataSet * @param list list * @param fields list * fields (/key) "ID","CODE","NAME" * DataRowkey row.put("0","100").put("1","A01").put("2",""); * listnullDataRow * * list * fileds DataRowkey "USER_ID:id","USER_NM:name" * * @return DataSet */ public static DataSet parse(Collection<?> list, String ... fields) { DataSet set = new DataSet(); if (null != list) { for (Object obj : list) { DataRow row = null; if(obj instanceof Collection){ row = DataRow.parseList((Collection)obj, fields); }else { row = DataRow.parse(obj, fields); } set.add(row); } } return set; } public static DataSet parseJson(DataRow.KEY_CASE keyCase, String json) { if (null != json) { try { return parseJson(keyCase, BeanUtil.JSON_MAPPER.readTree(json)); } catch (Exception e) { } } return null; } public static DataSet parseJson(String json) { return parseJson(DataRow.KEY_CASE.CONFIG, json); } public static DataSet parseJson(DataRow.KEY_CASE keyCase, JsonNode json) { DataSet set = new DataSet(); if (null != json) { if (json.isArray()) { Iterator<JsonNode> items = json.iterator(); while (items.hasNext()) { JsonNode item = items.next(); set.add(DataRow.parseJson(keyCase, item)); } } } return set; } public static DataSet parseJson(JsonNode json) { return parseJson(DataRow.KEY_CASE.CONFIG, json); } public DataSet Camel(){ for(DataRow row:rows){ row.Camel(); } return this; } public DataSet camel(){ for(DataRow row:rows){ row.camel(); } return this; } public DataSet setIsNew(boolean bol) { for (DataRow row : rows) { row.setIsNew(bol); } return this; } /** * key * * @param keys keys * @return DataSet */ public DataSet remove(String... keys) { for (DataRow row : rows) { for (String key : keys) { row.remove(key); } } return this; } public DataSet trim(){ for(DataRow row:rows){ row.trim(); } return this; } /** * * * @param applyItem DataRow true * @param pks pks * @return return */ public DataSet addPrimaryKey(boolean applyItem, String... pks) { if (null != pks) { List<String> list = new ArrayList<>(); for (String pk : pks) { list.add(pk); } addPrimaryKey(applyItem, list); } return this; } public DataSet addPrimaryKey(String... pks) { return addPrimaryKey(true, pks); } public DataSet addPrimaryKey(boolean applyItem, Collection<String> pks) { if (null == primaryKeys) { primaryKeys = new ArrayList<>(); } if (null == pks) { return this; } for (String pk : pks) { if (BasicUtil.isEmpty(pk)) { continue; } pk = key(pk); if (!primaryKeys.contains(pk)) { primaryKeys.add(pk); } } if (applyItem) { for (DataRow row : rows) { row.setPrimaryKey(false, primaryKeys); } } return this; } public DataSet addPrimaryKey(Collection<String> pks) { return addPrimaryKey(true, pks); } /** * * * @param applyItem applyItem * @param pks pks * @return return */ public DataSet setPrimaryKey(boolean applyItem, String... pks) { if (null != pks) { List<String> list = new ArrayList<>(); for (String pk : pks) { list.add(pk); } setPrimaryKey(applyItem, list); } return this; } public DataSet setPrimaryKey(String... pks) { return setPrimaryKey(true, pks); } public DataSet setPrimaryKey(boolean applyItem, Collection<String> pks) { if (null == pks) { return this; } this.primaryKeys = new ArrayList<>(); addPrimaryKey(applyItem, pks); return this; } public DataSet setPrimaryKey(Collection<String> pks) { return setPrimaryKey(true, pks); } public DataSet set(int index, DataRow item) { rows.set(index, item); return this; } /** * * * @return return */ public boolean hasPrimaryKeys() { if (null != primaryKeys && primaryKeys.size() > 0) { return true; } else { return false; } } /** * * * @return return */ public List<String> getPrimaryKeys() { if (null == primaryKeys) { primaryKeys = new ArrayList<>(); } return primaryKeys; } /** * * * @param col col * @return return */ public DataSet addHead(String col) { if (null == head) { head = new ArrayList<>(); } if ("ROW_NUMBER".equals(col)) { return this; } if (head.contains(col)) { return this; } head.add(col); return this; } /** * * * @return return */ public List<String> getHead() { return head; } public int indexOf(Object obj) { return rows.indexOf(obj); } /** * beginend,DataSet * * @param begin * @param end * @return DataSet */ public DataSet truncates(int begin, int end) { if (!rows.isEmpty()) { if (begin < 0) { begin = 0; } if (end >= rows.size()) { end = rows.size() - 1; } if (begin >= rows.size()) { begin = rows.size() - 1; } if (end <= 0) { end = 0; } rows = rows.subList(begin, end); } return this; } /** * begin * * @param begin * @return DataSet */ public DataSet truncates(int begin) { if (begin < 0) { begin = rows.size() + begin; int end = rows.size() - 1; return truncates(begin, end); } else { return truncates(begin, rows.size() - 1); } } /** * beginDataRow * * @param begin * @return DataRow */ public DataRow truncate(int begin) { return truncate(begin, rows.size() - 1); } /** * beginendDataRow * * @param begin * @param end * @return DataRow */ public DataRow truncate(int begin, int end) { truncates(begin, end); if (rows.size() > 0) { return rows.get(0); } else { return null; } } /** * begin * * @param begin * n, * @return DataSet */ public DataSet cuts(int begin) { if (begin < 0) { begin = rows.size() + begin; int end = rows.size() - 1; return cuts(begin, end); } else { return cuts(begin, rows.size() - 1); } } /** * beginendDataSetset * * @param begin * @param end * @return DataSet */ public DataSet cuts(int begin, int end) { DataSet result = new DataSet(); if (rows.isEmpty()) { return result; } if (begin < 0) { begin = 0; } if (end >= rows.size()) { end = rows.size() - 1; } if (begin >= rows.size()) { begin = rows.size() - 1; } if (end <= 0) { end = 0; } for (int i = begin; i <= end; i++) { result.add(rows.get(i)); } return result; } /** * begin,DataRow * * @param begin * @return DataSet */ public DataRow cut(int begin) { return cut(begin, rows.size() - 1); } /** * beginendDataRow,DataSetset * * @param begin * @param end * @return DataSet */ public DataRow cut(int begin, int end) { DataSet result = cuts(begin, end); if (result.size() > 0) { return result.getRow(0); } return null; } /** * * * @return return */ public int size() { int result = 0; if (null != rows) result = rows.size(); return result; } public int getSize() { return size(); } /** * * * @return return */ public boolean isException() { return null != exception; } public boolean isFromCache() { return isFromCache; } public DataSet setIsFromCache(boolean bol) { this.isFromCache = bol; return this; } /** * * * @return return */ public boolean isEmpty() { boolean result = true; if (null == rows) { result = true; } else if (rows instanceof Collection) { result = ((Collection<?>) rows).isEmpty(); } return result; } /** * * * @param index index * @return return */ public DataRow getRow(int index) { DataRow row = null; if (null != rows && index < rows.size()) { row = rows.get(index); } if (null != row) { row.setContainer(this); } return row; } public boolean exists(String ... params){ DataRow row = getRow(0, params); return row != null; } public DataRow getRow(String... params) { return getRow(0, params); } public DataRow getRow(DataRow params) { return getRow(0, params); } public DataRow getRow(List<String> params) { String[] kvs = BeanUtil.list2array(params); return getRow(0, kvs); } public DataRow getRow(int begin, String... params) { DataSet set = getRows(begin, 1, params); if (set.size() > 0) { return set.getRow(0); } return null; } public DataRow getRow(int begin, DataRow params) { DataSet set = getRows(begin, 1, params); if (set.size() > 0) { return set.getRow(0); } return null; } /** * keys * * @param keys keys * @return DataSet */ public DataSet distinct(String... keys) { DataSet result = new DataSet(); if (null != rows) { int size = rows.size(); for (int i = 0; i < size; i++) { DataRow row = rows.get(i); //result String[] params = packParam(row, keys); if (result.getRow(params) == null) { DataRow tmp = new DataRow(); for (String key : keys) { tmp.put(key, row.get(key)); } result.addRow(tmp); } } } result.cloneProperty(this); return result; } public DataSet distinct(List<String> keys) { DataSet result = new DataSet(); if (null != rows) { for (DataRow row:rows) { //result String[] params = packParam(row, keys); if (result.getRow(params) == null) { DataRow tmp = new DataRow(); for (String key : keys) { tmp.put(key, row.get(key)); } result.addRow(tmp); } } } result.cloneProperty(this); return result; } public Object clone() { DataSet set = new DataSet(); List<DataRow> rows = new ArrayList<DataRow>(); for (DataRow row : this.rows) { rows.add((DataRow) row.clone()); } set.setRows(rows); set.cloneProperty(this); return set; } private DataSet cloneProperty(DataSet from) { return cloneProperty(from, this); } public static DataSet cloneProperty(DataSet from, DataSet to) { if (null != from && null != to) { to.exception = from.exception; to.message = from.message; to.navi = from.navi; to.head = from.head; to.primaryKeys = from.primaryKeys; to.dataSource = from.dataSource; to.datalink = from.datalink; to.schema = from.schema; to.table = from.table; } return to; } /** * keynumber * @param keys keys * @return DataRow */ public DataSet convertNumber(String ... keys){ if(null != keys) { for(DataRow row:rows){ row.convertNumber(keys); } } return this; } public DataSet convertString(String ... keys){ if(null != keys) { for(DataRow row:rows){ row.convertString(keys); } } return this; } public DataSet skip(boolean skip){ for(DataRow row:rows){ row.skip = skip; } return this; } /** * * String 11.0, convertNumber * @param params key1,value1,key2:value2,key3,value3 * "NM:zh%","AGE:&gt;20","NM","%zh%" * @param begin begin * @param qty 0 * @return return */ public DataSet getRows(int begin, int qty, String... params) { DataSet set = new DataSet(); Map<String, String> kvs = new HashMap<String, String>(); int len = params.length; int i = 0; String srcFlagTag = "srcFlag"; //{} kvskey+tag ,TIME:{10:10} while (i < len) { String p1 = params[i]; if (BasicUtil.isEmpty(p1)) { i++; continue; } else if (p1.contains(":")) { String ks[] = BeanUtil.parseKeyValue(p1); kvs.put(ks[0], ks[1]); i++; continue; } else { if (i + 1 < len) { String p2 = params[i + 1]; if (BasicUtil.isEmpty(p2) || !p2.contains(":")) { kvs.put(p1, p2); i += 2; continue; } else if (p2.startsWith("{") && p2.endsWith("}")) { p2 = p2.substring(1, p2.length() - 1); kvs.put(p1, p2); kvs.put(p1 + srcFlagTag, "true"); i += 2; continue; } else { String ks[] = BeanUtil.parseKeyValue(p2); kvs.put(ks[0], ks[1]); i += 2; continue; } } } i++; } return getRows(begin, qty, kvs); } public DataSet getRows(int begin, int qty, DataRow kvs) { Map<String,String> map = new HashMap<String,String>(); for(String k:kvs.keySet()){ map.put(k, kvs.getString(k)); } return getRows(begin, qty, map); } public DataSet getRows(int begin, int qty, Map<String, String> kvs) { DataSet set = new DataSet(); String srcFlagTag = "srcFlag"; //{} kvskey+tag BigDecimal d1; BigDecimal d2; for (DataRow row:rows) { if(row.skip){ continue; } boolean chk = true; for (String k : kvs.keySet()) { boolean srcFlag = false; if (k.endsWith(srcFlagTag)) { continue; } else { String srcFlagValue = kvs.get(k + srcFlagTag); if (BasicUtil.isNotEmpty(srcFlagValue)) { srcFlag = true; } } String v = kvs.get(k); Object value = row.get(k); if(!row.containsKey(k) && null == value){ //key chk = false; break; } if (null == v) { if (null != value) { chk = false; break; }else{ continue; } } else { if (null == value) { chk = false; break; } //SQL.COMPARE_TYPE int compare = 10; if (v.startsWith("=")) { compare = 10; v = v.substring(1); } else if (v.startsWith(">")) { compare = 20; v = v.substring(1); } else if (v.startsWith(">=")) { compare = 21; v = v.substring(2); } else if (v.startsWith("<")) { compare = 30; v = v.substring(1); } else if (v.startsWith("<=")) { compare = 31; v = v.substring(2); } else if (v.startsWith("%") && v.endsWith("%")) { compare = 50; v = v.substring(1, v.length() - 1); } else if (v.endsWith("%")) { compare = 51; v = v.substring(0, v.length() - 1); } else if (v.startsWith("%")) { compare = 52; v = v.substring(1); } if(compare <= 31 && value instanceof Number) { try { d1 = new BigDecimal(value.toString()); d2 = new BigDecimal(v); int cr = d1.compareTo(d2); if (compare == 10) { if (cr != 0) { chk = false; break; } } else if (compare == 20) { if (cr <= 0) { chk = false; break; } } else if (compare == 21) { if (cr < 0) { chk = false; break; } } else if (compare == 30) { if (cr >= 0) { chk = false; break; } } else if (compare == 31) { if (cr > 0) { chk = false; break; } } }catch (<API key> e){ chk = false; break; } } String str = value + ""; str = str.toLowerCase(); v = v.toLowerCase(); if (srcFlag) { v = "{" + v + "}"; } if (compare == 10) { if (!v.equals(str)) { chk = false; break; } } else if (compare == 50) { if (!str.contains(v)) { chk = false; break; } } else if (compare == 51) { if (!str.startsWith(v)) { chk = false; break; } } else if (compare == 52) { if (!str.endsWith(v)) { chk = false; break; } } } }//end for kvs if (chk) { set.add(row); if (qty > 0 && set.size() >= qty) { break; } } }//end for rows set.cloneProperty(this); return set; } public DataSet getRows(int begin, String... params) { return getRows(begin, -1, params); } public DataSet getRows(String... params) { return getRows(0, params); } public DataSet getRows(DataSet set, String key) { String kvs[] = new String[set.size()]; int i = 0; for (DataRow row : set) { String value = row.getString(key); if (BasicUtil.isNotEmpty(value)) { kvs[i++] = key + ":" + value; } } return getRows(kvs); } public DataSet getRows(DataRow row, String... keys) { List<String> list = new ArrayList<>(); int i = 0; for (String key : keys) { String value = row.getString(key); if (BasicUtil.isNotEmpty(value)) { list.add(key + ":" + value); } } String[] kvs = BeanUtil.list2array(list); return getRows(kvs); } /** * * * @param format format * @param cols cols * @return return */ public DataSet formatNumber(String format, String... cols) { if (null == cols || BasicUtil.isEmpty(format)) { return this; } int size = size(); for (int i = 0; i < size; i++) { DataRow row = getRow(i); row.formatNumber(format, cols); } return this; } public DataSet numberFormat(String target, String key, String format){ for(DataRow row: rows){ numberFormat(target, key, format); } return this; } public DataSet numberFormat(String key, String format){ return numberFormat(key, key, format); } /** * * * @param format format * @param cols cols * @return return */ public DataSet formatDate(String format, String... cols) { if (null == cols || BasicUtil.isEmpty(format)) { return this; } int size = size(); for (int i = 0; i < size; i++) { DataRow row = getRow(i); row.formatDate(format, cols); } return this; } public DataSet dateFormat(String target, String key, String format){ for(DataRow row: rows){ dateFormat(target, key, format); } return this; } public DataSet dateFormat(String key, String format){ return dateFormat(key, key, format); } /** * * * @param begin begin * @param end end * @param key key * @param value value * @return return */ public DataSet filter(int begin, int end, String key, String value) { DataSet set = new DataSet(); String tmpValue; int size = size(); if (begin < 0) { begin = 0; } for (int i = begin; i < size && i <= end; i++) { tmpValue = getString(i, key, ""); if ((null == value && null == tmpValue) || (null != value && value.equals(tmpValue))) { set.add(getRow(i)); } } set.cloneProperty(this); return set; } public DataSet getRows(int fr, int to) { DataSet set = new DataSet(); int size = this.size(); if (fr < 0) { fr = 0; } for (int i = fr; i < size && i <= to; i++) { set.addRow(getRow(i)); } return set; } /** * * @param begin * @param end * @param key key * @return BigDecimal */ public BigDecimal sum(int begin, int end, String key) { BigDecimal result = BigDecimal.ZERO; int size = rows.size(); if (begin <= 0) { begin = 0; } for (int i = begin; i < size && i <= end; i++) { BigDecimal tmp = getDecimal(i, key, 0); if (null != tmp) { result = result.add(getDecimal(i, key, 0)); } } return result; } public BigDecimal sum(String key) { BigDecimal result = BigDecimal.ZERO; result = sum(0, size() - 1, key); return result; } /** * * @param result * @param keys keys * @return DataRow */ public DataRow sums(DataRow result, String... keys) { if(null == result){ result = new DataRow(); } if (size() > 0) { if (null != keys) { for (String key : keys) { result.put(key, sum(key)); } } else { List<String> numberKeys = getRow(0).numberKeys(); for (String key : numberKeys) { result.put(key, sum(key)); } } } return result; } public DataRow sums(String... keys) { return sums(new DataRow(), keys); } /** * * * @param result * @param keys keys * @return DataRow */ public DataRow avgs(DataRow result, String... keys) { if(null == result){ result = new DataRow(); } if (size() > 0) { if (null != keys) { for (String key : keys) { result.put(key, avg(key)); } } else { List<String> numberKeys = getRow(0).numberKeys(); for (String key : numberKeys) { result.put(key, avg(key)); } } } return result; } public DataRow avgs(String... keys) { return avgs(new DataRow(), keys); } /** * * @param result * @param scale scale * @param round round * @param keys keys * @return DataRow */ public DataRow avgs(DataRow result, int scale, int round, String... keys) { if(null == result){ result = new DataRow(); } if (size() > 0) { if (null != keys) { for (String key : keys) { result.put(key, avg(key, scale, round)); } } else { List<String> numberKeys = getRow(0).numberKeys(); for (String key : numberKeys) { result.put(key, avg(key, scale, round)); } } } return result; } public DataRow avgs(int scale, int round, String... keys) { return avgs(new DataRow(), scale, round, keys); } /** * * * @param top * @param key key * @return return */ public BigDecimal maxDecimal(int top, String key) { BigDecimal result = null; int size = rows.size(); if (size > top) { size = top; } for (int i = 0; i < size; i++) { BigDecimal tmp = getDecimal(i, key, 0); if (null != tmp && (null == result || tmp.compareTo(result) > 0)) { result = tmp; } } return result; } public BigDecimal maxDecimal(String key) { return maxDecimal(size(), key); } public int maxInt(int top, String key) { BigDecimal result = maxDecimal(top, key); if (null == result) { return 0; } return result.intValue(); } public int maxInt(String key) { return maxInt(size(), key); } public double maxDouble(int top, String key) { BigDecimal result = maxDecimal(top, key); if (null == result) { return 0; } return result.doubleValue(); } public double maxDouble(String key) { return maxDouble(size(), key); } // public BigDecimal max(int top, String key){ // BigDecimal result = maxDecimal(top, key); // return result; // public BigDecimal max(String key){ // return maxDecimal(size(), key); /** * * * @param top * @param key key * @return return */ public BigDecimal minDecimal(int top, String key) { BigDecimal result = null; int size = rows.size(); if (size > top) { size = top; } for (int i = 0; i < size; i++) { BigDecimal tmp = getDecimal(i, key, 0); if (null != tmp && (null == result || tmp.compareTo(result) < 0)) { result = tmp; } } return result; } public BigDecimal minDecimal(String key) { return minDecimal(size(), key); } public int minInt(int top, String key) { BigDecimal result = minDecimal(top, key); if (null == result) { return 0; } return result.intValue(); } public int minInt(String key) { return minInt(size(), key); } public double minDouble(int top, String key) { BigDecimal result = minDecimal(top, key); if (null == result) { return 0; } return result.doubleValue(); } public double minDouble(String key) { return minDouble(size(), key); } // public BigDecimal min(int top, String key){ // BigDecimal result = minDecimal(top, key); // return result; // public BigDecimal min(String key){ // return minDecimal(size(), key); /** * keyvalue * * @param key key * @return return */ public DataRow max(String key) { int size = size(); if (size == 0) { return null; } DataRow row = null; if (isAsc) { row = getRow(size - 1); } else if (isDesc) { row = getRow(0); } else { asc(key); row = getRow(size - 1); } return row; } public DataRow min(String key) { int size = size(); if (size == 0) { return null; } DataRow row = null; if (isAsc) { row = getRow(0); } else if (isDesc) { row = getRow(size - 1); } else { asc(key); row = getRow(0); } return row; } /** * * * @param top * @param key key * @param scale scale * @param round round * @return return */ public BigDecimal avg(int top, String key, int scale, int round) { BigDecimal result = BigDecimal.ZERO; int size = rows.size(); if (size > top) { size = top; } int count = 0; for (int i = 0; i < size; i++) { BigDecimal tmp = getDecimal(i, key, 0); if (null != tmp) { result = result.add(tmp); } count++; } if (count > 0) { result = result.divide(new BigDecimal(count), scale, round); } return result; } public BigDecimal avg(String key, int scale, int round) { BigDecimal result = avg(size(), key, scale ,round); return result; } public BigDecimal avg(String key) { BigDecimal result = avg(size(), key, 2, BigDecimal.ROUND_HALF_UP); return result; } public DataSet addRow(DataRow row) { if (null != row) { rows.add(row); } return this; } public DataSet addRow(int idx, DataRow row) { if (null != row) { rows.add(idx, row); } return this; } /** * key connector * * @param key key * @param connector connector * @return return v1,v2,v3 */ public String concat(String key, String connector) { return BasicUtil.concat(getStrings(key), connector); } public String concatNvl(String key, String connector) { return BasicUtil.concat(getNvlStrings(key), connector); } /** * key connector(null) * * @param key key * @param connector connector * @return return v1,v2,v3 */ public String concatWithoutNull(String key, String connector) { return BasicUtil.concat(<API key>(key), connector); } /** * key connector() * * @param key key * @param connector connector * @return return v1,v2,v3 */ public String concatWithoutEmpty(String key, String connector) { return BasicUtil.concat(<API key>(key), connector); } public String concatNvl(String key) { return BasicUtil.concat(getNvlStrings(key), ","); } public String concatWithoutNull(String key) { return BasicUtil.concat(<API key>(key), ","); } public String concatWithoutEmpty(String key) { return BasicUtil.concat(<API key>(key), ","); } public String concat(String key) { return BasicUtil.concat(getStrings(key), ","); } /** * * * @param key key * @return return */ public List<Object> fetchValues(String key) { List<Object> result = new ArrayList<Object>(); for (int i = 0; i < size(); i++) { result.add(get(i, key)); } return result; } /** * * * @param key key * @return return */ public List<String> fetchDistinctValue(String key) { List<String> result = new ArrayList<>(); for (int i = 0; i < size(); i++) { String value = getString(i, key, ""); if (result.contains(value)) { continue; } result.add(value); } return result; } public List<String> fetchDistinctValues(String key) { return fetchDistinctValue(key); } /** * * * @param link link * @return return */ public String displayNavi(String link) { String result = ""; if (null != navi) { result = navi.getHtml(); } return result; } public String navi(String link) { return displayNavi(link); } public String displayNavi() { return displayNavi(null); } public String navi() { return displayNavi(null); } public DataSet put(int idx, String key, Object value) { DataRow row = getRow(idx); if (null != row) { row.put(key, value); } return this; } public DataSet removes(String... keys) { for (DataRow row : rows) { row.removes(keys); } return this; } /** * String * * @param index index * @param key key * @return String * @throws Exception Exception */ public String getString(int index, String key) throws Exception { return getRow(index).getString(key); } public String getString(int index, String key, String def) { try { return getString(index, key); } catch (Exception e) { return def; } } public String getString(String key) throws Exception { return getString(0, key); } public String getString(String key, String def) { return getString(0, key, def); } public Object get(int index, String key) { DataRow row = getRow(index); if (null != row) { return row.get(key); } return null; } public List<Object> gets(String key) { List<Object> list = new ArrayList<Object>(); for (DataRow row : rows) { list.add(row.getString(key)); } return list; } public List<DataSet> getSets(String key) { List<DataSet> list = new ArrayList<DataSet>(); for (DataRow row : rows) { DataSet set = row.getSet(key); if (null != set) { list.add(set); } } return list; } public List<String> getStrings(String key) { List<String> result = new ArrayList<>(); for (DataRow row : rows) { result.add(row.getString(key)); } return result; } public List<Integer> getInts(String key) throws Exception { List<Integer> result = new ArrayList<Integer>(); for (DataRow row : rows) { result.add(row.getInt(key)); } return result; } public List<Object> getObjects(String key) { List<Object> result = new ArrayList<Object>(); for (DataRow row : rows) { result.add(row.get(key)); } return result; } public List<String> getDistinctStrings(String key) { return fetchDistinctValue(key); } public List<String> getNvlStrings(String key) { List<String> result = new ArrayList<>(); List<Object> list = fetchValues(key); for (Object val : list) { if (null != val) { result.add(val.toString()); } else { result.add(""); } } return result; } public List<String> <API key>(String key) { List<String> result = new ArrayList<>(); List<Object> list = fetchValues(key); for (Object val : list) { if (BasicUtil.isNotEmpty(val)) { result.add(val.toString()); } } return result; } public List<String> <API key>(String key) { List<String> result = new ArrayList<>(); List<Object> list = fetchValues(key); for (Object val : list) { if (null != val) { result.add(val.toString()); } } return result; } public BigDecimal getDecimal(int idx, String key) throws Exception { return getRow(idx).getDecimal(key); } public BigDecimal getDecimal(int idx, String key, double def) { return getDecimal(idx, key, new BigDecimal(def)); } public BigDecimal getDecimal(int idx, String key, BigDecimal def) { try { BigDecimal val = getDecimal(idx, key); if (null == val) { return def; } return val; } catch (Exception e) { return def; } } /** * DataSet DataSet() * @param keys keys * @return DataSet */ public DataSet extract(String ... keys){ DataSet result = new DataSet(); for(DataRow row:rows){ DataRow item = row.extract(keys); result.add(item); } result.navi = this.navi; return result; } public DataSet extract(List<String> keys){ DataSet result = new DataSet(); for(DataRow row:rows){ DataRow item = row.extract(keys); result.add(item); } result.navi = this.navi; return result; } /** * html() * * @param index index * @param key key * @return return * @throws Exception Exception */ public String getHtmlString(int index, String key) throws Exception { return getString(index, key); } public String getHtmlString(int index, String key, String def) { return getString(index, key, def); } public String getHtmlString(String key) throws Exception { return getHtmlString(0, key); } /** * escape String * * @param index index * @param key key * @return return * @throws Exception Exception */ public String getEscapeString(int index, String key) throws Exception { return EscapeUtil.escape(getString(index, key)).toString(); } public String getEscapeString(int index, String key, String def) { try { return getEscapeString(index, key); } catch (Exception e) { return EscapeUtil.escape(def).toString(); } } public String <API key>(int index, String key) throws Exception { return EscapeUtil.doubleEscape(getString(index, key)); } public String <API key>(int index, String key, String def) { try { return <API key>(index, key); } catch (Exception e) { return EscapeUtil.doubleEscape(def); } } public String getEscapeString(String key) throws Exception { return getEscapeString(0, key); } public String <API key>(String key) throws Exception { return <API key>(0, key); } /** * int * * @param index index * @param key key * @return return * @throws Exception Exception */ public int getInt(int index, String key) throws Exception { return getRow(index).getInt(key); } public int getInt(int index, String key, int def) { try { return getInt(index, key); } catch (Exception e) { return def; } } public int getInt(String key) throws Exception { return getInt(0, key); } public int getInt(String key, int def) { return getInt(0, key, def); } /** * double * * @param index index * @param key key * @return return * @throws Exception Exception */ public double getDouble(int index, String key) throws Exception { return getRow(index).getDouble(key); } public double getDouble(int index, String key, double def) { try { return getDouble(index, key); } catch (Exception e) { return def; } } public double getDouble(String key) throws Exception { return getDouble(0, key); } public double getDouble(String key, double def) { return getDouble(0, key, def); } /** * key +value,key0puttarget * @param target key * @param key key * @param value value * @return this */ public DataSet add(String target, String key, int value){ for(DataRow row:rows){ row.add(target, key, value); } return this; } public DataSet add(String target, String key, double value){ for(DataRow row:rows){ row.add(target, key, value); } return this; } public DataSet add(String target, String key, short value){ for(DataRow row:rows){ row.add(target, key, value); } return this; } public DataSet add(String target, String key, float value){ for(DataRow row:rows){ row.add(target, key, value); } return this; } public DataSet add(String target, String key, BigDecimal value){ for(DataRow row:rows){ row.add(target, key, value); } return this; } public DataSet add(String key, int value){ return add(key, key, value); } public DataSet add(String key, double value){ return add(key, key, value); } public DataSet add(String key, short value){ return add(key, key, value); } public DataSet add(String key, float value){ return add(key, key, value); } public DataSet add(String key, BigDecimal value){ return add(key, key, value); } public DataSet subtract(String target, String key, int value){ for(DataRow row:rows){ row.subtract(target, key, value); } return this; } public DataSet subtract(String target, String key, double value){ for(DataRow row:rows){ row.subtract(target, key, value); } return this; } public DataSet subtract(String target, String key, short value){ for(DataRow row:rows){ row.subtract(target, key, value); } return this; } public DataSet subtract(String target, String key, float value){ for(DataRow row:rows){ row.subtract(target, key, value); } return this; } public DataSet subtract(String target, String key, BigDecimal value){ for(DataRow row:rows){ row.subtract(target, key, value); } return this; } public DataSet subtract(String key, int value){ return subtract(key, key, value); } public DataSet subtract(String key, double value){ return subtract(key, key, value); } public DataSet subtract(String key, short value){ return subtract(key, key, value); } public DataSet subtract(String key, float value){ return subtract(key, key, value); } public DataSet subtract(String key, BigDecimal value){ return subtract(key, key, value); } public DataSet multiply(String target, String key, int value){ for(DataRow row:rows){ row.multiply(target, key, value); } return this; } public DataSet multiply(String target, String key, double value){ for(DataRow row:rows){ row.multiply(target, key, value); } return this; } public DataSet multiply(String target, String key, short value){ for(DataRow row:rows){ row.multiply(target, key, value); } return this; } public DataSet multiply(String target, String key, float value){ for(DataRow row:rows){ row.multiply(target, key, value); } return this; } public DataSet multiply(String target, String key, BigDecimal value){ for(DataRow row:rows){ row.multiply(target, key, value); } return this; } public DataSet multiply(String key, int value){ return multiply(key,key,value); } public DataSet multiply(String key, double value){ return multiply(key,key,value); } public DataSet multiply(String key, short value){ return multiply(key,key,value); } public DataSet multiply(String key, float value){ return multiply(key,key,value); } public DataSet multiply(String key, BigDecimal value){ return multiply(key,key,value); } public DataSet divide(String target, String key, int value){ for(DataRow row:rows){ row.divide(target, key, value); } return this; } public DataSet divide(String target, String key, double value){ for(DataRow row:rows){ row.divide(target, key, value); } return this; } public DataSet divide(String target, String key, short value){ for(DataRow row:rows){ row.divide(target, key, value); } return this; } public DataSet divide(String target, String key, float value){ for(DataRow row:rows){ row.divide(target, key, value); } return this; } public DataSet divide(String target, String key, BigDecimal value, int mode){ for(DataRow row:rows){ row.divide(target, key, value, mode); } return this; } public DataSet divide(String key, int value){ return divide(key,key, value); } public DataSet divide(String key, double value){ return divide(key,key, value); } public DataSet divide(String key, short value){ return divide(key,key, value); } public DataSet divide(String key, float value){ return divide(key,key, value); } public DataSet divide(String key, BigDecimal value, int mode){ return divide(key,key, value, mode); } public DataSet round(String target, String key, int scale, int mode){ for (DataRow row:rows){ row.round(target, key, scale, mode); } return this; } public DataSet round(String key, int scale, int mode){ return round(key, key, scale, mode); } /** * DataSetsize * @param page * @return list */ public List<DataSet> split(int page){ List<DataSet> list = new ArrayList<>(); int size = this.size(); int vol = size / page; for(int i=0; i<page; i++){ int fr = i*vol; int to = (i+1)*vol-1; if(i == page-1){ to = size-1; } DataSet set = this.cuts(fr, to); list.add(set); } return list; } /** * rows json toJSON * map.put("type", "list"); * map.put("result", result); * map.put("message", message); * map.put("rows", rows); * map.put("success", result); * map.put("navi", navi); */ public String toString() { Map<String, Object> map = new HashMap<String, Object>(); map.put("type", "list"); map.put("result", result); map.put("message", message); map.put("rows", rows); map.put("success", result); if(null != navi){ Map<String,Object> navi_ = new HashMap<String,Object>(); navi_.put("page", navi.getCurPage()); navi_.put("pages", navi.getTotalPage()); navi_.put("rows", navi.getTotalRow()); navi_.put("vol", navi.getPageRows()); map.put("navi", navi_); } return BeanUtil.map2json(map); } /** * rows json toString * * @return return */ public String toJson() { return BeanUtil.object2json(this); } public String getJson() { return toJSON(); } public String toJSON() { return toJson(); } /** * map * * @param key ID,{ID}_{NM} * @return return */ public Map<String, DataRow> toMap(String key) { Map<String, DataRow> maps = new HashMap<String, DataRow>(); for (DataRow row : rows) { maps.put(row.getString(key), row); } return maps; } /** * * * @param idx idx * @return return */ public Object getChildren(int idx) { DataRow row = getRow(idx); if (null != row) { return row.getChildren(); } return null; } public Object getChildren() { return getChildren(0); } public DataSet setChildren(int idx, Object children) { DataRow row = getRow(idx); if (null != row) { row.setChildren(children); } return this; } public DataSet setChildren(Object children) { setChildren(0, children); return this; } /** * * * @param idx idx * @return return */ public Object getParent(int idx) { DataRow row = getRow(idx); if (null != row) { return row.getParent(); } return null; } public Object getParent() { return getParent(0); } public DataSet setParent(int idx, Object parent) { DataRow row = getRow(idx); if (null != row) { row.setParent(parent); } return this; } public DataSet setParent(Object parent) { setParent(0, parent); return this; } /** * * * @param <T> T * @param index index * @param clazz clazz * @return return */ public <T> T entity(int index, Class<T> clazz) { DataRow row = getRow(index); if (null != row) { return row.entity(clazz); } return null; } /** * * * @param <T> T * @param clazz clazz * @return return */ public <T> List<T> entity(Class<T> clazz) { List<T> list = new ArrayList<T>(); if (null != rows) { for (DataRow row : rows) { list.add(row.entity(clazz)); } } return list; } public <T> T entity(Class<T> clazz, int idx) { DataRow row = getRow(idx); if (null != row) { return row.entity(clazz); } return null; } public DataSet setDataSource(String dataSource) { if (null == dataSource) { return this; } this.dataSource = dataSource; if (dataSource.contains(".") && !dataSource.contains(":")) { schema = dataSource.substring(0, dataSource.indexOf(".")); table = dataSource.substring(dataSource.indexOf(".") + 1); } for (DataRow row : rows) { if (BasicUtil.isEmpty(row.getDataSource())) { row.setDataSource(dataSource); } } return this; } /** * * @param set DataSet * @param keys keys * @return DataSet */ public DataSet union(DataSet set, String... keys) { DataSet result = new DataSet(); if (null != rows) { int size = rows.size(); for (int i = 0; i < size; i++) { result.add(rows.get(i)); } } if (null == keys || keys.length == 0) { keys = new String[1]; keys[0] = ConfigTable.getString("DEFAULT_PRIMARY_KEY"); } int size = set.size(); for (int i = 0; i < size; i++) { DataRow item = set.getRow(i); if (!result.contains(item, keys)) { result.add(item); } } return result; } /** * * * @param set set * @return return */ public DataSet unionAll(DataSet set) { DataSet result = new DataSet(); if (null != rows) { int size = rows.size(); for (int i = 0; i < size; i++) { result.add(rows.get(i)); } } int size = set.size(); for (int i = 0; i < size; i++) { DataRow item = set.getRow(i); result.add(item); } return result; } /** * * * @param row row * @param keys keys * @return return */ public boolean contains(DataRow row, String... keys) { if (null == rows || rows.size() == 0 || null == row) { return false; } if (null == keys || keys.length == 0) { keys = new String[1]; keys[0] = ConfigTable.getString("DEFAULT_PRIMARY_KEY", "ID"); } String params[] = packParam(row, keys); return exists(params); } public String[] packParam(DataRow row, String... keys) { if (null == keys || null == row) { return null; } String params[] = new String[keys.length * 2]; int idx = 0; for (String key : keys) { if (null == key) { continue; } String ks[] = BeanUtil.parseKeyValue(key); params[idx++] = ks[0]; params[idx++] = row.getString(ks[1]); } return params; } /** * kvs * ["ID","1","CODE","A01"] * @param row DataRow * @param keys ID,CODE * @return kvs */ public String[] packParam(DataRow row, List<String> keys) { if (null == keys || null == row) { return null; } String params[] = new String[keys.size() * 2]; int idx = 0; for (String key : keys) { if (null == key) { continue; } String ks[] = BeanUtil.parseKeyValue(key); params[idx++] = ks[0]; params[idx++] = row.getString(ks[1]); } return params; } /** * itemskey * dispatch("children",items, "DEPAT_CD") * dispatchs("children",items, "CD:BASE_CD") * * @param field "ITEMS" * @param unique () * @param recursion * @param items items * @param keys keys ID:DEPT_IDID * @return return */ public DataSet dispatchs(String field, boolean unique, boolean recursion, DataSet items, String... keys) { if(null == keys || keys.length == 0){ throw new RuntimeException(""); } if (null == items) { return this; } if (BasicUtil.isEmpty(field)) { field = "ITEMS"; } for (DataRow row : rows) { if (null == row.get(field)) { String[] kvs = packParam(row, reverseKey(keys)); DataSet set = items.getRows(kvs); if (recursion) { set.dispatchs(field, unique, recursion, items, keys); } if(unique) { set.skip(true); } row.put(field, set); } } items.skip(false); return this; } public DataSet dispatchs(boolean unique, boolean recursion, DataSet items, String... keys) { return dispatchs("ITEMS", unique, recursion, items, keys); } public DataSet dispatchs(String field, DataSet items, String... keys) { return dispatchs(field,false, false, items, keys); } public DataSet dispatchs(DataSet items, String... keys) { return dispatchs("ITEMS", items, keys); } public DataSet dispatchs(boolean unique, boolean recursion, String... keys) { return dispatchs("ITEMS", unique, recursion, this, keys); } public DataSet dispatchs(String field, boolean unique, boolean recursion, String... keys) { return dispatchs(field, unique, recursion, this, keys); } public DataSet dispatch(String field, boolean unique, boolean recursion, DataSet items, String... keys) { if(null == keys || keys.length == 0){ throw new RuntimeException(""); } if (null == items) { return this; } if (BasicUtil.isEmpty(field)) { field = "ITEM"; } for (DataRow row : rows) { if (null == row.get(field)) { String[] params = packParam(row, reverseKey(keys)); DataRow result = items.getRow(params); if(unique){ result.skip = true; } row.put(field, result); } } items.skip(false); return this; } public DataSet dispatch(String field, DataSet items, String... keys) { return dispatch(field, false, false, items, keys); } public DataSet dispatch(DataSet items, String... keys) { return dispatch("ITEM", items, keys); } public DataSet dispatch(boolean unique, boolean recursion, String... keys) { return dispatch("ITEM", unique, recursion, this, keys); } public DataSet dispatch(String field, boolean unique, boolean recursion, String... keys) { return dispatch(field, unique, recursion, this, keys); } /** * dispatchs * @param field "ITEMS" * @param unique () * @param recursion * @param items items * @param keys keys ID:DEPT_IDID * @return return */ @Deprecated public DataSet dispatchItems(String field, boolean unique, boolean recursion, DataSet items, String... keys) { return dispatchs(field, unique, recursion, items, keys); } @Deprecated public DataSet dispatchItems(boolean unique, boolean recursion, DataSet items, String... keys) { return dispatchs( unique, recursion, items, keys); } @Deprecated public DataSet dispatchItems(String field, DataSet items, String... keys) { return dispatchs(field, items, keys); } @Deprecated public DataSet dispatchItems(DataSet items, String... keys) { return dispatchs(items, keys); } @Deprecated public DataSet dispatchItems(boolean unique, boolean recursion, String... keys) { return dispatchs( unique, recursion, keys); } @Deprecated public DataSet dispatchItems(String field, boolean unique, boolean recursion, String... keys) { return dispatchs(field, unique, recursion, keys); } @Deprecated public DataSet dispatchItem(String field, boolean unique, boolean recursion, DataSet items, String... keys) { return dispatch(field, unique, recursion, items, keys); } @Deprecated public DataSet dispatchItem(String field, DataSet items, String... keys) { return dispatch(field, items, keys); } @Deprecated public DataSet dispatchItem(DataSet items, String... keys) { return dispatch(items, keys); } @Deprecated public DataSet dispatchItem(boolean unique, boolean recursion, String... keys) { return dispatch(unique, recursion, keys); } @Deprecated public DataSet dispatchItem(String field, boolean unique, boolean recursion, String... keys) { return dispatch(field, unique, recursion, keys); } /** * keys * * @param items * @param keys * @return return */ public DataSet join(DataSet items, String... keys) { if (null == items || null == keys || keys.length == 0) { return this; } for (DataRow row : rows) { String[] params = packParam(row, reverseKey(keys)); DataRow result = items.getRow(params); if (null != result) { row.copy(result, result.keys()); } } return this; } public DataSet toLowerKey() { for (DataRow row : rows) { row.toLowerKey(); } return this; } public DataSet toUpperKey() { for (DataRow row : rows) { row.toUpperKey(); } return this; } /** * keys * * @param keys keys * @return return */ public DataSet group(String... keys) { DataSet result = distinct(keys); result.dispatchs(true,false, this, keys); return result; } public DataSet or(DataSet set, String... keys) { return this.union(set, keys); } public DataSet getRows(Map<String, String> kvs) { return getRows(0, -1, kvs); } /** * * * @param distinct keys * @param sets * @param keys * @return DataSet */ public static DataSet intersection(boolean distinct, List<DataSet> sets, String... keys) { DataSet result = null; if (null != sets && sets.size() > 0) { for (DataSet set : sets) { if (null == result) { result = set; } else { result = result.intersection(distinct, set, keys); } } } if (null == result) { result = new DataSet(); } return result; } public static DataSet intersection(List<DataSet> sets, String... keys) { return intersection(false, sets, keys); } /** * * * @param distinct keys(keys) * @param set set * @param keys keys"ID:USER_ID",IDDataSet,USER_IDDataSet * @return return */ public DataSet intersection(boolean distinct, DataSet set, String... keys) { DataSet result = new DataSet(); if (null == set) { return result; } for (DataRow row : rows) { String[] kv = reverseKey(keys); if (set.contains(row, kv)) { if(!result.contains(row, kv)){//result result.add((DataRow) row.clone()); }else { if(!distinct){//resultdistinct result.add((DataRow) row.clone()); } } } } return result; } public DataSet intersection(DataSet set, String... keys) { return intersection(false, set, keys); } public DataSet and(boolean distinct, DataSet set, String... keys) { return intersection(distinct, set, keys); } public DataSet and(DataSet set, String... keys) { return intersection(false, set, keys); } /** * * thisset * this set * * @param distinct keys * @param set set * @param keys keys * @return return */ public DataSet complement(boolean distinct, DataSet set, String... keys) { DataSet result = new DataSet(); for (DataRow row : rows) { String[] kv = reverseKey(keys); if (null == set || !set.contains(row, kv)) { if (!distinct || !result.contains(row, kv)) { result.add((DataRow) row.clone()); } } } return result; } public DataSet complement(DataSet set, String... keys) { return complement(false, set, keys); } /** * * setrow,DataSet * this set * * @param distinct keys * @param set set * @param keys CD,"CD:WORK_CD" * @return return */ public DataSet difference(boolean distinct, DataSet set, String... keys) { DataSet result = new DataSet(); for (DataRow row : rows) { String[] kv = reverseKey(keys); if (null == set || !set.contains(row, kv)) { if (!distinct || !result.contains(row, kv)) { result.add((DataRow) row.clone()); } } } return result; } public DataSet difference(DataSet set, String... keys) { return difference(false, set, keys); } /** * kv-vk * * @param keys kv * @return String[] */ private String[] reverseKey(String[] keys) { if (null == keys) { return new String[0]; } int size = keys.length; String result[] = new String[size]; for (int i = 0; i < size; i++) { String key = keys[i]; if (BasicUtil.isNotEmpty(key) && key.contains(":")) { String ks[] = BeanUtil.parseKeyValue(key); key = ks[1] + ":" + ks[0]; } result[i] = key; } return result; } /** * ,keys, * * @param keys keys * @return DataSet */ public DataSet removeEmptyRow(String... keys) { int size = this.size(); for (int i = size - 1; i >= 0; i DataRow row = getRow(i); if (null == keys || keys.length == 0) { if (row.isEmpty()) { this.remove(row); } } else { boolean isEmpty = true; for (String key : keys) { if (row.isNotEmpty(key)) { isEmpty = false; break; } } if (isEmpty) { this.remove(row); } } } return this; } public DataSet changeKey(String key, String target, boolean remove) { for(DataRow row:rows){ row.changeKey(key, target, remove); } return this; } public DataSet changeKey(String key, String target) { return changeKey(key, target, true); } /** * rowscolumns * * @param columns * @return DataSet */ public DataSet removeColumn(String... columns) { if (null != columns) { for (String column : columns) { for (DataRow row : rows) { row.remove(column); } } } return this; } /** * rows(null|'') * * @param columns * @return DataSet */ public DataSet removeEmptyColumn(String... columns) { for (DataRow row : rows) { row.removeEmpty(columns); } return this; } /** * NULL &gt; "" * * @return DataSet */ public DataSet nvl() { for (DataRow row : rows) { row.nvl(); } return this; } public boolean add(DataRow e) { return rows.add((DataRow) e); } @SuppressWarnings({"rawtypes", "unchecked"}) public boolean addAll(Collection c) { return rows.addAll(c); } public void clear() { rows.clear(); } public boolean contains(Object o) { return rows.contains(o); } public boolean containsAll(Collection<?> c) { return rows.containsAll(c); } public Iterator<DataRow> iterator() { return rows.iterator(); } public boolean remove(Object o) { return rows.remove(o); } public boolean removeAll(Collection<?> c) { return rows.removeAll(c); } public boolean retainAll(Collection<?> c) { return rows.retainAll(c); } public Object[] toArray() { return rows.toArray(); } @SuppressWarnings("unchecked") public Object[] toArray(Object[] a) { return rows.toArray(a); } public String getSchema() { return schema; } public DataSet setSchema(String schema) { this.schema = schema; return this; } public String getTable() { return table; } public DataSet setTable(String table) { if (null != table && table.contains(".")) { String[] tbs = table.split("\\."); this.table = tbs[1]; this.schema = tbs[0]; } else { this.table = table; } return this; } /** * * * true * * @param millisecond () millisecond () * @return boolean */ public boolean isExpire(int millisecond) { if (System.currentTimeMillis() - createTime > millisecond) { return true; } return false; } public boolean isExpire(long millisecond) { if (System.currentTimeMillis() - createTime > millisecond) { return true; } return false; } public boolean isExpire() { if (getExpires() == -1) { return false; } if (System.currentTimeMillis() - createTime > getExpires()) { return true; } return false; } public long getCreateTime() { return createTime; } public List<DataRow> getRows() { return rows; } /** * () * * @return long */ public long getExpires() { return expires; } public DataSet setExpires(long millisecond) { this.expires = millisecond; return this; } public DataSet setExpires(int millisecond) { this.expires = millisecond; return this; } public boolean isResult() { return result; } public boolean isSuccess() { return result; } public DataSet setResult(boolean result) { this.result = result; return this; } public Exception getException() { return exception; } public DataSet setException(Exception exception) { this.exception = exception; return this; } public String getMessage() { return message; } public DataSet setMessage(String message) { this.message = message; return this; } public PageNavi getNavi() { return navi; } public DataSet setNavi(PageNavi navi) { this.navi = navi; return this; } public DataSet setRows(List<DataRow> rows) { this.rows = rows; return this; } public String getDataSource() { String ds = table; if (BasicUtil.isNotEmpty(ds) && BasicUtil.isNotEmpty(schema)) { ds = schema + "." + ds; } if (BasicUtil.isEmpty(ds)) { ds = dataSource; } return ds; } public DataSet order(final String... keys) { return asc(keys); } public DataSet put(String key, Object value, boolean pk, boolean override) { for (DataRow row : rows) { row.put(key, value, pk, override); } return this; } public DataSet put(String key, Object value, boolean pk) { for (DataRow row : rows) { row.put(key, value, pk); } return this; } public DataSet put(String key, Object value) { for (DataRow row : rows) { row.put(key, value); } return this; } /** * * (, , , , , ) * @param pks key(,) * @param classKeys key(,) * @param valueKeys key(,),keyvalue * @return * key * [ * {:01,:,2010--:100}, * {:01,:,2010--:A}, * {:01,:,2010--:100} * ] * valueKey[ * {:01,:,2010-:100}, * {:01,:,2010-:90} * ] * valuekey [ * {:01,:,2010-:{:100,:A}}, * {:01,:,2010-:{:100,:A}} * ] */ public DataSet pivot(List<String> pks, List<String> classKeys, List<String> valueKeys) { DataSet result = distinct(pks); DataSet classValues = distinct(classKeys); //[{:2010,:},{:2010,:},{:2011,:}] for (DataRow row : result) { for (DataRow classValue : classValues) { DataRow params = new DataRow(); params.copy(row, pks).copy(classValue); DataRow valueRow = getRow(params); if(null != valueRow){ valueRow.skip = true; } String finalKey = concatValue(classValue,"-");//2010- if(null != valueKeys && valueKeys.size() > 0){ if(valueKeys.size() == 1){ if (null != valueRow) { row.put(finalKey, valueRow.get(valueKeys.get(0))); } else { row.put(finalKey, null); } }else { for (String valueKey : valueKeys) { //{2010--:100;2010--:A} if (null != valueRow) { row.put(finalKey + "-" + valueKey, valueRow.get(valueKey)); } else { row.put(finalKey + "-" + valueKey, null); } } } }else{ if (null != valueRow){ row.put(finalKey, valueRow); }else{ row.put(finalKey, null); } } } } skip(false); return result; } public DataSet pivot(String[] pks, String[] classKeys, String[] valueKeys) { return pivot(Arrays.asList(pks),Arrays.asList(classKeys),Arrays.asList(valueKeys)); } /** * * @param pk key()key,(,) * @param classKey key()key,(,) * @param valueKey key()key,(,) * @return * (,,) * [{:,:100,:90,:80},{:,:100,:90,:80}] */ public DataSet pivot(String pk, String classKey, String valueKey) { List<String> pks = new ArrayList<>(Arrays.asList(pk.trim().split(","))); List<String> classKeys = new ArrayList<>(Arrays.asList(classKey.trim().split(","))); List<String> valueKeys = new ArrayList<>(Arrays.asList(valueKey.trim().split(","))); return pivot(pks, classKeys, valueKeys); } public DataSet pivot(String pk, String classKey) { List<String> pks = new ArrayList<>(Arrays.asList(pk.trim().split(","))); List<String> classKeys = new ArrayList<>(Arrays.asList(classKey.trim().split(","))); List<String> valueKeys = new ArrayList<>(); return pivot(pks, classKeys, valueKeys); } public DataSet pivot(List<String> pks, List<String> classKeys, String ... valueKeys) { List<String> list = new ArrayList<>(); if(null != valueKeys){ for(String item:valueKeys){ list.add(item); } } return pivot(pks, classKeys, valueKeys); } private String concatValue(DataRow row, String split){ StringBuilder builder = new StringBuilder(); List<String> keys = row.keys(); for(String key:keys){ if(builder.length() > 0){ builder.append(split); } builder.append(row.getString(key)); } return builder.toString(); } private String[] kvs(DataRow row){ List<String> keys = row.keys(); int size = keys.size(); String[] kvs = new String[size*2]; for(int i=0; i<size; i++){ String k = keys.get(i); String v = row.getStringNvl(k); kvs[i*2] = k; kvs[i*2+1] = v; } return kvs; } /** * * * @param keys keys * @return DataSet */ public DataSet asc(final String... keys) { Collections.sort(rows, new Comparator<DataRow>() { public int compare(DataRow r1, DataRow r2) { int result = 0; for (String key : keys) { Object v1 = r1.get(key); Object v2 = r2.get(key); if (null == v1) { if (null == v2) { continue; } return -1; } else { if (null == v2) { return 1; } } if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) { BigDecimal num1 = new BigDecimal(v1.toString()); BigDecimal num2 = new BigDecimal(v2.toString()); result = num1.compareTo(num2); } else if (v1 instanceof Date && v2 instanceof Date) { Date date1 = (Date)v1; Date date2 = (Date)v2; result = date1.compareTo(date2); } else { result = v1.toString().compareTo(v2.toString()); } if (result != 0) { return result; } } return 0; } }); isAsc = true; isDesc = false; return this; } public DataSet desc(final String... keys) { Collections.sort(rows, new Comparator<DataRow>() { public int compare(DataRow r1, DataRow r2) { int result = 0; for (String key : keys) { Object v1 = r1.get(key); Object v2 = r2.get(key); if (null == v1) { if (null == v2) { continue; } return 1; } else { if (null == v2) { return -1; } } if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) { BigDecimal val1 = new BigDecimal(v1.toString()); BigDecimal val2 = new BigDecimal(v2.toString()); result = val2.compareTo(val1); } else if (v1 instanceof Date && v2 instanceof Date) { Date date1 = (Date)v1; Date date2 = (Date)v2; result = date2.compareTo(date1); } else { result = v2.toString().compareTo(v1.toString()); } if (result != 0) { return result; } } return 0; } }); isAsc = false; isDesc = true; return this; } public DataSet addAllUpdateColumns() { for (DataRow row : rows) { row.addAllUpdateColumns(); } return this; } public DataSet clearUpdateColumns() { for (DataRow row : rows) { row.clearUpdateColumns(); } return this; } public DataSet removeNull(String... keys) { for (DataRow row : rows) { row.removeNull(keys); } return this; } private static String key(String key) { if (null != key && ConfigTable.IS_UPPER_KEY) { key = key.toUpperCase(); } return key; } /** * NULL * * @param value value * @return return */ public DataSet replaceNull(String value) { for (DataRow row : rows) { row.replaceNull(value); } return this; } /** * * * @param value value * @return return */ public DataSet replaceEmpty(String value) { for (DataRow row : rows) { row.replaceEmpty(value); } return this; } /** * NULL * * @param key key * @param value value * @return return */ public DataSet replaceNull(String key, String value) { for (DataRow row : rows) { row.replaceNull(key, value); } return this; } /** * * * @param key key * @param value value * @return return */ public DataSet replaceEmpty(String key, String value) { for (DataRow row : rows) { row.replaceEmpty(key, value); } return this; } public DataSet replace(String key, String oldChar, String newChar) { if (null == key || null == oldChar || null == newChar) { return this; } for (DataRow row : rows) { row.replace(key, oldChar, newChar); } return this; } public DataSet replace(String oldChar, String newChar) { for (DataRow row : rows) { row.replace(oldChar, newChar); } return this; } /** * * @return DataRow */ public DataRow random() { DataRow row = null; int size = size(); if (size > 0) { row = getRow(BasicUtil.getRandomNumber(0, size - 1)); } return row; } /** * qty * @param qty * @return DataSet */ public DataSet randoms(int qty) { DataSet set = new DataSet(); int size = size(); if (qty < 0) { qty = 0; } if (qty > size) { qty = size; } for (int i = 0; i < qty; i++) { while (true) { int idx = BasicUtil.getRandomNumber(0, size - 1); DataRow row = set.getRow(idx); if (!set.contains(row)) { set.add(row); break; } } } set.cloneProperty(this); return set; } /** * minmax * @param min min * @param max max * @return DataSet */ public DataSet randoms(int min, int max) { int qty = BasicUtil.getRandomNumber(min, max); return randoms(qty); } public DataSet unique(String... keys) { return distinct(keys); } /** * * @param key key * @param regex * @param mode * @return DataSet */ public DataSet regex(String key, String regex, Regular.MATCH_MODE mode) { DataSet set = new DataSet(); String tmpValue; for (DataRow row : this) { tmpValue = row.getString(key); if (RegularUtil.match(tmpValue, regex, mode)) { set.add(row); } } set.cloneProperty(this); return set; } public DataSet regex(String key, String regex) { return regex(key, regex, Regular.MATCH_MODE.MATCH); } public boolean checkRequired(String... keys) { for (DataRow row : rows) { if (!row.checkRequired(keys)) { return false; } } return true; } public Map<String, Object> getQueryParams() { return queryParams; } public DataSet setQueryParams(Map<String, Object> params) { this.queryParams = params; return this; } public Object getQueryParam(String key) { return queryParams.get(key); } public DataSet addQueryParam(String key, Object param) { queryParams.put(key, param); return this; } public String getDatalink() { return datalink; } public void setDatalink(String datalink) { this.datalink = datalink; } public class Select implements Serializable { private static final long serialVersionUID = 1L; private boolean ignoreCase = true; /** * NULL true equal notEqual like contains nullnullfalse * NULLfalse * true equal notEqual */ private boolean ignoreNull = true; public DataSet setIgnoreCase(boolean bol) { this.ignoreCase = bol; return DataSet.this; } public DataSet setIgnoreNull(boolean bol) { this.ignoreNull = bol; return DataSet.this; } /** * key=value * * @param key key * @param value value * @return DataSet */ public DataSet equals(String key, String value) { return equals(DataSet.this, key, value); } private DataSet equals(DataSet src, String key, String value) { DataSet set = new DataSet(); String tmpValue; for (DataRow row : src) { tmpValue = row.getString(key); if (ignoreNull) { if (null == tmpValue || null == value) { continue; } } else { if (null == tmpValue && null == value) { set.add(row); continue; } } if (null != tmpValue) { boolean chk = false; if (ignoreCase) { chk = tmpValue.equalsIgnoreCase(value); } else { chk = tmpValue.equals(value); } if (chk) { set.add(row); } } } set.cloneProperty(src); return set; } /** * key = value * * @param key key * @param value value * @return DataSet */ public DataSet notEquals(String key, String value) { return notEquals(DataSet.this, key, value); } private DataSet notEquals(DataSet src, String key, String value) { DataSet set = new DataSet(); String tmpValue; for (DataRow row : src) { tmpValue = row.getString(key); if (ignoreNull) { if (null == tmpValue || null == value) { continue; } } else { if (null == tmpValue && null == value) { set.add(row); continue; } } if (null != tmpValue) { boolean chk = false; if (ignoreCase) { chk = !tmpValue.equalsIgnoreCase(value); } else { chk = !tmpValue.equals(value); } if (chk) { set.add(row); } } } set.cloneProperty(src); return set; } /** * keyvalue * * @param key key * @param value value * @return DataSet */ public DataSet contains(String key, String value) { return contains(DataSet.this, key, value); } private DataSet contains(DataSet src, String key, String value) { DataSet set = new DataSet(); String tmpValue; for (DataRow row : src) { tmpValue = row.getString(key); if (ignoreNull) { if (null == tmpValue || null == value) { continue; } } else { if (null == tmpValue && null == value) { set.add(row); continue; } } if (null != tmpValue) { if (null == value) { continue; } if (ignoreCase) { tmpValue = tmpValue.toLowerCase(); value = value.toLowerCase(); } if (tmpValue.contains(value)) { set.add(row); } } } set.cloneProperty(src); return set; } /** * keylike pattern,patternsql,%,_ * * @param key * @param pattern * @return DataSet */ public DataSet like(String key, String pattern) { return like(DataSet.this, key, pattern); } private DataSet like(DataSet src, String key, String pattern) { DataSet set = new DataSet(); if (null != pattern) { pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*"); } String tmpValue; for (DataRow row : src) { tmpValue = row.getString(key); if (ignoreNull) { if (null == tmpValue || null == pattern) { continue; } } else { if (null == tmpValue && null == pattern) { set.add(row); continue; } } if (null != tmpValue) { if (null == pattern) { continue; } if (ignoreCase) { tmpValue = tmpValue.toLowerCase(); pattern = pattern.toLowerCase(); } if (RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) { set.add(row); } } } set.cloneProperty(src); return set; } public DataSet notLike(String key, String pattern) { return notLike(DataSet.this, key, pattern); } private DataSet notLike(DataSet src, String key, String pattern) { DataSet set = new DataSet(); if (null == pattern) { return set; } pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*"); String tmpValue; for (DataRow row : src) { tmpValue = row.getString(key); if (ignoreNull) { if (null == tmpValue || null == pattern) { continue; } } else { if (null == tmpValue && null == pattern) { set.add(row); continue; } } if (null != tmpValue) { if (null == pattern) { continue; } if (ignoreCase) { tmpValue = tmpValue.toLowerCase(); pattern = pattern.toLowerCase(); } if (!RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) { set.add(row); } } } set.cloneProperty(src); return set; } public DataSet startWith(String key, String prefix) { return startWith(DataSet.this, key, prefix); } private DataSet startWith(DataSet src, String key, String prefix) { DataSet set = new DataSet(); String tmpValue; for (DataRow row : src) { tmpValue = row.getString(key); if (ignoreNull) { if (null == tmpValue || null == prefix) { continue; } } else { if (null == tmpValue && null == prefix) { set.add(row); continue; } } if (null != tmpValue) { if (null == prefix) { continue; } if (ignoreCase) { tmpValue = tmpValue.toLowerCase(); prefix = prefix.toLowerCase(); } if (tmpValue.startsWith(prefix)) { set.add(row); } } } set.cloneProperty(src); return set; } public DataSet endWith(String key, String suffix) { return endWith(DataSet.this, key, suffix); } private DataSet endWith(DataSet src, String key, String suffix) { DataSet set = new DataSet(); String tmpValue; for (DataRow row : src) { tmpValue = row.getString(key); if (ignoreNull) { if (null == tmpValue || null == suffix) { continue; } } else { if (null == tmpValue && null == suffix) { set.add(row); continue; } } if (null != tmpValue) { if (null == suffix) { continue; } if (ignoreCase) { tmpValue = tmpValue.toLowerCase(); suffix = suffix.toLowerCase(); } if (tmpValue.endsWith(suffix)) { set.add(row); } } } set.cloneProperty(src); return set; } public <T> DataSet in(String key, T... values) { return in(DataSet.this, key, BeanUtil.array2list(values)); } public <T> DataSet in(String key, Collection<T> values) { return in(DataSet.this, key, values); } private <T> DataSet in(DataSet src, String key, Collection<T> values) { DataSet set = new DataSet(); for (DataRow row : src) { if (BasicUtil.containsString(ignoreNull, ignoreCase, values, row.getString(key))) { set.add(row); } } set.cloneProperty(src); return set; } public <T> DataSet notIn(String key, T... values) { return notIn(DataSet.this, key, BeanUtil.array2list(values)); } public <T> DataSet notIn(String key, Collection<T> values) { return notIn(DataSet.this, key, values); } private <T> DataSet notIn(DataSet src, String key, Collection<T> values) { DataSet set = new DataSet(); if (null != values) { String tmpValue = null; for (DataRow row : src) { tmpValue = row.getString(key); if (ignoreNull && null == tmpValue) { continue; } if (!BasicUtil.containsString(ignoreNull, ignoreCase, values, tmpValue)) { set.add(row); } } } set.cloneProperty(src); return set; } public DataSet isNull(String... keys) { return isNull(DataSet.this, keys); } private DataSet isNull(DataSet src, String... keys) { DataSet set = src; if (null != keys) { for (String key : keys) { set = isNull(set, key); } } return set; } private DataSet isNull(DataSet src, String key) { DataSet set = new DataSet(); for(DataRow row:src){ if(null == row.get(key)){ set.add(row); } } return set; } public DataSet isNotNull(String... keys) { return isNotNull(DataSet.this, keys); } private DataSet isNotNull(DataSet src, String... keys) { DataSet set = src; if (null != keys) { for (String key : keys) { set = isNotNull(set, key); } } return set; } private DataSet isNotNull(DataSet src, String key) { DataSet set = new DataSet(); for(DataRow row:src){ if(null != row.get(key)){ set.add(row); } } return set; } public DataSet notNull(String... keys) { return isNotNull(keys); } public DataSet isEmpty(String... keys) { return isEmpty(DataSet.this, keys); } private DataSet isEmpty(DataSet src, String... keys) { DataSet set = src; if (null != keys) { for (String key : keys) { set = isEmpty(set, key); } } return set; } private DataSet isEmpty(DataSet src, String key) { DataSet set = new DataSet(); for(DataRow row:src){ if(row.isEmpty(key)){ set.add(row); } } return set; } public DataSet empty(String... keys) { return isEmpty(keys); } public DataSet isNotEmpty(String... keys) { return isNotEmpty(DataSet.this, keys); } private DataSet isNotEmpty(DataSet src, String... keys) { DataSet set = src; if (null != keys) { for (String key : keys) { set = isNotEmpty(set, key); } } return set; } private DataSet isNotEmpty(DataSet src, String key) { DataSet set = new DataSet(); for(DataRow row:src){ if(row.isNotEmpty(key)){ set.add(row); } } return set; } public DataSet notEmpty(String... keys) { return isNotEmpty(keys); } public <T> DataSet less(String key, T value) { return less(DataSet.this, key, value); } private <T> DataSet less(DataSet src, String key, T value) { DataSet set = new DataSet(); if (null == value) { return set; } if (BasicUtil.isNumber(value)) { BigDecimal number = new BigDecimal(value.toString()); for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.getDecimal(key, 0).compareTo(number) < 0) { set.add(row); } } } else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) { Date date = DateUtil.parse(value.toString()); for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.isNotEmpty(key) && DateUtil.diff(DateUtil.<API key>, date, row.getDate(key, new Date())) < 0) { set.add(row); } } } else { for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.getString(key).compareTo(value.toString()) < 0) { set.add(row); } } } set.cloneProperty(src); return set; } public <T> DataSet lessEqual(String key, T value) { return lessEqual(DataSet.this, key, value); } private <T> DataSet lessEqual(DataSet src, String key, T value) { DataSet set = new DataSet(); if (null == value) { return set; } if (BasicUtil.isNumber(value)) { BigDecimal number = new BigDecimal(value.toString()); for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.getDecimal(key, 0).compareTo(number) <= 0) { set.add(row); } } } else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) { Date date = DateUtil.parse(value.toString()); for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.isNotEmpty(key) && DateUtil.diff(DateUtil.<API key>, date, row.getDate(key, new Date())) <= 0) { set.add(row); } } } else { for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.getString(key).compareTo(value.toString()) >= 0) { set.add(row); } } } set.cloneProperty(src); return set; } public <T> DataSet greater(String key, T value) { return greater(DataSet.this, key, value); } private <T> DataSet greater(DataSet src, String key, T value) { DataSet set = new DataSet(); if (null == value) { return set; } if (BasicUtil.isNumber(value)) { BigDecimal number = new BigDecimal(value.toString()); for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.getDecimal(key, 0).compareTo(number) > 0) { set.add(row); } } } else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) { Date date = DateUtil.parse(value.toString()); for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.isNotEmpty(key) && DateUtil.diff(DateUtil.<API key>, date, row.getDate(key, new Date())) > 0) { set.add(row); } } } else { for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.getString(key).compareTo(value.toString()) > 0) { set.add(row); } } } set.cloneProperty(src); return set; } public <T> DataSet greaterEqual(String key, T value) { return greaterEqual(DataSet.this, key, value); } private <T> DataSet greaterEqual(DataSet src, String key, T value) { DataSet set = new DataSet(); if (null == value) { return set; } if (BasicUtil.isNumber(value)) { BigDecimal number = new BigDecimal(value.toString()); for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.getDecimal(key, 0).compareTo(number) >= 0) { set.add(row); } } } else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) { Date date = DateUtil.parse(value.toString()); for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.isNotEmpty(key) && DateUtil.diff(DateUtil.<API key>, date, row.getDate(key, new Date())) >= 0) { set.add(row); } } } else { for (DataRow row : src) { if (null == row.get(key)) { continue; } if (row.getString(key).compareTo(value.toString()) >= 0) { set.add(row); } } } set.cloneProperty(src); return set; } public <T> DataSet between(String key, T min, T max) { return between(DataSet.this, key, min, max); } private <T> DataSet between(DataSet src, String key, T min, T max) { DataSet set = greaterEqual(src, key, min); set = lessEqual(set, key, max); return set; } } public Select select = new Select(); }
package controllers import play.api.mvc._ import securesocial.core.SecureSocial /** Controller to display the Notebook. */ object Notebook extends Controller with SecureSocial { def show = SecuredAction { implicit request => Ok(views.html.Notebook.show()) } }
package ua.job4j.loop; public class Factorial { public int calc(int n) { int result = 1; if (n != 0) { for (int i = 1; i <= n; i++) { result *= i; } } return result; } }
package com.github.binarywang.wxpay.service.impl; import com.github.binarywang.wxpay.bean.request.*; import com.github.binarywang.wxpay.bean.result.*; import com.github.binarywang.wxpay.exception.WxPayException; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.testbase.ApiTestModule; import com.google.common.base.Joiner; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Guice; import org.testng.annotations.Test; /** * @author chenliang * @date 2021-08-02 6:45 */ @Test @Guice(modules = ApiTestModule.class) public class <API key> { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Inject private WxPayService payService; @Test public void testMpSign() { String contractCode = "222200002222"; String displayAccount = Joiner.on("").join("*", "(", "10000014", ")"); WxMpEntrustRequest wxMpEntrust = WxMpEntrustRequest.newBuilder() .planId("142323") .contractCode(contractCode) .<API key>(displayAccount) .notifyUrl("http://domain.com/api/wxpay/sign/callback.do") .requestSerial(6L) //.returnWeb(1) .version("1.0") .timestamp(String.valueOf(System.currentTimeMillis() / 1000)) .outerId(displayAccount) .build(); String url = null; try { url = this.payService.<API key>().mpSign(wxMpEntrust); } catch (WxPayException e) { e.printStackTrace(); } logger.info(url); } @Test public void testMaSign() { String contractCode = "222220000022222"; String displayAccount = Joiner.on("").join("*", "(", "10000001", ")"); WxMaEntrustRequest wxMaEntrustRequest = WxMaEntrustRequest.newBuilder() .contractCode(contractCode) .<API key>(contractCode) .notifyUrl("http://domain.com/api/wxpay/sign/callback.do") .outerId(displayAccount) .planId("141535") .requestSerial(2L) .timestamp(String.valueOf(System.currentTimeMillis() / 1000)) .build(); try { String url = this.payService.<API key>().maSign(wxMaEntrustRequest); logger.info(url); } catch (WxPayException e) { e.printStackTrace(); } } @Test public void testH5Sign() { String contractCode = "222111122222"; String displayAccount = Joiner.on("").join("*", "(", "100000000", ")"); WxH5EntrustRequest wxH5EntrustRequest = WxH5EntrustRequest.newBuilder() .requestSerial(2L) .clientIp("127.0.0.1") .contractCode(contractCode) .<API key>(displayAccount) .notifyUrl("http://domain.com/api/wxpay/sign/callback.do") .planId("141535") .returnAppid("1") .timestamp(String.valueOf(System.currentTimeMillis() / 1000)) .version("1.0") .outerId(displayAccount) .build(); try { WxH5EntrustResult wxH5EntrustResult = this.payService.<API key>().h5Sign(wxH5EntrustRequest); logger.info(wxH5EntrustResult.toString()); } catch (WxPayException e) { e.printStackTrace(); } } @Test public void testPaySign() { String contractCode = "2222211110000222"; String displayAccount = Joiner.on("").join("*", "(", "10000005", ")"); String outTradeNo = "11100111101"; WxPayEntrustRequest wxPayEntrustRequest = WxPayEntrustRequest.newBuilder() .attach("local") .body("") .contractAppId(this.payService.getConfig().getAppId()) .contractCode(contractCode) .<API key>(displayAccount) .contractMchId(this.payService.getConfig().getMchId()) .contractNotifyUrl("http://domain.com/api/wxpay/sign/callback.do") .detail("") .deviceInfo("oneplus 7 pro") //.goodsTag() //.limitPay() .notifyUrl("http://domain.com/api/wxpay/pay/callback.do") .openId("<API key>") //openId .outTradeNo(outTradeNo) .planId("141535") //.productId() .requestSerial(3L) .spbillCreateIp("127.0.0.1") //.timeExpire() //.timeStart() .totalFee(1) .tradeType("MWEB") .contractOuterId(displayAccount) .build(); try { WxPayEntrustResult wxPayEntrustResult = this.payService.<API key>().paySign(wxPayEntrustRequest); logger.info(wxPayEntrustResult.toString()); } catch (WxPayException e) { e.printStackTrace(); } } @Test public void testWithhold() { String outTradeNo = "101010101"; WxWithholdRequest withholdRequest = WxWithholdRequest.newBuilder() .attach("local") .body("") .contractId("202011065409471222") .detail("") .feeType("CNY") //.goodsTag() .notifyUrl("http://domain.com/api/wxpay/withhold/callback.do") .outTradeNo(outTradeNo) .spbillCreateIp("127.0.0.1") .totalFee(1) .tradeType("PAP") .build(); try { WxWithholdResult wxWithholdResult = this.payService.<API key>().withhold(withholdRequest); logger.info(wxWithholdResult.toString()); } catch (WxPayException e) { e.printStackTrace(); } } @Test public void testPreWithhold() { <API key>.EstimateAmount estimateAmount = new <API key>.EstimateAmount(); estimateAmount.setAmount(1); estimateAmount.setCurrency("CNY"); <API key> <API key> = <API key>.newBuilder() .appId("wx73dssxxxxxx") .contractId("202010275173070001") .estimateAmount(estimateAmount) .mchId("1600010102") .build(); try { String httpResponseModel = this.payService.<API key>().preWithhold(<API key>); logger.info(httpResponseModel); } catch (WxPayException e) { e.printStackTrace(); } } @Test public void testQuerySign() { String outTradeNo = "1212121212"; WxSignQueryRequest wxSignQueryRequest = WxSignQueryRequest.newBuilder() //.contractId("202010275173073211") .contractCode(outTradeNo) .planId(1432112) .version("1.0") .build(); try { WxSignQueryResult wxSignQueryResult = this.payService.<API key>().querySign(wxSignQueryRequest); logger.info(wxSignQueryResult.toString()); } catch (WxPayException e) { logger.info(":" + e.getErrCode()); logger.info("" + e); } } @Test public void <API key>() { <API key> <API key> = <API key>.newBuilder() .contractId("202010275173070231") .<API key>("") .version("1.0") .build(); try { <API key> <API key> = this.payService.<API key>().terminationContract(<API key>); logger.info(<API key>.toString()); } catch (WxPayException e) { logger.error(e.getMessage()); } } }
package org.clinical3PO.common.security; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.<API key>; import org.springframework.security.authentication.<API key>; import org.springframework.security.authentication.Username<API key>; import org.springframework.security.core.Authentication; import org.springframework.security.core.<API key>; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Component; import org.clinical3PO.common.security.model.User; import org.clinical3PO.common.security.service.UserService; @Component public class Custom<API key> implements <API key> { @Autowired private UserService userService; @Override public Authentication authenticate(Authentication authentication) throws <API key> { String username = authentication.getName(); String password = (String) authentication.getCredentials(); User user = userService.loadUserByUsername(username); if (user == null) { throw new <API key>("Username not found."); } if (!password.equals(user.getPassword())) { throw new <API key>("Wrong password."); } Collection<? extends GrantedAuthority> authorities = user.getAuthorities(); return new Username<API key>(user, password, authorities); } @Override public boolean supports(Class<?> arg0) { return true; } }
<?php namespace NetSuite\Classes; class NSSoapFault { /** * @var \NetSuite\Classes\FaultCodeType */ public $code; /** * @var string */ public $message; static $paramtypesmap = array( "code" => "FaultCodeType", "message" => "string", ); }
package com.example.mywechat.utils; import java.util.ArrayList; import java.util.List; import android.app.Activity; public class ActivityCollector { public static List<Activity> activities=new ArrayList<Activity>(); public static void addActivity(Activity activity){ activities.add(activity); } public static void removeActivity(Activity activity){ activities.remove(activity); } public static void finishAll(){ for(Activity activity:activities){ if(!activity.isFinishing()){ activity.finish(); } } } public ActivityCollector() { } }
package com.seamusdawkins.tablayout.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import com.seamusdawkins.tablayout.R; public class FirstFragment extends Fragment { TextView tv; RelativeLayout rl; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_one, container, false); tv = (TextView) rootView.findViewById(R.id.action); tv.setText(R.string.str_first); return rootView; } }
<font class='sw'>Connexion ($var['msize'] bytes).</font>
package seborama.demo2.kafka.model; import com.fasterxml.jackson.annotation.<API key>; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_EMPTY) @<API key>(ignoreUnknown = true) public class Order { private String id; private boolean fulfilled; private boolean dispatched; private boolean completed; public void setId(String id) { this.id = id; } public void setFulfilled(Boolean fulfilled) { this.fulfilled = fulfilled; } public void setDispatched(Boolean dispatched) { this.dispatched = dispatched; } public void setCompleted(Boolean completed) { this.completed = completed; } public String getId() { return id; } public Boolean getFulfilled() { return fulfilled; } public Boolean getDispatched() { return dispatched; } public Boolean getCompleted() { return completed; } @Override public String toString() { return "Order{" + "id='" + id + '\'' + ", fulfilled=" + fulfilled + ", dispatched=" + dispatched + ", completed=" + completed + '}'; } }
public class ChickenBurger extends Burger { @Override public float price() { return 50.5f; } @Override public String name() { return "Chicken Burger"; } }
package org.jnosql.artemis.column.query; import org.jnosql.artemis.CDIExtension; import org.jnosql.artemis.model.Person; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.inject.Inject; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; @ExtendWith(CDIExtension.class) public class <API key> { @Inject private <API key> mapperBuilder; @Test public void <API key>() { assertThrows(<API key>.class, () -> mapperBuilder.selectFrom(null)); } @Test public void <API key>() { ColumnMapperFrom columnFrom = mapperBuilder.selectFrom(Person.class); assertNotNull(columnFrom); } @Test public void <API key>() { assertThrows(<API key>.class, () -> mapperBuilder.deleteFrom(null)); } @Test public void <API key>() { <API key> columnDeleteFrom = mapperBuilder.deleteFrom(Person.class); assertNotNull(columnDeleteFrom); } }
/* tslint:disable:<API key> */ import { forEach } from 'ramda'; import Interactor from '../CourseInteractor'; import InteractorLoader from '../<API key>'; import { ICourseStorage } from '../ICourseStorage'; import { IProgressStorage } from '../IProgressStorage'; import { ISerializedCourse } from '../ISerializedCourse'; import { ISerializedProgress, Progress } from '../ISerializedProgress'; const courses: { [propName: string]: ISerializedCourse } = { '<API key>': { id: '<API key>', title: 'Foo bar', children: [ { id: '<API key>', children: [ { id: '<API key>', type: 'foo' } ] }, { id: '<API key>', children: [ { id: '<API key>', foo: 'bar', type: 'foo' } ] } ] } }; const progresses: ISerializedProgress = {}; class MockCourseStorage implements ICourseStorage { public getCourse(id: string) { return new Promise<ISerializedCourse>((resolve, reject) => { if (courses[id]) { resolve(courses[id]); } reject(new Error(`There exists no course with id ${id}`)); }); } } class MockProgressStorage implements IProgressStorage { public getProgress(id: string) { return Promise.resolve(progresses); } public setProgress(id: string, progress: ISerializedProgress): Promise<void> { return Promise.resolve(); } public resetProgress() { return Promise.resolve(); } } let interactorLoader: InteractorLoader; let interactor: Interactor; beforeEach(() => { const storage = new MockCourseStorage(); const progress = new MockProgressStorage(); interactorLoader = new InteractorLoader(storage, progress); }); it('loadCourse loads the course from storage if it exists', () => interactorLoader.loadCourse('<API key>')); it('loadCourse fails if the course does not exist', () => { return interactorLoader .loadCourse('<API key>') .catch(err => { expect(err).toBeInstanceOf(Error); }); }); describe('getStructure', () => { beforeEach(() => interactorLoader .loadCourse('<API key>') .then(i => { interactor = i; }) ); it('returns the whole tree by default', () => { expect(interactor.getStructure()).toMatchSnapshot(); }); it('returns only the first levels if a level is passed', () => { expect(interactor.getStructure(1)).toMatchSnapshot(); }); }); describe('reset children progress', () => { beforeEach(() => interactorLoader .loadCourse('<API key>') .then(i => { interactor = i; }) ); it('resets progress correctly', () => { const root = '<API key>'; const children = [ '<API key>', '<API key>', '<API key>', '<API key>' ]; forEach( id => { interactor.markAsCorrect(id); }, [root, ...children] ); interactor.<API key>(root); expect(interactor.getProgress(root).progress).toBe(Progress.Correct); forEach(id => { expect(interactor.getProgress(id).progress).toBe(Progress.Unseen); }, children); }); });
import React from 'react'; import { action } from '@storybook/addon-actions'; import { Action } from '../Actions'; import ActionBar from './ActionBar.component'; const primary = { label: 'Primary', icon: 'talend-cog', bsStyle: 'primary', 'data-feature': 'actionbar.primary', onClick: action('You clicked me'), }; const actions = { left: [ primary, { label: 'Secondary1', icon: 'talend-cog', 'data-feature': 'actionbar.secondary', onClick: action('You clicked me'), }, { displayMode: ActionBar.DISPLAY_MODES.SPLIT_DROPDOWN, label: 'Secondary3', icon: 'talend-cog', 'data-feature': 'actionbar.splitdropdown', onClick: action('on split button click'), items: [ { label: 'From Local', 'data-feature': 'actionbar.splitdropdown.items', onClick: action('From Local click'), }, { label: 'From Remote', 'data-feature': 'actionbar.splitdropdown.items', onClick: action('From Remote click'), }, ], emptyDropdownLabel: 'No option', }, { id: 'dropdown', displayMode: ActionBar.DISPLAY_MODES.DROPDOWN, label: 'Dropdown', icon: 'talend-cog', items: [ { label: 'From Local', onClick: action('From Local click'), }, { label: 'From Remote', onClick: action('From Remote click'), }, ], }, ], right: [ { label: 'Secondary4', icon: 'talend-upload', displayMode: 'file', onChange: action('You changed me'), }, { label: 'Secondary5', icon: 'talend-cog', onClick: action('You clicked me'), }, ], }; const multi3 = { label: 'multi3', icon: 'talend-cog', onClick: action('You clicked me'), }; const multiSelectActions = { left: [ { label: 'multi1', icon: 'talend-cog', onClick: action('You clicked me'), }, { label: 'multi2', icon: 'talend-cog', onClick: action('You clicked me'), }, ], center: [ { label: 'multi5', icon: 'talend-cog', onClick: action('You clicked me'), }, ], right: [ multi3, { label: 'multi4', icon: 'talend-cog', onClick: action('You clicked me'), }, ], }; const btnGroupActions = { left: [ { displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP, actions: [ { label: 'hidden mean tooltips', icon: 'talend-cog', hideLabel: true, onClick: action('cog'), }, { label: 'you are a super star', icon: 'talend-badge', hideLabel: true, onClick: action('badge'), }, { label: 'but don t click this', icon: 'talend-cross', hideLabel: true, onClick: action('boom'), }, { label: 'edit me', icon: 'talend-pencil', hideLabel: true, onClick: action('oh yes'), }, ], }, { displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP, actions: [ { label: 'you can also add', icon: 'talend-plus-circle', hideLabel: true, onClick: action('add !'), }, { label: 'search', icon: 'talend-search', hideLabel: true, onClick: action('search'), }, { label: 'star', icon: 'talend-star', hideLabel: true, onClick: action('star'), }, ], }, ], center: [ { displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP, actions: [ { label: 'go to dataprep', icon: 'talend-dataprep', hideLabel: true, onClick: action('dataprep'), }, { label: 'go to elastic', icon: 'talend-elastic', hideLabel: true, onClick: action('elastic'), }, { label: 'go to cloud engine', icon: 'talend-cloud-engine', hideLabel: true, onClick: action('cloud-engine'), }, ], }, ], right: [ { displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP, actions: [ { label: 'table', icon: 'talend-table', hideLabel: true, onClick: action('table'), }, { label: 'trash', icon: 'talend-trash', hideLabel: true, onClick: action('trash'), }, ], }, ], }; const basicProps = { actions, multiSelectActions, }; const multiDelete = { label: 'Delete', icon: 'talend-trash', onClick: action('multiple delete'), className: 'btn-icon-text', }; const multiDuplicate = { label: 'Duplicate', icon: 'talend-files-o', onClick: action('multiple duplicate'), className: 'btn-icon-text', }; const multiUpdate = { label: 'Update', icon: 'talend-file-move', onClick: action('multiple update'), className: 'btn-icon-text', }; const multiFavorite = { label: 'Favorite', icon: 'talend-star', onClick: action('multiple favorite'), className: 'btn-icon-text', }; const multiCertify = { label: 'Certify', icon: 'talend-badge', onClick: action('multiple certify'), className: 'btn-icon-text', }; const massActions = { left: [multiDelete, multiDuplicate, multiUpdate], }; const appMassActions = { left: [multiFavorite, multiCertify], }; export default { title: 'Form/Controls/ActionBar', }; export const Default = () => ( <nav> <p>No Selected, Layout: Left Space Right</p> <div id="default"> <ActionBar {...basicProps} selected={0} /> </div> <p>1 Selected, Layout: Left Center Right</p> <div id="selected"> <ActionBar {...basicProps} selected={1} /> </div> <p>1 Selected, Layout: Right</p> <div id="right"> <ActionBar selected={1} actions={{ left: [primary] }} multiSelectActions={{ right: [multi3] }} /> </div> <p>Toolbar with btn-group and only icons/ Layout: left, center, right</p> <div id="btn-group"> <ActionBar actions={btnGroupActions} /> </div> <p>3 items selected, with mass/bulk Actions</p> <div id="mass-actions"> <ActionBar selected={3} multiSelectActions={massActions} <API key>={appMassActions} /> </div> </nav> ); export const Custom = () => ( <nav> <div id="default"> <ActionBar> <ActionBar.Content tag="a" left href="#/foo/bar"> Hello anchor </ActionBar.Content> <ActionBar.Content tag="button" className="btn btn-default" left> Hello button </ActionBar.Content> <ActionBar.Content left> <Action label="hello Action" icon="talend-trash" onClick={action('onClick')} /> </ActionBar.Content> <ActionBar.Content tag="form" role="search" center> <div className="form-group"> <input type="text" className="form-control" placeholder="Search" /> </div> <button type="submit" className="btn btn-default"> Submit </button> </ActionBar.Content> <ActionBar.Content tag="p" right> Hello paragraph </ActionBar.Content> </ActionBar> </div> </nav> );
import hashlib from core.analytics import InlineAnalytics from core.observables import Hash HASH_TYPES_DICT = { "md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512, } class HashFile(InlineAnalytics): default_values = { "name": "HashFile", "description": "Extracts MD5, SHA1, SHA256, SHA512 hashes from file", } ACTS_ON = ["File", "Certificate"] @staticmethod def each(f): if f.body: f.hashes = [] for hash_type, h in HashFile.extract_hashes(f.body.contents): hash_object = Hash.get_or_create(value=h.hexdigest()) hash_object.add_source("analytics") hash_object.save() f.active_link_to( hash_object, "{} hash".format(hash_type.upper()), "HashFile", clean_old=False, ) f.hashes.append({"hash": hash_type, "value": h.hexdigest()}) f.save() @staticmethod def extract_hashes(body_contents): hashers = {k: HASH_TYPES_DICT[k]() for k in HASH_TYPES_DICT} while True: chunk = body_contents.read(512 * 16) if not chunk: break for h in hashers.values(): h.update(chunk) return hashers.items()
package org.jruby.ext.ffi.jna; import java.util.ArrayList; import org.jruby.runtime.ThreadContext; /** * An invocation session. * This provides post-invoke cleanup. */ final class Invocation { private final ThreadContext context; private ArrayList<Runnable> postInvokeList; Invocation(ThreadContext context) { this.context = context; } void finish() { if (postInvokeList != null) { for (Runnable r : postInvokeList) { r.run(); } } } void addPostInvoke(Runnable postInvoke) { if (postInvokeList == null) { postInvokeList = new ArrayList<Runnable>(); } postInvokeList.add(postInvoke); } ThreadContext getThreadContext() { return context; } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_75) on Tue May 19 17:12:39 PDT 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>org.apache.hadoop.registry.client.impl.zk (Apache Hadoop Main 2.6.0-cdh5.4.2 API)</title> <meta name="date" content="2015-05-19"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../../../../org/apache/hadoop/registry/client/impl/zk/package-summary.html" target="classFrame">org.apache.hadoop.registry.client.impl.zk</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="<API key>.html" title="interface in org.apache.hadoop.registry.client.impl.zk" target="classFrame"><i><API key></i></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="BindingInformation.html" title="class in org.apache.hadoop.registry.client.impl.zk" target="classFrame">BindingInformation</a></li> <li><a href="<API key>.html" title="class in org.apache.hadoop.registry.client.impl.zk" target="classFrame"><API key></a></li> </ul> </div> </body> </html>
package lists class OrderedTest(val value: String) extends Ordered[OrderedTest] { override def compare(that: OrderedTest): Int = { value.compareToIgnoreCase(that.value) } override def toString = value } object Test extends App { val test1 = List(0, 1, 2, 3, 4, 5, 6, 7) val test1concat = List(8, 9, 10) val test2 = List("Foo", "Bar") val test2concat = List("Baz") val test3 = List(new OrderedTest("a"), new OrderedTest("C"), new OrderedTest("B")) println(length(test1)) println(concat(test1, test1concat)) println(length(test2)) println(concat(test2, test2concat)) println(last(test1)) println(init(test1)) println(tail(test2concat)) println(head(test1)) println(reverse(concat(test1, test1concat))) println(reverse(reverse(test1)) == test1) println(take(test1, 3)) println(drop(test1, 3)) println(apply(test1, 3)) println(splitAt(test1, length(test1) / 2)) println(flatten(List(test1, test1concat))) println(flatten(List(test2, test2concat))) val normalOrderMerge = mergeSort[Int](_ < _)_ val normalOrderInsert = insertSort[Int](_ < _)_ val reverseOrderMerge = mergeSort[Int](_ > _)_ val reverseOrderInsert = insertSort[Int](_ > _)_ val stringSortMerge = mergeSort[String](_ < _)_ val stringSortInsert = insertSort[String](_ < _)_ println(stringSortMerge(concat(test2concat, test2))) println(stringSortInsert(concat(test2concat, test2))) println(normalOrderMerge(concat(reverse(test1), test1concat))) println(normalOrderInsert(concat(reverse(test1), test1concat))) println(reverseOrderMerge(test1)) println(reverseOrderInsert(test1)) println(normalOrderMerge(reverseOrderMerge(test1))) println(normalOrderInsert(reverseOrderInsert(test1))) println(orderedMergeSort(test3)) }
package org.onetwo.ext.security.utils; import java.util.Collection; import org.onetwo.common.web.userdetails.UserDetail; import org.onetwo.common.web.userdetails.UserRoot; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; @SuppressWarnings("serial") public class LoginUserDetails extends User implements UserDetail, /*SsoTokenable,*/ UserRoot { final private long userId; // private String token; private String nickname; private String avatar; public LoginUserDetails(long userId, String username, String password, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); this.userId = userId; } public long getUserId() { return userId; } @Override public String getUserName() { return getUsername(); } @Override public boolean isSystemRootUser() { return userId==ROOT_USER_ID; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } /*public String getToken() { return token; } public void setToken(String token) { this.token = token; }*/ }
/* <samplecode> <abstract> A DSPKernel subclass implementing the realtime signal processing portion of the FilterDemo audio unit. </abstract> </samplecode> */ #ifndef FilterDSPKernel_hpp #define FilterDSPKernel_hpp #import "DSPKernel.hpp" #import "ParameterRamper.hpp" #import <vector> static inline float <API key>(float x) { /* Eliminate denormals, not-a-numbers, and infinities. Denormals will fail the first test (absx > 1e-15), infinities will fail the second test (absx < 1e15), and NaNs will fail both tests. Zero will also fail both tests, but since it will get set to zero that is OK. */ float absx = fabs(x); if (absx > 1e-15 && absx < 1e15) { return x; } return 0.0; } enum { FilterParamCutoff = 0, <API key> = 1 }; static inline double squared(double x) { return x * x; } /* FilterDSPKernel Performs our filter signal processing. As a non-ObjC class, this is safe to use from render thread. */ class FilterDSPKernel : public DSPKernel { public: // MARK: Types struct FilterState { float x1 = 0.0; float x2 = 0.0; float y1 = 0.0; float y2 = 0.0; void clear() { x1 = 0.0; x2 = 0.0; y1 = 0.0; y2 = 0.0; } void <API key>() { /* These filters work by feedback. If an infinity or NaN should come into the filter input, the feedback variables can become infinity or NaN which will cause the filter to stop operating. This function clears out any bad numbers in the feedback variables. */ x1 = <API key>(x1); x2 = <API key>(x2); y1 = <API key>(y1); y2 = <API key>(y2); } }; struct BiquadCoefficients { float a1 = 0.0; float a2 = 0.0; float b0 = 0.0; float b1 = 0.0; float b2 = 0.0; void <API key>(double frequency, double resonance) { /* The transcendental function calls here could be replaced with interpolated table lookups or other approximations. */ // Convert from decibels to linear. double r = pow(10.0, 0.05 * -resonance); double k = 0.5 * r * sin(M_PI * frequency); double c1 = (1.0 - k) / (1.0 + k); double c2 = (1.0 + c1) * cos(M_PI * frequency); double c3 = (1.0 + c1 - c2) * 0.25; b0 = float(c3); b1 = float(2.0 * c3); b2 = float(c3); a1 = float(-c2); a2 = float(c1); } // Arguments in Hertz. double <API key>( double inFreq) { // Cast to Double. double _b0 = double(b0); double _b1 = double(b1); double _b2 = double(b2); double _a1 = double(a1); double _a2 = double(a2); // Frequency on unit circle in z-plane. double zReal = cos(M_PI * inFreq); double zImaginary = sin(M_PI * inFreq); // Zeros response. double numeratorReal = (_b0 * (squared(zReal) - squared(zImaginary))) + (_b1 * zReal) + _b2; double numeratorImaginary = (2.0 * _b0 * zReal * zImaginary) + (_b1 * zImaginary); double numeratorMagnitude = sqrt(squared(numeratorReal) + squared(numeratorImaginary)); // Poles response. double denominatorReal = squared(zReal) - squared(zImaginary) + (_a1 * zReal) + _a2; double <API key> = (2.0 * zReal * zImaginary) + (_a1 * zImaginary); double <API key> = sqrt(squared(denominatorReal) + squared(<API key>)); // Total response. double response = numeratorMagnitude / <API key>; return response; } }; // MARK: Member Functions FilterDSPKernel() {} void init(int channelCount, double inSampleRate) { channelStates.resize(channelCount); sampleRate = float(inSampleRate); nyquist = 0.5 * sampleRate; inverseNyquist = 1.0 / nyquist; <API key> = (AUAudioFrameCount)floor(0.02 * sampleRate); cutoffRamper.init(); resonanceRamper.init(); } void reset() { cutoffRamper.reset(); resonanceRamper.reset(); for (FilterState& state : channelStates) { state.clear(); } } void setParameter(AUParameterAddress address, AUValue value) { switch (address) { case FilterParamCutoff: //cutoffRamper.setUIValue(clamp(value * inverseNyquist, 0.0f, 0.99f)); cutoffRamper.setUIValue(clamp(value * inverseNyquist, 0.0005444f, 0.9070295f)); break; case <API key>: resonanceRamper.setUIValue(clamp(value, -20.0f, 20.0f)); break; } } AUValue getParameter(AUParameterAddress address) { switch (address) { case FilterParamCutoff: // Return the goal. It is not thread safe to return the ramping value. //return (cutoffRamper.getUIValue() * nyquist); return roundf((cutoffRamper.getUIValue() * nyquist) * 100) / 100; case <API key>: return resonanceRamper.getUIValue(); default: return 12.0f * inverseNyquist; } } void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override { switch (address) { case FilterParamCutoff: cutoffRamper.startRamp(clamp(value * inverseNyquist, 12.0f * inverseNyquist, 0.99f), duration); break; case <API key>: resonanceRamper.startRamp(clamp(value, -20.0f, 20.0f), duration); break; } } void setBuffers(AudioBufferList* inBufferList, AudioBufferList* outBufferList) { inBufferListPtr = inBufferList; outBufferListPtr = outBufferList; } void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override { int channelCount = int(channelStates.size()); cutoffRamper.dezipperCheck(<API key>); resonanceRamper.dezipperCheck(<API key>); // For each sample. for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { /* The filter coefficients are updated every sample! This is very expensive. You probably want to do things differently. */ double cutoff = double(cutoffRamper.getAndStep()); double resonance = double(resonanceRamper.getAndStep()); coeffs.<API key>(cutoff, resonance); int frameOffset = int(frameIndex + bufferOffset); for (int channel = 0; channel < channelCount; ++channel) { FilterState& state = channelStates[channel]; float* in = (float*)inBufferListPtr->mBuffers[channel].mData + frameOffset; float* out = (float*)outBufferListPtr->mBuffers[channel].mData + frameOffset; float x0 = *in; float y0 = (coeffs.b0 * x0) + (coeffs.b1 * state.x1) + (coeffs.b2 * state.x2) - (coeffs.a1 * state.y1) - (coeffs.a2 * state.y2); *out = y0; state.x2 = state.x1; state.x1 = x0; state.y2 = state.y1; state.y1 = y0; } } // Squelch any blowups once per cycle. for (int channel = 0; channel < channelCount; ++channel) { channelStates[channel].<API key>(); } } // MARK: Member Variables private: std::vector<FilterState> channelStates; BiquadCoefficients coeffs; float sampleRate = 44100.0; float nyquist = 0.5 * sampleRate; float inverseNyquist = 1.0 / nyquist; AUAudioFrameCount <API key>; AudioBufferList* inBufferListPtr = nullptr; AudioBufferList* outBufferListPtr = nullptr; public: // Parameters. ParameterRamper cutoffRamper = 400.0 / 44100.0; ParameterRamper resonanceRamper = 20.0; }; #endif /* FilterDSPKernel_hpp */
// import { Domain } from '../Domain'; // import { GetDomain } from './GetDomain'; // /** // * Find domain from object or type // */ // export function FindDomain(target: Function | object): Domain | undefined { // let prototype; // prototype = target.prototype; // } else { // prototype = target; // while (prototype) { // const domain = GetDomain(prototype); // if (domain) { // // console.log('FOUND'); // return domain; // // console.log('NOT FOUND!!!'); // prototype = Reflect.getPrototypeOf(prototype); // return;
package acceptance; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import utils.CommandStatus; import utils.<API key>; import java.nio.file.Path; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static utils.TestUtils.copyResource; import static utils.TestUtils.main; // This file doesn't contain normal case. // It defined in another test. public class ValidateProjectIT { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Rule public <API key> server = <API key>.builder() .build(); private Path config; private Path projectDir; @Before public void setUp() throws Exception { projectDir = folder.getRoot().toPath().resolve("foobar"); config = folder.newFile().toPath(); } @Test public void <API key>() throws Exception { // Create new project CommandStatus initStatus = main("init", "-c", config.toString(), projectDir.toString()); assertThat(initStatus.code(), is(0)); copyResource("acceptance/error_task/invalid_at_group.dig", projectDir.resolve("invalid_at_group.dig")); // Push the project CommandStatus pushStatus = main( "push", "--project", projectDir.toString(), "foobar", "-c", config.toString(), "-e", server.endpoint()); assertThat(pushStatus.code(), is(1)); assertThat(pushStatus.errUtf8(), containsString("A task can't have more than one operator")); } @Test public void <API key>() throws Exception { // Create new project CommandStatus initStatus = main("init", "-c", config.toString(), projectDir.toString()); assertThat(initStatus.code(), is(0)); copyResource("acceptance/schedule/invalid_schedule.dig", projectDir.resolve("invalid_schedule.dig")); // Push the project CommandStatus pushStatus = main( "push", "--project", projectDir.toString(), "foobar", "-c", config.toString(), "-e", server.endpoint()); assertThat(pushStatus.code(), is(1)); assertThat(pushStatus.errUtf8(), containsString("scheduler requires mm:ss format")); } }
package io.strimzi.api.kafka.model.connect.build; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.strimzi.api.kafka.model.<API key>; import io.strimzi.crdgenerator.annotations.Description; import lombok.EqualsAndHashCode; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Abstract baseclass for different representations of connect build outputs, discriminated by {@link #getType() type}. */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type" ) @JsonSubTypes( { @JsonSubTypes.Type(value = DockerOutput.class, name = Output.TYPE_DOCKER), @JsonSubTypes.Type(value = ImageStreamOutput.class, name = Output.TYPE_IMAGESTREAM) } ) @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode public abstract class Output implements <API key>, Serializable { private static final long serialVersionUID = 1L; public static final String TYPE_DOCKER = "docker"; public static final String TYPE_IMAGESTREAM = "imagestream"; private String image; private Map<String, Object> <API key> = new HashMap<>(0); @Description("Output type. " + "Must be either `docker` for pushing the newly build image to Docker compatible registry or `imagestream` for pushing the image to OpenShift ImageStream. " + "Required.") public abstract String getType(); @Description("The name of the image which will be built. " + "Required") @JsonProperty(required = true) public String getImage() { return image; } public void setImage(String image) { this.image = image; } @Override public Map<String, Object> <API key>() { return this.<API key>; } @Override public void <API key>(String name, Object value) { this.<API key>.put(name, value); } }
package com.transcend.rds.worker; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.hibernate.Session; import org.slf4j.Logger; import org.springframework.transaction.annotation.Transactional; import com.msi.tough.cf.json.DatabagParameter; import com.msi.tough.core.Appctx; import com.msi.tough.core.HibernateUtil; import com.msi.tough.core.JsonUtil; import com.msi.tough.model.AccountBean; import com.msi.tough.model.rds.RdsDbinstance; import com.msi.tough.model.rds.RdsDbparameterGroup; import com.msi.tough.model.rds.RdsParameter; import com.msi.tough.query.ErrorResponse; import com.msi.tough.query.QueryFaults; import com.msi.tough.query.<API key>; import com.msi.tough.rds.ValidationManager; import com.msi.tough.rds.json.<API key>; import com.msi.tough.rds.json.RDSDatabag; import com.msi.tough.rds.json.<API key>; import com.msi.tough.utils.AccountUtil; import com.msi.tough.utils.ChefUtil; import com.msi.tough.utils.ConfigurationUtil; import com.msi.tough.utils.Constants; import com.msi.tough.utils.RDSQueryFaults; import com.msi.tough.utils.rds.InstanceEntity; import com.msi.tough.utils.rds.<API key>; import com.msi.tough.utils.rds.RDSUtilities; import com.msi.tough.workflow.core.AbstractWorker; import com.transcend.rds.message.<API key>.<API key>; import com.transcend.rds.message.<API key>.<API key>; import com.transcend.rds.message.RDSMessage.Parameter; /** * @author tdhite */ public class <API key> extends AbstractWorker<<API key>, <API key>> { private final static Logger logger = Appctx .getLogger(<API key>.class.getName()); /** * We need a local copy of this doWork to provide the transactional * annotation. Transaction management is handled by the annotation, which * can only be on a concrete class. * @param req * @return * @throws Exception */ @Transactional public <API key> doWork( <API key> req) throws Exception { logger.debug("Performing work for <API key>."); return super.doWork(req, getSession()); } @Override protected <API key> doWork0(<API key> req, <API key> context) throws Exception { logger.debug("<API key> action is called."); final Session sess = HibernateUtil.newSession(); final AccountBean ac = context.getAccountBean(); final <API key>.Builder resp = <API key>.newBuilder(); try { sess.beginTransaction(); final long userId = ac.getId(); final String grpName = ValidationManager.validateIdentifier( req.<API key>(), 255, true); final List<Parameter> pList = req.getParametersList(); final int pListLen = pList.size(); logger.info("<API key>: " + " UserID = " + userId + " ParameterGroupName = " + grpName + " Total Number of Listed Parameters = " + pListLen); if (grpName.equals("default.mysql5.5")) { throw RDSQueryFaults .<API key>("You do not have privilege to modify default DBParameterGroup."); } // check that DBParameterGroup exists final RdsDbparameterGroup pGrpRec = <API key> .getParameterGroup(sess, grpName, ac.getId()); if (pGrpRec == null) { throw RDSQueryFaults.<API key>(); } final Collection<RdsDbinstance> dbInstances = InstanceEntity .<API key>(sess, grpName, -1, ac); // make sure that all DBInstances using this DBParameterGroup are in // available state for (final RdsDbinstance dbinstance : dbInstances) { if (!dbinstance.getDbinstanceStatus().equals( RDSUtilities.STATUS_AVAILABLE)) { throw RDSQueryFaults .<API key>("Currently there are DBInstance(s) that use this DBParameterGroup and it" + " is not in available state."); } } // reset the parameters in the DB List<RdsParameter> forRebootPending = new LinkedList<RdsParameter>(); final String paramGrpFamily = pGrpRec.<API key>(); final AccountBean sac = AccountUtil.readAccount(sess, 1L); for (final Parameter p : pList) { final RdsParameter target = <API key>.getParameter( sess, grpName, p.getParameterName(), userId); if (target == null) { throw RDSQueryFaults.<API key>(p .getParameterName() + " parameter does not exist."); } logger.debug("Current target parameter: " + target.toString()); if (!target.getIsModifiable()) { throw RDSQueryFaults.<API key>(p .getParameterName() + " is not modifiable parameter."); } // TODO validate p.getParameterValue along with // p.getParameterName to ensure the value is allowed else if (p.getApplyMethod().equals( RDSUtilities.<API key>)) { if (target.getApplyType().equals( RDSUtilities.PARM_APPTYPE_STATIC)) { throw QueryFaults .<API key>(target .getParameterName() + " is not dynamic. You can only" + " use \"pending-reboot\" as valid ApplyMethod for this parameter."); } target.setParameterValue(p.getParameterValue()); target.setSource(Constants.USER); sess.save(target); } else if (p.getApplyMethod().equals( RDSUtilities.<API key>)) { final RdsParameter temp = new RdsParameter(); temp.setParameterName(p.getParameterName()); temp.setApplyMethod(p.getApplyMethod()); temp.setParameterValue(p.getParameterValue()); forRebootPending.add(temp); } } // Delete and regenerate the Databag logger.debug("There are " + dbInstances.size() + " databags to modify."); for (final RdsDbinstance instance : dbInstances) { logger.debug("Currently updating the databag for DBInstance " + instance.getDbinstanceId()); final String databagName = "rds-" + ac.getId() + "-" + instance.getDbinstanceId(); logger.debug("Deleting the databag " + databagName); ChefUtil.deleteDatabagItem(databagName, "config"); final String postWaitUrl = (String) ConfigurationUtil .getConfiguration(Arrays.asList(new String[] { "TRANSCEND_URL", instance.getAvailabilityZone() })); final String servletUrl = (String) ConfigurationUtil .getConfiguration(Arrays.asList(new String[] { "SERVLET_URL", instance.getAvailabilityZone() })); final <API key> configDataBagItem = new <API key>( "config", instance.getAllocatedStorage().toString(), instance.getMasterUsername(), instance.<API key>(), instance.<API key>(), instance.getEngine(), instance.getEngineVersion(), instance.getDbName(), instance .<API key>().toString(), instance.<API key>(), instance.<API key>(), instance .getPort().toString(), postWaitUrl, servletUrl, instance.getDbinstanceId(), "rds." + ac.getId() + "." + instance.getDbinstanceId(), ac.getId(), instance.getDbinstanceClass(), "false"); final <API key> <API key> = new <API key>( "parameters", pGrpRec); <API key>.getParameters().remove("read_only"); <API key>.getParameters().put( "read_only", DatabagParameter.factory("boolean", "" + instance.getRead_only(), true, "dynamic")); <API key>.getParameters().remove("port"); <API key>.getParameters().put( "port", DatabagParameter.factory("integer", "" + instance.getPort(), false, "static")); final RDSDatabag bag = new RDSDatabag(configDataBagItem, <API key>); logger.debug("Databag: " + JsonUtil.<API key>(bag)); logger.debug("Regenerating the databag " + databagName); ChefUtil.createDatabagItem(databagName, "config", bag.toJson()); } if (forRebootPending != null && forRebootPending.size() > 0) { // forRebootPending is now a list of static parameters and // dynamic parameters with pending-reboot ApplyMethod forRebootPending = <API key> .<API key>(sess, pGrpRec, forRebootPending, userId); // code below may need to be rewritten for better performance; // Hibernate may be useful to improve the snippet below for (final RdsDbinstance instance : dbInstances) { final List<RdsParameter> alreadyPending = instance .<API key>(); if (alreadyPending == null || alreadyPending.size() == 0) { instance.<API key>(forRebootPending); // instance.setDbinstanceStatus(RDSUtilities.STATUS_MODIFYING); sess.save(instance); } else { for (final RdsParameter newParam : forRebootPending) { boolean found = false; int i = 0; while (!found && i < alreadyPending.size()) { if (alreadyPending.get(i).getParameterName() .equals(newParam.getParameterName())) { alreadyPending.get(i).setParameterValue( newParam.getParameterValue()); found = true; } ++i; } if (!found) { alreadyPending.add(newParam); } } } } } // build response document - returns <API key> resp.<API key>(grpName); logger.debug("Committing all the changes..."); sess.getTransaction().commit(); } catch (final ErrorResponse rde) { sess.getTransaction().rollback(); throw rde; } catch (final Exception e) { e.printStackTrace(); sess.getTransaction().rollback(); final String msg = "CreateInstance: Class: " + e.getClass() + "Msg:" + e.getMessage(); logger.error(msg); throw RDSQueryFaults.InternalFailure(); } finally { sess.close(); } return resp.buildPartial(); } }
class PagosController < <API key> before_action :set_pago, only: [:show, :edit, :update, :destroy] # GET /pagos # GET /pagos.json def index @pagos = Pago.all end # GET /pagos/1 # GET /pagos/1.json def show end # GET /pagos/new def new @pago = Pago.new end # GET /pagos/1/edit def edit end # POST /pagos # POST /pagos.json def create @pago = Pago.new(pago_params) respond_to do |format| if @pago.save format.html { redirect_to @pago, notice: 'Pago añadido' } format.json { render :show, status: :created, location: @pago } else format.html { render :new } format.json { render json: @pago.errors, status: :<API key> } end end end # PATCH/PUT /pagos/1 # PATCH/PUT /pagos/1.json def update respond_to do |format| if @pago.update(pago_params) format.html { redirect_to @pago, notice: 'Pago actualizado' } format.json { render :show, status: :ok, location: @pago } else format.html { render :edit } format.json { render json: @pago.errors, status: :<API key> } end end end # DELETE /pagos/1 # DELETE /pagos/1.json def destroy @pago.destroy respond_to do |format| format.html { redirect_to pagos_url, notice: 'Pago eliminado' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_pago @pago = Pago.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def pago_params params.require(:pago).permit(:cliente_id,:<API key>, :pagado, :fecha_pago, :ano,:dominio_nombre ,:dominio_anual ,:hosting_mes ,:hosting_anual, :total, :comentarios) end end
/** Automatically generated file. DO NOT MODIFY */ package com.example.android_servicetest; public final class BuildConfig { public final static boolean DEBUG = true; }
#include "inter_vn_stats.h" #include <oper/interface.h> #include <oper/mirror_table.h> using namespace std; <API key>::VnStatsSet *<API key>::Find(string vn) { VnStatsMap::iterator it = inter_vn_stats_.find(vn); if (it != inter_vn_stats_.end()) { return it->second; } return NULL; } void <API key>::PrintAll() { VnStatsMap::iterator it = inter_vn_stats_.begin(); while(it != inter_vn_stats_.end()) { PrintVn(it->first); it++; } } void <API key>::PrintVn(string vn) { VnStatsSet *stats_set; VnStats *stats; LOG(DEBUG, "...........Stats for Vn " << vn); VnStatsMap::iterator it = inter_vn_stats_.find(vn); if (it != inter_vn_stats_.end()) { stats_set = it->second; /* Remove all the elements of map entry value which is a set */ VnStatsSet::iterator stats_it = stats_set->begin(); while(stats_it != stats_set->end()) { stats = *stats_it; stats_it++; LOG(DEBUG, " Other-VN " << stats->dst_vn); LOG(DEBUG, " in_pkts " << stats->in_pkts << " in_bytes " << stats->in_bytes); LOG(DEBUG, " out_pkts " << stats->out_pkts << " out_bytes " << stats->out_bytes); } } } void <API key>::Remove(string vn) { VnStatsSet *stats_set; VnStats *stats; VnStatsMap::iterator it = inter_vn_stats_.find(vn); if (it != inter_vn_stats_.end()) { stats_set = it->second; /* Remove the entry from the inter_vn_stats_ map */ inter_vn_stats_.erase(it); /* Remove all the elements of map entry value which is a set */ VnStatsSet::iterator stats_it = stats_set->begin(); VnStatsSet::iterator del_it; while(stats_it != stats_set->end()) { stats = *stats_it; delete stats; del_it = stats_it; stats_it++; stats_set->erase(del_it); } delete stats_set; } } void <API key>::UpdateVnStats(FlowEntry *fe, uint64_t bytes, uint64_t pkts) { string src_vn = fe->data.source_vn, dst_vn = fe->data.dest_vn; if (!fe->data.source_vn.length()) src_vn = *FlowHandler::UnknownVn(); if (!fe->data.dest_vn.length()) dst_vn = *FlowHandler::UnknownVn(); if (fe->local_flow) { <API key>(src_vn, dst_vn, bytes, pkts, true); <API key>(dst_vn, src_vn, bytes, pkts, false); } else { if (fe->data.ingress) { <API key>(src_vn, dst_vn, bytes, pkts, true); } else { <API key>(dst_vn, src_vn, bytes, pkts, false); } } //PrintAll(); } void <API key>::<API key>(string src_vn, string dst_vn, uint64_t bytes, uint64_t pkts, bool outgoing) { VnStatsSet *stats_set; VnStats *stats; VnStatsMap::iterator it = inter_vn_stats_.find(src_vn); if (it == inter_vn_stats_.end()) { stats = new VnStats(dst_vn, bytes, pkts, outgoing); stats_set = new VnStatsSet; stats_set->insert(stats); inter_vn_stats_.insert(make_pair(src_vn, stats_set)); } else { stats_set = it->second; VnStats key(dst_vn, 0, 0, false); VnStatsSet::iterator stats_it = stats_set->find(&key); if (stats_it == stats_set->end()) { stats = new VnStats(dst_vn, bytes, pkts, outgoing); stats_set->insert(stats); } else { stats = *stats_it; if (outgoing) { stats->out_bytes += bytes; stats->out_pkts += pkts; } else { stats->in_bytes += bytes; stats->in_pkts += pkts; } } } }
import zerorpc import gevent.queue import logging import sys logging.basicConfig() # root logger logger = logging.getLogger() # set the mimimum level for root logger so it will be possible for a client # to subscribe and receive logs for any log level logger.setLevel(0) class QueueingLogHandler(logging.Handler): """ A simple logging handler which puts all emitted logs into a gevent queue. """ def __init__(self, queue, level, formatter): super(QueueingLogHandler, self).__init__() self._queue = queue self.setLevel(level) self.setFormatter(formatter) def emit(self, record): msg = self.format(record) self._queue.put_nowait(msg) def close(self): super(QueueingLogHandler, self).close() self._queue.put_nowait(None) @property def emitted(self): return self._queue class TestService(object): _HANDLER_CLASS = QueueingLogHandler _DEFAULT_FORMAT = '%(name)s - %(levelname)s - %(asctime)s - %(message)s' logger = logging.getLogger("service") def __init__(self): self._logging_handlers = set() def test(self, logger_name, logger_level, message): logger = logging.getLogger(logger_name) getattr(logger, logger_level.lower())(message) def available_loggers(self): """ List of initalized loggers """ return logging.getLogger().manager.loggerDict.keys() def close_log_streams(self): """ Closes all log_stream streams. """ while self._logging_handlers: self._logging_handlers.pop().close() @zerorpc.stream def log_stream(self, logger_name, level_name, format_str): """ Attaches a log handler to the specified logger and sends emitted logs back as stream. """ if logger_name != "" and logger_name not in self.available_loggers(): raise ValueError("logger {0} is not available".format(logger_name)) level_name_upper = level_name.upper() if level_name else "NOTSET" try: level = getattr(logging, level_name_upper) except AttributeError, e: raise AttributeError("log level {0} is not available".format(level_name_upper)) q = gevent.queue.Queue() fmt = format_str if format_str.strip() else self._DEFAULT_FORMAT logger = logging.getLogger(logger_name) formatter = logging.Formatter(fmt) handler = self._HANDLER_CLASS(q, level, formatter) logger.addHandler(handler) self._logging_handlers.add(handler) self.logger.debug("new subscriber for {0}/{1}".format(logger_name or "root", level_name_upper)) try: for msg in handler.emitted: if msg is None: return yield msg finally: self._logging_handlers.discard(handler) handler.close() self.logger.debug("subscription finished for {0}/{1}".format(logger_name or "root", level_name_upper)) if __name__ == "__main__": service = TestService() server = zerorpc.Server(service) server.bind(sys.argv[1]) logger.warning("starting service") try: server.run() except BaseException, e: logger.error(str(e)) finally: logger.warning("shutting down")
<?php declare(strict_types=1); namespace DaPigGuy\PiggyCustomEnchants\enchants\armor\chestplate; use DaPigGuy\PiggyCustomEnchants\enchants\CustomEnchant; use DaPigGuy\PiggyCustomEnchants\enchants\<API key>; use DaPigGuy\PiggyCustomEnchants\enchants\traits\TickingTrait; use pocketmine\entity\effect\EffectInstance; use pocketmine\entity\effect\VanillaEffects; use pocketmine\inventory\Inventory; use pocketmine\item\Item; use pocketmine\player\Player; class ProwlEnchant extends <API key> { use TickingTrait; public string $name = "Prowl"; public int $maxLevel = 1; public int $usageType = CustomEnchant::TYPE_CHESTPLATE; public int $itemType = CustomEnchant::<API key>; /** @var bool[] */ public array $prowled; public function toggle(Player $player, Item $item, Inventory $inventory, int $slot, int $level, bool $toggle): void { if (!$toggle && isset($this->prowled[$player->getName()])) { foreach ($player->getServer()->getOnlinePlayers() as $p) { $p->showPlayer($player); } $player->getEffects()->remove(VanillaEffects::SLOWNESS()); if (!$player->getEffects()->has(VanillaEffects::INVISIBILITY())) { $player->setInvisible(false); } unset($this->prowled[$player->getName()]); } } public function tick(Player $player, Item $item, Inventory $inventory, int $slot, int $level): void { if ($player->isSneaking()) { foreach ($player->getServer()->getOnlinePlayers() as $p) { $p->hidePlayer($player); } $effect = new EffectInstance(VanillaEffects::SLOWNESS(), 2147483647, 0, false); $player->setInvisible(); $player->getEffects()->add($effect); $this->prowled[$player->getName()] = true; } else { if (isset($this->prowled[$player->getName()])) { foreach ($player->getServer()->getOnlinePlayers() as $p) { $p->showPlayer($player); } $player->getEffects()->remove(VanillaEffects::SLOWNESS()); if (!$player->getEffects()->has(VanillaEffects::INVISIBILITY())) { $player->setInvisible(false); } unset($this->prowled[$player->getName()]); } } } }
# AUTOGENERATED FILE FROM balenalib/edge-ubuntu:xenial-build # remove several traces of debian python RUN apt-get purge -y python.* # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.6.15 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.3.1 ENV SETUPTOOLS_VERSION 60.5.4 RUN set -x \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" \ && echo "<SHA256-like> Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/<SHA1-like>/get-pip.py" \ && echo "<SHA256-like> get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install --no-cache-dir virtualenv ENV PYTHON_DBUS_VERSION 1.2.18 # install dbus-python dependencies RUN apt-get update && apt-get install -y --<API key> \ libdbus-1-dev \ libdbus-glib-1-dev \
package org.artifactory.ui.rest.resource.home; import org.artifactory.api.security.<API key>; import org.artifactory.ui.rest.resource.BaseResource; import org.artifactory.ui.rest.service.general.<API key>; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * @author Chen keinan */ @Path("home") @RolesAllowed({<API key>.ROLE_ADMIN, <API key>.ROLE_USER}) @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class HomeResource extends BaseResource { @Autowired <API key> generalFactory; @GET @Produces(MediaType.APPLICATION_JSON) public Response getHomeData() throws Exception { return runService(generalFactory.getHomePage()); } }
using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Castleroid.NPCs { public class ai8 : ModNPC { public override void SetDefaults() { npc.name = "ai8"; npc.displayName = "ai8"; npc.width = 28; npc.height = 20; npc.damage = 2; npc.defense = 0; npc.lifeMax = 2; npc.soundHit = 1; npc.soundKilled = 16; npc.value = 60f; npc.knockBackResist = 0.0f; npc.aiStyle = 8; Main.npcFrameCount[npc.type] = Main.npcFrameCount[NPCID.CyanBeetle]; aiType = NPCID.CyanBeetle; animationType = NPCID.CyanBeetle; npc.noGravity = false; npc.noTileCollide = true; } public override void HitEffect(int hitDirection, double damage) { for (int i = 0; i < 10; i++) { int dustType = Main.rand.Next(139, 143); int dustIndex = Dust.NewDust(npc.position, npc.width, npc.height, dustType); Dust dust = Main.dust[dustIndex]; dust.velocity.X = dust.velocity.X + Main.rand.Next(-50, 51) * 0.01f; dust.velocity.Y = dust.velocity.Y + Main.rand.Next(-50, 51) * 0.01f; dust.scale *= 1f + Main.rand.Next(-30, 31) * 0.01f; } } } }
class <API key> < ActiveRecord::Migration[6.0] def change add_column :versions, :resource_id, :integer add_column :versions, :resource_type, :string add_index :versions, [:resource_type, :resource_id] end end
package org.drools.persistence; import javax.transaction.xa.XAResource; public interface PersistenceManager { XAResource getXAResource(); Transaction getTransaction(); void save(); void load(); }
package com.coolweather.android; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.preference.PreferenceManager; import android.support.v4.view.GravityCompat; import android.support.v4.view.ScrollingView; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.coolweather.android.gson.Forecast; import com.coolweather.android.gson.Weather; import com.coolweather.android.service.AutoUpdateService; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class WeatherActivity extends AppCompatActivity { private ScrollView weatherLayout; private TextView titleCity; private TextView titleUpdateTime; private TextView degreeText; private TextView weatherInfoText; private LinearLayout forecastLayout; private TextView aqiText; private TextView pm25Text; private TextView comfortText; private TextView carWashText; private TextView sportText; private ImageView bingPicImg; public SwipeRefreshLayout swipeRefreshLayout; private String mWeatherId; public DrawerLayout drawerLayout; private Button navButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); decorView.<API key>(View.<API key> | View.<API key>); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_weather); weatherLayout = (ScrollView) findViewById(R.id.weather_layout); titleCity = (TextView) findViewById(R.id.title_city); titleUpdateTime = (TextView) findViewById(R.id.title_update_time); degreeText = (TextView) findViewById(R.id.degree_text); weatherInfoText = (TextView) findViewById(R.id.weather_info_text); forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout); aqiText = (TextView) findViewById(R.id.aqi_text); pm25Text = (TextView) findViewById(R.id.pm25_text); comfortText = (TextView) findViewById(R.id.comfort_text); carWashText = (TextView) findViewById(R.id.car_wash_text); sportText = (TextView) findViewById(R.id.sport_text); bingPicImg = (ImageView) findViewById(R.id.bing_pic_img); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); navButton = (Button) findViewById(R.id.nav_button); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); swipeRefreshLayout.<API key>(R.color.colorTopic); SharedPreferences prefs = PreferenceManager.<API key>(this); String weatherString = prefs.getString("weather", null); if (weatherString != null) { Weather weather = Utility.<API key>(weatherString); mWeatherId = weather.basic.weatherId; showWeatherInfo(weather); } else { mWeatherId = getIntent().getStringExtra("weather_id"); String weatherId = getIntent().getStringExtra("weather_id"); weatherLayout.setVisibility(View.INVISIBLE); requestWeather(weatherId); } navButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawerLayout.openDrawer(GravityCompat.START); } }); swipeRefreshLayout.<API key>(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { requestWeather(mWeatherId); } }); String bingPic = prefs.getString("bing_pic", null); if (bingPic != null) { Glide.with(this).load(bingPic).into(bingPicImg); } else { loadBingPic(); } } public void requestWeather(final String weatherId) { String weatherUtl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=<API key>"; HttpUtil.sendOkHttpRequest(weatherUtl, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WeatherActivity.this, "", Toast.LENGTH_SHORT).show(); swipeRefreshLayout.setRefreshing(false); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String responseText = response.body().string(); final Weather weather = Utility.<API key>(responseText); runOnUiThread(new Runnable() { @Override public void run() { if (weather != null && "ok".equals(weather.status)) { SharedPreferences.Editor editor = PreferenceManager .<API key>(WeatherActivity.this).edit(); editor.putString("weather", responseText); editor.apply(); Toast.makeText(WeatherActivity.this, "", Toast.LENGTH_SHORT).show(); showWeatherInfo(weather); } else { Toast.makeText(WeatherActivity.this, "", Toast.LENGTH_SHORT).show(); } swipeRefreshLayout.setRefreshing(false); } }); } }); loadBingPic(); } private void loadBingPic() { String requestBingPic = "http://guolin.tech/api/bing_pic"; HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { final String bingPic = response.body().string(); SharedPreferences.Editor editor = PreferenceManager.<API key>(WeatherActivity.this).edit(); editor.putString("bing_pic", bingPic); editor.apply(); runOnUiThread(new Runnable() { @Override public void run() { Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg); } }); } }); } /** * Weather */ private void showWeatherInfo(Weather weather) { String cityName = weather.basic.cityName; String updateTime = ": " + weather.basic.update.updateTime.split(" ")[1]; String degree = weather.now.temperature + "ºC"; String weatherInfo = weather.now.more.info; titleCity.setText(cityName); titleUpdateTime.setText(updateTime); degreeText.setText(degree); weatherInfoText.setText(weatherInfo); forecastLayout.removeAllViews(); for (Forecast forecast : weather.forecastList) { View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false); TextView dateText = (TextView) view.findViewById(R.id.date_text); TextView infoText = (TextView) view.findViewById(R.id.info_text); TextView maxText = (TextView) view.findViewById(R.id.max_text); TextView minText = (TextView) view.findViewById(R.id.min_text); dateText.setText(forecast.date); infoText.setText(forecast.more.info); maxText.setText(forecast.temperature.max); minText.setText(forecast.temperature.min); forecastLayout.addView(view); } if (weather.aqi != null) { aqiText.setText(weather.aqi.city.aqi); pm25Text.setText(weather.aqi.city.pm25); } String comfort = "" + weather.suggestion.comfort.info; String catWash = "" + weather.suggestion.carWash.info; String sport = "" + weather.suggestion.sport.info; comfortText.setText(comfort); carWashText.setText(catWash); sportText.setText(sport); weatherLayout.setVisibility(View.VISIBLE); if (weather != null && "ok".equals(weather.status)) { Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } else { Toast.makeText(WeatherActivity.this, "", Toast.LENGTH_SHORT).show(); } } }
package com.example.cdm.huntfun.activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.<API key>; import android.support.v4.view.ViewPager.<API key>; import android.widget.TextView; import com.example.cdm.huntfun.R; import com.example.cdm.huntfun.photoView.ImageDetailFragment; import com.example.cdm.huntfun.widget.HackyViewPager; import java.util.List; public class ImagePagerActivity extends FragmentActivity { private static final String STATE_POSITION = "STATE_POSITION"; public static final String EXTRA_IMAGE_INDEX = "image_index"; public static final String EXTRA_IMAGE_URLS = "image_urls"; private HackyViewPager mPager; private int pagerPosition; private TextView indicator; // public static Drawable DEFAULTDRAWABLE; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.<API key>); // DEFAULTDRAWABLE=this.getResources().getDrawable(R.drawable.<API key>); pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0); List<String> urls = getIntent().<API key>(EXTRA_IMAGE_URLS); mPager = (HackyViewPager) findViewById(R.id.pager); ImagePagerAdapter mAdapter = new ImagePagerAdapter(<API key>(), urls); mPager.setAdapter(mAdapter); indicator = (TextView) findViewById(R.id.indicator); CharSequence text = getString(R.string.<API key>, 1, mPager.getAdapter().getCount()); indicator.setText(text); mPager.<API key>(new <API key>() { @Override public void <API key>(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int arg0) { CharSequence text = getString(R.string.<API key>, arg0 + 1, mPager.getAdapter().getCount()); indicator.setText(text); } }); if (savedInstanceState != null) { pagerPosition = savedInstanceState.getInt(STATE_POSITION); } mPager.setCurrentItem(pagerPosition); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(STATE_POSITION, mPager.getCurrentItem()); } private class ImagePagerAdapter extends <API key> { public List<String> fileList; public ImagePagerAdapter(FragmentManager fm, List<String> fileList) { super(fm); this.fileList = fileList; } @Override public int getCount() { return fileList == null ? 0 : fileList.size(); } @Override public Fragment getItem(int position) { String url = fileList.get(position); return ImageDetailFragment.newInstance(url); } } }
package net.sf.mmm.util.version.impl; import net.sf.mmm.util.version.api.DevelopmentPhase; import net.sf.mmm.util.version.api.VersionIdentifier; /** * This is the implementation of {@link net.sf.mmm.util.lang.api.Formatter} for the {@link DevelopmentPhase#getValue() * value} of the {@link VersionIdentifier#getPhase() phase}. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 3.0.0 */ public class <API key> extends <API key> { /** * The constructor. * * @param prefix is the static prefix to append before the {@link VersionIdentifier#getPhase() phase}. Will be omitted * if {@link VersionIdentifier#getPhase() phase} is {@code null}. * @param maximumLength is the maximum number of letters for the {@link VersionIdentifier#getPhase() phase}. The * default is {@link Integer#MAX_VALUE}. */ public <API key>(String prefix, int maximumLength) { super(prefix, maximumLength); } @Override protected String getString(VersionIdentifier value) { DevelopmentPhase phase = value.getPhase(); if (phase != null) { return phase.getValue(); } return null; } }
package Escape; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Insets; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import Escape.Controller.Controller; import Escape.Model.Arena; import Escape.Service.Service; import Escape.View.Rank; import Escape.View.View; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.IOException; import java.io.InputStream; import java.util.logging.LogManager; /** * The main class of the program. */ public class Escape extends JFrame { static { InputStream in = Escape.class.getResourceAsStream("/logging.properties"); if (in != null) { try { LogManager.getLogManager().readConfiguration(in); } catch(IOException e) { e.printStackTrace(); } } } /** * The <code>serialVersionUID</code> of the class. */ private static final long serialVersionUID = -<API key>; /** * The main JPanel of the <code>frame</code>. */ private JPanel contentPane; /** * The main <code>Arena</code> object of the program. */ private Arena arena; /** * Part of the Game tab, the main <code>View</code> object. */ private View view; /** * The main <code>Controller</code> object of the program. */ private Controller control; /** * Part of the Rank tab, the main <code>Rank</code> object. */ private Rank rank; /** * The name of the player. * Default is "Guest". */ private String username = "Guest"; /** * The password for the database. */ private String DAOpassword = "pwd"; /** * Main method of the program. * Creates the main JFrame object and asks the user to set <code>DAOpassword</code> * and <code>username</code> before start the game. * * @param args command-line parameters */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Escape frame = new Escape(); frame.setVisible(true); do{ frame.DAOpassword = JOptionPane.showInputDialog(frame, "Enter password for database!"); } while(frame.DAOpassword.equals("pwd")); do{ frame.username = JOptionPane.showInputDialog(frame, "Enter your in-game name!"); } while(frame.username.equals("") || frame.username == null); frame.rank.setDAOpassword(frame.DAOpassword); frame.rank.refreshRank(); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Constructor for the main JFrame object. * Sets the <code>frame</code> and initialize the <code>arena</code>, <code>view</code>, * <code>control</code>, <code>rank</code> variables, add tabs. * Calls the <code>initMenu</code> for add menu. */ public Escape() { <API key>(JFrame.EXIT_ON_CLOSE); setTitle("Escape"); setBounds(300, 0, 0, 0); pack(); Insets insets = getInsets(); setSize(new Dimension(insets.left + insets.right + 600, insets.top + insets.bottom + 630)); contentPane = new JPanel(); contentPane.setBackground(Color.WHITE); arena = new Arena(6, 600); view = new View(arena); control = new Controller(arena, view); view.setControl(control); rank = new Rank(); setContentPane(contentPane); contentPane.setLayout(new BorderLayout()); createMenuBar(); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("Game", view); tabbedPane.addTab("Rank", rank); tabbedPane.setFocusable(false); contentPane.add(tabbedPane); <API key>(view.getPlayer()); } /** * Creates the Menu and add to the main JFrame. * Creates the "New Game", "Save Game" and "Exit" items and * add ActionListener for control actions. */ private void createMenuBar() { JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); JMenuItem newGameMenuItem = new JMenuItem("New Game"); newGameMenuItem.setMnemonic(KeyEvent.VK_E); newGameMenuItem.setToolTipText("Start a new game"); newGameMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Service.newGame(arena, control, view); } }); JMenuItem saveGameMenuItem = new JMenuItem("Save Game"); saveGameMenuItem.setMnemonic(KeyEvent.VK_E); saveGameMenuItem.setToolTipText("Save the actual score and start a new game!"); saveGameMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { System.out.println(control.getPlayerScore()+control.getEnemyScore()); Service.saveGame(control, username, DAOpassword); Service.newGame(arena, control, view); } }); JMenuItem exitMenuItem = new JMenuItem("Exit"); exitMenuItem.setMnemonic(KeyEvent.VK_E); exitMenuItem.setToolTipText("Exit application"); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { System.exit(0); } }); file.add(newGameMenuItem); file.add(saveGameMenuItem); file.add(exitMenuItem); menubar.add(file); setJMenuBar(menubar); } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const options_1 = require("./options"); class TslintFixTask { constructor(configOrPath, options) { if (options) { this._configOrPath = configOrPath; this._options = options; } else { this._options = configOrPath; this._configOrPath = null; } } toConfiguration() { const path = typeof this._configOrPath == 'string' ? { tslintPath: this._configOrPath } : {}; const config = typeof this._configOrPath == 'object' && this._configOrPath !== null ? { tslintConfig: this._configOrPath } : {}; const options = { this._options, path, config, }; return { name: options_1.TslintFixName, options }; } } exports.TslintFixTask = TslintFixTask;
// option. This file may not be copied, modified, or distributed // except according to those terms. use core::prelude::*; use common::mode_run_pass; use common::mode_run_fail; use common::mode_compile_fail; use common::mode_pretty; use common::config; use errors; use header::load_props; use header::TestProps; use procsrv; use util; use util::logv; use core::io::WriterUtil; use core::io; use core::os; use core::str; use core::uint; use core::vec; pub fn run(config: config, testfile: ~str) { if config.verbose { // We're going to be dumping a lot of info. Start on a new line. io::stdout().write_str(~"\n\n"); } let testfile = Path(testfile); debug!("running %s", testfile.to_str()); let props = load_props(&testfile); debug!("loaded props"); match config.mode { mode_compile_fail => run_cfail_test(config, props, &testfile), mode_run_fail => run_rfail_test(config, props, &testfile), mode_run_pass => run_rpass_test(config, props, &testfile), mode_pretty => run_pretty_test(config, props, &testfile), mode_debug_info => run_debuginfo_test(config, props, &testfile) } } fn run_cfail_test(config: config, props: TestProps, testfile: &Path) { let ProcRes = compile_test(config, props, testfile); if ProcRes.status == 0 { fatal_ProcRes(~"compile-fail test compiled successfully!", ProcRes); } <API key>(ProcRes); let expected_errors = errors::load_errors(testfile); if !expected_errors.is_empty() { if !props.error_patterns.is_empty() { fatal(~"both error pattern and expected errors specified"); } <API key>(expected_errors, testfile, ProcRes); } else { <API key>(props, testfile, ProcRes); } } fn run_rfail_test(config: config, props: TestProps, testfile: &Path) { let ProcRes = if !config.jit { let ProcRes = compile_test(config, props, testfile); if ProcRes.status != 0 { fatal_ProcRes(~"compilation failed!", ProcRes); } exec_compiled_test(config, props, testfile) } else { jit_test(config, props, testfile) }; // The value our Makefile configures valgrind to return on failure static valgrind_err: int = 100; if ProcRes.status == valgrind_err { fatal_ProcRes(~"run-fail test isn't valgrind-clean!", ProcRes); } <API key>(ProcRes); <API key>(props, testfile, ProcRes); } fn <API key>(ProcRes: ProcRes) { // The value the rust runtime returns on failure static rust_err: int = 101; if ProcRes.status != rust_err { fatal_ProcRes( fmt!("failure produced the wrong error code: %d", ProcRes.status), ProcRes); } } fn run_rpass_test(config: config, props: TestProps, testfile: &Path) { if !config.jit { let mut ProcRes = compile_test(config, props, testfile); if ProcRes.status != 0 { fatal_ProcRes(~"compilation failed!", ProcRes); } ProcRes = exec_compiled_test(config, props, testfile); if ProcRes.status != 0 { fatal_ProcRes(~"test run failed!", ProcRes); } } else { let mut ProcRes = jit_test(config, props, testfile); if ProcRes.status != 0 { fatal_ProcRes(~"jit failed!", ProcRes); } } } fn run_pretty_test(config: config, props: TestProps, testfile: &Path) { if props.pp_exact.is_some() { logv(config, ~"testing for exact pretty-printing"); } else { logv(config, ~"testing for converging pretty-printing"); } let rounds = match props.pp_exact { Some(_) => 1, None => 2 }; let mut srcs = ~[io::read_whole_file_str(testfile).get()]; let mut round = 0; while round < rounds { logv(config, fmt!("pretty-printing round %d", round)); let ProcRes = print_source(config, testfile, srcs[round]); if ProcRes.status != 0 { fatal_ProcRes(fmt!("pretty-printing failed in round %d", round), ProcRes); } srcs.push(ProcRes.stdout); round += 1; } let mut expected = match props.pp_exact { Some(file) => { let filepath = testfile.dir_path().push_rel(&file); io::read_whole_file_str(&filepath).get() } None => { srcs[vec::len(srcs) - 2u] } }; let mut actual = srcs[vec::len(srcs) - 1u]; if props.pp_exact.is_some() { // Now we have to care about line endings let cr = ~"\r"; actual = str::replace(actual, cr, ~""); expected = str::replace(expected, cr, ~""); } compare_source(expected, actual); // Finally, let's make sure it actually appears to remain valid code let ProcRes = typecheck_source(config, props, testfile, actual); if ProcRes.status != 0 { fatal_ProcRes(~"pretty-printed source does not typecheck", ProcRes); } return; fn print_source(config: config, testfile: &Path, src: ~str) -> ProcRes { compose_and_run(config, testfile, make_pp_args(config, testfile), ~[], config.compile_lib_path, Some(src)) } fn make_pp_args(config: config, _testfile: &Path) -> ProcArgs { let prog = config.rustc_path; let args = ~[~"-", ~"--pretty", ~"normal"]; return ProcArgs {prog: prog.to_str(), args: args}; } fn compare_source(expected: ~str, actual: ~str) { if expected != actual { error(~"pretty-printed source does not match expected source"); let msg = fmt!("\n\ expected:\n\ %s\n\ actual:\n\ %s\n\ \n", expected, actual); io::stdout().write_str(msg); fail!(); } } fn typecheck_source(config: config, props: TestProps, testfile: &Path, src: ~str) -> ProcRes { <API key>( config, props, testfile, make_typecheck_args(config, props, testfile), Some(src)) } fn make_typecheck_args(config: config, props: TestProps, testfile: &Path) -> ProcArgs { let prog = config.rustc_path; let mut args = ~[~"-", ~"--no-trans", ~"--lib", ~"-L", config.build_base.to_str(), ~"-L", aux_output_dir_name(config, testfile).to_str()]; args += split_maybe_args(config.rustcflags); args += split_maybe_args(props.compile_flags); return ProcArgs {prog: prog.to_str(), args: args}; } } fn run_debuginfo_test(config: config, props: TestProps, testfile: &Path) { // do not optimize debuginfo tests let config = match config.rustcflags { Some(flags) => config { rustcflags: Some(str::replace(flags, ~"-O", ~"")), .. config }, None => config }; // compile test file (it shoud have 'compile-flags:-g' in the header) let mut ProcRes = compile_test(config, props, testfile); if ProcRes.status != 0 { fatal_ProcRes(~"compilation failed!", ProcRes); } // write debugger script let script_str = str::append(str::connect(props.debugger_cmds, "\n"), ~"\nquit\n"); debug!("script_str = %s", script_str); dump_output_file(config, testfile, script_str, ~"debugger.script"); // run debugger script with gdb #[cfg(windows)] fn debugger() -> ~str { ~"gdb.exe" } #[cfg(unix)] fn debugger() -> ~str { ~"gdb" } let debugger_script = make_out_name(config, testfile, ~"debugger.script"); let debugger_opts = ~[~"-quiet", ~"-batch", ~"-nx", ~"-command=" + debugger_script.to_str(), make_exe_name(config, testfile).to_str()]; let ProcArgs = ProcArgs {prog: debugger(), args: debugger_opts}; ProcRes = compose_and_run(config, testfile, ProcArgs, ~[], ~"", None); if ProcRes.status != 0 { fatal(~"gdb failed to execute"); } let num_check_lines = vec::len(props.check_lines); if num_check_lines > 0 { // check if each line in props.check_lines appears in the // output (in order) let mut i = 0u; for str::each_line(ProcRes.stdout) |line| { if props.check_lines[i].trim() == line.trim() { i += 1u; } if i == num_check_lines { // all lines checked break; } } if i != num_check_lines { fatal_ProcRes(fmt!("line not found in debugger output: %s" props.check_lines[i]), ProcRes); } } } fn <API key>(props: TestProps, testfile: &Path, ProcRes: ProcRes) { if vec::is_empty(props.error_patterns) { fatal(~"no error pattern specified in " + testfile.to_str()); } if ProcRes.status == 0 { fatal(~"process did not return an error status"); } let mut next_err_idx = 0u; let mut next_err_pat = props.error_patterns[next_err_idx]; let mut done = false; for str::each_line(ProcRes.stderr) |line| { if str::contains(line, next_err_pat) { debug!("found error pattern %s", next_err_pat); next_err_idx += 1u; if next_err_idx == vec::len(props.error_patterns) { debug!("found all error patterns"); done = true; break; } next_err_pat = props.error_patterns[next_err_idx]; } } if done { return; } let missing_patterns = vec::slice(props.error_patterns, next_err_idx, vec::len(props.error_patterns)); if vec::len(missing_patterns) == 1u { fatal_ProcRes(fmt!("error pattern '%s' not found!", missing_patterns[0]), ProcRes); } else { for missing_patterns.each |pattern| { error(fmt!("error pattern '%s' not found!", *pattern)); } fatal_ProcRes(~"multiple error patterns not found", ProcRes); } } fn <API key>(expected_errors: ~[errors::ExpectedError], testfile: &Path, ProcRes: ProcRes) { // true if we found the error in question let mut found_flags = vec::from_elem( vec::len(expected_errors), false); if ProcRes.status == 0 { fatal(~"process did not return an error status"); } let prefixes = vec::map(expected_errors, |ee| { fmt!("%s:%u:", testfile.to_str(), ee.line) }); // Scan and extract our error/warning messages, // which look like: // filename:line1:col1: line2:col2: *error:* msg // filename:line1:col1: line2:col2: *warning:* msg // where line1:col1: is the starting point, line2:col2: // is the ending point, and * represents ANSI color codes. for str::each_line(ProcRes.stderr) |line| { let mut was_expected = false; for vec::eachi(expected_errors) |i, ee| { if !found_flags[i] { debug!("prefix=%s ee.kind=%s ee.msg=%s line=%s", prefixes[i], ee.kind, ee.msg, line); if (str::starts_with(line, prefixes[i]) && str::contains(line, ee.kind) && str::contains(line, ee.msg)) { found_flags[i] = true; was_expected = true; break; } } } // ignore this msg which gets printed at the end if str::contains(line, ~"aborting due to") { was_expected = true; } if !was_expected && <API key>(str::from_slice(line)) { fatal_ProcRes(fmt!("unexpected compiler error or warning: '%s'", line), ProcRes); } } for uint::range(0u, vec::len(found_flags)) |i| { if !found_flags[i] { let ee = expected_errors[i]; fatal_ProcRes(fmt!("expected %s on line %u not found: %s", ee.kind, ee.line, ee.msg), ProcRes); } } } fn <API key>(line: ~str) -> bool { let mut i = 0u; return scan_until_char(line, ':', &mut i) && scan_char(line, ':', &mut i) && scan_integer(line, &mut i) && scan_char(line, ':', &mut i) && scan_integer(line, &mut i) && scan_char(line, ':', &mut i) && scan_char(line, ' ', &mut i) && scan_integer(line, &mut i) && scan_char(line, ':', &mut i) && scan_integer(line, &mut i) && scan_char(line, ' ', &mut i) && (scan_string(line, ~"error", &mut i) || scan_string(line, ~"warning", &mut i)); } fn scan_until_char(haystack: ~str, needle: char, idx: &mut uint) -> bool { if *idx >= haystack.len() { return false; } let opt = str::find_char_from(haystack, needle, *idx); if opt.is_none() { return false; } *idx = opt.get(); return true; } fn scan_char(haystack: ~str, needle: char, idx: &mut uint) -> bool { if *idx >= haystack.len() { return false; } let range = str::char_range_at(haystack, *idx); if range.ch != needle { return false; } *idx = range.next; return true; } fn scan_integer(haystack: ~str, idx: &mut uint) -> bool { let mut i = *idx; while i < haystack.len() { let range = str::char_range_at(haystack, i); if range.ch < '0' || '9' < range.ch { break; } i = range.next; } if i == *idx { return false; } *idx = i; return true; } fn scan_string(haystack: ~str, needle: ~str, idx: &mut uint) -> bool { let mut haystack_i = *idx; let mut needle_i = 0u; while needle_i < needle.len() { if haystack_i >= haystack.len() { return false; } let range = str::char_range_at(haystack, haystack_i); haystack_i = range.next; if !scan_char(needle, range.ch, &mut needle_i) { return false; } } *idx = haystack_i; return true; } struct ProcArgs {prog: ~str, args: ~[~str]} struct ProcRes {status: int, stdout: ~str, stderr: ~str, cmdline: ~str} fn compile_test(config: config, props: TestProps, testfile: &Path) -> ProcRes { compile_test_(config, props, testfile, []) } fn jit_test(config: config, props: TestProps, testfile: &Path) -> ProcRes { compile_test_(config, props, testfile, [~"--jit"]) } fn compile_test_(config: config, props: TestProps, testfile: &Path, extra_args: &[~str]) -> ProcRes { let link_args = ~[~"-L", aux_output_dir_name(config, testfile).to_str()]; <API key>( config, props, testfile, make_compile_args(config, props, link_args + extra_args, make_exe_name, testfile), None) } fn exec_compiled_test(config: config, props: TestProps, testfile: &Path) -> ProcRes { // If testing the new runtime then set the RUST_NEWRT env var let env = if config.newrt { props.exec_env + ~[(~"RUST_NEWRT", ~"1")] } else { props.exec_env }; compose_and_run(config, testfile, make_run_args(config, props, testfile), env, config.run_lib_path, None) } fn <API key>( config: config, props: TestProps, testfile: &Path, args: ProcArgs, input: Option<~str>) -> ProcRes { if !props.aux_builds.is_empty() { ensure_dir(&aux_output_dir_name(config, testfile)); } let extra_link_args = ~[~"-L", aux_output_dir_name(config, testfile).to_str()]; for vec::each(props.aux_builds) |rel_ab| { let abs_ab = config.aux_base.push_rel(&Path(*rel_ab)); let aux_args = make_compile_args(config, props, ~[~"--lib"] + extra_link_args, |a,b| make_lib_name(a, b, testfile), &abs_ab); let auxres = compose_and_run(config, &abs_ab, aux_args, ~[], config.compile_lib_path, None); if auxres.status != 0 { fatal_ProcRes( fmt!("auxiliary build of %s failed to compile: ", abs_ab.to_str()), auxres); } } compose_and_run(config, testfile, args, ~[], config.compile_lib_path, input) } fn ensure_dir(path: &Path) { if os::path_is_dir(path) { return; } if !os::make_dir(path, 0x1c0i32) { fail!(fmt!("can't make dir %s", path.to_str())); } } fn compose_and_run(config: config, testfile: &Path, ProcArgs: ProcArgs, procenv: ~[(~str, ~str)], lib_path: ~str, input: Option<~str>) -> ProcRes { return program_output(config, testfile, lib_path, ProcArgs.prog, ProcArgs.args, procenv, input); } fn make_compile_args(config: config, props: TestProps, extras: ~[~str], xform: &fn(config, (&Path)) -> Path, testfile: &Path) -> ProcArgs { let prog = config.rustc_path; let mut args = ~[testfile.to_str(), ~"-o", xform(config, testfile).to_str(), ~"-L", config.build_base.to_str()] + extras; args += split_maybe_args(config.rustcflags); args += split_maybe_args(props.compile_flags); return ProcArgs {prog: prog.to_str(), args: args}; } fn make_lib_name(config: config, auxfile: &Path, testfile: &Path) -> Path { // what we return here is not particularly important, as it // happens; rustc ignores everything except for the directory. let auxname = output_testname(auxfile); aux_output_dir_name(config, testfile).push_rel(&auxname) } fn make_exe_name(config: config, testfile: &Path) -> Path { Path(output_base_name(config, testfile).to_str() + str::from_slice(os::EXE_SUFFIX)) } fn make_run_args(config: config, _props: TestProps, testfile: &Path) -> ProcArgs { let toolargs = { // If we've got another tool to run under (valgrind), // then split apart its command let runtool = match config.runtool { Some(s) => Some(s), None => None }; split_maybe_args(runtool) }; let args = toolargs + ~[make_exe_name(config, testfile).to_str()]; return ProcArgs {prog: args[0], args: vec::slice(args, 1, args.len()).to_vec()}; } fn split_maybe_args(argstr: Option<~str>) -> ~[~str] { fn rm_whitespace(v: ~[~str]) -> ~[~str] { v.filtered(|s| !str::is_whitespace(*s)) } match argstr { Some(s) => { let mut ss = ~[]; for str::each_split_char(s, ' ') |s| { ss.push(s.to_owned()) } rm_whitespace(ss) } None => ~[] } } fn program_output(config: config, testfile: &Path, lib_path: ~str, prog: ~str, args: ~[~str], env: ~[(~str, ~str)], input: Option<~str>) -> ProcRes { let cmdline = { let cmdline = make_cmdline(lib_path, prog, args); logv(config, fmt!("executing %s", cmdline)); cmdline }; let res = procsrv::run(lib_path, prog, args, env, input); dump_output(config, testfile, res.out, res.err); return ProcRes {status: res.status, stdout: res.out, stderr: res.err, cmdline: cmdline}; } // Linux and mac don't require adjusting the library search path #[cfg(target_os = "linux")] #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] fn make_cmdline(_libpath: ~str, prog: ~str, args: ~[~str]) -> ~str { fmt!("%s %s", prog, str::connect(args, ~" ")) } #[cfg(target_os = "win32")] fn make_cmdline(libpath: ~str, prog: ~str, args: ~[~str]) -> ~str { fmt!("%s %s %s", lib_path_cmd_prefix(libpath), prog, str::connect(args, ~" ")) } // Build the LD_LIBRARY_PATH variable as it would be seen on the command line // for diagnostic purposes fn lib_path_cmd_prefix(path: ~str) -> ~str { fmt!("%s=\"%s\"", util::lib_path_env_var(), util::make_new_path(path)) } fn dump_output(config: config, testfile: &Path, out: ~str, err: ~str) { dump_output_file(config, testfile, out, ~"out"); dump_output_file(config, testfile, err, ~"err"); <API key>(config, out, err); } fn dump_output_file(config: config, testfile: &Path, out: ~str, extension: ~str) { let outfile = make_out_name(config, testfile, extension); let writer = io::file_writer(&outfile, ~[io::Create, io::Truncate]).get(); writer.write_str(out); } fn make_out_name(config: config, testfile: &Path, extension: ~str) -> Path { output_base_name(config, testfile).with_filetype(extension) } fn aux_output_dir_name(config: config, testfile: &Path) -> Path { output_base_name(config, testfile).with_filetype("libaux") } fn output_testname(testfile: &Path) -> Path { Path(testfile.filestem().get()) } fn output_base_name(config: config, testfile: &Path) -> Path { config.build_base .push_rel(&output_testname(testfile)) .with_filetype(config.stage_id) } fn <API key>(config: config, out: ~str, err: ~str) { if config.verbose { let sep1 = fmt!(" let sep2 = fmt!(" let sep3 = ~" io::stdout().write_line(sep1); io::stdout().write_line(out); io::stdout().write_line(sep2); io::stdout().write_line(err); io::stdout().write_line(sep3); } } fn error(err: ~str) { io::stdout().write_line(fmt!("\nerror: %s", err)); } fn fatal(err: ~str) -> ! { error(err); fail!(); } fn fatal_ProcRes(err: ~str, ProcRes: ProcRes) -> ! { let msg = fmt!("\n\ error: %s\n\ command: %s\n\ stdout:\n\ %s\n\ stderr:\n\ %s\n\ \n", err, ProcRes.cmdline, ProcRes.stdout, ProcRes.stderr); io::stdout().write_str(msg); fail!(); }