repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
billy1380/markdown4j-gwt-demo
|
src/markdown4j/gwt/demo/client/MarkdownDemoPage.java
|
8530
|
//
// MarkdownDemoPage.java
// markdown4j-gwt-demo
//
// Created by William Shakour (billy1380) on 2 Jan 2015.
// Copyright © 2015 SPACEHOPPER STUDIOS Ltd. All rights reserved.
//
package markdown4j.gwt.demo.client;
import java.util.List;
import java.util.Map;
import org.markdown4j.Plugin;
import org.markdown4j.client.Markdown;
import org.markdown4j.client.MarkdownProcessor;
import org.markdown4j.client.event.PluginContentReadyEventHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.InlineHyperlink;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import emoji.gwt.emoji.Emoji;
/**
* @author William Shakour (billy1380)
*
*/
public class MarkdownDemoPage extends Composite
implements PluginContentReadyEventHandler {
private static MarkdownDemoPageUiBinder uiBinder = GWT
.create(MarkdownDemoPageUiBinder.class);
interface MarkdownDemoPageUiBinder
extends UiBinder<Widget, MarkdownDemoPage> {}
@UiField TextArea markdown;
@UiField HTMLPanel converted;
@UiField InlineHyperlink another;
@UiField InlineHyperlink clear;
@UiField TextArea asyncMarkdown;
@UiField HTMLPanel asyncConverted;
@UiField InlineHyperlink process;
interface MarkdownSnippets extends ClientBundle {
static final MarkdownSnippets INSTANCE = GWT
.create(MarkdownSnippets.class);
@Source("res/generated.md")
Markdown generated ();
@Source("res/emoji.md")
Markdown emoji ();
}
// removes async plugin registration
MarkdownProcessor processor = new MarkdownProcessor() {
protected void registerPlugins () {};
};
MarkdownProcessor asyncProcessor = new MarkdownProcessor();
private HandlerRegistration registration;
public MarkdownDemoPage () {
initWidget(uiBinder.createAndBindUi(this));
Emoji.get("noto", e -> {
markdown.setText("# Ponat mortalia prior suo cum Lami adit\n" + "\n"
+ "## :thumbsup: Quod quas relictis tenuit\n" + "\n"
+ "Lorem markdownum mutato Achivos **pectora tenebris**, inde nisi divesque,\n"
+ "praetereunt favilla, et letum. Manu Idas praemia! Deae nec? Tam verba; agat quod\n"
+ "dentemque amanti referunt :rose:, nova sed *minoribus habitus*.\n"
+ "\n"
+ " vfat_navigation.caps /= subdirectory(joystick_pci - fddi, computer +\n"
+ " minicomputer_refresh);\n"
+ " remoteCore.rtAbendOdbc += power / designWeb - 4;\n"
+ " if (widget_isp >= upnpToggleSystem(uatDsl(bar_activex_widget,\n"
+ " impactTutorialEps), 325247)) {\n"
+ " control_keystroke_compile -= insertion_carrier;\n"
+ " drive_ping_heap.vdu_pop_source = website_sidebar_throughput;\n"
+ " hdmiInput.ip_compact(phreakingPublishingQuery, telecommunicationsMemory,\n"
+ " sample + 4);\n" + " }\n" + "\n"
+ "Silvis densi comitante saepe imitamina unum lignea retemptat est ergo dictoque.\n"
+ "Gerunt si aquarum per missus, in dedere ambiguis et :tennis:. Cum Turnus stetit.\n"
+ "Saepe undas.\n" + "\n" + "## Via concutit visa\n" + "\n"
+ "Voce matrem, ebiberant ferus, curvamine genus, inspicitur? Tulimus molliaque\n"
+ "occasus tibi? Neptunius illa solet miratur, est classe ab nullum fortiter.\n"
+ "*Amori* mea geminis suumque feres ego doleret causa; citi, matris [stantibus\n"
+ "fratre](http://www.thesecretofinvisibility.com/), sum fata.\n"
+ "\n"
+ " if (fragmentation_pci(tag_pdf / vlog_transistor_program, 52, printer) !=\n"
+ " localhost) {\n"
+ " directory_hibernate_plagiarism += crossplatform_pci(adsl_pdf.operating(\n"
+ " metaTabletReality), 3);\n" + " }\n"
+ " if (kernelHackerEngine == friend_e_process) {\n"
+ " bootFile = isp;\n" + " }\n"
+ " if (backup_left) {\n"
+ " data *= dynamic(-3, -5, primaryVoip) - 1;\n"
+ " url_in_compression = characterSidebar;\n"
+ " } else {\n"
+ " basic(resolutionDomain, 71);\n" + " }\n"
+ "\n"
+ "## Tartara ad animum fluviis ventis terga moresque\n"
+ "\n"
+ "Suas ferrataque audenti tollit nec. Ante illi sed sonant *iaculo*, Noctisque\n"
+ "quinos silva, in tollit per possum est submisso cepit.\n"
+ "\n"
+ "1. Ante cursus inpono praemia cultumque tetigere auro\n"
+ "2. Tollere tecta\n"
+ "3. Nulla dixit tersis in Isthmon marem\n"
+ "4. Simul viridem senectae Memnonides super rogabam flores\n"
+ "5. Gravidae nomine\n"
+ "6. Ora trepident pectore molior quem\n" + "\n"
+ "[Sternit](http://zeus.ugent.be/) temptare, valet dispositam ripis te dixi\n"
+ "[irascentemque paulatim](http://jaspervdj.be/) praebentem eunt miserere, retraxi\n"
+ "non castris. Gigantas suspiria :bath: ait colores in fretum semper et lateri?\n"
+ "Petis corpore caput. Et tangit opposuit et meque domum inde ad sinuatoque\n"
+ "triste, dixere turbantur Lycias foret sternitur stantem fessa, nequit. In\n"
+ "comitesque ulla perstant curas reverti scelerata saxa ramum quibus quam ore\n"
+ "nomen cetera.");
process();
asyncMarkdown.setText(
"%%% yuml type=class scale=100 style=scruffy dir=LR format=png\n"
+ "[Customer]<>1->*[Order], [Customer]-[note: Aggregate Root{bg:cornsilk}]\n"
+ "%%%\n" + "\n" + "---\n" + "\n"
+ "%%% sequence style=modern-blue\n"
+ "title Authentication Sequence\n" + "\n"
+ "Alice->Bob: Authentication Request\n"
+ "note right of Bob: Bob thinks about it\n"
+ "Bob->Alice: Authentication Response\n" + "%%%\n"
+ "\n" + "---\n" + "\n"
+ "%%% include src=https://raw.github.com/vmg/redcarpet/4c14d0875163890e553897efcceb7480aa34f8e9/README.markdown %%%");
onProcessClicked(null);
});
}
/* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.Composite#onAttach() */
@Override
protected void onAttach () {
super.onAttach();
if (registration != null) {
registration.removeHandler();
}
registration = asyncProcessor.addPluginContentReadyHandler(this);
}
/* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.Composite#onDetach() */
@Override
protected void onDetach () {
super.onDetach();
if (registration != null) {
registration.removeHandler();
}
}
@UiHandler("markdown")
void onMarkdownKeyUp (KeyUpEvent kue) {
process();
}
@UiHandler("another")
void onAnotherClicked (ClickEvent ce) {
if (markdown.getText().length() > 0) {
process();
converted.add(new HTMLPanel(SafeHtmlUtils.EMPTY_SAFE_HTML));
markdown.setText("");
}
}
@UiHandler("clear")
void onClearClicked (ClickEvent ce) {
markdown.setText("");
converted.clear();
}
@UiHandler("process")
void onProcessClicked (ClickEvent ce) {
asyncConverted.getElement()
.setInnerHTML(asyncProcessor.process(asyncMarkdown.getText()));
}
private void process () {
HTMLPanel panel;
int count = converted.getWidgetCount();
if (count == 0) {
converted.add(panel = new HTMLPanel(SafeHtmlUtils.EMPTY_SAFE_HTML));
} else {
panel = (HTMLPanel) converted.getWidget(count - 1);
}
panel.getElement().setInnerHTML(processor.process(markdown.getText()));
}
/* (non-Javadoc)
*
* @see
* org.markdown4j.client.event.PluginContentReadyEventHandler#ready(org.
* markdown4j.client.event.PluginContentReadyEventHandler.
* PluginContentReadyEvent, org.markdown4j.Plugin, java.util.List,
* java.util.Map, java.lang.String, java.lang.String) */
@Override
public void ready (PluginContentReadyEvent event, Plugin plugin,
List<String> lines, Map<String, String> params, String id,
String content) {
if (event.getSource() == processor) {
throw new RuntimeException(
"Should not be getting events for the realtime processor");
} else if (event.getSource() == asyncProcessor) {
Element e = asyncConverted.getElementById(id);
e.setInnerHTML(content);
}
}
}
|
apache-2.0
|
K7Gt/java_pft
|
sandbox/src/main/java/ru/stqa/pft/sandbox/DiffTests.java
|
1031
|
package ru.stqa.pft.sandbox;
/**
* Created by Golem on 08.04.2017.
*/
public class DiffTests {
public static void main(String[] args){
String test = "testname testMiddlename testlastname\n" +
"testNick\n" +
"testtitle\n" +
"testCompany\n" +
"testaddres\n" +
"\n" +
"H: 111\n" +
"M: 2222\n" +
"W: 33333\n" +
"\n" +
"test1@gmail.com\n" +
"test2@gmail.com\n" +
"test3@gmail.com\n" +
"Homepage:\n" +
"test.com";
System.out.println(cleaned(test));
}
public static String cleaned(String string){
return string.replaceAll("\\s","")
.replaceAll("[-()]","")
.replaceAll("\n","")
.replaceAll("H:","")
.replaceAll("M:","")
.replaceAll("W:","")
.replaceAll("Homepage:","");
}
}
|
apache-2.0
|
icotting/Phocalstream
|
Phocalstream_Shared/Data/Model/Photo/TimeLapseFrame.cs
|
352
|
using Phocalstream_Shared.Data.Model.External;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Phocalstream_Shared.Data.Model.Photo
{
public class TimeLapseFrame
{
public long PhotoID { get; set; }
public DateTime FrameTime { get; set; }
}
}
|
apache-2.0
|
PaloAltoNetworks/minemeld-core
|
minemeld/traced/writer.py
|
2567
|
# Copyright 2016 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module implements the writer class for logs
"""
import logging
import psutil
import ujson
import gevent
import gevent.event
LOG = logging.getLogger(__name__)
class DiskSpaceMonitor(gevent.Greenlet):
def __init__(self, threshold, low_disk):
self._threshold = threshold
self._low_disk = low_disk
super(DiskSpaceMonitor, self).__init__()
def _run(self):
while True:
perc_used = psutil.disk_usage('.').percent
if perc_used >= self._threshold:
if not self._low_disk.is_set():
self._low_disk.set()
LOG.critical(
'Disk space used above threshold ({}%), writing disabled'.format(self._threshold)
)
else:
if self._low_disk.is_set():
self._low_disk.clear()
LOG.info('Disk space used below threshold, writing restored')
gevent.sleep(60)
class Writer(object):
def __init__(self, comm, store, topic, config):
self._stop = gevent.event.Event()
self._low_disk = gevent.event.Event()
self.store = store
self.comm = comm
self.comm.request_sub_channel(
topic,
self,
allowed_methods=['log'],
name='mbus:log:writer',
multi_write=True
)
self._disk_monitor_glet = DiskSpaceMonitor(
threshold=config.get('threshold', 70),
low_disk=self._low_disk
)
self._disk_monitor_glet.start()
def log(self, timestamp, **kwargs):
if self._stop.is_set():
return
if self._low_disk.is_set():
return
self.store.write(timestamp, ujson.dumps(kwargs))
def stop(self):
LOG.info('Writer - stop called')
if self._stop.is_set():
return
self._stop.set()
self._disk_monitor_glet.kill()
|
apache-2.0
|
chenglongwei/trafficserver
|
iocore/cache/CachePages.cc
|
23717
|
/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "P_Cache.h"
#include "Show.h"
#include "I_Tasks.h"
#include "CacheControl.h"
struct ShowCache : public ShowCont {
enum scan_type {
scan_type_lookup,
scan_type_delete,
scan_type_invalidate,
};
int vol_index;
int seg_index;
scan_type scan_flag;
int urlstrs_index;
int linecount;
char (*show_cache_urlstrs)[500];
URL url;
CacheKey show_cache_key;
CacheVC *cache_vc;
MIOBuffer *buffer;
IOBufferReader *buffer_reader;
int64_t content_length;
VIO *cvio;
int showMain(int event, Event *e);
int lookup_url_form(int event, Event *e);
int delete_url_form(int event, Event *e);
int lookup_regex_form(int event, Event *e);
int delete_regex_form(int event, Event *e);
int invalidate_regex_form(int event, Event *e);
int lookup_url(int event, Event *e);
int delete_url(int event, Event *e);
int lookup_regex(int event, Event *e);
int delete_regex(int event, Event *e);
int invalidate_regex(int event, Event *e);
int handleCacheEvent(int event, Event *e);
int handleCacheDeleteComplete(int event, Event *e);
int handleCacheScanCallback(int event, Event *e);
ShowCache(Continuation *c, HTTPHdr *h)
: ShowCont(c, h),
vol_index(0),
seg_index(0),
scan_flag(scan_type_lookup),
cache_vc(nullptr),
buffer(nullptr),
buffer_reader(nullptr),
content_length(0),
cvio(nullptr)
{
urlstrs_index = 0;
linecount = 0;
int query_len;
char query[4096];
char unescapedQuery[sizeof(query)];
show_cache_urlstrs = nullptr;
URL *u = h->url_get();
// process the query string
if (u->query_get(&query_len) && query_len < (int)sizeof(query)) {
strncpy(query, u->query_get(&query_len), query_len);
strncpy(unescapedQuery, u->query_get(&query_len), query_len);
query[query_len] = unescapedQuery[query_len] = '\0';
query_len = unescapifyStr(query);
Debug("cache_inspector", "query params: '%s' len %d [unescaped]", unescapedQuery, query_len);
Debug("cache_inspector", "query params: '%s' len %d [escaped]", query, query_len);
// remove 'C-m' s
unsigned l, m;
for (l = 0, m = 0; l < (unsigned)query_len; l++) {
if (query[l] != '\015') {
query[m++] = query[l];
}
}
query[m] = '\0';
unsigned nstrings = 1;
char *p = strstr(query, "url=");
// count the no of urls
if (p) {
while ((p = strstr(p, "\n"))) {
nstrings++;
if ((size_t)(p - query) >= strlen(query) - 1)
break;
else
p++;
}
}
// initialize url array
show_cache_urlstrs = new char[nstrings + 1][500];
memset(show_cache_urlstrs, '\0', (nstrings + 1) * 500 * sizeof(char));
char *q, *t;
p = strstr(unescapedQuery, "url=");
if (p) {
p += 4; // 4 ==> strlen("url=")
t = strchr(p, '&');
if (!t)
t = (char *)unescapedQuery + strlen(unescapedQuery);
for (int s = 0; p < t; s++) {
show_cache_urlstrs[s][0] = '\0';
q = strstr(p, "%0D%0A" /* \r\n */); // we used this in the JS to separate urls
if (!q)
q = t;
ink_strlcpy(show_cache_urlstrs[s], p, q - p + 1);
p = q + 6; // +6 ==> strlen(%0D%0A)
}
}
Debug("cache_inspector", "there were %d url(s) passed in", nstrings == 1 ? 1 : nstrings - 1);
for (unsigned i = 0; i < nstrings; i++) {
if (show_cache_urlstrs[i][0] == '\0') {
continue;
}
Debug("cache_inspector", "URL %d: '%s'", i + 1, show_cache_urlstrs[i]);
unescapifyStr(show_cache_urlstrs[i]);
Debug("cache_inspector", "URL %d: '%s'", i + 1, show_cache_urlstrs[i]);
}
}
SET_HANDLER(&ShowCache::showMain);
}
~ShowCache()
{
if (show_cache_urlstrs)
delete[] show_cache_urlstrs;
url.destroy();
}
};
#define STREQ_PREFIX(_x, _s) (!strncasecmp(_x, _s, sizeof(_s) - 1))
#define STREQ_LEN_PREFIX(_x, _l, _s) (path_len < sizeof(_s) && !strncasecmp(_x, _s, sizeof(_s) - 1))
Action *
register_ShowCache(Continuation *c, HTTPHdr *h)
{
ShowCache *theshowcache = new ShowCache(c, h);
URL *u = h->url_get();
int path_len;
const char *path = u->path_get(&path_len);
if (!path) {
} else if (STREQ_PREFIX(path, "lookup_url_form")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::lookup_url_form);
} else if (STREQ_PREFIX(path, "delete_url_form")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::delete_url_form);
} else if (STREQ_PREFIX(path, "lookup_regex_form")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::lookup_regex_form);
} else if (STREQ_PREFIX(path, "delete_regex_form")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::delete_regex_form);
} else if (STREQ_PREFIX(path, "invalidate_regex_form")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::invalidate_regex_form);
}
else if (STREQ_PREFIX(path, "lookup_url")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::lookup_url);
} else if (STREQ_PREFIX(path, "delete_url")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::delete_url);
} else if (STREQ_PREFIX(path, "lookup_regex")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::lookup_regex);
} else if (STREQ_PREFIX(path, "delete_regex")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::delete_regex);
} else if (STREQ_PREFIX(path, "invalidate_regex")) {
SET_CONTINUATION_HANDLER(theshowcache, &ShowCache::invalidate_regex);
}
if (theshowcache->mutex->thread_holding) {
CONT_SCHED_LOCK_RETRY(theshowcache);
} else {
eventProcessor.schedule_imm(theshowcache, ET_TASK);
}
return &theshowcache->action;
}
int
ShowCache::showMain(int event, Event *e)
{
CHECK_SHOW(begin("Cache"));
CHECK_SHOW(show("<H3><A HREF=\"./lookup_url_form\">Lookup url</A></H3>\n"
"<H3><A HREF=\"./delete_url_form\">Delete url</A></H3>\n"
"<H3><A HREF=\"./lookup_regex_form\">Regex lookup</A></H3>\n"
"<H3><A HREF=\"./delete_regex_form\">Regex delete</A></H3>\n"
"<H3><A HREF=\"./invalidate_regex_form\">Regex invalidate</A></H3>\n\n"));
return complete(event, e);
}
int
ShowCache::lookup_url_form(int event, Event *e)
{
CHECK_SHOW(begin("Cache Lookup"));
CHECK_SHOW(show("<FORM METHOD=\"GET\" ACTION=\"./lookup_url\">\n"
"<H3>Lookup</H3>\n"
"<INPUT TYPE=\"TEXT\" NAME=\"url\" value=\"http://\">\n"
"<INPUT TYPE=\"SUBMIT\" value=\"Lookup\">\n"
"</FORM>\n\n"));
return complete(event, e);
}
int
ShowCache::delete_url_form(int event, Event *e)
{
CHECK_SHOW(begin("Cache Delete"));
CHECK_SHOW(show("<FORM METHOD=\"GET\" ACTION=\"./delete_url\">\n"
"<P><B>Type the list urls that you want to delete\n"
"in the box below. The urls MUST be separated by\n"
"new lines</B></P>\n\n"
"<TEXTAREA NAME=\"url\" rows=10 cols=50>"
"http://"
"</TEXTAREA>\n"
"<INPUT TYPE=\"SUBMIT\" value=\"Delete\">\n"
"</FORM>\n\n"));
return complete(event, e);
}
int
ShowCache::lookup_regex_form(int event, Event *e)
{
CHECK_SHOW(begin("Cache Regex Lookup"));
CHECK_SHOW(show("<FORM METHOD=\"GET\" ACTION=\"./lookup_regex\">\n"
"<P><B>Type the list of regular expressions that you want to lookup\n"
"in the box below. The regular expressions MUST be separated by\n"
"new lines</B></P>\n\n"
"<TEXTAREA NAME=\"url\" rows=10 cols=50>"
"http://"
"</TEXTAREA>\n"
"<INPUT TYPE=\"SUBMIT\" value=\"Lookup\">\n"
"</FORM>\n\n"));
return complete(event, e);
}
int
ShowCache::delete_regex_form(int event, Event *e)
{
CHECK_SHOW(begin("Cache Regex delete"));
CHECK_SHOW(show("<FORM METHOD=\"GET\" ACTION=\"./delete_regex\">\n"
"<P><B>Type the list of regular expressions that you want to delete\n"
"in the box below. The regular expressions MUST be separated by\n"
"new lines</B></P>\n\n"
"<TEXTAREA NAME=\"url\" rows=10 cols=50>"
"http://"
"</TEXTAREA>\n"
"<INPUT TYPE=\"SUBMIT\" value=\"Delete\">\n"
"</FORM>\n\n"));
return complete(event, e);
}
int
ShowCache::invalidate_regex_form(int event, Event *e)
{
CHECK_SHOW(begin("Cache Regex Invalidate"));
CHECK_SHOW(show("<FORM METHOD=\"GET\" ACTION=\"./invalidate_regex\">\n"
"<P><B>Type the list of regular expressions that you want to invalidate\n"
"in the box below. The regular expressions MUST be separated by\n"
"new lines</B></P>\n\n"
"<TEXTAREA NAME=\"url\" rows=10 cols=50>"
"http://"
"</TEXTAREA>\n"
"<INPUT TYPE=\"SUBMIT\" value=\"Invalidate\">\n"
"</FORM>\n"));
return complete(event, e);
}
int
ShowCache::handleCacheEvent(int event, Event *e)
{
// we use VC_EVENT_xxx to finish the cluster read in cluster mode
switch (event) {
case VC_EVENT_EOS:
case VC_EVENT_READ_COMPLETE: {
// cluster read done, we just print hit in cluster
CHECK_SHOW(show("<P><TABLE border=1 width=100%%>"));
CHECK_SHOW(show("<TR><TH bgcolor=\"#FFF0E0\" colspan=2>Doc Hit from Cluster</TH></TR>\n"));
CHECK_SHOW(show("<tr><td>Size</td><td>%" PRId64 "</td>\n", content_length));
// delete button
CHECK_SHOW(show("<tr><td>Action</td>\n"
"<td><FORM action=\"./delete_url\" method=get>\n"
"<Input type=HIDDEN name=url value=\"%s\">\n"
"<input type=submit value=\"Delete URL\">\n"
"</FORM></td></tr>\n",
show_cache_urlstrs[0]));
CHECK_SHOW(show("</TABLE></P>"));
if (buffer_reader) {
buffer->dealloc_reader(buffer_reader);
buffer_reader = nullptr;
}
if (buffer) {
free_MIOBuffer(buffer);
buffer = nullptr;
}
cvio = nullptr;
cache_vc->do_io_close(-1);
cache_vc = nullptr;
return complete(event, e);
}
case CACHE_EVENT_OPEN_READ: {
// get the vector
cache_vc = (CacheVC *)e;
CacheHTTPInfoVector *vec = &(cache_vc->vector);
int alt_count = vec->count();
if (alt_count) {
Doc *d = (Doc *)(cache_vc->first_buf->data());
time_t t;
char tmpstr[4096];
// print the Doc
CHECK_SHOW(show("<P><TABLE border=1 width=100%%>"));
CHECK_SHOW(show("<TR><TH bgcolor=\"#FFF0E0\" colspan=2>Doc</TH></TR>\n"));
CHECK_SHOW(
show("<TR><TD>Volume</td> <td>#%d - store='%s'</td></tr>\n", cache_vc->vol->cache_vol->vol_number, cache_vc->vol->path));
CHECK_SHOW(show("<TR><TD>first key</td> <td>%s</td></tr>\n", d->first_key.toHexStr(tmpstr)));
CHECK_SHOW(show("<TR><TD>key</td> <td>%s</td></tr>\n", d->key.toHexStr(tmpstr)));
CHECK_SHOW(show("<tr><td>sync_serial</td><td>%lu</tr>\n", d->sync_serial));
CHECK_SHOW(show("<tr><td>write_serial</td><td>%lu</tr>\n", d->write_serial));
CHECK_SHOW(show("<tr><td>header length</td><td>%lu</tr>\n", d->hlen));
CHECK_SHOW(show("<tr><td>fragment type</td><td>%lu</tr>\n", d->doc_type));
CHECK_SHOW(show("<tr><td>No of Alternates</td><td>%d</td></tr>\n", alt_count));
CHECK_SHOW(show("<tr><td>Action</td>\n"
"<td><FORM action=\"./delete_url\" method=get>\n"
"<Input type=HIDDEN name=url value=\"%s\">\n"
"<input type=submit value=\"Delete URL\">\n"
"</FORM></td></tr>\n",
show_cache_urlstrs[0]));
CHECK_SHOW(show("</TABLE></P>"));
for (int i = 0; i < alt_count; i++) {
// unmarshal the alternate??
CHECK_SHOW(show("<p><table border=1>\n"));
CHECK_SHOW(show("<tr><th bgcolor=\"#FFF0E0\" colspan=2>Alternate %d</th></tr>\n", i + 1));
CacheHTTPInfo *obj = vec->get(i);
CacheKey obj_key = obj->object_key_get();
HTTPHdr *cached_request = obj->request_get();
HTTPHdr *cached_response = obj->response_get();
int64_t obj_size = obj->object_size_get();
int offset, tmp, used, done;
char b[4096];
// print request header
CHECK_SHOW(show("<tr><td>Request Header</td><td><PRE>"));
offset = 0;
do {
used = 0;
tmp = offset;
done = cached_request->print(b, 4095, &used, &tmp);
offset += used;
b[used] = '\0';
CHECK_SHOW(show("%s", b));
} while (!done);
CHECK_SHOW(show("</PRE></td><tr>\n"));
// print response header
CHECK_SHOW(show("<tr><td>Response Header</td><td><PRE>"));
offset = 0;
do {
used = 0;
tmp = offset;
done = cached_response->print(b, 4095, &used, &tmp);
offset += used;
b[used] = '\0';
CHECK_SHOW(show("%s", b));
} while (!done);
CHECK_SHOW(show("</PRE></td></tr>\n"));
CHECK_SHOW(show("<tr><td>Size</td><td>%" PRId64 "</td>\n", obj_size));
CHECK_SHOW(show("<tr><td>Key</td><td>%s</td>\n", obj_key.toHexStr(tmpstr)));
t = obj->request_sent_time_get();
ink_ctime_r(&t, tmpstr);
CHECK_SHOW(show("<tr><td>Request sent time</td><td>%s</td></tr>\n", tmpstr));
t = obj->response_received_time_get();
ink_ctime_r(&t, tmpstr);
CHECK_SHOW(show("<tr><td>Response received time</td><td>%s</td></tr>\n", tmpstr));
CHECK_SHOW(show("</TABLE></P>"));
}
cache_vc->do_io_close(-1);
return complete(event, e);
}
// open success but no vector, that is the Cluster open read, pass through
}
case VC_EVENT_READ_READY:
if (!cvio) {
buffer = new_empty_MIOBuffer();
buffer_reader = buffer->alloc_reader();
content_length = cache_vc->get_object_size();
cvio = cache_vc->do_io_read(this, content_length, buffer);
} else
buffer_reader->consume(buffer_reader->read_avail());
return EVENT_DONE;
case CACHE_EVENT_OPEN_READ_FAILED:
// something strange happen, or cache miss in cluster mode.
CHECK_SHOW(show("<H3>Cache Lookup Failed, or missing in cluster</H3>\n"));
return complete(event, e);
default:
CHECK_SHOW(show("<H3>Cache Miss</H3>\n"));
return complete(event, e);
}
}
int
ShowCache::lookup_url(int event, Event *e)
{
char header_str[300];
HttpCacheKey key;
cache_generation_t generation = -1;
snprintf(header_str, sizeof(header_str), "<font color=red>%s</font>", show_cache_urlstrs[0]);
CHECK_SHOW(begin(header_str));
url.create(nullptr);
const char *s;
s = show_cache_urlstrs[0];
url.parse(&s, s + strlen(s));
RecGetRecordInt("proxy.config.http.cache.generation", &generation);
Cache::generate_key(&key, &url, generation);
SET_HANDLER(&ShowCache::handleCacheEvent);
Action *lookup_result =
cacheProcessor.open_read(this, &key.hash, getClusterCacheLocal(&url), CACHE_FRAG_TYPE_HTTP, key.hostname, key.hostlen);
if (!lookup_result)
lookup_result = ACTION_IO_ERROR;
if (lookup_result == ACTION_RESULT_DONE)
return EVENT_DONE; // callback complete
else if (lookup_result == ACTION_IO_ERROR) {
handleEvent(CACHE_EVENT_OPEN_READ_FAILED, nullptr);
return EVENT_DONE; // callback complete
} else
return EVENT_CONT; // callback pending, will be a cluster read.
}
int
ShowCache::delete_url(int event, Event *e)
{
if (urlstrs_index == 0) {
// print the header the first time delete_url is called
CHECK_SHOW(begin("Delete URL"));
CHECK_SHOW(show("<B><TABLE border=1>\n"));
}
if (strcmp(show_cache_urlstrs[urlstrs_index], "") == 0) {
// close the page when you reach the end of the
// url list
CHECK_SHOW(show("</TABLE></B>\n"));
return complete(event, e);
}
url.create(nullptr);
const char *s;
s = show_cache_urlstrs[urlstrs_index];
CHECK_SHOW(show("<TR><TD>%s</TD>", s));
url.parse(&s, s + strlen(s));
SET_HANDLER(&ShowCache::handleCacheDeleteComplete);
// increment the index so that the next time
// delete_url is called you delete the next url
urlstrs_index++;
HttpCacheKey key;
Cache::generate_key(&key, &url); // XXX choose a cache generation number ...
cacheProcessor.remove(this, &key, getClusterCacheLocal(&url), CACHE_FRAG_TYPE_HTTP);
return EVENT_DONE;
}
int
ShowCache::handleCacheDeleteComplete(int event, Event *e)
{
if (event == CACHE_EVENT_REMOVE) {
CHECK_SHOW(show("<td>Delete <font color=green>succeeded</font></td></tr>\n"));
} else {
CHECK_SHOW(show("<td>Delete <font color=red>failed</font></td></tr>\n"));
}
return delete_url(event, e);
}
int
ShowCache::lookup_regex(int event, Event *e)
{
CHECK_SHOW(begin("Regex Lookup"));
CHECK_SHOW(show("<SCRIPT LANGIAGE=\"Javascript1.2\">\n"
"urllist = new Array(100);\n"
"index = 0;\n"
"function addToUrlList(input) {\n"
" for (c=0; c < index; c++) {\n"
" if (urllist[c] == encodeURIComponent(input.name)) {\n"
" urllist.splice(c,1);\n"
" index--;\n"
" return true;\n"
" }\n"
" }\n"
" urllist[index++] = encodeURIComponent(input.name);\n"
" return true;\n"
"}\n"
"function setUrls(form) {\n"
" form.elements[0].value=\"\";\n"
" if (index > 10) {\n"
" alert(\"Can't choose more than 10 urls for deleting\");\n"
" return true;\n"
"}\n"
" for (c=0; c < index; c++){\n"
" form.elements[0].value += urllist[c]+ \"%%0D%%0A\";\n"
" }\n"
" if (form.elements[0].value == \"\"){\n"
" alert(\"Please select atleast one url before clicking delete\");\n"
" return true;\n"
"}\n"
" srcfile=\"./delete_url?url=\" + form.elements[0].value;\n"
" document.location=srcfile;\n "
" return true;\n"
"}\n"
"</SCRIPT>\n"));
CHECK_SHOW(show("<FORM NAME=\"f\" ACTION=\"./delete_url\" METHOD=GET> \n"
"<INPUT TYPE=HIDDEN NAME=\"url\">\n"
"<B><TABLE border=1>\n"));
scan_flag = scan_type_lookup; // lookup
SET_HANDLER(&ShowCache::handleCacheScanCallback);
cacheProcessor.scan(this);
return EVENT_DONE;
}
int
ShowCache::delete_regex(int event, Event *e)
{
CHECK_SHOW(begin("Regex Delete"));
CHECK_SHOW(show("<B><TABLE border=1>\n"));
scan_flag = scan_type_delete; // delete
SET_HANDLER(&ShowCache::handleCacheScanCallback);
cacheProcessor.scan(this);
return EVENT_DONE;
}
int
ShowCache::invalidate_regex(int event, Event *e)
{
CHECK_SHOW(begin("Regex Invalidate"));
CHECK_SHOW(show("<B><TABLE border=1>\n"));
scan_flag = scan_type_invalidate; // invalidate
SET_HANDLER(&ShowCache::handleCacheScanCallback);
cacheProcessor.scan(this);
return EVENT_DONE;
}
int
ShowCache::handleCacheScanCallback(int event, Event *e)
{
switch (event) {
case CACHE_EVENT_SCAN: {
cache_vc = (CacheVC *)e;
return EVENT_CONT;
}
case CACHE_EVENT_SCAN_OBJECT: {
HTTPInfo *alt = (HTTPInfo *)e;
char xx[501], m[501];
int ib = 0, xd = 0, ml = 0;
alt->request_get()->url_print(xx, 500, &ib, &xd);
xx[ib] = '\0';
const char *mm = alt->request_get()->method_get(&ml);
memcpy(m, mm, ml);
m[ml] = 0;
int res = CACHE_SCAN_RESULT_CONTINUE;
for (unsigned s = 0; show_cache_urlstrs[s][0] != '\0'; s++) {
const char *error;
int erroffset;
pcre *preq = pcre_compile(show_cache_urlstrs[s], 0, &error, &erroffset, nullptr);
Debug("cache_inspector", "matching url '%s' '%s' with regex '%s'", m, xx, show_cache_urlstrs[s]);
if (preq) {
int r = pcre_exec(preq, nullptr, xx, ib, 0, 0, nullptr, 0);
pcre_free(preq);
if (r != -1) {
linecount++;
if ((linecount % 5) == 0) {
CHECK_SHOW(show("<TR bgcolor=\"#FFF0E0\">"));
} else {
CHECK_SHOW(show("<TR>"));
}
switch (scan_flag) {
case scan_type_lookup:
/*Y! Bug: 2249781: using onClick() because i need encodeURIComponent() and YTS doesn't have something like that */
CHECK_SHOW(show("<TD><INPUT TYPE=CHECKBOX NAME=\"%s\" "
"onClick=\"addToUrlList(this)\"></TD>"
"<TD><A onClick='window.location.href=\"./lookup_url?url=\"+ encodeURIComponent(\"%s\");' HREF=\"#\">"
"<B>%s</B></A></br></TD></TR>\n",
xx, xx, xx));
break;
case scan_type_delete:
CHECK_SHOW(show("<TD><B>%s</B></TD>"
"<TD><font color=red>deleted</font></TD></TR>\n",
xx));
res = CACHE_SCAN_RESULT_DELETE;
break;
case scan_type_invalidate:
HTTPInfo new_info;
res = CACHE_SCAN_RESULT_UPDATE;
new_info.copy(alt);
new_info.response_get()->set_cooked_cc_need_revalidate_once();
CHECK_SHOW(show("<TD><B>%s</B></TD>"
"<TD><font color=red>Invalidate</font></TD>"
"</TR>\n",
xx));
cache_vc->set_http_info(&new_info);
}
break;
}
} else {
// TODO: Regex didn't compile, show errors ?
Debug("cache_inspector", "regex '%s' didn't compile", show_cache_urlstrs[s]);
}
}
return res;
}
case CACHE_EVENT_SCAN_DONE:
CHECK_SHOW(show("</TABLE></B>\n"));
if (scan_flag == 0)
if (linecount) {
CHECK_SHOW(show("<P><INPUT TYPE=button value=\"Delete\" "
"onClick=\"setUrls(window.document.f)\"></P>"
"</FORM>\n"));
}
CHECK_SHOW(show("<H3>Done</H3>\n"));
Debug("cache_inspector", "scan done");
complete(event, e);
return EVENT_DONE;
case CACHE_EVENT_SCAN_FAILED:
default:
CHECK_SHOW(show("<H3>Error while scanning disk</H3>\n"));
return EVENT_DONE;
}
}
|
apache-2.0
|
ronichoudhury-work/resonantlab
|
legacy/views/overlays/Menu/index.js
|
3218
|
import d3 from 'd3';
import Backbone from 'backbone';
import template from './template.html';
import './style.scss';
let Menu = Backbone.View.extend({
initialize: function (menuSpec) {
this.menuSpec = menuSpec;
},
render: function () {
if (!this.addedTemplate) {
this.$el.html(template);
this.addedTemplate = true;
}
let menuDiv = d3.select(this.el).select('div.menu');
let menuItems = menuDiv.selectAll('.menuItem')
.data(this.menuSpec.items);
let menuItemsEnter = menuItems.enter()
.append('div')
.attr('class', 'menuItem');
menuItems.exit().remove();
// Make sure that only items with icons have img.icon elements
menuItems.select('img.icon')
.filter(d => d === null || !d.icon)
.remove();
menuItemsEnter.filter(d => d !== null && d.icon)
.append('img')
.attr('class', 'icon');
menuItems.select('img.icon')
.attr('src', d => typeof d.icon === 'function' ? d.icon() : d.icon);
// Make sure that only items with text have p elements
menuItems.select('p')
.filter(d => d === null || !d.text)
.remove();
menuItemsEnter.filter(d => d !== null && d.text)
.append('p');
menuItems.select('p')
.text(d => typeof d.text === 'function' ? d.text() : d.text);
// Make sure that only separators have hr elements
menuItems.select('hr')
.filter(d => d !== null)
.remove();
menuItemsEnter.filter(d => d === null)
.append('hr');
// Add any extra classes to style the items appropriately
let checksExist = menuItems.filter(d => d !== null && d.checked).size() > 0;
menuItems.attr('class', d => {
let classString = 'menuItem';
if (checksExist) {
classString += ' checkPadded';
}
if (d === null) {
classString += ' separator';
} else if (d.checked) {
classString += ' checked';
}
return classString;
});
// Attach / update any events
menuItems.on('click', d => {
if (d !== null && d.onclick) {
d.onclick();
}
});
this.positionMenu();
},
positionMenu: function () {
let menuDiv = d3.select(this.el).select('.menu');
// Move the menu to an appropriate place
let targetBounds = this.menuSpec.targetElement.getBoundingClientRect();
let menuBounds = menuDiv.node().getBoundingClientRect();
if (window.innerWidth - targetBounds.right >= menuBounds.width) {
// Default: put the menu to the right of the target
menuDiv.style('left', targetBounds.right + 'px');
} else if (targetBounds.left >= menuBounds.width) {
// Move it to the left
menuDiv.style('right', (window.innerWidth - targetBounds.left) + 'px');
} else {
// Sheesh, no space. Just put it on the right and let it overlap
menuDiv.style('right', '0px');
}
if (window.innerHeight - targetBounds.top >= menuBounds.height) {
// Default: align the menu to the top of the target
menuDiv.style('top', targetBounds.top + 'px');
} else {
// Sheesh, no space. Just put it on the bottom and let it
// overlap
menuDiv.style('bottom', '0px');
}
}
});
export default Menu;
|
apache-2.0
|
endfalse/EzFramework7
|
Tools/ProjTool/ToEntity/ini.cs
|
1706
|
using System;
using System.Threading;
using System.Windows.Forms;
namespace Ez.ToEntity
{
public partial class ini : Form
{
private Home home;
public ini(Home home)
{
InitializeComponent();
this.home = home;
if (this.home.IniConfigModel != null)
{
tb_namespace.Text = this.home.IniConfigModel.spacename;
cb_ezwork.Checked = this.home.IniConfigModel.ez;
cb_map.Checked = this.home.IniConfigModel.map;
cb_vir.Checked = this.home.IniConfigModel.vir;
}
}
private void btn_save_Click(object sender, EventArgs e)
{
Thread thread = new Thread(() =>
{
this.btn_save.Invoke(new Action(() =>
{
this.btn_save.Enabled = false;
this.btn_save.Text = "保存中..";
if (!string.IsNullOrEmpty(this.tb_namespace.Text.Trim()))
{
this.home.IniConfigModel.spacename = tb_namespace.Text.Trim();
this.home.IniConfigModel.ez = cb_ezwork.Checked;
this.home.IniConfigModel.map = cb_map.Checked;
this.home.IniConfigModel.vir = cb_vir.Checked;
this.home.SaveIniConfig();
this.Close();
this.Dispose();
}
else
{
MessageBox.Show("请正确填写!");
}
}));
});
thread.Start();
}
}
}
|
apache-2.0
|
marcks28/Sistema
|
src/controle/ControleTipoMovimentacao.java
|
1351
|
package controle;
import java.sql.SQLException;
import java.util.List;
import java.util.function.Predicate;
import modelo.TipoMovimentacao;
import modelo.data.TipoMovimentacaoDAL;
import modelo.data.interfaces.IControle;
public class ControleTipoMovimentacao implements IControle<TipoMovimentacao>{
private TipoMovimentacaoDAL dal;
public ControleTipoMovimentacao() {
this.dal = new TipoMovimentacaoDAL();
}
@Override
public void saveUpdate(TipoMovimentacao entity) throws SQLException {
if(entity.getId()>=0)
{
dal.Update(entity);
}else
{
dal.Save(entity);
}
}
@Override
public void delete(TipoMovimentacao entity) throws SQLException {
dal.Delete(entity);
}
@Override
public TipoMovimentacao findById(long id) throws SQLException {
return dal.FindId(id);
}
@Override
public List<TipoMovimentacao> getAll() throws SQLException {
return dal.GetAll();
}
@Override
public List<TipoMovimentacao> getAll(Predicate<TipoMovimentacao> predicate) throws SQLException {
return dal.GetAll(predicate);
}
@Override
public TipoMovimentacao find(Predicate<TipoMovimentacao> predicate) throws SQLException {
return dal.Find(predicate);
}
}
|
apache-2.0
|
google/iree
|
llvm-external-projects/iree-compiler-api/python/iree/compiler/tools/binaries.py
|
10467
|
# Lint-as: python3
"""Utilities for locating and invoking compiler tool binaries."""
# Copyright 2020 The IREE Authors
#
# Licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import importlib
import io
import logging
import os
import platform
import shlex
import subprocess
import sys
import textwrap
import threading
from typing import List, Optional, Union
__all__ = [
"find_tool",
"invoke_immediate",
"invoke_pipeline",
"get_tool_path",
"CompilerToolError",
]
_BUILTIN_TOOLS = [
"ireec",
"iree-lld",
"iree-translate",
]
# In normal distribution circumstances, each named tool is associated with
# a python module that provides a `get_tool` function for getting its absolute
# path. This dictionary maps the tool name to the module.
_TOOL_MODULE_MAP = {
# Note that ireec is builtin, but if not found, it can be resolved
# in the external 'core' module. This is used for some outside packaging
# options.
"ireec": "iree.tools.core",
"iree-lld": "iree.tools.core",
"iree-import-tflite": "iree.tools.tflite",
"iree-import-xla": "iree.tools.xla",
"iree-import-tf": "iree.tools.tf",
}
# Map of tool module to package name as distributed to archives (used for
# error messages).
_TOOL_MODULE_PACKAGES = {
"iree.tools.core": "<none>",
"iree.tools.tf": "iree-tools-tf",
"iree.tools.tflite": "iree-tools-tflite",
"iree.tools.xla": "iree-tools-xla",
}
# Environment variable holding directories to be searched for named tools.
# Delimitted by os.pathsep.
_TOOL_PATH_ENVVAR = "IREE_TOOL_PATH"
# We do complicated logging so retain our own Logger instance.
logger = logging.getLogger(__name__)
class CompilerToolError(Exception):
"""Compiler exception that preserves the command line and error output."""
def __init__(self, process: subprocess.CompletedProcess):
try:
errs = process.stderr.decode("utf-8")
except:
errs = str(process.stderr) # Decode error or other: best we can do.
tool_name = os.path.basename(process.args[0])
super().__init__(f"Error invoking IREE compiler tool {tool_name}\n"
f"Diagnostics:\n{errs}\n\n"
f"Invoked with:\n {tool_name} {' '.join(process.args)}\n\n"
f"Need more information? Set IREE_SAVE_TEMPS=/some/dir "
f"in your environment to save all artifacts and "
f"reproducers.\n")
def get_tool_path() -> List[str]:
"""Returns list of paths to search for tools."""
list_str = os.environ.get(_TOOL_PATH_ENVVAR)
if not list_str:
return []
return list_str.split(os.pathsep)
def find_tool(exe_name: str) -> str:
"""Finds a tool by its (extension-less) executable name.
Args:
exe_name: The name of the executable (extension-less).
Returns:
An absolute path to the tool.
Raises:
ValueError: If the tool is not known or not found.
"""
is_builtin = exe_name in _BUILTIN_TOOLS
if not is_builtin and exe_name not in _TOOL_MODULE_MAP:
raise ValueError(f"IREE compiler tool '{exe_name}' is not a known tool")
# First search an explicit tool path (from environment).
tool_path = get_tool_path()
for path_entry in tool_path:
if not path_entry:
continue
candidate_exe = os.path.join(path_entry, exe_name)
if _is_executable(candidate_exe):
return candidate_exe
if is_builtin:
# Get builtin tool.
candidate_exe = _get_builtin_tool(exe_name)
if _is_executable(candidate_exe):
return candidate_exe
# Fall-through and attempt to find it via a tools module.
# Attempt to load the tool module.
tool_module_name = _TOOL_MODULE_MAP[exe_name]
tool_module_package = _TOOL_MODULE_PACKAGES[tool_module_name]
try:
tool_module = importlib.import_module(tool_module_name)
except ModuleNotFoundError:
raise ValueError(
f"IREE compiler tool '{exe_name}' is not installed (it should have been "
f"found in the python module '{tool_module_name}', typically installed "
f"via the package {tool_module_package}).\n\n"
f"Either install the package or set the {_TOOL_PATH_ENVVAR} environment "
f"variable to contain the path of the tool executable "
f"(current {_TOOL_PATH_ENVVAR} = {repr(tool_path)}).") from None
# Ask the module for its tool.
candidate_exe = tool_module.get_tool(exe_name)
if (not _is_executable(candidate_exe)):
raise ValueError(
f"IREE compiler tool '{exe_name}' was located in module "
f"'{tool_module_name}' but the file was not found or not executable: "
f"{candidate_exe}")
return candidate_exe
def _get_builtin_tool(exe_name: str) -> Optional[str]:
# Transitional note: iree-translate is allowed and resolves to "ireec".
if exe_name == "iree-translate":
exe_name = "ireec"
if platform.system() == "Windows":
exe_name = exe_name + ".exe"
this_path = os.path.dirname(__file__)
tool_path = os.path.join(this_path, "..", "_mlir_libs", exe_name)
return tool_path
def _is_executable(candidate_exe: str) -> bool:
if not candidate_exe:
return False
if not os.path.isfile(candidate_exe):
return False
if not os.access(candidate_exe, os.X_OK):
return False
return True
def invoke_immediate(command_line: List[str],
*,
input_file: Optional[bytes] = None,
immediate_input=None):
"""Invokes an immediate command.
This is separate from invoke_pipeline as it is simpler and supports more
complex input redirection, using recommended facilities for sub-processes
(less magic).
Note that this differs from the usual way of using subprocess.run or
subprocess.Popen().communicate() because we need to pump all of the error
streams individually and only pump pipes not connected to a different stage.
Uses threads to pump everything that is required.
"""
if logger.isEnabledFor(logging.INFO):
logging.info("Invoke IREE Tool: %s", _quote_command_line(command_line))
run_args = {}
input_file_handle = None
stderr_handle = sys.stderr
try:
# Redirect input.
if input_file is not None:
input_file_handle = open(input_file, "rb")
run_args["stdin"] = input_file_handle
elif immediate_input is not None:
run_args["input"] = immediate_input
# Capture output.
# TODO(#4131) python>=3.7: Use capture_output=True.
run_args["stdout"] = subprocess.PIPE
run_args["stderr"] = subprocess.PIPE
process = subprocess.run(command_line, **run_args)
if process.returncode != 0:
raise CompilerToolError(process)
# Emit stderr contents.
_write_binary_stderr(stderr_handle, process.stderr)
return process.stdout
finally:
if input_file_handle:
input_file_handle.close()
def invoke_pipeline(command_lines: List[List[str]], immediate_input=None):
"""Invoke a pipeline of commands.
The first stage of the pipeline will have its stdin set to DEVNULL and each
subsequent stdin will derive from the prior stdout. The final stdout will
be accumulated and returned. All stderr contents are accumulated and printed
to stderr on completion or the first failing stage of the pipeline will have
an exception raised with its stderr output.
"""
logging.info(
"Invoke IREE Pipeline:\n %s",
"\n ".join([_quote_command_line(line) for line in command_lines]))
stages = []
pipeline_input = (subprocess.DEVNULL
if immediate_input is None else subprocess.PIPE)
prev_out = pipeline_input
stderr_handle = sys.stderr
# Create all stages.
for i in range(len(command_lines)):
command_line = command_lines[i]
popen_args = {
"stdin": prev_out,
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
}
process = subprocess.Popen(command_line, **popen_args)
prev_out = process.stdout
capture_output = (i == (len(command_lines) - 1))
stages.append(_PipelineStage(process, capture_output))
# Start stages.
for stage in stages:
stage.start()
# Pump input.
pipe_success = True
if immediate_input is not None:
try:
pipe_success = False
stages[0].process.stdin.write(immediate_input)
pipe_success = True
finally:
stages[0].process.stdin.close()
# Join.
for stage in stages:
stage.join()
# Check for errors.
for stage in stages:
assert stage.completed
if stage.completed.returncode != 0:
raise CompilerToolError(stage.completed)
# Broken pipe.
if not pipe_success:
raise CompilerToolError(stages[0].completed)
# Print any stderr output.
for stage in stages:
_write_binary_stderr(stderr_handle, stage.errs)
return stages[-1].outs
class _PipelineStage(threading.Thread):
"""Wraps a process and pumps its handles, waiting for completion."""
def __init__(self, process, capture_output):
super().__init__()
self.process = process
self.capture_output = capture_output
self.completed: Optional[subprocess.CompletedProcess] = None
self.outs = None
self.errs = None
def pump_stderr(self):
self.errs = self.process.stderr.read()
def pump_stdout(self):
self.outs = self.process.stdout.read()
def run(self):
stderr_thread = threading.Thread(target=self.pump_stderr)
stderr_thread.start()
if self.capture_output:
stdout_thread = threading.Thread(target=self.pump_stdout)
stdout_thread.start()
self.process.wait()
stderr_thread.join()
if self.capture_output:
stdout_thread.join()
self.completed = subprocess.CompletedProcess(self.process.args,
self.process.returncode,
self.outs, self.errs)
self.process.stderr.close()
self.process.stdout.close()
def _write_binary_stderr(out_handle, contents):
# Fast-paths buffered text-io (which stderr is by default) while allowing
# full decode for non buffered and binary io.
if hasattr(out_handle, "buffer"):
out_handle.buffer.write(contents)
elif isinstance(out_handle, io.TextIOBase):
out_handle.write(contents.decode("utf-8"))
else:
out_handle.write(contents)
def _quote_command_line(command_line: List[str]) -> str:
return " ".join([shlex.quote(token) for token in command_line])
|
apache-2.0
|
acisternino/ticket-downloader
|
src/main/java/tido/naming/TicketDirectoryNamer.java
|
5275
|
/*
* Copyright 2013 Andrea Cisternino <a.cisternino@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tido.naming;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import tido.Dialogs.Wait;
import tido.config.ConfigManager;
import tido.model.Ticket;
/**
*
* @author Andrea Cisternino
*/
public class TicketDirectoryNamer
{
private static final Logger log = Logger.getLogger( TicketDirectoryNamer.class.getName() );
/** The application configuration. */
private final ConfigManager config;
/** Base ticket directory. */
private Path baseDir;
/** A simple cache for the generated directory names. */
private final WeakHashMap<Ticket, Path> nameCache = new WeakHashMap<>();
/** The JavaScript engine used to run the name generator function. */
private final ScriptEngine engine;
//---- Lifecycle ---------------------------------------------------------------
/**
* Creates an instance of the TicketDirectorynamer.
*
* @param config the configuration manager of the application.
*/
public TicketDirectoryNamer(final ConfigManager config) {
this.config = config;
// set initial value of the base directory from configuration
baseDir = Paths.get( config.config().getBaseDirectory() );
// JS engine
engine = new ScriptEngineManager().getEngineByName( "javascript" );
try {
// inject some global variables
engine.put( "log", Logger.getAnonymousLogger() );
engine.put( "separator", File.separator );
// this is needed to support string.js
engine.eval( "var window = this;");
// load string.js library (see http://stringjs.com)
evalFromClasspath( "/js/string.min.js" );
// load directory naming script
engine.eval( config.namingScript() );
} catch ( final ScriptException ex ) {
log.log( Level.SEVERE, "in constructor:", ex );
config.getDialogs().jsEngineError( ex, Wait.NO );
}
}
//---- API ---------------------------------------------------------------------
public Path getTicketPath(Ticket ticket) {
// test cache first
Path tp;
if ( nameCache.containsKey( ticket ) ) {
tp = nameCache.get( ticket );
if ( tp != null ) {
log.log( Level.FINE, "found in cache: {0}", tp.toString() );
return tp;
}
}
// use global JS generateName() function to generate the name
String ticketDir = null;
try {
Invocable eng = (Invocable) engine;
ticketDir = (String) eng.invokeFunction( "generateName", ticket );
} catch ( ScriptException | NoSuchMethodException ex ) {
log.log( Level.SEVERE, null, ex );
}
if ( ticketDir == null ) {
tp = backupName( ticket );
log.log( Level.FINE, "js problems; backup name: {0}", tp.toString());
}
else {
tp = baseDir.resolve( ticketDir );
log.log( Level.FINE, "generated: {0}", ticketDir);
}
nameCache.put( ticket, tp );
return tp;
}
/**
* Sets the name of the base directory for the ticket folders.
*
* @param dirName the name of the directory.
*/
public void setBaseDir(Path dirName) {
log.fine( dirName.toString() );
baseDir = dirName;
}
//---- Support methods ---------------------------------------------------------
/**
* Evaluate a script found on the classpath.
*
* @param scriptName the path of the script.
* @return the value returned from the script.
* @throws ScriptException if an error occurs while evaluating the script.
*/
private Object evalFromClasspath(String scriptName) throws ScriptException {
log.fine( scriptName );
InputStream is = getClass().getResourceAsStream( scriptName );
return engine.eval( new InputStreamReader( is ) );
}
/**
* Returns a backup name for the ticket directory in case something goes
* wrong with the JavaScript side.
*
* @param ticket the ticket being processed.
* @return a default Path for the Ticket directory.
*/
private Path backupName(Ticket ticket) {
return baseDir.resolve( ticket.getId() );
}
}
|
apache-2.0
|
denverpost/va-hospital
|
js/functions.js
|
17425
|
var href = location.href.split('/');
href.pop();
var adPathRoot = href.join('/') + '/';
var body = document.body, html = document.documentElement;
var docHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
var swapped = false;
var adsloaded = [];
/* THIS IS CONFIG DATA SPECIFIC TO SITE */
var showAds = true; //show slide-up leaderboards at bottom
var slideAds = 3; //number of times to slide up a leaderboard
var titleFade = true; //whether to fade the Denver Post logo in the top-bar to show the "DP" and a text title
function revealSocial(type,link,title,image,desc,twvia,twrel) {
title = typeof title !== 'undefined' ? title : false;
image = typeof image !== 'undefined' ? image : false;
desc = typeof desc !== 'undefined' ? desc : false;
twvia = typeof twvia !== 'undefined' ? twvia.toString().replace('@','') : false;
twrel = typeof twrel !== 'undefined' ? twrel.toString().replace('@','') : false;
//type can be twitter, facebook or gplus
var srcurl = '';
if (type == 'twitter') {
srcurl = 'http://twitter.com/intent/tweet?text=' + encodeURIComponent(title).replace('|','%7c') + '&url=' + link + '&via=' + twvia + '&related=' + twrel;
} else if (type == 'facebook') {
srcurl = 'http://www.facebook.com/sharer/sharer.php?s=100&p[url]=' + link + '&p[images][0]=' + image + '&p[title]=' + encodeURIComponent(title).replace('|','%7c') + '&p[summary]=' + encodeURIComponent(desc).replace('|','%7c');
} else if (type == 'gplus') {
srcurl = 'https://plus.google.com/share?url=' + link;
}
console.log(srcurl);
if (srcurl.length > 1) {
window.open(srcurl, type, 'left=60,top=60,width=500,height=500,toolbar=1,resizable=1').focus();
}
return false;
}
var videoButtonBack;
function eachButton(button,i) {
$(button[i]).siblings().each(function(){
button[i].style.backgroundColor = '#fff';
document.getElementById('lessontitle').style.visibility = 'hidden';
document.getElementById('lessontitle').innerHTML = '';
});
button[i].style.backgroundColor = '#bbb';
document.getElementById('lessontitle').innerHTML = button[i].getAttribute('data-text');
document.getElementById('lessontitle').style.visibility = 'visible';
var buttonDelay = button[i];
videoButtonBack = setTimeout(function() {
buttonDelay.style.backgroundColor = '#fff';
document.getElementById('lessontitle').style.visibility = 'hidden';
document.getElementById('lessontitle').innerHTML = '';
if (i < button.length) {
eachButton(button,i+1);
} else {
video.load();
}
}, parseInt(button[i].getAttribute('data-length')));
}
function playFragment() {
var video, sources, nav, buttons;
video = document.querySelector('video#lessons');
sources = video.getElementsByTagName('source');
nav = document.querySelector('#lessonnav');
buttons = nav.getElementsByTagName('button');
for (var i = buttons.length - 1; i >= 0; i--) {
buttons[i].addEventListener('click', function() {
for (var i = sources.length - 1; i >= 0; i--) {
sources[i].setAttribute(
'src', (sources[i].getAttribute('data-original')
.concat('#t=' + this.getAttribute('data-start'))));
};
video.load();
video.play();
$(this).siblings().each(function(){
this.style.backgroundColor = '#fff';
document.getElementById('lessontitle').style.visibility = 'hidden';
document.getElementById('lessontitle').innerHTML = '';
});
this.style.backgroundColor = '#bbb';
document.getElementById('lessontitle').innerHTML = this.getAttribute('data-text');
document.getElementById('lessontitle').style.visibility = 'visible';
var buttonDelay = this;
setTimeout(function() {
buttonDelay.style.backgroundColor = '#fff';
document.getElementById('lessontitle').style.visibility = 'hidden';
document.getElementById('lessontitle').innerHTML = '';
}, parseInt(this.getAttribute('data-length')));
if ( $('#lessonplaypause').hasClass('lessonplay') ) {
$('#lessonplaypause').addClass('lessonpause').removeClass('lessonplay');
}
});
};
$('#lessonplaypause').on('click',function(){
if ( $(this).hasClass('lessonplay') ) {
$(this).addClass('lessonpause').removeClass('lessonplay');
for (var i = sources.length - 1; i >= 0; i--) {
sources[i].setAttribute(
'src', (sources[i].getAttribute('data-original')
.concat('#t=' + this.getAttribute('data-start'))));
};
video.load();
video.play();
eachButton(buttons,0);
} else {
$(this).addClass('lessonplay').removeClass('lessonpause');
video.load();
clearTimeout(videoButtonBack);
$(buttons).each(function(){
this.style.backgroundColor = '#fff';
document.getElementById('lessontitle').style.visibility = 'hidden';
document.getElementById('lessontitle').innerHTML = '';
});
}
});
}
playFragment();
var buildButtonBack;
function eachBuildButton(button,i) {
$(button[i]).siblings().each(function(){
button[i].style.backgroundColor = '#fff';
document.getElementById('builddate').style.visibility = 'hidden';
document.getElementById('builddate').innerHTML = '';
});
button[i].style.backgroundColor = '#bbb';
document.getElementById('builddate').innerHTML = button[i].getAttribute('data-text');
document.getElementById('builddate').style.visibility = 'visible';
var buttonDelay = button[i];
document.getElementById('buildimg').src = './img/build/' + button[i].getAttribute('data-img') + '.jpg';
buildButtonBack = setTimeout(function() {
buttonDelay.style.backgroundColor = '#fff';
document.getElementById('builddate').style.visibility = 'hidden';
document.getElementById('builddate').innerHTML = '';
if (i < button.length - 1) {
eachBuildButton(button,i+1);
} else {
$('#buildplaypause').addClass('buildplay').removeClass('buildpause');
clearTimeout(buildButtonBack);
document.getElementById('builddate').src = './img/build/build-title.jpg';
document.getElementById('builddate').innerHTML = '';
}
}, 2000);
}
function playBuilder() {
var image, nav, buttons, origin;
image = document.querySelector('#buildimg');
origin = image.src;
nav = document.querySelector('#buildnav');
buttons = nav.getElementsByTagName('button');
for (var i = buttons.length - 1; i >= 0; i--) {
buttons[i].addEventListener('click', function() {
image.src = './img/build/' + this.getAttribute('data-img') + '.jpg';
$(this).siblings().each(function(){
this.style.backgroundColor = '#fff';
document.getElementById('builddate').style.visibility = 'hidden';
document.getElementById('builddate').innerHTML = '';
});
this.style.backgroundColor = '#bbb';
document.getElementById('builddate').innerHTML = this.getAttribute('data-text');
document.getElementById('builddate').style.visibility = 'visible';
var buttonDelay = this;
setTimeout(function() {
buttonDelay.style.backgroundColor = '#fff';
image.src = './img/build/' + this.getAttribute('data-img') + '.jpg';
document.getElementById('builddate').style.visibility = 'hidden';
document.getElementById('builddate').innerHTML = '';
}, 2000);
});
};
$('#buildplaypause').on('click',function(){
if ( $(this).hasClass('buildplay') ) {
$(this).addClass('buildpause').removeClass('buildplay');
image.src = './img/build/' + this.getAttribute('data-img') + '.jpg';
eachBuildButton(buttons,0);
} else {
$(this).addClass('buildplay').removeClass('buildpause');
clearTimeout(buildButtonBack);
$(buttons).each(function(){
this.style.backgroundColor = '#fff';
document.getElementById('builddate').style.visibility = 'hidden';
document.getElementById('builddate').innerHTML = '';
document.getElementById('buildimg').src = './img/build/build-title.jpg';
document.getElementById('builddate').innerHTML = '';
});
}
});
}
playBuilder();
function graphicOverlay() {
nav = document.querySelector('#graphics');
buttons = nav.getElementsByTagName('button');
for (var i = buttons.length - 1; i >= 0; i--) {
buttons[i].addEventListener('click', function() {
document.getElementById('graphic-legend').style.opacity = '0';
$(this).siblings('button').each(function(){
this.style.backgroundColor = 'rgba(255,255,255,0.7)';
});
this.style.backgroundColor = 'rgba(220,0,0,0.7)';
el = document.getElementById("graphic-over");
elChild = document.getElementById('over-' + this.getAttribute('data-pop'));
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
el.style.opacity = (el.style.opacity == "1") ? "0" : "1";
elChild.style.visibility = (elChild.style.visibility == "visible") ? "hidden" : "visible";
elChild.style.opacity = (elChild.style.opacity == "1") ? "0" : "1";
el.addEventListener('click', function() {
el = document.getElementById("graphic-over");
el.style.visibility = "hidden";
el.style.opacity = "0";
elChildren = el.childNodes;
for(var i=0;i<elChildren.length;i++){
if (elChildren[i].className == "over-hide") {
elChildren[i].style.visibility = "hidden";
elChildren[i].style.opacity = "0";
}
}
nav = document.querySelector('#graphics');
buttons = nav.getElementsByTagName('button');
for (var i = buttons.length - 1; i >= 0; i--) {
buttons[i].style.backgroundColor = 'rgba(255,255,255,0.7)';
}
this.removeEventListener('click');
})
});
};
}
graphicOverlay()
$(document).foundation('reveal', {
animation: 'fade',
animationspeed: 200
});
function revealCredits() {
$('#credits').foundation('reveal', 'open');
}
function checkHash() {
if (window.location.hash) {
var hash = window.location.hash;
if ($(hash).hasClass('hide')) {
toggleSidebar(hash,hash + 'link');
} else {
scrollDownTo(hash);
}
}
}
function scrollDownTo(whereToScroll, scrollOffset) {
scrollOffset = typeof scrollOffset !== 'undefined' ? scrollOffset : 60;
if ($(whereToScroll).length) {
$('html,body').animate({
scrollTop: ($(whereToScroll).offset().top - scrollOffset)
}, 300);
} else {
var new_url = window.location.href.split('#')[0];
window.history.replaceState('', document.title, new_url);
}
}
function toggleSidebar(toShow,toHide) {
$(toShow).removeClass('hide');
$(toHide).addClass('hide');
scrollDownTo(toShow);
}
function playerCreator(embedId, playerId, divId) {
divId = typeof divId !== 'undefined' ? divId : false;
if (divId) {
$(divId).animate({backgroundColor:'rgba(0,70,70,0.3)',paddingLeft:'.5em',paddingRight:'.5em'}, 350).delay(2000).animate({backgroundColor:'transparent',paddingLeft:'0',paddingRight:'0'},1000);
}
OO.Player.create(embedId, playerId, {'autoplay':true});
}
function playerScroller(embedId, playerId, divId) {
scrollDownTo(('#' + embedId),100);
playerCreator(embedId, playerId, divId);
}
function getNodePosition(node) {
var eTop = $(node).offset().top;
return Math.abs(eTop - $(window).scrollTop());
}
function isVisible(element) {
var vidTop = $(element).offset().top;
var vidBot = $(element).offset().top + $(element).height();
var fromTop = $(window).scrollTop() + $(element).height() / 2;
if ( fromTop > vidTop && fromTop < vidBot ) {
return true;
} else {
return false;
}
}
function isElementInViewport(el) {
el = el.toString().replace('#','');
if (document.getElementById(el) != null) {
var rect = document.getElementById(el).getBoundingClientRect();
var half = window.innerHeight / 2;
var whole = window.innerHeight;
return ( (rect.top > 0 && rect.top < half) || (rect.bottom < whole && rect.bottom > half) || (rect.top < 0 && rect.bottom > whole) );
} else {
return;
}
}
$('.top-top').click(function(evt) {
$('.toggle-topbar').click();
});
$('.vid-embed').on("mouseenter", function() {
$(this).find('.playicon').fadeTo(300, 0);
$(this).find('.playtext').fadeTo(300, 1);
});
$('.vid-embed').on("mouseleave", function() {
$(this).find('.playicon').fadeTo(300, 1);
$(this).find('.playtext').fadeTo(300, 0);
});
function fadeNavBar(reverse) {
if (reverse) {
$('#name1').animate({opacity:1},500);
$('#name2').animate({opacity:0},500);
$('#name2').css('z-index','0');
titleFade = true;
} else {
$('#name1').animate({opacity:0},500);
$('#name2').animate({opacity:1},500);
$('#name2').css('z-index','3');
titleFade = false;
}
}
function checkFade() {
if ( !($(window).scrollTop() < window.innerHeight) && titleFade ) {
fadeNavBar(false);
} else if ( ($(window).scrollTop() < window.innerHeight) && !titleFade) {
fadeNavBar(true);
}
}
function hideAdManual() {
$('#adwrapper').fadeOut(300);
$('#adwrapper a.boxclose').css('display', 'none');
$('#footer-bar').delay(150).animate({marginBottom:'0'},300);
$('#adframewrapper').html('');
swapped = false;
}
$(document).keyup(function(e) {
if (swapped && e.keyCode == 27) {
hideAdManual();
}
if ( e.keyCode == 27 && document.getElementById("graphic-over").style.visibility == 'visible' ) {
el = document.getElementById("graphic-over");
el.style.visibility = "hidden";
el.style.opacity = "0";
elChildren = el.childNodes;
for(var i=0;i<elChildren.length;i++){
if (elChildren[i].className == "over-hide") {
console.log(elChildren[i]);
elChildren[i].style.visibility = "hidden";
elChildren[i].style.opacity = "0";
}
}
for (var i = buttons.length - 1; i >= 0; i--) {
buttons[i].style.backgroundColor = 'rgba(255,255,255,0.7)';
}
el.removeEventListener('click');
}
});
$('#timeline').scroll(function(){
$(this).find('.gridphotograd').animate({opacity:'0'},400,function(){
$(this).css('display','none');
});
});
function getAdSize() {
if ( $(window).width() >= 740 ) {
var adSizes = ['ad=medium','728','90'];
return adSizes;
} else {
return false;
}
/* else if ( $(window).width() >= 300 && $(window).width() < 740 ) {
var adSizes = ['ad=small','300','50'];
return adSizes;
}*/
}
function showAd() {
var adSize = getAdSize();
if (adSize) {
$('#adframewrapper').html('<iframe src="' + adPathRoot + 'ad.html?' + adSize[0] + '" seamless height="' + adSize[2] + '" width="' + adSize[1] + '" frameborder="0"></iframe>');
$('#adwrapper').fadeIn(400);
$('a.boxclose').fadeIn(400);
var adH = $('#adwrapper').height();
$('#footer-bar').css('margin-bottom',adH);
swapped = true;
}
}
function swapAd() {
if (swapped) {
hideAdManual();
}
if (!swapped) {
showAd();
}
}
function getAdTimes(numAds) {
var adReturns = [];
var chunkHeight = docHeight / numAds;
var chunkHalf = chunkHeight / 2;
for (i=0;i<numAds;i++) {
adReturns.push( Math.round( chunkHalf + (chunkHeight * i) ) );
}
return adReturns;
}
function checkAdPos() {
if (showAds) {
var topNow = $(window).scrollTop();
if (!swapped) {
var adTimes = getAdTimes(slideAds);
for (var i = 0; i < adTimes.length; i++) {
if (!adsloaded[i] && topNow > adTimes[i] && topNow < (typeof adTimes[(i+1)] !== 'undefined' ? adTimes[(i+1)] : docHeight)) {
swapAd();
adsloaded[i] = true;
break;
}
}
}
}
}
$(document).ready(function() {
checkHash();
checkFade();
checkAdPos();
});
var didScroll = false;
$(window).scroll(function() {
didScroll = true;
});
setInterval(function() {
if (didScroll) {
checkFade();
checkAdPos();
}
},250);
|
apache-2.0
|
huangjianke/Gitter
|
src/pages/account/follow.js
|
3351
|
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { GLOBAL_CONFIG } from '../../constants/globalConfig'
import FollowItem from '../../components/account/followItem'
import { REFRESH_STATUS } from '../../constants/status'
import Empty from '../../components/index/empty'
import LoadMore from '../../components/common/loadMore'
import './follow.less'
import api from "../../service/api";
class Follow extends Component {
config = {
enablePullDownRefresh: true
}
constructor(props) {
super(props)
this.state = {
url: '',
page: 1,
dataList: [],
refresh_status: REFRESH_STATUS.NORMAL
}
}
componentWillReceiveProps (nextProps) {
console.log(this.props, nextProps)
}
componentWillMount() {
let params = this.$router.params
let type = params.type
let username = params.username
let url = ''
let title = ''
if (type === 'followers') {
// Followers
url = '/user/followers'
if (username) {
url = '/users/' + username + '/followers'
}
title = 'Followers'
} else if (type === 'following') {
// Following
url = '/user/following'
if (username) {
url = '/users/' + username + '/following'
}
title = 'Following'
}
Taro.setNavigationBarTitle({
title: title
})
this.setState({
url: url
})
}
componentDidMount() {
Taro.showLoading({title: GLOBAL_CONFIG.LOADING_TEXT})
this.getDataist()
}
componentWillUnmount () { }
componentDidShow () { }
componentDidHide () { }
handleClickedItem(item) {
Taro.navigateTo({
url: '/pages/account/developerInfo?username=' + item.login
})
}
onPullDownRefresh() {
let that = this
this.setState({
page: 1
}, ()=>{
that.getDataist()
})
}
onReachBottom() {
const { page, refresh_status } = this.state
if (refresh_status !== REFRESH_STATUS.NO_MORE_DATA) {
let that = this
this.setState({
page: page + 1
}, ()=>{
that.getDataist()
})
}
}
getDataist() {
let that = this
const { url, page, dataList } = this.state
if (page !== 1) {
that.setState({
refresh_status: REFRESH_STATUS.REFRESHING
})
}
let params = {
page: page,
per_page: GLOBAL_CONFIG.PER_PAGE
}
api.get(url, params).then((res)=>{
if (page === 1) {
that.setState({
dataList: res.data
})
} else {
that.setState({
dataList: dataList.concat(res.data)
})
}
let status = res.data.length < GLOBAL_CONFIG.PER_PAGE ? REFRESH_STATUS.NO_MORE_DATA : REFRESH_STATUS.NORMAL
that.setState({
refresh_status: status
})
Taro.stopPullDownRefresh()
Taro.hideLoading()
})
}
render () {
const { dataList, refresh_status } = this.state
const itemList = dataList.map((item, index) => {
return (
<View onClick={this.handleClickedItem.bind(this, item)} key={index}>
<FollowItem item={item} />
</View>
)
})
return (
<View className='content'>
{dataList.length > 0 ? itemList : <Empty />}
<LoadMore status={refresh_status} />
</View>
)
}
}
export default Follow
|
apache-2.0
|
ausaccessfed/saml-service
|
db/migrate/20151204023033_add_flags_to_raw_entity_descriptors.rb
|
251
|
Sequel.migration do
change do
alter_table :raw_entity_descriptors do
add_column :idp, TrueClass, default: false
add_column :sp, TrueClass, default: false
add_column :standalone_aa, TrueClass, default: false
end
end
end
|
apache-2.0
|
nirvanesque/g5k-api
|
app/controllers/environments_controller.rb
|
862
|
# Copyright (c) 2009-2011 Cyril Rohr, INRIA Rennes - Bretagne Atlantique
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'resources_controller'
class EnvironmentsController < ResourcesController
protected
def collection_path
if params[:site_id]
site_environments_path(params[:site_id])
else
environments_path
end
end
end
|
apache-2.0
|
transcendent-ai-labs/DynaML
|
dynaml-core/src/main/scala/io/github/mandar2812/dynaml/prototype/Measure.scala
|
986
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.mandar2812.dynaml.prototype
/**
* Trait which outlines basic behavior
* of a subset utility measure.
*/
trait Measure[T] {
def evaluate(data: List[T]): Double
}
|
apache-2.0
|
jmarin/mesos-proxy
|
src/main/scala/mesos/dns/client/MesosClient.scala
|
870
|
package mesos.dns.client
import akka.actor.ActorSystem
import akka.event.{ Logging, LoggingAdapter }
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import mesos.dns.client.http.HttpService
import scala.concurrent.ExecutionContextExecutor
object MesosClient extends App with HttpService {
override implicit val system: ActorSystem = ActorSystem("mesos-proxy")
override val log: LoggingAdapter = Logging(system, getClass)
override implicit val executor: ExecutionContextExecutor = system.dispatcher
override implicit val materializer: ActorMaterializer = ActorMaterializer()
override val config = ConfigFactory.load()
val host = config.getString("mesos.proxy.host")
val port = config.getInt("mesos.proxy.port")
val http = Http(system).bindAndHandle(
routes,
host,
port
)
}
|
apache-2.0
|
consulo/consulo-android
|
tools-base/sdk-common/src/main/java/com/android/ide/common/blame/parser/LegacyNdkOutputParser.java
|
9586
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ide.common.blame.parser;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.ide.common.blame.Message;
import com.android.ide.common.blame.SourceFilePosition;
import com.android.ide.common.blame.SourcePosition;
import com.android.ide.common.blame.parser.util.OutputLineReader;
import com.android.utils.ILogger;
import com.android.utils.SdkUtils;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import java.io.File;
import java.util.List;
/**
* Parses output from the legacy NDK support.
*/
public class LegacyNdkOutputParser implements PatternAwareOutputParser {
private static final String FROM = "from";
private static final String UNKNOWN_MSG_PREFIX1 = "In file included " + FROM;
private static final String UNKNOWN_MSG_PREFIX2 = " " + FROM;
private static final char COLON = ':';
@Override
public boolean parse(@NonNull String line, @NonNull OutputLineReader reader,
@NonNull List<Message> messages, @NonNull ILogger logger)
throws ParsingFailedException {
// Parses unknown message
if (line.startsWith(UNKNOWN_MSG_PREFIX1) || line.startsWith(UNKNOWN_MSG_PREFIX2)) {
int fromIndex = line.indexOf(FROM);
String unknownMsgCause = line.substring(0, fromIndex).trim();
unknownMsgCause = "(Unknown) " + unknownMsgCause;
String coordinates = line.substring(fromIndex + FROM.length()).trim();
if (!coordinates.isEmpty()) {
int colonIndex1 = line.indexOf(COLON);
if (colonIndex1 == 1) { // drive letter (Windows)
coordinates = coordinates.substring(colonIndex1 + 1);
}
if (coordinates.endsWith(",") || coordinates.endsWith(":")) {
coordinates = coordinates.substring(0, coordinates.length() - 1);
}
List<String> segments = Splitter.on(COLON).splitToList(coordinates);
if (segments.size() == 3) {
String pathname = segments.get(0);
File file = new File(pathname);
int lineNumber = 0;
try {
lineNumber = Integer.parseInt(segments.get(1));
}
catch (NumberFormatException ignore) {
}
int column = 0;
try {
column = Integer.parseInt(segments.get(2));
}
catch (NumberFormatException ignore) {
}
SourceFilePosition position = new SourceFilePosition(file,
new SourcePosition(lineNumber - 1, column - 1, -1));
Message message = new Message(Message.Kind.INFO, unknownMsgCause.trim(), position);
if (!messages.contains(message)) {
// There may be a few duplicate "unknown" messages
addMessage(message, messages);
}
}
}
return true;
}
// Parses unresolved include.
int colonIndex1 = line.indexOf(COLON);
if (colonIndex1 == 1) { // drive letter (Windows)
colonIndex1 = line.indexOf(COLON, colonIndex1 + 1);
}
if (colonIndex1 >= 0) { // looks like found something like a file path.
String part1 = line.substring(0, colonIndex1).trim();
int colonIndex2 = line.indexOf(COLON, colonIndex1 + 1);
if (colonIndex2 >= 0) {
File file = new File(part1);
if (!file.isFile()) {
// the part one is not a file path.
return false;
}
try {
int lineNumber = Integer.parseInt(
line.substring(colonIndex1 + 1, colonIndex2).trim()); // 1-based.
int colonIndex3 = line.indexOf(COLON, colonIndex2 + 1);
if (colonIndex1 >= 0) {
int column = Integer.parseInt(
line.substring(colonIndex2 + 1, colonIndex3).trim());
int colonIndex4 = line.indexOf(COLON, colonIndex3 + 1);
if (colonIndex4 >= 0) {
Message.Kind kind = Message.Kind.INFO;
String severity =
line.substring(colonIndex3 + 1, colonIndex4).toLowerCase()
.trim();
if (severity.endsWith("error")) {
kind = Message.Kind.ERROR;
} else if (severity.endsWith("warning")) {
kind = Message.Kind.WARNING;
}
String text = line.substring(colonIndex4 + 1).trim();
List<String> messageList = Lists.newArrayList();
messageList.add(text);
String prevLine = null;
do {
String nextLine = reader.readLine();
if (nextLine == null) {
return false;
}
if (nextLine.trim().equals("^")) {
String messageEnd = reader.readLine();
while (isMessageEnd(messageEnd)) {
messageList.add(messageEnd.trim());
messageEnd = reader.readLine();
}
if (messageEnd != null) {
reader.pushBack(messageEnd);
}
break;
}
if (prevLine != null) {
messageList.add(prevLine);
}
prevLine = nextLine;
} while (true);
if (column >= 0) {
messageList = convertMessages(messageList);
StringBuilder buf = new StringBuilder();
for (String m : messageList) {
if (buf.length() > 0) {
buf.append(SdkUtils.getLineSeparator());
}
buf.append(m);
}
Message msg = new Message(kind, buf.toString(),
new SourceFilePosition(file,
new SourcePosition(lineNumber - 1, column - 1, -1)));
if (!messages.contains(msg)) {
addMessage(msg, messages);
}
return true;
}
}
}
} catch (NumberFormatException ignored) {
}
}
}
return false;
}
private static void addMessage(@NonNull Message message, @NonNull List<Message> messages) {
boolean duplicatesPrevious = false;
int messageCount = messages.size();
if (messageCount > 0) {
Message lastMessage = messages.get(messageCount - 1);
duplicatesPrevious = lastMessage.equals(message);
}
if (!duplicatesPrevious) {
messages.add(message);
}
}
private static boolean isMessageEnd(@Nullable String line) {
return line != null && !line.isEmpty() && Character.isWhitespace(line.charAt(0));
}
@NonNull
private static List<String> convertMessages(@NonNull List<String> messages) {
if (messages.size() <= 1) {
return messages;
}
final String line0 = messages.get(0);
final String line1 = messages.get(1);
final int colonIndex = line1.indexOf(':');
if (colonIndex > 0) {
String part1 = line1.substring(0, colonIndex).trim();
// jikes
if ("symbol".equals(part1)) {
String symbol = line1.substring(colonIndex + 1).trim();
messages.remove(1);
if (messages.size() >= 2) {
messages.remove(1);
}
messages.set(0, line0 + " " + symbol);
}
}
return messages;
}
}
|
apache-2.0
|
sunlin901203/example-java
|
src/main/java/javas/design/decorator/MochaDecorator.java
|
701
|
package javas.design.decorator;
/**
* @author sunny
* @version 1.0.0
* @since 2013-7-17
*/
public class MochaDecorator extends CondimentDecorator {
private Beverage beverage;
public MochaDecorator(Beverage beverage) {
this.beverage = beverage;
description = "Mocha";
price = 350D;
}
public double cost() {
return price + beverage.cost();
}
@Override
public String getDescription() {
return beverage.getDescription() + "," + description;
}
@Override
public void setSize(String size) {
beverage.setSize(size);
}
@Override
public String getSize() {
return beverage.getSize();
}
}
|
apache-2.0
|
uboot/stromx-opencv
|
stromx/cvimgproc/test/FloodFillTest.cpp
|
1607
|
#include "stromx/cvimgproc/test/FloodFillTest.h"
#include <stromx/runtime/OperatorException.h>
#include <stromx/runtime/ReadAccess.h>
#include "stromx/cvsupport/Image.h"
#include "stromx/cvimgproc/FloodFill.h"
CPPUNIT_TEST_SUITE_REGISTRATION (stromx::cvimgproc::FloodFillTest);
namespace stromx
{
namespace cvimgproc
{
void FloodFillTest::setUp()
{
m_operator = new stromx::runtime::OperatorTester(new FloodFill);
}
void FloodFillTest::tearDown()
{
delete m_operator;
}
void FloodFillTest::testInPlace0()
{
m_operator->initialize();
m_operator->activate();
runtime::DataContainer src(new cvsupport::Image("circle.png", cvsupport::Image::GRAYSCALE));
runtime::UInt32 seedPointX(20);
runtime::UInt32 seedPointY(10);
runtime::Float64 newVal(125.0);
m_operator->setInputData(FloodFill::INPUT_SRC, src);
m_operator->setParameter(FloodFill::PARAMETER_SEED_POINT_X, seedPointX);
m_operator->setParameter(FloodFill::PARAMETER_SEED_POINT_Y, seedPointY);
m_operator->setParameter(FloodFill::PARAMETER_NEW_VAL, newVal);
runtime::DataContainer srcResult = m_operator->getOutputData(FloodFill::OUTPUT_SRC);
runtime::ReadAccess srcAccess(srcResult);
cvsupport::Image::save("FloodFillTest_testInPlace0_src.png", srcAccess.get<runtime::Image>());
}
} // cvimgproc
} // stromx
|
apache-2.0
|
CustomizedTools/CustomizedTools-jar
|
core/src/main/java/com/customized/tools/util/BundleUtil.java
|
8770
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.customized.tools.util;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class BundleUtil {
/**
* The product properties used to override default localized text.
*/
static protected ResourceBundle productProps;
/**
* The name of the resource bundle.
*/
private final String bundleName;
/**
* The {@link ResourceBundle}for localization; initialized in the constructor.
*/
private final ResourceBundle bundle;
protected final String pluginId;
public interface Event {
//String id();
}
/**
* Return the {@link BundleUtil} for the class. The bundle must be in the same package or a parent package of the class.
* @param clazz
* @return
*/
public static BundleUtil getBundleUtil(Class<?> clazz) {
String packageName = clazz.getPackage().getName();
while (true) {
//scan up packages until found
String bundleName = packageName + ".i18n"; //$NON-NLS-1$
try {
ResourceBundle bundle = ResourceBundle.getBundle(bundleName, Locale.getDefault(), clazz.getClassLoader());
return new BundleUtil(packageName, bundleName, bundle);
} catch (MissingResourceException e) {
int index = packageName.lastIndexOf('.');
if (index < 0) {
throw e;
}
packageName = packageName.substring(0, index);
}
}
}
/**
* Construct an instance of this class by specifying the plugin ID.
*
* @param pluginId
* the identifier of the plugin for which this utility is being instantiated
* @param bundleName
* the name of the resource bundle; used for problem reporting purposes only
* @param bundle
* the resource bundle
*/
public BundleUtil(final String pluginId, final String bundleName, final ResourceBundle bundle) {
this.pluginId = pluginId;
this.bundleName = bundleName;
this.bundle = bundle;
}
/**
* Get the string identified by the given key and localized to the current locale.
*
* @param key
* the key in the resource file
* @return the localized String, or <code>
* "Missing message: " + key + " in: " + this.bundleName
* </code> if the string could
* not be found in the current locale, or <code>
* "No message available"
* </code> if the <code>key</code> is null.
*/
public String getString(final String key) {
try {
// Since this string has no parameters, it will not be run through MessageFormat.
// MessageFormat eliminates double ticks, so the next two lines replace double ticks
// with single ticks. This is only needed if the localized string contains double ticks
// (the policy is that localized strings without parameters should not).
// COMMENTED OUT BECAUSE OF POLICY
//char[] messageWithNoDoubleQuotes = CharOperation.replace(text.toCharArray(), DOUBLE_QUOTES, SINGLE_QUOTE);
//text = new String(messageWithNoDoubleQuotes);
String value = getProductValue(key);
return ((value == null) ? this.bundle.getString(key) : value);
} catch (final Exception err) {
String msg;
if (err instanceof NullPointerException) {
msg = "<No message available>"; //$NON-NLS-1$
} else if (err instanceof MissingResourceException) {
msg = "<Missing message for key \"" + key + "\" in: " + this.bundleName + '>'; //$NON-NLS-1$ //$NON-NLS-2$
} else {
msg = err.getLocalizedMessage();
}
// RMH: See DataAccessPlugin.ResourceLocator.getString(...) method, which tries one bundle before
// delegating to another. Therefore, this will happen normally in some situations.
//log(msg);
return msg;
}
}
/**
* Obtains the value that is overriding the default value.
* @param theKey the key whose product value is being requested
* @return the value or <code>null</code> if not overridden by the product
*/
private String getProductValue(String theKey) {
String result = null;
if ((productProps != null) && !StringUtil.isEmpty(theKey)) {
String key = this.pluginId + '.' + theKey;
try {
result = productProps.getString(key);
} catch (MissingResourceException theException) {
// not found in product properties
}
}
return result;
}
/**
* Determines if the given key exists in the resource file.
*
* @param key
* the key in the resource file
* @return True if the key exists.
* @since 4.0
*/
public boolean keyExists(final String key) {
try {
return ((getProductValue(key) != null) || (this.bundle.getString(key) != null));
} catch (final Exception err) {
return false;
}
}
/**
* Get the string identified by the given key and localized to the current locale, and replace placeholders in the localized
* string with the string form of the parameters.
*
* @param key
* the key in the resource file
* @param parameters
* the list of parameters that should replace placeholders in the localized string (e.g., "{0}", "{1}", etc.)
* @return the localized String, or <code>
* "Missing message: " + key + " in: " + this.bundleName
* </code> if the string could
* not be found in the current locale, or <code>
* "No message available"
* </code> if the <code>key</code> is null.
*/
public String getString(final String key, final List parameters) {
if (parameters == null) {
return getString(key);
}
return getString(key, parameters.toArray());
}
/**
* Get the string identified by the given key and localized to the current locale, and replace placeholders in the localized
* string with the string form of the parameters.
*
* @param key
* the key in the resource file
* @param parameters
* the list of parameters that should replace placeholders in the localized string (e.g., "{0}", "{1}", etc.)
* @return the localized String, or <code>
* "Missing message: " + key + " in: " + this.bundleName
* </code> if the string could
* not be found in the current locale, or <code>
* "No message available"
* </code> if the <code>key</code> is null.
*/
public String getString(final String key, final Object... parameters) {
String text = getString(key);
// Check the trivial cases ...
if (text == null) {
return '<' + key + '>';
}
if (parameters == null || parameters.length == 0) {
return text;
}
return MessageFormat.format(text, parameters);
}
public String gs(final String key, final Object... parameters) {
return getString(key, parameters);
}
public String gs(final Event key, final Object... parameters) {
StringBuilder sb = new StringBuilder();
sb.append(key);
sb.append(" "); //$NON-NLS-1$
sb.append(getString(key.toString(), parameters));
return sb.toString();
}
public String getStringOrKey(final String key) {
ArgCheck.isNotNull(key);
String value = getProductValue(key);
if (value == null) {
try {
return this.bundle.getString(key);
} catch (final MissingResourceException err) {
return key;
}
}
return value;
}
}
|
apache-2.0
|
BiyuHuang/CodePrototypesDemo
|
demo/ScalaDemo/src/main/scala/com/wallace/demo/app/multithread/MultiThreadTestDemo.scala
|
1448
|
package com.wallace.demo.app.multithread
import java.util.concurrent.{ExecutorService, Executors}
import com.wallace.demo.app.common.LogSupport
/**
* com.wallace.demo.app.multithread
* Created by 10192057 on 2017/10/18 0018.
*/
object MultiThreadTestDemo extends LogSupport {
private val maxPoolSize: Int = Runtime.getRuntime.availableProcessors()
private val currentPoolSize: Int = Math.min(maxPoolSize, 5)
def main(args: Array[String]): Unit = {
//创建线程池
log.info(s"Thread Pool Size: $currentPoolSize")
val threadPool: ExecutorService = Executors.newFixedThreadPool(currentPoolSize)
try {
//提交5个线程
for (i <- 1 to 5) {
//threadPool.submit(new ThreadDemo("thread"+i))
threadPool.execute(new ThreadDemo("thread" + i))
}
} finally {
threadPool.shutdown()
}
}
//定义线程类,每打印一次睡眠100毫秒
class ThreadDemo(threadName: String) extends Runnable {
override def run(): Unit = {
val threadId = Thread.currentThread().getId
for (_ <- 1 to 10) {
log.info(threadName + "|" + threadId)
Thread.sleep(100)
}
val state: Thread.State = Thread.currentThread().getState
val symbol: Boolean = Thread.currentThread().isAlive
log.info(s"Thread State: $state, Thread Symbol: $symbol, Thread Name: $threadName, Thread ID: $threadId")
}
}
}
|
apache-2.0
|
cjqian/traffic_control
|
traffic_router/core/src/main/java/com/comcast/cdn/traffic_control/traffic_router/core/util/PeriodicResourceUpdater.java
|
9553
|
/*
* Copyright 2015 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.comcast.cdn.traffic_control.traffic_router.core.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.channels.FileLock;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.wicket.ajax.json.JSONException;
import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
/**
*
* @author jlaue
*
*/
public class PeriodicResourceUpdater {
private static final Logger LOGGER = Logger.getLogger(PeriodicResourceUpdater.class);
private static final AsyncHttpClient asyncHttpClient;
static {
final AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder()
.setConnectionTimeoutInMs(10000)
// .addRequestFilter(new ThrottleRequestFilter(10))
.build();
asyncHttpClient = new AsyncHttpClient(cf);
}
protected int urlSelectStrategy = 0; // 0 = ordered, 1 = random select
protected int lastSuccessfulUrl = 0;
protected String databaseLocation;
protected final ResourceUrl urls;
static protected ScheduledExecutorService executorService;
protected long pollingInterval;
protected boolean sourceCompressed = true;
protected ScheduledFuture<?> scheduledService;
public PeriodicResourceUpdater(final AbstractUpdatable listener, final ResourceUrl urls,
final String location, final long interval, final boolean pauseTilLoaded) {
this.listener = listener;
this.urls = urls;
databaseLocation = location;
pollingInterval = interval;
this.pauseTilLoaded = pauseTilLoaded;
}
public PeriodicResourceUpdater(final AbstractUpdatable listener, final String[] urla,
final String location, final int interval, final boolean pauseTilLoaded) {
this.listener = listener;
this.urls = new MyResourceUrl(urla);
databaseLocation = location;
pollingInterval = interval;
this.pauseTilLoaded = pauseTilLoaded;
}
static class MyResourceUrl implements ResourceUrl{
private final String[] urla;
private int i = 0;
public MyResourceUrl(final String[] urla) {
this.urla = urla;
}
@Override
public String nextUrl() {
i++;
i %= urla.length;
return urla[i];
}
}
public PeriodicResourceUpdater(final AbstractUpdatable listener,
final ResourceUrl urls, final String location,
final int interval, final boolean pauseTilLoaded) {
this.listener = listener;
this.urls = urls;
databaseLocation = location;
pollingInterval = interval;
this.pauseTilLoaded = pauseTilLoaded;
}
static {
executorService = java.util.concurrent.Executors.newSingleThreadScheduledExecutor();
}
static public void destroy() {
executorService.shutdownNow();
while(!asyncHttpClient.isClosed()) {
LOGGER.warn("closing");
asyncHttpClient.close();
}
}
/**
* Gets pollingInterval.
*
* @return the pollingInterval
*/
public long getPollingInterval() {
if(pollingInterval == 0) { return 66000; }
return pollingInterval;
}
final private Runnable updater = new Runnable() {
@Override
public void run() {
updateDatabase();
}
};
private boolean hasBeenLoaded = false;
final private AbstractUpdatable listener;
final private boolean pauseTilLoaded;
// private Object future;
public void init() {
putCurrent();
LOGGER.warn("Starting schedule with interval: "+getPollingInterval() + " : "+TimeUnit.MILLISECONDS);
scheduledService = executorService.scheduleWithFixedDelay(updater, 0, getPollingInterval(), TimeUnit.MILLISECONDS);
// wait here until something is loaded
final File existingDB = new File(databaseLocation);
if(pauseTilLoaded ) {
while(!existingDB.exists()) {
LOGGER.warn("Waiting for valid: "+databaseLocation );
try {
Thread.sleep(getPollingInterval());
} catch (InterruptedException e) {
}
}
}
}
private void putCurrent() {
final File existingDB = new File(databaseLocation);
if(existingDB.exists()) {
try {
listener.update(IOUtils.toString(new FileReader(existingDB)));
} catch (Exception e) {
LOGGER.warn(e,e);
}
}
}
public boolean updateDatabase() {
final File existingDB = new File(databaseLocation);
try {
if (!hasBeenLoaded || needsUpdating(existingDB)) {
// future =
asyncHttpClient.executeRequest(getRequest(urls.nextUrl()), updateHandler);
return true;
} else {
LOGGER.info("Database " + existingDB.getAbsolutePath() + " does not require updating.");
}
} catch (final Exception e) {
LOGGER.warn(e.getMessage(), e);
}
return false;
}
public boolean updateDatabase(final String newDB) {
final File existingDB = new File(databaseLocation);
try {
if (newDB != null && !filesEqual(existingDB, newDB)) {
LOGGER.debug("updating " + listener);
if (listener.update(newDB)) {
copyDatabase(existingDB, newDB);
LOGGER.info("updated " + existingDB.getAbsolutePath());
listener.setLastUpdated(System.currentTimeMillis());
listener.complete();
} else {
LOGGER.warn("File rejected: " + existingDB.getAbsolutePath());
}
} else {
listener.noChange();
LOGGER.debug("File unchanged: " + existingDB.getAbsolutePath());
}
hasBeenLoaded = true;
return true;
} catch (final Exception e) {
LOGGER.warn(e.getMessage(), e);
}
return false;
}
public void setDatabaseLocation(final String databaseLocation) {
this.databaseLocation = databaseLocation;
}
// public void setDataBaseURL(final Model<String> url, final long refresh) {
// if(refresh !=0 && refresh != pollingInterval) {
// scheduledService.cancel(false);
// this.pollingInterval = refresh;
// LOGGER.info("restarting schedule with interval: "+refresh);
// init();
// }
// if ((url != null) && !url.equals(dataBaseURL)
// || (refresh!=0 && refresh!=pollingInterval)) {
// this.dataBaseURL = url;
// updateDatabase();
// }
// }
/**
* Sets executorService.
*
* @param executorService
* the executorService to set
*/
public void setExecutorService(final ScheduledExecutorService es) {
executorService = es;
}
/**
* Sets pollingInterval.
*
* @param pollingInterval
* the pollingInterval to set
*/
public void setPollingInterval(final long pollingInterval) {
this.pollingInterval = pollingInterval;
}
boolean filesEqual(final File a, final String newDB) throws IOException {
if(!a.exists() && newDB == null) { return true; }
if(!a.exists() || newDB == null) { return false; }
if(a.length() != newDB.length()) { return false; }
final FileInputStream fis = new FileInputStream(a);
final String md5a = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
fis.close();
final InputStream is = IOUtils.toInputStream(newDB);
final String md5b = org.apache.commons.codec.digest.DigestUtils.md5Hex(is);
is.close();
if(md5a.equals(md5b)) { return true; }
return false;
}
protected void copyDatabase(final File existingDB, final String newDB) throws IOException {
final StringReader in = new StringReader(newDB);
final FileOutputStream out = new FileOutputStream(existingDB);
final FileLock lock = out.getChannel().tryLock();
if (lock != null) {
LOGGER.debug("Updating database " + existingDB.getAbsolutePath());
IOUtils.copy(in, out);
existingDB.setReadable(true, false);
existingDB.setWritable(true, true);
lock.release();
} else {
LOGGER.info("Database " + existingDB.getAbsolutePath() + " locked by another process.");
}
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
protected boolean needsUpdating(final File existingDB) {
final long now = System.currentTimeMillis();
final long fileTime = existingDB.lastModified();
final long pollingIntervalInMS = getPollingInterval();
return ((fileTime + pollingIntervalInMS) < now);
}
final private UpdateHandler updateHandler = new UpdateHandler();;
Request request;
private class UpdateHandler extends AsyncCompletionHandler<java.lang.Object> {
public UpdateHandler() {
}
@Override
public Integer onCompleted(final Response response) throws JSONException, IOException {
// Do something with the Response
final int code = response.getStatusCode();
if(code != 200) {
return code;
}
updateDatabase(response.getResponseBody());
return code;
}
@Override
public void onThrowable(final Throwable t){
if(LOGGER.isDebugEnabled()) {
LOGGER.warn(t,t);
} else {
LOGGER.warn(t);
}
}
};
private Request getRequest(final String url) {
LOGGER.debug("Creating request for " + url);
return asyncHttpClient.prepareGet(url).build();
}
}
|
apache-2.0
|
oehme/analysing-gradle-performance
|
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p481/Production9632.java
|
1963
|
package org.gradle.test.performance.mediummonolithicjavaproject.p481;
public class Production9632 {
private Production9629 property0;
public Production9629 getProperty0() {
return property0;
}
public void setProperty0(Production9629 value) {
property0 = value;
}
private Production9630 property1;
public Production9630 getProperty1() {
return property1;
}
public void setProperty1(Production9630 value) {
property1 = value;
}
private Production9631 property2;
public Production9631 getProperty2() {
return property2;
}
public void setProperty2(Production9631 value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
}
|
apache-2.0
|
cyanide-studio/dialog
|
Dev/DialogueEditorDLL/Sources/Panels/PanelProperties.cs
|
6734
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
namespace DialogueEditor
{
public partial class PanelProperties : DockContent
{
//--------------------------------------------------------------------------------------------------------------
// Class Methods
public PanelProperties()
{
InitializeComponent();
}
public void Clear()
{
if (layoutPanel.Controls.Count > 0)
{
//Copy the controls into an array, since the Dispose calls will remove them from the source list
UserControl[] properties = new UserControl[layoutPanel.Controls.Count];
layoutPanel.Controls.CopyTo(properties, 0);
foreach (UserControl property in properties)
{
IFormProperties propertyBase = property as IFormProperties;
if (propertyBase != null)
propertyBase.Clear();
}
layoutPanel.Controls.Clear();
}
}
public void ShowDialogueNodeProperties(DocumentDialogue document, TreeNode treeNode, DialogueNode dialogueNode)
{
//SetDoubleBuffered(LayoutPanel);
WIN32.StopRedraw(this);
//SuspendLayout();
Clear();
if (dialogueNode is DialogueNodeRoot)
{
DialogueNodeRoot castNode = dialogueNode as DialogueNodeRoot;
FormPropertiesRoot properties = new FormPropertiesRoot();
properties.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(properties);
FormPropertiesCommon propertiesCommon = new FormPropertiesCommon();
propertiesCommon.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(propertiesCommon);
}
else if (dialogueNode is DialogueNodeSentence)
{
DialogueNodeSentence castNode = dialogueNode as DialogueNodeSentence;
FormPropertiesSentence properties = new FormPropertiesSentence();
properties.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(properties);
FormPropertiesCommon propertiesCommon = new FormPropertiesCommon();
propertiesCommon.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(propertiesCommon);
}
else if (dialogueNode is DialogueNodeChoice)
{
DialogueNodeChoice castNode = dialogueNode as DialogueNodeChoice;
FormPropertiesChoice properties = new FormPropertiesChoice();
properties.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(properties);
FormPropertiesCommon propertiesCommon = new FormPropertiesCommon();
propertiesCommon.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(propertiesCommon);
}
else if (dialogueNode is DialogueNodeReply)
{
DialogueNodeReply castNode = dialogueNode as DialogueNodeReply;
FormPropertiesReply properties = new FormPropertiesReply();
properties.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(properties);
FormPropertiesCommon propertiesCommon = new FormPropertiesCommon();
propertiesCommon.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(propertiesCommon);
}
else if (dialogueNode is DialogueNodeGoto)
{
DialogueNodeGoto castNode = dialogueNode as DialogueNodeGoto;
//FormPropertiesGoto properties = new FormPropertiesGoto();
//properties.Init(document, treeNode, castNode);
//layoutPanel.Controls.Add(properties);
FormPropertiesCommon propertiesCommon = new FormPropertiesCommon();
propertiesCommon.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(propertiesCommon);
}
else if (dialogueNode is DialogueNodeBranch)
{
DialogueNodeBranch castNode = dialogueNode as DialogueNodeBranch;
FormPropertiesBranch properties = new FormPropertiesBranch();
properties.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(properties);
FormPropertiesCommon propertiesCommon = new FormPropertiesCommon();
propertiesCommon.Init(document, treeNode, castNode);
layoutPanel.Controls.Add(propertiesCommon);
}
layoutPanel.VerticalScroll.Value = 0;
//ResumeLayout();
WIN32.ResumeRedraw(this);
this.Refresh();
}
public void ForceFocus()
{
Focus();
foreach (UserControl property in layoutPanel.Controls)
{
IFormProperties propertyBase = property as IFormProperties;
if (propertyBase != null)
propertyBase.ForceFocus();
}
}
public bool IsEditingWorkstring()
{
foreach (UserControl property in layoutPanel.Controls)
{
IFormProperties propertyBase = property as IFormProperties;
if (propertyBase != null && propertyBase.IsEditingWorkstring())
return true;
}
return false;
}
public void OnResolvePendingDirty()
{
foreach (UserControl property in layoutPanel.Controls)
{
IFormProperties propertyBase = property as IFormProperties;
if (propertyBase != null)
propertyBase.OnResolvePendingDirty();
}
}
//--------------------------------------------------------------------------------------------------------------
// Events
private void OnVisibleChanged(object sender, EventArgs e)
{
if (EditorCore.MainWindow != null)
EditorCore.MainWindow.SyncMenuItemFromPanel(this);
}
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/transform/DeleteIdentityResultStaxUnmarshaller.java
|
2231
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simpleemail.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.simpleemail.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* DeleteIdentityResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteIdentityResultStaxUnmarshaller implements Unmarshaller<DeleteIdentityResult, StaxUnmarshallerContext> {
public DeleteIdentityResult unmarshall(StaxUnmarshallerContext context) throws Exception {
DeleteIdentityResult deleteIdentityResult = new DeleteIdentityResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 2;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return deleteIdentityResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return deleteIdentityResult;
}
}
}
}
private static DeleteIdentityResultStaxUnmarshaller instance;
public static DeleteIdentityResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new DeleteIdentityResultStaxUnmarshaller();
return instance;
}
}
|
apache-2.0
|
Tom-Davidson/ruby-sinatra-dependancydiscovery
|
spec/cartographer_spec.rb
|
460
|
require 'spec_helper'
describe 'Cartographer' do
let(:cartographer) { DependancyDiscovery::Cartographer.new }
it 'Cartographer accepts a Chronicler with POIs' do
chronicler = double('Chronicler')
allow(chronicler).to receive(:points_of_interest).and_return(
[
{ context: 'r1', uri: 'uri1' },
{ context: 'r2', uri: 'uri2' }
]
)
cartographer << chronicler
expect(cartographer.list.length).to eq(2)
end
end
|
apache-2.0
|
Activiti/Activiti
|
activiti-core/activiti-image-generator/src/main/java/org/activiti/image/ProcessDiagramGenerator.java
|
6016
|
/*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.image;
import java.io.InputStream;
import java.util.List;
import org.activiti.bpmn.model.BpmnModel;
/**
* This interface declares methods to generate process diagram
*/
public interface ProcessDiagramGenerator {
/**
* Generates a diagram of the given process definition, using the diagram interchange information of the process.
* If there is no interchange information available, an ActivitiInterchangeInfoNotFoundException is thrown.
* @param bpmnModel bpmn model to get diagram for
* @param highLightedActivities activities to highlight
* @param highLightedFlows flows to highlight
* @param activityFontName override the default activity font
* @param labelFontName override the default label font
*/
InputStream generateDiagram(BpmnModel bpmnModel,
List<String> highLightedActivities,
List<String> highLightedFlows,
String activityFontName,
String labelFontName,
String annotationFontName);
/**
* Generates a diagram of the given process definition, using the diagram interchange information of the process,
* or the default diagram image, if generateDefaultDiagram param is true.
* @param bpmnModel bpmn model to get diagram for
* @param highLightedActivities activities to highlight
* @param highLightedFlows flows to highlight
* @param activityFontName override the default activity font
* @param labelFontName override the default label font
* @param generateDefaultDiagram true if a default diagram should be generated if there is no graphic info available
*/
InputStream generateDiagram(BpmnModel bpmnModel,
List<String> highLightedActivities,
List<String> highLightedFlows,
String activityFontName,
String labelFontName,
String annotationFontName,
boolean generateDefaultDiagram);
/**
* Generates a diagram of the given process definition, using the diagram interchange information of the process,
* or the default diagram image, if generateDefaultDiagram param is true.
* @param bpmnModel bpmn model to get diagram for
* @param highLightedActivities activities to highlight
* @param highLightedFlows flows to highlight
* @param currentActivities current activities to highlight
* @param erroredActivities errored activities to highlight
* @param activityFontName override the default activity font
* @param labelFontName override the default label font
* @param generateDefaultDiagram true if a default diagram should be generated if there is no graphic info available
* @param defaultDiagramImageFileName override the default diagram image file name
*/
InputStream generateDiagram(BpmnModel bpmnModel,
List<String> highLightedActivities,
List<String> highLightedFlows,
List<String> currentActivities,
List<String> erroredActivities,
String activityFontName,
String labelFontName,
String annotationFontName,
boolean generateDefaultDiagram,
String defaultDiagramImageFileName);
/**
* Generates a diagram of the given process definition, using the diagram interchange information of the process.
* If there is no interchange information available, an ActivitiInterchangeInfoNotFoundException is thrown.
* @param bpmnModel bpmn model to get diagram for
* @param highLightedActivities activities to highlight
* @param highLightedFlows flows to highlight
*/
InputStream generateDiagram(BpmnModel bpmnModel,
List<String> highLightedActivities,
List<String> highLightedFlows);
/**
* Generates a diagram of the given process definition, using the diagram interchange information of the process.
* If there is no interchange information available, an ActivitiInterchangeInfoNotFoundException is thrown.
* @param bpmnModel bpmn model to get diagram for
* @param highLightedActivities activities to highlight
*/
InputStream generateDiagram(BpmnModel bpmnModel,
List<String> highLightedActivities);
/**
* Generates a diagram of the given process definition, using the diagram interchange information of the process.
* If there is no interchange information available, an ActivitiInterchangeInfoNotFoundException is thrown.
* @param bpmnModel bpmn model to get diagram for
*/
InputStream generateDiagram(BpmnModel bpmnModel,
String activityFontName,
String labelFontName,
String annotationFontName);
String getDefaultActivityFontName();
String getDefaultLabelFontName();
String getDefaultAnnotationFontName();
String getDefaultDiagramImageFileName();
}
|
apache-2.0
|
zhml8951/tianhuan
|
jsDemo/small_demo/fun_demo02.js
|
714
|
function fun_demo01() {
var a = 0;
function bb(x) {
console.log(x);
}
function timer(time, callback) {
setTimeout(function() {
a = 6;
callback(a);
}, time);
}
console.log(a);
timer(3000, bb);
timer(2000, function(x) {
console.log(x);
});
}
function scope_demo01() {
var scope = "global scope";
function checkScope() {
var scope = "local scope";
function f() {
return scope;
}
return f();
}
console.log(checkScope());
}
function scope_demo02() {
var scope = "global scope";
function checkScope(){
var scope = "local scope";
function f() {
return scope;
}
return f;
}
console.log(checkScope()());
}
scope_demo02();
|
apache-2.0
|
tectronics/hyracks
|
hyracks/hyracks-storage-am-lsm-invertedindex/src/main/java/org/apache/hyracks/storage/am/lsm/invertedindex/ondisk/OnDiskInvertedIndexOpContext.java
|
2502
|
/*
* Copyright 2009-2013 by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hyracks.storage.am.lsm.invertedindex.ondisk;
import org.apache.hyracks.storage.am.btree.impls.BTree;
import org.apache.hyracks.storage.am.btree.impls.RangePredicate;
import org.apache.hyracks.storage.am.common.api.IIndexAccessor;
import org.apache.hyracks.storage.am.common.api.IIndexCursor;
import org.apache.hyracks.storage.am.common.api.IIndexOperationContext;
import org.apache.hyracks.storage.am.common.impls.NoOpOperationCallback;
import org.apache.hyracks.storage.am.common.ophelpers.IndexOperation;
import org.apache.hyracks.storage.am.common.ophelpers.MultiComparator;
public class OnDiskInvertedIndexOpContext implements IIndexOperationContext {
public final RangePredicate btreePred = new RangePredicate(null, null, true, true, null, null);
public IIndexAccessor btreeAccessor;
public IIndexCursor btreeCursor;
public MultiComparator searchCmp;
// For prefix search on partitioned indexes.
public MultiComparator prefixSearchCmp;
public OnDiskInvertedIndexOpContext(BTree btree) {
// TODO: Ignore opcallbacks for now.
btreeAccessor = btree.createAccessor(NoOpOperationCallback.INSTANCE, NoOpOperationCallback.INSTANCE);
btreeCursor = btreeAccessor.createSearchCursor(false);
searchCmp = MultiComparator.create(btree.getComparatorFactories());
if (btree.getComparatorFactories().length > 1) {
prefixSearchCmp = MultiComparator.create(btree.getComparatorFactories(), 0, 1);
}
}
@Override
public void reset() {
// Nothing to be done here, only search operation supported.
}
@Override
public void setOperation(IndexOperation newOp) {
// Nothing to be done here, only search operation supported.
}
@Override
public IndexOperation getOperation() {
return IndexOperation.SEARCH;
}
}
|
apache-2.0
|
wenxuan-xia/net_info_publisher-SE_1_5
|
user_check_model/oa.php
|
9488
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Oa extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('cookie');
$this->load->helper('url');
}
private function check_token($token) {
$url = "http://passport.myqsc.com/api/get_member_by_token?token=$token";
$content = file_get_contents($url);
$content = json_decode($content);
if (isset($content->msg) || isset($content->code)) {
return FALSE;
}
if (isset($content->uid)) {
return $content;
}
return FALSE;
}
private function cookie_check_online() {
$token = $this->session->userdata("token");
$content = $this->check_token($token);
if ($content === false) {
header("location: http://passport.myqsc.com/member/auth?redirect=".current_url());
return;
}
return $content;
}
private function cookie_check() {
$info = $this->input->post();
if ($info) {
$token = $info['token'];
$content = $this->check_token($token);
if ($content === false) {
header("location: http://passport.myqsc.com/member/auth?redirect=".current_url());
return;
}
$this->session->set_userdata("token", $token);
} else {
$token = $this->session->userdata("token");
$content = $this->check_token($token);
if ($content === false) {
header("location: http://passport.myqsc.com/member/auth?redirect=".current_url());
return;
}
}
$this->load->model("public_model",'', TRUE);
$exist = $this->public_model->fetch_user_info($content->stuid);
if ($exist === 0) {
header("location: http://passport.myqsc.com/member/auth?redirect=".current_url());
return;
}
return $content;
}
public function logout() {
$this->session->sess_destroy();
header("location: http://passport.myqsc.com/member/logout");
}
/**
END of passport_check and local_cookie_save
**/
public function first_login_check() {
$data = $this->cookie_check_online();
$this->load->model("public_model",'', TRUE);
$result = $this->public_model->first_login_check($data->stuid);
if ($result == 0) {
//header("location: ".base_url()."index.php/oa/personal_data");
}
}
/**
END of first_log_check
**/
public function index()
{
$data = $this->cookie_check();
//$this->first_login_check();
$array = array(
'stuid' => $data->stuid,
'username'=>$data->username,
'page' => 'notice'
);
$this->load->view('frame', $array);
}
public function personal_data() {
$data = $this->cookie_check();
$this->load->model("public_model", '', TRUE);
$info = $this->public_model->fetch_user_info($data->stuid);
$array = array(
'stuid' => $data->stuid,
'realname' => $info->realname,
'username' => $info->username,
'sex' => $info->sex,
'department'=> $info->dep_name,
'position' => $info->position_name,
'telephone' => $info->telephone,
'shortnum' => $info->shortnum,
'email' => $info->email,
'qq' => $info->qq,
'msn' => $info->msn,
'home' => $info->home,
'page' => 'personal_data'
);
$this->load->view('frame', $array);
}
public function personal_data_submit() { //belongs to page personal_data
$info = $this->input->post();
$data = $this->cookie_check_online();
$this->load->model("public_model", '' , TRUE);
$this->public_model->personal_data_submit($data->stuid, $info);
return ;
}
public function message() {
$data = $this->cookie_check();
$array = array(
'stuid' => $data->stuid,
'username'=>$data->username,
'page' => 'message'
);
$this->load->view('frame', $array);
}
public function freetime() {
$data = $this->cookie_check();
$array = array(
'stuid' => $data->stuid,
'username'=>$data->username,
'page' => 'freetime'
);
$this->load->view('frame', $array);
}
public function fetch_freetime() { //belongs to page freetime
$data = $this->cookie_check_online();
$this->load->model("public_model", '' , TRUE);
$result = $this->public_model->fetch_freetime($data->stuid);
echo $result;
}
public function freetime_change() { //belongs to page freetime
$info = $this->input->post();
$data = $this->cookie_check_online();
$this->load->model("public_model", '' , TRUE);
$this->public_model->freetime_change($data->stuid, $info["time_value"]);
}
/**
the END of public functions
**/
public function onwatch_evaluate() {
$data = $this->cookie_check();
$this->load->model("public_model", '' , TRUE);
$info = $this->public_model->fetch_user_info($data->stuid);
//if ($info->power == 1) echo "你有权限"; //加权限判断.
$duty = $this->public_model->fetch_duty_time($data->stuid);
$array = array(
'stuid' => $data->stuid,
'username'=>$data->username,
'duty' => $duty,
'page' => 'onwatch_evaluate'
);
$this->load->view('frame', $array);
}
public function fetch_watch_user() { //belongs to onwatch_evaluate
$data = $this->cookie_check_online();
$this->load->model("hr_model", '' , TRUE);
$result = $this->hr_model->fetch_watch_user($data->stuid);
echo json_encode($result);
}
public function watch_arrangement() {
$data = $this->cookie_check();
$array = array(
'stuid' => $data->stuid,
'username'=>$data->username,
'page' => 'watch_arrangement'
);
$this->load->view('frame', $array);
}
public function arrange_duty_fetch_department() { //belongs to watch_arrangement
$data = $this->cookie_check_online();
$post = $this->input->post();
$this->load->model("hr_model", '' , TRUE);
$result = $this->hr_model->arrange_duty_fetch_department(1 << $post['key']);
echo json_encode($result);
}
public function add_watch_duty() { //belongs to watch_arrangement
$data = $this->cookie_check_online();
$post = $this->input->post();
$this->load->model("hr_model", '' , TRUE);
$result = $this->hr_model->add_watch_duty($post["stu_id"], $post["time_value"]);
if ($result == 0) {
echo 0;
} else {
echo json_encode($result);
}
}
public function fetch_duty_init() { //belongs to watch_arrangement
$data = $this->cookie_check_online();
$this->load->model("hr_model", '' , TRUE);
$result = $this->hr_model->fetch_duty_init();
echo json_encode($result);
}
public function cancel_duty() { //belongs to watch_arrangement
$data = $this->cookie_check_online();
$post = $this->input->post();
$this->load->model("hr_model", '' , TRUE);
$this->hr_model->cancel_duty($post['stu_id'], $post['time_value']);
echo json_encode("删除成功");
}
public function add_member() {
$data = $this->cookie_check();
$this->load->model("hr_model", '' , TRUE);
$department = $this->hr_model->fetch_department();
$position = $this->hr_model->fetch_position();
$power = $this->hr_model->fetch_power();
$array = array(
'stuid' => $data->stuid,
'username'=>$data->username,
'department' => $department,
'position' => $position,
'power' => $power,
'page' => 'add_member'
);
$this->load->view('frame', $array);
}
public function add_member_submit() {
$data = $this->cookie_check_online();
$this->load->model("public_model", '' , TRUE);
$info = $this->public_model->fetch_user_info($data->stuid);
$post = $this->input->post();
$this->load->model("hr_model", '' , TRUE);
$msg = $this->hr_model->add_member_submit($post);
echo json_encode($msg);
}
/**
the END of hr functions
**/
}
/* End of file oa.php */
/* Location: ./application/controllers/oa.php */
|
apache-2.0
|
Otaka/mydifferentprojects
|
nes-java/src/com/nes/processor/commands/impl/Rti.java
|
577
|
package com.nes.processor.commands.impl;
import com.nes.processor.ALU;
import com.nes.processor.AluUtils;
import com.nes.processor.commands.AbstractCommand;
/**
* @author Dmitry
*/
public class Rti extends AbstractCommand {
@Override
public byte execute(ALU alu, byte input) {
byte flag = alu.popFromStack();
byte low = alu.popFromStack();
byte hi = alu.popFromStack();
int index = AluUtils.lhTo16Bit(low, hi);
alu.setPc(index);
alu.getAluFlags().setFlagByte(flag);
return 0;
}
}
|
apache-2.0
|
XClouded/t4f-core
|
java/concurrent/src/main/java/io/aos/concurrent/spl5/Entrepot3.java
|
1994
|
/****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package io.aos.concurrent.spl5;
public class Entrepot3 {
private int article;
private boolean disponible = false;
public synchronized int get(int id) {
while (disponible == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
disponible = false;
System.out.println("Consumer #" + id + " got: " + article);
notifyAll();
return article;
}
public synchronized void put(int value) {
while (disponible == true) {
try {
wait();
} catch (InterruptedException e) {
}
}
article = value;
disponible = true;
System.out.println("Producer put: " + article);
notifyAll();
}
}
|
apache-2.0
|
Xuyuanp/goscheme
|
lexer/precedure.go
|
854
|
package lexer
import "fmt"
type precedure func(tokens ...*Token) (*Token, error)
var precedureMap = map[string]precedure{
"+": add,
}
func doPrecedure(tokens ...*Token) (*Token, error) {
token := tokens[0]
if token.typ != typePrecedure {
}
result, err := token.val.(precedure)(tokens[1:]...)
return result, err
}
func add(args ...*Token) (*Token, error) {
result := &Token{
typ: typeInteger,
val: 0.0,
}
for _, arg := range args {
if arg.typ == typeInteger {
result.val = result.val.(float64) + float64(arg.val.(int))
} else if arg.typ == typeFloat {
result.val = result.val.(float64) + arg.val.(float64)
result.typ = typeFloat
} else {
return nil, fmt.Errorf("wrong type arg [%v:%s] for +", arg.raw, arg.typ)
}
}
if result.typ == typeInteger {
result.val = int(result.val.(float64))
}
return result, nil
}
|
apache-2.0
|
ChineaseMedicine/MedicineFormatInput
|
ChineseMedicineInputSystem/ChineseMedicineInputSystem/obj/Debug/View/BasicInfo/NavigationBasicInfoView.g.i.cs
|
4081
|
#pragma checksum "..\..\..\..\View\BasicInfo\NavigationBasicInfoView.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "538145DE93BDD53960E25800FC428B3D"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using ChineseMedicineInputSystem.View.BasicInfo;
using ChineseMedicineInputSystem.ViewModel.BasicInfo;
using DevExpress.Core;
using DevExpress.Mvvm;
using DevExpress.Mvvm.UI;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Core.DataSources;
using DevExpress.Xpf.Core.Serialization;
using DevExpress.Xpf.Core.ServerMode;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Editors.DataPager;
using DevExpress.Xpf.Editors.DateNavigator;
using DevExpress.Xpf.Editors.ExpressionEditor;
using DevExpress.Xpf.Editors.Filtering;
using DevExpress.Xpf.Editors.Flyout;
using DevExpress.Xpf.Editors.Popups;
using DevExpress.Xpf.Editors.Popups.Calendar;
using DevExpress.Xpf.Editors.RangeControl;
using DevExpress.Xpf.Editors.Settings;
using DevExpress.Xpf.Editors.Settings.Extension;
using DevExpress.Xpf.Editors.Validation;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Grid.LookUp;
using DevExpress.Xpf.Grid.TreeList;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace ChineseMedicineInputSystem.View.BasicInfo {
/// <summary>
/// NavigationBasicInfoView
/// </summary>
public partial class NavigationBasicInfoView : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/ChineseMedicineInputSystem;component/view/basicinfo/navigationbasicinfoview.xaml" +
"", System.UriKind.Relative);
#line 1 "..\..\..\..\View\BasicInfo\NavigationBasicInfoView.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
|
apache-2.0
|
Juklab/emmaline
|
html/app/tour/add_tour_promotion.php
|
20716
|
<!DOCTYPE html>
<?php
require_once ('/var/www/html/app/model/connect.php');
require_once ('/var/www/html/app/library/function.php');
if(!isset($_SESSION['current_user_name']) && !isset($_COOKIE[$cookie_name])) {
header('Location: ../login.php');
exit();
}
$user_name = $_COOKIE["user"];
?>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Zoo Tour | Promotion</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="fonts/css/font-awesome.min.css" rel="stylesheet">
<link href="css/animate.min.css" rel="stylesheet">
<!-- Custom styling plus plugins -->
<link href="css/custom.css" rel="stylesheet">
<link href="css/icheck/flat/green.css" rel="stylesheet">
<!-- editor -->
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css" rel="stylesheet">
<link href="css/editor/external/google-code-prettify/prettify.css" rel="stylesheet">
<link href="css/editor/index.css" rel="stylesheet">
<!-- select2 -->
<link href="css/select/select2.min.css" rel="stylesheet">
<!-- switchery -->
<link rel="stylesheet" href="css/switchery/switchery.min.css" />
<script src="js/jquery.min.js"></script>
<!--[if lt IE 9]>
<script src="../assets/js/ie8-responsive-file-warning.js"></script>
<![endif]-->
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="nav-md">
<div class="container body">
<div class="main_container">
<div class="col-md-3 left_col">
<div class="left_col scroll-view">
<div class="navbar nav_title" style="border: 0;">
<a href="index.php" class="site_title"><i class="fa fa-paw"></i> <span>Zoo Tour</span></a>
</div>
<div class="clearfix"></div>
<!-- menu prile quick info -->
<div class="profile">
<div class="profile_pic">
<img src="images/img.jpg" alt="..." class="img-circle profile_img">
</div>
<div class="profile_info">
<span>Welcome,</span>
<h2><?php echo $user_name; ?></h2>
</div>
</div>
<!-- /menu prile quick info -->
<br />
<!-- sidebar menu -->
<div id="sidebar-menu" class="main_menu_side hidden-print main_menu">
<div class="menu_section">
<h3>General</h3>
<ul class="nav side-menu">
<li><a><i class="fa fa-home"></i> Home <span class="fa fa-chevron-down"></span></a>
<ul class="nav child_menu" style="display: none">
<li><a href="index.php">Zoo Tour</a>
<li><a href="../index.php">Admin Page</a>
</ul>
</li>
<li><a><i class="fa fa-edit"></i> Add Data <span class="fa fa-chevron-down"></span></a>
<ul class="nav child_menu" style="display: none">
<li><a href="add_tour_ticket_type.php">Add Ticket Type</a>
</li>
<li><a href="add_tour_ticket.php">Add Ticket</a>
</li>
<li><a href="add_tour_promotion.php">Add Promotion</a>
</li>
<li><a href="add_tour_schedule.php">Add Schedule</a>
</li>
<li><a href="add_tour_driver.php">Add Driver</a>
</li>
<li><a href="add_tour_guide.php">Add Guide</a>
</li>
<li><a href="add_tour_vehicle.php">Add Vehicle</a>
</li>
</ul>
</li>
<li><a><i class="fa fa-desktop"></i> View Data <span class="fa fa-chevron-down"></span></a>
<ul class="nav child_menu" style="display: none">
<li><a href="tour_ticket_type.php">Ticket Type</a>
</li>
<li><a href="tour_ticket.php">Ticket</a>
</li>
<li><a href="tour_promotion.php">Promotion</a>
</li>
<li><a href="tour_schedule.php">Schedule</a>
</li>
<li><a href="tour_driver.php">Driver</a>
</li>
<li><a href="tour_guide.php">Guide</a>
</li>
<li><a href="tour_vehicle.php">Vehicle</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- /sidebar menu -->
<!-- /menu footer buttons -->
<div class="sidebar-footer hidden-small">
<a data-toggle="tooltip" data-placement="top" title="Settings">
<span class="glyphicon glyphicon-cog" aria-hidden="true"></span>
</a>
<a data-toggle="tooltip" data-placement="top" title="FullScreen">
<span class="glyphicon glyphicon-fullscreen" aria-hidden="true"></span>
</a>
<a data-toggle="tooltip" data-placement="top" title="Lock">
<span class="glyphicon glyphicon-eye-close" aria-hidden="true"></span>
</a>
<a data-toggle="tooltip" data-placement="top" title="Logout">
<span class="glyphicon glyphicon-off" aria-hidden="true"></span>
</a>
</div>
<!-- /menu footer buttons -->
</div>
</div>
<!-- top navigation -->
<div class="top_nav">
<div class="nav_menu">
<nav class="" role="navigation">
<div class="nav toggle">
<a id="menu_toggle"><i class="fa fa-bars"></i></a>
</div>
<ul class="nav navbar-nav navbar-right">
<li class="">
<a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<img src="images/img.jpg" alt=""><?php echo $user_name;?>
<span class=" fa fa-angle-down"></span>
</a>
<ul class="dropdown-menu dropdown-usermenu animated fadeInDown pull-right">
<li><a href="../index.php"><i class="fa fa-sign-out pull-right"></i>Back to Admin Page</a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
<!-- /top navigation -->
<!-- /top navigation -->
<!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="page-title">
<div class="title_left">
<h3>Tour | Promotion</h3>
</div>
</div>
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Promotion</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
<form action="controllerAddTourPromotion.php" method="POST" class="form-horizontal form-label-left">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="type">Type
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="type" name="type" required="required" class="form-control col-md-7 col-xs-12"> </div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Price
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="price" name="price" required="required" class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
<!-- footer content -->
<footer>
<div class="">
<p class="pull-right">Copyright 2015. |
<span class="lead"> <i class="fa fa-paw"></i>Zoo Tour</span>
</p>
</div>
<div class="clearfix"></div>
</footer>
<!-- /footer content -->
</div>
</div>
</div>
<div id="custom_notifications" class="custom-notifications dsp_none">
<ul class="list-unstyled notifications clearfix" data-tabbed_notifications="notif-group">
</ul>
<div class="clearfix"></div>
<div id="notif-group" class="tabbed_notifications"></div>
</div>
<script src="js/bootstrap.min.js"></script>
<!-- chart js -->
<script src="js/chartjs/chart.min.js"></script>
<!-- bootstrap progress js -->
<script src="js/progressbar/bootstrap-progressbar.min.js"></script>
<script src="js/nicescroll/jquery.nicescroll.min.js"></script>
<!-- icheck -->
<script src="js/icheck/icheck.min.js"></script>
<!-- tags -->
<script src="js/tags/jquery.tagsinput.min.js"></script>
<!-- switchery -->
<script src="js/switchery/switchery.min.js"></script>
<!-- daterangepicker -->
<script type="text/javascript" src="js/moment.min2.js"></script>
<script type="text/javascript" src="js/datepicker/daterangepicker.js"></script>
<!-- richtext editor -->
<script src="js/editor/bootstrap-wysiwyg.js"></script>
<script src="js/editor/external/jquery.hotkeys.js"></script>
<script src="js/editor/external/google-code-prettify/prettify.js"></script>
<!-- select2 -->
<script src="js/select/select2.full.js"></script>
<!-- form validation -->
<script type="text/javascript" src="js/parsley/parsley.min.js"></script>
<!-- textarea resize -->
<script src="js/textarea/autosize.min.js"></script>
<script>
autosize($('.resizable_textarea'));
</script>
<!-- Autocomplete -->
<script type="text/javascript" src="js/autocomplete/countries.js"></script>
<script src="js/autocomplete/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(function () {
'use strict';
var countriesArray = $.map(countries, function (value, key) {
return {
value: value,
data: key
};
});
// Initialize autocomplete with custom appendTo:
$('#autocomplete-custom-append').autocomplete({
lookup: countriesArray,
appendTo: '#autocomplete-container'
});
});
</script>
<script src="js/custom.js"></script>
<!-- select2 -->
<script>
$(document).ready(function () {
$(".select2_single").select2({
placeholder: "Select a state",
allowClear: true
});
$(".select2_group").select2({});
$(".select2_multiple").select2({
maximumSelectionLength: 4,
placeholder: "With Max Selection limit 4",
allowClear: true
});
});
</script>
<!-- /select2 -->
<!-- input tags -->
<script>
function onAddTag(tag) {
alert("Added a tag: " + tag);
}
function onRemoveTag(tag) {
alert("Removed a tag: " + tag);
}
function onChangeTag(input, tag) {
alert("Changed a tag: " + tag);
}
$(function () {
$('#tags_1').tagsInput({
width: 'auto'
});
});
</script>
<!-- /input tags -->
<!-- form validation -->
<script type="text/javascript">
$(document).ready(function () {
$.listen('parsley:field:validate', function () {
validateFront();
});
$('#demo-form .btn').on('click', function () {
$('#demo-form').parsley().validate();
validateFront();
});
var validateFront = function () {
if (true === $('#demo-form').parsley().isValid()) {
$('.bs-callout-info').removeClass('hidden');
$('.bs-callout-warning').addClass('hidden');
} else {
$('.bs-callout-info').addClass('hidden');
$('.bs-callout-warning').removeClass('hidden');
}
};
});
$(document).ready(function () {
$.listen('parsley:field:validate', function () {
validateFront();
});
$('#demo-form2 .btn').on('click', function () {
$('#demo-form2').parsley().validate();
validateFront();
});
var validateFront = function () {
if (true === $('#demo-form2').parsley().isValid()) {
$('.bs-callout-info').removeClass('hidden');
$('.bs-callout-warning').addClass('hidden');
} else {
$('.bs-callout-info').addClass('hidden');
$('.bs-callout-warning').removeClass('hidden');
}
};
});
try {
hljs.initHighlightingOnLoad();
} catch (err) {}
</script>
<!-- /form validation -->
<!-- editor -->
<script>
$(document).ready(function () {
$('.xcxc').click(function () {
$('#descr').val($('#editor').html());
});
});
$(function () {
function initToolbarBootstrapBindings() {
var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
'Times New Roman', 'Verdana'],
fontTarget = $('[title=Font]').siblings('.dropdown-menu');
$.each(fonts, function (idx, fontName) {
fontTarget.append($('<li><a data-edit="fontName ' + fontName + '" style="font-family:\'' + fontName + '\'">' + fontName + '</a></li>'));
});
$('a[title]').tooltip({
container: 'body'
});
$('.dropdown-menu input').click(function () {
return false;
})
.change(function () {
$(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');
})
.keydown('esc', function () {
this.value = '';
$(this).change();
});
$('[data-role=magic-overlay]').each(function () {
var overlay = $(this),
target = $(overlay.data('target'));
overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight());
});
if ("onwebkitspeechchange" in document.createElement("input")) {
var editorOffset = $('#editor').offset();
$('#voiceBtn').css('position', 'absolute').offset({
top: editorOffset.top,
left: editorOffset.left + $('#editor').innerWidth() - 35
});
} else {
$('#voiceBtn').hide();
}
};
function showErrorAlert(reason, detail) {
var msg = '';
if (reason === 'unsupported-file-type') {
msg = "Unsupported format " + detail;
} else {
console.log("error uploading file", reason, detail);
}
$('<div class="alert"> <button type="button" class="close" data-dismiss="alert">×</button>' +
'<strong>File upload error</strong> ' + msg + ' </div>').prependTo('#alerts');
};
initToolbarBootstrapBindings();
$('#editor').wysiwyg({
fileUploadError: showErrorAlert
});
window.prettyPrint && prettyPrint();
});
</script>
<!-- /editor -->
</body>
</html>
|
apache-2.0
|
currying/molecule
|
molecule/src/main/java/com/toparchy/molecule/bi/report/BirtBean.java
|
825
|
//package com.toparchy.molecule.bi.report;
//
//import javax.enterprise.context.SessionScoped;
//import javax.inject.Named;
//
//import java.io.Serializable;
//
//import org.eclipse.birt.report.engine.api.EngineException;
//
//@Named
//@SessionScoped
//public class BirtBean implements Serializable {
//
// private static final long serialVersionUID = 7859020695443611979L;
// private String name;
//
// public String getReport() {
// birt2jsf report = new birt2jsf();
// String reportHTML = null;
// try {
// reportHTML = report.executeReport("76000DWT-1");
//
// } catch (EngineException e) {
// e.printStackTrace();
// }
//
// return reportHTML;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//}
|
apache-2.0
|
virtualdataset/metagen-java
|
virtdata-lib-curves4/src/main/java/org/apache/commons/math4/exception/NullArgumentException.java
|
2827
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math4.exception;
import org.apache.commons.math4.exception.util.ExceptionContext;
import org.apache.commons.math4.exception.util.ExceptionContextProvider;
import org.apache.commons.math4.exception.util.Localizable;
import org.apache.commons.math4.exception.util.LocalizedFormats;
/**
* All conditions checks that fail due to a {@code null} argument must throw
* this exception.
* This class is meant to signal a precondition violation ("null is an illegal
* argument") and so does not extend the standard {@code NullPointerException}.
* Propagation of {@code NullPointerException} from within Commons-Math is
* construed to be a bug.
* <p>
* Note: from 4.0 onwards, this class extends {@link NullPointerException} instead
* of {@link MathIllegalArgumentException}.
*
* @since 2.2
*/
public class NullArgumentException extends NullPointerException
implements ExceptionContextProvider {
/** Serializable version Id. */
private static final long serialVersionUID = 20150225L;
/** Context. */
private final ExceptionContext context;
/**
* Default constructor.
*/
public NullArgumentException() {
this(LocalizedFormats.NULL_NOT_ALLOWED);
}
/**
* @param pattern Message pattern providing the specific context of
* the error.
* @param arguments Values for replacing the placeholders in {@code pattern}.
*/
public NullArgumentException(Localizable pattern,
Object ... arguments) {
context = new ExceptionContext(this);
context.addMessage(pattern, arguments);
}
/**
* {@inheritDoc}
* @since 4.0
*/
@Override
public ExceptionContext getContext() {
return context;
}
/** {@inheritDoc} */
@Override
public String getMessage() {
return context.getMessage();
}
/** {@inheritDoc} */
@Override
public String getLocalizedMessage() {
return context.getLocalizedMessage();
}
}
|
apache-2.0
|
rPraml/org.openntf.domino
|
domino/design-impl/src/main/java/org/openntf/domino/design/impl/AbstractXspResource.java
|
3856
|
/*
* Copyright 2013
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.openntf.domino.design.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.openntf.domino.design.XspResource;
/**
* @author jgallagher
*
*/
@SuppressWarnings("unused")
public abstract class AbstractXspResource extends AbstractDesignNapiFileResource implements XspResource {
private static final long serialVersionUID = 1L;
private static final Logger log_ = Logger.getLogger(AbstractXspResource.class.getName());
private static final String CLASS_INDEX_ITEM = "$ClassIndexItem";
/* (non-Javadoc)
* @see org.openntf.domino.design.JavaResource#getClassNames()
*/
@Override
public Collection<String> getClassNames() {
String[] classIndex = getDocument().getItemValue(CLASS_ITEM, String[].class);
List<String> names = new ArrayList<String>();
for (String path : classIndex) {
if (path.startsWith("WEB-INF/classes/") && path.endsWith(".class")) {
String className = path.substring(16, path.length() - 6).replace('/', '.');
names.add(className);
} else {
names.add("");// add blank entries, otherwise the wrong $ClassData item will be located
}
}
return names;
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.design.JavaResource#getClassData()
*/
@Override
public Map<String, byte[]> getClassData() {
List<String> names = new ArrayList<String>(getClassNames());
Map<String, byte[]> result = new HashMap<String, byte[]>();
for (int i = 0; i < names.size(); i++) {
byte[] classData = null;
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
nReadNestedFileContent(getDocument(), "$ClassData" + i, os);
classData = os.toByteArray();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
if (classData != null && classData.length > 0) {
result.put(names.get(i), classData);
}
}
return result;
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.design.JavaResource#setClassData(java.util.Map)
*/
@Override
public void setClassData(final Map<String, byte[]> classData) {
throw new UnsupportedOperationException();
// // First step, clear out the existing data, index, and size fields
//
// Document doc = getDocument();
//
// for (int i = 0; i < 99; i++) {
// doc.removeItem("$ClassData" + i);
// doc.removeItem("$ClassSize" + i);
// }
//
// int index = 0;
// for (Map.Entry<String, byte[]> classEntry : classData.entrySet()) {
// XMLNode sizeNode = itemParent.addChildElement("item");
// sizeNode.setAttribute("name", "$ClassSize" + index);
// XMLNode sizeText = sizeNode.addChildElement("number");
// sizeText.setTextContent(String.valueOf(classEntry.getValue().length));
//
// try {
// setFileDataRaw("$ClassData" + index, new ByteArrayInputStream(classEntry.getValue()));
// } catch (IOException e) {
// ODAUtils.handleException(e);
// }
//
// XMLNode name = indexNode.addChildElement("text");
// name.setTextContent("WEB-INF/classes/" + DominoUtils.javaBinaryNameToFilePath(classEntry.getKey(), "/"));
//
// index++;
// }
}
}
|
apache-2.0
|
k9mail/k-9
|
mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/RealImapStoreTest.java
|
21362
|
package com.fsck.k9.mail.store.imap;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.net.ConnectivityManager;
import com.fsck.k9.mail.AuthType;
import com.fsck.k9.mail.ConnectionSecurity;
import com.fsck.k9.mail.FolderType;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.ServerSettings;
import com.fsck.k9.mail.oauth.OAuth2TokenProvider;
import com.fsck.k9.mail.ssl.TrustedSocketFactory;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.collections.Sets;
import static com.fsck.k9.mail.store.imap.ImapResponseHelper.createImapResponse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class RealImapStoreTest {
private ImapStoreConfig config = mock(ImapStoreConfig.class);
private TestImapStore imapStore;
@Before
public void setUp() throws Exception {
ServerSettings serverSettings = createServerSettings();
TrustedSocketFactory trustedSocketFactory = mock(TrustedSocketFactory.class);
ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
OAuth2TokenProvider oauth2TokenProvider = mock(OAuth2TokenProvider.class);
imapStore = new TestImapStore(serverSettings, config, trustedSocketFactory, connectivityManager,
oauth2TokenProvider);
}
@Test
public void checkSettings_shouldCreateImapConnectionAndCallOpen() throws Exception {
ImapConnection imapConnection = createMockConnection();
imapStore.enqueueImapConnection(imapConnection);
imapStore.checkSettings();
verify(imapConnection).open();
}
@Test
public void checkSettings_withOpenThrowing_shouldThrowMessagingException() throws Exception {
ImapConnection imapConnection = createMockConnection();
doThrow(IOException.class).when(imapConnection).open();
imapStore.enqueueImapConnection(imapConnection);
try {
imapStore.checkSettings();
fail("Expected exception");
} catch (MessagingException e) {
assertEquals("Unable to connect", e.getMessage());
assertNotNull(e.getCause());
assertEquals(IOException.class, e.getCause().getClass());
}
}
@Test
public void getFolders_withSpecialUseCapability_shouldReturnSpecialFolderInfo() throws Exception {
ImapConnection imapConnection = createMockConnection();
when(imapConnection.hasCapability(Capabilities.LIST_EXTENDED)).thenReturn(true);
when(imapConnection.hasCapability(Capabilities.SPECIAL_USE)).thenReturn(true);
List<ImapResponse> imapResponses = Arrays.asList(
createImapResponse("* LIST (\\HasNoChildren) \"/\" \"INBOX\""),
createImapResponse("* LIST (\\Noselect \\HasChildren) \"/\" \"[Gmail]\""),
createImapResponse("* LIST (\\HasNoChildren \\All) \"/\" \"[Gmail]/All Mail\""),
createImapResponse("* LIST (\\HasNoChildren \\Drafts) \"/\" \"[Gmail]/Drafts\""),
createImapResponse("* LIST (\\HasNoChildren \\Important) \"/\" \"[Gmail]/Important\""),
createImapResponse("* LIST (\\HasNoChildren \\Sent) \"/\" \"[Gmail]/Sent Mail\""),
createImapResponse("* LIST (\\HasNoChildren \\Junk) \"/\" \"[Gmail]/Spam\""),
createImapResponse("* LIST (\\HasNoChildren \\Flagged) \"/\" \"[Gmail]/Starred\""),
createImapResponse("* LIST (\\HasNoChildren \\Trash) \"/\" \"[Gmail]/Trash\""),
createImapResponse("5 OK Success")
);
when(imapConnection.executeSimpleCommand("LIST \"\" \"*\" RETURN (SPECIAL-USE)")).thenReturn(imapResponses);
imapStore.enqueueImapConnection(imapConnection);
List<FolderListItem> folders = imapStore.getFolders();
Map<String, FolderListItem> folderMap = toFolderMap(folders);
assertEquals(FolderType.INBOX, folderMap.get("INBOX").getType());
assertEquals(FolderType.DRAFTS, folderMap.get("[Gmail]/Drafts").getType());
assertEquals(FolderType.SENT, folderMap.get("[Gmail]/Sent Mail").getType());
assertEquals(FolderType.SPAM, folderMap.get("[Gmail]/Spam").getType());
assertEquals(FolderType.TRASH, folderMap.get("[Gmail]/Trash").getType());
assertEquals(FolderType.ARCHIVE, folderMap.get("[Gmail]/All Mail").getType());
}
@Test
public void getFolders_withoutSpecialUseCapability_shouldUseSimpleListCommand() throws Exception {
ImapConnection imapConnection = createMockConnection();
when(imapConnection.hasCapability(Capabilities.LIST_EXTENDED)).thenReturn(true);
when(imapConnection.hasCapability(Capabilities.SPECIAL_USE)).thenReturn(false);
imapStore.enqueueImapConnection(imapConnection);
imapStore.getFolders();
verify(imapConnection, never()).executeSimpleCommand("LIST \"\" \"*\" RETURN (SPECIAL-USE)");
verify(imapConnection).executeSimpleCommand("LIST \"\" \"*\"");
}
@Test
public void getFolders_withoutListExtendedCapability_shouldUseSimpleListCommand() throws Exception {
ImapConnection imapConnection = createMockConnection();
when(imapConnection.hasCapability(Capabilities.LIST_EXTENDED)).thenReturn(false);
when(imapConnection.hasCapability(Capabilities.SPECIAL_USE)).thenReturn(true);
imapStore.enqueueImapConnection(imapConnection);
imapStore.getFolders();
verify(imapConnection, never()).executeSimpleCommand("LIST \"\" \"*\" RETURN (SPECIAL-USE)");
verify(imapConnection).executeSimpleCommand("LIST \"\" \"*\"");
}
@Test
public void getFolders_withoutSubscribedFoldersOnly() throws Exception {
when(config.isSubscribedFoldersOnly()).thenReturn(false);
ImapConnection imapConnection = createMockConnection();
List<ImapResponse> imapResponses = Arrays.asList(
createImapResponse("* LIST (\\HasNoChildren) \".\" \"INBOX\""),
createImapResponse("* LIST (\\Noselect \\HasChildren) \".\" \"Folder\""),
createImapResponse("* LIST (\\HasNoChildren) \".\" \"Folder.SubFolder\""),
createImapResponse("6 OK Success")
);
when(imapConnection.executeSimpleCommand("LIST \"\" \"*\"")).thenReturn(imapResponses);
imapStore.enqueueImapConnection(imapConnection);
List<FolderListItem> result = imapStore.getFolders();
assertNotNull(result);
assertEquals(Sets.newSet("INBOX", "Folder.SubFolder"), extractFolderServerIds(result));
}
@Test
public void getFolders_withSubscribedFoldersOnly_shouldOnlyReturnExistingSubscribedFolders()
throws Exception {
when(config.isSubscribedFoldersOnly()).thenReturn(true);
ImapConnection imapConnection = createMockConnection();
List<ImapResponse> lsubResponses = Arrays.asList(
createImapResponse("* LSUB (\\HasNoChildren) \".\" \"INBOX\""),
createImapResponse("* LSUB (\\Noselect \\HasChildren) \".\" \"Folder\""),
createImapResponse("* LSUB (\\HasNoChildren) \".\" \"Folder.SubFolder\""),
createImapResponse("* LSUB (\\HasNoChildren) \".\" \"SubscribedFolderThatHasBeenDeleted\""),
createImapResponse("5 OK Success")
);
when(imapConnection.executeSimpleCommand("LSUB \"\" \"*\"")).thenReturn(lsubResponses);
List<ImapResponse> imapResponses = Arrays.asList(
createImapResponse("* LIST (\\HasNoChildren) \".\" \"INBOX\""),
createImapResponse("* LIST (\\Noselect \\HasChildren) \".\" \"Folder\""),
createImapResponse("* LIST (\\HasNoChildren) \".\" \"Folder.SubFolder\""),
createImapResponse("6 OK Success")
);
when(imapConnection.executeSimpleCommand("LIST \"\" \"*\"")).thenReturn(imapResponses);
imapStore.enqueueImapConnection(imapConnection);
List<FolderListItem> result = imapStore.getFolders();
assertNotNull(result);
assertEquals(Sets.newSet("INBOX", "Folder.SubFolder"), extractFolderServerIds(result));
}
@Test
public void getFolders_withNamespacePrefix() throws Exception {
ImapConnection imapConnection = createMockConnection();
List<ImapResponse> imapResponses = Arrays.asList(
createImapResponse("* LIST () \".\" \"INBOX\""),
createImapResponse("* LIST () \".\" \"INBOX.FolderOne\""),
createImapResponse("* LIST () \".\" \"INBOX.FolderTwo\""),
createImapResponse("5 OK Success")
);
when(imapConnection.executeSimpleCommand("LIST \"\" \"INBOX.*\"")).thenReturn(imapResponses);
imapStore.enqueueImapConnection(imapConnection);
imapStore.setTestCombinedPrefix("INBOX.");
List<FolderListItem> result = imapStore.getFolders();
assertNotNull(result);
assertEquals(Sets.newSet("INBOX", "INBOX.FolderOne", "INBOX.FolderTwo"), extractFolderServerIds(result));
assertEquals(Sets.newSet("INBOX", "FolderOne", "FolderTwo"), extractFolderNames(result));
assertEquals(Sets.newSet("INBOX", "FolderOne", "FolderTwo"), extractOldFolderServerIds(result));
}
@Test
public void getFolders_withFolderNotMatchingNamespacePrefix() throws Exception {
ImapConnection imapConnection = createMockConnection();
List<ImapResponse> imapResponses = Arrays.asList(
createImapResponse("* LIST () \".\" \"INBOX\""),
createImapResponse("* LIST () \".\" \"INBOX.FolderOne\""),
createImapResponse("* LIST () \".\" \"FolderTwo\""),
createImapResponse("5 OK Success")
);
when(imapConnection.executeSimpleCommand("LIST \"\" \"INBOX.*\"")).thenReturn(imapResponses);
imapStore.enqueueImapConnection(imapConnection);
imapStore.setTestCombinedPrefix("INBOX.");
List<FolderListItem> result = imapStore.getFolders();
assertNotNull(result);
assertEquals(Sets.newSet("INBOX", "INBOX.FolderOne", "FolderTwo"), extractFolderServerIds(result));
assertEquals(Sets.newSet("INBOX", "FolderOne", "FolderTwo"), extractFolderNames(result));
assertEquals(Sets.newSet("INBOX", "FolderOne"), extractOldFolderServerIds(result));
}
@Test
public void getFolders_withDuplicateFolderNames_shouldRemoveDuplicatesAndKeepFolderType()
throws Exception {
ImapConnection imapConnection = createMockConnection();
when(imapConnection.hasCapability(Capabilities.LIST_EXTENDED)).thenReturn(true);
when(imapConnection.hasCapability(Capabilities.SPECIAL_USE)).thenReturn(true);
List<ImapResponse> imapResponses = Arrays.asList(
createImapResponse("* LIST () \".\" \"INBOX\""),
createImapResponse("* LIST (\\HasNoChildren) \".\" \"Junk\""),
createImapResponse("* LIST (\\Junk) \".\" \"Junk\""),
createImapResponse("* LIST (\\HasNoChildren) \".\" \"Junk\""),
createImapResponse("5 OK Success")
);
when(imapConnection.executeSimpleCommand("LIST \"\" \"*\" RETURN (SPECIAL-USE)")).thenReturn(imapResponses);
imapStore.enqueueImapConnection(imapConnection);
List<FolderListItem> result = imapStore.getFolders();
assertNotNull(result);
assertEquals(2, result.size());
FolderListItem junkFolder = getFolderByServerId(result, "Junk");
assertNotNull(junkFolder);
assertEquals(FolderType.SPAM, junkFolder.getType());
}
@Test
public void getFolders_withoutException_shouldLeaveImapConnectionOpen() throws Exception {
ImapConnection imapConnection = createMockConnection();
List<ImapResponse> imapResponses = Collections.singletonList(createImapResponse("5 OK Success"));
when(imapConnection.executeSimpleCommand(anyString())).thenReturn(imapResponses);
imapStore.enqueueImapConnection(imapConnection);
imapStore.getFolders();
verify(imapConnection, never()).close();
}
@Test
public void getFolders_withIoException_shouldCloseImapConnection() throws Exception {
ImapConnection imapConnection = createMockConnection();
doThrow(IOException.class).when(imapConnection).executeSimpleCommand("LIST \"\" \"*\"");
imapStore.enqueueImapConnection(imapConnection);
try {
imapStore.getFolders();
fail("Expected exception");
} catch (MessagingException ignored) {
}
verify(imapConnection).close();
}
@Test
public void getConnection_shouldCreateImapConnection() throws Exception {
ImapConnection imapConnection = createMockConnection();
imapStore.enqueueImapConnection(imapConnection);
ImapConnection result = imapStore.getConnection();
assertSame(imapConnection, result);
}
@Test
public void getConnection_calledTwiceWithoutRelease_shouldCreateTwoImapConnection() throws Exception {
ImapConnection imapConnectionOne = createMockConnection();
ImapConnection imapConnectionTwo = createMockConnection();
imapStore.enqueueImapConnection(imapConnectionOne);
imapStore.enqueueImapConnection(imapConnectionTwo);
ImapConnection resultOne = imapStore.getConnection();
ImapConnection resultTwo = imapStore.getConnection();
assertSame(imapConnectionOne, resultOne);
assertSame(imapConnectionTwo, resultTwo);
}
@Test
public void getConnection_calledAfterRelease_shouldReturnCachedImapConnection() throws Exception {
ImapConnection imapConnection = createMockConnection();
when(imapConnection.isConnected()).thenReturn(true);
imapStore.enqueueImapConnection(imapConnection);
ImapConnection connection = imapStore.getConnection();
imapStore.releaseConnection(connection);
ImapConnection result = imapStore.getConnection();
assertSame(imapConnection, result);
}
@Test
public void getConnection_calledAfterReleaseWithAClosedConnection_shouldReturnNewImapConnectionInstance()
throws Exception {
ImapConnection imapConnectionOne = createMockConnection();
ImapConnection imapConnectionTwo = createMockConnection();
imapStore.enqueueImapConnection(imapConnectionOne);
imapStore.enqueueImapConnection(imapConnectionTwo);
imapStore.getConnection();
when(imapConnectionOne.isConnected()).thenReturn(false);
imapStore.releaseConnection(imapConnectionOne);
ImapConnection result = imapStore.getConnection();
assertSame(imapConnectionTwo, result);
}
@Test
public void getConnection_withDeadConnectionInPool_shouldReturnNewImapConnectionInstance() throws Exception {
ImapConnection imapConnectionOne = createMockConnection();
ImapConnection imapConnectionTwo = createMockConnection();
imapStore.enqueueImapConnection(imapConnectionOne);
imapStore.enqueueImapConnection(imapConnectionTwo);
imapStore.getConnection();
when(imapConnectionOne.isConnected()).thenReturn(true);
doThrow(IOException.class).when(imapConnectionOne).executeSimpleCommand(Commands.NOOP);
imapStore.releaseConnection(imapConnectionOne);
ImapConnection result = imapStore.getConnection();
assertSame(imapConnectionTwo, result);
}
@Test
public void getConnection_withConnectionInPoolAndCloseAllConnections_shouldReturnNewImapConnectionInstance()
throws Exception {
ImapConnection imapConnectionOne = createMockConnection(1);
ImapConnection imapConnectionTwo = createMockConnection(2);
imapStore.enqueueImapConnection(imapConnectionOne);
imapStore.enqueueImapConnection(imapConnectionTwo);
imapStore.getConnection();
when(imapConnectionOne.isConnected()).thenReturn(true);
imapStore.releaseConnection(imapConnectionOne);
imapStore.closeAllConnections();
ImapConnection result = imapStore.getConnection();
assertSame(imapConnectionTwo, result);
}
@Test
public void getConnection_withConnectionOutsideOfPoolAndCloseAllConnections_shouldReturnNewImapConnectionInstance()
throws Exception {
ImapConnection imapConnectionOne = createMockConnection(1);
ImapConnection imapConnectionTwo = createMockConnection(2);
imapStore.enqueueImapConnection(imapConnectionOne);
imapStore.enqueueImapConnection(imapConnectionTwo);
imapStore.getConnection();
when(imapConnectionOne.isConnected()).thenReturn(true);
imapStore.closeAllConnections();
imapStore.releaseConnection(imapConnectionOne);
ImapConnection result = imapStore.getConnection();
assertSame(imapConnectionTwo, result);
}
private ImapConnection createMockConnection() {
ImapConnection imapConnection = mock(ImapConnection.class);
when(imapConnection.getConnectionGeneration()).thenReturn(1);
return imapConnection;
}
private ImapConnection createMockConnection(int connectionGeneration) {
ImapConnection imapConnection = mock(ImapConnection.class);
when(imapConnection.getConnectionGeneration()).thenReturn(connectionGeneration);
return imapConnection;
}
private ServerSettings createServerSettings() {
Map<String, String> extra = ImapStoreSettings.createExtra(true, null);
return new ServerSettings(
"imap",
"imap.example.org",
143,
ConnectionSecurity.NONE,
AuthType.PLAIN,
"user",
"password",
null,
extra);
}
private Set<String> extractFolderServerIds(List<FolderListItem> folders) {
Set<String> folderServerIds = new HashSet<>(folders.size());
for (FolderListItem folder : folders) {
folderServerIds.add(folder.getServerId());
}
return folderServerIds;
}
private Set<String> extractFolderNames(List<FolderListItem> folders) {
Set<String> folderNames = new HashSet<>(folders.size());
for (FolderListItem folder : folders) {
folderNames.add(folder.getName());
}
return folderNames;
}
private Set<String> extractOldFolderServerIds(List<FolderListItem> folders) {
Set<String> folderNames = new HashSet<>(folders.size());
for (FolderListItem folder : folders) {
String oldServerId = folder.getOldServerId();
if (oldServerId != null) {
folderNames.add(oldServerId);
}
}
return folderNames;
}
private FolderListItem getFolderByServerId(List<FolderListItem> result, String serverId) {
for (FolderListItem imapFolder : result) {
if (imapFolder.getServerId().equals(serverId)) {
return imapFolder;
}
}
return null;
}
private Map<String, FolderListItem> toFolderMap(List<FolderListItem> folders) {
Map<String, FolderListItem> folderMap = new HashMap<>();
for (FolderListItem folder : folders) {
folderMap.put(folder.getServerId(), folder);
}
return folderMap;
}
static class TestImapStore extends RealImapStore {
private Deque<ImapConnection> imapConnections = new ArrayDeque<>();
private String testCombinedPrefix;
public TestImapStore(ServerSettings serverSettings, ImapStoreConfig config,
TrustedSocketFactory trustedSocketFactory, ConnectivityManager connectivityManager,
OAuth2TokenProvider oauth2TokenProvider) {
super(serverSettings, config, trustedSocketFactory, connectivityManager, oauth2TokenProvider);
}
@Override
ImapConnection createImapConnection() {
if (imapConnections.isEmpty()) {
throw new AssertionError("Unexpectedly tried to create an ImapConnection instance");
}
return imapConnections.pop();
}
public void enqueueImapConnection(ImapConnection imapConnection) {
imapConnections.add(imapConnection);
}
@Override
@NotNull
public String getCombinedPrefix() {
return testCombinedPrefix != null ? testCombinedPrefix : super.getCombinedPrefix();
}
void setTestCombinedPrefix(String prefix) {
testCombinedPrefix = prefix;
}
}
}
|
apache-2.0
|
llamahunter/docker-java
|
src/main/java/com/github/dockerjava/core/command/CreateContainerCmdImpl.java
|
27658
|
package com.github.dockerjava.core.command;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Capability;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Device;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.ExposedPorts;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Link;
import com.github.dockerjava.api.model.LogConfig;
import com.github.dockerjava.api.model.LxcConf;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.RestartPolicy;
import com.github.dockerjava.api.model.Ulimit;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.api.model.Volumes;
import com.github.dockerjava.api.model.VolumesFrom;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.singletonMap;
/**
* Creates a new container.
* `/containers/create`
*/
@JsonInclude(Include.NON_NULL)
public class CreateContainerCmdImpl extends AbstrDockerCmd<CreateContainerCmd, CreateContainerResponse> implements
CreateContainerCmd {
private String name;
@JsonProperty("Hostname")
private String hostName;
@JsonProperty("Domainname")
private String domainName;
@JsonProperty("User")
private String user;
@JsonProperty("AttachStdin")
private Boolean attachStdin;
@JsonProperty("AttachStdout")
private Boolean attachStdout;
@JsonProperty("AttachStderr")
private Boolean attachStderr;
@JsonProperty("PortSpecs")
private String[] portSpecs;
@JsonProperty("Tty")
private Boolean tty;
@JsonProperty("OpenStdin")
private Boolean stdinOpen;
@JsonProperty("StdinOnce")
private Boolean stdInOnce;
@JsonProperty("Env")
private String[] env;
@JsonProperty("Cmd")
private String[] cmd;
@JsonProperty("Entrypoint")
private String[] entrypoint;
@JsonProperty("Image")
private String image;
@JsonProperty("Volumes")
private Volumes volumes = new Volumes();
@JsonProperty("WorkingDir")
private String workingDir;
@JsonProperty("MacAddress")
private String macAddress;
@JsonProperty("NetworkDisabled")
private Boolean networkDisabled;
@JsonProperty("ExposedPorts")
private ExposedPorts exposedPorts = new ExposedPorts();
/**
* @since {@link com.github.dockerjava.core.RemoteApiVersion#VERSION_1_21}
*/
@JsonProperty("StopSignal")
private String stopSignal;
@JsonProperty("HostConfig")
private HostConfig hostConfig = new HostConfig();
@JsonProperty("Labels")
private Map<String, String> labels;
@JsonProperty("NetworkingConfig")
private NetworkingConfig networkingConfig;
@JsonIgnore
private String ipv4Address = null;
@JsonIgnore
private String ipv6Address = null;
@JsonIgnore
private List<String> aliases = null;
public CreateContainerCmdImpl(CreateContainerCmd.Exec exec, String image) {
super(exec);
checkNotNull(image, "image was not specified");
withImage(image);
}
/**
* @throws NotFoundException
* No such container
* @throws ConflictException
* Named container already exists
*/
@Override
public CreateContainerResponse exec() throws NotFoundException, ConflictException {
//code flow taken from https://github.com/docker/docker/blob/master/runconfig/opts/parse.go
ContainerNetwork containerNetwork = null;
if (ipv4Address != null || ipv6Address != null) {
containerNetwork = new ContainerNetwork()
.withIpamConfig(new ContainerNetwork.Ipam()
.withIpv4Address(ipv4Address)
.withIpv6Address(ipv6Address)
);
}
if (hostConfig.isUserDefinedNetwork() && hostConfig.getLinks().length > 0) {
if (containerNetwork == null) {
containerNetwork = new ContainerNetwork();
}
containerNetwork.withLinks(hostConfig.getLinks());
}
if (aliases != null) {
if (containerNetwork == null) {
containerNetwork = new ContainerNetwork();
}
containerNetwork.withAliases(aliases);
}
if (containerNetwork != null) {
networkingConfig = new NetworkingConfig()
.withEndpointsConfig(singletonMap(hostConfig.getNetworkMode(), containerNetwork));
}
return super.exec();
}
@Override
@JsonIgnore
public List<String> getAliases() {
return aliases;
}
@Override
@JsonIgnore
public Bind[] getBinds() {
return hostConfig.getBinds();
}
@Override
@JsonIgnore
public Integer getBlkioWeight() {
return hostConfig.getBlkioWeight();
}
@Override
@JsonIgnore
public Capability[] getCapAdd() {
return hostConfig.getCapAdd();
}
@Override
@JsonIgnore
public Capability[] getCapDrop() {
return hostConfig.getCapDrop();
}
@Override
public String[] getCmd() {
return cmd;
}
@Override
@JsonIgnore
public Integer getCpuPeriod() {
return hostConfig.getCpuPeriod();
}
@Override
@JsonIgnore
public String getCpusetCpus() {
return hostConfig.getCpusetCpus();
}
@Override
@JsonIgnore
public String getCpusetMems() {
return hostConfig.getCpusetMems();
}
@Override
@JsonIgnore
public Integer getCpuShares() {
return hostConfig.getCpuShares();
}
@Override
@JsonIgnore
public Device[] getDevices() {
return hostConfig.getDevices();
}
@Override
@JsonIgnore
public String[] getDns() {
return hostConfig.getDns();
}
@Override
@JsonIgnore
public String[] getDnsSearch() {
return hostConfig.getDnsSearch();
}
@Override
public String getDomainName() {
return domainName;
}
@Override
public String[] getEntrypoint() {
return entrypoint;
}
@Override
public String[] getEnv() {
return env;
}
@Override
@JsonIgnore
public ExposedPort[] getExposedPorts() {
return exposedPorts.getExposedPorts();
}
/**
* @see #stopSignal
*/
@JsonIgnore
@Override
public String getStopSignal() {
return stopSignal;
}
@Override
@JsonIgnore
public String[] getExtraHosts() {
return hostConfig.getExtraHosts();
}
@Override
public String getHostName() {
return hostName;
}
@Override
public String getImage() {
return image;
}
@Override
public String getIpv4Address() {
return ipv4Address;
}
@Override
public String getIpv6Address() {
return ipv6Address;
}
@Override
@JsonIgnore
public Map<String, String> getLabels() {
return labels;
}
@Override
@JsonIgnore
public Link[] getLinks() {
return hostConfig.getLinks();
}
@Override
@JsonIgnore
public LxcConf[] getLxcConf() {
return hostConfig.getLxcConf();
}
@Override
@JsonIgnore
public LogConfig getLogConfig() {
return hostConfig.getLogConfig();
}
@Override
public String getMacAddress() {
return macAddress;
}
@Override
@JsonIgnore
public Long getMemory() {
return hostConfig.getMemory();
}
@Override
@JsonIgnore
public Long getMemorySwap() {
return hostConfig.getMemorySwap();
}
@Override
public String getName() {
return name;
}
@Override
@JsonIgnore
public String getNetworkMode() {
return hostConfig.getNetworkMode();
}
@Override
@JsonIgnore
public Ports getPortBindings() {
return hostConfig.getPortBindings();
}
@Override
public String[] getPortSpecs() {
return portSpecs;
}
@Override
@JsonIgnore
public RestartPolicy getRestartPolicy() {
return hostConfig.getRestartPolicy();
}
@Override
@JsonIgnore
public Ulimit[] getUlimits() {
return hostConfig.getUlimits();
}
@Override
public String getUser() {
return user;
}
@Override
@JsonIgnore
public Volume[] getVolumes() {
return volumes.getVolumes();
}
@Override
@JsonIgnore
public VolumesFrom[] getVolumesFrom() {
return hostConfig.getVolumesFrom();
}
@Override
public String getWorkingDir() {
return workingDir;
}
@Override
public Boolean isAttachStderr() {
return attachStderr;
}
@Override
public Boolean isAttachStdin() {
return attachStdin;
}
@Override
public Boolean isAttachStdout() {
return attachStdout;
}
@Override
public Boolean isNetworkDisabled() {
return networkDisabled;
}
@Override
@JsonIgnore
public Boolean getOomKillDisable() {
return hostConfig.getOomKillDisable();
}
@Override
@JsonIgnore
public Boolean getPrivileged() {
return hostConfig.getPrivileged();
}
@Override
@JsonIgnore
public Boolean getPublishAllPorts() {
return hostConfig.getPublishAllPorts();
}
@Override
@JsonIgnore
public Boolean getReadonlyRootfs() {
return hostConfig.getReadonlyRootfs();
}
@Override
public Boolean isStdInOnce() {
return stdInOnce;
}
@Override
public Boolean isStdinOpen() {
return stdinOpen;
}
@Override
public Boolean isTty() {
return tty;
}
@Override
@JsonIgnore
public String getPidMode() {
return hostConfig.getPidMode();
}
@Override
public String getCgroupParent() {
return hostConfig.getCgroupParent();
}
@Override
public CreateContainerCmd withAliases(String... aliases) {
this.aliases = Arrays.asList(aliases);
return this;
}
@Override
public CreateContainerCmd withAliases(List<String> aliases) {
checkNotNull(aliases, "aliases was not specified");
this.aliases = aliases;
return this;
}
@Override
public CreateContainerCmd withAttachStderr(Boolean attachStderr) {
checkNotNull(attachStderr, "attachStderr was not specified");
this.attachStderr = attachStderr;
return this;
}
@Override
public CreateContainerCmd withAttachStdin(Boolean attachStdin) {
checkNotNull(attachStdin, "attachStdin was not specified");
this.attachStdin = attachStdin;
return this;
}
@Override
public CreateContainerCmd withAttachStdout(Boolean attachStdout) {
checkNotNull(attachStdout, "attachStdout was not specified");
this.attachStdout = attachStdout;
return this;
}
@Override
public CreateContainerCmd withBinds(Bind... binds) {
checkNotNull(binds, "binds was not specified");
hostConfig.setBinds(binds);
return this;
}
@Override
public CreateContainerCmd withBinds(List<Bind> binds) {
checkNotNull(binds, "binds was not specified");
return withBinds(binds.toArray(new Bind[binds.size()]));
}
@Override
public CreateContainerCmd withBlkioWeight(Integer blkioWeight) {
checkNotNull(blkioWeight, "blkioWeight was not specified");
hostConfig.withBlkioWeight(blkioWeight);
return this;
}
@Override
public CreateContainerCmd withCapAdd(Capability... capAdd) {
checkNotNull(capAdd, "capAdd was not specified");
hostConfig.withCapAdd(capAdd);
return this;
}
@Override
public CreateContainerCmd withCapAdd(List<Capability> capAdd) {
checkNotNull(capAdd, "capAdd was not specified");
return withCapAdd(capAdd.toArray(new Capability[capAdd.size()]));
}
@Override
public CreateContainerCmd withCapDrop(Capability... capDrop) {
checkNotNull(capDrop, "capDrop was not specified");
hostConfig.withCapDrop(capDrop);
return this;
}
@Override
public CreateContainerCmd withCapDrop(List<Capability> capDrop) {
checkNotNull(capDrop, "capDrop was not specified");
return withCapDrop(capDrop.toArray(new Capability[capDrop.size()]));
}
@Override
public CreateContainerCmd withCmd(String... cmd) {
checkNotNull(cmd, "cmd was not specified");
this.cmd = cmd;
return this;
}
@Override
public CreateContainerCmd withCmd(List<String> cmd) {
checkNotNull(cmd, "cmd was not specified");
return withCmd(cmd.toArray(new String[cmd.size()]));
}
@Override
public CreateContainerCmd withContainerIDFile(String containerIDFile) {
checkNotNull(containerIDFile, "no containerIDFile was specified");
hostConfig.withContainerIDFile(containerIDFile);
return this;
}
@Override
public CreateContainerCmd withCpuPeriod(Integer cpuPeriod) {
checkNotNull(cpuPeriod, "cpuPeriod was not specified");
hostConfig.withCpuPeriod(cpuPeriod);
return this;
}
@Override
public CreateContainerCmd withCpusetCpus(String cpusetCpus) {
checkNotNull(cpusetCpus, "cpusetCpus was not specified");
hostConfig.withCpusetCpus(cpusetCpus);
return this;
}
@Override
public CreateContainerCmd withCpusetMems(String cpusetMems) {
checkNotNull(cpusetMems, "cpusetMems was not specified");
hostConfig.withCpusetMems(cpusetMems);
return this;
}
@Override
public CreateContainerCmd withCpuShares(Integer cpuShares) {
checkNotNull(cpuShares, "cpuShares was not specified");
hostConfig.withCpuShares(cpuShares);
return this;
}
@Override
public CreateContainerCmd withDevices(Device... devices) {
checkNotNull(devices, "devices was not specified");
this.hostConfig.withDevices(devices);
return this;
}
@Override
public CreateContainerCmd withDevices(List<Device> devices) {
checkNotNull(devices, "devices was not specified");
return withDevices(devices.toArray(new Device[devices.size()]));
}
@Override
public CreateContainerCmd withDns(String... dns) {
checkNotNull(dns, "dns was not specified");
this.hostConfig.withDns(dns);
return this;
}
@Override
public CreateContainerCmd withDns(List<String> dns) {
checkNotNull(dns, "dns was not specified");
return withDns(dns.toArray(new String[dns.size()]));
}
@Override
public CreateContainerCmd withDnsSearch(String... dnsSearch) {
checkNotNull(dnsSearch, "dnsSearch was not specified");
this.hostConfig.withDnsSearch(dnsSearch);
return this;
}
@Override
public CreateContainerCmd withDnsSearch(List<String> dnsSearch) {
checkNotNull(dnsSearch, "dnsSearch was not specified");
return withDnsSearch(dnsSearch.toArray(new String[0]));
}
@Override
public CreateContainerCmd withDomainName(String domainName) {
checkNotNull(domainName, "no domainName was specified");
this.domainName = domainName;
return this;
}
@Override
public CreateContainerCmd withEntrypoint(String... entrypoint) {
checkNotNull(entrypoint, "entrypoint was not specified");
this.entrypoint = entrypoint;
return this;
}
@Override
public CreateContainerCmd withEntrypoint(List<String> entrypoint) {
checkNotNull(entrypoint, "entrypoint was not specified");
return withEntrypoint(entrypoint.toArray(new String[entrypoint.size()]));
}
@Override
public CreateContainerCmd withEnv(String... env) {
checkNotNull(env, "env was not specified");
this.env = env;
return this;
}
@Override
public CreateContainerCmd withEnv(List<String> env) {
checkNotNull(env, "env was not specified");
return withEnv(env.toArray(new String[env.size()]));
}
@Override
public CreateContainerCmd withExposedPorts(ExposedPort... exposedPorts) {
checkNotNull(exposedPorts, "exposedPorts was not specified");
this.exposedPorts = new ExposedPorts(exposedPorts);
return this;
}
@Override
public CreateContainerCmd withStopSignal(String stopSignal) {
checkNotNull(stopSignal, "stopSignal wasn't specified.");
this.stopSignal = stopSignal;
return this;
}
@Override
public CreateContainerCmd withExposedPorts(List<ExposedPort> exposedPorts) {
checkNotNull(exposedPorts, "exposedPorts was not specified");
return withExposedPorts(exposedPorts.toArray(new ExposedPort[exposedPorts.size()]));
}
@Override
public CreateContainerCmd withExtraHosts(String... extraHosts) {
checkNotNull(extraHosts, "extraHosts was not specified");
this.hostConfig.withExtraHosts(extraHosts);
return this;
}
@Override
public CreateContainerCmd withExtraHosts(List<String> extraHosts) {
checkNotNull(extraHosts, "extraHosts was not specified");
return withExtraHosts(extraHosts.toArray(new String[extraHosts.size()]));
}
@Override
public CreateContainerCmd withHostName(String hostName) {
checkNotNull(hostConfig, "no hostName was specified");
this.hostName = hostName;
return this;
}
@Override
public CreateContainerCmd withImage(String image) {
checkNotNull(image, "no image was specified");
this.image = image;
return this;
}
@Override
public CreateContainerCmd withIpv4Address(String ipv4Address) {
checkNotNull(ipv4Address, "no ipv4Address was specified");
this.ipv4Address = ipv4Address;
return this;
}
@Override
public CreateContainerCmd withIpv6Address(String ipv6Address) {
checkNotNull(ipv6Address, "no ipv6Address was specified");
this.ipv6Address = ipv6Address;
return this;
}
@Override
public CreateContainerCmd withLabels(Map<String, String> labels) {
checkNotNull(labels, "labels was not specified");
this.labels = labels;
return this;
}
@Override
public CreateContainerCmd withLinks(Link... links) {
checkNotNull(links, "links was not specified");
this.hostConfig.setLinks(links);
return this;
}
@Override
public CreateContainerCmd withLinks(List<Link> links) {
checkNotNull(links, "links was not specified");
return withLinks(links.toArray(new Link[links.size()]));
}
@Override
public CreateContainerCmd withLxcConf(LxcConf... lxcConf) {
checkNotNull(lxcConf, "lxcConf was not specified");
this.hostConfig.withLxcConf(lxcConf);
return this;
}
@Override
public CreateContainerCmd withLxcConf(List<LxcConf> lxcConf) {
checkNotNull(lxcConf, "lxcConf was not specified");
return withLxcConf(lxcConf.toArray(new LxcConf[0]));
}
@Override
public CreateContainerCmd withLogConfig(LogConfig logConfig) {
checkNotNull(logConfig, "logConfig was not specified");
this.hostConfig.withLogConfig(logConfig);
return this;
}
@Override
public CreateContainerCmd withMacAddress(String macAddress) {
checkNotNull(macAddress, "macAddress was not specified");
this.macAddress = macAddress;
return this;
}
@Override
public CreateContainerCmd withMemory(Long memory) {
checkNotNull(memory, "memory was not specified");
hostConfig.withMemory(memory);
return this;
}
@Override
public CreateContainerCmd withMemorySwap(Long memorySwap) {
checkNotNull(memorySwap, "memorySwap was not specified");
hostConfig.withMemorySwap(memorySwap);
return this;
}
@Override
public CreateContainerCmd withName(String name) {
checkNotNull(name, "name was not specified");
this.name = name;
return this;
}
@Override
public CreateContainerCmd withNetworkDisabled(Boolean disableNetwork) {
checkNotNull(disableNetwork, "disableNetwork was not specified");
this.networkDisabled = disableNetwork;
return this;
}
@Override
public CreateContainerCmd withNetworkMode(String networkMode) {
checkNotNull(networkMode, "networkMode was not specified");
this.hostConfig.withNetworkMode(networkMode);
return this;
}
@Override
public CreateContainerCmd withOomKillDisable(Boolean oomKillDisable) {
checkNotNull(oomKillDisable, "oomKillDisable was not specified");
hostConfig.withOomKillDisable(oomKillDisable);
return this;
}
@Override
public CreateContainerCmd withPortBindings(PortBinding... portBindings) {
checkNotNull(portBindings, "portBindings was not specified");
this.hostConfig.withPortBindings(new Ports(portBindings));
return this;
}
@Override
public CreateContainerCmd withPortBindings(List<PortBinding> portBindings) {
checkNotNull(portBindings, "portBindings was not specified");
return withPortBindings(portBindings.toArray(new PortBinding[0]));
}
@Override
public CreateContainerCmd withPortBindings(Ports portBindings) {
checkNotNull(portBindings, "portBindings was not specified");
this.hostConfig.withPortBindings(portBindings);
return this;
}
@Override
public CreateContainerCmd withPortSpecs(String... portSpecs) {
checkNotNull(portSpecs, "portSpecs was not specified");
this.portSpecs = portSpecs;
return this;
}
@Override
public CreateContainerCmd withPortSpecs(List<String> portSpecs) {
checkNotNull(portSpecs, "portSpecs was not specified");
return withPortSpecs(portSpecs.toArray(new String[portSpecs.size()]));
}
@Override
public CreateContainerCmd withPrivileged(Boolean privileged) {
checkNotNull(privileged, "no privileged was specified");
this.hostConfig.withPrivileged(privileged);
return this;
}
@Override
public CreateContainerCmd withPublishAllPorts(Boolean publishAllPorts) {
checkNotNull(publishAllPorts, "no publishAllPorts was specified");
this.hostConfig.withPublishAllPorts(publishAllPorts);
return this;
}
@Override
public CreateContainerCmd withReadonlyRootfs(Boolean readonlyRootfs) {
checkNotNull(readonlyRootfs, "no readonlyRootfs was specified");
hostConfig.withReadonlyRootfs(readonlyRootfs);
return this;
}
@Override
public CreateContainerCmd withRestartPolicy(RestartPolicy restartPolicy) {
checkNotNull(restartPolicy, "restartPolicy was not specified");
this.hostConfig.withRestartPolicy(restartPolicy);
return this;
}
@Override
public CreateContainerCmd withStdInOnce(Boolean stdInOnce) {
checkNotNull(stdInOnce, "no stdInOnce was specified");
this.stdInOnce = stdInOnce;
return this;
}
@Override
public CreateContainerCmd withStdinOpen(Boolean stdinOpen) {
checkNotNull(stdinOpen, "no stdinOpen was specified");
this.stdinOpen = stdinOpen;
return this;
}
@Override
public CreateContainerCmd withTty(Boolean tty) {
checkNotNull(tty, "no tty was specified");
this.tty = tty;
return this;
}
@Override
public CreateContainerCmd withUlimits(Ulimit... ulimits) {
checkNotNull(ulimits, "no ulimits was specified");
hostConfig.withUlimits(ulimits);
return this;
}
@Override
public CreateContainerCmd withUlimits(List<Ulimit> ulimits) {
checkNotNull(ulimits, "no ulimits was specified");
return withUlimits(ulimits.toArray(new Ulimit[ulimits.size()]));
}
@Override
public CreateContainerCmd withUser(String user) {
checkNotNull(user, "user was not specified");
this.user = user;
return this;
}
@Override
public CreateContainerCmd withVolumes(Volume... volumes) {
checkNotNull(volumes, "volumes was not specified");
this.volumes = new Volumes(volumes);
return this;
}
@Override
public CreateContainerCmd withVolumes(List<Volume> volumes) {
checkNotNull(volumes, "volumes was not specified");
return withVolumes(volumes.toArray(new Volume[volumes.size()]));
}
@Override
public CreateContainerCmd withVolumesFrom(VolumesFrom... volumesFrom) {
checkNotNull(volumesFrom, "volumesFrom was not specified");
this.hostConfig.withVolumesFrom(volumesFrom);
return this;
}
@Override
public CreateContainerCmd withVolumesFrom(List<VolumesFrom> volumesFrom) {
checkNotNull(volumesFrom, "volumesFrom was not specified");
return withVolumesFrom(volumesFrom.toArray(new VolumesFrom[volumesFrom.size()]));
}
@Override
public CreateContainerCmd withWorkingDir(String workingDir) {
checkNotNull(workingDir, "workingDir was not specified");
this.workingDir = workingDir;
return this;
}
@Override
public CreateContainerCmd withCgroupParent(final String cgroupParent) {
checkNotNull(cgroupParent, "cgroupParent was not specified");
this.hostConfig.withCgroupParent(cgroupParent);
return this;
}
@Override
public CreateContainerCmd withPidMode(String pidMode) {
checkNotNull(pidMode, "pidMode was not specified");
this.hostConfig.withPidMode(pidMode);
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public static class NetworkingConfig {
@JsonProperty("EndpointsConfig")
public Map<String, ContainerNetwork> endpointsConfig;
public Map<String, ContainerNetwork> getEndpointsConfig() {
return endpointsConfig;
}
public NetworkingConfig withEndpointsConfig(Map<String, ContainerNetwork> endpointsConfig) {
this.endpointsConfig = endpointsConfig;
return this;
}
}
}
|
apache-2.0
|
dimone-kun/cuba
|
modules/gui/src/com/haulmont/cuba/gui/ComponentPalette.java
|
1308
|
/*
* Copyright (c) 2008-2016 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.haulmont.cuba.gui;
import com.haulmont.cuba.gui.components.Component;
import com.haulmont.cuba.gui.xml.layout.ComponentLoader;
import java.util.Map;
/**
* Palette with UI components for screen descriptors
*
* @deprecated Use {@link com.haulmont.cuba.gui.xml.layout.ExternalUIComponentsSource} or app-components mechanism
*/
@Deprecated
public interface ComponentPalette {
/**
* Get loaders for XML screen descriptors
* @return Loaders
*/
Map<String, Class<? extends ComponentLoader>> getLoaders();
/**
* Get components for register in ComponentsFactory
* @return Components
*/
Map<String, Class<? extends Component>> getComponents();
}
|
apache-2.0
|
getsentry/zeus
|
tests/zeus/web/test_auth_github.py
|
11971
|
from urllib.parse import parse_qs
from zeus import auth, factories
from zeus.constants import GITHUB_AUTH_URI, GITHUB_TOKEN_URI, Permission
from zeus.models import Email, Identity, RepositoryAccess, User
def test_login(client):
resp = client.get("/auth/github")
assert resp.status_code == 302
location, querystring = resp.headers["Location"].split("?", 1)
assert location == GITHUB_AUTH_URI
qs = parse_qs(querystring)
assert qs["client_id"] == ["github.client-id"]
assert qs["redirect_uri"] == ["http://localhost/auth/github/complete"]
assert qs["response_type"] == ["code"]
assert sorted(qs["scope"][0].split(",")) == ["read:org", "repo", "user:email"]
def test_login_binds_next_target(client):
resp = client.get("/auth/github?next=/gh/github/zeus")
assert resp.status_code == 302
location, querystring = resp.headers["Location"].split("?", 1)
assert location == GITHUB_AUTH_URI
qs = parse_qs(querystring)
assert qs["client_id"] == ["github.client-id"]
assert qs["redirect_uri"] == ["http://localhost/auth/github/complete"]
assert qs["response_type"] == ["code"]
assert sorted(qs["scope"][0].split(",")) == ["read:org", "repo", "user:email"]
assert auth.get_redirect_target(False) == "/gh/github/zeus"
def test_login_complete(client, db_session, mocker, responses):
responses.add(
"POST",
GITHUB_TOKEN_URI,
json={
"token_type": "bearer",
"scope": "user:email,read:org",
"access_token": "access-token",
},
)
# TOOD(dcramer): ideally we could test the header easily, but responses
# doesnt make that highly accessible yet
responses.add(
"GET",
"https://api.github.com/user",
match_querystring=True,
json={"id": 1, "login": "test", "email": "foo@example.com"},
)
responses.add(responses.GET, "https://api.github.com/user/orgs", json=[])
responses.add(
"GET",
"https://api.github.com/user/emails",
match_querystring=True,
json=[
{"email": "foo@example.com", "verified": True, "primary": True},
{"email": "foo.bar@example.com", "verified": False, "primary": False},
],
)
resp = client.get("/auth/github/complete?code=abc")
assert resp.status_code == 302, repr(resp)
assert resp.headers["Location"] == "http://localhost/"
user = User.query.filter(User.email == "foo@example.com").first()
assert user
identity = Identity.query.filter(Identity.user_id == user.id).first()
assert identity
assert identity.provider == "github"
assert identity.external_id == "1"
assert identity.scopes == ["user:email", "read:org"]
assert identity.config == {
"access_token": "access-token",
"refresh_token": None,
"login": "test",
}
emails = {
r[0]: r[1]
for r in db_session.query(Email.email, Email.verified).filter(
Email.user_id == user.id
)
}
assert emails.get("foo@example.com") is True
assert emails.get("foo.bar@example.com") is False
assert emails.get("test@users.noreply.github.com") is True
def test_login_complete_with_next_target(client, db_session, mocker, responses):
responses.add(
"POST",
GITHUB_TOKEN_URI,
json={
"token_type": "bearer",
"scope": "user:email,read:org",
"access_token": "access-token",
},
)
# TOOD(dcramer): ideally we could test the header easily, but responses
# doesnt make that highly accessible yet
responses.add(
"GET",
"https://api.github.com/user",
match_querystring=True,
json={"id": 1, "login": "test", "email": "foo@example.com"},
)
responses.add(responses.GET, "https://api.github.com/user/orgs", json=[])
responses.add(
"GET",
"https://api.github.com/user/emails",
match_querystring=True,
json=[
{"email": "foo@example.com", "verified": True, "primary": True},
{"email": "foo.bar@example.com", "verified": False, "primary": False},
],
)
with client.session_transaction() as session:
auth.bind_redirect_target("/gh/getsentry/zeus", session=session)
resp = client.get("/auth/github/complete?code=abc")
assert resp.status_code == 302, repr(resp)
assert resp.headers["Location"] == "http://localhost/gh/getsentry/zeus"
assert auth.get_redirect_target() is None
def test_login_complete_no_visible_email(client, mocker, responses):
responses.add(
"POST",
GITHUB_TOKEN_URI,
json={
"token_type": "bearer",
"scope": "user:email,read:org",
"access_token": "access-token",
},
)
responses.add(responses.GET, "https://api.github.com/user/orgs", json=[])
# TOOD(dcramer): ideally we could test the header easily, but responses
# doesnt make that highly accessible yet
responses.add(
"GET",
"https://api.github.com/user",
match_querystring=True,
body='{"id": 1, "login": "test", "email": null}',
)
responses.add(
"GET",
"https://api.github.com/user/emails",
match_querystring=True,
json=[{"email": "foo@example.com", "verified": True, "primary": True}],
)
resp = client.get("/auth/github/complete?code=abc")
assert resp.status_code == 302
assert resp.headers["Location"] == "http://localhost/"
user = User.query.filter(User.email == "foo@example.com").first()
assert user
def test_login_complete_automatic_repo_access(
client, mocker, db_session, responses, default_repo
):
responses.add(
"POST",
GITHUB_TOKEN_URI,
json={
"token_type": "bearer",
"scope": "user:email,read:org",
"access_token": "access-token",
},
)
# TOOD(dcramer): ideally we could test the header easily, but responses
# doesnt make that highly accessible yet
responses.add(
responses.GET,
"https://api.github.com/user",
match_querystring=True,
json={"id": 1, "login": "test", "email": "foo@example.com"},
)
responses.add(
"GET",
"https://api.github.com/user/emails",
match_querystring=True,
json=[{"email": "foo@example.com", "verified": True, "primary": True}],
)
responses.add(
responses.GET,
"https://api.github.com/user/orgs",
json=[{"login": default_repo.owner_name, "permissions": {"admin": True}}],
)
responses.add(
responses.GET,
"https://api.github.com/orgs/{}/repos".format(default_repo.owner_name),
json=[
{
"id": default_repo.external_id,
"name": default_repo.name,
"full_name": default_repo.data["full_name"],
"clone_url": "https://github.com/{}.git".format(
default_repo.data["full_name"]
),
"ssh_url": "git@github.com:getsentry/zeus.git",
"permissions": {"admin": True},
}
],
)
resp = client.get("/auth/github/complete?code=abc")
assert resp.status_code == 302
assert resp.headers["Location"] == "http://localhost/"
user = User.query.filter(User.email == "foo@example.com").first()
assert user
identity = Identity.query.filter(Identity.user_id == user.id).first()
assert identity
assert identity.provider == "github"
assert identity.external_id == "1"
assert identity.config == {
"access_token": "access-token",
"refresh_token": None,
"login": "test",
}
assert identity.scopes == ["user:email", "read:org"]
access = RepositoryAccess.query.filter(
RepositoryAccess.repository_id == default_repo.id,
RepositoryAccess.user_id == user.id,
).first()
assert access
assert access.permission == Permission.admin
def test_login_complete_existing_user_no_identity(
client, db_session, mocker, responses
):
responses.add(
"POST",
GITHUB_TOKEN_URI,
json={
"token_type": "bearer",
"scope": "user:email,read:org",
"access_token": "access-token",
},
)
# TOOD(dcramer): ideally we could test the header easily, but responses
# doesnt make that highly accessible yet
responses.add(
"GET",
"https://api.github.com/user",
match_querystring=True,
json={"id": 1, "login": "test", "email": "foo@example.com"},
)
# responses.add(responses.GET, 'https://api.github.com/user/orgs', json=[])
responses.add(
"GET",
"https://api.github.com/user/emails",
match_querystring=True,
json=[
{"email": "foo@example.com", "verified": True, "primary": True},
{"email": "foo.bar@example.com", "verified": False, "primary": False},
],
)
user = factories.UserFactory.create(email="foo@example.com")
resp = client.get("/auth/github/complete?code=abc")
assert resp.status_code == 302
assert resp.headers["Location"] == "http://localhost/"
identity = Identity.query.filter(Identity.user_id == user.id).first()
assert identity
assert identity.provider == "github"
assert identity.external_id == "1"
assert identity.config == {
"access_token": "access-token",
"refresh_token": None,
"login": "test",
}
assert identity.scopes == ["user:email", "read:org"]
emails = {
r[0]: r[1]
for r in db_session.query(Email.email, Email.verified).filter(
Email.user_id == user.id
)
}
assert emails.get("foo@example.com") is True
assert emails.get("foo.bar@example.com") is False
assert emails.get("test@users.noreply.github.com") is True
def test_login_complete_existing_identity(client, db_session, mocker, responses):
responses.add(
"POST",
GITHUB_TOKEN_URI,
json={
"token_type": "bearer",
"scope": "user:email,read:org",
"access_token": "access-token",
},
)
# TOOD(dcramer): ideally we could test the header easily, but responses
# doesnt make that highly accessible yet
responses.add(
"GET",
"https://api.github.com/user",
match_querystring=True,
json={"id": 1, "login": "test", "email": "foo@example.com"},
)
# responses.add(responses.GET, 'https://api.github.com/user/orgs', json=[])
responses.add(
"GET",
"https://api.github.com/user/emails",
match_querystring=True,
json=[
{"email": "foo@example.com", "verified": True, "primary": True},
{"email": "foo.bar@example.com", "verified": False, "primary": False},
],
)
user = factories.UserFactory.create(email="foo@example.com")
identity = factories.IdentityFactory.create(
user=user, provider="github", external_id="1"
)
resp = client.get("/auth/github/complete?code=abc")
assert resp.status_code == 302
assert resp.headers["Location"] == "http://localhost/"
identity = Identity.query.filter(Identity.user_id == user.id).first()
assert identity
assert identity.provider == "github"
assert identity.external_id == "1"
assert identity.config == {
"access_token": "access-token",
"refresh_token": None,
"login": "test",
}
assert identity.scopes == ["user:email", "read:org"]
emails = {
r[0]: r[1]
for r in db_session.query(Email.email, Email.verified).filter(
Email.user_id == user.id
)
}
assert emails.get("foo@example.com") is True
assert emails.get("foo.bar@example.com") is False
assert emails.get("test@users.noreply.github.com") is True
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-codegurureviewer/src/main/java/com/amazonaws/services/codegurureviewer/model/transform/ListRecommendationsRequestProtocolMarshaller.java
|
2763
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.codegurureviewer.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.codegurureviewer.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListRecommendationsRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListRecommendationsRequestProtocolMarshaller implements Marshaller<Request<ListRecommendationsRequest>, ListRecommendationsRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/codereviews/{CodeReviewArn}/Recommendations").httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false)
.hasPayloadMembers(false).serviceName("AmazonCodeGuruReviewer").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public ListRecommendationsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<ListRecommendationsRequest> marshall(ListRecommendationsRequest listRecommendationsRequest) {
if (listRecommendationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<ListRecommendationsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
listRecommendationsRequest);
protocolMarshaller.startMarshalling();
ListRecommendationsRequestMarshaller.getInstance().marshall(listRecommendationsRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
apache-2.0
|
metasim/ews
|
src/EWS/app/drawable/CameraController.cpp
|
14117
|
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include "CameraController.h"
#include <osg/Quat>
#include <osg/Notify>
#include <osg/io_utils>
#include <osgUtil/LineSegmentIntersector>
#include "MathUtils.h"
namespace ews {
namespace app {
namespace drawable {
using namespace osg;
const Vec3 DEFAULT_OFFSET(200, 300, 200);
const Vec3 UP(0, 1, 0);
CameraController::CameraController()
: TerrainManipulator()
{
setMinimumDistance(MIN_ZOOM_DISTANCE);
computeHomePosition();
}
CameraController::~CameraController() {
}
/** Compute the home position.*/
void CameraController::computeHomePosition() {
if(getNode()) {
const BoundingSphere& boundingSphere = getNode()->getBound();
const Vec3& center = boundingSphere.center();
setHomePosition(center+DEFAULT_OFFSET, center, UP,
getAutoComputeHomePosition());
}
else {
notify(NOTICE) << "Can't compute home position. No node assigned to camera" << std::endl;
}
}
bool CameraController::handle(const GUIEventAdapter& ea, GUIActionAdapter& us) {
if (ea.getHandled()) return false;
if (ea.getEventType() == GUIEventAdapter::FRAME) return false;
switch(ea.getEventType())
{
case(GUIEventAdapter::PUSH):
case(GUIEventAdapter::RELEASE):
{
flushMouseEventStack();
addMouseEvent(ea);
if (calcMovement()) us.requestRedraw();
us.requestContinuousUpdate(false);
return true;
}
case(GUIEventAdapter::DRAG):
{
addMouseEvent(ea);
if (calcMovement()) us.requestRedraw();
us.requestContinuousUpdate(false);
return true;
}
case(GUIEventAdapter::MOVE):
{
return false;
}
case(GUIEventAdapter::KEYDOWN):
if (ea.getKey()== GUIEventAdapter::KEY_Space) {
flushMouseEventStack();
home(ea,us);
us.requestRedraw();
us.requestContinuousUpdate(false);
return true;
}
return false;
default:
return false;
}
}
void CameraController::computePosition(const osg::Vec3d& eye,const osg::Vec3d& center,const osg::Vec3d& up) {
if (!_node) return;
// compute rotation matrix
osg::Vec3d lv(center - eye);
_distance = lv.length();
_center = center;
osg::notify(osg::INFO) << "In compute"<< std::endl;
if (_node.valid()) {
bool hitFound = false;
const double distance = lv.length();
const double maxDistance = distance + 2 * (eye - _node->getBound().center()).length();
const osg::Vec3d farPosition = eye + lv * (maxDistance / distance);
osg::Vec3d endPoint = center;
for (int i = 0; !hitFound && i < 2; ++i, endPoint = farPosition) {
// compute the intersection with the scene.
osg::Vec3d ip;
if (intersect(eye, endPoint, ip)) {
_center = ip;
_distance = (ip - eye).length();
hitFound = true;
}
}
}
// note LookAt = inv(CF)*inv(RM)*inv(T) which is equivalent to:
// inv(R) = CF*LookAt.
osg::Matrixd rotation_matrix = osg::Matrixd::lookAt(eye, center, up);
_rotation = rotation_matrix.getRotate().inverse();
CoordinateFrame coordinateFrame = getCoordinateFrame(_center);
_previousUp = getUpVector(coordinateFrame);
clampOrientation();
}
void CameraController::doRotate(double dx, double dy) {
// rotate camera.
osg::Vec3 axis;
double angle;
double px0 = _ga_t0->getXnormalized();
double py0 = _ga_t0->getYnormalized();
double px1 = _ga_t1->getXnormalized();
double py1 = _ga_t1->getYnormalized();
trackball(axis, angle, px1, py1, px0, py0);
osg::Quat new_rotate;
new_rotate.makeRotate(angle, axis);
_rotation = _rotation * new_rotate;
clampOrientation();
}
void CameraController::doZoom(double dx, double dy) {
using namespace ews::util;
// zoom model.
const double scale = 1.0f + dy;
_distance = imposeBounds(getMinimumDistance(), _distance * scale, MAX_ZOOM_DISTANCE);
}
void CameraController::doPan(double dx, double dy) {
// pan model.
double scale = -0.3f*_distance;
osg::Matrixd rotation_matrix;
rotation_matrix.makeRotate(_rotation);
// compute look vector.
osg::Vec3d lookVector = -getUpVector(rotation_matrix);
osg::Vec3d sideVector = getSideVector(rotation_matrix);
osg::Vec3d upVector = getFrontVector(rotation_matrix);
// CoordinateFrame coordinateFrame = getCoordinateFrame(_center);
// osg::Vec3d localUp = getUpVector(coordinateFrame);
osg::Vec3d localUp = _previousUp;
osg::Vec3d forwardVector =localUp^sideVector;
sideVector = forwardVector^localUp;
forwardVector.normalize();
sideVector.normalize();
osg::Vec3d dv = forwardVector * (dy*scale) + sideVector * (dx*scale);
_center += dv;
// need to recompute the intersection point along the look vector.
bool hitFound = false;
if (_node.valid()) {
// now reorientate the coordinate frame to the frame coords.
CoordinateFrame coordinateFrame = getCoordinateFrame(_center);
// need to reintersect with the terrain
double distance = _node->getBound().radius()*0.25f;
osg::Vec3d ip1;
osg::Vec3d ip2;
bool hit_ip1 = intersect(_center, _center + getUpVector(coordinateFrame) * distance, ip1);
bool hit_ip2 = intersect(_center, _center - getUpVector(coordinateFrame) * distance, ip2);
if (hit_ip1) {
if (hit_ip2) {
_center = (_center-ip1).length2() < (_center-ip2).length2() ?
ip1 :
ip2;
hitFound = true;
}
else {
_center = ip1;
hitFound = true;
}
}
else if (hit_ip2) {
_center = ip2;
hitFound = true;
}
if (!hitFound) {
// ??
osg::notify(INFO)<<"CameraController unable to intersect"<<std::endl;
}
coordinateFrame = getCoordinateFrame(_center);
osg::Vec3d new_localUp = getUpVector(coordinateFrame);
osg::Quat pan_rotation;
pan_rotation.makeRotate(localUp, new_localUp);
if (!pan_rotation.zeroRotation()) {
_rotation = _rotation * pan_rotation;
_previousUp = new_localUp;
osg::notify(osg::NOTICE)<<"Rotating from "<<localUp<<" to "<<new_localUp<<" angle = "<<acos(localUp*new_localUp/(localUp.length()*new_localUp.length()))<<std::endl;
// clampOrientation();
}
else {
osg::notify(osg::INFO)<<"New up orientation nearly inline - no need to rotate"<<std::endl;
}
}
}
bool CameraController::calcMovement() {
// return if less then two events have been added.
if (_ga_t0.get() == NULL || _ga_t1.get() == NULL) return false;
double dx = _ga_t0->getXnormalized() - _ga_t1->getXnormalized();
double dy = _ga_t0->getYnormalized() - _ga_t1->getYnormalized();
// return if there is no movement.
if (dx==0 && dy==0) return false;
unsigned int buttonMask = _ga_t1->getButtonMask();
if (buttonMask==GUIEventAdapter::LEFT_MOUSE_BUTTON) {
doRotate(dx, dy);
return true;
}
else if (buttonMask==GUIEventAdapter::MIDDLE_MOUSE_BUTTON ||
buttonMask==(GUIEventAdapter::LEFT_MOUSE_BUTTON|GUIEventAdapter::RIGHT_MOUSE_BUTTON)) {
doPan(dx, dy);
return true;
}
else if (buttonMask==GUIEventAdapter::RIGHT_MOUSE_BUTTON) {
doZoom(dx, dy);
return true;
}
return false;
}
void CameraController::clampOrientation() {
osg::Matrixd rotation_matrix;
rotation_matrix.makeRotate(_rotation);
osg::Vec3d lookVector = -getUpVector(rotation_matrix);
osg::Vec3d upVector = getFrontVector(rotation_matrix);
// Don't let it rotate past the X-Y plane
if (lookVector.z() > 0) {
Vec3d newLookVector(lookVector.x(), lookVector.y(), 0);
newLookVector.normalize();
osg::Quat keepNegative;
keepNegative.makeRotate(lookVector, newLookVector);
_rotation = _rotation * keepNegative;
rotation_matrix.makeRotate(_rotation);
lookVector = -getUpVector(rotation_matrix);
upVector = getFrontVector(rotation_matrix);
}
// Don't let it rotate beyond the Z-axis
if (upVector.z() < 0) {
Vec3d newUpVector(upVector.x(), upVector.y(), 0);
newUpVector.normalize();
osg::Quat keepPositive;
keepPositive.makeRotate(upVector, newUpVector);
_rotation = _rotation * keepPositive;
rotation_matrix.makeRotate(_rotation);
lookVector = -getUpVector(rotation_matrix);
upVector = getFrontVector(rotation_matrix);
}
CoordinateFrame coordinateFrame = getCoordinateFrame(_center);
osg::Vec3d localUp = getUpVector(coordinateFrame);
//osg::Vec3d localUp = _previousUp;
osg::Vec3d sideVector = lookVector ^ localUp;
if (sideVector.length()<0.1) {
osg::notify(osg::INFO) << "Side vector short " << sideVector.length() << std::endl;
sideVector = upVector ^ localUp;
sideVector.normalize();
}
Vec3d newUpVector = sideVector ^ lookVector;
newUpVector.normalize();
osg::Quat rotate_roll;
rotate_roll.makeRotate(upVector, newUpVector);
if (!rotate_roll.zeroRotation()) {
_rotation = _rotation * rotate_roll;
}
}
}
}
}
|
apache-2.0
|
seirion/code
|
lge/2014/june/3/main.cpp
|
3946
|
// http://lgecodejam.com
// lge code jam June, 2014
// problem.3
// hyungyu.jang@lge.com
#if defined _EXTERNAL_DEBUGGER && defined _DEBUG
#include <trace/trace.h>
#include <intrin.h>
#else
#define trace printf
#endif
#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include <functional>
#include <algorithm>
using namespace std;
enum { X = 0, Y, }; // for indexing
typedef unsigned int uint32;
class Point { public:
Point() : x(0), y(0) {}
Point(int x_, int y_) : x(x_), y(y_) {}
~Point() {}
bool operator <(const Point& p) const {
return x == p.x ? y < p.y : x < p.x;
}
bool operator >(const Point& p) const {
return x == p.x ? y > p.y : x > p.x;
}
int x, y;
};
typedef multiset<Point> MinSet;
typedef multiset<Point, greater<Point> > MaxSet;
int n;
MinSet min_xy, min_yx;
MaxSet max_xy, max_yx;
template<typename T>
void remove(T &s, const Point p) {
typename T::iterator i = s.begin();
for (; i != s.end(); i++) {
if (i->x == p.x && i->y == p.y) {
s.erase(i);
return;
}
}
}
int simulation(int left, int right, int top, int bottom) {
MinSet min_xy_(min_xy);
MinSet min_yx_(min_yx);
MaxSet max_xy_(max_xy);
MaxSet max_yx_(max_yx);
int i;
for (i = 0; i < left; i++) {
Point p = *min_xy_.begin();
Point q(p.y, p.x);
remove<MinSet>(min_yx_, q);
remove<MaxSet>(max_yx_, q);
min_xy_.erase(min_xy_.begin());
}
for (i = 0; i < right; i++) {
Point p = *max_xy_.begin();
Point q(p.y, p.x);
remove<MinSet>(min_yx_, q);
remove<MaxSet>(max_yx_, q);
max_xy_.erase(max_xy_.begin());
}
for (i = 0; i < bottom; i++) {
Point p = *min_yx_.begin();
Point q(p.y, p.x);
remove<MinSet>(min_xy_, q);
remove<MaxSet>(max_xy_, q);
min_yx_.erase(min_yx_.begin());
}
for (i = 0; i < top; i++) {
Point p = *max_yx_.begin();
Point q(p.y, p.x);
remove<MinSet>(min_xy_, q);
remove<MaxSet>(max_xy_, q);
max_yx_.erase(max_yx_.begin());
}
return max(max_xy_.begin()->x - min_xy_.begin()->x, max_yx_.begin()->x - min_yx_.begin()->x);
}
void solve() {
min_xy.clear();
min_yx.clear();
max_xy.clear();
max_yx.clear();
scanf("%d", &n);
int i, x, y;
for (i = 0; i < 4; i++) {
scanf("%d %d", &x, &y);
min_xy.insert(Point(x, y));
max_xy.insert(Point(x, y));
min_yx.insert(Point(y, x));
max_yx.insert(Point(y, x));
}
for (; i < n; i++) {
scanf("%d %d", &x, &y);
min_xy.insert(Point(x, y));
max_xy.insert(Point(x, y));
min_yx.insert(Point(y, x));
max_yx.insert(Point(y, x));
min_xy.erase(--min_xy.rbegin().base());
min_yx.erase(--min_yx.rbegin().base());
max_xy.erase(--max_xy.rbegin().base());
max_yx.erase(--max_yx.rbegin().base());
}
// for all cases
int solution = 0x7FFFFFFF;
int direct[4]; // left, right, top, bottom
for (i = 0; i < 4; i++) {
memset(direct, 0, sizeof(int) * 4);
direct[i] = 3;
solution = min(solution, simulation(direct[0], direct[1], direct[2], direct[3]));
direct[0] = direct[1] = direct[2] = direct[3] = 1;
direct[i] = 0;
solution = min(solution, simulation(direct[0], direct[1], direct[2], direct[3]));
}
for (i = 0; i < 4; i++) {
memset(direct, 0, sizeof(int) * 4);
direct[i] = 2;
for (int j = 0; j < 3; j++) {
direct[(i+j+1)%4] = 1;
solution = min(solution, simulation(direct[0], direct[1], direct[2], direct[3]));
direct[(i+j+1)%4] = 0;
}
}
trace("%d\n", solution);
}
int main(int, char*[]) {
int num;
scanf("%d", &num);
for (int i = 0; i < num; i++) {solve();}
return 0;
}
|
apache-2.0
|
zoozooll/MyExercise
|
meep/MeepStore2/src/com/oregonscientific/meep/store2/CommonDialog.java
|
1356
|
package com.oregonscientific.meep.store2;
import com.oregonscientific.meep.store2.inapp.PurchaseActivity;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CommonDialog extends Dialog implements OnClickListener {
Button okButton;
TextView text;
Context mContext;
public CommonDialog(Context context, int resource) {
super(context);
mContext = context;
initDialog();
text.setText(resource);
}
public CommonDialog(Context context, String t) {
super(context);
mContext = context;
initDialog();
text.setText(t);
}
public void initDialog() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.common_message);
getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getWindow().setBackgroundDrawable(new ColorDrawable(0));
text = (TextView) findViewById(R.id.exchangeCode);
okButton = (Button) findViewById(R.id.ok);
okButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == okButton) {
dismiss();
}
}
}
|
apache-2.0
|
jlannoy/ninja
|
ninja-core/src/test/java/ninja/params/ControllerMethodInvokerWithDeprecatedValidationTest.java
|
63544
|
/**
* Copyright (C) 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ninja.params;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.multibindings.Multibinder;
import ninja.Context;
import ninja.Result;
import ninja.RoutingException;
import ninja.i18n.Lang;
import ninja.i18n.LangImpl;
import ninja.session.FlashScope;
import ninja.session.Session;
import ninja.utils.NinjaMode;
import ninja.utils.NinjaProperties;
import ninja.utils.NinjaPropertiesImpl;
import ninja.validation.*;
import org.joda.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Optional;
import ninja.exceptions.BadRequestException;
import ninja.utils.NinjaConstant;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hamcrest.Matchers;
import static org.junit.Assert.*;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.mockito.Captor;
import org.mockito.Mockito;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* ControllerMethodInvokerTest.
*/
@RunWith(MockitoJUnitRunner.class)
public class ControllerMethodInvokerWithDeprecatedValidationTest {
@Mock
private MockController mockController;
@Mock
private Context context;
@Mock
private Session session;
@Mock
private FlashScope flash;
private NinjaProperties ninjaProperties;
private Lang lang;
private Validation validation;
@Before
public void setUp() throws Exception {
this.ninjaProperties = Mockito.spy(new NinjaPropertiesImpl(NinjaMode.test));
this.lang = new LangImpl(this.ninjaProperties);
this.validation = new ValidationImpl();
when(this.context.getSession()).thenReturn(this.session);
when(this.context.getFlashScope()).thenReturn(this.flash);
when(this.context.getValidation()).thenReturn(this.validation);
}
@Test
public void noParameterMethodShouldBeInvoked() throws Exception {
create("noParameter").invoke(mockController, context);
verify(mockController).noParameter();
}
@Test
public void contextShouldBePassed() throws Exception {
create("context").invoke(mockController, context);
verify(mockController).context(context);
}
@Test
public void sessionShouldBePassed() throws Exception {
create("session").invoke(mockController, context);
verify(mockController).session(session);
}
@Test
public void flashArgumentShouldBePassed() throws Exception {
create("flash").invoke(mockController, context);
verify(mockController).flash(flash);
}
@Test
public void paramAnnotatedArgumentShouldBePassed() throws Exception {
when(context.getParameter("param1")).thenReturn("value");
create("param").invoke(mockController, context);
verify(mockController).param("value");
}
@Test
public void pathParamAnnotatedArgumentShouldBePassed() throws Exception {
when(context.getPathParameter("param1")).thenReturn("value");
create("pathParam").invoke(mockController, context);
verify(mockController).pathParam("value");
}
@Test
public void sessionParamAnnotatedArgumentShouldBePassed() throws Exception {
when(session.get("param1")).thenReturn("value");
create("sessionParam").invoke(mockController, context);
verify(mockController).sessionParam("value");
}
@Test
public void attributeAnnotatedArgumentShouldBePassed() throws Exception {
Dep dep = new Dep("dep");
when(context.getAttribute("param1", Dep.class)).thenReturn(dep);
create("attribute").invoke(mockController, context);
verify(mockController).attribute(dep);
}
@Test
public void headerAnnotatedArgumentShouldBePassed() throws Exception {
when(context.getHeader("param1")).thenReturn("value");
create("header").invoke(mockController, context);
verify(mockController).header("value");
}
@Test
public void headerAnnotatedArgumentShouldHandleNull() throws Exception {
when(context.getHeader("param1")).thenReturn(null);
create("header").invoke(mockController, context);
verify(mockController).header(null);
}
@Test
public void headersAnnotatedArgumentShouldReturnNull() throws Exception {
when(context.getHeaders("param1")).thenReturn(new ArrayList<String>());
create("headers").invoke(mockController, context);
verify(mockController).headers(null);
}
@Test
public void headersAnnotatedArgumentShouldBePassed() throws Exception {
when(context.getHeaders("param1")).thenReturn(Arrays.asList("a", "b", "c"));
create("headers").invoke(mockController, context);
verify(mockController).headers(new String[]{"a", "b", "c"});
}
@Test
public void headersAnnotatedArgumentShouldHandleNull() throws Exception {
when(context.getHeader("param1")).thenReturn(null);
create("headers").invoke(mockController, context);
verify(mockController).headers(null);
}
@Test
public void integerParamShouldBeParsedToInteger() throws Exception {
when(context.getParameter("param1")).thenReturn("20");
create("integerParam").invoke(mockController, context);
verify(mockController).integerParam(20);
}
@Test
public void integerParamShouldHandleNull() throws Exception {
create("integerParam").invoke(mockController, context);
verify(mockController).integerParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void integerValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("integerParam").invoke(mockController, context);
verify(mockController).integerParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void intParamShouldBeParsedToInteger() throws Exception {
when(context.getParameter("param1")).thenReturn("20");
create("intParam").invoke(mockController, context);
verify(mockController).intParam(20);
}
@Test
public void intParamShouldHandleNull() throws Exception {
create("intParam").invoke(mockController, context);
verify(mockController).intParam(0);
assertFalse(validation.hasViolations());
}
@Test
public void intValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("intParam").invoke(mockController, context);
verify(mockController).intParam(0);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void shortParamShouldBeParsedToShort() throws Exception {
when(context.getParameter("param1")).thenReturn("20");
create("shortParam").invoke(mockController, context);
verify(mockController).shortParam((short) 20);
}
@Test
public void shortParamShouldHandleNull() throws Exception {
create("shortParam").invoke(mockController, context);
verify(mockController).shortParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void shortValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("shortParam").invoke(mockController, context);
verify(mockController).shortParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void primShortParamShouldBeParsedToShort() throws Exception {
when(context.getParameter("param1")).thenReturn("20");
create("primShortParam").invoke(mockController, context);
verify(mockController).primShortParam((short) 20);
}
@Test
public void primShortParamShouldHandleNull() throws Exception {
create("primShortParam").invoke(mockController, context);
verify(mockController).primShortParam((short) 0);
assertFalse(validation.hasViolations());
}
@Test
public void primShortValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("primShortParam").invoke(mockController, context);
verify(mockController).primShortParam((short) 0);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void characterParamShouldBeParsedToCharacter() throws Exception {
when(context.getParameter("param1")).thenReturn("ABC");
create("characterParam").invoke(mockController, context);
verify(mockController).characterParam('A');
}
@Test
public void characterParamShouldHandleNull() throws Exception {
create("characterParam").invoke(mockController, context);
verify(mockController).characterParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void charParamShouldBeParsedToCharacter() throws Exception {
when(context.getParameter("param1")).thenReturn("ABC");
create("charParam").invoke(mockController, context);
verify(mockController).charParam('A');
}
@Test
public void charParamShouldHandleNull() throws Exception {
create("charParam").invoke(mockController, context);
verify(mockController).charParam('\0');
assertFalse(validation.hasViolations());
}
@Test
public void byteParamShouldBeParsedToByte() throws Exception {
when(context.getParameter("param1")).thenReturn("20");
create("byteParam").invoke(mockController, context);
verify(mockController).byteParam((byte) 20);
}
@Test
public void byteParamShouldHandleNull() throws Exception {
create("byteParam").invoke(mockController, context);
verify(mockController).byteParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void byteValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("byteParam").invoke(mockController, context);
verify(mockController).byteParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void primByteParamShouldBeParsedToByte() throws Exception {
when(context.getParameter("param1")).thenReturn("20");
create("primByteParam").invoke(mockController, context);
verify(mockController).primByteParam((byte) 20);
}
@Test
public void primByteParamShouldHandleNull() throws Exception {
create("primByteParam").invoke(mockController, context);
verify(mockController).primByteParam((byte) 0);
assertFalse(validation.hasViolations());
}
@Test
public void primByteValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("primByteParam").invoke(mockController, context);
verify(mockController).primByteParam((byte) 0);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void booleanParamShouldBeParsedToBoolean() throws Exception {
when(context.getParameter("param1")).thenReturn("true");
create("booleanParam").invoke(mockController, context);
verify(mockController).booleanParam(true);
}
@Test
public void booleanParamShouldHandleNull() throws Exception {
create("booleanParam").invoke(mockController, context);
verify(mockController).booleanParam(null);
assertFalse(validation.hasViolations());
}
@Test(expected = BadRequestException.class)
public void booleanParamShouldHandleNullInStrictMode() throws Exception {
when(context.getParameter("param1")).thenReturn(null);
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
create("booleanParam").invoke(mockController, context);
}
@Test(expected = BadRequestException.class)
public void booleanParamShouldHandleWrongInputForBooleanInStrictMode() throws Exception {
when(context.getParameter("param1")).thenReturn("test");
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
create("booleanParam").invoke(mockController, context);
}
@Test
public void primBooleanParamShouldBeParsedToBoolean() throws Exception {
when(context.getParameter("param1")).thenReturn("true");
create("primBooleanParam").invoke(mockController, context);
verify(mockController).primBooleanParam(true);
}
@Test
public void primBooleanParamShouldHandleNull() throws Exception {
create("primBooleanParam").invoke(mockController, context);
verify(mockController).primBooleanParam(false);
assertFalse(validation.hasViolations());
}
@Test
public void booleanParamWithOptionalShouldHandleWrongInputForBooleanInStrictMode() throws Exception {
when(context.getParameter("param1")).thenReturn("test");
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
create("booleanParamWithOptional").invoke(mockController, context);
verify(mockController).booleanParamWithOptional(Optional.empty());
}
@Test
public void booleanParamWithOptionalShouldHandleTrueInStrictMode() throws Exception {
when(context.getParameter("param1")).thenReturn("true");
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
create("booleanParamWithOptional").invoke(mockController, context);
verify(mockController).booleanParamWithOptional(Optional.of(Boolean.TRUE));
}
@Test
public void booleanParamWithOptionalShouldHandleFalseInStrictMode() throws Exception {
when(context.getParameter("param1")).thenReturn("false");
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
create("booleanParamWithOptional").invoke(mockController, context);
verify(mockController).booleanParamWithOptional(Optional.of(Boolean.FALSE));
}
@Test
public void longParamShouldBeParsedToLong() throws Exception {
when(context.getParameter("param1")).thenReturn("20");
create("longParam").invoke(mockController, context);
verify(mockController).longParam(20l);
}
@Test
public void longParamShouldHandleNull() throws Exception {
create("longParam").invoke(mockController, context);
verify(mockController).longParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void longValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("longParam").invoke(mockController, context);
verify(mockController).longParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void primLongParamShouldBeParsedToLong() throws Exception {
when(context.getParameter("param1")).thenReturn("20");
create("primLongParam").invoke(mockController, context);
verify(mockController).primLongParam(20);
}
@Test
public void primLongParamShouldHandleNull() throws Exception {
create("primLongParam").invoke(mockController, context);
verify(mockController).primLongParam(0);
assertFalse(validation.hasViolations());
}
@Test
public void primLongValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("primLongParam").invoke(mockController, context);
verify(mockController).primLongParam(0L);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void floatParamShouldBeParsedToFloat() throws Exception {
when(context.getParameter("param1")).thenReturn("3.14");
create("floatParam").invoke(mockController, context);
verify(mockController).floatParam(3.14f);
}
@Test
public void floatParamShouldHandleNull() throws Exception {
create("floatParam").invoke(mockController, context);
verify(mockController).floatParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void floatValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("floatParam").invoke(mockController, context);
verify(mockController).floatParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void primFloatParamShouldBeParsedToFloat() throws Exception {
when(context.getParameter("param1")).thenReturn("3.14");
create("primFloatParam").invoke(mockController, context);
verify(mockController).primFloatParam(3.14f);
}
@Test
public void primFloatParamShouldHandleNull() throws Exception {
create("primFloatParam").invoke(mockController, context);
verify(mockController).primFloatParam(0);
assertFalse(validation.hasViolations());
}
@Test
public void primFloatValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("primFloatParam").invoke(mockController, context);
verify(mockController).primFloatParam(0);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void doubleParamShouldBeParsedToDouble() throws Exception {
when(context.getParameter("param1")).thenReturn("3.14");
create("doubleParam").invoke(mockController, context);
verify(mockController).doubleParam(3.14);
}
@Test
public void doubleParamShouldHandleNull() throws Exception {
create("doubleParam").invoke(mockController, context);
verify(mockController).doubleParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void doubleValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("doubleParam").invoke(mockController, context);
verify(mockController).doubleParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void primDoubleParamShouldBeParsedToDouble() throws Exception {
when(context.getParameter("param1")).thenReturn("3.14");
create("primDoubleParam").invoke(mockController, context);
verify(mockController).primDoubleParam(3.14);
}
@Test
public void primDoubleParamShouldHandleNull() throws Exception {
create("primDoubleParam").invoke(mockController, context);
verify(mockController).primDoubleParam(0);
assertFalse(validation.hasViolations());
}
@Test
public void primDoubleValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("primDoubleParam").invoke(mockController, context);
verify(mockController).primDoubleParam(0);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void enumParamShouldBeParsedToEnumCaseSensitive() throws Exception {
when(context.getParameter("param1")).thenReturn("Red");
create("enumParam").invoke(mockController, context);
verify(mockController).enumParam(Rainbow.Red);
}
@Test
public void enumParamShouldBeParsedToEnumCaseInsensitive() throws Exception {
when(context.getParameter("param1")).thenReturn("red");
create("enumParam").invoke(mockController, context);
verify(mockController).enumParam(Rainbow.Red);
}
@Test
public void enumParamShouldHandleNull() throws Exception {
create("enumParam").invoke(mockController, context);
verify(mockController).enumParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void enumParamValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("enumParam").invoke(mockController, context);
verify(mockController).enumParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void enumCsvParamSingleShouldBeParsed() throws Exception {
when(context.getParameter("param1")).thenReturn("Red");
create("enumCsvParam").invoke(mockController, context);
verify(mockController).enumCsvParam(new Rainbow[]{Rainbow.Red});
}
@Test
public void enumCsvParamMultipleShouldBeParsed() throws Exception {
when(context.getParameter("param1")).thenReturn("Red,Orange,Yellow");
create("enumCsvParam").invoke(mockController, context);
verify(mockController).enumCsvParam(new Rainbow[]{Rainbow.Red, Rainbow.Orange, Rainbow.Yellow});
}
@Test
public void enumCsvParamShouldReturnNull() throws Exception {
when(context.getParameter("param1")).thenReturn("");
create("enumCsvParam").invoke(mockController, context);
verify(mockController).enumCsvParam(null);
assertFalse(validation.hasFieldViolation("param1"));
}
@Test
public void enumCsvParamValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("White,Black");
create("enumCsvParam").invoke(mockController, context);
verify(mockController).enumCsvParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void enumArrayParamSingleShouldBeParsed() throws Exception {
when(context.getParameterValues("param1")).thenReturn(Arrays.asList("Blue"));
create("enumArrayParam").invoke(mockController, context);
verify(mockController).enumArrayParam(new Rainbow[]{Rainbow.Blue});
}
@Test
public void enumArrayParamMultipleShouldBeParsed() throws Exception {
when(context.getParameterValues("param1")).thenReturn(Arrays.asList("Blue", "Indigo", "Violet"));
create("enumArrayParam").invoke(mockController, context);
verify(mockController).enumArrayParam(new Rainbow[]{Rainbow.Blue, Rainbow.Indigo, Rainbow.Violet});
}
@Test
public void enumArrayParamShouldReturnNull() throws Exception {
when(context.getParameterValues("param1")).thenReturn(new ArrayList<String>());
create("enumArrayParam").invoke(mockController, context);
verify(mockController).enumArrayParam(null);
assertFalse(validation.hasFieldViolation("param1"));
}
@Test
public void enumArrayParamValidationShouldWork() throws Exception {
when(context.getParameterValues("param1")).thenReturn(Arrays.asList("White", "Black"));
create("enumArrayParam").invoke(mockController, context);
verify(mockController).enumArrayParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void customDateFormatParamShouldBeParsedToDate() throws Exception {
when(context.getParameter("param1")).thenReturn("15/01/2015");
create("dateParam", DateParamParser.class).invoke(mockController, context);
verify(mockController).dateParam(new LocalDateTime(2015, 1, 15, 0, 0).toDate());
}
@Test
public void customDateFormatParamWithOptionalShouldBeParsedToDate() throws Exception {
when(context.getParameter("param1")).thenReturn("15/01/2015");
create("dateParamWithOptional", DateParamParser.class).invoke(mockController, context);
verify(mockController).dateParamWithOptional(Optional.of(new LocalDateTime(2015, 1, 15, 0, 0).toDate()));
}
@Test
public void customDateFormatParamShouldHandleNull() throws Exception {
create("dateParam", DateParamParser.class).invoke(mockController, context);
verify(mockController).dateParam(null);
assertFalse(validation.hasViolations());
}
@Test
public void customDateFormatParamWithOptionalShouldHandleEmpty() throws Exception {
create("dateParamWithOptional", DateParamParser.class).invoke(mockController, context);
verify(mockController).dateParamWithOptional(Optional.empty());
assertFalse(validation.hasViolations());
}
@Test
public void customDateFormatValidationShouldWork() throws Exception {
when(context.getParameter("param1")).thenReturn("blah");
create("dateParam", DateParamParser.class).invoke(mockController, context);
verify(mockController).dateParam(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test(expected = RoutingException.class)
public void needingInjectionParamParserNotBinded() throws Exception {
when(context.getParameter("param1")).thenReturn("hello");
create("needingInjectionParamParser").invoke(mockController, context);
verify(mockController).needingInjectionParamParser(new Dep("hello_hello"));
}
@Test
public void needingInjectionParamParser() throws Exception {
when(context.getParameter("param1")).thenReturn("hello");
create("needingInjectionParamParser", NeedingInjectionParamParser.class).invoke(mockController, context);
verify(mockController).needingInjectionParamParser(new Dep("hello_hello"));
}
@Test
public void needingInjectionParamParserArray() throws Exception {
when(context.getParameterValues("param1")).thenReturn(Arrays.asList("hello1", "hello2"));
create("needingInjectionParamParserArray", NeedingInjectionParamParser.class).invoke(mockController, context);
verify(mockController).needingInjectionParamParserArray(new Dep[] { new Dep("hello_hello1"), new Dep("hello_hello2") });
}
@Test
public void customArgumentExtractorWithNoArgsShouldBeInstantiated() {
create("noArgArgumentExtractor").invoke(mockController, context);
verify(mockController).noArgArgumentExtractor("noargs");
}
@Test
public void customArgumentExtractorWithClassArgShouldBeInstantiated() {
create("classArgArgumentExtractor").invoke(mockController, context);
verify(mockController).classArgArgumentExtractor("java.lang.String");
}
@Test
public void customArgumentExtractorWithGuiceShouldBeInstantiated() {
create("guiceArgumentExtractor", new Dep("dep")).invoke(mockController, context);
verify(mockController).guiceArgumentExtractor("dep:bar:java.lang.String");
}
@Test
public void customArgumentExtractorWithOptionalAndGuiceShouldBeInstantiated() {
create("guiceArgumentExtractorWithOptional", new Dep("dep")).invoke(mockController, context);
verify(mockController).guiceArgumentExtractorWithOptional(Optional.of("dep:bar:java.lang.String"));
}
@Test
public void multipleDifferentExtractorsShouldWorkFine() {
when(context.getParameter("param1")).thenReturn("value");
when(context.getPathParameter("param2")).thenReturn("20");
create("multiple").invoke(mockController, context);
verify(mockController).multiple("value", 20, context, session);
}
@Test
public void validationShouldFailWhenBadRequest() {
create("required").invoke(mockController, context);
verify(mockController).required(null);
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void validationShouldPassWhenGoodRequest() {
when(context.getParameter("param1")).thenReturn("value");
create("required").invoke(mockController, context);
verify(mockController).required("value");
assertFalse(validation.hasViolations());
}
@Test
public void optionalSessionParam() {
when(session.get("param1")).thenReturn("value");
create("optionalSessionParam").invoke(mockController, context);
verify(mockController).optionalSessionParam(Optional.of("value"));
}
@Test
public void optionalSessionParamEmpty() {
when(session.get("param1")).thenReturn(null);
create("optionalSessionParam").invoke(mockController, context);
verify(mockController).optionalSessionParam(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void sessionParamStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(session.get("param1")).thenReturn(null);
create("sessionParam").invoke(mockController, context);
}
@Test
public void optionalAttribute() {
Dep dep = new Dep("dep");
when(context.getAttribute("param1", Dep.class)).thenReturn(dep);
create("optionalAttribute").invoke(mockController, context);
verify(mockController).optionalAttribute(Optional.of(dep));
}
@Test
public void optionalAttributeEmpty() {
when(context.getAttribute("param1", Dep.class)).thenReturn(null);
create("optionalAttribute").invoke(mockController, context);
verify(mockController).optionalAttribute(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void attributeStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getAttribute("param1", Dep.class)).thenReturn(null);
create("attribute").invoke(mockController, context);
}
@Test
public void optionalHeader() {
when(context.getHeader("param1")).thenReturn("value");
create("optionalHeader").invoke(mockController, context);
verify(mockController).optionalHeader(Optional.of("value"));
}
@Test
public void optionalHeaderEmpty() {
when(context.getHeader("param1")).thenReturn(null);
create("optionalHeader").invoke(mockController, context);
verify(mockController).optionalHeader(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void headerStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getHeader("param1")).thenReturn(null);
create("header").invoke(mockController, context);
}
@Test
public void optionalParam() {
when(context.getParameter("param1")).thenReturn("value");
create("optionalParam").invoke(mockController, context);
verify(mockController).optionalParam(Optional.of("value"));
}
@Test
public void optionalParamEmpty() {
when(context.getParameter("param1")).thenReturn(null);
create("optionalParam").invoke(mockController, context);
verify(mockController).optionalParam(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void paramStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getParameter("param1")).thenReturn(null);
create("param").invoke(mockController, context);
}
@Test
public void optionalIntegerParam() {
when(context.getParameter("param1")).thenReturn("1");
create("optionalIntegerParam").invoke(mockController, context);
verify(mockController).optionalIntegerParam(Optional.of(1));
}
@Test
public void optionalIntegerParamEmpty() {
when(context.getParameter("param1")).thenReturn(null);
create("optionalIntegerParam").invoke(mockController, context);
verify(mockController).optionalIntegerParam(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void integerParamStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getParameter("param1")).thenReturn(null);
create("integerParam").invoke(mockController, context);
}
@Test
public void optionalLongParam() {
when(context.getParameter("param1")).thenReturn("1");
create("optionalLongParam").invoke(mockController, context);
verify(mockController).optionalLongParam(Optional.of(1L));
}
@Test
public void optionalLongParamEmpty() {
when(context.getParameter("param1")).thenReturn(null);
create("optionalLongParam").invoke(mockController, context);
verify(mockController).optionalLongParam(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void longParamEmptyStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getParameter("param1")).thenReturn(null);
create("longParam").invoke(mockController, context);
}
@Test
public void optionalShortParam() {
when(context.getParameter("param1")).thenReturn("1");
create("optionalShortParam").invoke(mockController, context);
verify(mockController).optionalShortParam(Optional.of(new Short("1")));
}
@Test
public void optionalShortParamEmpty() {
when(context.getParameter("param1")).thenReturn(null);
create("optionalShortParam").invoke(mockController, context);
verify(mockController).optionalShortParam(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void shortParamEmptyStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getParameter("param1")).thenReturn(null);
create("shortParam").invoke(mockController, context);
}
@Test
public void optionalEnumParam() {
when(context.getParameter("param1")).thenReturn("red");
create("optionalEnumParam").invoke(mockController, context);
verify(mockController).optionalEnumParam(Optional.of(Rainbow.Red));
}
@Test
public void optionalEnumParamEmpty() {
when(context.getParameter("param1")).thenReturn(null);
create("optionalEnumParam").invoke(mockController, context);
verify(mockController).optionalEnumParam(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void rainbowParamStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getParameter("param1")).thenReturn(null);
create("enumParam").invoke(mockController, context);
}
@Captor
ArgumentCaptor<Optional<Rainbow[]>> argumentCaptor;
@Test
public void optionalEnumArrayParam() {
when(context.getParameter("param1")).thenReturn("Red,Orange,Yellow");
create("optionalEnumArrayParam").invoke(mockController, context);
verify(mockController).optionalEnumArrayParam(argumentCaptor.capture());
Rainbow [] rainbows = argumentCaptor.getValue().get();
assertThat(rainbows, Matchers.arrayContaining(Rainbow.Red, Rainbow.Orange, Rainbow.Yellow));
}
@Test
public void optionalEnumArrayParamEmpty() {
when(context.getParameter("param1")).thenReturn(null);
create("optionalEnumArrayParam").invoke(mockController, context);
verify(mockController).optionalEnumArrayParam(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void rainbowArrayParamEmptyStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getParameter("param1")).thenReturn(null);
create("enumArrayParam").invoke(mockController, context);
}
@Test
public void optionalDateParam() {
when(context.getParameter("param1")).thenReturn("15/01/2015");
create("optionalDateParam", DateParamParser.class).invoke(mockController, context);
verify(mockController).optionalDateParam(Optional.of(new LocalDateTime(2015, 1, 15, 0, 0).toDate()));
}
@Test
public void optionalDateParamEmpty() {
when(context.getParameter("param1")).thenReturn(null);
create("optionalDateParam", DateParamParser.class).invoke(mockController, context);
verify(mockController).optionalDateParam(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void dateParamStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.getParameter("param1")).thenReturn(null);
create("dateParam", DateParamParser.class).invoke(mockController, context);
}
@Test
public void optionalBody() {
Object body = new Object();
when(context.parseBody(Object.class)).thenReturn(body);
create("optionalBody").invoke(mockController, context);
verify(mockController).optionalBody(Optional.of(body));
}
@Test
public void optionalBodyEmpty() {
when(context.parseBody(Object.class)).thenReturn(null);
create("optionalBody").invoke(mockController, context);
verify(mockController).optionalBody(Optional.empty());
}
@Test(expected = BadRequestException.class)
public void bodyEmptyStrictModeWorks() {
when(ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false)).thenReturn(true);
when(context.parseBody(Object.class)).thenReturn(null);
create("body").invoke(mockController, context);
}
@Test
public void validationShouldBeAppliedInCorrectOrderPreFail() {
create("requiredInt").invoke(mockController, context);
verify(mockController).requiredInt(0);
assertTrue(validation.hasFieldViolation("param1"));
assertEquals(1, validation.getFieldViolations("param1").size());
assertEquals("validation.required.violation", validation.getFieldViolations("param1").get(0).constraintViolation.getMessageKey());
}
@Test
public void validationWithOptionalShouldBeAppliedInCorrectOrderPreFail() {
create("requiredIntWithOptional").invoke(mockController, context);
verify(mockController).requiredIntWithOptional(Optional.empty());
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void validationShouldBeAppliedInCorrectOrderPostFail() {
when(context.getParameter("param1")).thenReturn("5");
create("requiredInt").invoke(mockController, context);
verify(mockController).requiredInt(5);
assertTrue(validation.hasFieldViolation("param1"));
assertEquals(1, validation.getFieldViolations("param1").size());
assertEquals("validation.number.min.violation", validation.getFieldViolations("param1").get(0).constraintViolation.getMessageKey());
}
@Test
public void validationWithOptionalShouldBeAppliedInCorrectOrderPostFail() {
when(context.getParameter("param1")).thenReturn("5");
create("requiredIntWithOptional").invoke(mockController, context);
verify(mockController).requiredIntWithOptional(Optional.of(5));
assertTrue(validation.hasFieldViolation("param1"));
}
@Test
public void validationShouldBeAppliedInCorrectOrderPass() {
when(context.getParameter("param1")).thenReturn("20");
create("requiredInt").invoke(mockController, context);
verify(mockController).requiredInt(20);
assertFalse(validation.hasViolations());
}
@Test
public void validationWithOptionalShouldBeAppliedInCorrectOrderPass() {
when(context.getParameter("param1")).thenReturn("20");
create("requiredIntWithOptional").invoke(mockController, context);
verify(mockController).requiredIntWithOptional(Optional.of(20));
assertFalse(validation.hasViolations());
}
@Test(expected = RoutingException.class)
public void invalidValidatorShouldBeFlagged() {
create("badValidator").invoke(mockController, context);
}
@Test(expected = RoutingException.class)
public void invalidValidatorWithOptionalShouldBeFlagged() {
create("badValidatorWithOptional").invoke(mockController, context);
}
@Test(expected = RoutingException.class)
public void tooManyBodiesShouldBeFlagged() {
create("tooManyBodies").invoke(mockController, context);
}
@Test
public void bodyShouldBeParsedIntoLeftOverParameter() {
Object body = new Object();
when(context.parseBody(Object.class)).thenReturn(body);
create("body").invoke(mockController, context);
verify(mockController).body(body);
}
@Test
public void bodyWithOptionalShouldBeParsedIntoLeftOverParameter() {
Object body = new Object();
when(context.parseBody(Object.class)).thenReturn(body);
create("bodyWithOptional").invoke(mockController, context);
verify(mockController).bodyWithOptional(Optional.of(body));
}
@Test
public void bodyWithOptionalShouldBeEmptyIfNoBodyPresent() {
when(context.parseBody(Object.class)).thenReturn(null);
create("bodyWithOptional").invoke(mockController, context);
verify(mockController).bodyWithOptional(Optional.empty());
}
// JSR303Validation(@Pattern(regexp = "[a-z]*") String param1,
// @Length(min = 5, max = 10) String param2, @Min(3) @Max(10) int param3);
@Test
public void validationPassed() {
validateJSR303(buildDto("regex", "length", 5));
doCheckValidationPassed(context);
}
@Test
public void validationWithOptionalPassed() {
validateJSR303WithOptional(buildDto("regex", "length", 5));
doCheckValidationPassed(context);
}
private void doCheckValidationPassed(Context context) {
assertFalse(context.getValidation().hasViolations());
assertFalse("Expected not to have regex violation.", context.getValidation().hasBeanViolation("regex"));
}
@Test
public void validationFailedRegex() {
validateJSR303(buildDto("regex!!!", "length", 5));
docheckValidationFailedRegex(context);
}
@Test
public void validationWithOptionalFailedRegex() {
validateJSR303WithOptional(buildDto("regex!!!", "length", 5));
docheckValidationFailedRegex(context);
}
private void docheckValidationFailedRegex(Context context) {
assertTrue(context.getValidation().hasViolations());
assertEquals(context.getValidation().getBeanViolations().size(), 1);
assertTrue("Expected to have regex violation.",
context.getValidation().hasBeanViolation("regex"));
assertTrue(context.getValidation().getBeanViolations().get(0).field
.contentEquals("regex"));
}
@Test
public void validationFailedLength() {
validateJSR303(buildDto("regex", "length - too long", 5));
doCheckValidationFailedLength(context);
}
@Test
public void validationWithOptionalFailedLength() {
validateJSR303WithOptional(buildDto("regex", "length - too long", 5));
doCheckValidationFailedLength(context);
}
private void doCheckValidationFailedLength(Context context) {
assertTrue(context.getValidation().hasViolations());
assertEquals(context.getValidation().getBeanViolations().size(), 1);
assertTrue("Expected to have length violation.",
context.getValidation().hasBeanViolation("length"));
assertTrue(context.getValidation().getBeanViolations().get(0).field
.contentEquals("length"));
}
@Test
public void validationFailedRange() {
validateJSR303(buildDto("regex", "length", 25));
doCheckValidationFailedRange(context);
}
@Test
public void validationWithOptionalFailedRange() {
validateJSR303WithOptional(buildDto("regex", "length", 25));
doCheckValidationFailedRange(context);
}
private void doCheckValidationFailedRange(Context context) {
assertTrue(context.getValidation().hasViolations());
assertEquals(context.getValidation().getBeanViolations().size(), 1);
assertTrue("Expected to have range violation.",
context.getValidation().hasBeanViolation("range"));
assertTrue(context.getValidation().getBeanViolations().get(0).field
.contentEquals("range"));
}
@Test
public void validationFailedTranslationFr() {
when(this.context.getAcceptLanguage()).thenReturn("fr");
validateJSR303(buildDto("regex", "length - too long", 5));
doCheckValidationFailedTranslationFr(context);
}
@Test
public void validationWithOptionalFailedTranslationFr() {
when(this.context.getAcceptLanguage()).thenReturn("fr");
validateJSR303WithOptional(buildDto("regex", "length - too long", 5));
doCheckValidationFailedTranslationFr(context);
}
private void doCheckValidationFailedTranslationFr(Context context) {
assertTrue(this.context.getValidation().hasViolations());
assertEquals(this.context.getValidation().getBeanViolations().size(), 1);
assertEquals(this.context.getValidation().getBeanViolations().get(0).constraintViolation.getMessageKey(), "la taille doit être entre 5 et 10");
}
@Test
public void validationFailedTranslationEn() {
when(this.context.getAcceptLanguage()).thenReturn("en");
validateJSR303(buildDto("regex", "length - too long", 5));
doCheckValidationFailedTranslationEn(context);
}
@Test
public void validationWithOptionalFailedTranslationEn() {
when(this.context.getAcceptLanguage()).thenReturn("en");
validateJSR303WithOptional(buildDto("regex", "length - too long", 5));
doCheckValidationFailedTranslationEn(context);
}
private void doCheckValidationFailedTranslationEn(Context context) {
assertTrue(context.getValidation().hasViolations());
assertEquals(context.getValidation().getBeanViolations().size(), 1);
assertEquals(context.getValidation().getBeanViolations().get(0).constraintViolation.getMessageKey(), "size must be between 5 and 10");
}
@Test
public void validationFailedWithThreeFields() {
validateJSR303(buildDto("regex!!!", "length is now tooooo loooong", 25));
doCheckValidationFailedWithThreeFields(context);
}
@Test
public void validationWithOptionalFailedWithThreeFields() {
validateJSR303WithOptional(buildDto("regex!!!", "length is now tooooo loooong", 25));
doCheckValidationFailedWithThreeFields(context);
}
private void doCheckValidationFailedWithThreeFields(Context context) {
assertTrue(context.getValidation().hasViolations());
assertTrue(context.getValidation().hasBeanViolations());
assertTrue("Expected to have regex violation.",
context.getValidation().hasBeanViolation("regex"));
assertEquals(context.getValidation().getBeanViolations().size(), 3);
for (int i = 0; i < context.getValidation().getBeanViolations().size(); i++) {
String fieldName = context.getValidation().getBeanViolations().get(i).field;
assertTrue(fieldName.contentEquals("regex") || fieldName.contentEquals("length")
|| fieldName.contentEquals("range"));
}
}
@Test
public void validationFailedWithTwoAnnotations() {
validateJSR303(buildDto("regex!!! which is also too long", "length", 5));
doValidationFailedWithTwoAnnotations(context);
}
@Test
public void validationWithOptionalFailedWithTwoAnnotations() {
validateJSR303WithOptional(buildDto("regex!!! which is also too long", "length", 5));
doValidationFailedWithTwoAnnotations(context);
}
private void doValidationFailedWithTwoAnnotations(Context context) {
assertTrue(context.getValidation().hasViolations());
assertTrue(context.getValidation().hasBeanViolations());
assertEquals(context.getValidation().getBeanViolations().size(), 2);
for (int i = 0; i < context.getValidation().getBeanViolations().size(); i++) {
String fieldName = context.getValidation().getBeanViolations().get(i).field;
assertTrue(fieldName.contentEquals("regex"));
}
String message0 =
context.getValidation().getBeanViolations().get(0).constraintViolation
.getMessageKey();
String message1 =
context.getValidation().getBeanViolations().get(1).constraintViolation
.getMessageKey();
assertFalse(message0.contentEquals(message1));
}
@Test
public void validationWithNullObject() {
validateJSR303(null);
assertFalse(context.getValidation().hasViolations());
validateJSR303WithOptional(null);
assertFalse(context.getValidation().hasViolations());
validateJSR303WithRequired(null);
assertTrue(context.getValidation().hasViolations());
}
private void validateJSR303(Dto dto) {
when(context.parseBody(Dto.class)).thenReturn(dto);
create("JSR303Validation", this.lang).invoke(mockController, context);
}
private void validateJSR303WithOptional(Dto dto) {
when(context.parseBody(Dto.class)).thenReturn(dto);
create("JSR303ValidationWithOptional", this.lang).invoke(mockController, context);
}
private void validateJSR303WithRequired(Dto dto) {
when(context.parseBody(Dto.class)).thenReturn(dto);
create("JSR303ValidationWithRequired", this.lang).invoke(mockController, context);
}
private Dto buildDto(String regex, String length, int range) {
Dto dto = new Dto();
dto.regex = regex;
dto.length = length;
dto.range = range;
return dto;
}
private ControllerMethodInvoker create(String methodName, final Object... toBind) {
Method method = null;
for (Method m : MockController.class.getMethods()) {
if (m.getName().equals(methodName)) {
method = m;
break;
}
}
return ControllerMethodInvoker.build(method, method, Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
Multibinder<ParamParser> parsersBinder = Multibinder.newSetBinder(binder(), ParamParser.class);
bind(NinjaProperties.class).toInstance(ninjaProperties);
for (Object o : toBind) {
if(o instanceof Class && ParamParser.class.isAssignableFrom((Class) o)) {
parsersBinder.addBinding().to((Class<? extends ParamParser>) o);
} else {
bind((Class<Object>) o.getClass()).toInstance(o);
}
}
}
}), ninjaProperties);
}
public enum Rainbow {
Red, Orange, Yellow, Green, Blue, Indigo, Violet
}
// Custom argument extractors for testing different instantiation paths
public interface MockController {
public Result noParameter();
public Result context(Context context);
public Result session(Session session);
public Result flash(FlashScope flash);
public Result param(@Param("param1") String param1);
public Result pathParam(@PathParam("param1") String param1);
public Result sessionParam(@SessionParam("param1") String param1);
public Result attribute(@Attribute("param1") Dep param1);
public Result header(@Header("param1") String param1);
public Result headers(@Headers("param1") String[] param1);
public Result integerParam(@Param("param1") Integer param1);
public Result intParam(@Param("param1") int param1);
public Result shortParam(@Param("param1") Short param1);
public Result primShortParam(@Param("param1") short param1);
public Result characterParam(@Param("param1") Character param1);
public Result charParam(@Param("param1") char param1);
public Result byteParam(@Param("param1") Byte param1);
public Result primByteParam(@Param("param1") byte param1);
public Result booleanParam(@Param("param1") Boolean param1);
public Result booleanParamWithOptional(@Param("param1") Optional<Boolean> param1);
public Result primBooleanParam(@Param("param1") boolean param1);
public Result longParam(@Param("param1") Long param1);
public Result primLongParam(@Param("param1") long param1);
public Result floatParam(@Param("param1") Float param1);
public Result primFloatParam(@Param("param1") float param1);
public Result doubleParam(@Param("param1") Double param1);
public Result primDoubleParam(@Param("param1") double param1);
public Result enumParam(@Param("param1") Rainbow param1);
public Result enumCsvParam(@Param("param1") Rainbow[] param1);
public Result enumArrayParam(@Params("param1") Rainbow[] param1);
public Result noArgArgumentExtractor(@NoArg String param1);
public Result classArgArgumentExtractor(@ClassArg String param1);
public Result guiceArgumentExtractor(@GuiceAnnotation(foo = "bar") String param1);
public Result guiceArgumentExtractorWithOptional(@GuiceAnnotation(foo = "bar") Optional<String> param1);
public Result multiple(@Param("param1") String param1, @PathParam("param2") int param2,
Context context, Session session);
public Result required(@Param("param1") @Required String param1);
public Result optionalSessionParam(@SessionParam("param1") Optional<String> param1);
public Result optionalAttribute(@Attribute("param1") Optional<Dep> param1);
public Result optionalHeader(@Header("param1") Optional<String> param1);
public Result optionalHeaders(@Headers("param1") Optional<String[]> param1);
public Result optionalParam(@Param("param1") Optional<String> param1);
public Result optionalIntegerParam(@Param("param1") Optional<Integer> param1);
public Result optionalLongParam(@Param("param1") Optional<Long> param1);
public Result optionalShortParam(@Param("param1") Optional<Short> param1);
public Result optionalEnumParam(@Param("param1") Optional<Rainbow> param1);
public Result optionalEnumArrayParam(@Param("param1") Optional<Rainbow[]> param1);
public Result optionalDateParam(@Param("param1") Optional<Date> param1);
public Result optionalBody(Optional<Object> body);
public Result requiredInt(@Param("param1") @Required @NumberValue(min = 10) int param1);
public Result requiredIntWithOptional(@Param("param1") @Required @NumberValue(min = 10) Optional<Integer> param1);
public Result badValidator(@Param("param1") @NumberValue(min = 10) String param1);
public Result badValidatorWithOptional(@Param("param1") @NumberValue(min = 10) Optional<String> param1);
public Result body(Object body);
public Result bodyWithOptional(Optional<Object> body);
public Result tooManyBodies(Object body1, Object body2);
public Result JSR303Validation(@JSR303Validation Dto dto, Validation validation);
public Result JSR303ValidationWithOptional(@JSR303Validation Optional<Dto> dto, Validation validation);
public Result JSR303ValidationWithRequired(@Required @JSR303Validation Dto dto, Validation validation);
public Result dateParam(@Param("param1") Date param1);
public Result dateParamWithOptional(@Param("param1") Optional<Date> param1);
public Result needingInjectionParamParser(@Param("param1") Dep param1);
public Result needingInjectionParamParserArray(@Params("param1") Dep[] paramsArray);
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@WithArgumentExtractor(NoArgArgumentExtractor.class)
public @interface NoArg {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@WithArgumentExtractor(ClassArgArgumentExtractor.class)
public @interface ClassArg {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@WithArgumentExtractor(GuiceArgumentExtractor.class)
public @interface GuiceAnnotation {
String foo();
}
public static class NoArgArgumentExtractor implements ArgumentExtractor<String> {
@Override
public String extract(Context context) {
return "noargs";
}
@Override
public Class<String> getExtractedType() {
return String.class;
}
@Override
public String getFieldName() {
return null;
}
}
public static class ClassArgArgumentExtractor implements ArgumentExtractor<String> {
private final Class<?> clazz;
public ClassArgArgumentExtractor(Class<?> clazz) {
this.clazz = clazz;
}
@Override
public String extract(Context context) {
return clazz.getName();
}
@Override
public Class<String> getExtractedType() {
return String.class;
}
@Override
public String getFieldName() {
return null;
}
}
public static class DateParamParser implements ParamParser<Date> {
public static final String DATE_FORMAT = "dd/MM/yyyy";
public static final String KEY = "validation.is.date.violation";
public static final String MESSAGE = "{0} must be a valid date";
@Override
public Date parseParameter(String field, String parameterValue, Validation validation) {
try {
return parameterValue == null ? null : new SimpleDateFormat(DATE_FORMAT).parse(parameterValue);
} catch(ParseException e) {
validation.addFieldViolation(field, ConstraintViolation.createForFieldWithDefault(
KEY, field, MESSAGE, parameterValue));
return null;
}
}
@Override
public Class<Date> getParsedType() {
return Date.class;
}
}
public static class NeedingInjectionParamParser implements ParamParser<Dep> {
// In a real application, you can also use @Named as each properties is binded by its name
@Inject
NinjaProperties properties;
@Override
public Dep parseParameter(String field, String parameterValue, Validation validation) {
return new Dep(properties.get("needingInjectionParamParser.value") + "_" + parameterValue);
}
@Override
public Class<Dep> getParsedType() {
return Dep.class;
}
}
/**
* Argument extractor that has a complex constructor for Guice. It depends on some
* other dependency (dep), plus the annotation that was on the parameter, and the
* class of the parameter.
*/
public static class GuiceArgumentExtractor implements ArgumentExtractor<String> {
private final Dep dep;
private final GuiceAnnotation annot;
private final Class clazz;
@Inject
public GuiceArgumentExtractor(Dep dep, GuiceAnnotation annot, ArgumentClassHolder holder) {
this.dep = dep;
this.annot = annot;
this.clazz = holder.getArgumentClass();
}
@Override
public String extract(Context context) {
return dep.value() + ":" + annot.foo() + ":" + clazz.getName();
}
@Override
public Class<String> getExtractedType() {
return String.class;
}
@Override
public String getFieldName() {
return null;
}
}
public static class Dep {
private final String value;
public Dep(String value) {
this.value = value;
}
public String value() {
return value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Dep other = (Dep) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
public class Dto {
@Size(min = 1, max = 10)
@Pattern(regexp = "[a-z]*")
public String regex;
@Size(min = 5, max = 10)
public String length;
@Min(value = 3)
@Max(value = 10)
public int range;
}
}
|
apache-2.0
|
arturdm/cppworkshop
|
01-KeyProviderTest/src/cpp/android/keyprovider/NativeKeyProviderTest.java
|
200
|
package cpp.android.keyprovider;
public class NativeKeyProviderTest extends KeyProviderTest<NativeKeyProvider> {
public NativeKeyProviderTest() {
super(NativeKeyProvider.class);
}
}
|
apache-2.0
|
samuelfvlcastro/dharma-stations
|
teste/Assets/script/PlayerBehaviour.cs
|
2153
|
using UnityEngine;
using System.Collections;
public class PlayerBehaviour : MonoBehaviour {
private Ray rayToInteract;
private RaycastHit hitInteract;
public float rangeInteract;
public Renderer feedBackSlender;
public float scare=0;
public float recoverScare;
public AudioClip walking;
private GameController gameController;
private ArduinoConnection arduino;
// Use this for initialization
void Start () {
gameController=FindObjectOfType(typeof(GameController)) as GameController;
arduino=FindObjectOfType(typeof(ArduinoConnection)) as ArduinoConnection;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.JoystickButton0) || Input.GetKeyDown(KeyCode.E))
{
rayToInteract=Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2, 0));
if(Physics.Raycast(rayToInteract, out hitInteract, rangeInteract))
{
if(hitInteract.collider.tag == "InteractObject")
{
hitInteract.collider.GetComponent<ObjectiveObjectBehaviour>().Interact();
}
}
}
if(scare >= 0 && scare < 0.5)
arduino.sendGreenHealth();
else if (scare >= 0.5 && scare <0.8)
arduino.sendOrangeHealth();
else if(scare >= 0.8)
arduino.sendRedHealth();
if(scare>0)
{
scare-=recoverScare;
if(scare<0)
scare=0;
}
SetFeedBackAlpha(scare);
if(scare>=1)
die();
if(GetComponent<CharacterMotor>().inputMoveDirection != Vector3.zero)
{
if(audio.isPlaying == false)
{
audio.Play();
}
}
if(GetComponent<CharacterMotor>().inputMoveDirection == Vector3.zero)
{
audio.Stop();
}
}
private void SetFeedBackAlpha(float alpha)
{
Color currentAlpha = feedBackSlender.material.color;
currentAlpha.a=alpha;
feedBackSlender.material.color=currentAlpha;
}
void OnGUI()
{
GUI.Box(new Rect(15, 30, 75, 23), "Objectives");
GUI.Box(new Rect(100, 30, 50, 23), gameController.GetTotalObjectiveOk().ToString() + "/" + gameController.GetTotalObjective().ToString());
}
private void die()
{
Application.LoadLevel("final");
}
}
|
apache-2.0
|
mlaggner/tinyMediaManager
|
src/org/tinymediamanager/ui/components/JHintLabel.java
|
3088
|
/*
* Copyright 2012 - 2015 Manuel Laggner
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinymediamanager.ui.components;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.concurrent.TimeUnit;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.ToolTipManager;
/**
* The class JHintLabel. To provide a label with a hint icon and an extended tooltip
*
* @author Manuel Laggner
*/
public class JHintLabel extends JLabel {
private static final long serialVersionUID = 3027595143561381907L;
private Icon hintIcon = null;
private MouseAdapter tooltipAdatapter = new MouseAdapter() {
final int defaultDismissTimeout = ToolTipManager.sharedInstance().getDismissDelay();
final int dismissDelayMinutes = (int) TimeUnit.MINUTES.toMillis(10); // 10 minutes
@Override
public void mouseEntered(MouseEvent me) {
ToolTipManager.sharedInstance().setDismissDelay(dismissDelayMinutes);
}
@Override
public void mouseExited(MouseEvent me) {
ToolTipManager.sharedInstance().setDismissDelay(defaultDismissTimeout);
}
};
public JHintLabel() {
super();
}
public JHintLabel(String text) {
super(text);
}
public void setHintIcon(Icon icon) {
this.hintIcon = icon;
if (icon != null) {
setBorder(BorderFactory.createEmptyBorder(2, 2, 2, icon.getIconWidth() + 6));
}
}
public Icon getHintIcon() {
return this.hintIcon;
}
@Override
public void setToolTipText(String text) {
// remove the mouse listener if already added
removeMouseListener(tooltipAdatapter);
// and readd
addMouseListener(tooltipAdatapter);
super.setToolTipText(text);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.hintIcon != null) {
int iconWidth = hintIcon.getIconWidth();
int x = getWidth() - iconWidth - 2;
int y = 0;
hintIcon.paintIcon(this, g, x, y);
}
}
}
|
apache-2.0
|
dreamllq/node
|
deps/v8/src/compiler/register-allocator-verifier.cc
|
24534
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/bit-vector.h"
#include "src/compiler/instruction.h"
#include "src/compiler/register-allocator-verifier.h"
namespace v8 {
namespace internal {
namespace compiler {
namespace {
size_t OperandCount(const Instruction* instr) {
return instr->InputCount() + instr->OutputCount() + instr->TempCount();
}
void VerifyEmptyGaps(const Instruction* instr) {
for (int i = Instruction::FIRST_GAP_POSITION;
i <= Instruction::LAST_GAP_POSITION; i++) {
Instruction::GapPosition inner_pos =
static_cast<Instruction::GapPosition>(i);
CHECK(instr->GetParallelMove(inner_pos) == nullptr);
}
}
void VerifyAllocatedGaps(const Instruction* instr) {
for (int i = Instruction::FIRST_GAP_POSITION;
i <= Instruction::LAST_GAP_POSITION; i++) {
Instruction::GapPosition inner_pos =
static_cast<Instruction::GapPosition>(i);
auto moves = instr->GetParallelMove(inner_pos);
if (moves == nullptr) continue;
for (auto move : *moves) {
if (move->IsRedundant()) continue;
CHECK(move->source().IsAllocated() || move->source().IsConstant());
CHECK(move->destination().IsAllocated());
}
}
}
} // namespace
void RegisterAllocatorVerifier::VerifyInput(
const OperandConstraint& constraint) {
CHECK_NE(kSameAsFirst, constraint.type_);
if (constraint.type_ != kImmediate) {
CHECK_NE(InstructionOperand::kInvalidVirtualRegister,
constraint.virtual_register_);
}
}
void RegisterAllocatorVerifier::VerifyTemp(
const OperandConstraint& constraint) {
CHECK_NE(kSameAsFirst, constraint.type_);
CHECK_NE(kImmediate, constraint.type_);
CHECK_NE(kConstant, constraint.type_);
}
void RegisterAllocatorVerifier::VerifyOutput(
const OperandConstraint& constraint) {
CHECK_NE(kImmediate, constraint.type_);
CHECK_NE(InstructionOperand::kInvalidVirtualRegister,
constraint.virtual_register_);
}
RegisterAllocatorVerifier::RegisterAllocatorVerifier(
Zone* zone, const RegisterConfiguration* config,
const InstructionSequence* sequence)
: zone_(zone), config_(config), sequence_(sequence), constraints_(zone) {
constraints_.reserve(sequence->instructions().size());
// TODO(dcarney): model unique constraints.
// Construct OperandConstraints for all InstructionOperands, eliminating
// kSameAsFirst along the way.
for (const auto* instr : sequence->instructions()) {
// All gaps should be totally unallocated at this point.
VerifyEmptyGaps(instr);
const size_t operand_count = OperandCount(instr);
auto* op_constraints = zone->NewArray<OperandConstraint>(operand_count);
size_t count = 0;
for (size_t i = 0; i < instr->InputCount(); ++i, ++count) {
BuildConstraint(instr->InputAt(i), &op_constraints[count]);
VerifyInput(op_constraints[count]);
}
for (size_t i = 0; i < instr->TempCount(); ++i, ++count) {
BuildConstraint(instr->TempAt(i), &op_constraints[count]);
VerifyTemp(op_constraints[count]);
}
for (size_t i = 0; i < instr->OutputCount(); ++i, ++count) {
BuildConstraint(instr->OutputAt(i), &op_constraints[count]);
if (op_constraints[count].type_ == kSameAsFirst) {
CHECK(instr->InputCount() > 0);
op_constraints[count].type_ = op_constraints[0].type_;
op_constraints[count].value_ = op_constraints[0].value_;
}
VerifyOutput(op_constraints[count]);
}
InstructionConstraint instr_constraint = {instr, operand_count,
op_constraints};
constraints()->push_back(instr_constraint);
}
}
void RegisterAllocatorVerifier::VerifyAssignment() {
CHECK(sequence()->instructions().size() == constraints()->size());
auto instr_it = sequence()->begin();
for (const auto& instr_constraint : *constraints()) {
const auto* instr = instr_constraint.instruction_;
// All gaps should be totally allocated at this point.
VerifyAllocatedGaps(instr);
const size_t operand_count = instr_constraint.operand_constaints_size_;
const auto* op_constraints = instr_constraint.operand_constraints_;
CHECK_EQ(instr, *instr_it);
CHECK(operand_count == OperandCount(instr));
size_t count = 0;
for (size_t i = 0; i < instr->InputCount(); ++i, ++count) {
CheckConstraint(instr->InputAt(i), &op_constraints[count]);
}
for (size_t i = 0; i < instr->TempCount(); ++i, ++count) {
CheckConstraint(instr->TempAt(i), &op_constraints[count]);
}
for (size_t i = 0; i < instr->OutputCount(); ++i, ++count) {
CheckConstraint(instr->OutputAt(i), &op_constraints[count]);
}
++instr_it;
}
}
void RegisterAllocatorVerifier::BuildConstraint(const InstructionOperand* op,
OperandConstraint* constraint) {
constraint->value_ = kMinInt;
constraint->virtual_register_ = InstructionOperand::kInvalidVirtualRegister;
if (op->IsConstant()) {
constraint->type_ = kConstant;
constraint->value_ = ConstantOperand::cast(op)->virtual_register();
constraint->virtual_register_ = constraint->value_;
} else if (op->IsImmediate()) {
auto imm = ImmediateOperand::cast(op);
int value = imm->type() == ImmediateOperand::INLINE ? imm->inline_value()
: imm->indexed_value();
constraint->type_ = kImmediate;
constraint->value_ = value;
} else {
CHECK(op->IsUnallocated());
const auto* unallocated = UnallocatedOperand::cast(op);
int vreg = unallocated->virtual_register();
constraint->virtual_register_ = vreg;
if (unallocated->basic_policy() == UnallocatedOperand::FIXED_SLOT) {
constraint->type_ = sequence()->IsFloat(vreg) ? kDoubleSlot : kSlot;
constraint->value_ = unallocated->fixed_slot_index();
} else {
switch (unallocated->extended_policy()) {
case UnallocatedOperand::ANY:
CHECK(false);
break;
case UnallocatedOperand::NONE:
if (sequence()->IsFloat(vreg)) {
constraint->type_ = kNoneDouble;
} else {
constraint->type_ = kNone;
}
break;
case UnallocatedOperand::FIXED_REGISTER:
constraint->type_ = kFixedRegister;
constraint->value_ = unallocated->fixed_register_index();
break;
case UnallocatedOperand::FIXED_DOUBLE_REGISTER:
constraint->type_ = kFixedDoubleRegister;
constraint->value_ = unallocated->fixed_register_index();
break;
case UnallocatedOperand::MUST_HAVE_REGISTER:
if (sequence()->IsFloat(vreg)) {
constraint->type_ = kDoubleRegister;
} else {
constraint->type_ = kRegister;
}
break;
case UnallocatedOperand::MUST_HAVE_SLOT:
constraint->type_ = sequence()->IsFloat(vreg) ? kDoubleSlot : kSlot;
break;
case UnallocatedOperand::SAME_AS_FIRST_INPUT:
constraint->type_ = kSameAsFirst;
break;
}
}
}
}
void RegisterAllocatorVerifier::CheckConstraint(
const InstructionOperand* op, const OperandConstraint* constraint) {
switch (constraint->type_) {
case kConstant:
CHECK(op->IsConstant());
CHECK_EQ(ConstantOperand::cast(op)->virtual_register(),
constraint->value_);
return;
case kImmediate: {
CHECK(op->IsImmediate());
auto imm = ImmediateOperand::cast(op);
int value = imm->type() == ImmediateOperand::INLINE
? imm->inline_value()
: imm->indexed_value();
CHECK_EQ(value, constraint->value_);
return;
}
case kRegister:
CHECK(op->IsRegister());
return;
case kFixedRegister:
CHECK(op->IsRegister());
CHECK_EQ(RegisterOperand::cast(op)->index(), constraint->value_);
return;
case kDoubleRegister:
CHECK(op->IsDoubleRegister());
return;
case kFixedDoubleRegister:
CHECK(op->IsDoubleRegister());
CHECK_EQ(DoubleRegisterOperand::cast(op)->index(), constraint->value_);
return;
case kFixedSlot:
CHECK(op->IsStackSlot());
CHECK_EQ(StackSlotOperand::cast(op)->index(), constraint->value_);
return;
case kSlot:
CHECK(op->IsStackSlot());
return;
case kDoubleSlot:
CHECK(op->IsDoubleStackSlot());
return;
case kNone:
CHECK(op->IsRegister() || op->IsStackSlot());
return;
case kNoneDouble:
CHECK(op->IsDoubleRegister() || op->IsDoubleStackSlot());
return;
case kSameAsFirst:
CHECK(false);
return;
}
}
namespace {
typedef RpoNumber Rpo;
static const int kInvalidVreg = InstructionOperand::kInvalidVirtualRegister;
struct PhiData : public ZoneObject {
PhiData(Rpo definition_rpo, const PhiInstruction* phi, int first_pred_vreg,
const PhiData* first_pred_phi, Zone* zone)
: definition_rpo(definition_rpo),
virtual_register(phi->virtual_register()),
first_pred_vreg(first_pred_vreg),
first_pred_phi(first_pred_phi),
operands(zone) {
operands.reserve(phi->operands().size());
operands.insert(operands.begin(), phi->operands().begin(),
phi->operands().end());
}
const Rpo definition_rpo;
const int virtual_register;
const int first_pred_vreg;
const PhiData* first_pred_phi;
IntVector operands;
};
class PhiMap : public ZoneMap<int, PhiData*>, public ZoneObject {
public:
explicit PhiMap(Zone* zone) : ZoneMap<int, PhiData*>(zone) {}
};
struct OperandLess {
bool operator()(const InstructionOperand* a,
const InstructionOperand* b) const {
return a->CompareModuloType(*b);
}
};
class OperandMap : public ZoneObject {
public:
struct MapValue : public ZoneObject {
MapValue()
: incoming(nullptr),
define_vreg(kInvalidVreg),
use_vreg(kInvalidVreg),
succ_vreg(kInvalidVreg) {}
MapValue* incoming; // value from first predecessor block.
int define_vreg; // valid if this value was defined in this block.
int use_vreg; // valid if this value was used in this block.
int succ_vreg; // valid if propagated back from successor block.
};
class Map
: public ZoneMap<const InstructionOperand*, MapValue*, OperandLess> {
public:
explicit Map(Zone* zone)
: ZoneMap<const InstructionOperand*, MapValue*, OperandLess>(zone) {}
// Remove all entries with keys not in other.
void Intersect(const Map& other) {
if (this->empty()) return;
auto it = this->begin();
OperandLess less;
for (const auto& o : other) {
while (less(it->first, o.first)) {
this->erase(it++);
if (it == this->end()) return;
}
if (it->first->EqualsModuloType(*o.first)) {
++it;
if (it == this->end()) return;
} else {
CHECK(less(o.first, it->first));
}
}
}
};
explicit OperandMap(Zone* zone) : map_(zone) {}
Map& map() { return map_; }
void RunParallelMoves(Zone* zone, const ParallelMove* moves) {
// Compute outgoing mappings.
Map to_insert(zone);
for (auto move : *moves) {
if (move->IsEliminated()) continue;
auto cur = map().find(&move->source());
CHECK(cur != map().end());
auto res =
to_insert.insert(std::make_pair(&move->destination(), cur->second));
// Ensure injectivity of moves.
CHECK(res.second);
}
// Drop current mappings.
for (auto move : *moves) {
if (move->IsEliminated()) continue;
auto cur = map().find(&move->destination());
if (cur != map().end()) map().erase(cur);
}
// Insert new values.
map().insert(to_insert.begin(), to_insert.end());
}
void RunGaps(Zone* zone, const Instruction* instr) {
for (int i = Instruction::FIRST_GAP_POSITION;
i <= Instruction::LAST_GAP_POSITION; i++) {
auto inner_pos = static_cast<Instruction::GapPosition>(i);
auto move = instr->GetParallelMove(inner_pos);
if (move == nullptr) continue;
RunParallelMoves(zone, move);
}
}
void Drop(const InstructionOperand* op) {
auto it = map().find(op);
if (it != map().end()) map().erase(it);
}
void DropRegisters(const RegisterConfiguration* config) {
// TODO(dcarney): sort map by kind and drop range.
for (auto it = map().begin(); it != map().end();) {
auto op = it->first;
if (op->IsRegister() || op->IsDoubleRegister()) {
map().erase(it++);
} else {
++it;
}
}
}
void Define(Zone* zone, const InstructionOperand* op, int virtual_register) {
auto value = new (zone) MapValue();
value->define_vreg = virtual_register;
auto res = map().insert(std::make_pair(op, value));
if (!res.second) res.first->second = value;
}
void Use(const InstructionOperand* op, int use_vreg, bool initial_pass) {
auto it = map().find(op);
CHECK(it != map().end());
auto v = it->second;
if (v->define_vreg != kInvalidVreg) {
CHECK_EQ(v->define_vreg, use_vreg);
}
// Already used this vreg in this block.
if (v->use_vreg != kInvalidVreg) {
CHECK_EQ(v->use_vreg, use_vreg);
return;
}
if (!initial_pass) {
// A value may be defined and used in this block or the use must have
// propagated up.
if (v->succ_vreg != kInvalidVreg) {
CHECK_EQ(v->succ_vreg, use_vreg);
} else {
CHECK_EQ(v->define_vreg, use_vreg);
}
// Mark the use.
it->second->use_vreg = use_vreg;
return;
}
// Go up block list and ensure the correct definition is reached.
for (; v != nullptr; v = v->incoming) {
// Value unused in block.
if (v->define_vreg == kInvalidVreg && v->use_vreg == kInvalidVreg) {
continue;
}
// Found correct definition or use.
CHECK(v->define_vreg == use_vreg || v->use_vreg == use_vreg);
// Mark the use.
it->second->use_vreg = use_vreg;
return;
}
// Use of a non-phi value without definition.
CHECK(false);
}
void UsePhi(const InstructionOperand* op, const PhiData* phi,
bool initial_pass) {
auto it = map().find(op);
CHECK(it != map().end());
auto v = it->second;
int use_vreg = phi->virtual_register;
// Phis are not defined.
CHECK_EQ(kInvalidVreg, v->define_vreg);
// Already used this vreg in this block.
if (v->use_vreg != kInvalidVreg) {
CHECK_EQ(v->use_vreg, use_vreg);
return;
}
if (!initial_pass) {
// A used phi must have propagated its use to a predecessor.
CHECK_EQ(v->succ_vreg, use_vreg);
// Mark the use.
v->use_vreg = use_vreg;
return;
}
// Go up the block list starting at the first predecessor and ensure this
// phi has a correct use or definition.
for (v = v->incoming; v != nullptr; v = v->incoming) {
// Value unused in block.
if (v->define_vreg == kInvalidVreg && v->use_vreg == kInvalidVreg) {
continue;
}
// Found correct definition or use.
if (v->define_vreg != kInvalidVreg) {
CHECK(v->define_vreg == phi->first_pred_vreg);
} else if (v->use_vreg != phi->first_pred_vreg) {
// Walk the phi chain, hunting for a matching phi use.
auto p = phi;
for (; p != nullptr; p = p->first_pred_phi) {
if (p->virtual_register == v->use_vreg) break;
}
CHECK(p);
}
// Mark the use.
it->second->use_vreg = use_vreg;
return;
}
// Use of a phi value without definition.
UNREACHABLE();
}
private:
Map map_;
DISALLOW_COPY_AND_ASSIGN(OperandMap);
};
} // namespace
class RegisterAllocatorVerifier::BlockMaps {
public:
BlockMaps(Zone* zone, const InstructionSequence* sequence)
: zone_(zone),
sequence_(sequence),
phi_map_guard_(sequence->VirtualRegisterCount(), zone),
phi_map_(zone),
incoming_maps_(zone),
outgoing_maps_(zone) {
InitializePhis();
InitializeOperandMaps();
}
bool IsPhi(int virtual_register) {
return phi_map_guard_.Contains(virtual_register);
}
const PhiData* GetPhi(int virtual_register) {
auto it = phi_map_.find(virtual_register);
CHECK(it != phi_map_.end());
return it->second;
}
OperandMap* InitializeIncoming(size_t block_index, bool initial_pass) {
return initial_pass ? InitializeFromFirstPredecessor(block_index)
: InitializeFromIntersection(block_index);
}
void PropagateUsesBackwards() {
typedef std::set<size_t, std::greater<size_t>, zone_allocator<size_t>>
BlockIds;
BlockIds block_ids((BlockIds::key_compare()),
zone_allocator<size_t>(zone()));
// First ensure that incoming contains only keys in all predecessors.
for (auto block : sequence()->instruction_blocks()) {
size_t index = block->rpo_number().ToSize();
block_ids.insert(index);
auto& succ_map = incoming_maps_[index]->map();
for (size_t i = 0; i < block->PredecessorCount(); ++i) {
auto pred_rpo = block->predecessors()[i];
succ_map.Intersect(outgoing_maps_[pred_rpo.ToSize()]->map());
}
}
// Back propagation fixpoint.
while (!block_ids.empty()) {
// Pop highest block_id.
auto block_id_it = block_ids.begin();
const size_t succ_index = *block_id_it;
block_ids.erase(block_id_it);
// Propagate uses back to their definition blocks using succ_vreg.
auto block = sequence()->instruction_blocks()[succ_index];
auto& succ_map = incoming_maps_[succ_index]->map();
for (size_t i = 0; i < block->PredecessorCount(); ++i) {
for (auto& succ_val : succ_map) {
// An incoming map contains no defines.
CHECK_EQ(kInvalidVreg, succ_val.second->define_vreg);
// Compute succ_vreg.
int succ_vreg = succ_val.second->succ_vreg;
if (succ_vreg == kInvalidVreg) {
succ_vreg = succ_val.second->use_vreg;
// Initialize succ_vreg in back propagation chain.
succ_val.second->succ_vreg = succ_vreg;
}
if (succ_vreg == kInvalidVreg) continue;
// May need to transition phi.
if (IsPhi(succ_vreg)) {
auto phi = GetPhi(succ_vreg);
if (phi->definition_rpo.ToSize() == succ_index) {
// phi definition block, transition to pred value.
succ_vreg = phi->operands[i];
}
}
// Push succ_vreg up to all predecessors.
auto pred_rpo = block->predecessors()[i];
auto& pred_map = outgoing_maps_[pred_rpo.ToSize()]->map();
auto& pred_val = *pred_map.find(succ_val.first);
if (pred_val.second->use_vreg != kInvalidVreg) {
CHECK_EQ(succ_vreg, pred_val.second->use_vreg);
}
if (pred_val.second->define_vreg != kInvalidVreg) {
CHECK_EQ(succ_vreg, pred_val.second->define_vreg);
}
if (pred_val.second->succ_vreg != kInvalidVreg) {
CHECK_EQ(succ_vreg, pred_val.second->succ_vreg);
} else {
pred_val.second->succ_vreg = succ_vreg;
block_ids.insert(pred_rpo.ToSize());
}
}
}
}
// Clear uses and back links for second pass.
for (auto operand_map : incoming_maps_) {
for (auto& succ_val : operand_map->map()) {
succ_val.second->incoming = nullptr;
succ_val.second->use_vreg = kInvalidVreg;
}
}
}
private:
OperandMap* InitializeFromFirstPredecessor(size_t block_index) {
auto to_init = outgoing_maps_[block_index];
CHECK(to_init->map().empty());
auto block = sequence()->instruction_blocks()[block_index];
if (block->predecessors().empty()) return to_init;
size_t predecessor_index = block->predecessors()[0].ToSize();
// Ensure not a backedge.
CHECK(predecessor_index < block->rpo_number().ToSize());
auto incoming = outgoing_maps_[predecessor_index];
// Copy map and replace values.
to_init->map() = incoming->map();
for (auto& it : to_init->map()) {
auto incoming = it.second;
it.second = new (zone()) OperandMap::MapValue();
it.second->incoming = incoming;
}
// Copy to incoming map for second pass.
incoming_maps_[block_index]->map() = to_init->map();
return to_init;
}
OperandMap* InitializeFromIntersection(size_t block_index) {
return incoming_maps_[block_index];
}
void InitializeOperandMaps() {
size_t block_count = sequence()->instruction_blocks().size();
incoming_maps_.reserve(block_count);
outgoing_maps_.reserve(block_count);
for (size_t i = 0; i < block_count; ++i) {
incoming_maps_.push_back(new (zone()) OperandMap(zone()));
outgoing_maps_.push_back(new (zone()) OperandMap(zone()));
}
}
void InitializePhis() {
const size_t block_count = sequence()->instruction_blocks().size();
for (size_t block_index = 0; block_index < block_count; ++block_index) {
const auto block = sequence()->instruction_blocks()[block_index];
for (auto phi : block->phis()) {
int first_pred_vreg = phi->operands()[0];
const PhiData* first_pred_phi = nullptr;
if (IsPhi(first_pred_vreg)) {
first_pred_phi = GetPhi(first_pred_vreg);
first_pred_vreg = first_pred_phi->first_pred_vreg;
}
CHECK(!IsPhi(first_pred_vreg));
auto phi_data = new (zone()) PhiData(
block->rpo_number(), phi, first_pred_vreg, first_pred_phi, zone());
auto res =
phi_map_.insert(std::make_pair(phi->virtual_register(), phi_data));
CHECK(res.second);
phi_map_guard_.Add(phi->virtual_register());
}
}
}
typedef ZoneVector<OperandMap*> OperandMaps;
typedef ZoneVector<PhiData*> PhiVector;
Zone* zone() const { return zone_; }
const InstructionSequence* sequence() const { return sequence_; }
Zone* const zone_;
const InstructionSequence* const sequence_;
BitVector phi_map_guard_;
PhiMap phi_map_;
OperandMaps incoming_maps_;
OperandMaps outgoing_maps_;
};
void RegisterAllocatorVerifier::VerifyGapMoves() {
BlockMaps block_maps(zone(), sequence());
VerifyGapMoves(&block_maps, true);
block_maps.PropagateUsesBackwards();
VerifyGapMoves(&block_maps, false);
}
// Compute and verify outgoing values for every block.
void RegisterAllocatorVerifier::VerifyGapMoves(BlockMaps* block_maps,
bool initial_pass) {
const size_t block_count = sequence()->instruction_blocks().size();
for (size_t block_index = 0; block_index < block_count; ++block_index) {
auto current = block_maps->InitializeIncoming(block_index, initial_pass);
const auto block = sequence()->instruction_blocks()[block_index];
for (int instr_index = block->code_start(); instr_index < block->code_end();
++instr_index) {
const auto& instr_constraint = constraints_[instr_index];
const auto instr = instr_constraint.instruction_;
current->RunGaps(zone(), instr);
const auto op_constraints = instr_constraint.operand_constraints_;
size_t count = 0;
for (size_t i = 0; i < instr->InputCount(); ++i, ++count) {
if (op_constraints[count].type_ == kImmediate) continue;
int virtual_register = op_constraints[count].virtual_register_;
auto op = instr->InputAt(i);
if (!block_maps->IsPhi(virtual_register)) {
current->Use(op, virtual_register, initial_pass);
} else {
auto phi = block_maps->GetPhi(virtual_register);
current->UsePhi(op, phi, initial_pass);
}
}
for (size_t i = 0; i < instr->TempCount(); ++i, ++count) {
current->Drop(instr->TempAt(i));
}
if (instr->IsCall()) {
current->DropRegisters(config());
}
for (size_t i = 0; i < instr->OutputCount(); ++i, ++count) {
int virtual_register = op_constraints[count].virtual_register_;
current->Define(zone(), instr->OutputAt(i), virtual_register);
}
}
}
}
} // namespace compiler
} // namespace internal
} // namespace v8
|
apache-2.0
|
VoldemarLeGrand/rest-assured
|
rest-assured/src/main/java/com/jayway/restassured/authentication/PreemptiveAuthProvider.java
|
1388
|
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.restassured.authentication;
public class PreemptiveAuthProvider {
/**
* Use preemptive http basic authentication. This means that the authentication details are sent in the request
* header regardless if the server has challenged for authentication or not.
*
* @param userName The user name.
* @param password The password.
*
* @return The Request specification
*/
public AuthenticationScheme basic(String userName, String password) {
final PreemptiveBasicAuthScheme preemptiveBasicAuthScheme = new PreemptiveBasicAuthScheme();
preemptiveBasicAuthScheme.setUserName(userName);
preemptiveBasicAuthScheme.setPassword(password);
return preemptiveBasicAuthScheme;
}
}
|
apache-2.0
|
ros2/rclpy
|
rclpy/rclpy/expand_topic_name.py
|
1472
|
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy
def expand_topic_name(topic_name, node_name, node_namespace):
"""
Expand a given topic name using given node name and namespace as well.
Note that this function can succeed but the expanded topic name may still
be invalid.
The :py:func:validate_full_topic_name(): should be used on the expanded
topic name to ensure it is valid after expansion.
:param topic_name str: topic name to be expanded
:param node_name str: name of the node that this topic is associated with
:param namespace str: namespace that the topic is within
:returns: expanded topic name which is fully qualified
:raises: ValueError if the topic name, node name or namespace are invalid
"""
return _rclpy.rclpy_expand_topic_name(topic_name, node_name, node_namespace)
|
apache-2.0
|
larsrh/libisabelle
|
modules/pide/2017/src/main/scala/ROOT.scala
|
864
|
/* Title: Pure/ROOT.scala
Author: Makarius
Root of isabelle package.
*/
package object isabelle
{
val ERROR = Exn.ERROR
val error = Exn.error _
val cat_error = Exn.cat_error _
def using[A <: { def close() }, B](x: A)(f: A => B): B = Library.using(x)(f)
val space_explode = Library.space_explode _
val split_lines = Library.split_lines _
val cat_lines = Library.cat_lines _
val terminate_lines = Library.terminate_lines _
val quote = Library.quote _
val commas = Library.commas _
val commas_quote = Library.commas_quote _
def proper[A](x: A): Option[A] = Library.proper(x)
val proper_string = Library.proper_string _
def proper_list[A](list: List[A]): Option[List[A]] = Library.proper_list(list)
object sys {
def exit(rc: Int) = throw info.hupel.isabelle.api.ExitTrap(rc)
def env = _root_.scala.sys.env
}
}
|
apache-2.0
|
Ruwan-Ranganath/wpclone-dating
|
gulpfile.js
|
1950
|
var elixir = require('laravel-elixir');
//require('./elixir-extensions');
elixir(function(mix) {
mix
.phpUnit()
//.compressHtml()
/**
* Copy needed files from /node directories
* to /public directory.
*/
.copy(
'node_modules/font-awesome/fonts',
'public/build/fonts/font-awesome'
)
.copy(
'node_modules/bootstrap-sass/assets/fonts/bootstrap',
'public/build/fonts/bootstrap'
)
.copy(
'node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
'public/js/vendor/bootstrap'
)
/**
* Process frontend SCSS stylesheets
*/
.sass([
'frontend/app.scss',
'plugin/sweetalert/sweetalert.scss'
], 'resources/assets/css/frontend/app.css')
/**
* Combine pre-processed frontend CSS files
*/
.styles([
'frontend/app.css'
], 'public/css/frontend.css')
/**
* Combine frontend scripts
*/
.scripts([
'plugin/sweetalert/sweetalert.min.js',
'plugins.js',
'frontend/app.js'
], 'public/js/frontend.js')
/**
* Process backend SCSS stylesheets
*/
.sass([
'backend/app.scss',
'backend/plugin/toastr/toastr.scss',
'plugin/sweetalert/sweetalert.scss'
], 'resources/assets/css/backend/app.css')
/**
* Combine pre-processed backend CSS files
*/
.styles([
'backend/app.css'
], 'public/css/backend.css')
/**
* Combine backend scripts
*/
.scripts([
'plugin/sweetalert/sweetalert.min.js',
'plugins.js',
'backend/app.js',
'backend/plugin/toastr/toastr.min.js',
'backend/custom.js'
], 'public/js/backend.js')
/**
* Apply version control
*/
.version(["public/css/frontend.css", "public/js/frontend.js", "public/css/backend.css", "public/js/backend.js"]);
});
|
apache-2.0
|
Likeminded/Likeminded
|
db/migrate/20140617095329_create_adsenses.rb
|
201
|
class CreateAdsenses < ActiveRecord::Migration
def change
create_table :adsenses do |t|
t.string :title
t.string :picture
t.integer :order
t.timestamps
end
end
end
|
apache-2.0
|
cjduffett/stork
|
config/config.go
|
2026
|
package config
// DefaultConfig is the default set of configuration options for Stork.
// Note: with this default configuration Stork has enough information to start,
// but not to make requests to AWS. Those configuration options will need
// to be passed from the command line.
var DefaultConfig = &StorkConfig{
ServerHost: "localhost",
ServerPort: "8080",
Debug: false,
DatabaseHost: "localhost:27017",
DatabaseName: "stork",
SyntheaImageID: "",
SyntheaInstanceType: "t2.micro",
SyntheaSecurityGroupID: "",
SyntheaRoleArn: "",
SyntheaSubnetID: "",
MinPopulationSize: 500,
DoneEndpoint: "/task/:id/done",
}
// StorkConfig encapsulates all Stork configuration options.
type StorkConfig struct {
// Stork Server configuration options.
ServerHost string
ServerPort string
Debug bool
// MongoDB configuration options.
DatabaseHost string
DatabaseName string
// The prebuilt Snythea image (already available in AWS) to use.
SyntheaImageID string
// The EC2 instance type to run Synthea on. A compute-optimized instance
// is recommended, for example a c4.large instance.
SyntheaInstanceType string
// The security groups ID (already created in AWS) for Snythea to use.
// Minimally, Synthea must be able to make outbound HTTP/HTTPS requests.
SyntheaSecurityGroupID string
// The ARN of the IAM role (already created in AWS) that Synthea should use.
// Minimally, Synthea must be able to perform an s3:putObject action.
SyntheaRoleArn string
// The VPC subnet to run Synthea in. Typically this a private subnet that must
// be in the same region as Stork and the S3 bucket Synthea writes to.
SyntheaSubnetID string
// The minimum number of patient records that an instance should generate.
// This is practically defined by the towns.json data the feeds a sequential
// synthea run. In that case, 481 patients are generated.
MinPopulationSize int
// The stork endpoint that Synthea instances should ping when done.
DoneEndpoint string
}
|
apache-2.0
|
stasimus/just.ws
|
src/main/scala/com/scalaloader/ws/WebSocketClientHandler.scala
|
1854
|
package com.scalaloader.ws
import io.netty.handler.codec.http.websocketx.{CloseWebSocketFrame, PongWebSocketFrame, TextWebSocketFrame, WebSocketClientHandshaker}
import io.netty.channel.{ChannelHandlerContext, SimpleChannelInboundHandler}
import io.netty.handler.codec.http.FullHttpResponse
import io.netty.util.CharsetUtil
/**
* User: stas
* Date: 06/08/13, 10:40
*/
private class WebSocketClientHandler(handshaker: WebSocketClientHandshaker, client: WebSocketClient)
extends SimpleChannelInboundHandler[AnyRef] {
def channelRead0(ctx: ChannelHandlerContext, msg: AnyRef): Unit = msg match {
case msg: FullHttpResponse if !handshaker.isHandshakeComplete =>
handshaker.finishHandshake(ctx.channel, msg)
client.handler(Connected(client))
case m: FullHttpResponse =>
client.handler(Error(client, new IllegalStateException(
s"Unexpected FullHttpResponse (getStatus=${m.getStatus}, content=${m.content.toString(CharsetUtil.UTF_8)}")))
case m if !handshaker.isHandshakeComplete =>
client.handler(Error(client, new IllegalStateException(
s"Unexpected FullHttpResponse (content=$m")))
case f: TextWebSocketFrame =>
client.handler(TextMessage(client, f.text))
case _: PongWebSocketFrame =>
case _: CloseWebSocketFrame => ctx.channel.close
}
override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit =
if (!handshaker.isHandshakeComplete)
client.handler(ConnectionFailed(client, Some(cause)))
else
client.handler(Error(client, cause))
override def handlerAdded(ctx: ChannelHandlerContext): Unit = client.handler(Connecting)
override def channelActive(ctx: ChannelHandlerContext): Unit = handshaker.handshake(ctx.channel)
override def channelInactive(ctx: ChannelHandlerContext): Unit = client.handler(Disconnected(client))
}
|
apache-2.0
|
dvanherbergen/robotframework-filelibrary
|
src/main/java/io/github/dvanherbergen/filelibrary/FileLibrary.java
|
1152
|
package io.github.dvanherbergen.filelibrary;
import org.robotframework.javalib.library.AnnotationLibrary;
public class FileLibrary extends AnnotationLibrary {
public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL";
// @formatter:off
public static final String LIBRARY_DOCUMENTATION = "FileLibrary is a Robot Framework test library for generating test data files.\n\n"
+ "Built in variables: ${now}, ${today}\n\n"
+ "For SQL related commands, you can specify SQL satements either directly in the argument or provide them in an .sql file. \n\n\n"
+ " | *IMPORTANT* | For statements included directly in the test case, you need to escape any template data variables. If you do not, it will not be able to find the value. | \n"
+ " | _Example_ | Execute SQL update mytable set value = 2 where id = \\${my_id} | \n";
// @formatter:on
public FileLibrary() {
super("io/github/dvanherbergen/filelibrary/keyword/**/*.class");
}
@Override
public String getKeywordDocumentation(String keywordName) {
if (keywordName.equals("__intro__"))
return LIBRARY_DOCUMENTATION;
return super.getKeywordDocumentation(keywordName);
}
}
|
apache-2.0
|
mbohlool/client-python
|
kubernetes/client/models/apps_v1beta1_rolling_update_deployment.py
|
6612
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class AppsV1beta1RollingUpdateDeployment(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'max_surge': 'object',
'max_unavailable': 'object'
}
attribute_map = {
'max_surge': 'maxSurge',
'max_unavailable': 'maxUnavailable'
}
def __init__(self, max_surge=None, max_unavailable=None):
"""
AppsV1beta1RollingUpdateDeployment - a model defined in Swagger
"""
self._max_surge = None
self._max_unavailable = None
self.discriminator = None
if max_surge is not None:
self.max_surge = max_surge
if max_unavailable is not None:
self.max_unavailable = max_unavailable
@property
def max_surge(self):
"""
Gets the max_surge of this AppsV1beta1RollingUpdateDeployment.
The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new RC can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new RC can be scaled up further, ensuring that total number of pods running at any time during the update is atmost 130% of desired pods.
:return: The max_surge of this AppsV1beta1RollingUpdateDeployment.
:rtype: object
"""
return self._max_surge
@max_surge.setter
def max_surge(self, max_surge):
"""
Sets the max_surge of this AppsV1beta1RollingUpdateDeployment.
The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new RC can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new RC can be scaled up further, ensuring that total number of pods running at any time during the update is atmost 130% of desired pods.
:param max_surge: The max_surge of this AppsV1beta1RollingUpdateDeployment.
:type: object
"""
self._max_surge = max_surge
@property
def max_unavailable(self):
"""
Gets the max_unavailable of this AppsV1beta1RollingUpdateDeployment.
The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old RC can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old RC can be scaled down further, followed by scaling up the new RC, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods.
:return: The max_unavailable of this AppsV1beta1RollingUpdateDeployment.
:rtype: object
"""
return self._max_unavailable
@max_unavailable.setter
def max_unavailable(self, max_unavailable):
"""
Sets the max_unavailable of this AppsV1beta1RollingUpdateDeployment.
The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old RC can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old RC can be scaled down further, followed by scaling up the new RC, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods.
:param max_unavailable: The max_unavailable of this AppsV1beta1RollingUpdateDeployment.
:type: object
"""
self._max_unavailable = max_unavailable
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, AppsV1beta1RollingUpdateDeployment):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
apache-2.0
|
vcdemon/wechat-framework
|
wechat-core/src/main/java/com/itfvck/wechatframework/core/util/http/https/HttpsClient.java
|
1691
|
/**
*
*/
package com.itfvck.wechatframework.core.util.http.https;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* 支持https的所有站点信任
*
* @author ChengNing
* @date 2015年1月13日
*/
class HttpsClient extends DefaultHttpClient {
/**
* 重写DefaultHttpClient
*
* @throws Exception
*/
public HttpsClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
|
apache-2.0
|
Lovin000/AbyssalCraft
|
src/main/java/com/shinoow/abyssalcraft/common/items/ItemDarkstoneSword.java
|
4451
|
/**AbyssalCraft
*Copyright 2012-2014 Shinoow
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package com.shinoow.abyssalcraft.common.items;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.world.World;
import com.google.common.collect.Multimap;
import com.shinoow.abyssalcraft.common.util.EnumToolMaterialAC;
public class ItemDarkstoneSword extends ItemSword
{
private float weaponDamage;
private final EnumToolMaterialAC toolMaterial;
public ItemDarkstoneSword(EnumToolMaterialAC darkstone)
{
super(ToolMaterial.valueOf("DARKSTONE"));
toolMaterial = darkstone;
maxStackSize = 1;
setMaxDamage(darkstone.getMaxUses());
weaponDamage = 4.0F + darkstone.getDamageVsEntity();
}
/**
* Returns the strength of the stack against a given block. 1.0F base, (Quality+1)*2 if correct blocktype, 1.5F if
* sword
*/
public float getStrVsBlock(ItemStack par1ItemStack, Block par2Block)
{
return par2Block != Blocks.web ? 1.5F : 15F;
}
/**
* Current implementations of this method in child classes do not use the entry argument beside ev. They just raise
* the damage on the stack.
*/
@Override
public boolean hitEntity(ItemStack par1ItemStack, EntityLivingBase par2EntityLivingBase, EntityLivingBase par3EntityLivingBase)
{
par1ItemStack.damageItem(1, par3EntityLivingBase);
return true;
}
@Override
public boolean onBlockDestroyed(ItemStack par1ItemStack, World par2World, Block par3, int par4, int par5, int par6, EntityLivingBase par7EntityLivingBase)
{
if (par3.getBlockHardness(par2World, par4, par5, par6) != 0.0D)
{
par1ItemStack.damageItem(1, par7EntityLivingBase);
}
return true;
}
public float func_82803_g()
{
return toolMaterial.getDamageVsEntity();
}
/**
* Returns True is the item is renderer in full 3D when hold.
*/
@Override
public boolean isFull3D()
{
return true;
}
/**
* returns the action that specifies what animation to play when the items is being used
*/
@Override
public EnumAction getItemUseAction(ItemStack par1ItemStack)
{
return EnumAction.block;
}
/**
* How long it takes to use or consume an item
*/
@Override
public int getMaxItemUseDuration(ItemStack par1ItemStack)
{
return 0x11940;
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
@Override
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
par3EntityPlayer.setItemInUse(par1ItemStack, getMaxItemUseDuration(par1ItemStack));
return par1ItemStack;
}
/**
* Returns if the item (tool) can harvest results from the block type.
*/
public boolean canHarvestBlock(Block par1Block)
{
return par1Block == Blocks.web;
}
/**
* Return the enchantability factor of the item, most of the time is based on material.
*/
@Override
public int getItemEnchantability()
{
return toolMaterial.getEnchantability();
}
/**
* Return whether this item is repairable in an anvil.
*/
@Override
public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack)
{
return toolMaterial.getToolCraftingMaterial() == par2ItemStack.getItem() ? true : super.getIsRepairable(par1ItemStack, par2ItemStack);
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Multimap getItemAttributeModifiers()
{
Multimap multimap = super.getItemAttributeModifiers();
multimap.put(SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(), new AttributeModifier(field_111210_e, "Weapon modifier", weaponDamage, 0));
return multimap;
}
}
|
apache-2.0
|
KayLerch/alexa-pokemon
|
src/main/java/io/klerch/alexa/pokemon/api/What3Words.java
|
2423
|
package io.klerch.alexa.pokemon.api;
import io.klerch.alexa.pokemon.SkillConfig;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
public class What3Words {
public static Optional<Pair<Double, Double>> resolve(final String s1, final String s2, final String s3) {
try {
final URI uri = new URIBuilder(SkillConfig.getProperty("What3WordsForwardEndpoint"))
.addParameter("addr", s1 + "." + s2 + "." + s3)
.addParameter("format", "xml")
.addParameter("key", SkillConfig.getProperty("What3WordsApiKey"))
.build();
final HttpGet httpGet = new HttpGet(uri.toURL().toString());
final HttpResponse response = HttpClientBuilder.create().build().execute(httpGet);
Validate.inclusiveBetween(200, 399, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
final String html = IOUtils.toString(response.getEntity().getContent());
final Document doc = Jsoup.parse(html);
final String latitude = doc.getElementsByTag("response").first()
.getElementsByTag("geometry").first()
.getElementsByTag("lat").first()
.text();
final String longitude = doc.getElementsByTag("response").first()
.getElementsByTag("geometry").first()
.getElementsByTag("lng").first()
.text();
return Optional.of(new ImmutablePair<>(Double.parseDouble(longitude), Double.parseDouble(latitude)));
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Optional.empty();
}
}
|
apache-2.0
|
ydc201211/bookdownload
|
js/register.js
|
24
|
$(function() {
});
|
apache-2.0
|
citrix/terraform-provider-netscaler
|
vendor/github.com/citrix/adc-nitro-go/resource/config/vpn/vpnvserver_auditnslogpolicy_binding.go
|
3863
|
/*
* Copyright (c) 2021 Citrix Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vpn
/**
* Binding class showing the auditnslogpolicy that can be bound to vpnvserver.
*/
type Vpnvserverauditnslogpolicybinding struct {
/**
* The name of the policy, if any, bound to the VPN virtual server.
*/
Policy string `json:"policy,omitempty"`
/**
* Integer specifying the policy's priority. The lower the number, the higher the priority. Policies are evaluated in the order of their priority numbers. Maximum value for default syntax policies is 2147483647 and for classic policies is 64000.
*/
Priority int `json:"priority,omitempty"`
Acttype int `json:"acttype,omitempty"`
/**
* Name of the virtual server.
*/
Name string `json:"name,omitempty"`
/**
* Binds the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only via a primary authentication method but also via a secondary authentication method. User groups are aggregated across both. The user name must be exactly the same for both authentication methods, but they can require different passwords.
*/
Secondary bool `json:"secondary,omitempty"`
/**
* Binds the authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called if primary and/or secondary authentication has succeeded.
*/
Groupextraction bool `json:"groupextraction,omitempty"`
/**
* Applicable only to advance vpn session policy. Expression or other value specifying the next policy to evaluate if the current policy evaluates to TRUE. Specify one of the following values:
* NEXT - Evaluate the policy with the next higher priority number.
* END - End policy evaluation.
* An expression that evaluates to a number.
If you specify an expression, the number to which it evaluates determines the next policy to evaluate, as follows:
* If the expression evaluates to a higher numbered priority, the policy with that priority is evaluated next.
* If the expression evaluates to the priority of the current policy, the policy with the next higher numbered priority is evaluated next.
* If the expression evaluates to a number that is larger than the largest numbered priority, policy evaluation ends.
An UNDEF event is triggered if:
* The expression is invalid.
* The expression evaluates to a priority number that is numerically lower than the current policy's priority.
* The expression evaluates to a priority number that is between the current policy's priority number (say, 30) and the highest priority number (say, 100), but does not match any configured priority number (for example, the expression evaluates to the number 85). This example assumes that the priority number increments by 10 for every successive policy, and therefore a priority number of 85 does not exist in the policy label.
*/
Gotopriorityexpression string `json:"gotopriorityexpression,omitempty"`
/**
* Bind point to which to bind the policy. Applies only to rewrite and cache policies. If you do not set this parameter, the policy is bound to REQ_DEFAULT or RES_DEFAULT, depending on whether the policy rule is a response-time or a request-time expression.
*/
Bindpoint string `json:"bindpoint,omitempty"`
}
|
apache-2.0
|
bjorndm/prebake
|
code/third_party/bdb/src/com/sleepycat/je/config/ConfigParam.java
|
3891
|
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2000-2010 Oracle. All rights reserved.
*
* $Id: ConfigParam.java,v 1.40 2010/01/04 15:50:40 cwl Exp $
*/
package com.sleepycat.je.config;
import com.sleepycat.je.EnvironmentFailureException;
/**
* A ConfigParam embodies the metadata about a JE configuration parameter:
* the parameter name, default value, and a validation method.
*
* Validation can be done in the scope of this parameter, or as a function of
* other parameters.
*/
public class ConfigParam {
protected String name;
private String defaultValue;
private boolean mutable;
private boolean forReplication;
private boolean isMultiValueParam;
/*
* Create a String parameter.
*/
public ConfigParam(String configName,
String configDefault,
boolean mutable,
boolean forReplication)
throws IllegalArgumentException {
if (configName == null) {
name = null;
} else {
/*
* For Multi-Value params (i.e. those whose names end with ".#"),
* strip the .# off the end of the name before storing and flag it
* with isMultiValueParam=true.
*/
int mvFlagIdx = configName.indexOf(".#");
if (mvFlagIdx < 0) {
name = configName;
isMultiValueParam = false;
} else {
name = configName.substring(0, mvFlagIdx);
isMultiValueParam = true;
}
}
defaultValue = configDefault;
this.mutable = mutable;
this.forReplication = forReplication;
/* Check that the name and default value are valid */
validateName(name);
validateValue(configDefault);
/* Add it the list of supported environment parameters. */
EnvironmentParams.addSupportedParam(this);
}
/*
* Return the parameter name of a multi-value parameter. e.g.
* "je.rep.remote.address.foo" => "je.rep.remote.address"
*/
public static String multiValueParamName(String paramName) {
int mvParamIdx = paramName.lastIndexOf('.');
if (mvParamIdx < 0) {
return null;
}
return paramName.substring(0, mvParamIdx);
}
/*
* Return the label of a multi-value parameter. e.g.
* "je.rep.remote.address.foo" => foo.
*/
public static String mvParamIndex(String paramName) {
int mvParamIdx = paramName.lastIndexOf('.');
return paramName.substring(mvParamIdx + 1);
}
public String getName() {
return name;
}
public String getDefault() {
return defaultValue;
}
public boolean isMutable() {
return mutable;
}
public boolean isForReplication() {
return forReplication;
}
public void setForReplication(boolean forReplication) {
this.forReplication = forReplication;
}
public boolean isMultiValueParam() {
return isMultiValueParam;
}
/**
* A param name can't be null or 0 length
*/
private void validateName(String name)
throws IllegalArgumentException {
if ((name == null) || (name.length() < 1)) {
throw EnvironmentFailureException.unexpectedState
("A configuration parameter name can't be null or 0 length");
}
}
/**
* Validate your value. (No default validation for strings.)
* May be overridden for (e.g.) Multi-value params.
*
* @throws IllegalArgumentException via XxxConfig.setXxx methods and
* XxxConfig(Properties) ctor.
*/
public void validateValue(String value)
throws IllegalArgumentException {
}
@Override
public String toString() {
return name;
}
}
|
apache-2.0
|
boneman1231/org.apache.felix
|
trunk/configadmin/src/test/java/org/apache/felix/cm/impl/ConfigurationAdapterTest.java
|
6109
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.cm.impl;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;
import junit.framework.TestCase;
import org.apache.felix.cm.MockPersistenceManager;
import org.apache.felix.cm.PersistenceManager;
import org.osgi.framework.Constants;
import org.osgi.service.cm.Configuration;
public class ConfigurationAdapterTest extends TestCase
{
private static final String SCALAR = "scalar";
private static final String STRING_VALUE = "String Value";
private static final String STRING_VALUE2 = "Another String Value";
private static final String ARRAY = "array";
private final String[] ARRAY_VALUE;
private static final String COLLECTION = "collection";
private final Collection COLLECTION_VALUE;
private static final String TEST_PID = "test.pid";
private static final String TEST_LOCATION = "test:location";
private final PersistenceManager pm = new MockPersistenceManager();
private final MockConfigurationManager configMgr = new MockConfigurationManager()
{
boolean isActive()
{
return true;
}
};
{
ARRAY_VALUE = new String[]
{ STRING_VALUE };
COLLECTION_VALUE = new ArrayList();
COLLECTION_VALUE.add( STRING_VALUE );
}
private Configuration getConfiguration() throws IOException
{
ConfigurationImpl cimpl = new ConfigurationImpl( configMgr, pm, TEST_PID, null, TEST_LOCATION );
return new ConfigurationAdapter( null, cimpl );
}
public void testScalar() throws IOException
{
Configuration cimpl = getConfiguration();
Dictionary props = cimpl.getProperties();
assertNull( "Configuration is fresh", props );
props = new Hashtable();
props.put( SCALAR, STRING_VALUE );
cimpl.update( props );
Dictionary newProps = cimpl.getProperties();
assertNotNull( "Configuration is not fresh", newProps );
assertEquals( "Expect 2 elements", 2, newProps.size() );
assertEquals( "Service.pid must match", TEST_PID, newProps.get( Constants.SERVICE_PID ) );
assertEquals( "Scalar value must match", STRING_VALUE, newProps.get( SCALAR ) );
}
public void testArray() throws IOException
{
Configuration cimpl = getConfiguration();
Dictionary props = cimpl.getProperties();
assertNull( "Configuration is fresh", props );
props = new Hashtable();
props.put( ARRAY, ARRAY_VALUE );
cimpl.update( props );
Dictionary newProps = cimpl.getProperties();
assertNotNull( "Configuration is not fresh", newProps );
assertEquals( "Expect 2 elements", 2, newProps.size() );
assertEquals( "Service.pid must match", TEST_PID, newProps.get( Constants.SERVICE_PID ) );
Object testProp = newProps.get( ARRAY );
assertNotNull( testProp );
assertTrue( testProp.getClass().isArray() );
assertEquals( 1, Array.getLength( testProp ) );
assertEquals( STRING_VALUE, Array.get( testProp, 0 ) );
// modify the array property
Array.set( testProp, 0, STRING_VALUE2 );
// the array element change must not be reflected in the configuration
Dictionary newProps2 = cimpl.getProperties();
Object testProp2 = newProps2.get( ARRAY );
assertNotNull( testProp2 );
assertTrue( testProp2.getClass().isArray() );
assertEquals( 1, Array.getLength( testProp2 ) );
assertEquals( STRING_VALUE, Array.get( testProp2, 0 ) );
}
public void testCollection() throws IOException
{
Configuration cimpl = getConfiguration();
Dictionary props = cimpl.getProperties();
assertNull( "Configuration is fresh", props );
props = new Hashtable();
props.put( COLLECTION, COLLECTION_VALUE );
cimpl.update( props );
Dictionary newProps = cimpl.getProperties();
assertNotNull( "Configuration is not fresh", newProps );
assertEquals( "Expect 2 elements", 2, newProps.size() );
assertEquals( "Service.pid must match", TEST_PID, newProps.get( Constants.SERVICE_PID ) );
Object testProp = newProps.get( COLLECTION );
assertNotNull( testProp );
assertTrue( testProp instanceof Collection );
Collection coll = ( Collection ) testProp;
assertEquals( 1, coll.size() );
assertEquals( STRING_VALUE, coll.iterator().next() );
// modify the array property
coll.clear();
coll.add( STRING_VALUE2 );
// the array element change must not be reflected in the configuration
Dictionary newProps2 = cimpl.getProperties();
Object testProp2 = newProps2.get( COLLECTION );
assertNotNull( testProp2 );
assertTrue( testProp2 instanceof Collection );
Collection coll2 = ( Collection ) testProp2;
assertEquals( 1, coll2.size() );
assertEquals( STRING_VALUE, coll2.iterator().next() );
}
}
|
apache-2.0
|
igarashitm/camel
|
components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelContextFactoryBean.java
|
42495
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.core.xml;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelException;
import org.apache.camel.ManagementStatisticsLevel;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.ShutdownRoute;
import org.apache.camel.ShutdownRunningTask;
import org.apache.camel.builder.ErrorHandlerBuilderRef;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.component.properties.PropertiesParser;
import org.apache.camel.component.properties.PropertiesResolver;
import org.apache.camel.management.DefaultManagementAgent;
import org.apache.camel.management.DefaultManagementLifecycleStrategy;
import org.apache.camel.management.DefaultManagementStrategy;
import org.apache.camel.management.ManagedManagementStrategy;
import org.apache.camel.model.ContextScanDefinition;
import org.apache.camel.model.IdentifiedType;
import org.apache.camel.model.InterceptDefinition;
import org.apache.camel.model.InterceptFromDefinition;
import org.apache.camel.model.InterceptSendToEndpointDefinition;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.OnCompletionDefinition;
import org.apache.camel.model.OnExceptionDefinition;
import org.apache.camel.model.PackageScanDefinition;
import org.apache.camel.model.RouteBuilderDefinition;
import org.apache.camel.model.RouteContainer;
import org.apache.camel.model.RouteContextRefDefinition;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.model.RouteDefinitionHelper;
import org.apache.camel.model.ThreadPoolProfileDefinition;
import org.apache.camel.model.config.PropertiesDefinition;
import org.apache.camel.model.dataformat.DataFormatsDefinition;
import org.apache.camel.processor.interceptor.BacklogTracer;
import org.apache.camel.processor.interceptor.Delayer;
import org.apache.camel.processor.interceptor.HandleFault;
import org.apache.camel.processor.interceptor.TraceFormatter;
import org.apache.camel.processor.interceptor.Tracer;
import org.apache.camel.spi.ClassResolver;
import org.apache.camel.spi.Debugger;
import org.apache.camel.spi.EndpointStrategy;
import org.apache.camel.spi.EventFactory;
import org.apache.camel.spi.EventNotifier;
import org.apache.camel.spi.ExecutorServiceManager;
import org.apache.camel.spi.FactoryFinderResolver;
import org.apache.camel.spi.InflightRepository;
import org.apache.camel.spi.InterceptStrategy;
import org.apache.camel.spi.LifecycleStrategy;
import org.apache.camel.spi.ManagementNamingStrategy;
import org.apache.camel.spi.ManagementStrategy;
import org.apache.camel.spi.NodeIdFactory;
import org.apache.camel.spi.PackageScanClassResolver;
import org.apache.camel.spi.PackageScanFilter;
import org.apache.camel.spi.ProcessorFactory;
import org.apache.camel.spi.RuntimeEndpointRegistry;
import org.apache.camel.spi.ShutdownStrategy;
import org.apache.camel.spi.StreamCachingStrategy;
import org.apache.camel.spi.ThreadPoolFactory;
import org.apache.camel.spi.ThreadPoolProfile;
import org.apache.camel.spi.UnitOfWorkFactory;
import org.apache.camel.spi.UuidGenerator;
import org.apache.camel.util.CamelContextHelper;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A factory to create and initialize a
* {@link CamelContext} and install routes either explicitly configured
* or found by searching the classpath for Java classes which extend
* {@link org.apache.camel.builder.RouteBuilder}.
*
* @version
*/
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class AbstractCamelContextFactoryBean<T extends ModelCamelContext> extends IdentifiedType implements RouteContainer {
/**
* JVM system property to control lazy loading of type converters.
*/
public static final String LAZY_LOAD_TYPE_CONVERTERS = "CamelLazyLoadTypeConverters";
private static final Logger LOG = LoggerFactory.getLogger(AbstractCamelContextFactoryBean.class);
@XmlTransient
private List<RoutesBuilder> builders = new ArrayList<RoutesBuilder>();
@XmlTransient
private ClassLoader contextClassLoaderOnStart;
@XmlTransient
private final AtomicBoolean routesSetupDone = new AtomicBoolean();
public AbstractCamelContextFactoryBean() {
// Keep track of the class loader for when we actually do start things up
contextClassLoaderOnStart = Thread.currentThread().getContextClassLoader();
}
public T getObject() throws Exception {
return getContext();
}
public abstract Class<T> getObjectType();
public boolean isSingleton() {
return true;
}
public ClassLoader getContextClassLoaderOnStart() {
return contextClassLoaderOnStart;
}
public void afterPropertiesSet() throws Exception {
if (ObjectHelper.isEmpty(getId())) {
throw new IllegalArgumentException("Id must be set");
}
// set the package scan resolver as soon as possible
PackageScanClassResolver packageResolver = getBeanForType(PackageScanClassResolver.class);
if (packageResolver != null) {
LOG.info("Using custom PackageScanClassResolver: {}", packageResolver);
getContext().setPackageScanClassResolver(packageResolver);
}
// then set custom properties
if (getProperties() != null) {
getContext().setProperties(getProperties().asMap());
}
// and enable lazy loading of type converters if applicable
initLazyLoadTypeConverters();
setupCustomServices();
// set the custom registry if defined
initCustomRegistry(getContext());
// setup property placeholder so we got it as early as possible
initPropertyPlaceholder();
// setup JMX agent at first
initJMXAgent();
Tracer tracer = getBeanForType(Tracer.class);
if (tracer != null) {
// use formatter if there is a TraceFormatter bean defined
TraceFormatter formatter = getBeanForType(TraceFormatter.class);
if (formatter != null) {
tracer.setFormatter(formatter);
}
LOG.info("Using custom Tracer: {}", tracer);
getContext().addInterceptStrategy(tracer);
}
BacklogTracer backlogTracer = getBeanForType(BacklogTracer.class);
if (backlogTracer != null) {
LOG.info("Using custom BacklogTracer: {}", backlogTracer);
getContext().addInterceptStrategy(backlogTracer);
}
HandleFault handleFault = getBeanForType(HandleFault.class);
if (handleFault != null) {
LOG.info("Using custom HandleFault: {}", handleFault);
getContext().addInterceptStrategy(handleFault);
}
Delayer delayer = getBeanForType(Delayer.class);
if (delayer != null) {
LOG.info("Using custom Delayer: {}", delayer);
getContext().addInterceptStrategy(delayer);
}
InflightRepository inflightRepository = getBeanForType(InflightRepository.class);
if (inflightRepository != null) {
LOG.info("Using custom InflightRepository: {}", inflightRepository);
getContext().setInflightRepository(inflightRepository);
}
ManagementStrategy managementStrategy = getBeanForType(ManagementStrategy.class);
if (managementStrategy != null) {
LOG.info("Using custom ManagementStrategy: {}", managementStrategy);
getContext().setManagementStrategy(managementStrategy);
}
ManagementNamingStrategy managementNamingStrategy = getBeanForType(ManagementNamingStrategy.class);
if (managementNamingStrategy != null) {
LOG.info("Using custom ManagementNamingStrategy: {}", managementNamingStrategy);
getContext().getManagementStrategy().setManagementNamingStrategy(managementNamingStrategy);
}
EventFactory eventFactory = getBeanForType(EventFactory.class);
if (eventFactory != null) {
LOG.info("Using custom EventFactory: {}", eventFactory);
getContext().getManagementStrategy().setEventFactory(eventFactory);
}
UnitOfWorkFactory unitOfWorkFactory = getBeanForType(UnitOfWorkFactory.class);
if (unitOfWorkFactory != null) {
LOG.info("Using custom UnitOfWorkFactory: {}", unitOfWorkFactory);
getContext().setUnitOfWorkFactory(unitOfWorkFactory);
}
RuntimeEndpointRegistry runtimeEndpointRegistry = getBeanForType(RuntimeEndpointRegistry.class);
if (runtimeEndpointRegistry != null) {
LOG.info("Using custom RuntimeEndpointRegistry: {}", runtimeEndpointRegistry);
getContext().setRuntimeEndpointRegistry(runtimeEndpointRegistry);
}
// set the event notifier strategies if defined
Map<String, EventNotifier> eventNotifiers = getContext().getRegistry().findByTypeWithName(EventNotifier.class);
if (eventNotifiers != null && !eventNotifiers.isEmpty()) {
for (Entry<String, EventNotifier> entry : eventNotifiers.entrySet()) {
EventNotifier notifier = entry.getValue();
// do not add if already added, for instance a tracer that is also an InterceptStrategy class
if (!getContext().getManagementStrategy().getEventNotifiers().contains(notifier)) {
LOG.info("Using custom EventNotifier with id: {} and implementation: {}", entry.getKey(), notifier);
getContext().getManagementStrategy().addEventNotifier(notifier);
}
}
}
// set endpoint strategies if defined
Map<String, EndpointStrategy> endpointStrategies = getContext().getRegistry().findByTypeWithName(EndpointStrategy.class);
if (endpointStrategies != null && !endpointStrategies.isEmpty()) {
for (Entry<String, EndpointStrategy> entry : endpointStrategies.entrySet()) {
EndpointStrategy strategy = entry.getValue();
LOG.info("Using custom EndpointStrategy with id: {} and implementation: {}", entry.getKey(), strategy);
getContext().addRegisterEndpointCallback(strategy);
}
}
// shutdown
ShutdownStrategy shutdownStrategy = getBeanForType(ShutdownStrategy.class);
if (shutdownStrategy != null) {
LOG.info("Using custom ShutdownStrategy: " + shutdownStrategy);
getContext().setShutdownStrategy(shutdownStrategy);
}
// add global interceptors
Map<String, InterceptStrategy> interceptStrategies = getContext().getRegistry().findByTypeWithName(InterceptStrategy.class);
if (interceptStrategies != null && !interceptStrategies.isEmpty()) {
for (Entry<String, InterceptStrategy> entry : interceptStrategies.entrySet()) {
InterceptStrategy strategy = entry.getValue();
// do not add if already added, for instance a tracer that is also an InterceptStrategy class
if (!getContext().getInterceptStrategies().contains(strategy)) {
LOG.info("Using custom InterceptStrategy with id: {} and implementation: {}", entry.getKey(), strategy);
getContext().addInterceptStrategy(strategy);
}
}
}
// set the lifecycle strategy if defined
Map<String, LifecycleStrategy> lifecycleStrategies = getContext().getRegistry().findByTypeWithName(LifecycleStrategy.class);
if (lifecycleStrategies != null && !lifecycleStrategies.isEmpty()) {
for (Entry<String, LifecycleStrategy> entry : lifecycleStrategies.entrySet()) {
LifecycleStrategy strategy = entry.getValue();
// do not add if already added, for instance a tracer that is also an InterceptStrategy class
if (!getContext().getLifecycleStrategies().contains(strategy)) {
LOG.info("Using custom LifecycleStrategy with id: {} and implementation: {}", entry.getKey(), strategy);
getContext().addLifecycleStrategy(strategy);
}
}
}
// set the default thread pool profile if defined
initThreadPoolProfiles(getContext());
// Set the application context and camelContext for the beanPostProcessor
initBeanPostProcessor(getContext());
// init camel context
initCamelContext(getContext());
// init stream caching strategy
initStreamCachingStrategy();
}
/**
* Setup all the routes which must be done prior starting {@link CamelContext}.
*/
protected void setupRoutes() throws Exception {
if (routesSetupDone.compareAndSet(false, true)) {
LOG.debug("Setting up routes");
// must init route refs before we prepare the routes below
initRouteRefs();
// do special preparation for some concepts such as interceptors and policies
// this is needed as JAXB does not build exactly the same model definition as Spring DSL would do
// using route builders. So we have here a little custom code to fix the JAXB gaps
prepareRoutes();
// and add the routes
getContext().addRouteDefinitions(getRoutes());
LOG.debug("Found JAXB created routes: {}", getRoutes());
findRouteBuilders();
installRoutes();
}
}
/**
* Do special preparation for some concepts such as interceptors and policies
* this is needed as JAXB does not build exactly the same model definition as Spring DSL would do
* using route builders. So we have here a little custom code to fix the JAXB gaps
*/
private void prepareRoutes() {
for (RouteDefinition route : getRoutes()) {
// sanity check first as the route is created using XML
RouteDefinitionHelper.sanityCheckRoute(route);
// leverage logic from route definition helper to prepare the route
RouteDefinitionHelper.prepareRoute(getContext(), route, getOnExceptions(), getIntercepts(), getInterceptFroms(),
getInterceptSendToEndpoints(), getOnCompletions());
// mark the route as prepared now
route.markPrepared();
}
}
protected abstract void initCustomRegistry(T context);
@SuppressWarnings("deprecation")
protected void initLazyLoadTypeConverters() {
if (getLazyLoadTypeConverters() != null) {
getContext().setLazyLoadTypeConverters(getLazyLoadTypeConverters());
} else if (System.getProperty(LAZY_LOAD_TYPE_CONVERTERS) != null) {
// suppose a JVM property to control it so we can use that for example for unit testing
// to speedup testing by enabling lazy loading of type converters
String lazy = System.getProperty(LAZY_LOAD_TYPE_CONVERTERS);
if ("true".equalsIgnoreCase(lazy)) {
getContext().setLazyLoadTypeConverters(true);
} else if ("false".equalsIgnoreCase(lazy)) {
getContext().setLazyLoadTypeConverters(false);
} else {
throw new IllegalArgumentException("System property with key " + LAZY_LOAD_TYPE_CONVERTERS + " has unknown value: " + lazy);
}
}
}
protected void initJMXAgent() throws Exception {
CamelJMXAgentDefinition camelJMXAgent = getCamelJMXAgent();
boolean disabled = false;
if (camelJMXAgent != null) {
disabled = CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getDisabled());
}
if (disabled) {
LOG.info("JMXAgent disabled");
// clear the existing lifecycle strategies define by the DefaultCamelContext constructor
getContext().getLifecycleStrategies().clear();
// no need to add a lifecycle strategy as we do not need one as JMX is disabled
getContext().setManagementStrategy(new DefaultManagementStrategy());
} else if (camelJMXAgent != null) {
LOG.info("JMXAgent enabled: {}", camelJMXAgent);
DefaultManagementAgent agent = new DefaultManagementAgent(getContext());
agent.setConnectorPort(CamelContextHelper.parseInteger(getContext(), camelJMXAgent.getConnectorPort()));
agent.setCreateConnector(CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getCreateConnector()));
agent.setMBeanObjectDomainName(CamelContextHelper.parseText(getContext(), camelJMXAgent.getMbeanObjectDomainName()));
agent.setMBeanServerDefaultDomain(CamelContextHelper.parseText(getContext(), camelJMXAgent.getMbeanServerDefaultDomain()));
agent.setRegistryPort(CamelContextHelper.parseInteger(getContext(), camelJMXAgent.getRegistryPort()));
agent.setServiceUrlPath(CamelContextHelper.parseText(getContext(), camelJMXAgent.getServiceUrlPath()));
agent.setUsePlatformMBeanServer(CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getUsePlatformMBeanServer()));
agent.setOnlyRegisterProcessorWithCustomId(CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getOnlyRegisterProcessorWithCustomId()));
agent.setRegisterAlways(CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getRegisterAlways()));
agent.setRegisterNewRoutes(CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getRegisterNewRoutes()));
agent.setIncludeHostName(CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getIncludeHostName()));
agent.setMask(CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getMask()));
ManagementStrategy managementStrategy = new ManagedManagementStrategy(getContext(), agent);
getContext().setManagementStrategy(managementStrategy);
// clear the existing lifecycle strategies define by the DefaultCamelContext constructor
getContext().getLifecycleStrategies().clear();
getContext().addLifecycleStrategy(new DefaultManagementLifecycleStrategy(getContext()));
// set additional configuration from camelJMXAgent
boolean onlyId = agent.getOnlyRegisterProcessorWithCustomId() != null && agent.getOnlyRegisterProcessorWithCustomId();
getContext().getManagementStrategy().onlyManageProcessorWithCustomId(onlyId);
String level = CamelContextHelper.parseText(getContext(), camelJMXAgent.getStatisticsLevel());
ManagementStatisticsLevel msLevel = getContext().getTypeConverter().mandatoryConvertTo(ManagementStatisticsLevel.class, level);
getContext().getManagementStrategy().setStatisticsLevel(msLevel);
Boolean loadStatisticsEnabled = CamelContextHelper.parseBoolean(getContext(), camelJMXAgent.getLoadStatisticsEnabled());
if (loadStatisticsEnabled != null) {
getContext().getManagementStrategy().setLoadStatisticsEnabled(loadStatisticsEnabled);
}
}
}
protected void initStreamCachingStrategy() throws Exception {
CamelStreamCachingStrategyDefinition streamCaching = getCamelStreamCachingStrategy();
if (streamCaching == null) {
return;
}
Boolean enabled = CamelContextHelper.parseBoolean(getContext(), streamCaching.getEnabled());
if (enabled != null) {
getContext().getStreamCachingStrategy().setEnabled(enabled);
}
String spoolDirectory = CamelContextHelper.parseText(getContext(), streamCaching.getSpoolDirectory());
if (spoolDirectory != null) {
getContext().getStreamCachingStrategy().setSpoolDirectory(spoolDirectory);
}
Long spoolThreshold = CamelContextHelper.parseLong(getContext(), streamCaching.getSpoolThreshold());
if (spoolThreshold != null) {
getContext().getStreamCachingStrategy().setSpoolThreshold(spoolThreshold);
}
Integer spoolUsedHeap = CamelContextHelper.parseInteger(getContext(), streamCaching.getSpoolUsedHeapMemoryThreshold());
if (spoolUsedHeap != null) {
getContext().getStreamCachingStrategy().setSpoolUsedHeapMemoryThreshold(spoolUsedHeap);
}
String limit = CamelContextHelper.parseText(getContext(), streamCaching.getSpoolUsedHeapMemoryLimit());
if (limit != null) {
StreamCachingStrategy.SpoolUsedHeapMemoryLimit ul = CamelContextHelper.mandatoryConvertTo(getContext(), StreamCachingStrategy.SpoolUsedHeapMemoryLimit.class, limit);
getContext().getStreamCachingStrategy().setSpoolUsedHeapMemoryLimit(ul);
}
String spoolChiper = CamelContextHelper.parseText(getContext(), streamCaching.getSpoolChiper());
if (spoolChiper != null) {
getContext().getStreamCachingStrategy().setSpoolChiper(spoolChiper);
}
Boolean remove = CamelContextHelper.parseBoolean(getContext(), streamCaching.getRemoveSpoolDirectoryWhenStopping());
if (remove != null) {
getContext().getStreamCachingStrategy().setRemoveSpoolDirectoryWhenStopping(remove);
}
Boolean statisticsEnabled = CamelContextHelper.parseBoolean(getContext(), streamCaching.getStatisticsEnabled());
if (statisticsEnabled != null) {
getContext().getStreamCachingStrategy().getStatistics().setStatisticsEnabled(statisticsEnabled);
}
Boolean anySpoolRules = CamelContextHelper.parseBoolean(getContext(), streamCaching.getAnySpoolRules());
if (anySpoolRules != null) {
getContext().getStreamCachingStrategy().setAnySpoolRules(anySpoolRules);
}
String spoolRules = CamelContextHelper.parseText(getContext(), streamCaching.getAnySpoolRules());
if (spoolRules != null) {
Iterator it = ObjectHelper.createIterator(spoolRules);
while (it.hasNext()) {
String name = it.next().toString();
StreamCachingStrategy.SpoolRule rule = getContext().getRegistry().lookupByNameAndType(name, StreamCachingStrategy.SpoolRule.class);
if (rule != null) {
getContext().getStreamCachingStrategy().addSpoolRule(rule);
}
}
}
}
protected void initPropertyPlaceholder() throws Exception {
if (getCamelPropertyPlaceholder() != null) {
CamelPropertyPlaceholderDefinition def = getCamelPropertyPlaceholder();
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation(def.getLocation());
if (def.isCache() != null) {
pc.setCache(def.isCache());
}
if (def.isIgnoreMissingLocation() != null) {
pc.setIgnoreMissingLocation(def.isIgnoreMissingLocation());
}
// if using a custom resolver
if (ObjectHelper.isNotEmpty(def.getPropertiesResolverRef())) {
PropertiesResolver resolver = CamelContextHelper.mandatoryLookup(getContext(), def.getPropertiesResolverRef(),
PropertiesResolver.class);
pc.setPropertiesResolver(resolver);
}
// if using a custom parser
if (ObjectHelper.isNotEmpty(def.getPropertiesParserRef())) {
PropertiesParser parser = CamelContextHelper.mandatoryLookup(getContext(), def.getPropertiesParserRef(),
PropertiesParser.class);
pc.setPropertiesParser(parser);
}
pc.setPropertyPrefix(def.getPropertyPrefix());
pc.setPropertySuffix(def.getPropertySuffix());
if (def.isFallbackToUnaugmentedProperty() != null) {
pc.setFallbackToUnaugmentedProperty(def.isFallbackToUnaugmentedProperty());
}
pc.setPrefixToken(def.getPrefixToken());
pc.setSuffixToken(def.getSuffixToken());
// register the properties component
getContext().addComponent("properties", pc);
}
}
protected void initRouteRefs() throws Exception {
// add route refs to existing routes
if (getRouteRefs() != null) {
for (RouteContextRefDefinition ref : getRouteRefs()) {
List<RouteDefinition> defs = ref.lookupRoutes(getContext());
for (RouteDefinition def : defs) {
LOG.debug("Adding route from {} -> {}", ref, def);
// add in top as they are most likely to be common/shared
// which you may want to start first
getRoutes().add(0, def);
}
}
}
}
protected abstract <S> S getBeanForType(Class<S> clazz);
public void destroy() throws Exception {
routesSetupDone.set(false);
getContext().stop();
}
// Properties
// -------------------------------------------------------------------------
public T getContext() {
return getContext(true);
}
public abstract T getContext(boolean create);
public abstract List<RouteDefinition> getRoutes();
public abstract List<? extends AbstractCamelEndpointFactoryBean> getEndpoints();
public abstract List<? extends AbstractCamelRedeliveryPolicyFactoryBean> getRedeliveryPolicies();
public abstract List<InterceptDefinition> getIntercepts();
public abstract List<InterceptFromDefinition> getInterceptFroms();
public abstract List<InterceptSendToEndpointDefinition> getInterceptSendToEndpoints();
public abstract PropertiesDefinition getProperties();
public abstract String[] getPackages();
public abstract PackageScanDefinition getPackageScan();
public abstract void setPackageScan(PackageScanDefinition packageScan);
public abstract ContextScanDefinition getContextScan();
public abstract void setContextScan(ContextScanDefinition contextScan);
public abstract CamelPropertyPlaceholderDefinition getCamelPropertyPlaceholder();
public abstract String getTrace();
public abstract String getMessageHistory();
public abstract String getStreamCache();
public abstract String getDelayer();
public abstract String getHandleFault();
public abstract String getAutoStartup();
public abstract String getUseMDCLogging();
public abstract String getUseBreadcrumb();
public abstract String getAllowUseOriginalMessage();
public abstract String getRuntimeEndpointRegistryEnabled();
public abstract String getManagementNamePattern();
public abstract String getThreadNamePattern();
/**
* @deprecated this option is no longer supported, will be removed in a future Camel release.
*/
@Deprecated
public abstract Boolean getLazyLoadTypeConverters();
public abstract Boolean getTypeConverterStatisticsEnabled();
public abstract CamelJMXAgentDefinition getCamelJMXAgent();
public abstract CamelStreamCachingStrategyDefinition getCamelStreamCachingStrategy();
public abstract List<RouteBuilderDefinition> getBuilderRefs();
public abstract List<RouteContextRefDefinition> getRouteRefs();
public abstract String getErrorHandlerRef();
public abstract DataFormatsDefinition getDataFormats();
public abstract List<OnExceptionDefinition> getOnExceptions();
public abstract List<OnCompletionDefinition> getOnCompletions();
public abstract ShutdownRoute getShutdownRoute();
public abstract ShutdownRunningTask getShutdownRunningTask();
public abstract List<ThreadPoolProfileDefinition> getThreadPoolProfiles();
public abstract String getDependsOn();
// Implementation methods
// -------------------------------------------------------------------------
/**
* Initializes the context
*
* @param ctx the context
* @throws Exception is thrown if error occurred
*/
protected void initCamelContext(T ctx) throws Exception {
if (getStreamCache() != null) {
ctx.setStreamCaching(CamelContextHelper.parseBoolean(getContext(), getStreamCache()));
}
if (getTrace() != null) {
ctx.setTracing(CamelContextHelper.parseBoolean(getContext(), getTrace()));
}
if (getMessageHistory() != null) {
ctx.setMessageHistory(CamelContextHelper.parseBoolean(getContext(), getMessageHistory()));
}
if (getDelayer() != null) {
ctx.setDelayer(CamelContextHelper.parseLong(getContext(), getDelayer()));
}
if (getHandleFault() != null) {
ctx.setHandleFault(CamelContextHelper.parseBoolean(getContext(), getHandleFault()));
}
if (getErrorHandlerRef() != null) {
ctx.setErrorHandlerBuilder(new ErrorHandlerBuilderRef(getErrorHandlerRef()));
}
if (getAutoStartup() != null) {
ctx.setAutoStartup(CamelContextHelper.parseBoolean(getContext(), getAutoStartup()));
}
if (getUseMDCLogging() != null) {
ctx.setUseMDCLogging(CamelContextHelper.parseBoolean(getContext(), getUseMDCLogging()));
}
if (getUseBreadcrumb() != null) {
ctx.setUseBreadcrumb(CamelContextHelper.parseBoolean(getContext(), getUseBreadcrumb()));
}
if (getAllowUseOriginalMessage() != null) {
ctx.setAllowUseOriginalMessage(CamelContextHelper.parseBoolean(getContext(), getAllowUseOriginalMessage()));
}
if (getRuntimeEndpointRegistryEnabled() != null) {
ctx.getRuntimeEndpointRegistry().setEnabled(CamelContextHelper.parseBoolean(getContext(), getRuntimeEndpointRegistryEnabled()));
}
if (getManagementNamePattern() != null) {
ctx.getManagementNameStrategy().setNamePattern(getManagementNamePattern());
}
if (getThreadNamePattern() != null) {
ctx.getExecutorServiceManager().setThreadNamePattern(getThreadNamePattern());
}
if (getShutdownRoute() != null) {
ctx.setShutdownRoute(getShutdownRoute());
}
if (getShutdownRunningTask() != null) {
ctx.setShutdownRunningTask(getShutdownRunningTask());
}
if (getDataFormats() != null) {
ctx.setDataFormats(getDataFormats().asMap());
}
if (getTypeConverterStatisticsEnabled() != null) {
ctx.setTypeConverterStatisticsEnabled(getTypeConverterStatisticsEnabled());
}
}
protected void initThreadPoolProfiles(T context) throws Exception {
Set<String> defaultIds = new HashSet<String>();
// lookup and use custom profiles from the registry
Map<String, ThreadPoolProfile> profiles = context.getRegistry().findByTypeWithName(ThreadPoolProfile.class);
if (profiles != null && !profiles.isEmpty()) {
for (Entry<String, ThreadPoolProfile> entry : profiles.entrySet()) {
ThreadPoolProfile profile = entry.getValue();
// do not add if already added, for instance a tracer that is also an InterceptStrategy class
if (profile.isDefaultProfile()) {
LOG.info("Using custom default ThreadPoolProfile with id: {} and implementation: {}", entry.getKey(), profile);
context.getExecutorServiceManager().setDefaultThreadPoolProfile(profile);
defaultIds.add(entry.getKey());
} else {
context.getExecutorServiceManager().registerThreadPoolProfile(profile);
}
}
}
// use custom profiles defined in the CamelContext
if (getThreadPoolProfiles() != null && !getThreadPoolProfiles().isEmpty()) {
for (ThreadPoolProfileDefinition definition : getThreadPoolProfiles()) {
if (definition.isDefaultProfile()) {
LOG.info("Using custom default ThreadPoolProfile with id: {} and implementation: {}", definition.getId(), definition);
context.getExecutorServiceManager().setDefaultThreadPoolProfile(asThreadPoolProfile(context, definition));
defaultIds.add(definition.getId());
} else {
context.getExecutorServiceManager().registerThreadPoolProfile(asThreadPoolProfile(context, definition));
}
}
}
// validate at most one is defined
if (defaultIds.size() > 1) {
throw new IllegalArgumentException("Only exactly one default ThreadPoolProfile is allowed, was " + defaultIds.size() + " ids: " + defaultIds);
}
}
/**
* Creates a {@link ThreadPoolProfile} instance based on the definition.
*
* @param context the camel context
* @return the profile
* @throws Exception is thrown if error creating the profile
*/
private ThreadPoolProfile asThreadPoolProfile(CamelContext context, ThreadPoolProfileDefinition definition) throws Exception {
ThreadPoolProfile answer = new ThreadPoolProfile();
answer.setId(definition.getId());
answer.setDefaultProfile(definition.getDefaultProfile());
answer.setPoolSize(CamelContextHelper.parseInteger(context, definition.getPoolSize()));
answer.setMaxPoolSize(CamelContextHelper.parseInteger(context, definition.getMaxPoolSize()));
answer.setKeepAliveTime(CamelContextHelper.parseLong(context, definition.getKeepAliveTime()));
answer.setMaxQueueSize(CamelContextHelper.parseInteger(context, definition.getMaxQueueSize()));
answer.setRejectedPolicy(definition.getRejectedPolicy());
answer.setTimeUnit(definition.getTimeUnit());
return answer;
}
protected abstract void initBeanPostProcessor(T context);
/**
* Strategy to install all available routes into the context
*/
protected void installRoutes() throws Exception {
List<RouteBuilder> builders = new ArrayList<RouteBuilder>();
// lets add RoutesBuilder's added from references
if (getBuilderRefs() != null) {
for (RouteBuilderDefinition builderRef : getBuilderRefs()) {
RoutesBuilder routes = builderRef.createRoutes(getContext());
if (routes != null) {
this.builders.add(routes);
} else {
throw new CamelException("Cannot find any routes with this RouteBuilder reference: " + builderRef);
}
}
}
// install already configured routes
for (RoutesBuilder routeBuilder : this.builders) {
getContext().addRoutes(routeBuilder);
}
// install builders
for (RouteBuilder builder : builders) {
// Inject the annotated resource
postProcessBeforeInit(builder);
getContext().addRoutes(builder);
}
}
protected abstract void postProcessBeforeInit(RouteBuilder builder);
/**
* Strategy method to try find {@link org.apache.camel.builder.RouteBuilder} instances on the classpath
*/
protected void findRouteBuilders() throws Exception {
// package scan
addPackageElementContentsToScanDefinition();
PackageScanDefinition packageScanDef = getPackageScan();
if (packageScanDef != null && packageScanDef.getPackages().size() > 0) {
// use package scan filter
PatternBasedPackageScanFilter filter = new PatternBasedPackageScanFilter();
// support property placeholders in include and exclude
for (String include : packageScanDef.getIncludes()) {
include = getContext().resolvePropertyPlaceholders(include);
filter.addIncludePattern(include);
}
for (String exclude : packageScanDef.getExcludes()) {
exclude = getContext().resolvePropertyPlaceholders(exclude);
filter.addExcludePattern(exclude);
}
String[] normalized = normalizePackages(getContext(), packageScanDef.getPackages());
findRouteBuildersByPackageScan(normalized, filter, builders);
}
// context scan
ContextScanDefinition contextScanDef = getContextScan();
if (contextScanDef != null) {
// use package scan filter
PatternBasedPackageScanFilter filter = new PatternBasedPackageScanFilter();
// support property placeholders in include and exclude
for (String include : contextScanDef.getIncludes()) {
include = getContext().resolvePropertyPlaceholders(include);
filter.addIncludePattern(include);
}
for (String exclude : contextScanDef.getExcludes()) {
exclude = getContext().resolvePropertyPlaceholders(exclude);
filter.addExcludePattern(exclude);
}
findRouteBuildersByContextScan(filter, builders);
}
}
protected abstract void findRouteBuildersByPackageScan(String[] packages, PackageScanFilter filter, List<RoutesBuilder> builders) throws Exception;
protected abstract void findRouteBuildersByContextScan(PackageScanFilter filter, List<RoutesBuilder> builders) throws Exception;
private void addPackageElementContentsToScanDefinition() {
PackageScanDefinition packageScanDef = getPackageScan();
if (getPackages() != null && getPackages().length > 0) {
if (packageScanDef == null) {
packageScanDef = new PackageScanDefinition();
setPackageScan(packageScanDef);
}
for (String pkg : getPackages()) {
packageScanDef.getPackages().add(pkg);
}
}
}
private String[] normalizePackages(T context, List<String> unnormalized) throws Exception {
List<String> packages = new ArrayList<String>();
for (String name : unnormalized) {
// it may use property placeholders
name = context.resolvePropertyPlaceholders(name);
name = ObjectHelper.normalizeClassName(name);
if (ObjectHelper.isNotEmpty(name)) {
LOG.trace("Using package: {} to scan for RouteBuilder classes", name);
packages.add(name);
}
}
return packages.toArray(new String[packages.size()]);
}
private void setupCustomServices() {
ClassResolver classResolver = getBeanForType(ClassResolver.class);
if (classResolver != null) {
LOG.info("Using custom ClassResolver: {}", classResolver);
getContext().setClassResolver(classResolver);
}
FactoryFinderResolver factoryFinderResolver = getBeanForType(FactoryFinderResolver.class);
if (factoryFinderResolver != null) {
LOG.info("Using custom FactoryFinderResolver: {}", factoryFinderResolver);
getContext().setFactoryFinderResolver(factoryFinderResolver);
}
ExecutorServiceManager executorServiceStrategy = getBeanForType(ExecutorServiceManager.class);
if (executorServiceStrategy != null) {
LOG.info("Using custom ExecutorServiceStrategy: {}", executorServiceStrategy);
getContext().setExecutorServiceManager(executorServiceStrategy);
}
ThreadPoolFactory threadPoolFactory = getBeanForType(ThreadPoolFactory.class);
if (threadPoolFactory != null) {
LOG.info("Using custom ThreadPoolFactory: {}", threadPoolFactory);
getContext().getExecutorServiceManager().setThreadPoolFactory(threadPoolFactory);
}
ProcessorFactory processorFactory = getBeanForType(ProcessorFactory.class);
if (processorFactory != null) {
LOG.info("Using custom ProcessorFactory: {}", processorFactory);
getContext().setProcessorFactory(processorFactory);
}
Debugger debugger = getBeanForType(Debugger.class);
if (debugger != null) {
LOG.info("Using custom Debugger: {}", debugger);
getContext().setDebugger(debugger);
}
UuidGenerator uuidGenerator = getBeanForType(UuidGenerator.class);
if (uuidGenerator != null) {
LOG.info("Using custom UuidGenerator: {}", uuidGenerator);
getContext().setUuidGenerator(uuidGenerator);
}
NodeIdFactory nodeIdFactory = getBeanForType(NodeIdFactory.class);
if (nodeIdFactory != null) {
LOG.info("Using custom NodeIdFactory: {}", nodeIdFactory);
getContext().setNodeIdFactory(nodeIdFactory);
}
StreamCachingStrategy streamCachingStrategy = getBeanForType(StreamCachingStrategy.class);
if (streamCachingStrategy != null) {
LOG.info("Using custom StreamCachingStrategy: {}", streamCachingStrategy);
getContext().setStreamCachingStrategy(streamCachingStrategy);
}
}
}
|
apache-2.0
|
noobyang/AndroidStudy
|
zmusic/src/main/java/com/noobyang/music/Music.java
|
1362
|
package com.noobyang.music;
public class Music {
private int id;
private String title;
private String artist;
private long duration;
private String data;
private int albumId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public int getAlbumId() {
return albumId;
}
public void setAlbumId(int albumId) {
this.albumId = albumId;
}
@Override
public String toString() {
return "Music{" +
"id=" + id +
", title='" + title + '\'' +
", artist='" + artist + '\'' +
", duration=" + duration +
", data='" + data + '\'' +
", albumId=" + albumId +
'}';
}
}
|
apache-2.0
|
antoniogi/HPC
|
Python/TACC_HPC/2_cython/test_cython1.py
|
240
|
#!/usr/bin/env python
#
# Iterative example to show Cython capabilities.
#
#
# agomez (at) tacc.utexas.edu
# 30 Oct 2014
#
# ---------------------------------------------------------------------
import myfunc1
print myfunc1.function(10.0)
|
apache-2.0
|
ArloL/liquibase
|
liquibase-core/src/main/java/liquibase/database/core/DerbyDatabase.java
|
6765
|
package liquibase.database.core;
import java.sql.*;
import liquibase.CatalogAndSchema;
import liquibase.database.AbstractJdbcDatabase;
import liquibase.database.DatabaseConnection;
import liquibase.database.jvm.JdbcConnection;
import liquibase.structure.DatabaseObject;
import liquibase.exception.DatabaseException;
import liquibase.logging.LogFactory;
import liquibase.logging.Logger;
import java.sql.Driver;
import java.util.Enumeration;
public class DerbyDatabase extends AbstractJdbcDatabase {
private Logger log = LogFactory.getLogger();
protected int driverVersionMajor;
protected int driverVersionMinor;
public DerbyDatabase() {
super.setCurrentDateTimeFunction("CURRENT_TIMESTAMP");
super.sequenceNextValueFunction = "NEXT VALUE FOR %s";
super.sequenceCurrentValueFunction = "(SELECT currentvalue FROM sys.syssequences WHERE %s='SEQ_TYPE')";
determineDriverVersion();
}
public boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException {
return "Apache Derby".equalsIgnoreCase(conn.getDatabaseProductName());
}
public String getDefaultDriver(String url) {
// CORE-1230 - don't shutdown derby network server
if (url.startsWith("jdbc:derby://")) {
return "org.apache.derby.jdbc.ClientDriver";
} else if (url.startsWith("java:derby")) {
return "org.apache.derby.jdbc.EmbeddedDriver";
}
return null;
}
public int getPriority() {
return PRIORITY_DEFAULT;
}
public Integer getDefaultPort() {
return 1527;
}
@Override
protected String getDefaultDatabaseProductName() {
return "Derby";
}
@Override
public String correctObjectName(String objectName, Class<? extends DatabaseObject> objectType) {
return objectName.toUpperCase();
}
public String getShortName() {
return "derby";
}
@Override
public boolean supportsSequences() {
if ((driverVersionMajor == 10 && driverVersionMinor >= 6) ||
driverVersionMajor >= 11)
{
return true;
} else {
return false;
}
}
public boolean supportsInitiallyDeferrableColumns() {
return false;
}
@Override
public String getDateLiteral(String isoDate) {
if (isDateOnly(isoDate)) {
return "DATE(" + super.getDateLiteral(isoDate) + ")";
} else if (isTimeOnly(isoDate)) {
return "TIME(" + super.getDateLiteral(isoDate) + ")";
} else {
String dateString = super.getDateLiteral(isoDate);
int decimalDigits = dateString.length() - dateString.indexOf('.') - 2;
String padding = "";
for (int i=6; i> decimalDigits; i--) {
padding += "0";
}
return "TIMESTAMP(" + dateString.replaceFirst("'$", padding+"'") + ")";
}
}
public boolean supportsTablespaces() {
return false;
}
@Override
public String getViewDefinition(CatalogAndSchema schema, String name) throws DatabaseException {
return super.getViewDefinition(schema, name).replaceFirst("CREATE VIEW \\w+ AS ", "");
}
@Override
public void close() throws DatabaseException {
String url = getConnection().getURL();
String driverName = getDefaultDriver(url);
super.close();
if (driverName.toLowerCase().contains("embedded")) {
try {
if (url.contains(";")) {
url = url.substring(0, url.indexOf(";")) + ";shutdown=true";
} else {
url += ";shutdown=true";
}
LogFactory.getLogger().info("Shutting down derby connection: " + url);
// this cleans up the lock files in the embedded derby database folder
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Driver driver = (Driver) contextClassLoader.loadClass(driverName).newInstance();
driver.connect(url, null);
} catch (Exception e) {
if (e instanceof SQLException) {
String state = ((SQLException) e).getSQLState();
if ("XJ015".equals(state) || "08006".equals(state)) {
// "The XJ015 error (successful shutdown of the Derby engine) and the 08006
// error (successful shutdown of a single database) are the only exceptions
// thrown by Derby that might indicate that an operation succeeded. All other
// exceptions indicate that an operation failed."
// See http://db.apache.org/derby/docs/dev/getstart/rwwdactivity3.html
return;
}
}
throw new DatabaseException("Error closing derby cleanly", e);
}
}
}
/**
* Determine Apache Derby driver major/minor version.
*/
@SuppressWarnings({ "static-access", "unchecked" })
protected void determineDriverVersion() {
try {
// Locate the Derby sysinfo class and query its version info
Enumeration<Driver> it = DriverManager.getDrivers();
while (it.hasMoreElements()) {
Driver driver = it.nextElement();
if (driver.getClass().getName().contains("derby")) {
driverVersionMajor = driver.getMajorVersion();
driverVersionMinor = driver.getMinorVersion();
return;
}
}
log.debug("Unable to load/access Apache Derby driver class " + "to check version");
driverVersionMajor = -1;
driverVersionMinor = -1;
} catch (Exception e) {
log.debug("Unable to load/access Apache Derby driver class " + "org.apache.derby.tools.sysinfo to check version: " + e.getMessage());
driverVersionMajor = -1;
driverVersionMinor = -1;
}
}
@Override
protected String doGetDefaultSchemaName() {
try {
ResultSet resultSet = ((JdbcConnection) getConnection()).prepareStatement("select current schema from sysibm.sysdummy1").executeQuery();
resultSet.next();
return resultSet.getString(1);
} catch (Exception e) {
LogFactory.getLogger().info("Error getting default schema", e);
}
return null;
}
}
|
apache-2.0
|
shenbaise/mltoy
|
src/main/scala/org/apache/spark/examples/mllib/BinaryClassification.scala
|
5873
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.examples.mllib
import org.apache.log4j.{Level, Logger}
import scopt.OptionParser
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.mllib.classification.{LogisticRegressionWithLBFGS, SVMWithSGD}
import org.apache.spark.mllib.evaluation.BinaryClassificationMetrics
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.mllib.optimization.{SquaredL2Updater, L1Updater}
import org.apache.hadoop.yarn.webapp.view.DefaultPage
import org.apache.spark.mllib.classification.LogisticRegressionModel
/**
* An example app for binary classification. Run with
* {{{
* bin/run-example org.apache.spark.examples.mllib.BinaryClassification
* }}}
* A synthetic dataset is located at `data/mllib/sample_binary_classification_data.txt`.
* If you use it as a template to create your own app, please use `spark-submit` to submit your app.
*/
object BinaryClassification {
object Algorithm extends Enumeration {
type Algorithm = Value
val SVM, LR = Value
}
object RegType extends Enumeration {
type RegType = Value
val L1, L2 = Value
}
import Algorithm._
import RegType._
case class Params(
input: String = "data/mllib/sample_binary_classification_data.txt",
numIterations: Int = 10,
stepSize: Double = 0.1,
algorithm: Algorithm = LR,
regType: RegType = L2,
regParam: Double = 0.01) extends AbstractParams[Params]
def main(args: Array[String]) {
val defaultParams = Params()
val parser = new OptionParser[Params]("BinaryClassification") {
head("BinaryClassification: an example app for binary classification.")
opt[Int]("numIterations")
.text("number of iterations")
.action((x, c) => c.copy(numIterations = x))
opt[Double]("stepSize")
.text("initial step size (ignored by logistic regression), " +
s"default: ${defaultParams.stepSize}")
.action((x, c) => c.copy(stepSize = x))
opt[String]("algorithm")
.text(s"algorithm (${Algorithm.values.mkString(",")}), " +
s"default: ${defaultParams.algorithm}")
.action((x, c) => c.copy(algorithm = Algorithm.withName(x)))
opt[String]("regType")
.text(s"regularization type (${RegType.values.mkString(",")}), " +
s"default: ${defaultParams.regType}")
.action((x, c) => c.copy(regType = RegType.withName(x)))
opt[Double]("regParam")
.text(s"regularization parameter, default: ${defaultParams.regParam}")
arg[String]("<input>")
.required()
.text("input paths to labeled examples in LIBSVM format")
.action((x, c) => c.copy(input = x))
note(
"""
|For example, the following command runs this app on a synthetic dataset:
|
| bin/spark-submit --class org.apache.spark.examples.mllib.BinaryClassification \
| examples/target/scala-*/spark-examples-*.jar \
| --algorithm LR --regType L2 --regParam 1.0 \
| data/mllib/sample_binary_classification_data.txt
""".stripMargin)
}
run(defaultParams)
// parser.parse(args, defaultParams).map { params =>
// run(params)
// } getOrElse {
// sys.exit(1)
// }
}
def run(params: Params) {
val conf = new SparkConf().setAppName(s"BinaryClassification with $params").setMaster("local[2]")
val sc = new SparkContext(conf)
Logger.getRootLogger.setLevel(Level.WARN)
val examples = MLUtils.loadLibSVMFile(sc, params.input).cache()
val splits = examples.randomSplit(Array(0.8, 0.2))
val training = splits(0).cache()
val test = splits(1).cache()
val numTraining = training.count()
val numTest = test.count()
println(s"Training: $numTraining, test: $numTest.")
examples.unpersist(blocking = false)
val updater = params.regType match {
case L1 => new L1Updater()
case L2 => new SquaredL2Updater()
}
val model = params.algorithm match {
case LR =>
val algorithm = new LogisticRegressionWithLBFGS()
algorithm.optimizer
.setNumIterations(params.numIterations)
.setUpdater(updater)
.setRegParam(params.regParam)
// algorithm.run(training).clearThreshold()
var m = algorithm.run(training)
println (m.getThreshold)
m
case SVM =>
val algorithm = new SVMWithSGD()
algorithm.optimizer
.setNumIterations(params.numIterations)
.setStepSize(params.stepSize)
.setUpdater(updater)
.setRegParam(params.regParam)
algorithm.run(training).clearThreshold()
}
val prediction = model.predict(test.map(_.features))
val predictionAndLabel = prediction.zip(test.map(_.label))
predictionAndLabel.foreach(a => println(s"${a._1} ${a._2}"))
val metrics = new BinaryClassificationMetrics(predictionAndLabel)
println(s"Test areaUnderPR = ${metrics.areaUnderPR()}.")
println(s"Test areaUnderROC = ${metrics.areaUnderROC()}.")
sc.stop()
}
}
|
apache-2.0
|
First-Peoples-Cultural-Council/fv-web-ui
|
frontend/app_v2/src/components/ShareLinks/index.js
|
142
|
import ShareLinksPresentation from 'components/ShareLinks/ShareLinksPresentation'
export default {
Presentation: ShareLinksPresentation,
}
|
apache-2.0
|
PonIC/PonIC
|
src/org/apache/pig/impl/io/SPigTextInputFormat.java
|
2738
|
package org.apache.pig.impl.io;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Arrays;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.Tuple;
import eu.stratosphere.nephele.configuration.Configuration;
import eu.stratosphere.pact.common.type.base.PactString;
/**
*
* Copy of TextInputFormat reading Tuples instead of PactRecords
* @author hinata
*
*/
public class SPigTextInputFormat extends SPigDelimitedInputFormat {
public static final String CHARSET_NAME = "textformat.charset";
public static final String DEFAULT_CHARSET_NAME = "UTF-8";
private static final Log LOG = LogFactory.getLog(SPigDelimitedInputFormat.class);
protected final PactString theString = new PactString();
protected CharsetDecoder decoder;
protected ByteBuffer byteWrapper;
protected boolean ascii;
@Override
public void configure(Configuration parameters)
{
super.configure(parameters);
// get the charset for the decoding
String charsetName = parameters.getString(CHARSET_NAME, DEFAULT_CHARSET_NAME);
if (charsetName == null || !Charset.isSupported(charsetName)) {
throw new RuntimeException("Unsupported charset: " + charsetName);
}
if (charsetName.equals("ISO-8859-1") || charsetName.equalsIgnoreCase("ASCII")) {
this.ascii = true;
} else {
this.decoder = Charset.forName(charsetName).newDecoder();
this.byteWrapper = ByteBuffer.allocate(1);
}
}
@Override
//TODO: Find where will this target Tuple be instantiated???
public boolean readRecord(Tuple target, byte[] bytes, int offset,
int numBytes) {
PactString str = this.theString;
if (this.ascii) {
str.setValueAscii(bytes, offset, numBytes);
}
else {
ByteBuffer byteWrapper = this.byteWrapper;
if (bytes != byteWrapper.array()) {
byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
this.byteWrapper = byteWrapper;
}
byteWrapper.clear();
byteWrapper.position(offset);
byteWrapper.limit(offset + numBytes);
try {
CharBuffer result = this.decoder.decode(byteWrapper);
str.setValue(result);
}
catch (CharacterCodingException e) {
byte[] copy = new byte[numBytes];
System.arraycopy(bytes, offset, copy, 0, numBytes);
LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
return false;
}
}
target.setNull(true);
//target.clear();
try {
target.set(0, str.getValue());
} catch (ExecException e) {
e.printStackTrace();
}
return true;
}
}
|
apache-2.0
|
jentfoo/aws-sdk-java
|
aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/transform/ExtendedS3DestinationDescriptionJsonUnmarshaller.java
|
6105
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kinesisfirehose.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.kinesisfirehose.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ExtendedS3DestinationDescription JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ExtendedS3DestinationDescriptionJsonUnmarshaller implements Unmarshaller<ExtendedS3DestinationDescription, JsonUnmarshallerContext> {
public ExtendedS3DestinationDescription unmarshall(JsonUnmarshallerContext context) throws Exception {
ExtendedS3DestinationDescription extendedS3DestinationDescription = new ExtendedS3DestinationDescription();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("RoleARN", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setRoleARN(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("BucketARN", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setBucketARN(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Prefix", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setPrefix(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("ErrorOutputPrefix", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setErrorOutputPrefix(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("BufferingHints", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setBufferingHints(BufferingHintsJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("CompressionFormat", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setCompressionFormat(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("EncryptionConfiguration", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setEncryptionConfiguration(EncryptionConfigurationJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("CloudWatchLoggingOptions", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setCloudWatchLoggingOptions(CloudWatchLoggingOptionsJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("ProcessingConfiguration", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setProcessingConfiguration(ProcessingConfigurationJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("S3BackupMode", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setS3BackupMode(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("S3BackupDescription", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setS3BackupDescription(S3DestinationDescriptionJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("DataFormatConversionConfiguration", targetDepth)) {
context.nextToken();
extendedS3DestinationDescription.setDataFormatConversionConfiguration(DataFormatConversionConfigurationJsonUnmarshaller.getInstance()
.unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return extendedS3DestinationDescription;
}
private static ExtendedS3DestinationDescriptionJsonUnmarshaller instance;
public static ExtendedS3DestinationDescriptionJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ExtendedS3DestinationDescriptionJsonUnmarshaller();
return instance;
}
}
|
apache-2.0
|
googleprojectzero/sandbox-attacksurface-analysis-tools
|
NtObjectManager/Cmdlets/Object/ReceiveNtAlpcMessageCmdlet.cs
|
2972
|
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet;
using System.Management.Automation;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Receives a message on an ALPC port.</para>
/// <para type="description">This cmdlet receives a message on an ALPC port.</para>
/// </summary>
/// <example>
/// <code>$recv_msg = Receive-NtAlpcMessage -Port $port -ReceiveLength 80</code>
/// <para>Receive a message of up to 80 bytes.</para>
/// </example>
/// <para type="link">about_ManagingNtObjectLifetime</para>
[Cmdlet(VerbsCommunications.Receive, "NtAlpcMessage")]
public class ReceiveNtAlpcMessageCmdlet : PSCmdlet
{
/// <summary>
/// <para type="description">Specify the port to send the message on.</para>
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
public NtAlpc Port { get; set; }
/// <summary>
/// <para type="description">Specify send flags.</para>
/// </summary>
[Parameter]
public AlpcMessageFlags Flags { get; set; }
/// <summary>
/// <para type="description">Specify optional timeout in MS.</para>
/// </summary>
[Parameter]
public long? TimeoutMs { get; set; }
/// <summary>
/// <para type="description">Specify the maximum length of message to receive.</para>
/// </summary>
[Parameter(Position = 1)]
public int ReceiveLength { get; set; }
/// <summary>
/// <para type="description">Specify receive attributes.</para>
/// </summary>
[Parameter]
public AlpcReceiveMessageAttributes ReceiveAttributes { get; set; }
/// <summary>
/// Constructor.
/// </summary>
public ReceiveNtAlpcMessageCmdlet()
{
Flags = AlpcMessageFlags.ReleaseMessage;
ReceiveLength = AlpcMessage.MaximumDataLength;
}
/// <summary>
/// Process record.
/// </summary>
protected override void ProcessRecord()
{
NtWaitTimeout timeout = TimeoutMs.HasValue
? NtWaitTimeout.FromMilliseconds(TimeoutMs.Value) : NtWaitTimeout.Infinite;
var msg = Port.Receive(Flags, ReceiveLength, ReceiveAttributes, timeout);
WriteObject(msg);
}
}
}
|
apache-2.0
|
P7h/CPrograms_Circa2002
|
C Programs/CNew/HANOITOW.C
|
388
|
// PROGRAM FOR HANOI OF TOWERS
#include<stdio.h>
#include<conio.h>
int main(void)
{
int n = 4;
clrscr();
move(n, 'A', 'B', 'C');
getch();
return 0;
}
int move(int n, char a, char b, char c)
{
if(n == 1)
printf("\n \t Move from %c to %c", a, c);
else
{
move(n-1,a, c, b);
move(1, a,' ' , c);
move(n-1, b, a, c);
}
return 0;
}
|
apache-2.0
|
osvik/simplecsv
|
logic.go
|
2106
|
package simplecsv
// countIndexesInSlices counts how many times an integrer shows up in one or more slices
func countIndexesInSlices(indexes [][]int) map[int]int {
valuesMap := map[int]int{}
var valueExists bool
for _, toCount := range indexes {
for _, v := range toCount {
_, valueExists = valuesMap[v]
if valueExists != true {
valuesMap[v] = 1
} else {
valuesMap[v]++
}
}
}
return valuesMap
}
// showsMoreThanTimes returns an array of ints they show more than the min time
func showsMoreThanTimes(valuesMap map[int]int, min int) []int {
result := []int{}
for k, v := range valuesMap {
if v >= min {
result = append(result, k)
}
}
return result
}
// contains checks if a number exits in a slice
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// OrIndex operates an OR operator in the indexes
func OrIndex(indexes ...[]int) []int {
minTimes := 1
base := [][]int{}
for _, index := range indexes {
base = append(base, index)
}
valuesMap := countIndexesInSlices(base)
result := showsMoreThanTimes(valuesMap, minTimes)
return result
}
// AndIndex operates an AND operator in the indexes
func AndIndex(indexes ...[]int) []int {
minTimes := len(indexes)
base := [][]int{}
for _, index := range indexes {
base = append(base, index)
}
valuesMap := countIndexesInSlices(base)
result := showsMoreThanTimes(valuesMap, minTimes)
return result
}
// NotIndex negates the index between a min value and a max value
// The min value tipically is either 0 or 1 (without and with headers)
// The max value tipically is the csv length - 1 (number of rows -1).
// A table with a header and 2 rows (length = 3) can have indexes with values of 1 and 2
func NotIndex(index []int, min, max int) []int {
counter := make(map[int]bool)
for i := min; i <= max; i++ {
counter[i] = false
}
for _, v := range index {
counter[v] = true
}
negativeIndex := []int{}
for i := min; i <= max; i++ {
if counter[i] == false {
negativeIndex = append(negativeIndex, i)
}
}
return negativeIndex
}
|
apache-2.0
|
kennyphilp/AutomatedBeanTester
|
src/test/java/com/kwp/automatedbeantester/utils/StringUtilsTest.java
|
742
|
package com.kwp.automatedbeantester.utils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
/**
* Created by Kenny on 01/10/2017.
*/
public class StringUtilsTest {
private static final Logger LOGGER = LoggerFactory.getLogger(StringUtilsTest.class);
@Test
public void testNumRepeatCharStartStr()
{
String testStr1="[Ljava.lang.Integer";
String testStr2="[[Ljava.lang.Integer";
String testStr3="[[[[[I";
assertEquals(1, StringUtils.numRepeatCharStartStr(testStr1));
assertEquals(2,StringUtils.numRepeatCharStartStr(testStr2));
assertEquals(5,StringUtils.numRepeatCharStartStr(testStr3));
}
}
|
apache-2.0
|
spring-projects/spring-framework
|
spring-tx/src/main/java/org/springframework/dao/TransientDataAccessException.java
|
1602
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.dao;
import org.springframework.lang.Nullable;
/**
* Root of the hierarchy of data access exceptions that are considered transient -
* where a previously failed operation might be able to succeed when the operation
* is retried without any intervention by application-level functionality.
*
* @author Thomas Risberg
* @since 2.5
* @see java.sql.SQLTransientException
*/
@SuppressWarnings("serial")
public abstract class TransientDataAccessException extends DataAccessException {
/**
* Constructor for TransientDataAccessException.
* @param msg the detail message
*/
public TransientDataAccessException(String msg) {
super(msg);
}
/**
* Constructor for TransientDataAccessException.
* @param msg the detail message
* @param cause the root cause (usually from using a underlying
* data access API such as JDBC)
*/
public TransientDataAccessException(String msg, @Nullable Throwable cause) {
super(msg, cause);
}
}
|
apache-2.0
|
rezaur86/Coding-competitions
|
Java/leetcode/MinRotatedSortedArray.java
|
943
|
package leetcode;
// https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
public class MinRotatedSortedArray {
public int findMin(int[] nums) {
if (nums.length == 1) return nums[0];
int n = nums.length;
int first = 0;
int last = 1;
while (first != last && nums[first] <= nums[last]) {
if (nums[first] == nums[last]) {
while(first < last && nums[first] == nums[last]) {
first++;
}
if (first < last) break;
}
int temp = last;
last = Math.min(last * 2, n-1);
first = temp;
}
if (first == last && last == n-1) return nums[0];
int min = Integer.MAX_VALUE;
for (int i = first; i <= Math.min(last, n-1); i++) {
if (min > nums[i]) {
min = nums[i];
}
}
return min;
}
}
|
apache-2.0
|
machinomy/machinomy
|
packages/machinomy/src/storage/sqlite/SqliteDatastore.ts
|
1058
|
import * as sqlite3 from 'sqlite3'
export default class SqliteDatastore {
database: sqlite3.Database
constructor (database: sqlite3.Database) {
this.database = database
}
run (query: string, params?: any): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.database.run(query, params, error => {
error ? reject(error) : resolve()
})
})
}
close (): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.database.close(error => {
error ? reject(error) : resolve()
})
})
}
get <A> (query: string, params?: any): Promise<A | null> {
return new Promise<A>((resolve, reject) => {
this.database.get(query, params, (error, row) => {
error ? reject(error) : resolve(row)
})
})
}
all <A> (query: string, params?: any): Promise<Array<A>> {
return new Promise<Array<A>>((resolve, reject) => {
this.database.all(query, params, (error, rows) => {
error ? reject(error) : resolve(rows)
})
})
}
}
|
apache-2.0
|
cdegroot/river
|
src/com/sun/jini/reggie/ConstrainableRegistrarProxy.java
|
5433
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.jini.reggie;
import com.sun.jini.proxy.ConstrainableProxyUtil;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;
import java.rmi.MarshalledObject;
import net.jini.admin.Administrable;
import net.jini.core.constraint.MethodConstraints;
import net.jini.core.constraint.RemoteMethodControl;
import net.jini.core.event.RemoteEventListener;
import net.jini.core.lookup.ServiceID;
import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.security.proxytrust.ProxyTrustIterator;
import net.jini.security.proxytrust.SingletonProxyTrustIterator;
/**
* RegistrarProxy subclass that supports constraints.
*
*
*
*/
final class ConstrainableRegistrarProxy
extends RegistrarProxy implements RemoteMethodControl
{
private static final long serialVersionUID = 2L;
/** Mappings between ServiceRegistrar and Registrar methods */
private static final Method[] methodMappings = {
Util.getMethod(ServiceRegistrar.class, "getEntryClasses",
new Class[]{ ServiceTemplate.class }),
Util.getMethod(Registrar.class, "getEntryClasses",
new Class[]{ Template.class }),
Util.getMethod(ServiceRegistrar.class, "getFieldValues",
new Class[]{ ServiceTemplate.class, int.class,
String.class }),
Util.getMethod(Registrar.class, "getFieldValues",
new Class[]{ Template.class, int.class, int.class }),
Util.getMethod(ServiceRegistrar.class, "getGroups", new Class[0]),
Util.getMethod(Registrar.class, "getMemberGroups", new Class[0]),
Util.getMethod(ServiceRegistrar.class, "getLocator", new Class[0]),
Util.getMethod(Registrar.class, "getLocator", new Class[0]),
Util.getMethod(ServiceRegistrar.class, "getServiceTypes",
new Class[]{ ServiceTemplate.class, String.class }),
Util.getMethod(Registrar.class, "getServiceTypes",
new Class[]{ Template.class, String.class }),
Util.getMethod(ServiceRegistrar.class, "lookup",
new Class[]{ ServiceTemplate.class }),
Util.getMethod(Registrar.class, "lookup",
new Class[]{ Template.class }),
Util.getMethod(ServiceRegistrar.class, "lookup",
new Class[]{ ServiceTemplate.class, int.class }),
Util.getMethod(Registrar.class, "lookup",
new Class[]{ Template.class, int.class }),
Util.getMethod(ServiceRegistrar.class, "notify",
new Class[]{ ServiceTemplate.class, int.class,
RemoteEventListener.class,
MarshalledObject.class, long.class }),
Util.getMethod(Registrar.class, "notify",
new Class[]{ Template.class, int.class,
RemoteEventListener.class,
MarshalledObject.class, long.class }),
Util.getMethod(ServiceRegistrar.class, "register",
new Class[]{ ServiceItem.class, long.class }),
Util.getMethod(Registrar.class, "register",
new Class[]{ Item.class, long.class }),
Util.getMethod(Administrable.class, "getAdmin", new Class[0]),
Util.getMethod(Administrable.class, "getAdmin", new Class[0])
};
/** Client constraints for this proxy, or null */
private final MethodConstraints constraints;
/**
* Creates new ConstrainableRegistrarProxy with given server reference,
* service ID and client constraints.
*/
ConstrainableRegistrarProxy(Registrar server,
ServiceID registrarID,
MethodConstraints constraints)
{
super((Registrar) ((RemoteMethodControl) server).setConstraints(
ConstrainableProxyUtil.translateConstraints(
constraints, methodMappings)),
registrarID);
this.constraints = constraints;
}
// javadoc inherited from RemoteMethodControl.setConstraints
public RemoteMethodControl setConstraints(MethodConstraints constraints) {
return new ConstrainableRegistrarProxy(
server, registrarID, constraints);
}
// javadoc inherited from RemoteMethodControl.getConstraints
public MethodConstraints getConstraints() {
return constraints;
}
/**
* Returns iterator used by ProxyTrustVerifier to retrieve a trust verifier
* for this object.
*/
private ProxyTrustIterator getProxyTrustIterator() {
return new SingletonProxyTrustIterator(server);
}
/**
* Verifies that the client constraints for this proxy are consistent with
* those set on the underlying server ref.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
ConstrainableProxyUtil.verifyConsistentConstraints(
constraints, server, methodMappings);
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-kinesisvideo/src/main/java/com/amazonaws/services/kinesisvideo/model/transform/HLSFragmentSelectorJsonUnmarshaller.java
|
3082
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kinesisvideo.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.kinesisvideo.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* HLSFragmentSelector JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HLSFragmentSelectorJsonUnmarshaller implements Unmarshaller<HLSFragmentSelector, JsonUnmarshallerContext> {
public HLSFragmentSelector unmarshall(JsonUnmarshallerContext context) throws Exception {
HLSFragmentSelector hLSFragmentSelector = new HLSFragmentSelector();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("FragmentSelectorType", targetDepth)) {
context.nextToken();
hLSFragmentSelector.setFragmentSelectorType(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("TimestampRange", targetDepth)) {
context.nextToken();
hLSFragmentSelector.setTimestampRange(HLSTimestampRangeJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return hLSFragmentSelector;
}
private static HLSFragmentSelectorJsonUnmarshaller instance;
public static HLSFragmentSelectorJsonUnmarshaller getInstance() {
if (instance == null)
instance = new HLSFragmentSelectorJsonUnmarshaller();
return instance;
}
}
|
apache-2.0
|
1100110/rust
|
src/librustc/front/intrinsic.rs
|
5649
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// NB: this file is include_str!'ed into the compiler, re-parsed
// and injected into each crate the compiler builds. Keep it small.
pub mod intrinsic {
pub use intrinsic::rusti::visit_tydesc;
// FIXME (#3727): remove this when the interface has settled and the
// version in sys is no longer present.
pub fn get_tydesc<T>() -> *TyDesc {
unsafe {
rusti::get_tydesc::<T>() as *TyDesc
}
}
pub struct TyDesc {
size: uint,
align: uint
// Remaining fields not listed
}
pub enum Opaque { }
pub trait TyVisitor {
fn visit_bot(&self) -> bool;
fn visit_nil(&self) -> bool;
fn visit_bool(&self) -> bool;
fn visit_int(&self) -> bool;
fn visit_i8(&self) -> bool;
fn visit_i16(&self) -> bool;
fn visit_i32(&self) -> bool;
fn visit_i64(&self) -> bool;
fn visit_uint(&self) -> bool;
fn visit_u8(&self) -> bool;
fn visit_u16(&self) -> bool;
fn visit_u32(&self) -> bool;
fn visit_u64(&self) -> bool;
fn visit_float(&self) -> bool;
fn visit_f32(&self) -> bool;
fn visit_f64(&self) -> bool;
fn visit_char(&self) -> bool;
fn visit_str(&self) -> bool;
fn visit_estr_box(&self) -> bool;
fn visit_estr_uniq(&self) -> bool;
fn visit_estr_slice(&self) -> bool;
fn visit_estr_fixed(&self, n: uint, sz: uint, align: uint) -> bool;
fn visit_box(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_uniq(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_ptr(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_rptr(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_vec(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_unboxed_vec(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_evec_box(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_evec_uniq(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_evec_slice(&self, mtbl: uint, inner: *TyDesc) -> bool;
fn visit_evec_fixed(&self, n: uint, sz: uint, align: uint,
mtbl: uint, inner: *TyDesc) -> bool;
fn visit_enter_rec(&self, n_fields: uint,
sz: uint, align: uint) -> bool;
fn visit_rec_field(&self, i: uint, name: &str,
mtbl: uint, inner: *TyDesc) -> bool;
fn visit_leave_rec(&self, n_fields: uint,
sz: uint, align: uint) -> bool;
fn visit_enter_class(&self, n_fields: uint,
sz: uint, align: uint) -> bool;
fn visit_class_field(&self, i: uint, name: &str,
mtbl: uint, inner: *TyDesc) -> bool;
fn visit_leave_class(&self, n_fields: uint,
sz: uint, align: uint) -> bool;
fn visit_enter_tup(&self, n_fields: uint,
sz: uint, align: uint) -> bool;
fn visit_tup_field(&self, i: uint, inner: *TyDesc) -> bool;
fn visit_leave_tup(&self, n_fields: uint,
sz: uint, align: uint) -> bool;
fn visit_enter_enum(&self, n_variants: uint,
get_disr: extern unsafe fn(ptr: *Opaque) -> int,
sz: uint, align: uint) -> bool;
fn visit_enter_enum_variant(&self, variant: uint,
disr_val: int,
n_fields: uint,
name: &str) -> bool;
fn visit_enum_variant_field(&self, i: uint, offset: uint, inner: *TyDesc) -> bool;
fn visit_leave_enum_variant(&self, variant: uint,
disr_val: int,
n_fields: uint,
name: &str) -> bool;
fn visit_leave_enum(&self, n_variants: uint,
get_disr: extern unsafe fn(ptr: *Opaque) -> int,
sz: uint, align: uint) -> bool;
fn visit_enter_fn(&self, purity: uint, proto: uint,
n_inputs: uint, retstyle: uint) -> bool;
fn visit_fn_input(&self, i: uint, mode: uint, inner: *TyDesc) -> bool;
fn visit_fn_output(&self, retstyle: uint, inner: *TyDesc) -> bool;
fn visit_leave_fn(&self, purity: uint, proto: uint,
n_inputs: uint, retstyle: uint) -> bool;
fn visit_trait(&self) -> bool;
fn visit_var(&self) -> bool;
fn visit_var_integral(&self) -> bool;
fn visit_param(&self, i: uint) -> bool;
fn visit_self(&self) -> bool;
fn visit_type(&self) -> bool;
fn visit_opaque_box(&self) -> bool;
fn visit_constr(&self, inner: *TyDesc) -> bool;
fn visit_closure_ptr(&self, ck: uint) -> bool;
}
pub mod rusti {
use super::{TyDesc, TyVisitor};
#[abi = "rust-intrinsic"]
pub extern "rust-intrinsic" {
pub fn get_tydesc<T>() -> *();
pub fn visit_tydesc(td: *TyDesc, tv: @TyVisitor);
}
}
}
|
apache-2.0
|
mariusj/org.openntf.domino
|
domino/core/src/main/java/org/openntf/domino/formula/NativeEvaluateFunctions.java
|
37763
|
package org.openntf.domino.formula;
import java.util.Map;
import org.openntf.formula.EvaluateException;
import org.openntf.formula.Function;
import org.openntf.formula.FunctionFactory;
import org.openntf.formula.FunctionSet;
import org.openntf.formula.ValueHolder;
import org.openntf.formula.ValueHolder.DataType;
import org.openntf.formula.annotation.ParamCount;
import org.openntf.formula.function.TextFunctions;
public enum NativeEvaluateFunctions {
;
public static class Functions extends FunctionSet {
private static final Map<String, Function> functionSet = FunctionFactory.getFunctions(NativeEvaluateFunctions.class);
@Override
public Map<String, Function> getFunctions() {
return functionSet;
}
@Override
public int getPriority() {
// TODO Auto-generated method stub
return 40; // @Unique is overwritten!
}
}
/*============================================================================*/
/*
* Text functions
*/
/*============================================================================*/
/*----------------------------------------------------------------------------*/
/*
* @Ascii
*/
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate({ "@Ascii", "Possible at all?" })
@ParamCount({ 1, 2 })
public static ValueHolder atAscii(final FormulaContextNotes ctx, final ValueHolder params[]) throws EvaluateException {
return (params.length == 2) ? ctx.evaluateNative("@Ascii(p1;" + params[1].quoteValue() + ")", params[0]) : // Force NL
ctx.evaluateNative("@Ascii(p1)", params[0]);
}
// TODO RPR: move to openntf @NeedsNativeEvaluate("@Explode(DateRange)")
@ParamCount({ 1, 4 })
public static ValueHolder atExplode(final FormulaContextNotes ctx, final ValueHolder[] params) {
ValueHolder vh = params[0];
if (vh.dataType != DataType.STRING)
return ctx.evaluateNative("@Explode(p1)", vh);
return TextFunctions.atExplode(ctx, params);
}
/*----------------------------------------------------------------------------*/
/*
* @Password, @HashPassword, @VerifyPassword, @PasswordQuality
*/
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Password")
@ParamCount(1)
public static ValueHolder atPassword(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@Password(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@HashPassword")
@ParamCount(1)
public static ValueHolder atHashPassword(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@HashPassword(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@VerifyPassword")
@ParamCount(2)
public static ValueHolder atVerifyPassword(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@VerifyPassword(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@PasswordQuality")
@ParamCount(1)
public static ValueHolder atPasswordQuality(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@PasswordQuality(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
/*
* @Wide, @Narrow
*/
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Wide")
@ParamCount(1)
public static ValueHolder atWide(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@Wide(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Narrow")
@ParamCount(1)
public static ValueHolder atNarrow(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@Narrow(p1)", params[0]);
}
/*============================================================================*/
/*
* Mail, Name, Certificate
*/
/*============================================================================*/
/*----------------------------------------------------------------------------*/
/*
* @Certificate
*/
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Certificate")
@ParamCount(2)
public static ValueHolder atCertificate(final FormulaContextNotes ctx, final ValueHolder params[]) throws EvaluateException {
return ctx.evaluateNative("@Certificate(" + params[0].quoteValue() + ";p1)", params[1]);
}
/*----------------------------------------------------------------------------*/
/*
* @LDAPServer, @Name, @NameLookup, @UserName
*/
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@LDAPServer")
@ParamCount(0)
public static ValueHolder atLDAPServer(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@LDAPServer");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate({ "@Name", "openNTF-Name doesn't yet look stable" })
@ParamCount(2)
public static ValueHolder atName(final FormulaContextNotes ctx, final ValueHolder params[]) throws EvaluateException {
return ctx.evaluateNative("@Name(" + params[0].quoteValue() + ";p1)", params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@NameLookup")
@ParamCount(3)
public static ValueHolder atNameLookup(final FormulaContextNotes ctx, final ValueHolder params[]) throws EvaluateException {
return ctx.evaluateNative("@NameLookup(" + params[0].quoteValue() + ";p1;p2)", params[1], params[2]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@UserName")
@ParamCount({ 0, 1 })
public static ValueHolder atUserName(final FormulaContextNotes ctx, final ValueHolder params[]) {
return (params.length == 0) ? ctx.evaluateNative("@UserName") : ctx.evaluateNative("@UserName(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
/*
* @MailDbName, @MailEncryptSavedPreference, @MailEncryptSentPreference,
* @MailSavePreference, @MailSignPreference, @OptimizeMailAddress
*/
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@MailDbName")
@ParamCount(0)
public static ValueHolder atMailDbName(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@MailDbName");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@MailEncryptSavedPreference")
@ParamCount(0)
public static ValueHolder atMailEncryptSavedPreference(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@MailEncryptSavedPreference");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@MailEncryptSentPreference")
@ParamCount(0)
public static ValueHolder atMailEncryptSentPreference(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@MailEncryptSentPreference");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@MailSavePreference")
@ParamCount(0)
public static ValueHolder atMailSavePreference(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@MailSavePreference");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@MailSignPreference")
@ParamCount(0)
public static ValueHolder atMailSignPreference(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@MailSignPreference");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@OptimizeMailAddress")
@ParamCount(1)
public static ValueHolder atOptimizeMailAddress(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@OptimizeMailAddress(p1)", params[0]);
}
/*============================================================================*/
/*
* Miscellanea
*/
/*============================================================================*/
@NeedsNativeEvaluate("@ConfigFile")
@ParamCount(0)
public static ValueHolder atConfigFile(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@ConfigFile");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Domain")
@ParamCount(0)
public static ValueHolder atDomain(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@Domain");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@LanguagePreference")
@ParamCount(1)
public static ValueHolder atLanguagePreference(final FormulaContextNotes ctx, final ValueHolder params[]) throws EvaluateException {
return ctx.evaluateNative("@LanguagePreference(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Locale")
@ParamCount({ 1, 2 })
public static ValueHolder atLocale(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
if (params.length == 1)
return ctx.evaluateNative("@Locale(" + params[0].quoteValue() + ")");
return ctx.evaluateNative("@Locale(" + params[0].quoteValue() + ";p1)", params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@OrgDir")
@ParamCount(0)
public static ValueHolder atOrgDir(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@OrgDir");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@PolicyIsFieldLocked")
@ParamCount(1)
public static ValueHolder atPolicyIsFieldLocked(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@PolicyIsFieldLocked(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@RegQueryValue")
@ParamCount(3)
public static ValueHolder atRegQueryValue(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@RegQueryValue(p1;p2;p3)", params[0], params[1], params[2]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@ServerAccess")
@ParamCount({ 2, 3 })
public static ValueHolder atServerAccess(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
if (params.length == 2) {
return ctx.evaluateNative("@ServerAccess(" + params[0].quoteValue() + ";p1)", params[1]);
} else {
return ctx.evaluateNative("@ServerAccess(" + params[0].quoteValue() + ";p1;p2)", params[1], params[2]);
}
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@AdminECLIsLocked")
@ParamCount(0)
public static ValueHolder atAdminECLIsLocked(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@AdminECLIsLocked");
}
/*============================================================================*/
/*
* Further
*/
/*============================================================================*/
@NeedsNativeEvaluate("@Abstract")
@ParamCount(4)
public static ValueHolder atAbstract(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
return ctx.evaluateNative("@Abstract(" + params[0].quoteValue() + ";" + params[1].quoteValue() + ";" + params[2].quoteValue() + ";"
+ params[3].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@AbstractSimple")
@ParamCount(1)
public static ValueHolder atAbstractSimple(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
return ctx.evaluateNative("@AbstractSimple(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@BrowserInfo")
@ParamCount(1)
public static ValueHolder atBrowserInfo(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@BrowserInfo(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@ClientType")
@ParamCount(0)
public static ValueHolder atClientType(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@ClientType");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DB2Schema")
@ParamCount(2)
public static ValueHolder atDB2Schema(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@DB2Schema(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DbColumn")
@ParamCount(4)
public static ValueHolder atDbColumn(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@DbColumn(p1;p2;p3;p4)", params[0], params[1], params[2], params[3]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DbCommand")
@ParamCount({ 2, 5 })
public static ValueHolder atDbCommand(final FormulaContextNotes ctx, final ValueHolder params[]) {
if (params.length == 2)
return ctx.evaluateNative("@DbCommand(p1;p2)", params[0], params[1]);
if (params.length == 3)
return ctx.evaluateNative("@DbCommand(p1;p2;p3)", params[0], params[1], params[2]);
if (params.length == 4)
return ctx.evaluateNative("@DbCommand(p1;p2;p3;p4)", params[0], params[1], params[2], params[3]);
return ctx.evaluateNative("@DbCommand(p1;p2;p3;p4;p5)", params[0], params[1], params[2], params[3], params[4]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DbExists")
@ParamCount({ 1, 2 })
public static ValueHolder atDbExists(final FormulaContextNotes ctx, final ValueHolder[] params) {
if (params.length == 1)
return ctx.evaluateNative("@DbExists(p1)", params[0]);
return ctx.evaluateNative("@DbExists(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DbLookup")
@ParamCount({ 5, 9 })
public static ValueHolder atDbLookup(final FormulaContextNotes ctx, final ValueHolder params[]) throws EvaluateException {
if (params.length == 5)
return ctx.evaluateNative("@DbLookup(p1;p2;p3;p4;p5)", params[0], params[1], params[2], params[3], params[4]);
if (params.length == 6) {
if (params[5].dataType == DataType.KEYWORD_STRING)
return ctx.evaluateNative("@DbLookup(p1;p2;p3;p4;p5;" + params[5].quoteValue() + ")", params[0], params[1], params[2],
params[3], params[4]);
else
return ctx.evaluateNative("@DbLookup(p1;p2;p3;p4;p5;p6)", params[0], params[1], params[2], params[3], params[4], params[5]);
}
if (params.length == 7)
return ctx.evaluateNative("@DbLookup(p1;p2;p3;p4;p5;p6;" + params[6].quoteValue() + ")", params[0], params[1], params[2],
params[3], params[4], params[5]);
if (params.length == 8)
return ctx.evaluateNative("@DbLookup(p1;p2;p3;p4;p5;p6;p7;p8)", params[0], params[1], params[2], params[3], params[4],
params[5], params[6], params[7]);
return ctx.evaluateNative("@DbLookup(p1;p2;p3;p4;p5;p6;p7;p8;p9)", params[0], params[1], params[2], params[3], params[4],
params[5], params[6], params[7], params[8]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DbManager")
@ParamCount(0)
public static ValueHolder atDbManager(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@DbManager");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DbName")
@ParamCount(0)
public static ValueHolder atDbName(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@DbName");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DbTitle")
@ParamCount(0)
public static ValueHolder atDbTitle(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@DbTitle");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DeleteDocument")
@ParamCount(0)
public static ValueHolder atDeleteDocument(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@DeleteDocument");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DocChildren")
@ParamCount({ 0, 3 })
public static ValueHolder atDocChildren(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
StringBuilder sb = new StringBuilder(256);
sb.append("@DocChildren");
if (params.length > 0) {
sb.append('(');
sb.append(params[0].quoteValue());
}
if (params.length > 1) {
sb.append(';');
sb.append(params[1].quoteValue());
}
if (params.length > 2) {
sb.append(';');
sb.append(params[2].quoteValue());
}
if (params.length > 0)
sb.append(')');
return ctx.evaluateNative(sb.toString());
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DocDescendants")
@ParamCount({ 0, 3 })
public static ValueHolder atDocDescendants(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
StringBuilder sb = new StringBuilder(256);
sb.append("@DocDescendants");
for (int i = 0; i < 3; i++)
if (params.length > i) {
sb.append((i == 0) ? '(' : ';');
sb.append(params[i].quoteValue());
}
if (params.length > 0)
sb.append(')');
return ctx.evaluateNative(sb.toString());
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DocLevel")
@ParamCount(0)
public static ValueHolder atDocLevel(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@DocLevel");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DocMark")
@ParamCount(1)
public static ValueHolder atDocMark(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
return ctx.evaluateNative("@DocMark(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DocNumber")
@ParamCount({ 0, 1 })
public static ValueHolder atDocNumber(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
if (params.length == 0)
return ctx.evaluateNative("@DocNumber");
return ctx.evaluateNative("@DocNumber(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DocOmittedLength")
@ParamCount(0)
public static ValueHolder atDocOmittedLength(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@DocOmittedLength");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DocParentNumber")
@ParamCount({ 0, 1 })
public static ValueHolder atDocParentNumber(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
if (params.length == 0)
return ctx.evaluateNative("@DocParentNumber");
return ctx.evaluateNative("@DocParentNumber(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@DocSiblings")
@ParamCount(0)
public static ValueHolder atDocSiblings(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@DocSiblings");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@EditECL")
@ParamCount(2)
public static ValueHolder atEditECL(final FormulaContextNotes ctx, final ValueHolder[] params) {
return ctx.evaluateNative("@EditECL(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@EditUserECL")
@ParamCount(0)
public static ValueHolder atEditUserECL(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@EditUserECL");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@FormLanguage")
@ParamCount(0)
public static ValueHolder atFormLanguage(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@FormLanguage");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@GetAddressBooks")
@ParamCount(1)
public static ValueHolder atGetAddressBooks(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
return ctx.evaluateNative("@GetAddressBooks(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@GetCurrentTimeZone")
@ParamCount(0)
public static ValueHolder atGetCurrentTimeZone(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@GetCurrentTimeZone");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@GetFocusTable")
@ParamCount(1)
public static ValueHolder atGetFocusTable(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
return ctx.evaluateNative("@GetFocusTable(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@GetHTTPHeader")
@ParamCount(1)
public static ValueHolder atGetHTTPHeader(final FormulaContextNotes ctx, final ValueHolder[] params) {
return ctx.evaluateNative("@GetHTTPHeader(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@GetPortsList")
@ParamCount(1)
public static ValueHolder atGetPortsList(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
return ctx.evaluateNative("@GetPortsList(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@GetProfileField")
@ParamCount({ 2, 3 })
public static ValueHolder atGetProfileField(final FormulaContextNotes ctx, final ValueHolder params[]) {
if (params.length == 2)
return ctx.evaluateNative("@GetProfileField(p1;p2)", params[0], params[1]);
return ctx.evaluateNative("@GetProfileField(p1;p2;p3)", params[0], params[1], params[2]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@HardDeleteDocument")
@ParamCount(0)
public static ValueHolder atHardDeleteDocument(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@HardDeleteDocument");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsAgentEnabled")
@ParamCount(1)
public static ValueHolder atIsAgentEnabled(final FormulaContextNotes ctx, final ValueHolder[] params) {
return ctx.evaluateNative("@IsAgentEnabled(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsAppInstalled")
@ParamCount(1)
public static ValueHolder atIsAppInstalled(final FormulaContextNotes ctx, final ValueHolder[] params) {
return ctx.evaluateNative("@IsAppInstalled(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsCategory")
@ParamCount({ 0, 2 })
public static ValueHolder atIsCategory(final FormulaContextNotes ctx, final ValueHolder[] params) {
if (params.length == 0)
return ctx.evaluateNative("@IsCategory");
if (params.length == 1)
return ctx.evaluateNative("@IsCategory(p1)", params[0]);
return ctx.evaluateNative("@IsCategory(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsDocBeingEdited")
@ParamCount(0)
public static ValueHolder atIsDocBeingEdited(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsDocBeingEdited");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsDocBeingLoaded")
@ParamCount(0)
public static ValueHolder atIsDocBeingLoaded(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsDocBeingLoaded");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsDocBeingMailed")
@ParamCount(0)
public static ValueHolder atIsDocBeingMailed(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsDocBeingMailed");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsDocBeingRecalculated")
@ParamCount(0)
public static ValueHolder atIsDocBeingRecalculated(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsDocBeingRecalculated");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsDocBeingSaved")
@ParamCount(0)
public static ValueHolder atIsDocBeingSaved(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsDocBeingSaved");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsDocTruncated")
@ParamCount(0)
public static ValueHolder atIsDocTruncated(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsDocTruncated");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsEmbeddedInsideWCT")
@ParamCount(0)
public static ValueHolder atIsEmbeddedInsideWCT(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsEmbeddedInsideWCT");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsExpandable")
@ParamCount({ 0, 2 })
public static ValueHolder atIsExpandable(final FormulaContextNotes ctx, final ValueHolder[] params) {
if (params.length == 0)
return ctx.evaluateNative("@IsExpandable");
if (params.length == 1)
return ctx.evaluateNative("@IsExpandable(p1)", params[0]);
return ctx.evaluateNative("@IsExpandable(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsModalHelp")
@ParamCount(0)
public static ValueHolder atIsModalHelp(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsModalHelp");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsUsingJavaElement")
@ParamCount(0)
public static ValueHolder atIsUsingJavaElement(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsUsingJavaElement");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@IsVirtualizedDirectory")
@ParamCount(0)
public static ValueHolder atIsVirtualizedDirectory(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@IsVirtualizedDirectory");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@LaunchApp")
@ParamCount(1)
public static ValueHolder atLaunchApp(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@LaunchApp(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@MailSend")
@ParamCount({ 0, 7 })
public static ValueHolder atMailSend(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
StringBuilder sb = new StringBuilder(256);
sb.append("@MailSend");
for (int i = 0; i < 7; i++)
if (params.length > i) {
sb.append((i == 0) ? '(' : ';');
sb.append(params[i].quoteValue());
}
if (params.length > 0)
sb.append(')');
return ctx.evaluateNative(sb.toString());
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Platform")
@ParamCount({ 0, 1 })
public static ValueHolder atPlatform(final FormulaContextNotes ctx, final ValueHolder[] params) throws EvaluateException {
if (params.length == 0)
return ctx.evaluateNative("@Platform");
return ctx.evaluateNative("@Platform(" + params[0].quoteValue() + ")");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@RefreshECL")
@ParamCount(2)
public static ValueHolder atRefreshECL(final FormulaContextNotes ctx, final ValueHolder[] params) {
return ctx.evaluateNative("@RefreshECL(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@ServerName")
@ParamCount(0)
public static ValueHolder atServerName(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@ServerName");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@SetHTTPHeader")
@ParamCount(2)
public static ValueHolder atSetHTTPHeader(final FormulaContextNotes ctx, final ValueHolder[] params) {
return ctx.evaluateNative("@SetHTTPHeader(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@SetProfileField")
@ParamCount({ 2, 3 })
public static ValueHolder atSetProfileField(final FormulaContextNotes ctx, final ValueHolder[] params) {
if (params.length == 2)
return ctx.evaluateNative("@SetProfileField(p1;p2)", params[0], params[1]);
return ctx.evaluateNative("@SetProfileField(p1;p2;p3)", params[0], params[1], params[2]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@ShowParentPreview")
@ParamCount(0)
public static ValueHolder atShowParentPreview(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@ShowParentPreview");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@SoundEx")
@ParamCount(1)
public static ValueHolder atSoundEx(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@SoundEx(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@StatusBar")
@ParamCount(1)
public static ValueHolder atStatusBar(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@StatusBar(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@ThisName")
@ParamCount(0)
public static ValueHolder atThisName(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@ThisName");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@ThisValue")
@ParamCount(0)
public static ValueHolder atThisValue(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@ThisValue");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@TimeToTextInZone")
@ParamCount({ 2, 3 })
public static ValueHolder atTimeToTextInZone(final FormulaContextNotes ctx, final ValueHolder params[]) {
if (params.length == 2)
return ctx.evaluateNative("@TimeToTextInZone(p1;p2)", params[0], params[1]);
return ctx.evaluateNative("@TimeToTextInZone(p1;p2;p3)", params[0], params[1], params[2]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@TimeZoneToText")
@ParamCount({ 1, 2 })
public static ValueHolder atTimeZoneToText(final FormulaContextNotes ctx, final ValueHolder params[]) {
if (params.length == 1)
return ctx.evaluateNative("@TimeZoneToText(p1)", params[0]);
return ctx.evaluateNative("@TimeZoneToText(p1;p2)", params[0], params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@UndeleteDocument")
@ParamCount(0)
public static ValueHolder atUndeleteDocument(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@UndeleteDocument");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@UpdateFormulaContext")
@ParamCount(0)
public static ValueHolder atUpdateFormulaContext(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@UpdateFormulaContext");
}
@ParamCount({ 0, 1 })
public static ValueHolder atUnique(final FormulaContextNotes ctx, final ValueHolder[] params) {
if (params == null || params.length == 0)
return ctx.evaluateNative("@Unique");
return TextFunctions.atUnique(ctx, params);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@URLQueryString")
@ParamCount({ 0, 1 })
public static ValueHolder atURLQueryString(final FormulaContextNotes ctx, final ValueHolder params[]) {
if (params.length == 0)
return ctx.evaluateNative("@URLQueryString");
return ctx.evaluateNative("@URLQueryString(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@UserNameLanguage")
@ParamCount(1)
public static ValueHolder atUserNameLanguage(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@UserNameLanguage(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@UserNamesList")
@ParamCount(0)
public static ValueHolder atUserNamesList(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@UserNamesList");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@UserPrivileges")
@ParamCount(0)
public static ValueHolder atUserPrivileges(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@UserPrivileges");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@UserRoles")
@ParamCount(0)
public static ValueHolder atUserRoles(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@UserRoles");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@V3UserName")
@ParamCount(0)
public static ValueHolder atV3UserName(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@V3UserName");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@V4UserAccess")
@ParamCount(1)
public static ValueHolder atV4UserAccess(final FormulaContextNotes ctx, final ValueHolder params[]) {
return ctx.evaluateNative("@V4UserAccess(p1)", params[0]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@ValidateInternetAddress")
@ParamCount(2)
public static ValueHolder atValidateInternetAddress(final FormulaContextNotes ctx, final ValueHolder params[]) throws EvaluateException {
return ctx.evaluateNative("@ValidateInternetAddress(" + params[0].quoteValue() + ";p1)", params[1]);
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Version")
@ParamCount(0)
public static ValueHolder atVersion(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@Version");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@ViewTitle")
@ParamCount(0)
public static ValueHolder atViewTitle(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@ViewTitle");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@WebDbName")
@ParamCount(0)
public static ValueHolder atWebDbName(final FormulaContextNotes ctx) {
return ctx.evaluateNative("@WebDbName");
}
/*----------------------------------------------------------------------------*/
@NeedsNativeEvaluate("@Zone")
@ParamCount({ 0, 1 })
public static ValueHolder atZone(final FormulaContextNotes ctx, final ValueHolder params[]) {
if (params.length == 0)
return ctx.evaluateNative("@Zone");
return ctx.evaluateNative("@Zone(p1)", params[0]);
}
}
|
apache-2.0
|
enigmampc/catalyst
|
tests/pipeline/test_downsampling.py
|
24481
|
"""
Tests for Downsampled Filters/Factors/Classifiers
"""
import pandas as pd
from pandas.util.testing import assert_frame_equal
from catalyst.pipeline import (
Pipeline,
CustomFactor,
CustomFilter,
CustomClassifier,
)
from catalyst.pipeline.data.testing import TestingDataSet
from catalyst.pipeline.factors.equity import SimpleMovingAverage
from catalyst.pipeline.filters.smoothing import All
from catalyst.testing import CatalystTestCase, parameter_space
from catalyst.testing.fixtures import (
WithTradingSessions,
WithSeededRandomPipelineEngine,
)
from catalyst.utils.input_validation import _qualified_name
from catalyst.utils.numpy_utils import int64_dtype
class NDaysAgoFactor(CustomFactor):
inputs = [TestingDataSet.float_col]
def compute(self, today, assets, out, floats):
out[:] = floats[0]
class NDaysAgoFilter(CustomFilter):
inputs = [TestingDataSet.bool_col]
def compute(self, today, assets, out, bools):
out[:] = bools[0]
class NDaysAgoClassifier(CustomClassifier):
inputs = [TestingDataSet.categorical_col]
dtype = TestingDataSet.categorical_col.dtype
def compute(self, today, assets, out, cats):
out[:] = cats[0]
class ComputeExtraRowsTestcase(WithTradingSessions, CatalystTestCase):
DATA_MIN_DAY = pd.Timestamp('2012-06', tz='UTC')
DATA_MAX_DAY = pd.Timestamp('2015', tz='UTC')
TRADING_CALENDAR_STRS = ('NYSE',)
# Test with different window_lengths to ensure that window length is not
# used when calculating exra rows for the top-level term.
factor1 = TestingDataSet.float_col.latest
factor11 = NDaysAgoFactor(window_length=11)
factor91 = NDaysAgoFactor(window_length=91)
filter1 = TestingDataSet.bool_col.latest
filter11 = NDaysAgoFilter(window_length=11)
filter91 = NDaysAgoFilter(window_length=91)
classifier1 = TestingDataSet.categorical_col.latest
classifier11 = NDaysAgoClassifier(window_length=11)
classifier91 = NDaysAgoClassifier(window_length=91)
all_terms = [
factor1,
factor11,
factor91,
filter1,
filter11,
filter91,
classifier1,
classifier11,
classifier91,
]
@parameter_space(
calendar_name=TRADING_CALENDAR_STRS,
base_terms=[
(factor1, factor11, factor91),
(filter1, filter11, filter91),
(classifier1, classifier11, classifier91),
],
__fail_fast=True
)
def test_yearly(self, base_terms, calendar_name):
downsampled_terms = tuple(
t.downsample('year_start') for t in base_terms
)
all_terms = base_terms + downsampled_terms
all_sessions = self.trading_sessions[calendar_name]
end_session = all_sessions[-1]
years = all_sessions.year
sessions_in_2012 = all_sessions[years == 2012]
sessions_in_2013 = all_sessions[years == 2013]
sessions_in_2014 = all_sessions[years == 2014]
# Simulate requesting computation where the unaltered lookback would
# land exactly on the first date in 2014. We shouldn't request any
# additional rows for the regular terms or the downsampled terms.
for i in range(0, 30, 5):
start_session = sessions_in_2014[i]
self.check_extra_row_calculations(
all_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i,
)
# Simulate requesting computation where the unaltered lookback would
# land on the second date in 2014. We should request one more extra
# row in the downsampled terms to push us back to the first date in
# 2014.
for i in range(0, 30, 5):
start_session = sessions_in_2014[i + 1]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i + 1,
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i,
)
# Simulate requesting computation where the unaltered lookback would
# land on the last date of 2013. The downsampled terms should request
# enough extra rows to push us back to the start of 2013.
for i in range(0, 30, 5):
start_session = sessions_in_2014[i]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + len(sessions_in_2013),
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + 1,
)
# Simulate requesting computation where the unaltered lookback would
# land on the last date of 2012. The downsampled terms should request
# enough extra rows to push us back to the first known date, which is
# in the middle of 2012
for i in range(0, 30, 5):
start_session = sessions_in_2013[i]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + len(sessions_in_2012),
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + 1,
)
@parameter_space(
calendar_name=TRADING_CALENDAR_STRS,
base_terms=[
(factor1, factor11, factor91),
(filter1, filter11, filter91),
(classifier1, classifier11, classifier91),
],
__fail_fast=True
)
def test_quarterly(self, calendar_name, base_terms):
downsampled_terms = tuple(
t.downsample('quarter_start') for t in base_terms
)
all_terms = base_terms + downsampled_terms
# This region intersects with Q4 2013, Q1 2014, and Q2 2014.
tmp = self.trading_sessions[calendar_name]
all_sessions = tmp[tmp.slice_indexer('2013-12-15', '2014-04-30')]
end_session = all_sessions[-1]
months = all_sessions.month
Q4_2013 = all_sessions[months == 12]
Q1_2014 = all_sessions[(months == 1) | (months == 2) | (months == 3)]
Q2_2014 = all_sessions[months == 4]
# Simulate requesting computation where the unaltered lookback would
# land exactly on the first date in Q2 2014. We shouldn't request any
# additional rows for the regular terms or the downsampled terms.
for i in range(0, 15, 5):
start_session = Q2_2014[i]
self.check_extra_row_calculations(
all_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i,
)
# Simulate requesting computation where the unaltered lookback would
# land exactly on the second date in Q2 2014.
# The downsampled terms should request one more extra row.
for i in range(0, 15, 5):
start_session = Q2_2014[i + 1]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i + 1,
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i,
)
# Simulate requesting computation where the unaltered lookback would
# land exactly on the last date in Q1 2014. The downsampled terms
# should request enough extra rows to push us back to the first date of
# Q1 2014.
for i in range(0, 15, 5):
start_session = Q2_2014[i]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + len(Q1_2014),
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + 1,
)
# Simulate requesting computation where the unaltered lookback would
# land exactly on the last date in Q4 2013. The downsampled terms
# should request enough extra rows to push us back to the first known
# date, which is in the middle of december 2013.
for i in range(0, 15, 5):
start_session = Q1_2014[i]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + len(Q4_2013),
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + 1,
)
@parameter_space(
calendar_name=TRADING_CALENDAR_STRS,
base_terms=[
(factor1, factor11, factor91),
(filter1, filter11, filter91),
(classifier1, classifier11, classifier91),
],
__fail_fast=True
)
def test_monthly(self, calendar_name, base_terms):
downsampled_terms = tuple(
t.downsample('month_start') for t in base_terms
)
all_terms = base_terms + downsampled_terms
# This region intersects with Dec 2013, Jan 2014, and Feb 2014.
tmp = self.trading_sessions[calendar_name]
all_sessions = tmp[tmp.slice_indexer('2013-12-15', '2014-02-28')]
end_session = all_sessions[-1]
months = all_sessions.month
dec2013 = all_sessions[months == 12]
jan2014 = all_sessions[months == 1]
feb2014 = all_sessions[months == 2]
# Simulate requesting computation where the unaltered lookback would
# land exactly on the first date in feb 2014. We shouldn't request any
# additional rows for the regular terms or the downsampled terms.
for i in range(0, 10, 2):
start_session = feb2014[i]
self.check_extra_row_calculations(
all_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i,
)
# Simulate requesting computation where the unaltered lookback would
# land on the second date in feb 2014. We should request one more
# extra row in the downsampled terms to push us back to the first date
# in 2014.
for i in range(0, 10, 2):
start_session = feb2014[i + 1]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i + 1,
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i,
)
# Simulate requesting computation where the unaltered lookback would
# land on the last date of jan 2014. The downsampled terms should
# request enough extra rows to push us back to the start of jan 2014.
for i in range(0, 10, 2):
start_session = feb2014[i]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + len(jan2014),
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + 1,
)
# Simulate requesting computation where the unaltered lookback would
# land on the last date of dec 2013. The downsampled terms should
# request enough extra rows to push us back to the first known date,
# which is in the middle of december 2013.
for i in range(0, 10, 2):
start_session = jan2014[i]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + len(dec2013),
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + 1,
)
@parameter_space(
calendar_name=TRADING_CALENDAR_STRS,
base_terms=[
(factor1, factor11, factor91),
(filter1, filter11, filter91),
(classifier1, classifier11, classifier91),
],
__fail_fast=True
)
def test_weekly(self, calendar_name, base_terms):
downsampled_terms = tuple(
t.downsample('week_start') for t in base_terms
)
all_terms = base_terms + downsampled_terms
# December 2013
# Mo Tu We Th Fr Sa Su
# 1
# 2 3 4 5 6 7 8
# 9 10 11 12 13 14 15
# 16 17 18 19 20 21 22
# 23 24 25 26 27 28 29
# 30 31
# January 2014
# Mo Tu We Th Fr Sa Su
# 1 2 3 4 5
# 6 7 8 9 10 11 12
# 13 14 15 16 17 18 19
# 20 21 22 23 24 25 26
# 27 28 29 30 31
# This region intersects with the last full week of 2013, the week
# shared by 2013 and 2014, and the first full week of 2014.
tmp = self.trading_sessions[calendar_name]
all_sessions = tmp[tmp.slice_indexer('2013-12-27', '2014-01-12')]
end_session = all_sessions[-1]
week0 = all_sessions[
all_sessions.slice_indexer('2013-12-27', '2013-12-29')
]
week1 = all_sessions[
all_sessions.slice_indexer('2013-12-30', '2014-01-05')
]
week2 = all_sessions[
all_sessions.slice_indexer('2014-01-06', '2014-01-12')
]
# Simulate requesting computation where the unaltered lookback would
# land exactly on the first date in week 2. We shouldn't request any
# additional rows for the regular terms or the downsampled terms.
for i in range(3):
start_session = week2[i]
self.check_extra_row_calculations(
all_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i,
)
# Simulate requesting computation where the unaltered lookback would
# land exactly on the second date in week 2. The downsampled terms
# should request one more extra row.
for i in range(3):
start_session = week2[i + 1]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i + 1,
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i,
expected_extra_rows=i,
)
# Simulate requesting computation where the unaltered lookback would
# land exactly on the last date in week 1. The downsampled terms
# should request enough extra rows to push us back to the first date of
# week 1.
for i in range(3):
start_session = week2[i]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + len(week1),
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + 1,
)
# Simulate requesting computation where the unaltered lookback would
# land exactly on the last date in week0. The downsampled terms
# should request enough extra rows to push us back to the first known
# date, which is in the middle of december 2013.
for i in range(3):
start_session = week1[i]
self.check_extra_row_calculations(
downsampled_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + len(week0),
)
self.check_extra_row_calculations(
base_terms,
all_sessions,
start_session,
end_session,
min_extra_rows=i + 1,
expected_extra_rows=i + 1,
)
def check_extra_row_calculations(self,
terms,
all_sessions,
start_session,
end_session,
min_extra_rows,
expected_extra_rows):
"""
Check that each term in ``terms`` computes an expected number of extra
rows for the given parameters.
"""
for term in terms:
result = term.compute_extra_rows(
all_sessions,
start_session,
end_session,
min_extra_rows,
)
self.assertEqual(
result,
expected_extra_rows,
"Expected {} extra_rows from {}, but got {}.".format(
expected_extra_rows,
term,
result,
)
)
class DownsampledPipelineTestCase(WithSeededRandomPipelineEngine,
CatalystTestCase):
# Extend into the last few days of 2013 to test year/quarter boundaries.
START_DATE = pd.Timestamp('2013-12-15', tz='UTC')
# Extend into the first few days of 2015 to test year/quarter boundaries.
END_DATE = pd.Timestamp('2015-01-06', tz='UTC')
ASSET_FINDER_EQUITY_SIDS = tuple(range(10))
def check_downsampled_term(self, term):
# June 2014
# Mo Tu We Th Fr Sa Su
# 1
# 2 3 4 5 6 7 8
# 9 10 11 12 13 14 15
# 16 17 18 19 20 21 22
# 23 24 25 26 27 28 29
# 30
all_sessions = self.nyse_sessions
compute_dates = all_sessions[
all_sessions.slice_indexer('2014-06-05', '2015-01-06')
]
start_date, end_date = compute_dates[[0, -1]]
pipe = Pipeline({
'year': term.downsample(frequency='year_start'),
'quarter': term.downsample(frequency='quarter_start'),
'month': term.downsample(frequency='month_start'),
'week': term.downsample(frequency='week_start'),
})
# Raw values for term, computed each day from 2014 to the end of the
# target period.
raw_term_results = self.run_pipeline(
Pipeline({'term': term}),
start_date=pd.Timestamp('2014-01-02', tz='UTC'),
end_date=pd.Timestamp('2015-01-06', tz='UTC'),
)['term'].unstack()
expected_results = {
'year': (raw_term_results
.groupby(pd.TimeGrouper('AS'))
.first()
.reindex(compute_dates, method='ffill')),
'quarter': (raw_term_results
.groupby(pd.TimeGrouper('QS'))
.first()
.reindex(compute_dates, method='ffill')),
'month': (raw_term_results
.groupby(pd.TimeGrouper('MS'))
.first()
.reindex(compute_dates, method='ffill')),
'week': (raw_term_results
.groupby(pd.TimeGrouper('W', label='left'))
.first()
.reindex(compute_dates, method='ffill')),
}
results = self.run_pipeline(pipe, start_date, end_date)
for frequency in expected_results:
result = results[frequency].unstack()
expected = expected_results[frequency]
assert_frame_equal(result, expected)
def _test_downsample_windowed_factor(self):
self.check_downsampled_term(
SimpleMovingAverage(
inputs=[TestingDataSet.float_col],
window_length=5,
)
)
def _test_downsample_non_windowed_factor(self):
sma = SimpleMovingAverage(
inputs=[TestingDataSet.float_col],
window_length=5,
)
self.check_downsampled_term(((sma + sma) / 2).rank())
def _test_downsample_windowed_filter(self):
sma = SimpleMovingAverage(
inputs=[TestingDataSet.float_col],
window_length=5,
)
self.check_downsampled_term(All(inputs=[sma.top(4)], window_length=5))
def _test_downsample_nonwindowed_filter(self):
sma = SimpleMovingAverage(
inputs=[TestingDataSet.float_col],
window_length=5,
)
self.check_downsampled_term(sma > 5)
def _test_downsample_windowed_classifier(self):
class IntSumClassifier(CustomClassifier):
inputs = [TestingDataSet.float_col]
window_length = 8
dtype = int64_dtype
missing_value = -1
def compute(self, today, assets, out, floats):
out[:] = floats.sum(axis=0).astype(int) % 4
self.check_downsampled_term(IntSumClassifier())
def _test_downsample_nonwindowed_classifier(self):
sma = SimpleMovingAverage(
inputs=[TestingDataSet.float_col],
window_length=5,
)
self.check_downsampled_term(sma.quantiles(5))
def test_errors_on_bad_downsample_frequency(self):
f = NDaysAgoFactor(window_length=3)
with self.assertRaises(ValueError) as e:
f.downsample('bad')
expected = (
"{}() expected a value in "
"('month_start', 'quarter_start', 'week_start', 'year_start') "
"for argument 'frequency', but got 'bad' instead."
).format(_qualified_name(f.downsample))
self.assertEqual(str(e.exception), expected)
|
apache-2.0
|
edeunix/across
|
across/edit-organization.php
|
3237
|
<?
include('top.php');
include('maps-load.html');
?>
<h3>Setup and configuration data</h3>
<a href="frontend.php">Back to Frontend</a>
<hr width="90%">
<div class="across" align="center">
<!-- SCORE -->
<div data-pws-tab="organization" data-pws-tab-name="Organization">
<form action="organization_xml_create.php" method="post">
<!-- Name -->
Name:
<br>
<input name="name" type="text" size="30" placeholder="My organization/institution name">
<br>
<!-- Acronym -->
Acronym (without blank space):
<br>
<input name="acronym" type="text" size="8" placeholder="ACROSS" style="text-transform: uppercase;">
<br>
<!-- Contact e-mail -->
Contact e-mail:
<br>
<input name="mail" type="text" size="30" placeholder="contact@myvo.br">
<br>
<br>
<!-- Coordinates -->
Coordinates (map):
<br>
<div id="mapCanvas"></div>
<br>
<div id="infoPanel">
Latitude, Longitude:
<br>
<input name="coordinates" type="text" size="20" placeholder="-22.9, -43.12" id="info">
<br>
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
<br />
<input type="submit">
</form>
</div>
<!-- Attribute Provider Module-->
<div data-pws-tab="ap" data-pws-tab-name="Attribute Provider Module">
<form action="ap_xml_create.php" method="post">
<!-- Name -->
Address (IP or FQDN):
<br>
<input name="address" type="text" size="30" placeholder="e.g. 200.20.10.22 or myAP.across.br">
<br><br>
<!-- Credential -->
Username: <input name="username" type="text" size="30" placeholder="admin" disabled="disabled">
Password: <input name="password" type="password" size="30" placeholder="****" disabled="disabled">
<br><br>
<input type="submit">
</form>
</div>
<!-- institutions-->
<div data-pws-tab="institutions" data-pws-tab-name="Add Institutions">
<form action="institutions_xml_create.php" method="post">
<p>
Add Institutions is necessary to verify distributed policies and list resources.
</p>
<input type="button" id="add_field_institution" value="institution++">
<br /><br />
<div id="list_institution">
<!-- Name -->
Address (IP or FQDN):
<br>
<input name="address[]" type="text" size="30" placeholder="e.g. 200.20.10.22 or myAP.across.br">
<br>
<!-- Acronym -->
Acronym:
<br>
<input name="acronym[]" type="text" size="6" placeholder="UFF" style="text-transform:uppercase;">
<br>
<!-- Description -->
Description:
<br>
<input name="description[]" type="text" size="30" placeholder="e.g. Universidade Federal Fluminense">
<br><br>
<!-- Credential -->
Username: <input name="username[]" type="text" size="30" placeholder="admin" disabled="disabled">
Password: <input name="password[]" type="password" size="30" placeholder="****" disabled="disabled">
<br>
<hr>
</div>
<input type="submit">
</form>
</div>
</div>
<br>
<?
include('bottom.php');
?>
|
apache-2.0
|
sustacek/stripes-4-netbeans
|
s4n.core/src/org/netbeans/modules/web/stripes/config/StripesWebFrameworkProvider.java
|
21981
|
/*
* Stripes1.5.java
*
* Created on October 23, 8, 11:21 AM
*/
package org.netbeans.modules.web.stripes.config;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.java.project.classpath.ProjectClassPathModifier;
import org.netbeans.api.project.FileOwnerQuery;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.netbeans.api.project.libraries.Library;
import org.netbeans.api.project.libraries.LibraryManager;
import org.netbeans.modules.j2ee.dd.api.common.CommonDDBean;
import org.netbeans.modules.j2ee.dd.api.common.CreateCapability;
import org.netbeans.modules.j2ee.dd.api.common.InitParam;
import org.netbeans.modules.j2ee.dd.api.common.VersionNotSupportedException;
import org.netbeans.modules.j2ee.dd.api.web.DDProvider;
import org.netbeans.modules.j2ee.dd.api.web.Filter;
import org.netbeans.modules.j2ee.dd.api.web.FilterMapping;
import org.netbeans.modules.j2ee.dd.api.web.Servlet;
import org.netbeans.modules.j2ee.dd.api.web.ServletMapping;
import org.netbeans.modules.j2ee.dd.api.web.WebApp;
import org.netbeans.modules.j2ee.dd.api.web.WelcomeFileList;
import org.netbeans.modules.web.api.webmodule.ExtenderController;
import org.netbeans.modules.web.api.webmodule.WebModule;
import org.netbeans.modules.web.spi.webmodule.WebFrameworkProvider;
import org.netbeans.modules.web.spi.webmodule.WebModuleExtender;
import org.netbeans.modules.web.stripes.palette.StripesPaletteUtilities;
import org.netbeans.modules.web.stripes.util.Constants;
import org.openide.ErrorManager;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileStateInvalidException;
import org.openide.filesystems.FileSystem;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;
public class StripesWebFrameworkProvider extends WebFrameworkProvider {
private static final Logger log = Logger.getLogger(Constants.LOGGER_NAME);
private StripesWebModuleExtender extender;
private ExtenderController controller;
private static final String FRAMEWORK_NAME = "Stripes 1.5";
private static final String FRAMEWORK_DESCRIPTION = "Modern, annotation " +
"driven and configuration-files-less MVC framework.";
private static final String JSTL_LIB_NAME = "JSTL 1.2";
private static final String STRIPES_LIB_NAME = "Stripes 1.5";
private static final String DISPATCHER_ERROR_MSG = "Dispatcher url mapping has wrong format.";
private static final String FILTER_ERROR_MSG = "Filter url mapping has wrong format.";
private static final String DISPATCHER_SERVLET_CLASS = "net.sourceforge.stripes.controller.DispatcherServlet";
private static final String DISPATCHER_SERVLET_NAME = "DispatcherServlet";
private static final String FILTER_CLASS = "net.sourceforge.stripes.controller.StripesFilter";
private static final String FILTER_NAME = "StripesFilter";
private static final String ENCODING = "utf-8";
private final Set<String> errors = new HashSet<String>(2);
public StripesWebFrameworkProvider() {
super(FRAMEWORK_NAME, FRAMEWORK_DESCRIPTION);
}
@Override
public boolean isInWebModule(WebModule wm) {
return true;
}
@Override
public WebModuleExtender createWebModuleExtender(WebModule wm,
ExtenderController controller) {
extender = new StripesWebModuleExtender(this,
StripesConfig.getInitialConfig());
this.controller = controller;
return extender;
}
/**
* No configuration files for Stripes.
*
* @param wm
* @return
*/
@Override
public File[] getConfigurationFiles(WebModule wm) {
return null;
}
@Override
public String getDescription() {
return FRAMEWORK_DESCRIPTION;
}
@Override
public String getName() {
return FRAMEWORK_NAME;
}
/**
* Implementation of extend method from StripesWebModuleExtender.
*
* @param wm
* @return
*/
protected Set<FileObject> extendImpl(WebModule wm) {
EnableFrameworkAction enableFrameworkAction =
new EnableFrameworkAction(wm, extender.getComponent());
FileObject webInf = wm.getWebInf();
if (webInf != null) {
try {
FileSystem fs = webInf.getFileSystem();
fs.runAtomicAction(enableFrameworkAction);
} catch (IOException e) {
ErrorManager.getDefault().notify(e);
return null;
}
}
return enableFrameworkAction.getFilesToOpen();
}
/**
* Checks the errors based on current cunfiguration in UI.
*
* Clears all errors, calls getComponent(), gets the corresponding
* configuration and if any error occurs (badly formed url mapping etc.),
* adds and error message to errors.
*/
protected void checkErrors() {
errors.clear();
StripesConfig conf = getConfiguration();
String newDispatcherValue = conf.getStripesDispatcherUrlPattern();
if (!ConfigurationValidator.isDispatcherUrlPatternValid(newDispatcherValue)) {
errors.add(DISPATCHER_ERROR_MSG);
} else {
errors.remove(DISPATCHER_ERROR_MSG);
}
String newFilterValue = conf.getStripesFilterUrlPattern();
if (!ConfigurationValidator.isFilterUrlPatternValid(newFilterValue)) {
errors.add(FILTER_ERROR_MSG);
} else {
errors.remove(FILTER_ERROR_MSG);
}
}
public Set<String> getErrors() {
return errors;
}
/**
* Gets the StripesConfig object filled with values distilled from
* UI.
*
* @return
*/
protected StripesConfig getConfiguration() {
StripesConfig config = new StripesConfig();
StripesConfigPanel panel = extender.getComponent();
// main tab
config.setStripesDispatcherUrlPattern(panel.getDispatcherUrl());
config.setStripesFilterUrlPattern(panel.getFilterUrl());
// localization
config.setBundleCreated(panel.getCreateResourcesFile());
if (config.isBundleCreated()) {
// included localizations
config.setIncludedLocalizations(panel.getIncludedLocalizations());
// default localization
config.setDefaultLocalization(panel.getDefaultLocalization());
}
// libraries
config.setJstlIncluded(panel.getIncludeJSTL());
return config;
}
protected ExtenderController getController() {
return controller;
}
private static class EnableFrameworkAction implements FileSystem.AtomicAction {
private Set<FileObject> filesToOpen = new LinkedHashSet<FileObject>();
private WebModule webModule;
private StripesConfigPanel frameworkPanel;
public EnableFrameworkAction(WebModule webModule, StripesConfigPanel frameworkPanel) {
this.webModule = webModule;
this.frameworkPanel = frameworkPanel;
}
private static enum FilterMappingType {
URL_PATTERN,
SERVLET_NAME
}
private static enum FilterMappingDispatcher {
REQUEST
}
public void run() throws IOException {
// MODIFY WEB.XML
FileObject dd = webModule.getDeploymentDescriptor();
WebApp webApp = DDProvider.getDefault().getDDRoot(dd);
Project project = FileOwnerQuery.getOwner(dd);
addServlet(webApp, DISPATCHER_SERVLET_NAME,
DISPATCHER_SERVLET_CLASS, frameworkPanel.getDispatcherUrl(), "1");
Map<String, String> initParams = new HashMap<String, String>(4);
initParams.put("ActionResolver.Packages", "TODO -- enter comma " +
"separated packages with Action Beans here");
initParams.put("LocalePicker.Locales", getLocalePickerContent(
frameworkPanel.getDefaultLocalization(),
frameworkPanel.getIncludedLocalizations()));
// initParams.put("Interceptor.Classes", "net.sourceforge.stripes.controller.BeforeAfterMethodInterceptor");
// initParams.put("MultipartWrapper.Class", "net.sourceforge.stripes.controller.multipart.CommonsMultipartWrapper");
addFilter(webApp, "StripesFilter", FILTER_CLASS, frameworkPanel.getFilterUrl(),
initParams, FilterMappingDispatcher.REQUEST);
addFilterMapping(webApp, FILTER_NAME, DISPATCHER_SERVLET_NAME,
FilterMappingType.SERVLET_NAME, FilterMappingDispatcher.REQUEST);
WelcomeFileList welcomeFiles = webApp.getSingleWelcomeFileList();
if (welcomeFiles == null) {
try {
welcomeFiles = (WelcomeFileList) webApp.createBean("WelcomeFileList");
webApp.setWelcomeFileList(welcomeFiles);
} catch (ClassNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
}
if (welcomeFiles.sizeWelcomeFile() == 0) {
welcomeFiles.addWelcomeFile("index.jsp");
}
webApp.write(dd);
log.info("web.xml modified");
addFileToOpen(dd);
// ADD libraries
addLibraryToWebModule(webModule, STRIPES_LIB_NAME);
log.info("stripes library added");
if (frameworkPanel.getIncludeJSTL()) {
addLibraryToWebModule(webModule, JSTL_LIB_NAME);
log.info("jstl library added");
}
// CREATE FOLDERS FOR FILES
FileObject webInf = webModule.getWebInf();
FileObject jspf = webInf.createFolder("jspf");
FileObject jsp = webInf.createFolder("jsp");
FileObject layout = webInf.createFolder("layout");
FileObject docBase = webModule.getDocumentBase();
FileObject css = docBase.createFolder("css");
FileObject js = docBase.createFolder("js");
FileObject resourcesRoot = getProjectResourcesRoot(project);
// COPY TEMPLATE STRIPES RESOURCES (BUNDLES, LAYOUTS, CSS, JS...)
if(frameworkPanel.getCreateResourcesFile()){
Locale defaultLang = frameworkPanel.getDefaultLocalization();
copyResource("StripesResources_" + defaultLang + ".properties",
FileUtil.createData(resourcesRoot, "StripesResources.properties"));
log.info("default resource bundle created");
for(Locale locale: frameworkPanel.getIncludedLocalizations()){
copyResource("StripesResources_" + locale + ".properties",
FileUtil.createData(resourcesRoot, "StripesResources_" + locale + ".properties"));
log.log(Level.INFO, "{0} resource bundle created", locale);
}
}
copyResource("menu.jspf", FileUtil.createData(jspf, "menu.jspf"));
copyResource("footer.jspf", FileUtil.createData(jspf, "footer.jspf"));
copyResource("layout-definition.jsp", FileUtil.createData(layout, "layout-definition.jsp"));
copyResource("layout-usage.jsp", FileUtil.createData(jsp, "layout-usage.jsp"));
copyResource("javascript.js", FileUtil.createData(js, "javascript.js"));
copyResource("style.css", FileUtil.createData(css, "style.css"));
log.info("jsp resources copied");
// MODIFY EXISTING INDEX.JSP
// FileObject documentBase = webModule.getDocumentBase();
// FileObject indexJsp = documentBase.getFileObject("index.jsp");
// if (indexJsp == null) {
// indexJsp = FileUtil.createData(documentBase, "index.jsp");
// }
// addFileToOpen(copyResource("redirect.jsp", indexJsp));
}
public void addFileToOpen(FileObject file) {
filesToOpen.add(file);
}
public Set<FileObject> getFilesToOpen() {
return filesToOpen;
}
protected FileObject copyResource(String resourceName, FileObject target) throws UnsupportedEncodingException, IOException {
InputStream in = getClass().getResourceAsStream("resources/" + resourceName);
String lineSeparator = System.getProperty("line.separator");
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, ENCODING));
try {
String line = reader.readLine();
while (line != null) {
buffer.append(line);
buffer.append(lineSeparator);
line = reader.readLine();
}
} finally {
reader.close();
}
FileLock lock = target.lock();
try {
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(target.getOutputStream(lock), ENCODING));
try {
writer.write(buffer.toString());
} finally {
writer.close();
}
} finally {
lock.releaseLock();
}
return target;
}
private void addLibraryToWebModule(WebModule wm, String libraryName) {
FileObject docroot = wm.getDocumentBase();
FileObject srcRootFO = null;
Project project = FileOwnerQuery.getOwner(docroot);
SourceGroup[] sgs = StripesPaletteUtilities.getSourceGroups(project,
JavaProjectConstants.SOURCES_TYPE_JAVA);
if(0 != sgs.length){
srcRootFO = sgs[0].getRootFolder();
}
Library lib = LibraryManager.getDefault().getLibrary(libraryName);
if (lib != null && srcRootFO != null) {
try {
ProjectClassPathModifier.addLibraries(
new Library[]{lib}, srcRootFO, ClassPath.COMPILE);
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
Logger.getLogger("global").log(Level.INFO,
"ProjectClassPathModifier could not add the {0} "
+ "library to project''s classpath.", libraryName);
}
}
}
protected Servlet addServlet(WebApp webApp, String name,
String classname, String pattern, String loadOnStartup) throws IOException {
Servlet servlet = (Servlet) createBean(webApp, "Servlet");
servlet.setServletName(name);
servlet.setServletClass(classname);
if (loadOnStartup != null) {
servlet.setLoadOnStartup(new BigInteger(loadOnStartup));
}
webApp.addServlet(servlet);
if (pattern != null) {
addServletMapping(webApp, name, pattern);
}
return servlet;
}
protected ServletMapping addServletMapping(WebApp webApp, String name, String pattern) throws IOException {
ServletMapping mapping = (ServletMapping) createBean(webApp, "ServletMapping");
mapping.setServletName(name);
mapping.setUrlPattern(pattern);
webApp.addServletMapping(mapping);
return mapping;
}
protected Filter addFilter(WebApp webApp, String name, String classname,
String pattern, Map<String, String> initParams,
FilterMappingDispatcher mappingDispatcher) throws IOException {
Filter filter = (Filter) createBean(webApp, "Filter");
filter.setFilterName(name);
filter.setFilterClass(classname);
if(null != initParams){
for(String paramName: initParams.keySet()){
InitParam ip = (InitParam) createBean(webApp, "InitParam");
ip.setParamName(paramName);
ip.setParamValue(initParams.get(paramName));
filter.addInitParam(ip);
}
}
webApp.addFilter(filter);
if (pattern != null) {
addFilterMapping(webApp, name, pattern,
FilterMappingType.URL_PATTERN, mappingDispatcher);
}
return filter;
}
protected FilterMapping addFilterMapping(WebApp webApp, String filterName,
String mappingValue, FilterMappingType mappingType,
FilterMappingDispatcher mappingDispatcher) throws IOException {
FilterMapping mapping = (FilterMapping) createBean(webApp, "FilterMapping");
mapping.setFilterName(filterName);
switch(mappingType){
case SERVLET_NAME:
mapping.setServletName(mappingValue);
break;
case URL_PATTERN:
mapping.setUrlPattern(mappingValue);
break;
default:
throw new IllegalArgumentException("Not supported filter " +
"mapping type");
}
try {
mapping.setDispatcher(new String[] {mappingDispatcher.toString()});
} catch (VersionNotSupportedException ve){
log.warning(ve.getMessage());
}
webApp.addFilterMapping(mapping);
return mapping;
}
protected InitParam addContextParam(WebApp webApp, String name, String value) throws IOException {
InitParam initParam = (InitParam) createBean(webApp, "InitParam");
initParam.setParamName(name);
initParam.setParamValue(value);
webApp.addContextParam(initParam);
return initParam;
}
protected CommonDDBean createBean(CreateCapability creator, String beanName) throws IOException {
CommonDDBean bean = null;
try {
bean = creator.createBean(beanName);
} catch (ClassNotFoundException ex) {
ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
throw new IOException("Error creating bean with name:" + beanName);
}
return bean;
}
protected Library getLibrary(String name) {
return LibraryManager.getDefault().getLibrary(name);
}
protected FileSystem getDefaultFileSystem() throws FileStateInvalidException {
return FileUtil.getConfigRoot().getFileSystem();
}
private String getLocaleId(String localeLabel){
if(StripesConfig.CS_LOCALIZATION_LABEL.equals(localeLabel)){
return "cs";
}else if(StripesConfig.EN_LOCALIZATION_LABEL.equals(localeLabel)){
return "en";
} else{
throw new RuntimeException(localeLabel + " is not supported locale label.");
}
}
private String getLocalePickerContent(Locale defaultLocalization,
List<Locale> includedLocalizations) {
StringBuilder sb = new StringBuilder();
sb.append(defaultLocalization).append(":" + ENCODING + ",");
for(Locale locale: includedLocalizations){
if(!locale.equals(defaultLocalization)){
sb.append(locale).append(":" + ENCODING + ",");
}
}
sb.replace(sb.length() - 1, sb.length(), "");
// "cs:utf-8,en:utf-8"
return sb.toString();
}
private FileObject getProjectJavaSourcesRoot(Project project) {
Sources srcs = ProjectUtils.getSources(project);
SourceGroup[] javaSrcs =
srcs.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
if(javaSrcs.length > 0){
return javaSrcs[0].getRootFolder();
}else {
throw new RuntimeException("No java sources in given project.");
}
}
private FileObject getProjectResourcesRoot(Project project) {
Sources srcs = ProjectUtils.getSources(project);
SourceGroup[] resources =
srcs.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_RESOURCES);
if(resources.length > 0){
return resources[0].getRootFolder();
}else {
// no resources in given project => place together with java sources
return getProjectJavaSourcesRoot(project);
// throw new RuntimeException("No resources in given project.");
}
}
}
}
|
apache-2.0
|
petewarden/tensorflow
|
tensorflow/core/kernels/data/finalize_dataset_op.cc
|
20067
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/finalize_dataset_op.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/model.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/experimental/threadpool_dataset_op.h"
#include "tensorflow/core/kernels/data/model_dataset_op.h"
#include "tensorflow/core/kernels/data/name_utils.h"
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const FinalizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const FinalizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const FinalizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const FinalizeDatasetOp::kOutputShapes;
namespace {
// Use "Opt" suffix so that they are not confused with the enums in Options
// proto.
constexpr char kMapVectorizationOpt[] = "map_vectorization";
constexpr char kMapAndBatchFusionOpt[] = "map_and_batch_fusion";
constexpr char kNoopEliminationOpt[] = "noop_elimination";
constexpr char kMapParallelizationOpt[] = "map_parallelization";
constexpr char kShuffleAndRepeatFusionOpt[] = "shuffle_and_repeat_fusion";
constexpr char kFilterFusionOpt[] = "filter_fusion";
constexpr char kFilterWithRandomUniformFusionOpt[] =
"filter_with_random_uniform_fusion";
constexpr char kHoistRandomUniformOpt[] = "hoist_random_uniform";
constexpr char kMapAndFilterFusionOpt[] = "map_and_filter_fusion";
constexpr char kMapFusionOpt[] = "map_fusion";
constexpr char kParallelBatchOpt[] = "parallel_batch";
constexpr char kReorderDataDiscardingOpsOpt[] = "reorder_data_discarding_ops";
constexpr char kAutotuneBufferSizesOpt[] = "autotune_buffer_sizes";
constexpr char kDisablePrefetchLegacyAutotuneOpt[] =
"disable_prefetch_legacy_autotune";
constexpr char kMakeSloppyOpt[] = "make_sloppy";
constexpr char kUseChooseFastestOpt[] = "use_choose_fastest";
constexpr char kBatchParallelizationOpt[] = "batch_parallelization";
constexpr char kEnableGradientDescentOpt[] = "enable_gradient_descent";
constexpr char kAutotuneOpt[] = "autotune";
constexpr char kSlackOpt[] = "slack";
constexpr char kSlackPeriodOpt[] = "slack_period";
void MapVectorizationGraphRewrites(const Options& options,
std::set<tstring>* optimization_enabled,
std::set<tstring>* optimization_disabled) {
if (options.optimization_options()
.map_vectorization()
.optional_enabled_case() != MapVectorization::kEnabled) {
return;
}
if (options.optimization_options().map_vectorization().enabled()) {
optimization_enabled->insert(kMapVectorizationOpt);
} else {
optimization_disabled->insert(kMapVectorizationOpt);
}
}
void DefaultOptimizationGraphRewrites(const Options& options,
std::set<tstring>* optimization_enabled,
std::set<tstring>* optimization_disabled,
std::set<tstring>* optimization_default) {
MapVectorizationGraphRewrites(options, optimization_enabled,
optimization_disabled);
const auto& optimization_options = options.optimization_options();
if (optimization_options.optional_apply_default_optimizations_case() !=
OptimizationOptions::kApplyDefaultOptimizations ||
optimization_options.apply_default_optimizations()) {
if (optimization_options.optional_map_and_batch_fusion_case() !=
OptimizationOptions::kMapAndBatchFusion) {
optimization_default->insert(kMapAndBatchFusionOpt);
}
if (optimization_options.optional_noop_elimination_case() !=
OptimizationOptions::kNoopElimination) {
optimization_default->insert(kNoopEliminationOpt);
}
if (optimization_options.optional_map_parallelization_case() !=
OptimizationOptions::kMapParallelization) {
optimization_default->insert(kMapParallelizationOpt);
}
if (optimization_options.optional_shuffle_and_repeat_fusion_case() !=
OptimizationOptions::kShuffleAndRepeatFusion) {
optimization_default->insert(kShuffleAndRepeatFusionOpt);
}
}
if (optimization_options.optional_filter_fusion_case() ==
OptimizationOptions::kFilterFusion) {
if (optimization_options.filter_fusion()) {
optimization_enabled->insert(kFilterFusionOpt);
} else {
optimization_disabled->insert(kFilterFusionOpt);
}
}
if (optimization_options.optional_filter_with_random_uniform_fusion_case() ==
OptimizationOptions::kFilterWithRandomUniformFusion) {
if (optimization_options.filter_with_random_uniform_fusion()) {
optimization_enabled->insert(kFilterWithRandomUniformFusionOpt);
} else {
optimization_disabled->insert(kFilterWithRandomUniformFusionOpt);
}
}
if (optimization_options.optional_hoist_random_uniform_case() ==
OptimizationOptions::kHoistRandomUniform) {
if (optimization_options.hoist_random_uniform()) {
optimization_enabled->insert(kHoistRandomUniformOpt);
} else {
optimization_disabled->insert(kHoistRandomUniformOpt);
}
}
if (optimization_options.optional_map_and_batch_fusion_case() ==
OptimizationOptions::kMapAndBatchFusion) {
if (optimization_options.map_and_batch_fusion()) {
optimization_enabled->insert(kMapAndBatchFusionOpt);
} else {
optimization_disabled->insert(kMapAndBatchFusionOpt);
}
}
if (optimization_options.optional_map_and_filter_fusion_case() ==
OptimizationOptions::kMapAndFilterFusion) {
if (optimization_options.map_and_filter_fusion()) {
optimization_enabled->insert(kMapAndFilterFusionOpt);
} else {
optimization_disabled->insert(kMapAndFilterFusionOpt);
}
}
if (optimization_options.optional_map_parallelization_case() ==
OptimizationOptions::kMapParallelization) {
if (optimization_options.map_parallelization()) {
optimization_enabled->insert(kMapParallelizationOpt);
} else {
optimization_disabled->insert(kMapParallelizationOpt);
}
}
if (optimization_options.optional_map_fusion_case() ==
OptimizationOptions::kMapFusion) {
if (optimization_options.map_fusion()) {
optimization_enabled->insert(kMapFusionOpt);
} else {
optimization_disabled->insert(kMapFusionOpt);
}
}
if (optimization_options.optional_noop_elimination_case() ==
OptimizationOptions::kNoopElimination) {
if (optimization_options.noop_elimination()) {
optimization_enabled->insert(kNoopEliminationOpt);
} else {
optimization_disabled->insert(kNoopEliminationOpt);
}
}
if (optimization_options.optional_parallel_batch_case() ==
OptimizationOptions::kParallelBatch) {
if (optimization_options.parallel_batch()) {
optimization_enabled->insert(kParallelBatchOpt);
} else {
optimization_disabled->insert(kParallelBatchOpt);
}
}
if (optimization_options.optional_reorder_data_discarding_ops_case() ==
OptimizationOptions::kReorderDataDiscardingOps) {
if (optimization_options.reorder_data_discarding_ops()) {
optimization_enabled->insert(kReorderDataDiscardingOpsOpt);
} else {
optimization_disabled->insert(kReorderDataDiscardingOpsOpt);
}
}
if (optimization_options.optional_shuffle_and_repeat_fusion_case() ==
OptimizationOptions::kShuffleAndRepeatFusion) {
if (optimization_options.shuffle_and_repeat_fusion()) {
optimization_enabled->insert(kShuffleAndRepeatFusionOpt);
} else {
optimization_disabled->insert(kShuffleAndRepeatFusionOpt);
}
}
const bool has_autotune = optimization_options.optional_autotune_case() ==
OptimizationOptions::kAutotune;
const bool has_autotune_buffers =
optimization_options.optional_autotune_buffers_case() ==
OptimizationOptions::kAutotuneBuffers;
if (!(has_autotune && !optimization_options.autotune()) &&
(has_autotune_buffers && optimization_options.autotune_buffers())) {
optimization_enabled->insert(kAutotuneBufferSizesOpt);
optimization_enabled->insert(kDisablePrefetchLegacyAutotuneOpt);
}
if (has_autotune && !optimization_options.autotune()) {
optimization_disabled->insert(kAutotuneBufferSizesOpt);
optimization_disabled->insert(kDisablePrefetchLegacyAutotuneOpt);
}
}
void GraphRewritesOptions(const Options& options,
std::set<tstring>* optimization_enabled,
std::set<tstring>* optimization_disabled,
std::set<tstring>* optimization_default) {
DefaultOptimizationGraphRewrites(options, optimization_enabled,
optimization_disabled, optimization_default);
if (options.optional_deterministic_case() == Options::kDeterministic) {
if (options.deterministic()) {
optimization_disabled->insert(kMakeSloppyOpt);
} else {
optimization_enabled->insert(kMakeSloppyOpt);
}
}
if (options.optional_slack_case() == Options::kSlack) {
if (options.slack()) {
optimization_enabled->insert(kSlackOpt);
} else {
optimization_disabled->insert(kSlackOpt);
}
}
}
void GraphRewriteConfigs(const Options& options,
std::vector<std::string>* configs) {
const auto& optimization_options = options.optimization_options();
const auto& map_vectorization = optimization_options.map_vectorization();
if (map_vectorization.optional_enabled_case() == MapVectorization::kEnabled &&
map_vectorization.enabled() &&
map_vectorization.optional_use_choose_fastest_case() ==
MapVectorization::kUseChooseFastest) {
if (map_vectorization.use_choose_fastest()) {
configs->push_back(absl::StrCat(kMapVectorizationOpt, ":",
kUseChooseFastestOpt, ":true"));
} else {
configs->push_back(absl::StrCat(kMapVectorizationOpt, ":",
kUseChooseFastestOpt, ":false"));
}
}
std::vector<tstring> autotune_only_optimizations = {
kAutotuneBufferSizesOpt, kBatchParallelizationOpt,
kDisablePrefetchLegacyAutotuneOpt, kEnableGradientDescentOpt,
kMapParallelizationOpt};
if (optimization_options.optional_autotune_case() ==
OptimizationOptions::kAutotune &&
!optimization_options.autotune()) {
for (const auto& optimization : autotune_only_optimizations) {
configs->push_back(
absl::StrCat(optimization.data(), ":", kAutotuneOpt, ":false"));
}
} else {
for (const auto& optimization : autotune_only_optimizations) {
configs->push_back(
absl::StrCat(optimization.data(), ":", kAutotuneOpt, ":true"));
}
}
if (options.slack()) {
int num_devices = 1;
if (options.distribute_options().optional_num_devices_case() ==
DistributeOptions::kNumDevices) {
num_devices = options.distribute_options().num_devices();
}
configs->push_back(
absl::StrCat(kSlackOpt, ":", kSlackPeriodOpt, ":", num_devices));
}
}
void GetOptimizationFromOptions(const Options& options,
std::vector<tstring>* optimizations_enabled,
std::vector<tstring>* optimizations_disabled,
std::vector<tstring>* optimizations_default) {
std::set<tstring> enabled_set;
std::set<tstring> disabled_set;
std::set<tstring> default_set;
GraphRewritesOptions(options, &enabled_set, &disabled_set, &default_set);
*optimizations_enabled = {enabled_set.begin(), enabled_set.end()};
*optimizations_disabled = {disabled_set.begin(), disabled_set.end()};
*optimizations_default = {default_set.begin(), default_set.end()};
}
void GetModelDatasetParams(const Options& options,
model::AutotuneAlgorithm* algorithm,
bool* cpu_budget, bool* ram_budget) {
*algorithm = model::AutotuneAlgorithm::HILL_CLIMB;
if (options.optimization_options().autotune_buffers()) {
*algorithm = model::AutotuneAlgorithm::GRADIENT_DESCENT;
}
*cpu_budget = options.optimization_options().autotune_cpu_budget();
*ram_budget = options.optimization_options().autotune_ram_budget();
}
bool ShouldUseMaxIntraOpParallelismDataset(const Options& options) {
return options.threading_options().optional_max_intra_op_parallelism_case() ==
ThreadingOptions::kMaxIntraOpParallelism;
}
bool ShouldUsePrivateThreadPoolDataset(const Options& options) {
return options.threading_options().optional_private_threadpool_size_case() ==
ThreadingOptions::kPrivateThreadpoolSize;
}
bool ShouldUseModelDataset(const Options& options) {
return options.optimization_options().optional_autotune_case() !=
OptimizationOptions::kAutotune ||
options.optimization_options().autotune();
}
bool ShouldUseOptimizeDataset(const Options& options,
const std::vector<tstring>& optimizations_enabled,
const std::vector<tstring>& optimizations_default,
bool has_captured_ref) {
if (has_captured_ref) {
if (!optimizations_enabled.empty() || !optimizations_default.empty()) {
LOG(WARNING)
<< "tf.data graph rewrites are not compatible with reference "
"variables. The following rewrites will be disabled: "
<< absl::StrJoin(optimizations_enabled, ", ") << ", "
<< absl::StrJoin(optimizations_default, ", ")
<< ". To enable rewrites, use resource variables instead by calling "
"`tf.enable_resource_variables()` at the start of the program.";
}
return false;
}
return (options.optimization_options()
.optional_apply_default_optimizations_case() !=
OptimizationOptions::kApplyDefaultOptimizations ||
options.optimization_options().apply_default_optimizations() ||
!optimizations_enabled.empty() || !optimizations_default.empty());
}
} // namespace
FinalizeDatasetOp::FinalizeDatasetOp(OpKernelConstruction* ctx)
: DatasetOpKernel(ctx) {
if (ctx->HasAttr(kHasCapturedRef)) {
OP_REQUIRES_OK(ctx, ctx->GetAttr(kHasCapturedRef, &has_captured_ref_));
} else {
has_captured_ref_ = false;
}
}
class FinalizeDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input, bool has_captured_ref)
: DatasetBase(DatasetContext(ctx)),
input_(input),
has_captured_ref_(has_captured_ref) {
input_->Ref();
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
DCHECK(false) << "FinalizeDatasetOp::Dataset::MakeIteratorInternal is "
"not expected to be called because it is supposed to "
"forward the iterator to its input dataset(s).";
LOG(ERROR) << "Datasets of type " << type_string()
<< " forwards its iterator to its input dataset. "
"`MakeIteratorInternal` is not implemented.";
return nullptr;
}
const DataTypeVector& output_dtypes() const override {
return input_->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return input_->output_shapes();
}
int64 Cardinality() const override { return input_->Cardinality(); }
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
inputs->push_back(input_);
return Status::OK();
}
Status CheckExternalState() const override {
return input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
AttrValue has_captured_ref_attr;
b->BuildAttrValue(has_captured_ref_, &has_captured_ref_attr);
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_graph_node},
{{kHasCapturedRef, has_captured_ref_attr}},
output));
return Status::OK();
}
private:
const DatasetBase* input_;
bool has_captured_ref_;
};
void FinalizeDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase** output) {
DatasetBase* input_dataset;
OP_REQUIRES_OK(ctx,
GetDatasetFromVariantTensor(ctx->input(0), &input_dataset));
std::vector<DatasetBase*> new_datasets;
const Options& options = input_dataset->options();
if (ShouldUseMaxIntraOpParallelismDataset(options)) {
experimental::MaxIntraOpParallelismDatasetOp::MakeDatasetFromOptions(
ctx, input_dataset,
options.threading_options().max_intra_op_parallelism(), output);
input_dataset = *output;
new_datasets.push_back(*output);
}
if (ShouldUsePrivateThreadPoolDataset(options)) {
experimental::PrivateThreadPoolDatasetOp::MakeDatasetFromOptions(
ctx, input_dataset,
options.threading_options().private_threadpool_size(), output);
input_dataset = *output;
new_datasets.push_back(*output);
}
if (ShouldUseModelDataset(options)) {
model::AutotuneAlgorithm algorithm;
bool cpu_budget;
bool ram_budget;
GetModelDatasetParams(options, &algorithm, &cpu_budget, &ram_budget);
ModelDatasetOp::MakeDatasetFromOptions(ctx, input_dataset, algorithm,
cpu_budget, ram_budget, output);
input_dataset = *output;
new_datasets.push_back(*output);
}
std::vector<tstring> optimizations_enabled;
std::vector<tstring> optimizations_disabled;
std::vector<tstring> optimizations_default;
GetOptimizationFromOptions(options, &optimizations_enabled,
&optimizations_disabled, &optimizations_default);
if (ShouldUseOptimizeDataset(options, optimizations_enabled,
optimizations_default, has_captured_ref_)) {
std::vector<std::string> optimization_configs;
GraphRewriteConfigs(options, &optimization_configs);
OptimizeDatasetOp::MakeDatasetFromOptions(
ctx, input_dataset, optimizations_enabled, optimizations_disabled,
optimizations_default, optimization_configs, output);
input_dataset = *output;
new_datasets.push_back(*output);
}
*output = new Dataset(ctx, input_dataset, has_captured_ref_);
for (auto new_dataset : new_datasets) {
new_dataset->Unref();
}
}
namespace {
REGISTER_KERNEL_BUILDER(Name("FinalizeDataset").Device(DEVICE_CPU).Priority(2),
FinalizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("FinalizeDataset")
.Device(DEVICE_GPU)
.HostMemory("input_dataset")
.HostMemory("handle")
.Priority(1),
FinalizeDatasetNoopOp);
} // namespace
} // namespace data
} // namespace tensorflow
|
apache-2.0
|
ctripcorp/dal
|
dal-client/src/main/java/com/ctrip/platform/dal/dao/sqlbuilder/DeleteSqlBuilder.java
|
1798
|
package com.ctrip.platform.dal.dao.sqlbuilder;
import java.sql.SQLException;
import com.ctrip.platform.dal.common.enums.DatabaseCategory;
import com.ctrip.platform.dal.dao.StatementParameters;
public class DeleteSqlBuilder extends AbstractTableSqlBuilder {
private static final String DELETE_TPL = "DELETE FROM %s WHERE %s";
private String whereClause;
private StatementParameters parameters;
/**
* @deprecated not suggested anymore
* @param tableName
* @param dbCategory
* @throws SQLException
*/
public DeleteSqlBuilder(String tableName, DatabaseCategory dbCategory) throws SQLException{
from(tableName).setDatabaseCategory(dbCategory);
setCompatible(true);
}
public DeleteSqlBuilder(){}
public DeleteSqlBuilder from(String tableName) throws SQLException {
super.from(tableName);
return this;
}
public DeleteSqlBuilder setDatabaseCategory(DatabaseCategory dbCategory) throws SQLException {
super.setDatabaseCategory(dbCategory);
return this;
}
public String build(){
return internalBuild(getTableName());
}
public DeleteSqlBuilder where(String whereClause) {
this.whereClause = whereClause;
return this;
}
public DeleteSqlBuilder with(StatementParameters parameters) {
this.parameters = parameters;
return this;
}
@Override
public StatementParameters buildParameters() {
return parameters == null ? super.buildParameters() : parameters;
}
@Override
public String build(String shardStr) {
return internalBuild(getTableName(shardStr));
}
private String internalBuild(String effectiveTableName) {
String whereStr = whereClause == null ? getWhereExp() : whereClause;
return String.format(DELETE_TPL, wrapField(effectiveTableName), whereStr);
}
}
|
apache-2.0
|
dgruber/ubercluster
|
vendor/github.com/dgruber/drmaa2os/reservation.go
|
558
|
package drmaa2os
import (
"github.com/dgruber/drmaa2interface"
)
type Reservation struct {
}
func (r *Reservation) GetID() (string, error) {
return "", nil
}
func (r *Reservation) GetSessionName() (string, error) {
return "", nil
}
func (r *Reservation) GetTemplate() (drmaa2interface.ReservationTemplate, error) {
return drmaa2interface.ReservationTemplate{}, nil
}
func (r *Reservation) GetInfo() (drmaa2interface.ReservationInfo, error) {
return drmaa2interface.ReservationInfo{}, nil
}
func (r *Reservation) Terminate() error {
return nil
}
|
apache-2.0
|
ostap0207/remotify.me
|
remotify.client/src/main/java/remotify/client/ws/processors/CameraProcessor.java
|
395
|
package remotify.client.ws.processors;
import messages.device.CameraMessage;
import remotify.client.profiles.camera.Camera;
import java.awt.image.BufferedImage;
/**
* .
* User: Ostap
* Date: 5/8/14
* Time: 12:07 AM
*/
public class CameraProcessor extends ImageProcessor<CameraMessage> {
@Override
protected BufferedImage getImage() {
return Camera.takePicture();
}
}
|
apache-2.0
|
jberezanski/choco
|
src/chocolatey/Properties/AssemblyInfo.cs
|
879
|
// Copyright © 2017 - 2018 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Runtime.InteropServices;
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bd59231e-97d1-4fc0-a975-80c3fed498b7")]
|
apache-2.0
|
mxm/incubator-beam
|
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/graph/ReplacePgbkWithPrecombineFunctionTest.java
|
6613
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.runners.dataflow.worker.graph;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import com.google.api.services.dataflow.model.InstructionOutput;
import com.google.api.services.dataflow.model.ParDoInstruction;
import com.google.api.services.dataflow.model.ParallelInstruction;
import com.google.api.services.dataflow.model.PartialGroupByKeyInstruction;
import com.google.common.graph.ImmutableNetwork;
import com.google.common.graph.MutableNetwork;
import com.google.common.graph.Network;
import com.google.common.graph.NetworkBuilder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.beam.runners.dataflow.worker.graph.Edges.DefaultEdge;
import org.apache.beam.runners.dataflow.worker.graph.Edges.Edge;
import org.apache.beam.runners.dataflow.worker.graph.Nodes.InstructionOutputNode;
import org.apache.beam.runners.dataflow.worker.graph.Nodes.Node;
import org.apache.beam.runners.dataflow.worker.graph.Nodes.ParallelInstructionNode;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link ReplacePgbkWithPrecombineFunction}. */
@RunWith(JUnit4.class)
public final class ReplacePgbkWithPrecombineFunctionTest {
@Test
public void testPrecombinePgbkIsReplaced() throws Exception {
// Network:
// out1 --> precombine_pgbk --> out2
Map<String, Object> valueCombiningFn = new HashMap<>();
Node out1 = createInstructionOutputNode("out1");
String pgbkName = "precombine_pgbk";
Node precombinePgbk = createPrecombinePgbkNode(pgbkName, valueCombiningFn);
Node out2 = createInstructionOutputNode("out2");
MutableNetwork<Node, Edge> network = createEmptyNetwork();
network.addNode(out1);
network.addNode(precombinePgbk);
network.addNode(out2);
network.addEdge(out1, precombinePgbk, DefaultEdge.create());
network.addEdge(precombinePgbk, out2, DefaultEdge.create());
Network<Node, Edge> inputNetwork = ImmutableNetwork.copyOf(network);
network = new ReplacePgbkWithPrecombineFunction().apply(network);
// Assert that network has same structure (same number of nodes and paths).
assertEquals(inputNetwork.nodes().size(), network.nodes().size());
assertEquals(inputNetwork.edges().size(), network.edges().size());
List<List<Node>> oldPaths = Networks.allPathsFromRootsToLeaves(inputNetwork);
List<List<Node>> newPaths = Networks.allPathsFromRootsToLeaves(network);
assertEquals(oldPaths.size(), newPaths.size());
// Assert that the pgbk node has been replaced.
for (Node node : network.nodes()) {
if (node instanceof ParallelInstructionNode) {
ParallelInstructionNode createdCombineNode = (ParallelInstructionNode) node;
ParallelInstruction parallelInstruction = createdCombineNode.getParallelInstruction();
assertEquals(parallelInstruction.getName(), pgbkName);
assertNull(parallelInstruction.getPartialGroupByKey());
assertNotNull(parallelInstruction.getParDo());
ParDoInstruction parDoInstruction = parallelInstruction.getParDo();
assertEquals(parDoInstruction.getUserFn(), valueCombiningFn);
break;
}
}
}
@Test
public void testNormalPgbkIsNotReplaced() throws Exception {
// Network:
// out1 --> pgbk --> out2
Node out1 = createInstructionOutputNode("out1");
Node pgbk = createPrecombinePgbkNode("pgbk", null);
Node out2 = createInstructionOutputNode("out2");
MutableNetwork<Node, Edge> network = createEmptyNetwork();
network.addNode(out1);
network.addNode(pgbk);
network.addNode(out2);
network.addEdge(out1, pgbk, DefaultEdge.create());
network.addEdge(pgbk, out2, DefaultEdge.create());
Network<Node, Edge> inputNetwork = ImmutableNetwork.copyOf(network);
network = new ReplacePgbkWithPrecombineFunction().apply(network);
// Assert that network is unchanged (identical paths).
List<List<Node>> oldPaths = Networks.allPathsFromRootsToLeaves(inputNetwork);
List<List<Node>> newPaths = Networks.allPathsFromRootsToLeaves(network);
assertThat(oldPaths, containsInAnyOrder(newPaths.toArray()));
// Assert that the pgbk node is still present and unchanged.
for (Node node : network.nodes()) {
if (node instanceof ParallelInstructionNode) {
ParallelInstructionNode newNode = (ParallelInstructionNode) node;
ParallelInstruction parallelInstruction = newNode.getParallelInstruction();
assertEquals(
parallelInstruction, ((ParallelInstructionNode) pgbk).getParallelInstruction());
break;
}
}
}
private static MutableNetwork<Node, Edge> createEmptyNetwork() {
return NetworkBuilder.directed()
.allowsSelfLoops(false)
.allowsParallelEdges(true)
.<Node, Edge>build();
}
/** Creates a PartialGroupByKey node with an optional combining function. */
private static ParallelInstructionNode createPrecombinePgbkNode(
String name, @Nullable Map<String, Object> valueCombiningFn) {
return ParallelInstructionNode.create(
new ParallelInstruction()
.setName(name)
.setPartialGroupByKey(
new PartialGroupByKeyInstruction().setValueCombiningFn(valueCombiningFn)),
Nodes.ExecutionLocation.SDK_HARNESS);
}
/** Creates an {@link InstructionOutputNode} to act as a PCollection. */
private static InstructionOutputNode createInstructionOutputNode(String name) {
return InstructionOutputNode.create(new InstructionOutput().setName(name), "fakeId");
}
}
|
apache-2.0
|
huitseeker/DataVec
|
datavec-api/src/main/java/org/datavec/api/records/reader/impl/csv/CSVRegexRecordReader.java
|
3178
|
/*-
* * Copyright 2017 Skymind, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*/
package org.datavec.api.records.reader.impl.csv;
import org.datavec.api.writable.Text;
import org.datavec.api.writable.Writable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A CSVRecordReader that can split each column into additional columns using regexs.
*
* @author saudet
*/
public class CSVRegexRecordReader extends CSVRecordReader {
protected String[] regexs = null;
protected Pattern[] patterns = null;
protected String delimiter;
protected String quote;
/**
* Skip lines, use delimiter, strip quotes, and parse each column with a regex
* @param skipNumLines the number of lines to skip
* @param delimiter the delimiter
* @param quote the quote to strip
* @param regexs the regexs to parse columns with
*/
public CSVRegexRecordReader(int skipNumLines, String delimiter, String quote, String[] regexs) {
super(skipNumLines);
this.delimiter = delimiter;
this.quote = quote;
this.regexs = regexs;
if (regexs != null) {
patterns = new Pattern[regexs.length];
for (int i = 0; i < regexs.length; i++) {
if (regexs[i] != null) {
patterns[i] = Pattern.compile(regexs[i]);
}
}
}
}
protected List<Writable> parseLine(String line) {
String[] split = line.split(delimiter, -1);
List<Writable> ret = new ArrayList<>();
for (int i = 0; i < split.length; i++) {
String s = split[i];
if (quote != null && s.startsWith(quote) && s.endsWith(quote)) {
int n = quote.length();
s = s.substring(n, s.length() - n).replace(quote + quote, quote);
}
if (regexs != null && regexs[i] != null) {
Matcher m = patterns[i].matcher(s);
if (m.matches()) {
for (int j = 1; j <= m.groupCount(); j++) { //Note: Matcher.group(0) is the entire sequence; we only care about groups 1 onward
ret.add(new Text(m.group(j)));
}
} else {
throw new IllegalStateException("Invalid line: value does not match regex (regex=\"" + regexs[i]
+ "\"; value=\"" + s + "\"");
}
} else {
ret.add(new Text(s));
}
}
return ret;
}
}
|
apache-2.0
|
alibaba/atlas
|
atlas-gradle-plugin/dexpatch/src/main/java/com/taobao/android/dx/dex/file/AnnotationSetRefItem.java
|
2340
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.taobao.android.dx.dex.file;
import com.taobao.android.dx.util.AnnotatedOutput;
import com.taobao.android.dx.util.Hex;
/**
* Indirect reference to an {@link AnnotationSetItem}.
*/
public final class AnnotationSetRefItem extends OffsettedItem {
/** the required alignment for instances of this class */
private static final int ALIGNMENT = 4;
/** write size of this class, in bytes */
private static final int WRITE_SIZE = 4;
/** {@code non-null;} the annotation set to refer to */
private AnnotationSetItem annotations;
/**
* Constructs an instance.
*
* @param annotations {@code non-null;} the annotation set to refer to
*/
public AnnotationSetRefItem(AnnotationSetItem annotations) {
super(ALIGNMENT, WRITE_SIZE);
if (annotations == null) {
throw new NullPointerException("annotations == null");
}
this.annotations = annotations;
}
/** {@inheritDoc} */
@Override
public ItemType itemType() {
return ItemType.TYPE_ANNOTATION_SET_REF_ITEM;
}
/** {@inheritDoc} */
public void addContents(DexFile file) {
MixedItemSection wordData = file.getWordData();
annotations = wordData.intern(annotations);
}
/** {@inheritDoc} */
@Override
public String toHuman() {
return annotations.toHuman();
}
/** {@inheritDoc} */
@Override
protected void writeTo0(DexFile file, AnnotatedOutput out) {
int annotationsOff = annotations.getAbsoluteOffset();
if (out.annotates()) {
out.annotate(4, " annotations_off: " + Hex.u4(annotationsOff));
}
out.writeInt(annotationsOff);
}
}
|
apache-2.0
|
siemens/ASLanPPConnector
|
src/aslan-core/src/main/java/org/avantssar/aslan/CompoundType.java
|
2229
|
// Copyright 2010-2013 (c) IeAT, Siemens AG, AVANTSSAR and SPaCIoS consortia.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.avantssar.aslan;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.avantssar.commons.ErrorGatherer;
import org.avantssar.commons.LocationInfo;
public class CompoundType extends AbstractNamed implements IType {
private final List<IType> componentTypes = new ArrayList<IType>();
public CompoundType(LocationInfo location, ErrorGatherer err, String operator, IType[] componentTypes) {
this(location, err, operator, Arrays.asList(componentTypes));
}
public CompoundType(LocationInfo location, ErrorGatherer err, String operator, List<IType> componentTypes) {
super(location, err, operator, new LowerNameValidator("compound type"));
this.componentTypes.addAll(componentTypes);
}
public List<IType> getBaseTypes() {
return componentTypes;
}
public void accept(IASLanVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean isAssignableFrom(IType subType, IASLanSpec spec) {
if (subType instanceof CompoundType) {
CompoundType ct = (CompoundType) subType;
if (!ct.getName().equals(this.getName())) {
return false;
}
if (ct.getBaseTypes().size() != this.getBaseTypes().size()) {
return false;
}
for (int i = 0; i < this.getBaseTypes().size(); i++) {
if (!this.getBaseTypes().get(i).isAssignableFrom(ct.getBaseTypes().get(i), spec)) {
return false;
}
}
return true;
}
return false;
}
public String toString() {
String s = "";
for (IType t : getBaseTypes()) {
if (s != "") {
s += ", ";
}
s += t.toString();
}
return getName()+"("+s+")";
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-globalaccelerator/src/main/java/com/amazonaws/services/globalaccelerator/model/WithdrawByoipCidrRequest.java
|
3468
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.globalaccelerator.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/globalaccelerator-2018-08-08/WithdrawByoipCidr"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class WithdrawByoipCidrRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The address range, in CIDR notation.
* </p>
*/
private String cidr;
/**
* <p>
* The address range, in CIDR notation.
* </p>
*
* @param cidr
* The address range, in CIDR notation.
*/
public void setCidr(String cidr) {
this.cidr = cidr;
}
/**
* <p>
* The address range, in CIDR notation.
* </p>
*
* @return The address range, in CIDR notation.
*/
public String getCidr() {
return this.cidr;
}
/**
* <p>
* The address range, in CIDR notation.
* </p>
*
* @param cidr
* The address range, in CIDR notation.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public WithdrawByoipCidrRequest withCidr(String cidr) {
setCidr(cidr);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCidr() != null)
sb.append("Cidr: ").append(getCidr());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof WithdrawByoipCidrRequest == false)
return false;
WithdrawByoipCidrRequest other = (WithdrawByoipCidrRequest) obj;
if (other.getCidr() == null ^ this.getCidr() == null)
return false;
if (other.getCidr() != null && other.getCidr().equals(this.getCidr()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCidr() == null) ? 0 : getCidr().hashCode());
return hashCode;
}
@Override
public WithdrawByoipCidrRequest clone() {
return (WithdrawByoipCidrRequest) super.clone();
}
}
|
apache-2.0
|
simonsoft/cms-item
|
src/main/java/se/simonsoft/cms/item/export/CmsExportReader.java
|
1828
|
/**
* Copyright (C) 2009-2017 Simonsoft Nordic AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package se.simonsoft.cms.item.export;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
public interface CmsExportReader {
/**
* Prepares and validates feasibility of import.
*
* @param job providing the location / key for the import
*/
void prepare(CmsImportJob job);
// Currently no need for isReady, the import files must be available already.
//boolean isReady();
/**
* @return map of key-value metadata, null when reader does not support metadata.
*/
public Map<CmsExportMetaKey, String> getMeta();
// Getting contents from cms-backend: OutputStream as parameter. (applicable to Writer)
// Committing with cms-backend: InputStream is suitable.
// Transforming with cms-xmlsource: Reader required, can use new InputStreamReader(InputStream)
// Transforming with cms-xmlsource using contents as parameter: Typically need a String.
// Converting to String:
// Now have the slightly optimized ByteArrayInOutStream in cms-item (avoids a second copy on heap).
public InputStream getContents();
public void getContents(OutputStream receiver) throws IOException;
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.