text stringlengths 2 1.04M | meta dict |
|---|---|
package haproxy
import (
"log"
"os"
"os/exec"
"strconv"
"sync"
"time"
)
type Event int
type Action int
// Events that can be fired from the event channel
const (
HasStarted Event = 1 << iota
HasStopped
HasReloaded
)
// Actions that can be received from the action channel
const (
WantsReload Action = 1 << iota
WantsStop
)
type Server struct {
Socket string
ActionChan chan Action
cmd *exec.Cmd
sync.RWMutex
}
const BINARYPATH = "/usr/local/bin/haproxy"
const CONFIGPATH = "config/haproxy.conf"
func (h *Server) createProcess() {
h.cmd = exec.Command(BINARYPATH, "-f", CONFIGPATH)
}
func (h *Server) setupStdout() {
h.cmd.Stdout = os.Stdout
h.cmd.Stderr = os.Stderr
}
func (h *Server) runProcess() error {
return h.cmd.Start()
}
func (h *Server) Start(notify chan Event, action chan Action) {
h.Lock()
h.createProcess()
h.setupStdout()
err := h.runProcess()
if err != nil {
log.Fatal(err)
}
h.ActionChan = action
h.Unlock()
// TODO: Do something to verify that the process has started,
// is alive, taking request, etc. Almost need a health check
// passed type of thing.
notify <- HasStarted
// Wait for a stop signal, reload signal, or process death
for {
switch <-action {
case WantsReload:
h.reloadProcess()
notify <- HasReloaded
case WantsStop:
h.stopProcess()
notify <- HasStopped
return
}
}
}
func (h *Server) reloadProcess() error {
h.Lock()
// Grab pid of current running process
old := h.cmd
pid := strconv.Itoa(h.cmd.Process.Pid)
// Start a new process, telling it to replace the old process
// This will signal the current process and tell it shutdown, which is why
// we don't need to do it here.
cmd := exec.Command(BINARYPATH, "-f", CONFIGPATH, "-sf", pid)
// Start the new process and check for errors. We bail out if there is
// an error and DON'T replace the old process.
err := cmd.Start()
if err != nil {
return err
}
// No errors? Replace the old process
h.cmd = cmd
h.finishOrKill(10*time.Second, old)
return nil
}
func (h *Server) finishOrKill(waitFor time.Duration, old *exec.Cmd) {
// Create a channel and wait for the old process
// to finish itself
didFinish := make(chan error, 1)
go func() {
didFinish <- old.Wait()
}()
// Wait for the didFinish channel or force kill the process
// if it takes longer than 10 seconds
select {
case <-time.After(waitFor):
log.Println("manually killing process")
if err := old.Process.Kill(); err != nil {
log.Println("failed to kill ", err)
}
case err := <-didFinish:
if err != nil {
log.Println("process finished with error", err)
}
}
}
func (h *Server) stopProcess() error {
return h.cmd.Process.Kill()
}
| {
"content_hash": "e62093701a81ad26c79707c0a538898a",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 75,
"avg_line_length": 19.948529411764707,
"alnum_prop": 0.6752672318466643,
"repo_name": "stevencorona/elastic-haproxy",
"id": "19046ff55f2636fbe4d6120087d53f55932085be",
"size": "2713",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "haproxy/server.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "677"
},
{
"name": "Go",
"bytes": "22437"
}
],
"symlink_target": ""
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.content.Context;
import android.os.Build;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import org.chromium.base.NativeClassQualifiedName;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
/**
* UrlRequest context using Chromium HTTP stack implementation.
*/
@JNINamespace("cronet")
public class CronetUrlRequestContext extends UrlRequestContext {
private static final int LOG_NONE = 3; // LOG(FATAL), no VLOG.
private static final int LOG_DEBUG = -1; // LOG(FATAL...INFO), VLOG(1)
private static final int LOG_VERBOSE = -2; // LOG(FATAL...INFO), VLOG(2)
static final String LOG_TAG = "ChromiumNetwork";
/**
* Synchronize access to mUrlRequestContextAdapter and shutdown routine.
*/
private final Object mLock = new Object();
private final ConditionVariable mInitCompleted = new ConditionVariable(false);
private final AtomicInteger mActiveRequestCount = new AtomicInteger(0);
private long mUrlRequestContextAdapter = 0;
private Thread mNetworkThread;
public CronetUrlRequestContext(Context context,
UrlRequestContextConfig config) {
CronetLibraryLoader.ensureInitialized(context, config);
nativeSetMinLogLevel(getLoggingLevel());
mUrlRequestContextAdapter = nativeCreateRequestContextAdapter(config.toString());
if (mUrlRequestContextAdapter == 0) {
throw new NullPointerException("Context Adapter creation failed.");
}
// Init native Chromium URLRequestContext on main UI thread.
Runnable task = new Runnable() {
@Override
public void run() {
synchronized (mLock) {
// mUrlRequestContextAdapter is guaranteed to exist until
// initialization on main and network threads completes and
// initNetworkThread is called back on network thread.
nativeInitRequestContextOnMainThread(mUrlRequestContextAdapter);
}
}
};
// Run task immediately or post it to the UI thread.
if (Looper.getMainLooper() == Looper.myLooper()) {
task.run();
} else {
new Handler(Looper.getMainLooper()).post(task);
}
}
@Override
public UrlRequest createRequest(String url, UrlRequestListener listener,
Executor executor) {
synchronized (mLock) {
checkHaveAdapter();
return new CronetUrlRequest(this, mUrlRequestContextAdapter, url,
UrlRequest.REQUEST_PRIORITY_MEDIUM, listener, executor);
}
}
@Override
public boolean isEnabled() {
return Build.VERSION.SDK_INT >= 14;
}
@Override
public String getVersionString() {
return "Cronet/" + Version.getVersion();
}
@Override
public void shutdown() {
synchronized (mLock) {
checkHaveAdapter();
if (mActiveRequestCount.get() != 0) {
throw new IllegalStateException(
"Cannot shutdown with active requests.");
}
// Destroying adapter stops the network thread, so it cannot be
// called on network thread.
if (Thread.currentThread() == mNetworkThread) {
throw new IllegalThreadStateException(
"Cannot shutdown from network thread.");
}
}
// Wait for init to complete on main and network thread (without lock,
// so other thread could access it).
mInitCompleted.block();
synchronized (mLock) {
// It is possible that adapter is already destroyed on another thread.
if (!haveRequestContextAdapter()) {
return;
}
nativeDestroy(mUrlRequestContextAdapter);
mUrlRequestContextAdapter = 0;
}
}
@Override
public void startNetLogToFile(String fileName) {
synchronized (mLock) {
checkHaveAdapter();
nativeStartNetLogToFile(mUrlRequestContextAdapter, fileName);
}
}
@Override
public void stopNetLog() {
synchronized (mLock) {
checkHaveAdapter();
nativeStopNetLog(mUrlRequestContextAdapter);
}
}
/**
* Mark request as started to prevent shutdown when there are active
* requests.
*/
void onRequestStarted(UrlRequest urlRequest) {
mActiveRequestCount.incrementAndGet();
}
/**
* Mark request as completed to allow shutdown when there are no active
* requests.
*/
void onRequestDestroyed(UrlRequest urlRequest) {
mActiveRequestCount.decrementAndGet();
}
long getUrlRequestContextAdapter() {
synchronized (mLock) {
checkHaveAdapter();
return mUrlRequestContextAdapter;
}
}
private void checkHaveAdapter() throws IllegalStateException {
if (!haveRequestContextAdapter()) {
throw new IllegalStateException("Context is shut down.");
}
}
private boolean haveRequestContextAdapter() {
return mUrlRequestContextAdapter != 0;
}
/**
* @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and
* {@link #LOG_VERBOSE}.
*/
private int getLoggingLevel() {
int loggingLevel;
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
loggingLevel = LOG_VERBOSE;
} else if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
loggingLevel = LOG_DEBUG;
} else {
loggingLevel = LOG_NONE;
}
return loggingLevel;
}
@SuppressWarnings("unused")
@CalledByNative
private void initNetworkThread() {
synchronized (mLock) {
mNetworkThread = Thread.currentThread();
mInitCompleted.open();
}
Thread.currentThread().setName("ChromiumNet");
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
// Native methods are implemented in cronet_url_request_context.cc.
private static native long nativeCreateRequestContextAdapter(String config);
private static native int nativeSetMinLogLevel(int loggingLevel);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeDestroy(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStartNetLogToFile(long nativePtr,
String fileName);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStopNetLog(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeInitRequestContextOnMainThread(long nativePtr);
}
| {
"content_hash": "5240e35242142262bdb34dcb40d4558d",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 89,
"avg_line_length": 34.10798122065728,
"alnum_prop": 0.64280798348245,
"repo_name": "sgraham/nope",
"id": "e03568c020fa499b6132a81affc3df342184296b",
"size": "7265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/cronet/android/java/src/org/chromium/net/CronetUrlRequestContext.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "39967"
},
{
"name": "C",
"bytes": "4061434"
},
{
"name": "C++",
"bytes": "279546186"
},
{
"name": "CMake",
"bytes": "27212"
},
{
"name": "CSS",
"bytes": "919339"
},
{
"name": "Emacs Lisp",
"bytes": "988"
},
{
"name": "Go",
"bytes": "13628"
},
{
"name": "Groff",
"bytes": "5283"
},
{
"name": "HTML",
"bytes": "15989749"
},
{
"name": "Java",
"bytes": "7541683"
},
{
"name": "JavaScript",
"bytes": "32372588"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "Makefile",
"bytes": "40513"
},
{
"name": "Objective-C",
"bytes": "1584184"
},
{
"name": "Objective-C++",
"bytes": "8249988"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "169060"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "427339"
},
{
"name": "Python",
"bytes": "8346306"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "844553"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "VimL",
"bytes": "4075"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
import inspect
import six
import collections
__all__ = [
'is_simple_callable',
'is_iterable',
'force_str',
'get_object_by_source',
'filter_list',
]
def is_simple_callable(obj):
'''
True if the object is a callable and takes no arguments, else False.
'''
function = inspect.isfunction(obj)
method = inspect.ismethod(obj)
if not (function or method):
return False
args, varargs, keywords, defaults = inspect.getargspec(obj)
len_args = len(args) if function else len(args) - 1
len_defaults = len(defaults) if defaults else 0
return len_args <= len_defaults
def is_iterable(obj):
'''
True if an object is iterable, else False
'''
return hasattr(obj, '__iter__')
def force_str(value, encoding='utf-8'):
"""
Forces the value to a str instance, decoding if necessary.
"""
if six.PY3:
if isinstance(value, bytes):
return str(value, encoding)
return value
def get_object_by_source(obj, source, allow_blank_source=False):
"""
Tries to get the object by source.
Similar to Python's `getattr(obj, source)`, but takes a dot separaed
string for source to get source from nested obj, instead of a single
source field. Also, supports getting source form obj where obj is a
dict type.
Example:
>>> obj = get_object_by_source(
object, source='user.username')
"""
try:
if isinstance(obj, collections.Mapping):
if '.' in source:
for source in source.split('.'):
obj = obj.get(source)
else:
obj = obj.get(source)
else:
if '.' in source:
for source in source.split('.'):
obj = getattr(obj, source)
else:
obj = getattr(obj, source)
except AttributeError:
if not allow_blank_source:
raise
obj = None
return obj
def filter_list(obj):
"""
Filters a list by removing all the None value within the list.
"""
if isinstance(obj, (list, tuple)):
return [item for item in obj if item is not None]
return obj
| {
"content_hash": "9aaee13289e4db6cf8d65554dace189b",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 72,
"avg_line_length": 26.202380952380953,
"alnum_prop": 0.5856428895956384,
"repo_name": "localmed/pyserializer",
"id": "6149cc497f644e7a859391eab1a47820377017be",
"size": "2201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pyserializer/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "1211"
},
{
"name": "Python",
"bytes": "117007"
},
{
"name": "Shell",
"bytes": "896"
}
],
"symlink_target": ""
} |
/*! normalize.css v3.0.1 | MIT License | git.io/normalize */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
*/
/* line 9, ../sass/normalize.scss */
html {
font-family: sans-serif;
/* 1 */
-ms-text-size-adjust: 100%;
/* 2 */
-webkit-text-size-adjust: 100%;
/* 2 */
}
/**
* Remove default margin.
*/
/* line 19, ../sass/normalize.scss */
body {
margin: 0;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined for any HTML5 element in IE 8/9.
* Correct `block` display not defined for `details` or `summary` in IE 10/11 and Firefox.
* Correct `block` display not defined for `main` in IE 11.
*/
/* line 43, ../sass/normalize.scss */
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
/* line 55, ../sass/normalize.scss */
audio,
canvas,
progress,
video {
display: inline-block;
/* 1 */
vertical-align: baseline;
/* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
/* line 65, ../sass/normalize.scss */
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9/10.
* Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22.
*/
/* line 76, ../sass/normalize.scss */
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
/* line 87, ../sass/normalize.scss */
a {
background: transparent;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
/* line 96, ../sass/normalize.scss */
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9/10/11, Safari, and Chrome.
*/
/* line 107, ../sass/normalize.scss */
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
*/
/* line 116, ../sass/normalize.scss */
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari and Chrome.
*/
/* line 124, ../sass/normalize.scss */
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari, and Chrome.
*/
/* line 133, ../sass/normalize.scss */
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
/* line 142, ../sass/normalize.scss */
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
/* line 151, ../sass/normalize.scss */
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
/* line 160, ../sass/normalize.scss */
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
/* line 167, ../sass/normalize.scss */
sup {
top: -0.5em;
}
/* line 171, ../sass/normalize.scss */
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9/10.
*/
/* line 182, ../sass/normalize.scss */
img {
border: 0;
}
/**
* Correct overflow not hidden in IE 9/10/11.
*/
/* line 190, ../sass/normalize.scss */
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari.
*/
/* line 201, ../sass/normalize.scss */
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
/* line 209, ../sass/normalize.scss */
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
/* line 219, ../sass/normalize.scss */
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
/* line 230, ../sass/normalize.scss */
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
*/
/* line 254, ../sass/normalize.scss */
button,
input,
optgroup,
select,
textarea {
color: inherit;
/* 1 */
font: inherit;
/* 2 */
margin: 0;
/* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10/11.
*/
/* line 264, ../sass/normalize.scss */
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
* Correct `select` style inheritance in Firefox.
*/
/* line 276, ../sass/normalize.scss */
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
/* line 291, ../sass/normalize.scss */
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
/* 2 */
cursor: pointer;
/* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
/* line 301, ../sass/normalize.scss */
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
/* line 310, ../sass/normalize.scss */
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
/* line 320, ../sass/normalize.scss */
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
/* line 333, ../sass/normalize.scss */
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
/* line 345, ../sass/normalize.scss */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari and Chrome
* (include `-moz` to future-proof).
*/
/* line 355, ../sass/normalize.scss */
input[type="search"] {
-webkit-appearance: textfield;
/* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
/* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
/* line 369, ../sass/normalize.scss */
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
/* line 377, ../sass/normalize.scss */
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9/10/11.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
/* line 388, ../sass/normalize.scss */
legend {
border: 0;
/* 1 */
padding: 0;
/* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9/10/11.
*/
/* line 397, ../sass/normalize.scss */
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
/* line 406, ../sass/normalize.scss */
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
/* line 417, ../sass/normalize.scss */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* line 423, ../sass/normalize.scss */
td,
th {
padding: 0;
}
| {
"content_hash": "5d344de6955d8233eaed95015774f012",
"timestamp": "",
"source": "github",
"line_count": 435,
"max_line_length": 90,
"avg_line_length": 21.406896551724138,
"alnum_prop": 0.6083548109965635,
"repo_name": "Ely-S/ODEtoJS",
"id": "f33d5186683361134175ea274acb58c56d4447e0",
"size": "9312",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "css/normalize.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "676"
},
{
"name": "CSS",
"bytes": "544903"
},
{
"name": "HTML",
"bytes": "43181"
},
{
"name": "JavaScript",
"bytes": "38611"
},
{
"name": "Ruby",
"bytes": "839"
}
],
"symlink_target": ""
} |
using Moq;
using Peasy.Synchronous;
using Shouldly;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Peasy.Extensions;
using System;
namespace Peasy.Core.Tests.Extensions
{
public class ICommandExtensions
{
[Fact]
public async Task ValidateAsync_Supports_ICommand()
{
var doerOfThings = new Mock<IDoThings>();
var command = new CommandBaseTests.CommandStub(doerOfThings.Object) as ICommand;
var result = await command.ValidateAsync();
result.CanContinue.ShouldBeTrue();
}
[Fact]
public async Task ValidateAsync_Throws_Exception_When_ICommand_Does_Not_Implement_Expected_Interface()
{
var command = new Mock<ICommand>();
var ex = await Assert.ThrowsAsync<InvalidCastException>(() => command.Object.ValidateAsync());
ex.Message.ShouldBe("Supplied command does not implement ISupportCommandValidation interface.");
}
[Fact]
public async Task ValidateAsync_Supports_ICommand_Of_T()
{
var doerOfThings = new Mock<IDoThings>();
var command = new CommandBaseTestsOfT.CommandStub(doerOfThings.Object) as ICommand<string>;
var result = await command.ValidateAsync();
result.CanContinue.ShouldBeTrue();
}
[Fact]
public async Task ValidateAsync_Throws_Exception_When_ICommand_Of_T_Does_Not_Implement_Expected_Interface()
{
var command = new Mock<ICommand<string>>();
var ex = await Assert.ThrowsAsync<InvalidCastException>(() => command.Object.ValidateAsync());
ex.Message.ShouldBe("Supplied command does not implement ISupportCommandValidation interface.");
}
[Fact]
public void Validate_Supports_ISynchronousCommand()
{
var doerOfThings = new Mock<IDoThings>();
var command = new SynchronousCommandBaseTests.SynchronousCommandStub(doerOfThings.Object) as ISynchronousCommand;
var result = command.Validate();
result.CanContinue.ShouldBeTrue();
}
[Fact]
public void Validate_Throws_Exception_When_ISynchronousCommand_Does_Not_Implement_Expected_Interface()
{
var command = new Mock<ISynchronousCommand>();
var ex = Assert.Throws<InvalidCastException>(() => command.Object.Validate());
ex.Message.ShouldBe("Supplied command does not implement ISupportSynchronousCommandValidation interface.");
}
[Fact]
public void Validate_Supports_ISynchronousCommand_Of_T()
{
var doerOfThings = new Mock<IDoThings>();
var command = new SynchronousCommandBaseTestsOfT.SynchronousCommandStub(doerOfThings.Object) as ISynchronousCommand<string>;
var result = command.Validate();
result.CanContinue.ShouldBeTrue();
}
[Fact]
public void Validate_Throws_Exception_When_ISynchronousCommand_Of_T_Does_Not_Implement_Expected_Interface()
{
var command = new Mock<ISynchronousCommand<string>>();
var ex = Assert.Throws<InvalidCastException>(() => command.Object.Validate());
ex.Message.ShouldBe("Supplied command does not implement ISupportSynchronousCommandValidation interface.");
}
[Fact]
public async Task GetRulesAsync_Supports_ICommand()
{
var doerOfThings = new Mock<IDoThings>();
var rules = new IRule[] { new TrueRule(), new FalseRule1() };
var command = new CommandBaseTests.CommandStub(doerOfThings.Object, rules) as ICommand;
var results = await command.GetRulesAsync();
results.Count().ShouldBe(2);
results.First().ShouldBeOfType<TrueRule>();
results.Second().ShouldBeOfType<FalseRule1>();
}
[Fact]
public async Task GetRulesAsync_Throws_Exception_When_ICommand_Does_Not_Implement_Expected_Interface()
{
var command = new Mock<ICommand>();
var ex = await Assert.ThrowsAsync<InvalidCastException>(() => command.Object.GetRulesAsync());
ex.Message.ShouldBe("Supplied command does not implement IRulesContainer interface.");
}
[Fact]
public async Task GetRulesAsync_Supports_ICommand_Of_T()
{
var doerOfThings = new Mock<IDoThings>();
var rules = new IRule[] { new TrueRule(), new FalseRule1() };
var command = new CommandBaseTestsOfT.CommandStub(doerOfThings.Object, rules) as ICommand<string>;
var results = await command.GetRulesAsync();
results.Count().ShouldBe(2);
results.First().ShouldBeOfType<TrueRule>();
results.Second().ShouldBeOfType<FalseRule1>();
}
[Fact]
public async Task GetRulesAsync_Throws_Exception_When_ICommand_Of_T_Does_Not_Implement_Expected_Interface()
{
var command = new Mock<ICommand<string>>();
var ex = await Assert.ThrowsAsync<InvalidCastException>(() => command.Object.ValidateAsync());
ex.Message.ShouldBe("Supplied command does not implement ISupportCommandValidation interface.");
}
[Fact]
public void GetRules_Supports_ISynchronousCommand()
{
var doerOfThings = new Mock<IDoThings>();
var rules = new ISynchronousRule[] { new SynchronousTrueRule(), new SynchronousFalseRule1() };
var command = new SynchronousCommandBaseTests.SynchronousCommandStub(doerOfThings.Object, rules) as ISynchronousCommand;
var results = command.GetRules();
results.Count().ShouldBe(2);
results.First().ShouldBeOfType<SynchronousTrueRule>();
results.Second().ShouldBeOfType<SynchronousFalseRule1>();
}
[Fact]
public void GetRules_Throws_Exception_When_ISynchronousCommand_Does_Not_Implement_Expected_Interface()
{
var command = new Mock<ISynchronousCommand>();
var ex = Assert.Throws<InvalidCastException>(() => command.Object.Validate());
ex.Message.ShouldBe("Supplied command does not implement ISupportSynchronousCommandValidation interface.");
}
[Fact]
public void GetRules_Supports_ISynchronousCommand_Of_T()
{
var doerOfThings = new Mock<IDoThings>();
var rules = new ISynchronousRule[] { new SynchronousTrueRule(), new SynchronousFalseRule1() };
var command = new SynchronousCommandBaseTestsOfT.SynchronousCommandStub(doerOfThings.Object, rules) as ISynchronousCommand<string>;
var results = command.GetRules();
results.Count().ShouldBe(2);
results.First().ShouldBeOfType<SynchronousTrueRule>();
results.Second().ShouldBeOfType<SynchronousFalseRule1>();
}
[Fact]
public void GetRules_Throws_Exception_When_ISynchronousCommand_Of_T_Does_Not_Implement_Expected_Interface()
{
var command = new Mock<ISynchronousCommand<string>>();
var ex = Assert.Throws<InvalidCastException>(() => command.Object.Validate());
ex.Message.ShouldBe("Supplied command does not implement ISupportSynchronousCommandValidation interface.");
}
}
}
| {
"content_hash": "81c0563ccc764c7fbee9189c269aa1d4",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 143,
"avg_line_length": 41.6123595505618,
"alnum_prop": 0.6465505602808155,
"repo_name": "ahanusa/Peasy.NET",
"id": "e1b0cc687f61f7f03bd3058b36cde0001a1e267e",
"size": "7409",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Peasy.Tests/Extensions/ICommandExtensionTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "159076"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Sylius\Bundle\ApiBundle\Provider;
use Sylius\Bundle\ApiBundle\Context\UserContextInterface;
use Sylius\Component\Core\Model\AdminUserInterface;
use Sylius\Component\Core\Model\ShopUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/** @experimental */
final class PathPrefixProvider implements PathPrefixProviderInterface
{
public function __construct(
private UserContextInterface $userContext,
private string $apiRoute,
) {
}
public function getPathPrefix(string $path): ?string
{
if (!str_contains($path, $this->apiRoute)) {
return null;
}
$pathElements = array_values(array_filter(explode('/', str_replace($this->apiRoute, '', $path))));
if ($pathElements[0] === PathPrefixes::SHOP_PREFIX) {
return PathPrefixes::SHOP_PREFIX;
}
if ($pathElements[0] === PathPrefixes::ADMIN_PREFIX) {
return PathPrefixes::ADMIN_PREFIX;
}
return null;
}
public function getCurrentPrefix(): ?string
{
/** @var UserInterface|null $user */
$user = $this->userContext->getUser();
if ($user === null || $user instanceof ShopUserInterface) {
return PathPrefixes::SHOP_PREFIX;
}
if ($user instanceof AdminUserInterface) {
return PathPrefixes::ADMIN_PREFIX;
}
return null;
}
}
| {
"content_hash": "d9a4325bb2cf0ad72e8a45106452d879",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 106,
"avg_line_length": 25.649122807017545,
"alnum_prop": 0.6333789329685362,
"repo_name": "Sylius/Sylius",
"id": "3fd2e9d783d291a6d0f9690f2f9f5350e9b8fca6",
"size": "1673",
"binary": false,
"copies": "2",
"ref": "refs/heads/1.13",
"path": "src/Sylius/Bundle/ApiBundle/Provider/PathPrefixProvider.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "674"
},
{
"name": "Gherkin",
"bytes": "1269548"
},
{
"name": "JavaScript",
"bytes": "102771"
},
{
"name": "Makefile",
"bytes": "1478"
},
{
"name": "PHP",
"bytes": "8145147"
},
{
"name": "SCSS",
"bytes": "53880"
},
{
"name": "Shell",
"bytes": "11411"
},
{
"name": "Twig",
"bytes": "446530"
}
],
"symlink_target": ""
} |
.. SPDX-License-Identifier: BSD-3-Clause
Copyright (c) 2021 NVIDIA Corporation & Affiliates
Overview of GPU Drivers
=======================
General-Purpose computing on Graphics Processing Unit (GPGPU)
is the use of GPU to perform parallel computation.
.. include:: overview_feature_table.txt
| {
"content_hash": "01ae0daf9c98e775b6154c6f188fd6cc",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 61,
"avg_line_length": 29.9,
"alnum_prop": 0.7190635451505016,
"repo_name": "john-mcnamara-intel/dpdk",
"id": "48303488185549c2e02768a580bf3cd9bf62a7d8",
"size": "299",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "doc/guides/gpus/overview.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "1623"
},
{
"name": "C",
"bytes": "39269990"
},
{
"name": "C++",
"bytes": "860345"
},
{
"name": "Makefile",
"bytes": "342834"
},
{
"name": "Meson",
"bytes": "144875"
},
{
"name": "Objective-C",
"bytes": "224248"
},
{
"name": "Python",
"bytes": "115929"
},
{
"name": "Shell",
"bytes": "77250"
},
{
"name": "SmPL",
"bytes": "2074"
}
],
"symlink_target": ""
} |
#include "security_manager.h"
#include <string.h>
#include "security_dispatcher.h"
#include "peer_database.h"
#include "ble_conn_state.h"
#define MAX_REGISTRANTS 3 /**< The number of user that can register with the module. */
#define MODULE_INITIALIZED (m_sm.n_registrants > 0) /**< Expression which is true when the module is initialized. */
/**@brief Macro for verifying that the module is initialized. It will cause the function to return
* @ref NRF_ERROR_INVALID_STATE if not.
*/
#define VERIFY_MODULE_INITIALIZED() \
do \
{ \
if (!MODULE_INITIALIZED) \
{ \
return NRF_ERROR_INVALID_STATE; \
} \
} while(0)
/**@brief Macro for verifying that the module is initialized. It will cause the function to return
* if not.
*/
#define VERIFY_MODULE_INITIALIZED_VOID()\
do \
{ \
if (!MODULE_INITIALIZED) \
{ \
return; \
} \
} while(0)
/**@brief Macro for verifying that the module is initialized. It will cause the function to return
* if not.
*
* @param[in] param The variable to check if is NULL.
*/
#define VERIFY_PARAM_NOT_NULL(param) \
do \
{ \
if (param == NULL) \
{ \
return NRF_ERROR_NULL; \
} \
} while(0)
typedef struct
{
sm_evt_handler_t evt_handlers[MAX_REGISTRANTS];
uint8_t n_registrants;
ble_conn_state_user_flag_id_t flag_id_link_secure_pending_busy;
ble_conn_state_user_flag_id_t flag_id_link_secure_pending_flash_full;
ble_conn_state_user_flag_id_t flag_id_link_secure_force_repairing;
ble_conn_state_user_flag_id_t flag_id_link_secure_null_params;
ble_conn_state_user_flag_id_t flag_id_params_reply_pending_busy;
ble_conn_state_user_flag_id_t flag_id_params_reply_pending_flash_full;
bool pdb_evt_handler_registered;
bool sec_params_valid;
ble_gap_sec_params_t sec_params;
} sm_t;
static sm_t m_sm = {.flag_id_link_secure_pending_busy = BLE_CONN_STATE_USER_FLAG_INVALID,
.flag_id_link_secure_pending_flash_full = BLE_CONN_STATE_USER_FLAG_INVALID,
.flag_id_link_secure_force_repairing = BLE_CONN_STATE_USER_FLAG_INVALID,
.flag_id_link_secure_null_params = BLE_CONN_STATE_USER_FLAG_INVALID,
.flag_id_params_reply_pending_busy = BLE_CONN_STATE_USER_FLAG_INVALID,
.flag_id_params_reply_pending_flash_full = BLE_CONN_STATE_USER_FLAG_INVALID};
static void evt_send(sm_evt_t * p_event)
{
for (int i = 0; i < m_sm.n_registrants; i++)
{
m_sm.evt_handlers[i](p_event);
}
}
static void flags_set_from_err_code(uint16_t conn_handle, ret_code_t err_code, bool params_reply)
{
bool flag_value_flash_full = false;
bool flag_value_busy = false;
if ( (err_code == NRF_ERROR_NO_MEM)
|| (err_code == NRF_ERROR_BUSY)
|| (err_code == NRF_SUCCESS))
{
if ((err_code == NRF_ERROR_NO_MEM))
{
flag_value_flash_full = true;
flag_value_busy = false;
}
else if (err_code == NRF_ERROR_BUSY)
{
flag_value_busy = true;
flag_value_flash_full = false;
}
else if (err_code == NRF_SUCCESS)
{
flag_value_busy = false;
flag_value_flash_full = false;
}
if (params_reply)
{
ble_conn_state_user_flag_set(conn_handle,
m_sm.flag_id_params_reply_pending_flash_full,
flag_value_flash_full);
ble_conn_state_user_flag_set(conn_handle,
m_sm.flag_id_params_reply_pending_busy,
flag_value_busy);
ble_conn_state_user_flag_set(conn_handle,
m_sm.flag_id_link_secure_pending_flash_full,
false);
ble_conn_state_user_flag_set(conn_handle,
m_sm.flag_id_link_secure_pending_busy,
false);
}
else
{
ble_conn_state_user_flag_set(conn_handle,
m_sm.flag_id_link_secure_pending_flash_full,
flag_value_flash_full);
ble_conn_state_user_flag_set(conn_handle,
m_sm.flag_id_link_secure_pending_busy,
flag_value_busy);
}
}
}
static void events_send_from_err_code(uint16_t conn_handle, ret_code_t err_code)
{
if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_BUSY))
{
sm_evt_t evt =
{
.conn_handle = conn_handle,
.params = {.error_unexpected = {
.error = err_code
}}
};
if (err_code == NRF_ERROR_TIMEOUT)
{
evt.evt_id = SM_EVT_ERROR_SMP_TIMEOUT;
}
else if (err_code == NRF_ERROR_NO_MEM)
{
evt.evt_id = SM_EVT_ERROR_NO_MEM;
}
else
{
evt.evt_id = SM_EVT_ERROR_UNEXPECTED;
}
evt_send(&evt);
}
}
static ret_code_t link_secure(uint16_t conn_handle, bool null_params, bool force_repairing, bool send_events)
{
ret_code_t err_code;
if (!null_params && !m_sm.sec_params_valid)
{
return NRF_ERROR_NOT_FOUND;
}
if(null_params)
{
err_code = smd_link_secure(conn_handle, NULL, force_repairing);
}
else
{
err_code = smd_link_secure(conn_handle, &m_sm.sec_params, force_repairing);
}
flags_set_from_err_code(conn_handle, err_code, false);
if (send_events)
{
events_send_from_err_code(conn_handle, err_code);
}
switch (err_code)
{
case NRF_ERROR_BUSY:
ble_conn_state_user_flag_set(conn_handle, m_sm.flag_id_link_secure_null_params, null_params);
ble_conn_state_user_flag_set(conn_handle, m_sm.flag_id_link_secure_force_repairing, force_repairing);
err_code = NRF_SUCCESS;
break;
case NRF_ERROR_NO_MEM:
ble_conn_state_user_flag_set(conn_handle, m_sm.flag_id_link_secure_null_params, null_params);
ble_conn_state_user_flag_set(conn_handle, m_sm.flag_id_link_secure_force_repairing, force_repairing);
break;
case NRF_SUCCESS:
case NRF_ERROR_TIMEOUT:
case BLE_ERROR_INVALID_CONN_HANDLE:
case NRF_ERROR_INVALID_STATE:
/* No action */
break;
default:
err_code = NRF_ERROR_INTERNAL;
break;
}
return err_code;
}
static void smd_params_reply_perform(uint16_t conn_handle)
{
ret_code_t err_code;
if (m_sm.sec_params_valid)
{
err_code = smd_params_reply(conn_handle, &m_sm.sec_params);
}
else
{
err_code = smd_params_reply(conn_handle, NULL);
}
flags_set_from_err_code(conn_handle, err_code, true);
events_send_from_err_code(conn_handle, err_code);
}
static void smd_evt_handler(smd_evt_t const * p_event)
{
switch(p_event->evt_id)
{
case SMD_EVT_PARAMS_REQ:
smd_params_reply_perform(p_event->conn_handle);
break;
case SMD_EVT_SLAVE_SECURITY_REQ:
{
bool null_params = false;
if (!m_sm.sec_params_valid)
{
null_params = true;
}
else if ((bool)m_sm.sec_params.bond < (bool)p_event->params.slave_security_req.bond)
{
null_params = true;
}
else if ((bool)m_sm.sec_params.mitm < (bool)p_event->params.slave_security_req.mitm)
{
null_params = true;
}
link_secure(p_event->conn_handle, null_params, false, true);
}
case SMD_EVT_PAIRING_SUCCESS:
case SMD_EVT_PAIRING_FAIL:
case SMD_EVT_LINK_ENCRYPTION_UPDATE:
case SMD_EVT_LINK_ENCRYPTION_FAILED:
case SMD_EVT_BONDING_INFO_STORED:
case SMD_EVT_ERROR_BONDING_INFO:
case SMD_EVT_ERROR_UNEXPECTED:
case SMD_EVT_SEC_PROCEDURE_START:
{
sm_evt_t evt =
{
.evt_id = (sm_evt_id_t)p_event->evt_id,
.conn_handle = p_event->conn_handle,
.params = p_event->params,
};
evt_send(&evt);
}
break;
}
}
static void link_secure_pending_process(ble_conn_state_user_flag_id_t flag_id)
{
sdk_mapped_flags_t flag_collection = ble_conn_state_user_flag_collection(flag_id);
if (sdk_mapped_flags_any_set(flag_collection))
{
sdk_mapped_flags_key_list_t conn_handle_list = ble_conn_state_conn_handles();
for (int i = 0; i < conn_handle_list.len; i++)
{
bool pending = ble_conn_state_user_flag_get(conn_handle_list.flag_keys[i], flag_id);
if (pending)
{
bool force_repairing = ble_conn_state_user_flag_get(conn_handle_list.flag_keys[i], m_sm.flag_id_link_secure_force_repairing);
bool null_params = ble_conn_state_user_flag_get(conn_handle_list.flag_keys[i], m_sm.flag_id_link_secure_null_params);
link_secure(conn_handle_list.flag_keys[i], null_params, force_repairing, true);
}
}
}
}
static void params_reply_pending_process(ble_conn_state_user_flag_id_t flag_id)
{
sdk_mapped_flags_t flag_collection = ble_conn_state_user_flag_collection(flag_id);
if (sdk_mapped_flags_any_set(flag_collection))
{
sdk_mapped_flags_key_list_t conn_handle_list = ble_conn_state_conn_handles();
for (int i = 0; i < conn_handle_list.len; i++)
{
bool pending = ble_conn_state_user_flag_get(conn_handle_list.flag_keys[i], flag_id);
if (pending)
{
smd_params_reply_perform(conn_handle_list.flag_keys[i]);
}
}
}
}
static void pdb_evt_handler(pdb_evt_t const * p_event)
{
switch (p_event->evt_id)
{
case PDB_EVT_COMPRESSED:
params_reply_pending_process(m_sm.flag_id_params_reply_pending_flash_full);
link_secure_pending_process(m_sm.flag_id_link_secure_pending_flash_full);
/* fallthrough */
case PDB_EVT_WRITE_BUF_STORED:
case PDB_EVT_RAW_STORED:
case PDB_EVT_RAW_STORE_FAILED:
case PDB_EVT_CLEARED:
case PDB_EVT_CLEAR_FAILED:
params_reply_pending_process(m_sm.flag_id_params_reply_pending_busy);
link_secure_pending_process(m_sm.flag_id_link_secure_pending_busy);
break;
case PDB_EVT_ERROR_NO_MEM:
case PDB_EVT_ERROR_UNEXPECTED:
break;
}
}
/**@brief Macro for initializing a BLE Connection State user flag.
*
* @param[out] flag_id The flag to initialize.
*/
#define FLAG_ID_INIT(flag_id) \
do \
{ \
if ((flag_id) == BLE_CONN_STATE_USER_FLAG_INVALID) \
{ \
(flag_id) = ble_conn_state_user_flag_acquire(); \
if ((flag_id) == BLE_CONN_STATE_USER_FLAG_INVALID)\
{ \
return NRF_ERROR_INTERNAL; \
} \
} \
} while(0)
ret_code_t sm_register(sm_evt_handler_t evt_handler)
{
VERIFY_PARAM_NOT_NULL(evt_handler);
ret_code_t err_code = NRF_SUCCESS;
if (!MODULE_INITIALIZED)
{
FLAG_ID_INIT(m_sm.flag_id_link_secure_pending_busy);
FLAG_ID_INIT(m_sm.flag_id_link_secure_pending_flash_full);
FLAG_ID_INIT(m_sm.flag_id_link_secure_force_repairing);
FLAG_ID_INIT(m_sm.flag_id_link_secure_null_params);
FLAG_ID_INIT(m_sm.flag_id_params_reply_pending_busy);
FLAG_ID_INIT(m_sm.flag_id_params_reply_pending_flash_full);
if (!m_sm.pdb_evt_handler_registered)
{
err_code = pdb_register(pdb_evt_handler);
if (err_code != NRF_SUCCESS)
{
return NRF_ERROR_INTERNAL;
}
m_sm.pdb_evt_handler_registered = true;
}
err_code = smd_register(smd_evt_handler);
if (err_code != NRF_SUCCESS)
{
return NRF_ERROR_INTERNAL;
}
}
if (err_code == NRF_SUCCESS)
{
if ((m_sm.n_registrants < MAX_REGISTRANTS))
{
m_sm.evt_handlers[m_sm.n_registrants++] = evt_handler;
}
else
{
err_code = NRF_ERROR_NO_MEM;
}
}
return err_code;
}
void sm_ble_evt_handler(ble_evt_t * p_ble_evt)
{
VERIFY_MODULE_INITIALIZED_VOID();
smd_ble_evt_handler(p_ble_evt);
link_secure_pending_process(m_sm.flag_id_link_secure_pending_busy);
}
static bool sec_params_verify(ble_gap_sec_params_t * p_sec_params)
{
// NULL check.
if (p_sec_params == NULL)
{
return false;
}
// OOB not allowed unless MITM.
if (!p_sec_params->mitm && p_sec_params->oob)
{
return false;
}
// IO Capabilities must be one of the valid values from @ref BLE_GAP_IO_CAPS.
if (p_sec_params->io_caps > BLE_GAP_IO_CAPS_KEYBOARD_DISPLAY)
{
return false;
}
// Must have either IO capabilities or OOB if MITM.
if (p_sec_params->mitm && (p_sec_params->io_caps == BLE_GAP_IO_CAPS_NONE) && !p_sec_params->oob)
{
return false;
}
// Minimum key size cannot be larger than maximum key size.
if (p_sec_params->min_key_size > p_sec_params->max_key_size)
{
return false;
}
// Key size cannot be below 7 bytes.
if (p_sec_params->min_key_size < 7)
{
return false;
}
// Key size cannot be above 16 bytes.
if (p_sec_params->max_key_size > 16)
{
return false;
}
// Signing is not supported.
if (p_sec_params->kdist_periph.sign || p_sec_params->kdist_central.sign)
{
return false;
}
// If bonding is not enabled, no keys can be distributed.
if (!p_sec_params->bond && ( p_sec_params->kdist_periph.enc
|| p_sec_params->kdist_periph.id
|| p_sec_params->kdist_central.enc
|| p_sec_params->kdist_central.id))
{
return false;
}
// If bonding is enabled, one or more keys must be distributed.
if ( p_sec_params->bond
&& !p_sec_params->kdist_periph.enc
&& !p_sec_params->kdist_periph.id
&& !p_sec_params->kdist_central.enc
&& !p_sec_params->kdist_central.id)
{
return false;
}
return true;
}
ret_code_t sm_sec_params_set(ble_gap_sec_params_t * p_sec_params)
{
VERIFY_MODULE_INITIALIZED();
if (p_sec_params == NULL)
{
m_sm.sec_params_valid = false;
return NRF_SUCCESS;
}
else if (sec_params_verify(p_sec_params))
{
m_sm.sec_params = *p_sec_params;
m_sm.sec_params_valid = true;
return NRF_SUCCESS;
}
else
{
return NRF_ERROR_INVALID_PARAM;
}
}
ret_code_t sm_sec_params_reply(uint16_t conn_handle, ble_gap_sec_params_t * p_sec_params)
{
VERIFY_MODULE_INITIALIZED();
return NRF_SUCCESS;
}
ret_code_t sm_link_secure(uint16_t conn_handle, bool force_repairing)
{
VERIFY_MODULE_INITIALIZED();
ret_code_t err_code = link_secure(conn_handle, false, force_repairing, false);
return err_code;
}
| {
"content_hash": "5ea6baacac29648bd81912b9adbc91bf",
"timestamp": "",
"source": "github",
"line_count": 531,
"max_line_length": 141,
"avg_line_length": 32.07909604519774,
"alnum_prop": 0.5086297992250792,
"repo_name": "Jewelbots/nordic-flash-data-storage",
"id": "b12628e8863dfc7fa6688d27de45a886aa6edbcf",
"size": "17414",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "nrf51_sdk/components/ble/peer_manager/security_manager.c",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "116634"
},
{
"name": "C",
"bytes": "11159656"
},
{
"name": "C++",
"bytes": "803989"
},
{
"name": "Shell",
"bytes": "348"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/caolan/async)
Async is a utility module which provides straight-forward, powerful functions
for working with asynchronous JavaScript. Although originally designed for
use with [Node.js](http://nodejs.org) and installable via `npm install async`,
it can also be used directly in the browser.
Async is also installable via:
- [bower](http://bower.io/): `bower install async`
- [component](https://github.com/component/component): `component install
caolan/async`
- [jam](http://jamjs.org/): `jam install async`
- [spm](http://spmjs.io/): `spm install async`
Async provides around 20 functions that include the usual 'functional'
suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns
for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these
functions assume you follow the Node.js convention of providing a single
callback as the last argument of your `async` function.
## Quick Examples
```javascript
async.map(['file1','file2','file3'], fs.stat, function(err, results){
// results is now an array of stats for each file
});
async.filter(['file1','file2','file3'], fs.exists, function(results){
// results now equals an array of the existing files
});
async.parallel([
function(){ ... },
function(){ ... }
], callback);
async.series([
function(){ ... },
function(){ ... }
]);
```
There are many more functions available so take a look at the docs below for a
full list. This module aims to be comprehensive, so if you feel anything is
missing please create a GitHub issue for it.
## Common Pitfalls
### Binding a context to an iterator
This section is really about `bind`, not about `async`. If you are wondering how to
make `async` execute your iterators in a given context, or are confused as to why
a method of another library isn't working as an iterator, study this example:
```js
// Here is a simple object with an (unnecessarily roundabout) squaring method
var AsyncSquaringLibrary = {
squareExponent: 2,
square: function(number, callback){
var result = Math.pow(number, this.squareExponent);
setTimeout(function(){
callback(null, result);
}, 200);
}
};
async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){
// result is [NaN, NaN, NaN]
// This fails because the `this.squareExponent` expression in the square
// function is not evaluated in the context of AsyncSquaringLibrary, and is
// therefore undefined.
});
async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){
// result is [1, 4, 9]
// With the help of bind we can attach a context to the iterator before
// passing it to async. Now the square function will be executed in its
// 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`
// will be as expected.
});
```
## Download
The source is available for download from
[GitHub](http://github.com/caolan/async).
Alternatively, you can install using Node Package Manager (`npm`):
npm install async
__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed
## In the Browser
So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5.
Usage:
```html
<script type="text/javascript" src="async.js"></script>
<script type="text/javascript">
async.map(data, asyncProcess, function(err, results){
alert(results);
});
</script>
```
## Documentation
### Collections
* [`each`](#each)
* [`eachSeries`](#eachSeries)
* [`eachLimit`](#eachLimit)
* [`map`](#map)
* [`mapSeries`](#mapSeries)
* [`mapLimit`](#mapLimit)
* [`filter`](#filter)
* [`filterSeries`](#filterSeries)
* [`reject`](#reject)
* [`rejectSeries`](#rejectSeries)
* [`reduce`](#reduce)
* [`reduceRight`](#reduceRight)
* [`detect`](#detect)
* [`detectSeries`](#detectSeries)
* [`sortBy`](#sortBy)
* [`some`](#some)
* [`every`](#every)
* [`concat`](#concat)
* [`concatSeries`](#concatSeries)
### Control Flow
* [`series`](#seriestasks-callback)
* [`parallel`](#parallel)
* [`parallelLimit`](#parallellimittasks-limit-callback)
* [`whilst`](#whilst)
* [`doWhilst`](#doWhilst)
* [`until`](#until)
* [`doUntil`](#doUntil)
* [`forever`](#forever)
* [`waterfall`](#waterfall)
* [`compose`](#compose)
* [`seq`](#seq)
* [`applyEach`](#applyEach)
* [`applyEachSeries`](#applyEachSeries)
* [`queue`](#queue)
* [`priorityQueue`](#priorityQueue)
* [`cargo`](#cargo)
* [`auto`](#auto)
* [`retry`](#retry)
* [`iterator`](#iterator)
* [`apply`](#apply)
* [`nextTick`](#nextTick)
* [`times`](#times)
* [`timesSeries`](#timesSeries)
### Utils
* [`memoize`](#memoize)
* [`unmemoize`](#unmemoize)
* [`log`](#log)
* [`dir`](#dir)
* [`noConflict`](#noConflict)
## Collections
<a name="forEach" />
<a name="each" />
### each(arr, iterator, callback)
Applies the function `iterator` to each item in `arr`, in parallel.
The `iterator` is called with an item from the list, and a callback for when it
has finished. If the `iterator` passes an error to its `callback`, the main
`callback` (for the `each` function) is immediately called with the error.
Note, that since this function applies `iterator` to each item in parallel,
there is no guarantee that the iterator functions will complete in order.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err)` which must be called once it has
completed. If no error has occurred, the `callback` should be run without
arguments or with an explicit `null` argument.
* `callback(err)` - A callback which is called when all `iterator` functions
have finished, or an error occurs.
__Examples__
```js
// assuming openFiles is an array of file names and saveFile is a function
// to save the modified contents of that file:
async.each(openFiles, saveFile, function(err){
// if any of the saves produced an error, err would equal that error
});
```
```js
// assuming openFiles is an array of file names
async.each(openFiles, function(file, callback) {
// Perform operation on file here.
console.log('Processing file ' + file);
if( file.length > 32 ) {
console.log('This file name is too long');
callback('File name too long');
} else {
// Do work to process file here
console.log('File processed');
callback();
}
}, function(err){
// if any of the file processing produced an error, err would equal that error
if( err ) {
// One of the iterations produced an error.
// All processing will now stop.
console.log('A file failed to process');
} else {
console.log('All files have been processed successfully');
}
});
```
---------------------------------------
<a name="forEachSeries" />
<a name="eachSeries" />
### eachSeries(arr, iterator, callback)
The same as [`each`](#each), only `iterator` is applied to each item in `arr` in
series. The next `iterator` is only called once the current one has completed.
This means the `iterator` functions will complete in order.
---------------------------------------
<a name="forEachLimit" />
<a name="eachLimit" />
### eachLimit(arr, limit, iterator, callback)
The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously
running at any time.
Note that the items in `arr` are not processed in batches, so there is no guarantee that
the first `limit` `iterator` functions will complete before any others are started.
__Arguments__
* `arr` - An array to iterate over.
* `limit` - The maximum number of `iterator`s to run at any time.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err)` which must be called once it has
completed. If no error has occurred, the callback should be run without
arguments or with an explicit `null` argument.
* `callback(err)` - A callback which is called when all `iterator` functions
have finished, or an error occurs.
__Example__
```js
// Assume documents is an array of JSON objects and requestApi is a
// function that interacts with a rate-limited REST api.
async.eachLimit(documents, 20, requestApi, function(err){
// if any of the saves produced an error, err would equal that error
});
```
---------------------------------------
<a name="map" />
### map(arr, iterator, callback)
Produces a new array of values by mapping each value in `arr` through
the `iterator` function. The `iterator` is called with an item from `arr` and a
callback for when it has finished processing. Each of these callback takes 2 arguments:
an `error`, and the transformed item from `arr`. If `iterator` passes an error to his
callback, the main `callback` (for the `map` function) is immediately called with the error.
Note, that since this function applies the `iterator` to each item in parallel,
there is no guarantee that the `iterator` functions will complete in order.
However, the results array will be in the same order as the original `arr`.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err, transformed)` which must be called once
it has completed with an error (which can be `null`) and a transformed item.
* `callback(err, results)` - A callback which is called when all `iterator`
functions have finished, or an error occurs. Results is an array of the
transformed items from the `arr`.
__Example__
```js
async.map(['file1','file2','file3'], fs.stat, function(err, results){
// results is now an array of stats for each file
});
```
---------------------------------------
<a name="mapSeries" />
### mapSeries(arr, iterator, callback)
The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in
series. The next `iterator` is only called once the current one has completed.
The results array will be in the same order as the original.
---------------------------------------
<a name="mapLimit" />
### mapLimit(arr, limit, iterator, callback)
The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously
running at any time.
Note that the items are not processed in batches, so there is no guarantee that
the first `limit` `iterator` functions will complete before any others are started.
__Arguments__
* `arr` - An array to iterate over.
* `limit` - The maximum number of `iterator`s to run at any time.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err, transformed)` which must be called once
it has completed with an error (which can be `null`) and a transformed item.
* `callback(err, results)` - A callback which is called when all `iterator`
calls have finished, or an error occurs. The result is an array of the
transformed items from the original `arr`.
__Example__
```js
async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){
// results is now an array of stats for each file
});
```
---------------------------------------
<a name="select" />
<a name="filter" />
### filter(arr, iterator, callback)
__Alias:__ `select`
Returns a new array of all the values in `arr` which pass an async truth test.
_The callback for each `iterator` call only accepts a single argument of `true` or
`false`; it does not accept an error argument first!_ This is in-line with the
way node libraries work with truth tests like `fs.exists`. This operation is
performed in parallel, but the results array will be in the same order as the
original.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
The `iterator` is passed a `callback(truthValue)`, which must be called with a
boolean argument once it has completed.
* `callback(results)` - A callback which is called after all the `iterator`
functions have finished.
__Example__
```js
async.filter(['file1','file2','file3'], fs.exists, function(results){
// results now equals an array of the existing files
});
```
---------------------------------------
<a name="selectSeries" />
<a name="filterSeries" />
### filterSeries(arr, iterator, callback)
__Alias:__ `selectSeries`
The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in
series. The next `iterator` is only called once the current one has completed.
The results array will be in the same order as the original.
---------------------------------------
<a name="reject" />
### reject(arr, iterator, callback)
The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
---------------------------------------
<a name="rejectSeries" />
### rejectSeries(arr, iterator, callback)
The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr`
in series.
---------------------------------------
<a name="reduce" />
### reduce(arr, memo, iterator, callback)
__Aliases:__ `inject`, `foldl`
Reduces `arr` into a single value using an async `iterator` to return
each successive step. `memo` is the initial state of the reduction.
This function only operates in series.
For performance reasons, it may make sense to split a call to this function into
a parallel map, and then use the normal `Array.prototype.reduce` on the results.
This function is for situations where each step in the reduction needs to be async;
if you can get the data before reducing it, then it's probably a good idea to do so.
__Arguments__
* `arr` - An array to iterate over.
* `memo` - The initial state of the reduction.
* `iterator(memo, item, callback)` - A function applied to each item in the
array to produce the next step in the reduction. The `iterator` is passed a
`callback(err, reduction)` which accepts an optional error as its first
argument, and the state of the reduction as the second. If an error is
passed to the callback, the reduction is stopped and the main `callback` is
immediately called with the error.
* `callback(err, result)` - A callback which is called after all the `iterator`
functions have finished. Result is the reduced value.
__Example__
```js
async.reduce([1,2,3], 0, function(memo, item, callback){
// pointless async:
process.nextTick(function(){
callback(null, memo + item)
});
}, function(err, result){
// result is now equal to the last value of memo, which is 6
});
```
---------------------------------------
<a name="reduceRight" />
### reduceRight(arr, memo, iterator, callback)
__Alias:__ `foldr`
Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
---------------------------------------
<a name="detect" />
### detect(arr, iterator, callback)
Returns the first value in `arr` that passes an async truth test. The
`iterator` is applied in parallel, meaning the first iterator to return `true` will
fire the detect `callback` with that result. That means the result might not be
the first item in the original `arr` (in terms of order) that passes the test.
If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
The iterator is passed a `callback(truthValue)` which must be called with a
boolean argument once it has completed.
* `callback(result)` - A callback which is called as soon as any iterator returns
`true`, or after all the `iterator` functions have finished. Result will be
the first item in the array that passes the truth test (iterator) or the
value `undefined` if none passed.
__Example__
```js
async.detect(['file1','file2','file3'], fs.exists, function(result){
// result now equals the first file in the list that exists
});
```
---------------------------------------
<a name="detectSeries" />
### detectSeries(arr, iterator, callback)
The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr`
in series. This means the result is always the first in the original `arr` (in
terms of array order) that passes the truth test.
---------------------------------------
<a name="sortBy" />
### sortBy(arr, iterator, callback)
Sorts a list by the results of running each `arr` value through an async `iterator`.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err, sortValue)` which must be called once it
has completed with an error (which can be `null`) and a value to use as the sort
criteria.
* `callback(err, results)` - A callback which is called after all the `iterator`
functions have finished, or an error occurs. Results is the items from
the original `arr` sorted by the values returned by the `iterator` calls.
__Example__
```js
async.sortBy(['file1','file2','file3'], function(file, callback){
fs.stat(file, function(err, stats){
callback(err, stats.mtime);
});
}, function(err, results){
// results is now the original array of files sorted by
// modified date
});
```
__Sort Order__
By modifying the callback parameter the sorting order can be influenced:
```js
//ascending order
async.sortBy([1,9,3,5], function(x, callback){
callback(null, x);
}, function(err,result){
//result callback
} );
//descending order
async.sortBy([1,9,3,5], function(x, callback){
callback(null, x*-1); //<- x*-1 instead of x, turns the order around
}, function(err,result){
//result callback
} );
```
---------------------------------------
<a name="some" />
### some(arr, iterator, callback)
__Alias:__ `any`
Returns `true` if at least one element in the `arr` satisfies an async test.
_The callback for each iterator call only accepts a single argument of `true` or
`false`; it does not accept an error argument first!_ This is in-line with the
way node libraries work with truth tests like `fs.exists`. Once any iterator
call returns `true`, the main `callback` is immediately called.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A truth test to apply to each item in the array
in parallel. The iterator is passed a callback(truthValue) which must be
called with a boolean argument once it has completed.
* `callback(result)` - A callback which is called as soon as any iterator returns
`true`, or after all the iterator functions have finished. Result will be
either `true` or `false` depending on the values of the async tests.
__Example__
```js
async.some(['file1','file2','file3'], fs.exists, function(result){
// if result is true then at least one of the files exists
});
```
---------------------------------------
<a name="every" />
### every(arr, iterator, callback)
__Alias:__ `all`
Returns `true` if every element in `arr` satisfies an async test.
_The callback for each `iterator` call only accepts a single argument of `true` or
`false`; it does not accept an error argument first!_ This is in-line with the
way node libraries work with truth tests like `fs.exists`.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A truth test to apply to each item in the array
in parallel. The iterator is passed a callback(truthValue) which must be
called with a boolean argument once it has completed.
* `callback(result)` - A callback which is called after all the `iterator`
functions have finished. Result will be either `true` or `false` depending on
the values of the async tests.
__Example__
```js
async.every(['file1','file2','file3'], fs.exists, function(result){
// if result is true then every file exists
});
```
---------------------------------------
<a name="concat" />
### concat(arr, iterator, callback)
Applies `iterator` to each item in `arr`, concatenating the results. Returns the
concatenated list. The `iterator`s are called in parallel, and the results are
concatenated as they return. There is no guarantee that the results array will
be returned in the original order of `arr` passed to the `iterator` function.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err, results)` which must be called once it
has completed with an error (which can be `null`) and an array of results.
* `callback(err, results)` - A callback which is called after all the `iterator`
functions have finished, or an error occurs. Results is an array containing
the concatenated results of the `iterator` function.
__Example__
```js
async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
// files is now a list of filenames that exist in the 3 directories
});
```
---------------------------------------
<a name="concatSeries" />
### concatSeries(arr, iterator, callback)
Same as [`concat`](#concat), but executes in series instead of parallel.
## Control Flow
<a name="series" />
### series(tasks, [callback])
Run the functions in the `tasks` array in series, each one running once the previous
function has completed. If any functions in the series pass an error to its
callback, no more functions are run, and `callback` is immediately called with the value of the error.
Otherwise, `callback` receives an array of results when `tasks` have completed.
It is also possible to use an object instead of an array. Each property will be
run as a function, and the results will be passed to the final `callback` as an object
instead of an array. This can be a more readable way of handling results from
[`series`](#series).
**Note** that while many implementations preserve the order of object properties, the
[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
explicitly states that
> The mechanics and order of enumerating the properties is not specified.
So if you rely on the order in which your series of functions are executed, and want
this to work on all platforms, consider using an array.
__Arguments__
* `tasks` - An array or object containing functions to run, each function is passed
a `callback(err, result)` it must call on completion with an error `err` (which can
be `null`) and an optional `result` value.
* `callback(err, results)` - An optional callback to run once all the functions
have completed. This function gets a results array (or object) containing all
the result arguments passed to the `task` callbacks.
__Example__
```js
async.series([
function(callback){
// do some stuff ...
callback(null, 'one');
},
function(callback){
// do some more stuff ...
callback(null, 'two');
}
],
// optional callback
function(err, results){
// results is now equal to ['one', 'two']
});
// an example using an object instead of an array
async.series({
one: function(callback){
setTimeout(function(){
callback(null, 1);
}, 200);
},
two: function(callback){
setTimeout(function(){
callback(null, 2);
}, 100);
}
},
function(err, results) {
// results is now equal to: {one: 1, two: 2}
});
```
---------------------------------------
<a name="parallel" />
### parallel(tasks, [callback])
Run the `tasks` array of functions in parallel, without waiting until the previous
function has completed. If any of the functions pass an error to its
callback, the main `callback` is immediately called with the value of the error.
Once the `tasks` have completed, the results are passed to the final `callback` as an
array.
It is also possible to use an object instead of an array. Each property will be
run as a function and the results will be passed to the final `callback` as an object
instead of an array. This can be a more readable way of handling results from
[`parallel`](#parallel).
__Arguments__
* `tasks` - An array or object containing functions to run. Each function is passed
a `callback(err, result)` which it must call on completion with an error `err`
(which can be `null`) and an optional `result` value.
* `callback(err, results)` - An optional callback to run once all the functions
have completed. This function gets a results array (or object) containing all
the result arguments passed to the task callbacks.
__Example__
```js
async.parallel([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
}
],
// optional callback
function(err, results){
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.
});
// an example using an object instead of an array
async.parallel({
one: function(callback){
setTimeout(function(){
callback(null, 1);
}, 200);
},
two: function(callback){
setTimeout(function(){
callback(null, 2);
}, 100);
}
},
function(err, results) {
// results is now equals to: {one: 1, two: 2}
});
```
---------------------------------------
<a name="parallelLimit" />
### parallelLimit(tasks, limit, [callback])
The same as [`parallel`](#parallel), only `tasks` are executed in parallel
with a maximum of `limit` tasks executing at any time.
Note that the `tasks` are not executed in batches, so there is no guarantee that
the first `limit` tasks will complete before any others are started.
__Arguments__
* `tasks` - An array or object containing functions to run, each function is passed
a `callback(err, result)` it must call on completion with an error `err` (which can
be `null`) and an optional `result` value.
* `limit` - The maximum number of `tasks` to run at any time.
* `callback(err, results)` - An optional callback to run once all the functions
have completed. This function gets a results array (or object) containing all
the result arguments passed to the `task` callbacks.
---------------------------------------
<a name="whilst" />
### whilst(test, fn, callback)
Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
or an error occurs.
__Arguments__
* `test()` - synchronous truth test to perform before each execution of `fn`.
* `fn(callback)` - A function which is called each time `test` passes. The function is
passed a `callback(err)`, which must be called once it has completed with an
optional `err` argument.
* `callback(err)` - A callback which is called after the test fails and repeated
execution of `fn` has stopped.
__Example__
```js
var count = 0;
async.whilst(
function () { return count < 5; },
function (callback) {
count++;
setTimeout(callback, 1000);
},
function (err) {
// 5 seconds have passed
}
);
```
---------------------------------------
<a name="doWhilst" />
### doWhilst(fn, test, callback)
The post-check version of [`whilst`](#whilst). To reflect the difference in
the order of operations, the arguments `test` and `fn` are switched.
`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
---------------------------------------
<a name="until" />
### until(test, fn, callback)
Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
or an error occurs.
The inverse of [`whilst`](#whilst).
---------------------------------------
<a name="doUntil" />
### doUntil(fn, test, callback)
Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
---------------------------------------
<a name="forever" />
### forever(fn, errback)
Calls the asynchronous function `fn` with a callback parameter that allows it to
call itself again, in series, indefinitely.
If an error is passed to the callback then `errback` is called with the
error, and execution stops, otherwise it will never be called.
```js
async.forever(
function(next) {
// next is suitable for passing to things that need a callback(err [, whatever]);
// it will result in this function being called again.
},
function(err) {
// if next is called with a value in its first parameter, it will appear
// in here as 'err', and execution will stop.
}
);
```
---------------------------------------
<a name="waterfall" />
### waterfall(tasks, [callback])
Runs the `tasks` array of functions in series, each passing their results to the next in
the array. However, if any of the `tasks` pass an error to their own callback, the
next function is not executed, and the main `callback` is immediately called with
the error.
__Arguments__
* `tasks` - An array of functions to run, each function is passed a
`callback(err, result1, result2, ...)` it must call on completion. The first
argument is an error (which can be `null`) and any further arguments will be
passed as arguments in order to the next task.
* `callback(err, [results])` - An optional callback to run once all the functions
have completed. This will be passed the results of the last task's callback.
__Example__
```js
async.waterfall([
function(callback) {
callback(null, 'one', 'two');
},
function(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
},
function(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
```
---------------------------------------
<a name="compose" />
### compose(fn1, fn2...)
Creates a function which is a composition of the passed asynchronous
functions. Each function consumes the return value of the function that
follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
`f(g(h()))`, only this version uses callbacks to obtain the return values.
Each function is executed with the `this` binding of the composed function.
__Arguments__
* `functions...` - the asynchronous functions to compose
__Example__
```js
function add1(n, callback) {
setTimeout(function () {
callback(null, n + 1);
}, 10);
}
function mul3(n, callback) {
setTimeout(function () {
callback(null, n * 3);
}, 10);
}
var add1mul3 = async.compose(mul3, add1);
add1mul3(4, function (err, result) {
// result now equals 15
});
```
---------------------------------------
<a name="seq" />
### seq(fn1, fn2...)
Version of the compose function that is more natural to read.
Each function consumes the return value of the previous function.
It is the equivalent of [`compose`](#compose) with the arguments reversed.
Each function is executed with the `this` binding of the composed function.
__Arguments__
* functions... - the asynchronous functions to compose
__Example__
```js
// Requires lodash (or underscore), express3 and dresende's orm2.
// Part of an app, that fetches cats of the logged user.
// This example uses `seq` function to avoid overnesting and error
// handling clutter.
app.get('/cats', function(request, response) {
var User = request.models.User;
async.seq(
_.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
function(user, fn) {
user.getCats(fn); // 'getCats' has signature (callback(err, data))
}
)(req.session.user_id, function (err, cats) {
if (err) {
console.error(err);
response.json({ status: 'error', message: err.message });
} else {
response.json({ status: 'ok', message: 'Cats found', data: cats });
}
});
});
```
---------------------------------------
<a name="applyEach" />
### applyEach(fns, args..., callback)
Applies the provided arguments to each function in the array, calling
`callback` after all functions have completed. If you only provide the first
argument, then it will return a function which lets you pass in the
arguments as if it were a single function call.
__Arguments__
* `fns` - the asynchronous functions to all call with the same arguments
* `args...` - any number of separate arguments to pass to the function
* `callback` - the final argument should be the callback, called when all
functions have completed processing
__Example__
```js
async.applyEach([enableSearch, updateSchema], 'bucket', callback);
// partial application example:
async.each(
buckets,
async.applyEach([enableSearch, updateSchema]),
callback
);
```
---------------------------------------
<a name="applyEachSeries" />
### applyEachSeries(arr, iterator, callback)
The same as [`applyEach`](#applyEach) only the functions are applied in series.
---------------------------------------
<a name="queue" />
### queue(worker, concurrency)
Creates a `queue` object with the specified `concurrency`. Tasks added to the
`queue` are processed in parallel (up to the `concurrency` limit). If all
`worker`s are in progress, the task is queued until one becomes available.
Once a `worker` completes a `task`, that `task`'s callback is called.
__Arguments__
* `worker(task, callback)` - An asynchronous function for processing a queued
task, which must call its `callback(err)` argument when finished, with an
optional `error` as an argument.
* `concurrency` - An `integer` for determining how many `worker` functions should be
run in parallel.
__Queue objects__
The `queue` object returned by this function has the following properties and
methods:
* `length()` - a function returning the number of items waiting to be processed.
* `started` - a function returning whether or not any items have been pushed and processed by the queue
* `running()` - a function returning the number of items currently being processed.
* `idle()` - a function returning false if there are items waiting or being processed, or true if not.
* `concurrency` - an integer for determining how many `worker` functions should be
run in parallel. This property can be changed after a `queue` is created to
alter the concurrency on-the-fly.
* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
the `worker` has finished processing the task. Instead of a single task, a `tasks` array
can be submitted. The respective callback is used for every task in the list.
* `unshift(task, [callback])` - add a new task to the front of the `queue`.
* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
and further tasks will be queued.
* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
* `paused` - a boolean for determining whether the queue is in a paused state
* `pause()` - a function that pauses the processing of tasks until `resume()` is called.
* `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle.
__Example__
```js
// create a queue object with concurrency 2
var q = async.queue(function (task, callback) {
console.log('hello ' + task.name);
callback();
}, 2);
// assign a callback
q.drain = function() {
console.log('all items have been processed');
}
// add some items to the queue
q.push({name: 'foo'}, function (err) {
console.log('finished processing foo');
});
q.push({name: 'bar'}, function (err) {
console.log('finished processing bar');
});
// add some items to the queue (batch-wise)
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
console.log('finished processing item');
});
// add some items to the front of the queue
q.unshift({name: 'bar'}, function (err) {
console.log('finished processing bar');
});
```
---------------------------------------
<a name="priorityQueue" />
### priorityQueue(worker, concurrency)
The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects:
* `push(task, priority, [callback])` - `priority` should be a number. If an array of
`tasks` is given, all tasks will be assigned the same priority.
* The `unshift` method was removed.
---------------------------------------
<a name="cargo" />
### cargo(worker, [payload])
Creates a `cargo` object with the specified payload. Tasks added to the
cargo will be processed altogether (up to the `payload` limit). If the
`worker` is in progress, the task is queued until it becomes available. Once
the `worker` has completed some tasks, each callback of those tasks is called.
Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work.
While [queue](#queue) passes only one task to one of a group of workers
at a time, cargo passes an array of tasks to a single worker, repeating
when the worker is finished.
__Arguments__
* `worker(tasks, callback)` - An asynchronous function for processing an array of
queued tasks, which must call its `callback(err)` argument when finished, with
an optional `err` argument.
* `payload` - An optional `integer` for determining how many tasks should be
processed per round; if omitted, the default is unlimited.
__Cargo objects__
The `cargo` object returned by this function has the following properties and
methods:
* `length()` - A function returning the number of items waiting to be processed.
* `payload` - An `integer` for determining how many tasks should be
process per round. This property can be changed after a `cargo` is created to
alter the payload on-the-fly.
* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
can be submitted. The respective callback is used for every task in the list.
* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
__Example__
```js
// create a cargo object with payload 2
var cargo = async.cargo(function (tasks, callback) {
for(var i=0; i<tasks.length; i++){
console.log('hello ' + tasks[i].name);
}
callback();
}, 2);
// add some items
cargo.push({name: 'foo'}, function (err) {
console.log('finished processing foo');
});
cargo.push({name: 'bar'}, function (err) {
console.log('finished processing bar');
});
cargo.push({name: 'baz'}, function (err) {
console.log('finished processing baz');
});
```
---------------------------------------
<a name="auto" />
### auto(tasks, [callback])
Determines the best order for running the functions in `tasks`, based on their
requirements. Each function can optionally depend on other functions being completed
first, and each function is run as soon as its requirements are satisfied.
If any of the functions pass an error to their callback, it will not
complete (so any other functions depending on it will not run), and the main
`callback` is immediately called with the error. Functions also receive an
object containing the results of functions which have completed so far.
Note, all functions are called with a `results` object as a second argument,
so it is unsafe to pass functions in the `tasks` object which cannot handle the
extra argument.
For example, this snippet of code:
```js
async.auto({
readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
}, callback);
```
will have the effect of calling `readFile` with the results object as the last
argument, which will fail:
```js
fs.readFile('data.txt', 'utf-8', cb, {});
```
Instead, wrap the call to `readFile` in a function which does not forward the
`results` object:
```js
async.auto({
readData: function(cb, results){
fs.readFile('data.txt', 'utf-8', cb);
}
}, callback);
```
__Arguments__
* `tasks` - An object. Each of its properties is either a function or an array of
requirements, with the function itself the last item in the array. The object's key
of a property serves as the name of the task defined by that property,
i.e. can be used when specifying requirements for other tasks.
The function receives two arguments: (1) a `callback(err, result)` which must be
called when finished, passing an `error` (which can be `null`) and the result of
the function's execution, and (2) a `results` object, containing the results of
the previously executed functions.
* `callback(err, results)` - An optional callback which is called when all the
tasks have been completed. It receives the `err` argument if any `tasks`
pass an error to their callback. Results are always returned; however, if
an error occurs, no further `tasks` will be performed, and the results
object will only contain partial results.
__Example__
```js
async.auto({
get_data: function(callback){
console.log('in get_data');
// async code to get some data
callback(null, 'data', 'converted to array');
},
make_folder: function(callback){
console.log('in make_folder');
// async code to create a directory to store a file in
// this is run at the same time as getting the data
callback(null, 'folder');
},
write_file: ['get_data', 'make_folder', function(callback, results){
console.log('in write_file', JSON.stringify(results));
// once there is some data and the directory exists,
// write the data to a file in the directory
callback(null, 'filename');
}],
email_link: ['write_file', function(callback, results){
console.log('in email_link', JSON.stringify(results));
// once the file is written let's email a link to it...
// results.write_file contains the filename returned by write_file.
callback(null, {'file':results.write_file, 'email':'user@example.com'});
}]
}, function(err, results) {
console.log('err = ', err);
console.log('results = ', results);
});
```
This is a fairly trivial example, but to do this using the basic parallel and
series functions would look like this:
```js
async.parallel([
function(callback){
console.log('in get_data');
// async code to get some data
callback(null, 'data', 'converted to array');
},
function(callback){
console.log('in make_folder');
// async code to create a directory to store a file in
// this is run at the same time as getting the data
callback(null, 'folder');
}
],
function(err, results){
async.series([
function(callback){
consol | {
"content_hash": "5e0d37904275d65e9f062a9b6bda6da9",
"timestamp": "",
"source": "github",
"line_count": 1325,
"max_line_length": 314,
"avg_line_length": 32.82566037735849,
"alnum_prop": 0.6766450544902746,
"repo_name": "wenjoy/homePage",
"id": "b19a49ade5cbb9907710a1fea20faf076860a924",
"size": "43520",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/geetest/node_modules/request/node_modules/karma/node_modules/grunt-bump/node_modules/grunt-contrib-nodeunit/node_modules/grunt-contrib-internal/node_modules/read-package-json/node_modules/normalize-package-data/node_modules/async/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "330"
},
{
"name": "HTML",
"bytes": "4292"
},
{
"name": "JavaScript",
"bytes": "26625"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class Echosign\Creators\Reminder | Echosign V3</title>
<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li class="active main">
<a href="namespace-Echosign.html">
Echosign<span></span>
</a>
<ul>
<li class="main">
<a href="namespace-Echosign.Abstracts.html">
Abstracts </a>
</li>
<li class="active main">
<a href="namespace-Echosign.Creators.html">
Creators </a>
</li>
<li class="main">
<a href="namespace-Echosign.Exceptions.html">
Exceptions </a>
</li>
<li class="main">
<a href="namespace-Echosign.Interfaces.html">
Interfaces </a>
</li>
<li class="main">
<a href="namespace-Echosign.RequestBuilders.html">
RequestBuilders<span></span>
</a>
<ul>
<li class="main">
<a href="namespace-Echosign.RequestBuilders.Agreement.html">
Agreement </a>
</li>
<li class="main">
<a href="namespace-Echosign.RequestBuilders.LibraryDocument.html">
LibraryDocument </a>
</li>
<li class="main">
<a href="namespace-Echosign.RequestBuilders.Widget.html">
Widget </a>
</li>
</ul></li>
<li class="main">
<a href="namespace-Echosign.Requests.html">
Requests </a>
</li>
<li class="main">
<a href="namespace-Echosign.Responses.html">
Responses </a>
</li>
<li class="main">
<a href="namespace-Echosign.Transports.html">
Transports </a>
</li>
</ul></li>
</ul>
</div>
<hr>
<div id="elements">
<h3>Classes</h3>
<ul>
<li><a href="class-Echosign.Creators.Agreement.html">Agreement</a></li>
<li><a href="class-Echosign.Creators.CreatorBase.html">CreatorBase</a></li>
<li><a href="class-Echosign.Creators.LibraryDocument.html">LibraryDocument</a></li>
<li class="active"><a href="class-Echosign.Creators.Reminder.html">Reminder</a></li>
<li><a href="class-Echosign.Creators.Search.html">Search</a></li>
<li><a href="class-Echosign.Creators.TransientDocument.html">TransientDocument</a></li>
<li><a href="class-Echosign.Creators.User.html">User</a></li>
<li><a href="class-Echosign.Creators.Widget.html">Widget</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="">
<input type="hidden" name="ie" value="UTF-8">
<input type="text" name="q" class="text" placeholder="Search">
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<a href="namespace-Echosign.Creators.html" title="Summary of Echosign\Creators"><span>Namespace</span></a>
</li>
<li class="active">
<span>Class</span> </li>
</ul>
<ul>
</ul>
<ul>
</ul>
</div>
<div id="content" class="class">
<h1>Class Reminder</h1>
<dl class="tree">
<dd style="padding-left:0px">
<a href="class-Echosign.Creators.CreatorBase.html"><span>Echosign\Creators\CreatorBase</span></a>
</dd>
<dd style="padding-left:30px">
<img src="resources/inherit.png" alt="Extended by">
<b><span>Echosign\Creators\Reminder</span></b>
</dd>
</dl>
<div class="info">
<b>Namespace:</b> <a href="namespace-Echosign.html">Echosign</a>\<a href="namespace-Echosign.Creators.html">Creators</a><br>
<b>Located at</b> <a href="source-class-Echosign.Creators.Reminder.html#8-47" title="Go to source code">Creators/Reminder.php</a>
<br>
</div>
<table class="summary methods" id="methods">
<caption>Methods summary</caption>
<tr data-order="create" id="_create">
<td class="attributes"><code>
public
boolean|string
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#_create">#</a>
<code><a href="source-class-Echosign.Creators.Reminder.html#15-37" title="Go to source code">create</a>( <span> <var>$agreementId</var></span>, <span>null <var>$message</var> = <span class="php-keyword1">null</span> </span> )</code>
<div class="description short">
<p>Create a reminder for an outstanding agreement.</p>
</div>
<div class="description detailed hidden">
<p>Create a reminder for an outstanding agreement.</p>
<h4>Parameters</h4>
<div class="list"><dl>
<dt><var>$agreementId</var></dt>
<dd></dd>
<dt><var>$message</var></dt>
<dd></dd>
</dl></div>
<h4>Returns</h4>
<div class="list">
boolean|string
</div>
</div>
</div></td>
</tr>
<tr data-order="getReminder" id="_getReminder">
<td class="attributes"><code>
public
<code><a href="class-Echosign.Reminders.html">Echosign\Reminders</a></code>
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#_getReminder">#</a>
<code><a href="source-class-Echosign.Creators.Reminder.html#39-45" title="Go to source code">getReminder</a>( )</code>
<div class="description short">
</div>
<div class="description detailed hidden">
<h4>Returns</h4>
<div class="list">
<code><a href="class-Echosign.Reminders.html">Echosign\Reminders</a></code>
</div>
</div>
</div></td>
</tr>
</table>
<table class="summary inherited">
<caption>Methods inherited from <a href="class-Echosign.Creators.CreatorBase.html#methods">Echosign\Creators\CreatorBase</a></caption>
<tr>
<td><code>
<a href="class-Echosign.Creators.CreatorBase.html#___construct">__construct()</a>,
<a href="class-Echosign.Creators.CreatorBase.html#_getErrorMessages">getErrorMessages()</a>,
<a href="class-Echosign.Creators.CreatorBase.html#_getResponse">getResponse()</a>,
<a href="class-Echosign.Creators.CreatorBase.html#_getToken">getToken()</a>,
<a href="class-Echosign.Creators.CreatorBase.html#_getTransport">getTransport()</a>,
<a href="class-Echosign.Creators.CreatorBase.html#_hasErrors">hasErrors()</a>,
<a href="class-Echosign.Creators.CreatorBase.html#_setToken">setToken()</a>,
<a href="class-Echosign.Creators.CreatorBase.html#_setTransport">setTransport()</a>
</code></td>
</tr>
</table>
<table class="summary properties" id="properties">
<caption>Properties summary</caption>
<tr data-order="reminder" id="$reminder">
<td class="attributes"><code>
protected
<code><a href="class-Echosign.Reminders.html">Echosign\Reminders</a></code>
</code></td>
<td class="name">
<a href="source-class-Echosign.Creators.Reminder.html#10-13" title="Go to source code"><var>$reminder</var></a>
<div class="description short">
</div>
<div class="description detailed hidden">
</div>
</td>
<td class="value">
<div>
<a href="#$reminder" class="anchor">#</a>
<code></code>
</div>
</td>
</tr>
</table>
<table class="summary inherited">
<caption>Properties inherited from <a href="class-Echosign.Creators.CreatorBase.html#properties">Echosign\Creators\CreatorBase</a></caption>
<tr>
<td><code>
<a href="class-Echosign.Creators.CreatorBase.html#$errorMessages"><var>$errorMessages</var></a>,
<a href="class-Echosign.Creators.CreatorBase.html#$response"><var>$response</var></a>,
<a href="class-Echosign.Creators.CreatorBase.html#$token"><var>$token</var></a>,
<a href="class-Echosign.Creators.CreatorBase.html#$transport"><var>$transport</var></a>
</code></td>
</tr>
</table>
</div>
<div id="footer">
Echosign V3 API documentation generated by <a href="http://apigen.org">ApiGen</a>
</div>
</div>
</div>
<script src="resources/combined.js"></script>
<script src="elementlist.js"></script>
</body>
</html>
| {
"content_hash": "da6b95a2daa1ef7dcbee33e7d8debd27",
"timestamp": "",
"source": "github",
"line_count": 338,
"max_line_length": 234,
"avg_line_length": 23.600591715976332,
"alnum_prop": 0.6268020559107433,
"repo_name": "nsbucky/echosignv3",
"id": "1400226a8e8d8387365bd7f6f32e1ece6d3de3f0",
"size": "7977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apigen/class-Echosign.Creators.Reminder.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8496"
},
{
"name": "HTML",
"bytes": "2224311"
},
{
"name": "JavaScript",
"bytes": "131443"
},
{
"name": "PHP",
"bytes": "247571"
}
],
"symlink_target": ""
} |
Got Scripts? Test’em!
=================
[](http://travis-ci.org/airportyh/testem)
Unit testing in Javascript can be tedious and painful, but Testem makes it so easy that you will actually *want* to write tests.
Features
--------
* Test-framework agnostic. Support for
- [Jasmine](http://pivotal.github.com/jasmine/)
- [QUnit](http://qunitjs.com/)
- [Mocha](http://visionmedia.github.com/mocha/)
- [Buster.js](http://docs.busterjs.org/)
- Others, through custom test framework adapters.
* Run tests in all major browsers as well as [Node](http://nodejs.org) and [PhantomJS](http://phantomjs.org/)
* Two distinct use-cases:
- Test-Driven-Development(TDD) — designed to streamline the TDD workflow
- Continuous Integration(CI) — designed to work well with popular CI servers like Jenkins or Teamcity
* Cross-platform support
- OS X
- Windows
- Linux
* Preprocessor support
- CoffeeScript
- Browserify
- JSHint/JSLint
- everything else
Screencasts
-----------
* Watch this **[introductory screencast (11:39)](http://www.youtube.com/watch?v=-1mjv4yk5JM)** to see it in action! This one demonstrates the TDD workflow.
* [Launchers (12:10)](http://www.youtube.com/watch?v=Up0lVjWk9Rk) — more detail about launchers: how to specify what to auto-launch and how to configure one yourself to run tests in **Node**.
* [Continous Integration (CI) Mode (4:24)](http://www.youtube.com/watch?v=Js16Cj80HKY) — details about how CI mode works.
* [Making JavaScript Testing Fun With Testem (22:53)](http://net.tutsplus.com/tutorials/javascript-ajax/make-javascript-testing-fun-with-testem/) — a thorough screencast by NetTuts+'s Jeffery Way covering the basics, Jasmine, Mocha/Chai, CoffeeScript and more!
Installation
------------
You need [Node](http://nodejs.org/) version 0.6.2 or later installed on your system. Node is extremely easy to install and has a small footprint, and is really awesome otherwise too, so [just do it](http://nodejs.org/).
Once you have Node installed:
npm install testem -g
This will install the `testem` executable globally on your system.
Usage
-----
As stated before, Testem supports two use cases: test-driven-development and continuous integration. Let's go over each one.
Development Mode
----------------
The simplest way to use Testem, in the TDD spirit, is to start in an empty directory and run the command
testem
You will see a terminal-based interface which looks like this

Now open your browser and go to the specified URL. You should now see

We see 0/0 for tests because at this point we haven't written any code. As we write them, Testem will pick up any `.js` files
that were added, include them, and if there are tests, run them automatically. So let's first write `hello_spec.js` in the spirit of "test first"(written in Jasmine)
```javascript
describe('hello', function(){
it('should say hello', function(){
expect(hello()).toBe('hello world');
});
});
```
Save that file and now you should see

Testem should automatically pick up the new files you've added and also any changes that you make to them and rerun the tests. The test fails as we'd expect. Now we implement the spec like so in `hello.js`
```javascript
function hello(){
return "hello world";
}
```
So you should now see

### Using the Text User Interface
In development mode, Testem has a text-based graphical user interface which uses keyboard-based controls. Here is a list of the control keys
* ENTER : Run the tests
* q : Quit
* ← LEFT ARROW : Move to the next browser tab on the left
* → RIGHT ARROW : Move to the next browser tab on the right
* TAB : switch the target text panel between the top and bottom halves of the split panel (if a split is present)
* ↑ UP ARROW : scroll up in the target text panel
* ↓ DOWN ARROW : scroll down in the target text panel
* SPACE : page down in the target text panel
* b : page up in the target text panel
* d : half a page down target text panel
* u : half a page up target text panel
### Command line options
To see all command line options
testem --help
Continuous Integration Mode
---------------------------
To use Testem for continuous integration
testem ci
In CI mode, Testem runs your tests on all the browsers that are available on the system one after another.
You can run multiple browsers in parallel in CI mode by specifying the `--parallel` (or `-P`) option to be the number of concurrent running browsers.
testem ci -P 5 # run 5 browser in parallel
To find out what browsers are currently available - those that Testem knows about and can make use of
testem launchers
Will print them out. The output might look like
$ testem launchers
Browsers available on this system:
IE7
IE8
IE9
Chrome
Firefox
Safari
Opera
PhantomJS
Did you notice that this system has IE versions 7-9? Yes, actually it has only IE9 installed, but Testem uses IE's compatibility mode feature to emulate IE 7 and 8.
When you run `testem ci` to run tests, it outputs the results in the [TAP](http://testanything.org/) format by default, which looks like
ok 1 Chrome 16.0 - hello should say hello.
1..1
# tests 1
# pass 1
# ok
TAP is a human-readable and language-agnostic test result format. TAP plugins exist for popular CI servers
* [Jenkins TAP plugin](https://wiki.jenkins-ci.org/display/JENKINS/TAP+Plugin) - I've added [detailed instructions](https://github.com/airportyh/testem/blob/master/docs/use_with_jenkins.md) for setup with Jenkins.
* [TeamCity TAP plugin](https://github.com/pavelsher/teamcity-tap-parser)
## Other Test Reporters
Testem has other test reporters than TAP: `dot` and `xunit`. You can use the `-R` to specify them
testem ci -R dot
### Command line options
To see all command line options for CI
testem ci --help
Configuration File
------------------
For the simplest JavaScript projects, the TDD workflow described above will work fine. There are times when you want
to structure your source files into separate directories, or want to have finer control over what files to include.
This calls for the `testem.json` configuration file (you can also alternatively use the YAML format with a `testem.yml` file). It looks like
```json
{
"framework": "jasmine",
"src_files": [
"hello.js",
"hello_spec.js"
]
}
```
The `src_files` can also be unix glob patterns.
```json
{
"src_files": [
"js/**/*.js",
"spec/**/*.js"
]
}
```
You can also ignore certain files using `src_files_ignore`.
***Update: I've removed the ability to use a space-separated list of globs as a string in the src_files property because it disallowed matching files or directories with spaces in them.***
```json
{
"src_files": [
"js/**/*.js",
"spec/**/*.js"
],
"src_files_ignore": "js/toxic/*.js"
}
```
Read [more details](docs/config_file.md) about the config options.
Custom Test Pages
-----------------
You can also use a custom page for testing. To do this, first you need to specify `test_page` to point to your test page in the config file (`framework` and `src_files` are irrelevant in this case)
```json
{
"test_page": "tests.html"
}
```
Next, the test page you use needs to have the adapter code installed on them, as specified in the next section.
### Include Snippet
Include this snippet directly after your `jasmine.js`, `qunit.js` or `mocha.js` or `buster.js` include to enable *Testem* with your test page.
```html
<script src="/testem.js"></script>
```
Or if you are using require.js or another loader, just make sure you load `/testem.js` as the next script after the test framework.
### Dynamic Substitution
To enable dynamically substituting in the Javascript files in your custom test page, you must
1. name your test page using `.mustache` as the extension
2. use `{{#serve_files}}` to loop over the set of Javascript files to be served, and then reference its `src` property to access their path
Example:
{{#serve_files}}
<script src="{{src}}"></script>
{{/serve_files}}
Launchers
---------
Testem has the ability to automatically launch browsers or processes for you. To see the list of launchers Testem knows about, you can use the command
testem launchers
This will display something like the following
Have 5 launchers available; auto-launch info displayed on the right.
Launcher Type CI Dev
------------ ------------ -- ---
Chrome browser ✔
Firefox browser ✔
Safari browser ✔
Opera browser ✔
Mocha process(TAP) ✔
This displays the current list of launchers that are available. Launchers can launch either a browser or a custom process — as shown in the "Type" column. Custom launchers can be defined to launch custom processes. The "CI" column indicates the launchers which will be automatically launch in CI-mode. Similarly, the "Dev" column those that will automatically launch in dev-mode.
Running Tests in Node and Custom Process Launchers
--------------------------------------------------
To run tests in Node you need to create a custom launcher which launches a process which will run your tests. This is nice because it means you can use any test framework - or lack thereof. For example, to make a launcher that runs mocha tests, you would write the following in the config file `testem.json`
```javascript
"launchers": {
"Mocha": {
"command": "mocha tests/*_tests.js"
}
}
```
When you run `testem`, it will auto-launch the mocha process based on the specified command every time the tests are run. It will display the stdout and well as the stderr of the process inside of the "Mocha" tab in the UI. It will base the pass/fail status on the exit code of the process. In fact, because Testem can launch any arbitrary process for you, you could very well be using it to run programs in other languages.
Processes with TAP Output
-------------------------
If your process outputs test results in [TAP](http://en.wikipedia.org/wiki/Test_Anything_Protocol) format, you can tell that to testem via the `protocol` property. For example
```javascript
"launchers": {
"Mocha": {
"command": "mocha tests/*_tests.js -R tap"
"protocol": "tap"
}
}
```
When this is done, Testem will read in the process's stdout and parse it as TAP, and then display the test results in Testem's normal format. It will also hide the process's stdout output from the console log panel, although it will still display the stderr.
PhantomJS
---------
PhantomJS is a Webkit-based headless browser. It's fast and it's awesome! Testem will pick it up if you have [PhantomJS](http://www.phantomjs.org/) installed in your system and the `phantomjs` executable is in your path. Run
testem launchers
And verify that it's in the list.
If you want to debug tests in PhantomJS, include the `phantomjs_debug_port` option in your testem configuration, referencing an available port number. Once testem has started PhantomJS, navigate (with a traditional browser) to http://localhost:<port> and attach to one of PhantomJS's browser tabs (probably the second one in the list). `debugger` statements will now break in the debugging console.
Preprocessors (CoffeeScript, LESS, Sass, Browserify, etc)
---------------------------------------------------------
If you need to run a preprocessor (or indeed any shell command before the start of the tests) use the `before_tests` option, such as
"before_tests": "coffee -c *.coffee"
And Testem will run it before each test run. For file watching, you may still use the `src_files` option
```javascript
"src_files": [
"*.coffee"
]
```
Since you want to be serving the `.js` files that are generated and not the `.coffee` files, you want to specify the `serve_files` option to tell it that
```javascript
"serve_files": [
"*.js"
]
```
Testem will throw up a big ol' error dialog if the preprocessor command exits with an error code, so code checkers like jshint can used here as well.
If you need to run a command after your tests have completed (such as removing compiled `.js` files), use the `after_tests` option.
```javascript
"after_tests": "rm *.js"
```
If you would prefer simply to clean up when Testem exits, you can use the `on_exit` option.
Custom Routes
-------------
Sometimes you may want to re-map a URL to a different directory on the file system. Maybe you have the following file structure:
+ src
+ hello.js
+ tests.js
+ css
+ styles.css
+ public
+ tests.html
Let's say you want to serve `tests.html` at the top level url `/tests.html`, all the Javascripts under `/js` and all the css under `/css` you can use the "routes" option to do that
```javascript
"routes": {
"/tests.html": "public/tests.html",
"/js": "src",
"/css": "css"
}
```
DIY: Use Any Test Framework
---------------------------
If you want to use Testem with a test framework that's not supported out of the box, you can write your own custom test framework adapter. See [customAdapter.js](https://github.com/airportyh/testem/blob/master/examples/custom_adapter/customAdapter.js) for an example of how to write a custom adapter.
Then, to use it, in your config file simply set
```javascript
"framework": "custom"
```
And then make sure you include the adapter code in your test suite and you are ready to go. Here for the [full example](https://github.com/airportyh/testem/tree/master/examples/custom_adapter).
Growl or Growl-ish Notifications
--------------------------------
If you'd prefer not to be looking at the terminal while developing, you can us growl notification (or simply desktop notifications on some platforms) using the `-g` option.
But, to use this option, you may first need to install some additional software, see the [node-growl page](https://github.com/visionmedia/node-growl#install) for more details.
API Proxy
--------------------------------
The proxy option allows you to transparently forward http requests to an external endpoint.
Simply add a `proxies` section to the `testem.json` configuration file.
```json
{
"proxies": {
"/api": {
"port": 4200,
"host": "localhost"
},
"/xmlapi": {
"port": 8000,
"host": "localhost"
}
}
}
```
This functionality is implemented as a *transparent proxy* hence a request to
`http://localhost:7357/api/posts.json` will be proxied to `http://localhost:4200/api/posts.json` without removing the `/api` prefix.
Example Projects
----------------
I've created [examples](https://github.com/airportyh/testem/tree/master/examples/) for various setups
* [Simple QUnit project](https://github.com/airportyh/testem/tree/master/examples/qunit_simple)
* [Simple Jasmine project](https://github.com/airportyh/testem/tree/master/examples/jasmine_simple)
* [Jasmine 2](https://github.com/airportyh/testem/tree/master/examples/jasmine2)
* [Custom Jasmine project](https://github.com/airportyh/testem/tree/master/examples/jasmine_custom)
* [Custom Jasmine project using Require.js](https://github.com/airportyh/testem/tree/master/examples/jasmine_requirejs)
* [Simple Mocha Project](https://github.com/airportyh/testem/tree/master/examples/mocha_simple)
* [Mocha + Chai](https://github.com/airportyh/testem/tree/master/examples/mocha_chai_simple)
* [Hybrid Project](https://github.com/airportyh/testem/tree/master/examples/hybrid_simple) - Mocha tests running in both the browser and Node.
* [Buster.js Project](https://github.com/airportyh/testem/tree/master/examples/buster)
* [Coffeescript Project](https://github.com/airportyh/testem/tree/master/examples/coffeescript)
* [Browserify Project](https://github.com/airportyh/testem/tree/master/examples/browserify)
* [JSHint Example](https://github.com/airportyh/testem/tree/master/examples/jshint)
* [Custom Test Framework](https://github.com/airportyh/testem/tree/master/examples/custom_adapter)
* [Tape Example](https://github.com/airportyh/testem/tree/master/examples/tape_example)
* [BrowserStack Integration](https://github.com/airportyh/testem/tree/master/examples/browserstack) **bleeding edge**
* [SauceLabs Integration](https://github.com/airportyh/testem/tree/master/examples/saucelabs) **bleeding edge**
* [Code Coverage with Istanbul](https://github.com/airportyh/testem/tree/master/examples/coverage_istanbul) **bleeding edge**
Known Issues
------------
1. On Windows, Mocha fails to run under Testem due to an [issue](https://github.com/joyent/node/issues/3871) in Node core. Until that gets resolved, I've made a [workaround](https://github.com/airportyh/mocha/tree/windowsfix) for mocha. To install this fork of Mocha, do
npm install https://github.com/airportyh/mocha/tarball/windowsfix -g
2. If you are using prototype.js version 1.6.3 or below, you will [encounter issues](https://github.com/airportyh/testem/issues/130).
Contributing
------------
If you want to [contribute to the project](https://github.com/airportyh/testem/blob/master/CONTRIBUTING.md), I am going to do my best to stay out of your way.
Roadmap
-------
1. [BrowserStack](http://www.browserstack.com/user/dashboard) integration - following [Bunyip](http://www.thecssninja.com/javascript/bunyip)'s example
2. Figure out a happy path for testing on mobile browsers (maybe BrowserStack).
Contributors
------------
* [Toby Ho](https://github.com/airportyh)
* [Raynos](https://github.com/Raynos)
* [Derek Brans](https://github.com/dbrans)
Community
---------
* **Mailing list**: <https://groups.google.com/forum/?fromgroups#!forum/testem-users>
Credits
-------
Testem depends on these great software
* [Jasmine](http://pivotal.github.com/jasmine/)
* [QUnit](http://code.google.com/p/jqunit/)
* [Mocha](http://visionmedia.github.com/mocha/)
* [Node](http://nodejs.org/)
* [Socket.IO](http://socket.io/)
* [PhantomJS](http://www.phantomjs.org/)
* [Node-Tap](https://github.com/isaacs/node-tap)
* [Node-Charm](https://github.com/substack/node-charm)
* [Node Commander](http://tjholowaychuk.com/post/9103188408/commander-js-nodejs-command-line-interfaces-made-easy)
* [JS-Yaml](https://github.com/nodeca/js-yaml)
* [Express](http://expressjs.com/)
* [jQuery](http://jquery.com/)
* [Backbone](http://backbonejs.org/)
License
-------
(The MIT License)
Copyright (c) 2012 Toby Ho <airportyh@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| {
"content_hash": "73efde22562fa88023fc0ae109c4dfe1",
"timestamp": "",
"source": "github",
"line_count": 504,
"max_line_length": 460,
"avg_line_length": 39.595238095238095,
"alnum_prop": 0.7144217278011625,
"repo_name": "wiredgms/contacts",
"id": "90f003dac28af82f8a56c4784d5a0618f5a2d502",
"size": "19974",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "client/node_modules/ember-cli/node_modules/testem/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15766"
},
{
"name": "JavaScript",
"bytes": "5189616"
},
{
"name": "Makefile",
"bytes": "195"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.easyrong.manage.db.dao.LogDAO">
<resultMap id="BaseResultMap"
type="com.easyrong.manage.db.model.Log">
<id column="id" property="id" jdbcType="BIGINT" />
<result column="type" property="type" jdbcType="TINYINT" />
<result column="user" property="user" jdbcType="VARCHAR" />
<result column="description" property="description" jdbcType="VARCHAR" />
<result column="ip" property="ip" jdbcType="VARCHAR" />
<result column="createTime" property="createTime" jdbcType="TIMESTAMP" />
</resultMap>
<sql id="Base_Column_List">
id, type, user, description, ip, createTime
</sql>
<select id="searchLogCount" resultType="java.lang.Integer">
select count(*)
from ${tableName}log
<if test="keyword.length() >0">
where (locate (#{keyword}, id) > 0 or locate (#{keyword}, user) > 0 or locate (#{keyword}, description) > 0)
</if>
<if test="fromDate != null" >
<if test="keyword.length() >0">
and (createTime > #{fromDate} and createTime < #{toDate})
</if>
<if test="keyword.length() ==0">
where createTime > #{fromDate} and createTime < #{toDate}
</if>
</if>
</select>
<select id="searchLog" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from ${tableName}log
<if test="keyword.length() >0">
where locate (#{keyword}, id) > 0 or locate (#{keyword}, user) > 0 or locate (#{keyword}, description) > 0
</if>
<if test="fromDate != null" >
<if test="keyword.length() >0">
and (createTime > #{fromDate} and createTime < #{toDate})
</if>
<if test="keyword.length() ==0">
where createTime > #{fromDate} and createTime < #{toDate}
</if>
</if>
order by id desc
limit #{offset}, #{pageSize}
</select>
<insert id="insertLog">
insert into ${tableName}log (type, user, description, ip, createTime)
values (#{type}, #{user}, #{description}, #{ip}, #{createTime})
</insert>
<delete id="deleteLog">
delete from
${tableName}log
where id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper> | {
"content_hash": "c315c37c0ccae42d721e8543dc6b6ab5",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 111,
"avg_line_length": 35.69230769230769,
"alnum_prop": 0.6267241379310344,
"repo_name": "wxiwei/manage",
"id": "68a5ffb07215401b3ccaaaca8710f4cc569a7983",
"size": "2320",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/wxiwei/manage/db/mapper/Log.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "208622"
},
{
"name": "Java",
"bytes": "262483"
},
{
"name": "JavaScript",
"bytes": "217179"
}
],
"symlink_target": ""
} |
package org.wildfly.swarm.microprofile.jwtauth;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.arquillian.CreateSwarm;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@RunWith(Arquillian.class)
public class StaticKeyWithFractionConfigTest {
@Deployment(testable = false)
public static JAXRSArchive createDeployment() {
return ShrinkWrap.create(JAXRSArchive.class)
.addClass(TestApplication.class)
.addClass(TokenResource.class)
.addClass(KeyTool.class)
.addClass(JwtTool.class)
.addAsResource("project-empty-roles-static-fraction.yml", "project-defaults.yml")
.addAsResource("emptyRoles.properties")
.addAsResource(new ClassLoaderAsset("keys/pkcs8_bad_key.pem"), "pkcs8_bad_key.pem")
.addAsResource(new ClassLoaderAsset("keys/pkcs8_good_key.pem"), "pkcs8_good_key.pem")
.setContextRoot("/testsuite");
}
@Test
@RunAsClient
public void testThatStaticKeyIsVerified() throws Exception {
final KeyTool keyTool = KeyTool.newKeyTool(getClass().getResource("/keys/pkcs8_good_key.pem").toURI());
final String jwt = new JwtTool(keyTool, "http://testsuite-jwt-issuer.io").generateSignedJwt();
final URL url = new URL("http://localhost:8080/testsuite/mpjwt/token");
final URLConnection urlConnection = url.openConnection();
urlConnection.addRequestProperty("Authorization", "Bearer " + jwt);
try (InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(isr)) {
assertEquals(jwt, br.readLine());
}
}
@Test
@RunAsClient
public void testThatStaticKeyIsFake() throws Exception {
final KeyTool keyTool = KeyTool.newKeyTool(getClass().getResource("/keys/pkcs8_bad_key.pem").toURI());
final String jwt = new JwtTool(keyTool, "http://testsuite-jwt-issuer.io").generateSignedJwt();
final URL url = new URL("http://localhost:8080/testsuite/mpjwt/token");
final URLConnection urlConnection = url.openConnection();
urlConnection.addRequestProperty("Authorization", "Bearer " + jwt);
try (InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(isr)) {
assertNull(br.readLine()); // only if no body is returned, we know that the JWT was refused.
}
}
}
| {
"content_hash": "9542f3de7987947d60a776a95201c1f7",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 111,
"avg_line_length": 48.34920634920635,
"alnum_prop": 0.7035456336178595,
"repo_name": "juangon/wildfly-swarm",
"id": "5e7e4e1cf1c57a0998ef60a2474f476d7737f9db",
"size": "3046",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "testsuite/testsuite-microprofile-jwt/src/test/java/org/wildfly/swarm/microprofile/jwtauth/StaticKeyWithFractionConfigTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5821"
},
{
"name": "HTML",
"bytes": "7920"
},
{
"name": "Java",
"bytes": "3664105"
},
{
"name": "JavaScript",
"bytes": "13673"
},
{
"name": "Ruby",
"bytes": "5349"
},
{
"name": "Shell",
"bytes": "7821"
},
{
"name": "XSLT",
"bytes": "20396"
}
],
"symlink_target": ""
} |
id: bad87fee1348bd9aedc08826
title: Individuare elementi per classe usando jQuery
challengeType: 6
forumTopicId: 18316
required:
-
link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css'
dashedName: target-elements-by-class-using-jquery
---
# --description--
Vedi come abbiamo fatto rimbalzare tutti gli elementi del tuo `button`? Li abbiamo selezionati con `$("button")`, poi abbiamo aggiunto alcune classi CSS con `.addClass("animated bounce");`.
Hai appena usato la funzione `.addClass()` di jQuery, che ti permette di aggiungere classi agli elementi.
Innanzitutto, individuiamo gli elementi `div` con la classe `well` utilizzando il selettore `$(".well")`.
Nota che, proprio come con le dichiarazioni CSS, devi digitare un `.` prima del nome della classe.
Quindi usa la funzione `.addClass()` di jQuery per aggiungere le classi `animated` e `shake`.
Ad esempio, potresti scuotere tutti gli elementi di classe `text-primary` aggiungendo quanto segue alla tua `document ready function`:
```js
$(".text-primary").addClass("animated shake");
```
# --hints--
Dovresti usare la funzione jQuery `addClass()` per dare le classi `animated` e `shake` a tutti i tuoi elementi di classe `well`.
```js
assert($('.well').hasClass('animated') && $('.well').hasClass('shake'));
```
Dovresti usare solo jQuery per aggiungere queste classi all'elemento.
```js
assert(!code.match(/class\.\*animated/g));
```
# --seed--
## --seed-contents--
```html
<script>
$(document).ready(function() {
$("button").addClass("animated bounce");
});
</script>
<!-- Only change code above this line -->
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
```
# --solutions--
```html
<script>
$(document).ready(function() {
$("button").addClass("animated bounce");
$(".well").addClass("animated shake");
});
</script>
<!-- Only change code above this line -->
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
```
| {
"content_hash": "2f3e412cde00ac50c0eb208a13297a06",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 189,
"avg_line_length": 31.357142857142858,
"alnum_prop": 0.655751708428246,
"repo_name": "FreeCodeCamp/FreeCodeCamp",
"id": "df72cb1da15d2f6aa5348030d273d57eadcdfc46",
"size": "3516",
"binary": false,
"copies": "2",
"ref": "refs/heads/i18n-sync-client",
"path": "curriculum/challenges/italian/03-front-end-development-libraries/jquery/target-elements-by-class-using-jquery.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "190263"
},
{
"name": "HTML",
"bytes": "160430"
},
{
"name": "JavaScript",
"bytes": "546299"
}
],
"symlink_target": ""
} |
#pragma once
#ifndef GLSL_OPTIMIZER_H
#define GLSL_OPTIMIZER_H
/*
Main GLSL optimizer interface.
See ../../README.md for more instructions.
General usage:
ctx = glslopt_initialize();
for (lots of shaders) {
shader = glslopt_optimize (ctx, shaderType, shaderSource, options);
if (glslopt_get_status (shader)) {
newSource = glslopt_get_output (shader);
} else {
errorLog = glslopt_get_log (shader);
}
glslopt_shader_delete (shader);
}
glslopt_cleanup (ctx);
*/
struct glslopt_shader;
struct glslopt_ctx;
enum glslopt_shader_type {
kGlslOptShaderVertex = 0,
kGlslOptShaderFragment,
};
// Options flags for glsl_optimize
enum glslopt_options {
kGlslOptionSkipPreprocessor = (1<<0), // Skip preprocessing shader source. Saves some time if you know you don't need it.
kGlslOptionNotFullShader = (1<<1), // Passed shader is not the full shader source. This makes some optimizations weaker.
};
// Optimizer target language
enum glslopt_target {
kGlslTargetOpenGL = 0,
kGlslTargetOpenGLES20 = 1,
kGlslTargetOpenGLES30 = 2
};
glslopt_ctx* glslopt_initialize (glslopt_target target);
void glslopt_cleanup (glslopt_ctx* ctx);
void glslopt_set_max_unroll_iterations (glslopt_ctx* ctx, unsigned iterations);
glslopt_shader* glslopt_optimize (glslopt_ctx* ctx, glslopt_shader_type type, const char* shaderSource, unsigned options);
bool glslopt_get_status (glslopt_shader* shader);
const char* glslopt_get_output (glslopt_shader* shader);
const char* glslopt_get_raw_output (glslopt_shader* shader);
const char* glslopt_get_log (glslopt_shader* shader);
void glslopt_shader_delete (glslopt_shader* shader);
int glslopt_shader_get_input_count (glslopt_shader* shader);
const char* glslopt_shader_get_input_name (glslopt_shader* shader, int index);
// Get *very* approximate shader stats:
// Number of math, texture and flow control instructions.
void glslopt_shader_get_stats (glslopt_shader* shader, int* approxMath, int* approxTex, int* approxFlow);
#endif /* GLSL_OPTIMIZER_H */
| {
"content_hash": "3e9bde50a65df67a10e9a88417decd2c",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 122,
"avg_line_length": 31.06153846153846,
"alnum_prop": 0.7449232293214463,
"repo_name": "kakashidinho/HQEngine",
"id": "6f95f4608b2cc7c2913a5352f3b5cfa8872c9243",
"size": "2019",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ThirdParty-mod/glsl_optimizer/include/glsl_optimizer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "661970"
},
{
"name": "Awk",
"bytes": "32706"
},
{
"name": "Batchfile",
"bytes": "14796"
},
{
"name": "C",
"bytes": "12872998"
},
{
"name": "C#",
"bytes": "76556"
},
{
"name": "C++",
"bytes": "25893894"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "100966"
},
{
"name": "CSS",
"bytes": "23584"
},
{
"name": "DIGITAL Command Language",
"bytes": "36015"
},
{
"name": "GLSL",
"bytes": "7830"
},
{
"name": "HLSL",
"bytes": "20473"
},
{
"name": "HTML",
"bytes": "2060539"
},
{
"name": "Java",
"bytes": "76190"
},
{
"name": "Lex",
"bytes": "13371"
},
{
"name": "M4",
"bytes": "236533"
},
{
"name": "Makefile",
"bytes": "1169529"
},
{
"name": "Module Management System",
"bytes": "17591"
},
{
"name": "Objective-C",
"bytes": "1535348"
},
{
"name": "Objective-C++",
"bytes": "41381"
},
{
"name": "Pascal",
"bytes": "69941"
},
{
"name": "Perl",
"bytes": "35354"
},
{
"name": "RPC",
"bytes": "3150250"
},
{
"name": "Roff",
"bytes": "290354"
},
{
"name": "SAS",
"bytes": "16347"
},
{
"name": "Shell",
"bytes": "986190"
},
{
"name": "Smalltalk",
"bytes": "6052"
},
{
"name": "TeX",
"bytes": "144346"
},
{
"name": "WebAssembly",
"bytes": "14280"
},
{
"name": "XSLT",
"bytes": "75795"
},
{
"name": "Yacc",
"bytes": "15640"
}
],
"symlink_target": ""
} |
#include "ast.hpp"
#include "object.hpp"
#include <memory>
#include <map>
class Memory {
public:
std::shared_ptr<Double> get_value(std::string variable_name) {
return memory[variable_name];
}
void store_value(std::string variable_name, std::shared_ptr<Double> value) {
memory[variable_name] = value;
}
private:
std::map<std::string, std::shared_ptr<Double>> memory;
};
class Interpreter {
public:
std::shared_ptr<Object> evaluate(std::shared_ptr<ASTNode> tree);
private:
Memory memory;
};
#endif // INTERPRETER_HPP
| {
"content_hash": "f67c50a8413339b1adda2864dc900549",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 80,
"avg_line_length": 22.653846153846153,
"alnum_prop": 0.6383701188455009,
"repo_name": "helton-hcs/toy_language_cpp",
"id": "437d432b2bf8c2dff8485e6857c2cb1c0361fc1d",
"size": "639",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "interpreter.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "28355"
}
],
"symlink_target": ""
} |
package com.xpn.xwiki.plugin.lucene.textextraction;
/**
* A text extractor for a specific mime type.
*/
public interface MimetypeTextExtractor
{
public String getText(byte[] data) throws Exception;
}
| {
"content_hash": "518af8bcc98a228b21d370021503af3f",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 56,
"avg_line_length": 20.8,
"alnum_prop": 0.75,
"repo_name": "i2geo/i2gCurriki",
"id": "31eff0dc1d14762b35d95ce08eb954972079265d",
"size": "919",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "plugins/lucene/src/main/java/com/xpn/xwiki/plugin/lucene/textextraction/MimetypeTextExtractor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "34411"
},
{
"name": "Java",
"bytes": "531135"
},
{
"name": "JavaScript",
"bytes": "6295201"
},
{
"name": "Perl",
"bytes": "566"
},
{
"name": "Python",
"bytes": "2066"
},
{
"name": "Shell",
"bytes": "13196"
}
],
"symlink_target": ""
} |
#ifndef __Ogre_Volume_Chunk_H__
#define __Ogre_Volume_Chunk_H__
#include "OgreSimpleRenderable.h"
#include "OgreResourceGroupManager.h"
#include "OgreFrameListener.h"
#include "OgreEntity.h"
#include "OgreVolumePrerequisites.h"
namespace Ogre {
namespace Volume {
class Source;
class MeshBuilderCallback;
class ChunkHandler;
class MeshBuilder;
class DualGridGenerator;
class OctreeNode;
/** Parameters for loading the volume.
*/
typedef struct ChunkParameters
{
/// The scenemanager to construct the entity with.
SceneManager *sceneManager;
/// The volume source.
Source *src;
/// The smallest allowed geometric error of the highest LOD.
Real baseError;
/// The error multiplicator per LOD level with 1.0 as default.
Real errorMultiplicator;
/// Whether to create the octree debug visualization entity with false as default.
bool createOctreeVisualization;
/// Whether to create the dualgrid debug visualization entity with false as default.
bool createDualGridVisualization;
/// Factor for the skirt length generation.
Real skirtFactor;
/// Callback for a specific LOD level.
MeshBuilderCallback *lodCallback;
/// The scale of the volume with 1.0 as default.
Real scale;
/// The maximum accepted screen space error when choosing the LOD levels to render.
Real maxScreenSpaceError;
/// The first LOD level to create geometry for. For scenarios where the lower levels won't be visible anyway. 0 is the default and switches this off.
size_t createGeometryFromLevel;
/// If an existing chunktree is to be partially updated, set this to the back lower left point of the (sub-)cube to be reloaded. Else, set both update vectors to zero (initial load). 1.5 is the default.
Vector3 updateFrom;
/// If an existing chunktree is to be partially updated, set this to the front upper right point of the (sub-)cube to be reloaded. Else, set both update vectors to zero (initial load).
Vector3 updateTo;
/// Whether to load the chunks async. if set to false, the call to load waits for the whole chunk. false is the default.
bool async;
/** Constructor.
*/
ChunkParameters(void) :
sceneManager(0), src(0), baseError((Real)0.0), errorMultiplicator((Real)1.0), createOctreeVisualization(false),
createDualGridVisualization(false), skirtFactor(0), lodCallback(0), scale((Real)1.0), maxScreenSpaceError(0), createGeometryFromLevel(0),
updateFrom(Vector3::ZERO), updateTo(Vector3::ZERO), async(false)
{
}
} ChunkParameters;
/** Internal shared values of the chunks which are equal in the whole tree.
*/
typedef struct ChunkTreeSharedData
{
/// Flag whether the octree is visible or not.
bool octreeVisible;
/// Flag whether the dualgrid is visible or not.
bool dualGridVisible;
/// Another visibility flag to be user setable.
bool volumeVisible;
/// The amount of chunks being processed (== loading).
int chunksBeingProcessed;
/// The parameters with which the chunktree got loaded.
ChunkParameters *parameters;
/** Constructor.
*/
ChunkTreeSharedData(const ChunkParameters *params) : octreeVisible(false), dualGridVisible(false), volumeVisible(true), chunksBeingProcessed(0)
{
this->parameters = new ChunkParameters(*params);
}
/** Destructor.
*/
~ChunkTreeSharedData(void)
{
delete parameters;
}
} ChunkTreeSharedData;
/** A single volume chunk mesh.
*/
class _OgreVolumeExport Chunk : public SimpleRenderable, public FrameListener
{
/// So the actual loading functions can be called.
friend class ChunkHandler;
protected:
/// To handle the WorkQueue.
static ChunkHandler mChunkHandler;
/// To attach this node to.
SceneNode *mNode;
/// Holds the error associated with this chunk.
Real mError;
/// Holds the dualgrid debug visualization.
Entity *mDualGrid;
/// The debug visualization of the octree.
Entity *mOctree;
/// The more detailed children chunks.
Chunk **mChildren;
/// Flag whether this node will never be shown.
bool mInvisible;
/// Whether this chunk is the root of the tree.
bool isRoot;
/// Holds some shared data among all chunks of the tree.
ChunkTreeSharedData *mShared;
/** Loads a single chunk of the tree.
@param parent
The parent scene node for the volume
@param from
The back lower left corner of the cell.
@param to
The front upper right corner of the cell.
@param totalFrom
The back lower left corner of the world.
@param totalTo
The front upper rightcorner of the world.
@param level
The current LOD level.
@param maxLevels
The maximum amount of levels.
*/
virtual void loadChunk(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels);
/** Whether the center of the given cube (from -> to) will contribute something
to the total volume mesh.
@param from
The back lower left corner of the cell.
@param to
The front upper right corner of the cell.
@return
true if triangles might be generated
*/
virtual bool contributesToVolumeMesh(const Vector3 &from, const Vector3 &to) const;
/** Loads the tree children of the current node.
@param parent
The parent scene node for the volume
@param from
The back lower left corner of the cell.
@param to
The front upper right corner of the cell.
@param totalFrom
The back lower left corner of the world.
@param totalTo
The front upper rightcorner of the world.
@param level
The current LOD level.
@param maxLevels
The maximum amount of levels.
*/
virtual void loadChildren(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels);
/** Actually loads the volume tree with all LODs.
@param parent
The parent scene node for the volume
@param from
The back lower left corner of the cell.
@param to
The front upper right corner of the cell.
@param totalFrom
The back lower left corner of the world.
@param totalTo
The front upper rightcorner of the world.
@param level
The current LOD level.
@param maxLevels
The maximum amount of levels.
*/
virtual void doLoad(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels);
/** Prepares the geometry of the chunk request. To be called in a different thread.
@param level
The current LOD level.
@param root
The root of the upcoming Octree (in here) of the chunk.
@param dualGridGenerator
The DualGrid.
@param meshBuilder
The MeshBuilder which will contain the geometry.
@param totalFrom
The back lower left corner of the world.
@param totalTo
The front upper rightcorner of the world.
*/
virtual void prepareGeometry(size_t level, OctreeNode *root, DualGridGenerator *dualGridGenerator, MeshBuilder *meshBuilder, const Vector3 &totalFrom, const Vector3 &totalTo);
/** Loads the actual geometry when the processing is done.
@param meshBuilder
The MeshBuilder holding the geometry.
@param dualGridGenerator
The DualGridGenerator to build up the debug visualization of the DualGrid.
@param root
The root node of the Octree to build up the debug visualization of the Otree.
@param level
The current LOD level.
@param isUpdate
Whether this loading is updating an existing ChunkTree.
*/
virtual void loadGeometry(MeshBuilder *meshBuilder, DualGridGenerator *dualGridGenerator, OctreeNode *root, size_t level, bool isUpdate);
/** Sets the visibility of this chunk.
@param visible
Whether this chunk is visible or not.
@param applyToChildren
Whether all children and subchildren should have their visibility changed, too.
*/
inline void setChunkVisible(const bool visible, const bool applyToChildren)
{
if (mInvisible)
{
return;
}
if (mShared->volumeVisible)
{
mVisible = visible;
}
if (mOctree)
{
mOctree->setVisible(mShared->octreeVisible && visible);
}
if (mDualGrid)
{
mDualGrid->setVisible(mShared->dualGridVisible && visible);
}
if (applyToChildren && mChildren)
{
mChildren[0]->setChunkVisible(visible, applyToChildren);
if (mChildren[1])
{
mChildren[1]->setChunkVisible(visible, applyToChildren);
mChildren[2]->setChunkVisible(visible, applyToChildren);
mChildren[3]->setChunkVisible(visible, applyToChildren);
mChildren[4]->setChunkVisible(visible, applyToChildren);
mChildren[5]->setChunkVisible(visible, applyToChildren);
mChildren[6]->setChunkVisible(visible, applyToChildren);
mChildren[7]->setChunkVisible(visible, applyToChildren);
}
}
}
public:
/// The type name.
static const String MOVABLE_TYPE_NAME;
/** Constructor.
*/
Chunk(void);
/** Destructor.
*/
virtual ~Chunk(void);
/** Overridden from MovableObject.
*/
virtual const String& getMovableType(void) const;
/** Overridden from Renderable.
*/
virtual Real getSquaredViewDepth(const Camera* camera) const;
/** Overridden from MovableObject.
*/
virtual Real getBoundingRadius() const;
/** Loads the volume mesh with all LODs.
@param parent
The parent scene node for the volume
@param from
The back lower left corner of the cell.
@param to
The front upper right corner of the cell.
@param level
The amount of LOD level.
@param parameters
The parameters to use while loading.
*/
virtual void load(SceneNode *parent, const Vector3 &from, const Vector3 &to, size_t level, const ChunkParameters *parameters);
/** Loads a TextureSource volume scene from a config file.
@param parent
The parent scene node for the volume.
@param sceneManager
The scenemanager to construct the entity with.
@param filename
The filename of the configuration file.
@param validSourceResult
If you want to use the loaded source afterwards of the parameters, set this to true. Beware, that you
will have to delete the pointer on your own then! On false here, it internally frees the
memory for you
@param lodCallback
Callback for a specific LOD level.
@param resourceGroup
The resource group where to search for the configuration file.
*/
virtual void load(SceneNode *parent, SceneManager *sceneManager, const String& filename, bool validSourceResult = false, MeshBuilderCallback *lodCallback = 0, const String& resourceGroup = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
/** Shows the debug visualization entity of the dualgrid.
@param visible
Whether the grid should be visible.
*/
virtual void setDualGridVisible(const bool visible);
/** Gets whether the debug visualization entity of the
dualgrid is visible.
@return
true if visible.
*/
virtual bool getDualGridVisible(void) const;
/** Shows the debug visualization entity of the octree.
@param visible
Whether the octree should be visible.
*/
virtual void setOctreeVisible(const bool visible);
/** Gets whether the debug visualization entity of the
octree is visible.
@return
true if visible.
*/
virtual bool getOctreeVisible(void) const;
/** Sets whether the volume mesh is visible.
@param visible
true if visible
*/
virtual void setVolumeVisible(const bool visible);
/** Gets whether the volume mesh is visible.
@return
true if visible
*/
virtual bool getVolumeVisible(void) const;
/** Overridden from FrameListener.
*/
virtual bool frameStarted(const FrameEvent& evt);
/** Overridable factory method.
@return
The created chunk.
*/
virtual Chunk* createInstance(void);
/** Overridden from SimpleRenderable.
Sets the material of this chunk and all of his children.
*/
virtual void setMaterial(const String& matName);
/** Sets the material of all chunks of a specific level in the tree.
This allows LODs where the lower levels (== less detail and more far away)
have simpler materials.
@param level
The tree level getting the material, 0 based. 0 means the chunk with the lowest level of detail.
@param matName
The material name to set.
*/
virtual void setMaterialOfLevel(size_t level, const String& matName);
/** A list of Chunks.
*/
typedef vector<const Chunk*>::type VecChunk;
/** Gathers all visible chunks (containing triangles) of a specific LOD level.
@param level
The desired chunk level, 0 based. 0 means the chunk with the lowest level of detail. If the chunks are loaded with
a level amount of 5, valid values here are 0-4.
@param result
Vector where the chunks will be added to.
*/
virtual void getChunksOfLevel(const size_t level, VecChunk &result) const;
/** Gets the parameters with which the chunktree got loaded.
@return
The parameters.
*/
ChunkParameters* getChunkParameters(void);
};
}
}
#endif | {
"content_hash": "da1550cef2314c279fb580792b7e48d7",
"timestamp": "",
"source": "github",
"line_count": 428,
"max_line_length": 248,
"avg_line_length": 36.27336448598131,
"alnum_prop": 0.607085346215781,
"repo_name": "MTASZTAKI/ApertusVR",
"id": "b9f57d07214629b182139516f74f24cd9e56fff1",
"size": "16884",
"binary": false,
"copies": "2",
"ref": "refs/heads/0.9",
"path": "plugins/render/ogreRender/3rdParty/ogre/Components/Volume/include/OgreVolumeChunk.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7599"
},
{
"name": "C++",
"bytes": "1207412"
},
{
"name": "CMake",
"bytes": "165066"
},
{
"name": "CSS",
"bytes": "1816"
},
{
"name": "GLSL",
"bytes": "223507"
},
{
"name": "HLSL",
"bytes": "141879"
},
{
"name": "HTML",
"bytes": "34827"
},
{
"name": "JavaScript",
"bytes": "140550"
},
{
"name": "Python",
"bytes": "1370"
}
],
"symlink_target": ""
} |
__all__ = ['AutoARIMAProphet']
# %% ../../nbs/adapters.prophet.ipynb 3
import sys
from copy import deepcopy
import pandas as pd
from ..arima import AutoARIMA
if sys.version_info.minor != 6 or (sys.platform not in ["win32", "cygwin"]):
try:
from prophet import Prophet
except ModuleNotFoundError as e:
msg = (
"{e}. To use prophet adapters you have to install "
"prophet. Please run `pip install prophet`. "
"Note that it is recommended to install prophet "
"using conda environments due to dependencies."
)
raise ModuleNotFoundError(msg) from e
elif sys.version_info.minor == 6 and (sys.platform in ["win32", "cygwin"]):
try:
from fbprophet import Prophet
except ModuleNotFoundError as e:
msg = (
"{e}. To use prophet adapters you have to install "
"fbprophet. Please run `pip install fbprophet`. "
"Note that it is recommended to install prophet "
"using conda environments due to dependencies."
)
raise ModuleNotFoundError(msg) from e
# %% ../../nbs/adapters.prophet.ipynb 6
class AutoARIMAProphet(Prophet):
"""AutoARIMAProphet adapter.
Returns best ARIMA model using external variables created by the Prophet interface.
This class receives as parameters the same as prophet.Prophet and uses a `models.AutoARIMA`
backend.
If your forecasting pipeline uses Prophet the `AutoARIMAProphet` adapter helps to
easily substitute Prophet with an AutoARIMA.
**Parameters:**<br>
`growth`: String 'linear', 'logistic' or 'flat' to specify a linear, logistic or flat trend.<br>
`changepoints`: List of dates of potential changepoints. Otherwise selected automatically.<br>
`n_changepoints`: Number of potential changepoints to include.<br>
`changepoint_range`: Proportion of history in which trend changepoints will be estimated.<br>
`yearly_seasonality`: Fit yearly seasonality.
Can be 'auto', True, False, or a number of Fourier terms to generate.<br>
`weekly_seasonality`: Fit weekly seasonality.
Can be 'auto', True, False, or a number of Fourier terms to generate.<br>
`daily_seasonality`: Fit daily seasonality.
Can be 'auto', True, False, or a number of Fourier terms to generate.<br>
`holidays`: pandas.DataFrame with columns holiday (string) and ds (date type).<br>
`interval_width`: float, uncertainty forecast intervals width. `StatsForecast`'s level <br>
**Notes:**<br>
You can create automated exogenous variables from the Prophet data processing pipeline
these exogenous will be included into `AutoARIMA`'s exogenous features. Parameters like
`seasonality_mode`, `seasonality_prior_scale`, `holidays_prior_scale`, `changepoint_prior_scale`,
`mcmc_samples`, `uncertainty_samples`, `stan_backend` are Prophet exclusive.
**References:**<br>
[Sean J. Taylor, Benjamin Letham (2017). "Prophet Forecasting at Scale"](https://peerj.com/preprints/3190.pdf)
[Oskar Triebe, Hansika Hewamalage, Polina Pilyugina, Nikolay Laptev, Christoph Bergmeir, Ram Rajagopal (2021). "NeuralProphet: Explainable Forecasting at Scale".](https://arxiv.org/pdf/2111.15397.pdf)
[Rob J. Hyndman, Yeasmin Khandakar (2008). "Automatic Time Series Forecasting: The forecast package for R"](https://www.jstatsoft.org/article/view/v027i03).
"""
def __init__(
self,
growth="linear",
changepoints=None,
n_changepoints=25,
changepoint_range=0.8,
yearly_seasonality="auto",
weekly_seasonality="auto",
daily_seasonality="auto",
holidays=None,
seasonality_mode="additive",
seasonality_prior_scale=10.0,
holidays_prior_scale=10.0,
changepoint_prior_scale=0.05,
mcmc_samples=0,
interval_width=0.80,
uncertainty_samples=1000,
stan_backend=None,
d=None,
D=None,
max_p=5,
max_q=5,
max_P=2,
max_Q=2,
max_order=5,
max_d=2,
max_D=1,
start_p=2,
start_q=2,
start_P=1,
start_Q=1,
stationary=False,
seasonal=True,
ic="aicc",
stepwise=True,
nmodels=94,
trace=False,
approximation=False,
method=None,
truncate=None,
test="kpss",
test_kwargs=None,
seasonal_test="seas",
seasonal_test_kwargs=None,
allowdrift=False,
allowmean=False,
blambda=None,
biasadj=False,
parallel=False,
num_cores=2,
period=1,
):
Prophet.__init__(
self,
growth,
changepoints,
n_changepoints,
changepoint_range,
yearly_seasonality,
weekly_seasonality,
daily_seasonality,
holidays,
seasonality_mode,
seasonality_prior_scale,
holidays_prior_scale,
changepoint_prior_scale,
mcmc_samples,
interval_width,
uncertainty_samples,
stan_backend,
)
self.arima = AutoARIMA(
d=d,
D=D,
max_p=max_p,
max_q=max_q,
max_P=max_P,
max_Q=max_Q,
max_order=max_order,
max_d=max_d,
max_D=max_D,
start_p=start_p,
start_q=start_q,
start_P=start_P,
start_Q=start_Q,
stationary=stationary,
seasonal=seasonal,
ic=ic,
stepwise=stepwise,
nmodels=nmodels,
trace=trace,
approximation=approximation,
method=method,
truncate=truncate,
test=test,
test_kwargs=test_kwargs,
seasonal_test=seasonal_test,
seasonal_test_kwargs=seasonal_test_kwargs,
allowdrift=allowdrift,
allowmean=allowmean,
blambda=blambda,
biasadj=biasadj,
parallel=parallel,
num_cores=num_cores,
period=period,
)
def fit(self, df, disable_seasonal_features=True, **kwargs):
"""Fit the AutoARIMAProphet adapter.
**Parameters:**<br>
`df`: pandas.DataFrame, with columns ds (date type) and y, the time series.<br>
`disable_seasonal_features`: bool, Wheter disable Prophet's seasonal features.<br>
`kwargs`: Additional arguments.<br>
**Returns:**<br>
`self`: `AutoARIMAProphet` adapter object with `AutoARIMA` fitted model.
"""
if self.history is not None:
raise Exception(
"Prophet object can only be fit once. " "Instantiate a new object."
)
if ("ds" not in df) or ("y" not in df):
raise ValueError(
'Dataframe must have columns "ds" and "y" with the dates and '
"values respectively."
)
history = df[df["y"].notnull()].copy()
if history.shape[0] < 2:
raise ValueError("Dataframe has less than 2 non-NaN rows.")
self.history_dates = pd.to_datetime(
pd.Series(df["ds"].unique(), name="ds")
).sort_values()
history = self.setup_dataframe(history, initialize_scales=True)
self.history = history
self.set_auto_seasonalities()
(
seasonal_features,
prior_scales,
component_cols,
modes,
) = self.make_all_seasonality_features(history)
self.train_component_cols = component_cols
self.component_modes = modes
self.fit_kwargs = deepcopy(kwargs)
if disable_seasonal_features:
seas = tuple(self.seasonalities.keys())
seasonal_features = seasonal_features.loc[
:, ~seasonal_features.columns.str.startswith(seas)
]
self.xreg_cols = seasonal_features.columns
y = history["y"].values
X = seasonal_features.values if not seasonal_features.empty else None
self.arima = self.arima.fit(y=y, X=X)
return self
def predict(self, df=None):
"""Predict using the AutoARIMAProphet adapter.
**Parameters:**<br>
`df`: pandas.DataFrame, with columns ds (date type) and y, the time series.<br>
**Returns:**<br>
`fcsts_df`: A pandas.DataFrame with the forecast components.
"""
if self.history is None:
raise Exception("Model has not been fit.")
if df is None:
df = self.history.copy()
else:
if df.shape[0] == 0:
raise ValueError("Dataframe has no rows.")
df = self.setup_dataframe(df.copy())
seasonal_features = self.make_all_seasonality_features(df)[0].loc[
:, self.xreg_cols
]
ds_forecast = set(df["ds"])
h = len(ds_forecast - set(self.history["ds"]))
if h > 0:
X = seasonal_features.values[-h:] if not seasonal_features.empty else None
fcsts_df = self.arima.predict(
h=h, X=X, level=int(100 * self.interval_width)
)
else:
fcsts_df = pd.DataFrame()
if len(ds_forecast) > h:
in_sample = self.arima.predict_in_sample(
level=int(100 * self.interval_width)
)
fcsts_df = pd.concat([in_sample, fcsts_df]).reset_index(drop=True)
yhat = fcsts_df.pop("mean")
fcsts_df.columns = ["yhat_lower", "yhat_upper"]
fcsts_df.insert(0, "yhat", yhat)
fcsts_df.insert(0, "ds", df["ds"])
return fcsts_df
| {
"content_hash": "d04682a31b8724ce9bff7d9ec31c45b1",
"timestamp": "",
"source": "github",
"line_count": 274,
"max_line_length": 204,
"avg_line_length": 35.7043795620438,
"alnum_prop": 0.5834611060002044,
"repo_name": "Nixtla/statsforecast",
"id": "ae4dea87d9a826a35a6a036d20bdf78a5eef505b",
"size": "9874",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "statsforecast/adapters/prophet.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "904"
},
{
"name": "Dockerfile",
"bytes": "866"
},
{
"name": "Jupyter Notebook",
"bytes": "29577745"
},
{
"name": "Makefile",
"bytes": "2137"
},
{
"name": "Python",
"bytes": "491864"
},
{
"name": "R",
"bytes": "4449"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.jetty;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
public class HttpBridgeAsyncRouteTest extends HttpBridgeRouteTest {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
errorHandler(noErrorHandler());
Processor serviceProc = new Processor() {
public void process(Exchange exchange) {
// get the request URL and copy it to the request body
String uri = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class);
exchange.getMessage().setBody(uri);
}
};
from("jetty:http://localhost:" + port2 + "/test/hello?async=true&useContinuation=false")
.to("http://localhost:" + port1 + "?throwExceptionOnFailure=false&bridgeEndpoint=true");
from("jetty://http://localhost:" + port1 + "?matchOnUriPrefix=true&async=true&useContinuation=false")
.process(serviceProc);
}
};
}
}
| {
"content_hash": "81686cf224f7d1d856407bf0d1500029",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 117,
"avg_line_length": 38.46875,
"alnum_prop": 0.5857026807473599,
"repo_name": "cunningt/camel",
"id": "b0795e6808a0ba6c2d025cb521a5a40d2892f9f9",
"size": "2033",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeAsyncRouteTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6695"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Dockerfile",
"bytes": "5676"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "396363"
},
{
"name": "HTML",
"bytes": "212954"
},
{
"name": "Java",
"bytes": "113234282"
},
{
"name": "JavaScript",
"bytes": "103655"
},
{
"name": "Jsonnet",
"bytes": "1734"
},
{
"name": "Kotlin",
"bytes": "41869"
},
{
"name": "Mustache",
"bytes": "525"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Ruby",
"bytes": "88"
},
{
"name": "Shell",
"bytes": "15221"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "699"
},
{
"name": "XSLT",
"bytes": "276597"
}
],
"symlink_target": ""
} |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
[module: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "LinqKit")]
namespace LinqKit
{
/// <summary>
/// See http://www.albahari.com/expressions for information and examples.
/// </summary>
public static class PredicateBuilder
{
/// <summary>
/// True expression.
/// </summary>
/// <typeparam name="T">The parameter type.</typeparam>
/// <returns>The expression.</returns>
public static Expression<Func<T, bool>> True<T>() { return f => true; }
/// <summary>
/// False expression.
/// </summary>
/// <typeparam name="T">The parameter type.</typeparam>
/// <returns>The expression.</returns>
public static Expression<Func<T, bool>> False<T>() { return f => false; }
/// <summary>
/// Or expression.
/// </summary>
/// <param name="left">The left expression.</param>
/// <param name="right">The right expression.</param>
/// <returns>The expression.</returns>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> left,
Expression<Func<T, bool>> right)
{
var invokedExpr = Expression.Invoke(right, left.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(left.Body, invokedExpr), left.Parameters);
}
/// <summary>
/// And expression.
/// </summary>
/// <param name="left">The left expression.</param>
/// <param name="right">The right expression.</param>
/// <returns>The expression.</returns>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> left,
Expression<Func<T, bool>> right)
{
var invokedExpr = Expression.Invoke(right, left.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(left.Body, invokedExpr), left.Parameters);
}
}
}
| {
"content_hash": "844577eda26e58b6d345590cfc0a512e",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 124,
"avg_line_length": 41.06666666666667,
"alnum_prop": 0.5844155844155844,
"repo_name": "giacomelli/AutoFilter",
"id": "c34c7f43398f63cbba886498b2647a238171d0bc",
"size": "2466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AutoFilter/Expressions/PredicateBuilder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "44952"
}
],
"symlink_target": ""
} |
package com.coolweather.app.activity;
import java.util.ArrayList;
import java.util.List;
import com.coolweather.app.db.CoolWeatherDB;
import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;
import com.example.coolweathers.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.DownloadManager.Query;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ChooseAreaActivity extends Activity {
public static final int LEVEL_PROVINCE =0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private ListView listView;
private ArrayAdapter<String> adapter;
private CoolWeatherDB coolWeatherDB;
private List<String> dataList = new ArrayList<String>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中省份
*/
private Province selectedProvince;
/**
* 选中城市
*/
private City selectedCity;
/**
* 当前选中级别
*/
private int currentLevel;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.choose_area);
listView = (ListView) findViewById(R.id.list_view);
titleText = (TextView) findViewById(R.id.title_text);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,dataList
);
listView.setAdapter(adapter);
coolWeatherDB = CoolWeatherDB.getInstance(this);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
}
}
});
queryProvinces();
}
/**
* 查询全国所有的省,优先从数据库查询,如果没有再去服务器上查询
*/
private void queryProvinces(){
provinceList = coolWeatherDB.loadProvince();
if (provinceList.size()>0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("中国");
currentLevel = LEVEL_PROVINCE;
}else {
queryFromServer(null, "province");
}
}
/**
* 查询选中省内所有的市,优先从数据库查询,如果没有查询再去服务器上查询。
*/
private void queryCities(){
cityList = coolWeatherDB.loadCities(selectedProvince.getId());
if (cityList.size()>0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedProvince.getProvinceName());
currentLevel = LEVEL_CITY;
}else {
queryFromServer(selectedProvince.getProvinceCode(),"city");
}
}
/**
* 查询选中城市内所有的县,优先从数据库查询,如果没有查询到再去服务器
*/
private void queryCounties(){
countyList = coolWeatherDB.loadCounties(selectedCity.getId());
if (countyList.size() >0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedCity.getCityName());
currentLevel = LEVEL_COUNTY;
}else {
queryFromServer(selectedCity.getCityCode(), "county");
}
}
/**
* 根据传入的代号和类型,从服务器上查询省市县数据
*/
private void queryFromServer(final String code,final String type){
String address;
if (!TextUtils.isEmpty(code)) {
address = "http://www.weather.com.cn/data/list3/city"+code+".xml";
}else {
address = "http://www.weather.com.cn/data/list3/city.xml";
}
//showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
// TODO Auto-generated method stub
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvincesResponse(coolWeatherDB, response);
}else if ("city".equals(type)) {
result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId());
}else if ("county".equals(type)) {
result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId());
}
if (result) {
//通过runOnUiThread()方法回到主线程处理逻辑
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
}else if ("city".equals(type)) {
queryCities();
}else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
@Override
public void onError(Exception e) {
// TODO Auto-generated method stub
//通过runOnUiThread()方法回到主线程处理逻辑
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this, "加载失败", 1);
}
});
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog(){
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭对话框
*/
private void closeProgressDialog() {
if (progressDialog !=null) {
progressDialog.dismiss();
}
}
/**
* 捕获Back按键,根据当前的级别来判断,此时应该返回市列表,省列表,还是直接退出
*/
public void onBackPressed(){
if (currentLevel == LEVEL_COUNTY) {
queryCities();
}else if (currentLevel == LEVEL_CITY) {
queryProvinces();
}else{
finish();
}
}
}
| {
"content_hash": "cd0deaa071da5f0a69b4ac3e5be5dd7f",
"timestamp": "",
"source": "github",
"line_count": 242,
"max_line_length": 94,
"avg_line_length": 25.921487603305785,
"alnum_prop": 0.6947234178224135,
"repo_name": "PrinceChou/coolweather",
"id": "53f3f95d1583270ad72db0d8466f64eea69eedc9",
"size": "6733",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/coolweather/app/activity/ChooseAreaActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "50669"
}
],
"symlink_target": ""
} |
"""Command-line sample app demonstrating customer-supplied encryption keys.
This sample demonstrates uploading an object while supplying an encryption key,
retrieving that object's contents, and finally rotating that key to a new
value.
This sample is used on this page:
https://cloud.google.com/storage/docs/json_api/v1/json-api-python-samples
For more information, see the README.md under /storage.
"""
import argparse
import filecmp
import tempfile
import googleapiclient.discovery
import googleapiclient.http
# You can (and should) generate your own encryption key. Here's a good way to
# accomplish this with Python:
# python -c \
# 'import base64; import os; print(base64.encodestring(os.urandom(32)))'
# Although these keys are provided here for simplicity, please remember that it
# is a bad idea to store your encryption keys in your source code.
ENCRYPTION_KEY = '4RzDI0TeWa9M/nAvYH05qbCskPaSU/CFV5HeCxk0IUA='
# You can use openssl to quickly calculate the hash of any key.
# Try running this:
# openssl base64 -d <<< ENCRYPTION_KEY | openssl dgst -sha256 -binary \
# | openssl base64
KEY_HASH = 'aanjNC2nwso8e2FqcWILC3/Tt1YumvIwEj34kr6PRpI='
ANOTHER_ENCRYPTION_KEY = 'oevtavYZC+TfGtV86kJBKTeytXAm1s2r3xIqam+QPKM='
ANOTHER_KEY_HASH = '/gd0N3k3MK0SEDxnUiaswl0FFv6+5PHpo+5KD5SBCeA='
def create_service():
"""Creates the service object for calling the Cloud Storage API."""
# Construct the service object for interacting with the Cloud Storage API -
# the 'storage' service, at version 'v1'.
# You can browse other available api services and versions here:
# https://developers.google.com/api-client-library/python/apis/
return googleapiclient.discovery.build('storage', 'v1')
def upload_object(bucket, filename, encryption_key, key_hash):
"""Uploads an object, specifying a custom encryption key."""
service = create_service()
with open(filename, 'rb') as f:
request = service.objects().insert(
bucket=bucket, name=filename,
# You can also just set media_body=filename, but for the sake of
# demonstration, pass in the more generic file handle, which could
# very well be a StringIO or similar.
media_body=googleapiclient.http.MediaIoBaseUpload(
f, 'application/octet-stream'))
request.headers['x-goog-encryption-algorithm'] = 'AES256'
request.headers['x-goog-encryption-key'] = encryption_key
request.headers['x-goog-encryption-key-sha256'] = key_hash
resp = request.execute()
return resp
def download_object(bucket, obj, out_file, encryption_key, key_hash):
"""Downloads an object protected by a custom encryption key."""
service = create_service()
request = service.objects().get_media(bucket=bucket, object=obj)
request.headers['x-goog-encryption-algorithm'] = 'AES256'
request.headers['x-goog-encryption-key'] = encryption_key
request.headers['x-goog-encryption-key-sha256'] = key_hash
# Unfortunately, http.MediaIoBaseDownload overwrites HTTP headers,
# and so it cannot be used here. Instead, we shall download as a
# single request.
out_file.write(request.execute())
def rotate_key(bucket, obj, current_encryption_key, current_key_hash,
new_encryption_key, new_key_hash):
"""Changes the encryption key used to store an existing object."""
service = create_service()
request = service.objects().rewrite(
sourceBucket=bucket, sourceObject=obj,
destinationBucket=bucket, destinationObject=obj,
body={})
# For very large objects, calls to rewrite may not complete on the first
# call and may need to be resumed.
while True:
request.headers.update({
'x-goog-copy-source-encryption-algorithm': 'AES256',
'x-goog-copy-source-encryption-key': current_encryption_key,
'x-goog-copy-source-encryption-key-sha256': current_key_hash,
'x-goog-encryption-algorithm': 'AES256',
'x-goog-encryption-key': new_encryption_key,
'x-goog-encryption-key-sha256': new_key_hash})
rewrite_response = request.execute()
if rewrite_response['done']:
break
print('Continuing rewrite call...')
request = service.objects().rewrite(
source_bucket=bucket, source_object=obj,
destination_bucket=bucket, destination_object=obj,
rewriteToken=rewrite_response['rewriteToken'])
rewrite_response.execute()
def main(bucket, filename):
print('Uploading object gs://{}/{}'.format(bucket, filename))
upload_object(bucket, filename, ENCRYPTION_KEY, KEY_HASH)
print('Downloading it back')
with tempfile.NamedTemporaryFile(mode='w+b') as tmpfile:
download_object(bucket, filename, tmpfile, ENCRYPTION_KEY, KEY_HASH)
tmpfile.seek(0)
assert filecmp.cmp(filename, tmpfile.name), \
'Downloaded file has different content from the original file.'
print('Rotating its key')
rotate_key(bucket, filename, ENCRYPTION_KEY, KEY_HASH,
ANOTHER_ENCRYPTION_KEY, ANOTHER_KEY_HASH)
print('Done')
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('bucket', help='Your Cloud Storage bucket.')
parser.add_argument('filename', help='A file to upload and download.')
args = parser.parse_args()
main(args.bucket, args.filename)
| {
"content_hash": "adef7e04060042722780d2ebab118538",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 79,
"avg_line_length": 39.20979020979021,
"alnum_prop": 0.6873550918494739,
"repo_name": "GoogleCloudPlatform/python-docs-samples",
"id": "4ddd4e78ccaac44e0570fc942598c859d18b4608",
"size": "6233",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "storage/api/customer_supplied_keys.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8008"
},
{
"name": "Dockerfile",
"bytes": "62031"
},
{
"name": "HTML",
"bytes": "69878"
},
{
"name": "JavaScript",
"bytes": "26494"
},
{
"name": "Jinja",
"bytes": "1892"
},
{
"name": "Jupyter Notebook",
"bytes": "47951698"
},
{
"name": "Makefile",
"bytes": "932"
},
{
"name": "Procfile",
"bytes": "138"
},
{
"name": "PureBasic",
"bytes": "11115"
},
{
"name": "Python",
"bytes": "5323502"
},
{
"name": "Shell",
"bytes": "78261"
}
],
"symlink_target": ""
} |
var express = require('express');
var querystring = require('querystring');
var http = require('http');
var util = require('util');
var env = process.env.NODE_ENV || 'development';
var config = require('../config');
var servers = {
java: config('java'),
cloud: config('cloud'),
php: config('php')
};
var request = {
actions: {
login: ['/agentbackground/{userName}/login', 'login.json'],
accessToken: ['/passport/token/getAccessToken.do', 'accessToken.json', 'cloud'],
myphotos: ['/agentbackground/{userName}/agent/list', 'myphotos.json']
},
getServer: function(actionKey) {
return servers[this.actions[actionKey][2] || 'java'];
},
getAction: function(actionKey, data) {
var actionConfig = this.actions[actionKey];
var path = actionConfig[0];
if (data) {
for (var i in data) {
path = path.replace('{' + i + '}', data[i]);
}
}
var server = this.getServer(actionKey);
return {
host: server.host,
port: server.port || 80,
path: path,
mock: actionConfig[1]
};
},
request: function(opts, data, callback) {
var postData;
// An object of options to indicate where to post to
var options = util._extend({
// host: 'localhost',
// port: '3000',
// path: '/hello',
// method: 'GET'
}, opts);
if (opts.method == 'POST') {
// Build the post string from an object
postData = data ? querystring.stringify(data) : '';
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
};
}
if (opts.method == 'GET') {
// Build the post string from an object
var query = data ? querystring.stringify(data) : '';
if (query) {
options.path += '?' + query;
}
options.headers = {};
}
var errorMsg = {
error: true,
msg: 'response parse error'
};
// callback once
var done = false;
function __callback(data){
if (done) {
return;
}
done = true;
if (typeof callback == 'function') {
callback(data);
}
}
// Set up the request
var req = http.request(options, function(res) {
res.setEncoding('utf8');
var data = '';
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
try {
data = JSON.parse(data);
} catch (e) {
console.error('\x1b[4m\x1b[31mProblem with request end\x1b[39m\x1b[24m', JSON.stringify(options), e.message, data);
data = errorMsg;
}
__callback(data);
});
});
req.on('error', function(e) {
console.error('\x1b[4m\x1b[31mProblem with request error\x1b[39m\x1b[24m', JSON.stringify(options), e.message);
__callback(errorMsg);
});
// req.setTimeout(3000, function() {
// console.log('\x1b[4m\x1b[31mProblem with request timeout\x1b[39m\x1b[24m', JSON.stringify(options));
// req.abort();
// __callback(errorMsg);
// });
if (postData) {
// write data to request body
req.write(postData);
}
req.end();
},
mock: function(name, callback, noCache) {
// delete mock cache
if (noCache) {
delete require.cache[require.resolve('../mock/' + name)];
}
callback(require('../mock/' + name));
},
// post with mock
// path: Array([path, mockPath]) or String(path)
post: function(actionKey, data, callback) {
var opts = this.getAction(actionKey, data);
if (env == 'development') {
this.mock(opts.mock, callback, true);
return;
}
opts.method = 'POST';
// console.log('\x1b[4m\x1b[31mPOST\x1b[39m\x1b[24m', opts, data);
this.request(opts, data, callback);
},
get: function(actionKey, data, callback) {
var opts = this.getAction(actionKey, data);
if (env == 'development') {
this.mock(opts.mock, callback, true);
return;
}
opts.method = 'GET';
// console.log('GET', opts, data);
this.request(opts, data, callback);
}
};
module.exports = request;
| {
"content_hash": "97ac80729f7c09a21148ed939f5262be",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 125,
"avg_line_length": 24.5207100591716,
"alnum_prop": 0.5675675675675675,
"repo_name": "justinyueh/express-react",
"id": "39c37bb035a6f0daf4fdf2a4f85247d5c582494b",
"size": "4144",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "libs/request.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14830"
},
{
"name": "HTML",
"bytes": "904"
},
{
"name": "JavaScript",
"bytes": "39267"
}
],
"symlink_target": ""
} |
package pr.tongson.packutil.task;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
/**
* <b>Project:</b> ${file_name}<br>
* <b>Create Date:</b> 2017/2/22<br>
* <b>Author:</b> mmc_Kongming_Tongson<br>
* <b>Description:</b> <br>
*/
public class HelloGradleTask extends DefaultTask {
@TaskAction
// 加上这个action的作用是当执行这个task的时候会自动执行这个方法
void sayHello(){
System.out.println("Hello Gradle Custom Task");
}
}
| {
"content_hash": "b48c5fcbab21699a64e1d871ce44e75d",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 55,
"avg_line_length": 24.36842105263158,
"alnum_prop": 0.67170626349892,
"repo_name": "gepriniusce/TongsonPlay",
"id": "5bc06ceb457c9cc86c8b82ae476741b4900ccc6a",
"size": "513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packutil/src/main/groovy/pr/tongson/packutil/task/HelloGradleTask.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "4549"
},
{
"name": "Java",
"bytes": "18708"
}
],
"symlink_target": ""
} |
SUBDIR+= ipf ipfs ipfstat ipftest ipmon ipnat ippool ipresend
SUBDIR+= ipsend iptest
.include <bsd.subdir.mk>
| {
"content_hash": "b24099361a776f4d8fdcb97d5467db78",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 61,
"avg_line_length": 27.75,
"alnum_prop": 0.7837837837837838,
"repo_name": "execunix/vinos",
"id": "dc287d79a73be2ce4616e7382df414919185f515",
"size": "173",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "external/bsd/ipf/bin/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<h1>This is where content will be projected</h1>
<ng-content select=".test-1"></ng-content>
<h1>Another projection</h1>
<ng-content select=".test-2"></ng-content> | {
"content_hash": "d9a833cf81ea7cf06a79b7ad434769ed",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 48,
"avg_line_length": 41.5,
"alnum_prop": 0.6987951807228916,
"repo_name": "shopOFF/TelerikAcademyCourses",
"id": "d03eb9e7e512cd7ae16ee32b60d7ec8c68015059",
"size": "166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Angular/Topics/03. Components/demos/content-projection/src/app/my/my.component.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "515567"
},
{
"name": "Batchfile",
"bytes": "2565"
},
{
"name": "C#",
"bytes": "4970351"
},
{
"name": "CSS",
"bytes": "1118468"
},
{
"name": "CoffeeScript",
"bytes": "8662"
},
{
"name": "HTML",
"bytes": "5364277"
},
{
"name": "Haskell",
"bytes": "6069"
},
{
"name": "JavaScript",
"bytes": "7198488"
},
{
"name": "Makefile",
"bytes": "100"
},
{
"name": "PowerShell",
"bytes": "468"
},
{
"name": "SQLPL",
"bytes": "10873"
},
{
"name": "Shell",
"bytes": "204"
},
{
"name": "Smalltalk",
"bytes": "6"
},
{
"name": "XSLT",
"bytes": "5210"
}
],
"symlink_target": ""
} |
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
| {
"content_hash": "62bccae2cdeed4f9f54c6cfc0681a734",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 90,
"avg_line_length": 31.6,
"alnum_prop": 0.6582278481012658,
"repo_name": "WangSongAA/WS_MVVM_RAC",
"id": "ac2aa6e3901a61d4737429780f8d2b7310f02a2d",
"size": "329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WS_MVVM_RAC/WS_MVVM_RAC/main.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "13187"
},
{
"name": "Ruby",
"bytes": "147"
}
],
"symlink_target": ""
} |
package com.example.tests;
public class Sample {
public static void main(String[] args) {
String line = "name1929093184,header258853482,footer999643423";
System.out.println(line.split(",").length);
}
}
| {
"content_hash": "b4a4a001dc6250ffd67bc6715955dd11",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 64,
"avg_line_length": 20.9,
"alnum_prop": 0.7368421052631579,
"repo_name": "alisakhaliullina/JavaHomeWork",
"id": "f08a5cdce54c9aca469832d7159f73f0df439e83",
"size": "209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AddressBook-AutoTests/src/com/example/tests/Sample.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5337"
},
{
"name": "HTML",
"bytes": "22465"
},
{
"name": "Java",
"bytes": "72825"
},
{
"name": "JavaScript",
"bytes": "3555"
}
],
"symlink_target": ""
} |
.class Landroid/support/v4/content/q;
.super Ljava/util/concurrent/FutureTask;
# annotations
.annotation system Ldalvik/annotation/Signature;
value = {
"Ljava/util/concurrent/FutureTask",
"<TResult;>;"
}
.end annotation
# instance fields
.field final synthetic a:Landroid/support/v4/content/ModernAsyncTask;
# direct methods
.method constructor <init>(Landroid/support/v4/content/ModernAsyncTask;Ljava/util/concurrent/Callable;)V
.locals 0
iput-object p1, p0, Landroid/support/v4/content/q;->a:Landroid/support/v4/content/ModernAsyncTask;
invoke-direct {p0, p2}, Ljava/util/concurrent/FutureTask;-><init>(Ljava/util/concurrent/Callable;)V
return-void
.end method
# virtual methods
.method protected done()V
.locals 3
:try_start_0
invoke-virtual {p0}, Landroid/support/v4/content/q;->get()Ljava/lang/Object;
move-result-object v0
iget-object v1, p0, Landroid/support/v4/content/q;->a:Landroid/support/v4/content/ModernAsyncTask;
invoke-static {v1, v0}, Landroid/support/v4/content/ModernAsyncTask;->b(Landroid/support/v4/content/ModernAsyncTask;Ljava/lang/Object;)V
:try_end_0
.catch Ljava/lang/InterruptedException; {:try_start_0 .. :try_end_0} :catch_0
.catch Ljava/util/concurrent/ExecutionException; {:try_start_0 .. :try_end_0} :catch_1
.catch Ljava/util/concurrent/CancellationException; {:try_start_0 .. :try_end_0} :catch_2
.catch Ljava/lang/Throwable; {:try_start_0 .. :try_end_0} :catch_3
:goto_0
return-void
:catch_0
move-exception v0
const-string v1, "AsyncTask"
invoke-static {v1, v0}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/Throwable;)I
goto :goto_0
:catch_1
move-exception v0
new-instance v1, Ljava/lang/RuntimeException;
const-string v2, "An error occured while executing doInBackground()"
invoke-virtual {v0}, Ljava/util/concurrent/ExecutionException;->getCause()Ljava/lang/Throwable;
move-result-object v0
invoke-direct {v1, v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V
throw v1
:catch_2
move-exception v0
iget-object v0, p0, Landroid/support/v4/content/q;->a:Landroid/support/v4/content/ModernAsyncTask;
const/4 v1, 0x0
invoke-static {v0, v1}, Landroid/support/v4/content/ModernAsyncTask;->b(Landroid/support/v4/content/ModernAsyncTask;Ljava/lang/Object;)V
goto :goto_0
:catch_3
move-exception v0
new-instance v1, Ljava/lang/RuntimeException;
const-string v2, "An error occured while executing doInBackground()"
invoke-direct {v1, v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V
throw v1
.end method
| {
"content_hash": "e9fbb13f928dc03921c7bd9150dae289",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 140,
"avg_line_length": 29.5625,
"alnum_prop": 0.6888653981677237,
"repo_name": "machinahub/MiBandDecompiled",
"id": "e890866f02227a50807cc5fb1ea89982a780ab81",
"size": "2838",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Original Files/apktool/Mi/smali/android/support/v4/content/q.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "109824"
},
{
"name": "Java",
"bytes": "8906016"
},
{
"name": "Lua",
"bytes": "134432"
},
{
"name": "Smali",
"bytes": "48075881"
}
],
"symlink_target": ""
} |
package com.yalin.fidoclient.net;
import com.android.volley.Request;
import com.android.volley.Response;
import com.yalin.fidoclient.net.response.BaseResponse;
import java.util.Map;
/**
* Created by 雅麟 on 2015/3/21.
*/
public class GetRequest<T extends BaseResponse> extends BaseRequest<T> {
public GetRequest(String url, Class<T> cls, Map<String, String> header, Response.Listener listener, Response.ErrorListener errorListener) {
super(Request.Method.GET, url, cls, header, listener, errorListener);
}
public GetRequest(String url, Class<T> cls, Response.Listener listener, Response.ErrorListener errorListener) {
this(url, cls, null, listener, errorListener);
}
} | {
"content_hash": "47dd0e765ae37ea53d5345940cfecaaf",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 143,
"avg_line_length": 28.36,
"alnum_prop": 0.7404795486600846,
"repo_name": "jinkg/UAFClient",
"id": "7ffe4a186fea434f56400dacdc04df8c8563d2e4",
"size": "1304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fidoclient/src/main/java/com/yalin/fidoclient/net/GetRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "209283"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\Form;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
interface FormTypeInterface
{
/**
* Builds the form.
*
* This method is called for each type in the hierarchy starting from the
* top most type. Type extensions can further modify the form.
*
* @see FormTypeExtensionInterface::buildForm()
*
* @param FormBuilderInterface $builder The form builder
* @param array $options The options
*/
public function buildForm(FormBuilderInterface $builder, array $options);
/**
* Builds the form view.
*
* This method is called for each type in the hierarchy starting from the
* top most type. Type extensions can further modify the view.
*
* A view of a form is built before the views of the child forms are built.
* This means that you cannot access child views in this method. If you need
* to do so, move your logic to {@link finishView()} instead.
*
* @see FormTypeExtensionInterface::buildView()
*
* @param FormView $view The view
* @param FormInterface $form The form
* @param array $options The options
*/
public function buildView(FormView $view, FormInterface $form, array $options);
/**
* Finishes the form view.
*
* This method gets called for each type in the hierarchy starting from the
* top most type. Type extensions can further modify the view.
*
* When this method is called, views of the form's children have already
* been built and finished and can be accessed. You should only implement
* such logic in this method that actually accesses child views. For everything
* else you are recommended to implement {@link buildView()} instead.
*
* @see FormTypeExtensionInterface::finishView()
*
* @param FormView $view The view
* @param FormInterface $form The form
* @param array $options The options
*/
public function finishView(FormView $view, FormInterface $form, array $options);
/**
* Sets the default options for this type.
*
* @param OptionsResolverInterface $resolver The resolver for the options
*
* @deprecated since version 2.7, to be renamed in 3.0.
* Use the method configureOptions instead. This method will be
* added to the FormTypeInterface with Symfony 3.0.
*/
public function setDefaultOptions(OptionsResolverInterface $resolver);
/**
* Returns the name of the parent type.
*
* You can also return a type instance from this method, although doing so
* is discouraged because it leads to a performance penalty. The support
* for returning type instances may be dropped from future releases.
*
* Returning a {@link FormTypeInterface} instance is deprecated since
* Symfony 2.8 and will be unsupported as of Symfony 3.0. Return the
* fully-qualified class name of the parent type instead.
*
* @return string|FormTypeInterface|null The name of the parent type if any, null otherwise
*/
public function getParent();
/**
* Returns the name of this type.
*
* @return string The name of this type
*
* @deprecated Deprecated since Symfony 2.8, to be removed in Symfony 3.0.
* Use the fully-qualified class name of the type instead.
*/
public function getName();
}
| {
"content_hash": "1007df7ff957ca07b2615d85f5535480",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 95,
"avg_line_length": 36.13131313131313,
"alnum_prop": 0.6594911937377691,
"repo_name": "OndraM/symfony",
"id": "3c095ab2bb01e3858b8efc0fd5330b4de99e438a",
"size": "3806",
"binary": false,
"copies": "3",
"ref": "refs/heads/2.8",
"path": "src/Symfony/Component/Form/FormTypeInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "8656"
},
{
"name": "CSS",
"bytes": "10309"
},
{
"name": "HTML",
"bytes": "245239"
},
{
"name": "PHP",
"bytes": "11622407"
},
{
"name": "Shell",
"bytes": "643"
},
{
"name": "TypeScript",
"bytes": "195"
}
],
"symlink_target": ""
} |
<?php
class Nexcessnet_Turpentine_Model_PageCache_Container_Notices
extends Enterprise_PageCache_Model_Container_Abstract {
/**
* Generate placeholder content before application was initialized and apply to page content if possible
*
* @param string $content
* @return boolean
*/
public function applyWithoutApp( &$content ) {
return false;
}
/**
* Render block content
*
* @return string
*/
protected function _renderBlock() {
$block = new Nexcessnet_Turpentine_Block_Notices();
$block->setTemplate( 'turpentine/notices.phtml' );
return $block->toHtml();
}
}
| {
"content_hash": "139e8a9bfa209316036e798fff654a8a",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 108,
"avg_line_length": 23.137931034482758,
"alnum_prop": 0.6333830104321908,
"repo_name": "mikrotikAhmet/mbe-cpdev",
"id": "670aac48f3b8fd94e43d6ef82bd19878005af693",
"size": "1488",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "app/code/community/Nexcessnet/Turpentine/Model/PageCache/Container/Notices.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "19946"
},
{
"name": "ApacheConf",
"bytes": "1148"
},
{
"name": "Batchfile",
"bytes": "1036"
},
{
"name": "C",
"bytes": "653"
},
{
"name": "CSS",
"bytes": "2469504"
},
{
"name": "HTML",
"bytes": "6706314"
},
{
"name": "JavaScript",
"bytes": "1271689"
},
{
"name": "PHP",
"bytes": "50903014"
},
{
"name": "Perl",
"bytes": "30260"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Ruby",
"bytes": "288"
},
{
"name": "Shell",
"bytes": "11651"
},
{
"name": "XSLT",
"bytes": "2135"
}
],
"symlink_target": ""
} |
package jsonconf
import (
"bytes"
"encoding/json"
"io/ioutil"
)
var (
dQuto = byte('"')
slash = byte('/')
backslash = byte('\\')
lineBreak = []byte{'\n'}
comment = []byte{slash, slash}
)
// ParseJSONFile parse config from file
func ParseJSONFile(filename string, v interface{}) error {
data, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
return ParseJSONData(data, v)
}
// ParseJSONData parse config by given data
func ParseJSONData(data []byte, v interface{}) error {
data = StripJSONOneLineComments(data)
err := json.Unmarshal(data, &v)
if err != nil {
return err
}
return nil
}
// StripJSONOneLineComments strip json data "//" comments
func StripJSONOneLineComments(data []byte) []byte {
datas := bytes.Split(data, lineBreak)
var slashNum = 0
inEscape := false
inDQuto := false
for k, line := range datas {
// reset
slashNum = 0
inEscape = false
inDQuto = false
line = bytes.TrimSpace(line)
if cmtIdx := bytes.Index(line, comment); cmtIdx == -1 { // this line no comment
continue
} else if cmtIdx == 0 {
datas[k] = lineBreak
continue
}
for i := 0; i < len(line); i++ {
if inEscape {
inEscape = !inEscape
continue // continue all escaped letter
}
switch line[i] {
case backslash:
inEscape = !inEscape
case dQuto:
inDQuto = !inDQuto
}
if line[i] == slash {
slashNum++
} else if slashNum > 0 {
slashNum = 0
}
if slashNum == 2 && !inDQuto {
datas[k] = line[:i-1]
break
}
}
}
return bytes.Join(datas, lineBreak)
}
| {
"content_hash": "2d892977cf77a6ca21a2a9c9baab4a9d",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 81,
"avg_line_length": 18.50588235294118,
"alnum_prop": 0.6268277177368087,
"repo_name": "iyidan/http-proxy-amqp",
"id": "59011dd002a3076b77d7b3152123fdd28efd4125",
"size": "1573",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsonconf/jsonconf.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "23994"
}
],
"symlink_target": ""
} |
/*
Look into a directory, analyze source code files and returns a json object with code metrics and relations.
*/
"use strict";
var fs = require('fs')
var path = require('path')
var decomment = require('decomment');
var recursive = require('recursive-readdir')
var util = require('./util.js')
var xml2js = require('xml2js')
var inspect = require('eyes').inspector({maxLength: false})
// var cheerio = require('cheerio')
var htmlparser = require("htmlparser2")
var analysisResult = {
path: '',
files: [],
metrics: {}
}
/*
Clone object helper
*/
var clone = (obj) => {
return JSON.parse(JSON.stringify(obj));
}
var newAnalysisResult = () => {
return clone(analysisResult)
}
var readdirPromise = (dirName) => {
return new Promise((resolve, reject) => {
recursive(dirName, function (err, files) {
if (err) {
reject(err)
return
}
resolve(files)
})
})
}
var removeComments = (content) => {
return new Promise((resolve, reject) => {
// transform cfml comments into html comments
var decommentedCode = content
.replace(new RegExp('<!---', 'g'), '<!--')
.replace(new RegExp('--->', 'g'), '-->')
// remove html comments
decommentedCode = decomment.html(decommentedCode)
resolve(decommentedCode)
})
}
//deprecated
var getIncludes = (dirName, content) => {
return new Promise((resolve, reject) => {
var includes = []
// find coldfusion cfinclude tags
var includeTags = content.match(/<cfinclude[\s\S]*?>/gm)
if (includeTags) {
includeTags.forEach(function(includeTag) {
var re = / template="([^"]*)"/
var matchResult = includeTag.match(re)
if (matchResult) {
var includeTemplate = matchResult[1]
if (includeTemplate.charAt(0) !== '/')
includeTemplate = path.join(path.dirname(dirName), includeTemplate)
/*
if (includeTemplate === "/adminmenu.cfm"){
//console.log(dirName)
console.log(includeTemplate)
// console.log(path.dirname(dirName))
}*/
// add each include template name to the currentFile includes list
includes.push(includeTemplate)
}
})
}
resolve(includes)
})
}
var analyzeFile = (filePath, dirName) => {
return new Promise((resolve, reject) => {
var currentFile = {
file: filePath.replace(dirName, ""),
includes: []
}
util.readFileContent(filePath)
.then(content => removeComments(content))
.then(content => getIncludes(currentFile.file, content))
.then(includes => currentFile.includes = includes)
.then(() => resolve(currentFile))
})
}
// module functions
var analyze = function(dirName) {
// analyze source code
return new Promise((resolve, reject) => {
// validate path
fs.exists(dirName, (exists) => {
if (!exists)
reject('directory [' + dirName + '] do not exists!')
else {
// initialize analysis result
var result = newAnalysisResult()
result.path = path.normalize(dirName)
// read all files
readdirPromise(dirName)
.then(files => Promise.all(files.map(file => analyzeFile(file, result.path))))
.then(data => {
result.files = data
resolve(result)
})
}
})
})
}
var parseXML = function(filePath) {
// returns a new promise
return new Promise((resolve, reject) => {
/*
var parser = new htmlparser.Parser({
onopentag: function(name, attribs){
console.log('opentag: ' + name)
inspect(attribs)
},
ontext: function(text){
console.log('text: ' + text)
},
onclosetag: function(name){
console.log('closetag: ' + name)
}},
{decodeEntities: true})
*/
util.readFileContent(filePath)
.then(content => {
var rawHtml = content;
var handler = new htmlparser.DomHandler(function (error, dom) {
if (error)
console.log('ERROR - ' + error)
else
console.log(dom)
})
var parser = new htmlparser.Parser(handler, {withDomLvl1: false, decodeEntities: true, withStartIndices: true, });
parser.write(rawHtml);
parser.done();
resolve('eze')
//parser.write(content)
//parser.end()
})
//var content = cheerio.load('<cfinclude template="file2.cfm" />')
/*
util.readFileContent(filePath)
.then(content => removeComments(content))
.then(content => {
var $ = cheerio.load(content)
//var inner = $('cffunction').children()
var inner = $.root()[0].serializeArray()
//var inner = $.root()[0].childNodes
console.log(inner)
//inspect(cfml().each(item => console.log(item)))
return 'eze'
})
.then(content => resolve(content))
*/
/*
util.readFileContent(filePath)
.then(content => cheerio.load(content))
.then(content => console.log(content))
.then(content => content.root().toArray())
.then(content => resolve(content))
*/
//var parser = new xml2js.Parser({strict: false, async: true})
//console.log(content.root().toArray())
//resolve(content.root().toArray())
/*
// read and parse file
util.readFileContent(filePath)
//.then(content => removeComments(content))
.then(content => {
parser.parseString(content, (err, result) => {
if (err) {
reject(err)
}
else {
resolve(result)
}
})
})
//.then(tokens => resolve(JSON.stringify(tokens)))
//.then(content => resolve(content))
*/
})
}
// exports
module.exports.newAnalysisResult = newAnalysisResult;
module.exports.analyze = analyze;
module.exports.parseXML = parseXML;
| {
"content_hash": "2ef3f636f153f4d879be8f64189755dd",
"timestamp": "",
"source": "github",
"line_count": 249,
"max_line_length": 120,
"avg_line_length": 23.3574297188755,
"alnum_prop": 0.5895804676753783,
"repo_name": "ORC-RIS/cf-code-metrics",
"id": "6ebb1327bb3e941bbeef17977191239fc8a8c5e5",
"size": "5816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc-gen/legacy_code/analyzer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ColdFusion",
"bytes": "276"
},
{
"name": "HTML",
"bytes": "449"
},
{
"name": "JavaScript",
"bytes": "53010"
},
{
"name": "Vue",
"bytes": "15255"
}
],
"symlink_target": ""
} |
@echo off
rem Author: Andrey Dibrov (andry at inbox dot ru)
rem Description:
rem Script detects native Windows cmd.exe.
rem Returns 0 if it is, and 1 - if not.
if not defined COMSPEC exit /b 1
call :CHECK "%%COMSPEC%%"
exit /b
:CHECK
if not "%~nx1" == "cmd.exe" exit /b 2
exit /b 0
| {
"content_hash": "bb83e911f45d45c5f56a21f616ad3d78",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 51,
"avg_line_length": 19.3125,
"alnum_prop": 0.6375404530744336,
"repo_name": "andry81/contools",
"id": "ce0dd23b1e2f16e87eb6d5386240cb44a7918cdb",
"size": "309",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "Scripts/Tools/isnativecmd.bat",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "959036"
},
{
"name": "C",
"bytes": "7239"
},
{
"name": "C++",
"bytes": "1047092"
},
{
"name": "HTML",
"bytes": "2134"
},
{
"name": "JavaScript",
"bytes": "11776"
},
{
"name": "Perl",
"bytes": "20305"
},
{
"name": "Python",
"bytes": "18433"
},
{
"name": "Shell",
"bytes": "445345"
},
{
"name": "Smarty",
"bytes": "80952"
},
{
"name": "Tcl",
"bytes": "1519"
},
{
"name": "VBA",
"bytes": "635"
},
{
"name": "VBScript",
"bytes": "93894"
},
{
"name": "XSLT",
"bytes": "4303"
},
{
"name": "sed",
"bytes": "6718"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Sing a Song of Sixpence | Nursery Rhymes and Traditional Poems | Traditional | Lit2Go ETC</title>
<link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" defer src="http://etc.usf.edu/lit2go/js/js.min.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5574891-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
$(document).ready(function() {
$('img').unveil();
$('#contactable').contactable({
url: 'http://etc.usf.edu/lit2go/welcome/feedback/',
subject: 'Lit2Go Feedback — Sing a Song of Sixpence | Nursery Rhymes and Traditional Poems | Traditional — http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5351/sing-a-song-of-sixpence/'
});
});
</script>
</head>
<body>
<div class="page"> <header>
<h1>
<a href="http://etc.usf.edu/lit2go/">Lit<span class="blue">2</span>Go</a>
</h1>
<ul>
<li id="search"><form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form></li>
</ul>
</header>
<nav id="shell">
<ul>
<li><a href="http://etc.usf.edu/lit2go/authors/" class="">Authors</a></li>
<li><a href="http://etc.usf.edu/lit2go/books/" class="selected">Books</a></li>
<li><a href="http://etc.usf.edu/lit2go/genres/" class="">Genres</a></li>
<li><a href="http://etc.usf.edu/lit2go/collections/" class="">Collections</a></li>
<li><a href="http://etc.usf.edu/lit2go/readability/" class="">Readability</a></li>
</ul>
</nav>
<section id="content">
<div id="contactable"><!-- contactable html placeholder --></div>
<div id="page_content">
<header>
<h2>
<a href="http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/">Nursery Rhymes and Traditional Poems</a>
</h2>
<h3>
by <a href="http://etc.usf.edu/lit2go/authors/194/fcit/">FCIT</a>
</h3>
</header>
<h4>
Sing a Song of Sixpence </h4>
<h5>
by <a href="http://etc.usf.edu/lit2go/authors/195/traditional/">Traditional</a>
</h5>
<div id="poem">
<details open>
<summary>
Additional Information
</summary>
<div id="columns">
<ul>
<li>
<strong>Year Published:</strong>
0 </li>
<li>
<strong>Language:</strong>
English </li>
<li>
<strong>Country of Origin:</strong>
United States of America </li>
<li>
<strong>Source:</strong>
- </li>
</ul>
</div>
<div id="columns">
<ul>
<li>
<strong>Readability:</strong>
<ul>
<li>
Flesch–Kincaid Level:
<a href="http://etc.usf.edu/lit2go/readability/flesch_kincaid_grade_level/2/" title="Flesch–Kincaid Grade Level 2.6">2.6</a>
</li>
</ul>
</li>
<li>
<strong>Word Count:</strong>
37 </li>
</ul>
</div>
<div id="columns">
<ul>
<li>
<strong>Genre:</strong>
<a href="http://etc.usf.edu/lit2go/genres/25/nursery-rhyme/">Nursery Rhyme</a>
</li>
<li>
<a class="btn" data-toggle="modal" href="#cite_this" >✎ Cite This</a>
</li>
<li>
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a addthis:ui_delay="500" href="http://www.addthis.com/bookmark.php?v=250&pub=roywinkelman" class="addthis_button_compact">Share</a>
<span class="addthis_separator">|</span>
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
</div>
<script type="text/javascript">$($.getScript("http://s7.addthis.com/js/250/addthis_widget.js?pub=roywinkelman"))</script>
<!-- <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=roywinkelman"></script> -->
<!-- AddThis Button END -->
</li>
</ul>
</div>
<h4>Downloads</h4>
<ul id="downloads">
<li>
<a href="http://etc.usf.edu/lit2go/audio/mp3/nursery-rhymes-and-traditional-poems-074-sing-a-song-of-sixpence.5351.mp3">Audio</a>
</li>
<li>
<a href="http://etc.usf.edu/lit2go/pdf/passage/5351/nursery-rhymes-and-traditional-poems-074-sing-a-song-of-sixpence.pdf">Passage PDF</a>
</li>
<li><a href="http://etc.usf.edu/lit2go/pdf/student_activity/5351/5351-1.pdf">Student Activity</a></li>
</ul>
<hr>
</details>
<div class="modal hide" id="cite_this">
<script>
$($('#myTab a').click(function (e) {e.preventDefault();$('#myTab a[href="#apa"]').tab('show');}));
</script>
<nav>
<ul id="myTab">
<li class="active">
<a href="#apa" data-toggle="tab">APA</a>
</li>
<li>
<a href="#mla" data-toggle="tab">MLA</a>
</li>
<li>
<a href="#chicago" data-toggle="tab">Chicago</a>
</li>
</ul>
</nav>
<div class="tab-content">
<div class="content tab-pane hide active" id="apa">
<p class="citation">
Traditional, . (0). Sing a Song of Sixpence. <em>Nursery Rhymes and Traditional Poems</em> (Lit2Go Edition). Retrieved February 15, 2016, from <span class="faux_link">http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5351/sing-a-song-of-sixpence/</span>
</p>
</div>
<div class="content tab-pane" id="mla">
<p class="citation">
Traditional, . "Sing a Song of Sixpence." <em>Nursery Rhymes and Traditional Poems</em>. Lit2Go Edition. 0. Web. <<span class="faux_link">http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5351/sing-a-song-of-sixpence/</span>>. February 15, 2016.
</p>
</div>
<div class="content tab-pane" id="chicago">
<p class="citation">
Traditional, "Sing a Song of Sixpence," <em>Nursery Rhymes and Traditional Poems</em>, Lit2Go Edition, (0), accessed February 15, 2016, <span class="faux_link">http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5351/sing-a-song-of-sixpence/</span>.
</p>
</div>
</div>
</div>
<span class="top"> <nav class="passage">
<ul>
<li><a href="http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5350/sing-a-song-of-sixpence/" title="Sing a Song of Sixpence" class="back">Back</a></li>
<li><a href="http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5354/sleepy-head/" title="Sleepy-Head" class="next">Next</a></li>
</ul>
</nav>
</span>
<div id="shrink_wrap">
<div id="i_apologize_for_the_soup">
<audio controls style="width:99%;">
<source src="http://etc.usf.edu/lit2go/audio/mp3/nursery-rhymes-and-traditional-poems-074-sing-a-song-of-sixpence.5351.mp3" type="audio/mpeg" />
<source src="http://etc.usf.edu/lit2go/audio/ogg/nursery-rhymes-and-traditional-poems-074-sing-a-song-of-sixpence.5351.ogg" type="audio/ogg" />
The embedded audio player requires a modern internet browser. You should visit <a href="http://browsehappy.com/">Browse Happy</a> and update your internet browser today!
</audio>
<p>
Sing a song of sixpence, a bag full of Rye,<br />
Four-and-twenty Blackbirds baked in a Pie;<br />
When the Pie was opened, the Birds began to sing,<br />
Was not that a dainty dish to set before a King?</p>
</div>
</div>
<span class="bottom"> <nav class="passage">
<ul>
<li><a href="http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5350/sing-a-song-of-sixpence/" title="Sing a Song of Sixpence" class="back">Back</a></li>
<li><a href="http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5354/sleepy-head/" title="Sleepy-Head" class="next">Next</a></li>
</ul>
</nav>
</span>
</div>
</div>
</section>
<footer screen>
<div id="footer-text">
<p>
This collection of children's literature is a part of the <a href="http://etc.usf.edu/">Educational Technology Clearinghouse</a> and is funded by various <a href="http://etc.usf.edu/lit2go/welcome/funding/">grants</a>.
</p>
<p>
Copyright © 2006—2016 by the <a href="http://fcit.usf.edu/">Florida Center for Instructional Technology</a>, <a href="http://www.coedu.usf.edu/">College of Education</a>, <a href="http://www.usf.edu/">University of South Florida</a>.
</p>
</div>
<ul id="footer-links">
<li><a href="http://etc.usf.edu/lit2go/welcome/license/">License</a></li>
<li><a href="http://etc.usf.edu/lit2go/welcome/credits/">Credits</a></li>
<li><a href="http://etc.usf.edu/lit2go/welcome/faq/">FAQ</a></li>
<li><a href="http://etc.usf.edu/lit2go/giving/">Giving</a></li>
</ul>
</footer>
<footer print>
<div id="footer-text">
<p>This document was downloaded from <a href="http://etc.usf.edu/lit2go/">Lit2Go</a>, a free online collection of stories and poems in Mp3 (audiobook) format published by the <a href="http://fcit.usf.edu/">Florida Center for Instructional Technology</a>. For more information, including classroom activities, readability data, and original sources, please visit <a href="http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5351/sing-a-song-of-sixpence/">http://etc.usf.edu/lit2go/74/nursery-rhymes-and-traditional-poems/5351/sing-a-song-of-sixpence/</a>.</p>
</div>
<div id="book-footer">
<p>Lit2Go: <em>Nursery Rhymes and Traditional Poems</em></p>
<p>Sing a Song of Sixpence</p>
</div>
</footer>
<script type="text/javascript" defer src="http://etc.usf.edu/lit2go/js/details.js"></script>
</div>
</body>
</html>
| {
"content_hash": "187315ba77fe9a8d6498e4a6a4be4f6a",
"timestamp": "",
"source": "github",
"line_count": 242,
"max_line_length": 584,
"avg_line_length": 47.15289256198347,
"alnum_prop": 0.5724301112961178,
"repo_name": "adrianosb/maprecude_team_adriano_barbosa_and_andre_matsuda",
"id": "9c434890ca28345abd84d3177f4958639e0a60b5",
"size": "11421",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "HtmlToText/lit2go.ok/74/nursery-rhymes-and-traditional-poems/5351/sing-a-song-of-sixpence/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "145411809"
},
{
"name": "Java",
"bytes": "6677"
}
],
"symlink_target": ""
} |
package com.google.cloud.datastore;
/**
* A full entity is a {@link BaseEntity} that holds all the properties associated with a
* Datastore entity (as opposed to {@link ProjectionEntity}).
*/
public class FullEntity<K extends IncompleteKey> extends BaseEntity<K> {
private static final long serialVersionUID = 432961565733066915L;
public static class Builder<K extends IncompleteKey> extends BaseEntity.Builder<K, Builder<K>> {
Builder() {
}
Builder(K key) {
super(key);
}
Builder(FullEntity<K> entity) {
super(entity);
}
@Override
public FullEntity<K> build() {
return new FullEntity<>(this);
}
}
FullEntity(BaseEntity.Builder<K, ?> builder) {
super(builder);
}
FullEntity(FullEntity<K> from) {
super(from);
}
@Override
protected BaseEntity.Builder<K, ?> emptyBuilder() {
return new Builder<K>();
}
public static Builder<IncompleteKey> builder() {
return new Builder<>();
}
public static <K extends IncompleteKey> Builder<K> builder(K key) {
return new Builder<>(key);
}
public static <K extends IncompleteKey> Builder<K> builder(FullEntity<K> copyFrom) {
return new Builder<>(copyFrom);
}
static FullEntity<?> fromPb(com.google.datastore.v1beta3.Entity entityPb) {
return new Builder<>().fill(entityPb).build();
}
}
| {
"content_hash": "6c62069d2051c925944d581f25a749eb",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 98,
"avg_line_length": 22.229508196721312,
"alnum_prop": 0.6703539823008849,
"repo_name": "aozarov/gcloud-java",
"id": "aa88a92d35547819ad403305b8bd360566a760e6",
"size": "1973",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "gcloud-java-datastore/src/main/java/com/google/cloud/datastore/FullEntity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "23012"
},
{
"name": "HTML",
"bytes": "11681"
},
{
"name": "Java",
"bytes": "2029406"
},
{
"name": "JavaScript",
"bytes": "989"
},
{
"name": "Shell",
"bytes": "6228"
}
],
"symlink_target": ""
} |
package org.openqa.selenium.grid.node.local;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.events.local.GuavaEventBus;
import org.openqa.selenium.grid.data.CreateSessionRequest;
import org.openqa.selenium.grid.data.CreateSessionResponse;
import org.openqa.selenium.grid.data.Session;
import org.openqa.selenium.grid.node.Node;
import org.openqa.selenium.grid.security.Secret;
import org.openqa.selenium.grid.testing.TestSessionFactory;
import org.openqa.selenium.internal.Either;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.remote.ErrorCodes;
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.tracing.DefaultTestTracer;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Instant;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.openqa.selenium.json.Json.MAP_TYPE;
import static org.openqa.selenium.remote.Dialect.OSS;
import static org.openqa.selenium.remote.Dialect.W3C;
import static org.openqa.selenium.remote.http.Contents.utf8String;
import static org.openqa.selenium.remote.http.HttpMethod.POST;
class CreateSessionTest {
private final Json json = new Json();
private final Capabilities stereotype = new ImmutableCapabilities("cheese", "brie");
private final Secret registrationSecret = new Secret("tunworth");
@Test
void shouldAcceptAW3CPayload() throws URISyntaxException {
String payload = json.toJson(ImmutableMap.of(
"capabilities", ImmutableMap.of(
"alwaysMatch", ImmutableMap.of("cheese", "brie"))));
HttpRequest request = new HttpRequest(POST, "/session");
request.setContent(utf8String(payload));
URI uri = new URI("http://example.com");
Node node = LocalNode.builder(
DefaultTestTracer.createTracer(),
new GuavaEventBus(),
uri,
uri,
registrationSecret)
.add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, new ImmutableCapabilities(), caps, Instant.now())))
.build();
Either<WebDriverException, CreateSessionResponse> response = node.newSession(
new CreateSessionRequest(
ImmutableSet.of(W3C),
stereotype,
ImmutableMap.of()));
if (response.isRight()) {
CreateSessionResponse sessionResponse = response.right();
Map<String, Object> all = json.toType(
new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),
MAP_TYPE);
// Ensure that there's no status field (as this is used by the protocol handshake to determine
// whether the session is using the JWP or the W3C dialect.
assertThat(all.containsKey("status")).isFalse();
// Now check the fields required by the spec
Map<?, ?> value = (Map<?, ?>) all.get("value");
assertThat(value.get("sessionId")).isInstanceOf(String.class);
assertThat(value.get("capabilities")).isInstanceOf(Map.class);
} else {
throw new AssertionError("Unable to create session" + response.left().getMessage());
}
}
@Test
void shouldOnlyAcceptAJWPPayloadIfConfiguredTo() {
// TODO: implement shouldOnlyAcceptAJWPPayloadIfConfiguredTo test
}
@Test
void ifOnlyW3CPayloadSentAndRemoteEndIsJWPOnlyFailSessionCreationIfJWPNotConfigured() {
// TODO: implement ifOnlyW3CPayloadSentAndRemoteEndIsJWPOnlyFailSessionCreationIfJWPNotConfigured test
}
@Test
void ifOnlyJWPPayloadSentResponseShouldBeJWPOnlyIfJWPConfigured()
throws URISyntaxException {
String payload = json.toJson(ImmutableMap.of(
"desiredCapabilities", ImmutableMap.of("cheese", "brie")));
HttpRequest request = new HttpRequest(POST, "/session");
request.setContent(utf8String(payload));
URI uri = new URI("http://example.com");
Node node = LocalNode.builder(
DefaultTestTracer.createTracer(),
new GuavaEventBus(),
uri,
uri,
registrationSecret)
.add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, new ImmutableCapabilities(), caps, Instant.now())))
.build();
Either<WebDriverException, CreateSessionResponse> response = node.newSession(
new CreateSessionRequest(
ImmutableSet.of(OSS),
stereotype,
ImmutableMap.of()));
if (response.isRight()) {
CreateSessionResponse sessionResponse = response.right();
Map<String, Object> all = json.toType(
new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),
MAP_TYPE);
// The status field is used by local ends to determine whether or not the session is a JWP one.
assertThat(all.get("status")).matches(obj -> ((Number) obj).intValue() == ErrorCodes.SUCCESS);
// The session id is a top level field
assertThat(all.get("sessionId")).isInstanceOf(String.class);
// And the value should contain the capabilities.
assertThat(all.get("value")).isInstanceOf(Map.class);
} else {
throw new AssertionError("Unable to create session" + response.left().getMessage());
}
}
@Test
void shouldPreferUsingTheW3CProtocol() throws URISyntaxException {
String payload = json.toJson(ImmutableMap.of(
"desiredCapabilities", ImmutableMap.of(
"cheese", "brie"),
"capabilities", ImmutableMap.of(
"alwaysMatch", ImmutableMap.of("cheese", "brie"))));
HttpRequest request = new HttpRequest(POST, "/session");
request.setContent(utf8String(payload));
URI uri = new URI("http://example.com");
Node node = LocalNode.builder(
DefaultTestTracer.createTracer(),
new GuavaEventBus(),
uri,
uri,
registrationSecret)
.add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, new ImmutableCapabilities(), caps, Instant.now())))
.build();
Either<WebDriverException, CreateSessionResponse> response = node.newSession(
new CreateSessionRequest(
ImmutableSet.of(W3C),
stereotype,
ImmutableMap.of()));
if (response.isRight()) {
CreateSessionResponse sessionResponse = response.right();
Map<String, Object> all = json.toType(
new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),
MAP_TYPE);
// Ensure that there's no status field (as this is used by the protocol handshake to determine
// whether the session is using the JWP or the W3C dialect.
assertThat(all.containsKey("status")).isFalse();
// Now check the fields required by the spec
Map<?, ?> value = (Map<?, ?>) all.get("value");
assertThat(value.get("sessionId")).isInstanceOf(String.class);
assertThat(value.get("capabilities")).isInstanceOf(Map.class);
} else {
throw new AssertionError("Unable to create session" + response.left().getMessage());
}
}
@Test
void sessionDataShouldBeCorrectRegardlessOfPayloadProtocol() {
// TODO: implement sessionDataShouldBeCorrectRegardlessOfPayloadProtocol test
}
@Test
void shouldSupportProtocolConversion() {
// TODO: implement shouldSupportProtocolConversion test
}
}
| {
"content_hash": "88994cab294c6f17a89462d6b700ee3a",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 134,
"avg_line_length": 37.65482233502538,
"alnum_prop": 0.7123213804259908,
"repo_name": "valfirst/selenium",
"id": "a7d31090a9426d8a410e5efd354deef743a68c5b",
"size": "8222",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "java/test/org/openqa/selenium/grid/node/local/CreateSessionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP.NET",
"bytes": "825"
},
{
"name": "Batchfile",
"bytes": "4443"
},
{
"name": "C",
"bytes": "82917"
},
{
"name": "C#",
"bytes": "2990022"
},
{
"name": "C++",
"bytes": "2285448"
},
{
"name": "CSS",
"bytes": "1049"
},
{
"name": "Dockerfile",
"bytes": "1737"
},
{
"name": "HTML",
"bytes": "1379853"
},
{
"name": "Java",
"bytes": "6286458"
},
{
"name": "JavaScript",
"bytes": "2535395"
},
{
"name": "Makefile",
"bytes": "4655"
},
{
"name": "Python",
"bytes": "988077"
},
{
"name": "Ragel",
"bytes": "3086"
},
{
"name": "Ruby",
"bytes": "1036679"
},
{
"name": "Rust",
"bytes": "45287"
},
{
"name": "Shell",
"bytes": "29804"
},
{
"name": "Starlark",
"bytes": "401750"
},
{
"name": "TypeScript",
"bytes": "126843"
},
{
"name": "XSLT",
"bytes": "1047"
}
],
"symlink_target": ""
} |
package pl.project13.janbanery.util.predicates;
import com.google.common.base.Predicate;
import pl.project13.janbanery.resources.Task;
/**
* @author Konrad Malawski
*/
public class TaskByTitlePredicate implements Predicate<Task> {
private String taskTitle;
public TaskByTitlePredicate(String taskTitle) {
this.taskTitle = taskTitle;
}
@Override
public boolean apply(Task input) {
return taskTitle.equals(input.getTitle());
}
}
| {
"content_hash": "c3d81546e5c95979e63c58a5e505a398",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 62,
"avg_line_length": 19.82608695652174,
"alnum_prop": 0.75,
"repo_name": "ktoso/janbanery",
"id": "49c3c677a0dbb2d621b3a9458a253a69f32560be",
"size": "1085",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "janbanery-core/src/main/java/pl/project13/janbanery/util/predicates/TaskByTitlePredicate.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "516324"
},
{
"name": "Shell",
"bytes": "235"
}
],
"symlink_target": ""
} |
<?php
?>
<?php echo ajax_modal_template(__('Edit Version'),get_partial('form', array('form' => $form))) ?>
| {
"content_hash": "3d64aa93693edcaa6f39a0bd531632e2",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 98,
"avg_line_length": 27.25,
"alnum_prop": 0.5963302752293578,
"repo_name": "arokia/oasis",
"id": "2bd1426718c09d043858dd4949601f9773c1dd7d",
"size": "973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/oasis-ems/core/apps/qdPM/modules/versions/templates/editSuccess.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1385"
},
{
"name": "Batchfile",
"bytes": "1134"
},
{
"name": "CSS",
"bytes": "424816"
},
{
"name": "HTML",
"bytes": "608424"
},
{
"name": "JavaScript",
"bytes": "1416921"
},
{
"name": "PHP",
"bytes": "1928133"
},
{
"name": "Shell",
"bytes": "1345"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import, division, print_function
def update_attributes(obj, dictionary, keys):
if not dictionary:
return
for key in keys:
if key not in dictionary:
continue
value = dictionary[key]
if getattr(obj, key) is not None and value is None:
continue
if type(value) is dict:
continue
setattr(obj, key, dictionary[key])
| {
"content_hash": "3f46eca852679cbc8bb5a56716c27b3f",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 64,
"avg_line_length": 22.05,
"alnum_prop": 0.5963718820861678,
"repo_name": "fuzeman/trakt.py",
"id": "98be8ad35c9da8ef5fd9dc716ffdd5e3cf2aca8d",
"size": "441",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "trakt/objects/core/helpers.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "295322"
}
],
"symlink_target": ""
} |
#include <psych.h>
VALUE cPsychParser;
VALUE ePsychSyntaxError;
static ID id_read;
static ID id_empty;
static ID id_start_stream;
static ID id_end_stream;
static ID id_start_document;
static ID id_end_document;
static ID id_alias;
static ID id_scalar;
static ID id_start_sequence;
static ID id_end_sequence;
static ID id_start_mapping;
static ID id_end_mapping;
#define PSYCH_TRANSCODE(_str, _yaml_enc, _internal_enc) \
do { \
rb_enc_associate_index(_str, _yaml_enc); \
if(_internal_enc) \
_str = rb_str_export_to_enc(_str, _internal_enc); \
} while (0)
static int io_reader(void * data, unsigned char *buf, size_t size, size_t *read)
{
VALUE io = (VALUE)data;
VALUE string = rb_funcall(io, id_read, 1, INT2NUM(size));
*read = 0;
if(! NIL_P(string)) {
void * str = (void *)StringValuePtr(string);
*read = (size_t)RSTRING_LEN(string);
memcpy(buf, str, *read);
}
return 1;
}
/*
* call-seq:
* parser.parse(yaml)
*
* Parse the YAML document contained in +yaml+. Events will be called on
* the handler set on the parser instance.
*
* See Psych::Parser and Psych::Parser#handler
*/
static VALUE parse(VALUE self, VALUE yaml)
{
yaml_parser_t parser;
yaml_event_t event;
int done = 0;
int tainted = 0;
#ifdef HAVE_RUBY_ENCODING_H
int encoding = rb_enc_find_index("ASCII-8BIT");
rb_encoding * internal_enc;
#endif
VALUE handler = rb_iv_get(self, "@handler");
yaml_parser_initialize(&parser);
if (OBJ_TAINTED(yaml)) tainted = 1;
if(rb_respond_to(yaml, id_read)) {
yaml_parser_set_input(&parser, io_reader, (void *)yaml);
if (RTEST(rb_obj_is_kind_of(yaml, rb_cIO))) tainted = 1;
} else {
StringValue(yaml);
yaml_parser_set_input_string(
&parser,
(const unsigned char *)RSTRING_PTR(yaml),
(size_t)RSTRING_LEN(yaml)
);
}
while(!done) {
if(!yaml_parser_parse(&parser, &event)) {
size_t line = parser.mark.line + 1;
size_t column = parser.mark.column;
yaml_parser_delete(&parser);
rb_raise(ePsychSyntaxError, "couldn't parse YAML at line %d column %d",
(int)line, (int)column);
}
switch(event.type) {
case YAML_STREAM_START_EVENT:
#ifdef HAVE_RUBY_ENCODING_H
switch(event.data.stream_start.encoding) {
case YAML_ANY_ENCODING:
break;
case YAML_UTF8_ENCODING:
encoding = rb_enc_find_index("UTF-8");
break;
case YAML_UTF16LE_ENCODING:
encoding = rb_enc_find_index("UTF-16LE");
break;
case YAML_UTF16BE_ENCODING:
encoding = rb_enc_find_index("UTF-16BE");
break;
default:
break;
}
internal_enc = rb_default_internal_encoding();
#endif
rb_funcall(handler, id_start_stream, 1,
INT2NUM((long)event.data.stream_start.encoding)
);
break;
case YAML_DOCUMENT_START_EVENT:
{
/* Get a list of tag directives (if any) */
VALUE tag_directives = rb_ary_new();
/* Grab the document version */
VALUE version = event.data.document_start.version_directive ?
rb_ary_new3(
(long)2,
INT2NUM((long)event.data.document_start.version_directive->major),
INT2NUM((long)event.data.document_start.version_directive->minor)
) : rb_ary_new();
if(event.data.document_start.tag_directives.start) {
yaml_tag_directive_t *start =
event.data.document_start.tag_directives.start;
yaml_tag_directive_t *end =
event.data.document_start.tag_directives.end;
for(; start != end; start++) {
VALUE handle = Qnil;
VALUE prefix = Qnil;
if(start->handle) {
handle = rb_str_new2((const char *)start->handle);
if (tainted) OBJ_TAINT(handle);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(handle, encoding, internal_enc);
#endif
}
if(start->prefix) {
prefix = rb_str_new2((const char *)start->prefix);
if (tainted) OBJ_TAINT(prefix);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(prefix, encoding, internal_enc);
#endif
}
rb_ary_push(tag_directives, rb_ary_new3((long)2, handle, prefix));
}
}
rb_funcall(handler, id_start_document, 3,
version, tag_directives,
event.data.document_start.implicit == 1 ? Qtrue : Qfalse
);
}
break;
case YAML_DOCUMENT_END_EVENT:
rb_funcall(handler, id_end_document, 1,
event.data.document_end.implicit == 1 ? Qtrue : Qfalse
);
break;
case YAML_ALIAS_EVENT:
{
VALUE alias = Qnil;
if(event.data.alias.anchor) {
alias = rb_str_new2((const char *)event.data.alias.anchor);
if (tainted) OBJ_TAINT(alias);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(alias, encoding, internal_enc);
#endif
}
rb_funcall(handler, id_alias, 1, alias);
}
break;
case YAML_SCALAR_EVENT:
{
VALUE anchor = Qnil;
VALUE tag = Qnil;
VALUE plain_implicit, quoted_implicit, style;
VALUE val = rb_str_new(
(const char *)event.data.scalar.value,
(long)event.data.scalar.length
);
if (tainted) OBJ_TAINT(val);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(val, encoding, internal_enc);
#endif
if(event.data.scalar.anchor) {
anchor = rb_str_new2((const char *)event.data.scalar.anchor);
if (tainted) OBJ_TAINT(anchor);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(anchor, encoding, internal_enc);
#endif
}
if(event.data.scalar.tag) {
tag = rb_str_new2((const char *)event.data.scalar.tag);
if (tainted) OBJ_TAINT(tag);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(tag, encoding, internal_enc);
#endif
}
plain_implicit =
event.data.scalar.plain_implicit == 0 ? Qfalse : Qtrue;
quoted_implicit =
event.data.scalar.quoted_implicit == 0 ? Qfalse : Qtrue;
style = INT2NUM((long)event.data.scalar.style);
rb_funcall(handler, id_scalar, 6,
val, anchor, tag, plain_implicit, quoted_implicit, style);
}
break;
case YAML_SEQUENCE_START_EVENT:
{
VALUE anchor = Qnil;
VALUE tag = Qnil;
VALUE implicit, style;
if(event.data.sequence_start.anchor) {
anchor = rb_str_new2((const char *)event.data.sequence_start.anchor);
if (tainted) OBJ_TAINT(anchor);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(anchor, encoding, internal_enc);
#endif
}
tag = Qnil;
if(event.data.sequence_start.tag) {
tag = rb_str_new2((const char *)event.data.sequence_start.tag);
if (tainted) OBJ_TAINT(tag);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(tag, encoding, internal_enc);
#endif
}
implicit =
event.data.sequence_start.implicit == 0 ? Qfalse : Qtrue;
style = INT2NUM((long)event.data.sequence_start.style);
rb_funcall(handler, id_start_sequence, 4,
anchor, tag, implicit, style);
}
break;
case YAML_SEQUENCE_END_EVENT:
rb_funcall(handler, id_end_sequence, 0);
break;
case YAML_MAPPING_START_EVENT:
{
VALUE anchor = Qnil;
VALUE tag = Qnil;
VALUE implicit, style;
if(event.data.mapping_start.anchor) {
anchor = rb_str_new2((const char *)event.data.mapping_start.anchor);
if (tainted) OBJ_TAINT(anchor);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(anchor, encoding, internal_enc);
#endif
}
if(event.data.mapping_start.tag) {
tag = rb_str_new2((const char *)event.data.mapping_start.tag);
if (tainted) OBJ_TAINT(tag);
#ifdef HAVE_RUBY_ENCODING_H
PSYCH_TRANSCODE(tag, encoding, internal_enc);
#endif
}
implicit =
event.data.mapping_start.implicit == 0 ? Qfalse : Qtrue;
style = INT2NUM((long)event.data.mapping_start.style);
rb_funcall(handler, id_start_mapping, 4,
anchor, tag, implicit, style);
}
break;
case YAML_MAPPING_END_EVENT:
rb_funcall(handler, id_end_mapping, 0);
break;
case YAML_NO_EVENT:
rb_funcall(handler, id_empty, 0);
break;
case YAML_STREAM_END_EVENT:
rb_funcall(handler, id_end_stream, 0);
done = 1;
break;
}
yaml_event_delete(&event);
}
return self;
}
void Init_psych_parser()
{
#if 0
mPsych = rb_define_module("Psych");
#endif
cPsychParser = rb_define_class_under(mPsych, "Parser", rb_cObject);
/* Any encoding: Let the parser choose the encoding */
rb_define_const(cPsychParser, "ANY", INT2NUM(YAML_ANY_ENCODING));
/* UTF-8 Encoding */
rb_define_const(cPsychParser, "UTF8", INT2NUM(YAML_UTF8_ENCODING));
/* UTF-16-LE Encoding with BOM */
rb_define_const(cPsychParser, "UTF16LE", INT2NUM(YAML_UTF16LE_ENCODING));
/* UTF-16-BE Encoding with BOM */
rb_define_const(cPsychParser, "UTF16BE", INT2NUM(YAML_UTF16BE_ENCODING));
ePsychSyntaxError = rb_define_class_under(mPsych, "SyntaxError", rb_eSyntaxError);
rb_define_method(cPsychParser, "parse", parse, 1);
id_read = rb_intern("read");
id_empty = rb_intern("empty");
id_start_stream = rb_intern("start_stream");
id_end_stream = rb_intern("end_stream");
id_start_document = rb_intern("start_document");
id_end_document = rb_intern("end_document");
id_alias = rb_intern("alias");
id_scalar = rb_intern("scalar");
id_start_sequence = rb_intern("start_sequence");
id_end_sequence = rb_intern("end_sequence");
id_start_mapping = rb_intern("start_mapping");
id_end_mapping = rb_intern("end_mapping");
}
/* vim: set noet sws=4 sw=4: */
| {
"content_hash": "5163f55b417b9e393e356948354c56a4",
"timestamp": "",
"source": "github",
"line_count": 341,
"max_line_length": 86,
"avg_line_length": 27.266862170087975,
"alnum_prop": 0.6457302645730264,
"repo_name": "nuclearsandwich/rubinius",
"id": "a69f2763bc98f4c5a8a977abaad5e66118fa2b8c",
"size": "9298",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/19/psych/ext/parser.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
.medium-toolbar-arrow-under:after {
border-color: #000 transparent transparent transparent;
top: 40px; }
.medium-toolbar-arrow-over:before {
border-color: transparent transparent #000 transparent; }
.medium-editor-toolbar {
background-color: #000;
border: none;
border-radius: 50px; }
.medium-editor-toolbar li button {
background-color: transparent;
border: none;
box-sizing: border-box;
color: #ccc;
height: 40px;
min-width: 40px;
padding: 5px 12px;
-webkit-transition: background-color .2s ease-in, color .2s ease-in;
transition: background-color .2s ease-in, color .2s ease-in; }
.medium-editor-toolbar li button:hover {
background-color: #000;
color: #a2d7c7; }
.medium-editor-toolbar li .medium-editor-button-first {
border-bottom-left-radius: 50px;
border-top-left-radius: 50px;
padding-left: 24px; }
.medium-editor-toolbar li .medium-editor-button-last {
border-bottom-right-radius: 50px;
border-right: none;
border-top-right-radius: 50px;
padding-right: 24px; }
.medium-editor-toolbar li .medium-editor-button-active {
background-color: #000;
color: #a2d7c7; }
.medium-editor-toolbar-form {
background: #000;
border-radius: 50px;
color: #ccc;
overflow: hidden; }
.medium-editor-toolbar-form .medium-editor-toolbar-input {
background: #000;
box-sizing: border-box;
color: #ccc;
height: 40px;
padding-left: 16px;
width: 220px; }
.medium-editor-toolbar-form .medium-editor-toolbar-input::-webkit-input-placeholder {
color: #f8f5f3;
color: rgba(248, 245, 243, 0.8); }
.medium-editor-toolbar-form .medium-editor-toolbar-input:-moz-placeholder {
/* Firefox 18- */
color: #f8f5f3;
color: rgba(248, 245, 243, 0.8); }
.medium-editor-toolbar-form .medium-editor-toolbar-input::-moz-placeholder {
/* Firefox 19+ */
color: #f8f5f3;
color: rgba(248, 245, 243, 0.8); }
.medium-editor-toolbar-form .medium-editor-toolbar-input:-ms-input-placeholder {
color: #f8f5f3;
color: rgba(248, 245, 243, 0.8); }
.medium-editor-toolbar-form a {
color: #ccc;
-webkit-transform: translateY(2px);
transform: translateY(2px); }
.medium-editor-toolbar-form .medium-editor-toolbar-close {
margin-right: 16px; }
.medium-editor-toolbar-anchor-preview {
background: #000;
border-radius: 50px;
padding: 5px 12px; }
.medium-editor-anchor-preview a {
color: #ccc;
text-decoration: none; }
| {
"content_hash": "c66b5cc230e750cbcd296ef2489c87c9",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 89,
"avg_line_length": 33.42307692307692,
"alnum_prop": 0.6425009589566552,
"repo_name": "Esri/shortlist-storytelling-template-js",
"id": "615851024053951119b73740eff8cc51b0ebe37e",
"size": "2607",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/lib-app/medium-editor/dist/css/themes/beagle.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "8450"
},
{
"name": "CSS",
"bytes": "350345"
},
{
"name": "HTML",
"bytes": "103724"
},
{
"name": "JavaScript",
"bytes": "2822595"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login Page - Photon Admin Panel Theme</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<link rel="shortcut icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/favicon.ico"/>
<link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/iosicon.png"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all"/>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" />
<![endif]-->
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" />
<script type="text/javascript" src="js/plugins/excanvas.js"></script>
<script type="text/javascript" src="js/plugins/html5shiv.js"></script>
<script type="text/javascript" src="js/plugins/respond.min.js"></script>
<script type="text/javascript" src="js/plugins/fixFontIcons.js"></script>
<![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/bootstrap/bootstrap.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/modernizr.custom.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.pnotify.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/less-1.3.1.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/xbreadcrumbs.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/charCount.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.textareaCounter.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/elrte.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/elrte.en.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/select2.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery-picklist.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/additional-methods.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.form.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.metadata.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.mockjax.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.uniform.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.tagsinput.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.rating.pack.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/farbtastic.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.timeentry.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.jstree.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.flot.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.flot.stack.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.flot.pie.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.flot.resize.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/raphael.2.1.0.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/justgage.1.0.1.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.qrcode.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.clock.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.countdown.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.jqtweet.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/jquery.cookie.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/prettify/prettify.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/bootstrapSwitch.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/plugins/mfupload.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/js/common.js"></script>
</head>
<body class="body-login">
<div class="nav-fixed-topright" style="visibility: hidden">
<ul class="nav nav-user-menu">
<li class="user-sub-menu-container">
<a href="javascript:;">
<i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i>
</a>
<ul class="nav user-sub-menu">
<li class="light">
<a href="javascript:;">
<i class='icon-photon stop'></i>Light Version
</a>
</li>
<li class="dark">
<a href="javascript:;">
<i class='icon-photon stop'></i>Dark Version
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-photon mail"></i>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-photon comment_alt2_stroke"></i>
<div class="notification-count">12</div>
</a>
</li>
</ul>
</div>
<script>
$(function(){
setTimeout(function(){
$('.nav-fixed-topright').removeAttr('style');
}, 300);
$(window).scroll(function(){
if($('.breadcrumb-container').length){
var scrollState = $(window).scrollTop();
if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released');
else $('.nav-fixed-topright').removeClass('nav-released')
}
});
$('.user-sub-menu-container').on('click', function(){
$(this).toggleClass('active-user-menu');
});
$('.user-sub-menu .light').on('click', function(){
if ($('body').is('.light-version')) return;
$('body').addClass('light-version');
setTimeout(function() {
$.cookie('themeColor', 'light', {
expires: 7,
path: '/'
});
}, 500);
});
$('.user-sub-menu .dark').on('click', function(){
if ($('body').is('.light-version')) {
$('body').removeClass('light-version');
$.cookie('themeColor', 'dark', {
expires: 7,
path: '/'
});
}
});
});
</script>
<div class="container-login">
<div class="form-centering-wrapper">
<div class="form-window-login">
<div class="form-window-login-logo">
<div class="login-logo">
<img src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/images/photon/login-logo@2x.png" alt="Photon UI"/>
</div>
<h2 class="login-title">Welcome to Photon UI!</h2>
<div class="login-member">Not a Member? <a href="jquery.mCustomScrollbar.js.html#">Sign Up »</a>
<a href="jquery.mCustomScrollbar.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a>
</div>
<div class="login-or">Or</div>
<div class="login-input-area">
<form method="POST" action="dashboard.php">
<span class="help-block">Login With Your Photon Account</span>
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn btn-large btn-success btn-login">Login</button>
</form>
<a href="jquery.mCustomScrollbar.js.html#" class="forgot-pass">Forgot Your Password?</a>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1936460-27']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
| {
"content_hash": "b65084de293bde65e707012dc1fd3481",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 228,
"avg_line_length": 83.89010989010988,
"alnum_prop": 0.739324076499869,
"repo_name": "user-tony/photon-rails",
"id": "ff1c0a94c74813b0fc2be43743ba7390d3a57198",
"size": "15268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/assets/css/css_compiled/@{photonImagePath}plugins/elrte/js/plugins/js/plugins/css/css_compiled/js/plugins/jquery.mCustomScrollbar.js.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "291750913"
},
{
"name": "JavaScript",
"bytes": "59305"
},
{
"name": "Ruby",
"bytes": "203"
},
{
"name": "Shell",
"bytes": "99"
}
],
"symlink_target": ""
} |
// Copyright 2010-2022 Google 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.
#include "ortools/math_opt/core/model_summary.h"
#include <cstdint>
#include <initializer_list>
#include <limits>
#include <optional>
#include <string>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "ortools/base/linked_hash_map.h"
#include "ortools/base/logging.h"
#include "ortools/base/status_macros.h"
#include "ortools/math_opt/model.pb.h"
#include "ortools/math_opt/model_update.pb.h"
namespace operations_research {
namespace math_opt {
namespace internal {
absl::Status CheckIdsRangeAndStrictlyIncreasing2(
absl::Span<const int64_t> ids) {
int64_t previous{-1};
for (int i = 0; i < ids.size(); previous = ids[i], ++i) {
if (ids[i] < 0 || ids[i] == std::numeric_limits<int64_t>::max()) {
return util::InvalidArgumentErrorBuilder()
<< "Expected ids to be nonnegative and not max(int64_t) but at "
"index "
<< i << " found id: " << ids[i];
}
if (ids[i] <= previous) {
return util::InvalidArgumentErrorBuilder()
<< "Expected ids to be strictly increasing, but at index " << i
<< " found id: " << ids[i] << " and at previous index " << i - 1
<< " found id: " << ids[i - 1];
}
}
return absl::OkStatus();
}
} // namespace internal
IdNameBiMap::IdNameBiMap(
std::initializer_list<std::pair<int64_t, absl::string_view>> ids)
: IdNameBiMap(/*check_names=*/true) {
for (const auto& pair : ids) {
CHECK_OK(Insert(pair.first, std::string(pair.second)));
}
}
IdNameBiMap::IdNameBiMap(const IdNameBiMap& other) { *this = other; }
IdNameBiMap& IdNameBiMap::operator=(const IdNameBiMap& other) {
if (&other == this) {
return *this;
}
next_free_id_ = other.next_free_id_;
id_to_name_ = other.id_to_name_;
if (!other.nonempty_name_to_id_.has_value()) {
nonempty_name_to_id_ = std::nullopt;
} else {
nonempty_name_to_id_.emplace();
for (const auto& [id, name] : id_to_name_) {
if (!name.empty()) {
const auto [it, success] =
nonempty_name_to_id_->insert({absl::string_view(name), id});
CHECK(success); // CHECK is OK, other cannot have duplicate names and
// non nullopt nonempty_name_to_id_.
}
}
}
return *this;
}
absl::Status IdNameBiMap::BulkUpdate(
absl::Span<const int64_t> deleted_ids, absl::Span<const int64_t> new_ids,
const absl::Span<const std::string* const> names) {
RETURN_IF_ERROR(internal::CheckIdsRangeAndStrictlyIncreasing2(deleted_ids))
<< "invalid deleted ids";
RETURN_IF_ERROR(internal::CheckIdsRangeAndStrictlyIncreasing2(new_ids))
<< "invalid new ids";
if (!names.empty() && names.size() != new_ids.size()) {
return util::InvalidArgumentErrorBuilder()
<< "names had size " << names.size()
<< " but should either be empty of have size matching new_ids which "
"has size "
<< new_ids.size();
}
for (const int64_t id : deleted_ids) {
RETURN_IF_ERROR(Erase(id));
}
for (int i = 0; i < new_ids.size(); ++i) {
RETURN_IF_ERROR(
Insert(new_ids[i], names.empty() ? std::string{} : *names[i]));
}
return absl::OkStatus();
}
ModelSummary::ModelSummary(const bool check_names)
: variables(check_names),
linear_constraints(check_names),
quadratic_constraints(check_names),
sos1_constraints(check_names),
sos2_constraints(check_names) {}
absl::StatusOr<ModelSummary> ModelSummary::Create(const ModelProto& model,
const bool check_names) {
ModelSummary summary(check_names);
RETURN_IF_ERROR(summary.variables.BulkUpdate({}, model.variables().ids(),
model.variables().names()))
<< "Model.variables are invalid";
RETURN_IF_ERROR(summary.linear_constraints.BulkUpdate(
{}, model.linear_constraints().ids(), model.linear_constraints().names()))
<< "Model.linear_constraints are invalid";
RETURN_IF_ERROR(internal::UpdateBiMapFromMappedConstraints(
{}, model.quadratic_constraints(), summary.quadratic_constraints))
<< "Model.quadratic_constraints are invalid";
RETURN_IF_ERROR(internal::UpdateBiMapFromMappedConstraints(
{}, model.sos1_constraints(), summary.sos1_constraints))
<< "Model.sos1_constraints are invalid";
RETURN_IF_ERROR(internal::UpdateBiMapFromMappedConstraints(
{}, model.sos2_constraints(), summary.sos2_constraints))
<< "Model.sos2_constraints are invalid";
return summary;
}
absl::Status ModelSummary::Update(const ModelUpdateProto& model_update) {
RETURN_IF_ERROR(variables.BulkUpdate(model_update.deleted_variable_ids(),
model_update.new_variables().ids(),
model_update.new_variables().names()))
<< "invalid variables";
RETURN_IF_ERROR(linear_constraints.BulkUpdate(
model_update.deleted_linear_constraint_ids(),
model_update.new_linear_constraints().ids(),
model_update.new_linear_constraints().names()))
<< "invalid linear constraints";
RETURN_IF_ERROR(internal::UpdateBiMapFromMappedConstraints(
model_update.quadratic_constraint_updates().deleted_constraint_ids(),
model_update.quadratic_constraint_updates().new_constraints(),
quadratic_constraints))
<< "invalid quadratic constraints";
RETURN_IF_ERROR(internal::UpdateBiMapFromMappedConstraints(
model_update.sos1_constraint_updates().deleted_constraint_ids(),
model_update.sos1_constraint_updates().new_constraints(),
sos1_constraints))
<< "invalid sos1 constraints";
RETURN_IF_ERROR(internal::UpdateBiMapFromMappedConstraints(
model_update.sos2_constraint_updates().deleted_constraint_ids(),
model_update.sos2_constraint_updates().new_constraints(),
sos2_constraints))
<< "invalid sos2 constraints";
return absl::OkStatus();
}
} // namespace math_opt
} // namespace operations_research
| {
"content_hash": "f4d35a5a7e2ef2d894f8996e753b5c8d",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 80,
"avg_line_length": 38.57142857142857,
"alnum_prop": 0.6551111111111111,
"repo_name": "google/or-tools",
"id": "f4301a2a136f61f39d7af5a5b4c65240174f890c",
"size": "6750",
"binary": false,
"copies": "2",
"ref": "refs/heads/stable",
"path": "ortools/math_opt/core/model_summary.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "18599"
},
{
"name": "C",
"bytes": "11382"
},
{
"name": "C#",
"bytes": "498888"
},
{
"name": "C++",
"bytes": "14071164"
},
{
"name": "CMake",
"bytes": "219723"
},
{
"name": "Dockerfile",
"bytes": "149476"
},
{
"name": "Java",
"bytes": "459136"
},
{
"name": "Lex",
"bytes": "2271"
},
{
"name": "Makefile",
"bytes": "207007"
},
{
"name": "Python",
"bytes": "629275"
},
{
"name": "SWIG",
"bytes": "414259"
},
{
"name": "Shell",
"bytes": "83555"
},
{
"name": "Starlark",
"bytes": "235950"
},
{
"name": "Yacc",
"bytes": "26027"
},
{
"name": "sed",
"bytes": "45"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Csla.Blazor.Test.Fakes
{
public class FakePersonEmailAddress : BusinessBase<FakePersonEmailAddress>
{
public static Csla.PropertyInfo<string> EmailAddressProperty = RegisterProperty<string>(nameof(EmailAddress));
#region Properties
[Required]
[MaxLength(250)]
public string EmailAddress
{
get { return GetProperty(EmailAddressProperty); }
set { SetProperty(EmailAddressProperty, value); }
}
#endregion
#region Data Access
[RunLocal]
[Create]
private void Create()
{
// Trigger object checks
BusinessRules.CheckRules();
}
#endregion
}
}
| {
"content_hash": "74e0bfdc5f19dca5d6799a95cef46c47",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 114,
"avg_line_length": 20.45945945945946,
"alnum_prop": 0.7001321003963011,
"repo_name": "MarimerLLC/csla",
"id": "82014f307536b6d0b0e27eecb2ff32043c07e47c",
"size": "759",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "Source/Csla.Blazor.Test/Fakes/FakePersonEmailAddress.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "53"
},
{
"name": "C#",
"bytes": "4160129"
},
{
"name": "HTML",
"bytes": "32375"
},
{
"name": "PowerShell",
"bytes": "26995"
},
{
"name": "Shell",
"bytes": "533"
},
{
"name": "Smalltalk",
"bytes": "3"
},
{
"name": "Vim Snippet",
"bytes": "74325"
},
{
"name": "Visual Basic .NET",
"bytes": "25744"
}
],
"symlink_target": ""
} |
#include <set>
class CVarDefCont
{
private:
CGString m_Key; // reference to map key
public:
static const char *m_sClassName;
CVarDefCont( LPCTSTR pszKey );
virtual ~CVarDefCont();
private:
CVarDefCont(const CVarDefCont& copy);
CVarDefCont& operator=(const CVarDefCont& other);
public:
LPCTSTR GetKey() const;
void SetKey( LPCTSTR pszKey );
virtual LPCTSTR GetValStr() const = 0;
virtual INT64 GetValNum() const = 0;
virtual CVarDefCont * CopySelf() const = 0;
};
class CVarDefContNum : public CVarDefCont
{
private:
INT64 m_iVal;
public:
static const char *m_sClassName;
CVarDefContNum( LPCTSTR pszKey, INT64 iVal );
CVarDefContNum( LPCTSTR pszKey );
~CVarDefContNum();
private:
CVarDefContNum(const CVarDefContNum& copy);
CVarDefContNum& operator=(const CVarDefContNum& other);
public:
INT64 GetValNum() const;
void SetValNum( INT64 iVal );
LPCTSTR GetValStr() const;
bool r_LoadVal( CScript & s );
bool r_WriteVal( LPCTSTR pKey, CGString & sVal, CTextConsole * pSrc );
virtual CVarDefCont * CopySelf() const;
};
class CVarDefContStr : public CVarDefCont
{
private:
CGString m_sVal; // the assigned value. (What if numeric?)
public:
static const char *m_sClassName;
CVarDefContStr( LPCTSTR pszKey, LPCTSTR pszVal );
explicit CVarDefContStr( LPCTSTR pszKey );
~CVarDefContStr();
private:
CVarDefContStr(const CVarDefContStr& copy);
CVarDefContStr& operator=(const CVarDefContStr& other);
public:
LPCTSTR GetValStr() const;
void SetValStr( LPCTSTR pszVal );
INT64 GetValNum() const;
bool r_LoadVal( CScript & s );
bool r_WriteVal( LPCTSTR pKey, CGString & sVal, CTextConsole * pSrc );
virtual CVarDefCont * CopySelf() const;
};
class CVarDefMap
{
private:
struct ltstr
{
bool operator()(CVarDefCont * s1, CVarDefCont * s2) const;
};
typedef std::set<CVarDefCont *, ltstr> DefSet;
typedef std::pair<DefSet::iterator, bool> DefPairResult;
class CVarDefContTest : public CVarDefCont // This is to alloc CVarDefCont without allocing any other things
{
public:
static const char *m_sClassName;
CVarDefContTest( LPCTSTR pszKey );
~CVarDefContTest();
private:
CVarDefContTest(const CVarDefContTest& copy);
CVarDefContTest& operator=(const CVarDefContTest& other);
public:
LPCTSTR GetValStr() const;
INT64 GetValNum() const;
virtual CVarDefCont * CopySelf() const;
};
private:
DefSet m_Container;
public:
static const char *m_sClassName;
private:
CVarDefCont * GetAtKey( LPCTSTR at ) const;
void DeleteAt( size_t at );
void DeleteAtKey( LPCTSTR at );
void DeleteAtIterator( DefSet::iterator it );
int SetNumOverride( LPCTSTR pszKey, INT64 iVal );
int SetStrOverride( LPCTSTR pszKey, LPCTSTR pszVal );
public:
void Copy( const CVarDefMap * pArray );
bool Compare( const CVarDefMap * pArray );
bool CompareAll( const CVarDefMap * pArray );
void Empty();
size_t GetCount() const;
public:
CVarDefMap() { };
~CVarDefMap();
CVarDefMap & operator = ( const CVarDefMap & array );
private:
CVarDefMap(const CVarDefMap& copy);
public:
LPCTSTR FindValNum( INT64 iVal ) const;
LPCTSTR FindValStr( LPCTSTR pVal ) const;
int SetNumNew( LPCTSTR pszKey, INT64 iVal );
int SetNum( LPCTSTR pszKey, INT64 iVal, bool fZero = false );
int SetStrNew( LPCTSTR pszKey, LPCTSTR pszVal );
int SetStr( LPCTSTR pszKey, bool fQuoted, LPCTSTR pszVal, bool fZero = false );
CVarDefCont * GetAt( size_t at ) const;
CVarDefCont * GetKey( LPCTSTR pszKey ) const;
INT64 GetKeyNum( LPCTSTR pszKey ) const;
LPCTSTR GetKeyStr( LPCTSTR pszKey, bool fZero = false ) const;
CVarDefCont * GetParseKey( LPCTSTR & pArgs ) const;
CVarDefCont * CheckParseKey( LPCTSTR & pszArgs ) const;
bool GetParseVal( LPCTSTR & pArgs, long long * plVal ) const;
void DumpKeys( CTextConsole * pSrc, LPCTSTR pszPrefix = NULL ) const;
void ClearKeys(LPCTSTR mask = NULL);
void DeleteKey( LPCTSTR key );
bool r_LoadVal( CScript & s );
void r_WritePrefix( CScript & s, LPCTSTR pszPrefix = NULL, LPCTSTR pszKeyExclude = NULL );
};
#endif
| {
"content_hash": "8f1bd29fb7042f16137eb7fdd37eeccc",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 109,
"avg_line_length": 25.05389221556886,
"alnum_prop": 0.7012428298279159,
"repo_name": "drk84/Source",
"id": "0fb77f322f94b09fc199cb7ab67358d564700217",
"size": "4252",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/common/CVarDefMap.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9025849"
},
{
"name": "C++",
"bytes": "4506597"
},
{
"name": "CMake",
"bytes": "12997"
},
{
"name": "Makefile",
"bytes": "5728"
},
{
"name": "Objective-C",
"bytes": "148556"
},
{
"name": "Pascal",
"bytes": "1988"
}
],
"symlink_target": ""
} |
<div class="content" ng-controller="blogArticleUpdateController">
<form ng-submit="update()" ng-model='article'>
<div class="input-prepend">
<span class="add-on"><i class="icon-bookmark"></i></span>
<input type=text placeholder="Titre" name="title" ng-model='article.title'>
</div>
<div class="input-prepend">
<span class="add-on"><i class="icon-tag"></i></span>
<input type=text placeholder="Langage, Application, Service, Tags" name="tags" ng-change="handleTag()" ng-model='article.tagsRepo'>
</div>
<span ng-repeat="tag in article.tags">
<span ng-click='removeTag($index)' class="label"><i class="icon-remove icon-white"></i> [[tag.name]]</span>
</span>
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="active"><a href="#tab-md" data-toggle="tab">Markdown</a></li>
<li><a href="#tab-prev" data-toggle="tab">Preview</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab-md">
<textarea ui-codemirror="editorOptions" ng-model="article.content"></textarea>
<a href="" ng-click="openHelp()">Aide Markdown</a>
</div>
<div class="tab-pane" id="tab-prev">
<div ng-bind-html-unsafe="article.content|markdown"></div>
</div>
</div>
</div>
<button class="btn btn-inverse btn-large pull-right" style="margin-top: 30px;" type="submit">Enregistrer</button>
</form>
</div>
| {
"content_hash": "1c26f41ae1596bafcefbd5a6f5dcb840",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 139,
"avg_line_length": 49.225806451612904,
"alnum_prop": 0.5865006553079948,
"repo_name": "gulian/fuzzy-octo-hipster",
"id": "7f446b21734e4f359880624b9e67a0ab4f1b7173",
"size": "1526",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/partials/update-article.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "48022"
},
{
"name": "JavaScript",
"bytes": "833430"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_02) on Tue Apr 29 11:29:42 CEST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>BuildBinaryTask (Gradle API 1.12)</title>
<meta name="date" content="2014-04-29">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="BuildBinaryTask (Gradle API 1.12)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/gradle/nativebinaries/tasks/BuildBinaryTask.html" target="_top">Frames</a></li>
<li><a href="BuildBinaryTask.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.gradle.nativebinaries.tasks</div>
<h2 title="Interface BuildBinaryTask" class="title">Interface BuildBinaryTask</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre><a href="../../../../org/gradle/api/Incubating.html" title="annotation in org.gradle.api">@Incubating</a>
public interface <span class="strong">BuildBinaryTask</span></pre>
<div class="block">A task that combines a set of object files into a single binary.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/nativebinaries/tasks/BuildBinaryTask.html#source(java.lang.Object)">source</a></strong>(<a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> source)</code>
<div class="block">Adds a set of object files to be combined into the file binary.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="source(java.lang.Object)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>source</h4>
<pre>void source(<a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> source)</pre>
<div class="block">Adds a set of object files to be combined into the file binary.
The provided source object is evaluated as per <a href="../../../../org/gradle/api/Project.html#files(java.lang.Object...)"><code>Project.files(Object...)</code></a>.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/gradle/nativebinaries/tasks/BuildBinaryTask.html" target="_top">Frames</a></li>
<li><a href="BuildBinaryTask.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "c61483d29fa1066cd3d5a7ddcbe3746d",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 318,
"avg_line_length": 32.88625592417062,
"alnum_prop": 0.6280443867992506,
"repo_name": "Pushjet/Pushjet-Android",
"id": "43b1c69dbab55fe5644cf5b9b40bba93870f8d40",
"size": "6939",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/docs/javadoc/org/gradle/nativebinaries/tasks/BuildBinaryTask.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "92331"
}
],
"symlink_target": ""
} |
<?php
namespace PHPExiftool\Driver\Tag\Olympus;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class AFAreas extends AbstractTag
{
protected $Id = 772;
protected $Name = 'AFAreas';
protected $FullName = 'Olympus::CameraSettings';
protected $GroupName = 'Olympus';
protected $g0 = 'MakerNotes';
protected $g1 = 'Olympus';
protected $g2 = 'Camera';
protected $Type = 'int32u';
protected $Writable = false;
protected $Description = 'AF Areas';
protected $flag_Permanent = true;
protected $MaxLength = 64;
}
| {
"content_hash": "40643ca80e1fc000221144736e2353d6",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 52,
"avg_line_length": 16.025,
"alnum_prop": 0.6645865834633385,
"repo_name": "bburnichon/PHPExiftool",
"id": "c18f3561a11616f98b1e08adc3d79a09a1d059ce",
"size": "865",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/PHPExiftool/Driver/Tag/Olympus/AFAreas.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22076400"
}
],
"symlink_target": ""
} |
#pragma checksum "..\..\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "6371E80F268951A6155954FACA293918"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18408
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
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 Solution_CS_WPF {
/// <summary>
/// App
/// </summary>
public partial class App : System.Windows.Application {
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
#line 4 "..\..\App.xaml"
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
Solution_CS_WPF.App app = new Solution_CS_WPF.App();
app.InitializeComponent();
app.Run();
}
}
}
| {
"content_hash": "bfeb20a0134a9d61c8b87c649fc82992",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 110,
"avg_line_length": 32.42028985507246,
"alnum_prop": 0.6119803308001788,
"repo_name": "noah95/RGB_LED_Controller",
"id": "1fac99f03938447a3e61a0746a904108e0390f35",
"size": "2239",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Solution_CS_WPF/Solution_CS_WPF/obj/Debug/App.g.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "11333"
},
{
"name": "C#",
"bytes": "31056"
},
{
"name": "C++",
"bytes": "198"
},
{
"name": "D",
"bytes": "560"
},
{
"name": "Shell",
"bytes": "1339"
}
],
"symlink_target": ""
} |
<!--
@license Apache-2.0
Copyright (c) 2018 The Stdlib 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.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title></title>
<style>
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
</style>
<style>
body {
box-sizing: border-box;
width: 100%;
padding: 40px;
}
#console {
width: 100%;
}
</style>
</head>
<body>
<p id="status">Running...</p>
<br>
<div id="console"></div>
<script type="text/javascript">
(function() {
'use strict';
// VARIABLES //
var methods = [
'log',
'error',
'warn',
'dir',
'debug',
'info',
'trace'
];
// MAIN //
/**
* Main.
*
* @private
*/
function main() {
var console;
var str;
var el;
var i;
// FIXME: IE9 has a non-standard `console.log` object (http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9)
console = window.console || {};
for ( i = 0; i < methods.length; i++ ) {
console[ methods[ i ] ] = write;
}
el = document.querySelector( '#console' );
str = el.innerHTML;
/**
* Writes content to a DOM element. Note that this assumes a single argument and no substitution strings.
*
* @private
* @param {string} message - message
*/
function write( message ) {
str += '<p>'+message+'</p>';
el.innerHTML = str;
}
}
main();
})();
</script>
<script type="text/javascript" src="/docs/api/latest/@stdlib/array/zeros-like/test_bundle.js"></script>
</body>
</html>
| {
"content_hash": "0838e8acc0b1f20505ba1cb1768438ee",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 139,
"avg_line_length": 22.233333333333334,
"alnum_prop": 0.6218890554722639,
"repo_name": "stdlib-js/www",
"id": "271a051a1aba755ffbdc88e4d8162e4436acaf5d",
"size": "3335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/docs/api/latest/@stdlib/array/zeros-like/test.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "190538"
},
{
"name": "HTML",
"bytes": "158086013"
},
{
"name": "Io",
"bytes": "14873"
},
{
"name": "JavaScript",
"bytes": "5395746994"
},
{
"name": "Makefile",
"bytes": "40479"
},
{
"name": "Shell",
"bytes": "9744"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="activity_masterdetail" type="layout">@layout/activity_base</item>
</resources> | {
"content_hash": "211ec3fe05b5c98718646202c2b29f49",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 81,
"avg_line_length": 36.25,
"alnum_prop": 0.7034482758620689,
"repo_name": "twisstosin/UdacityBakingAndroid",
"id": "6b354b7e021ab3c22183806ae7ffc8fefc2fafcc",
"size": "145",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/values/refs.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "58672"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta content="text/html; charset=iso-8859-1" http-equiv="content-type">
<title>Radius of gyration</title>
<link rel="stylesheet" type="text/css" href="Help.css">
</head>
<body>
<h1>Radius of gyration</h1>
<p>This can be used to calculate the radius of gyration (RoG) for the
polygon features within a raster image. RoG measures how far across
the landscape a polygon extends its reach on average, given by the
mean distance between cells in a patch (Mcgarigal et al. 2002).
The radius of gyration can be considered a measure of the average
distance an organism can move within a patch before encountering
the patch boundary from a random starting point (Mcgarigal et al.
2002). The input raster grid should contain polygons with unique
identifiers greater than zero. The user must also specify the name
of the output raster file (where the radius of gyration will be
assigned to each feature in the input file) and the specified
option of outputting text data.</p>
<h2 class="SeeAlso">See Also:</h2>
<ul>
<li>None</li>
</ul>
<h2 class="SeeAlso">Scripting:</h2>
<p>The following is an example of a Python script that uses this tool:</p>
<p style="background-color: rgb(240,240,240)">
<code>
wd = pluginHost.getWorkingDirectory() <br>
inputFile = wd + "polygons.dep" <br>
outputFile = wd + "output.dep" <br>
textOutput = "true" <br>
args = [inputFile, outputFile, textOutput] <br>
pluginHost.runPlugin("RadiusOfGyration", args, False) <br>
</code>
</p>
<p>This is a Groovy script also using this tool:</p>
<p style="background-color: rgb(240,240,240)">
<code>
def wd = pluginHost.getWorkingDirectory() <br>
def inputFile = wd + "polygons.dep" // raster input <br>
def outputFile = wd + "output.dep" <br>
def textOutput = "true" <br>
String[] args = [inputFile, outputFile, textOutput] <br>
pluginHost.runPlugin("RadiusOfGyration", args, False) <br>
</code>
</p>
<h2 class="SeeAlso">Credits:</h2>
<ul>
<li>John Lindsay (2012)</li>
</ul>
<h2 class="SeeAlso">References:</h2>
<ul><li>Mcgarigal, K., Cushman, S. A., Neel, M. C., & Ene, E. (2002).
FRAGSTATS: spatial pattern analysis program for categorical maps.</li>
</ul>
</body>
</html>
| {
"content_hash": "fb129ef2186836eca26f68cdfe87d064",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 90,
"avg_line_length": 44.59090909090909,
"alnum_prop": 0.5616717635066258,
"repo_name": "jblindsay/jblindsay.github.io",
"id": "6ca9ad4be19c1aa60959c62eff12f452f5944a87",
"size": "2943",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ghrg/Whitebox/WhiteboxGAT-linux/resources/Help/RadiusOfGyration.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "52"
},
{
"name": "CSS",
"bytes": "1086446"
},
{
"name": "Groovy",
"bytes": "2186907"
},
{
"name": "HTML",
"bytes": "11454480"
},
{
"name": "Java",
"bytes": "5373007"
},
{
"name": "JavaScript",
"bytes": "1745824"
},
{
"name": "Python",
"bytes": "82583"
},
{
"name": "SCSS",
"bytes": "173472"
},
{
"name": "TeX",
"bytes": "15589"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Create and initialize new event base</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.event-base-loopexit.html">event_base_loopexit</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.event-base-priority-init.html">event_base_priority_init</a></div>
<div class="up"><a href="ref.libevent.html">Libevent Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="function.event-base-new" class="refentry">
<div class="refnamediv">
<h1 class="refname">event_base_new</h1>
<p class="verinfo">(PECL libevent >= 0.0.1)</p><p class="refpurpose"><span class="refname">event_base_new</span> — <span class="dc-title">Create and initialize new event base</span></p>
</div>
<div class="refsect1 description" id="refsect1-function.event-base-new-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="type">resource</span> <span class="methodname"><strong>event_base_new</strong></span>
( <span class="methodparam">void</span>
)</div>
<p class="para rdfs-comment">
Returns new event base, which can be used later in <span class="function"><a href="function.event-base-set.html" class="function">event_base_set()</a></span>,
<span class="function"><a href="function.event-base-loop.html" class="function">event_base_loop()</a></span> and other functions.
</p>
</div>
<div class="refsect1 parameters" id="refsect1-function.event-base-new-parameters">
<h3 class="title">Parameters</h3>
<p class="para">This function has no parameters.</p>
<p class="para">
</p>
</div>
<div class="refsect1 returnvalues" id="refsect1-function.event-base-new-returnvalues">
<h3 class="title">Return Values</h3>
<p class="para">
<span class="function"><strong>event_base_new()</strong></span> returns valid event base resource on
success or <strong><code>FALSE</code></strong> on error.
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.event-base-loopexit.html">event_base_loopexit</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.event-base-priority-init.html">event_base_priority_init</a></div>
<div class="up"><a href="ref.libevent.html">Libevent Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
| {
"content_hash": "cbf3b1c00f68defe3003f6c3c3a6165c",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 196,
"avg_line_length": 49.55357142857143,
"alnum_prop": 0.6897297297297297,
"repo_name": "dpkshrma/phpdox",
"id": "8f1f0d5f63f8e9a9e68059eaece56887218ef189",
"size": "2775",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "functions/function.event-base-new.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "26553092"
},
{
"name": "PHP",
"bytes": "8567"
},
{
"name": "Shell",
"bytes": "286"
}
],
"symlink_target": ""
} |
import { Component, ViewChild, Input, Output, OnInit, EventEmitter } from '@angular/core';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import { OrderWindowComponent } from '../order-window/order-window.component';
import { DoctorsListComponent } from '../doctorsList/doctors-list.component';
import { OrderRequest } from '../order-window/order-request';
import { SpecialityService } from '../shared/speciality/speciality.service';
import { Specialities } from '../shared/speciality/speciality';
/**
* This class represents the lazy loaded HomeComponent.
*/
@Component({
moduleId: module.id,
selector: 'mm-home',
templateUrl: 'home.component.html',
styleUrls: ['home.component.css']
})
export class HomeComponent implements OnInit {
pageTitle: string = 'Mesomeds';
speciality: string;
mobileNumber: number;
specialities: Specialities[];
@ViewChild(OrderWindowComponent)
modalHtml: OrderWindowComponent;
@ViewChild(DoctorsListComponent)
modalHtml1: DoctorsListComponent;
current:string = 'Select'; //first string to load in the select field
constructor(private specialityService: SpecialityService) { //constructor for LocationService
}
//function to validate the phone number entered and open the OrderWindow else show an alert
open(value: any) {
let result: boolean = isNaN(value.mobileNumber);
if (result === true || value.mobileNumber.toString().length < 10 || value.mobileNumber.toString().match(/^\s*$/g)) {
return;
} else {
this.modalHtml.open();
}
console.log(value.speciality);
}
openConsultant(value: any) {
let result: boolean = isNaN(value.mobileNumber);
let speciality: string = value.speciality;
if (result === true || value.mobileNumber.toString().length < 10 || value.mobileNumber.toString().match(/^\s*$/g)
|| speciality === null || speciality === 'Select') {
return;
} else {
this.modalHtml1.open();
}
}
//initializes the select field options from LocationService
ngOnInit(): void {
this.getSpecialities();
}
getSpecialities() {
this.specialityService.getSpecialities()
.then(Specialities => {
this.specialities = Specialities;
});
}
}
| {
"content_hash": "7c0e8cfed1a3a67d739f16676295a8a5",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 120,
"avg_line_length": 32.2463768115942,
"alnum_prop": 0.701123595505618,
"repo_name": "rawnics/mesomeds-ng2",
"id": "3d43740f5270e861a8ab3a3c9400d3ea4698b847",
"size": "2225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/client/app/home/home.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15312"
},
{
"name": "HTML",
"bytes": "69490"
},
{
"name": "JavaScript",
"bytes": "7120"
},
{
"name": "Nginx",
"bytes": "1052"
},
{
"name": "TypeScript",
"bytes": "84781"
}
],
"symlink_target": ""
} |
extern NSString *const UpdateProgressNotification;
@interface CustomTableViewController : UITableViewController
@end
| {
"content_hash": "726856ec190ac8f8b5667c5875302abf",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 60,
"avg_line_length": 23.8,
"alnum_prop": 0.865546218487395,
"repo_name": "hanks/Multi_Status_Checklist_Demo",
"id": "f2609aa2c23a40ee7ae72e2e1227ed7b351081e8",
"size": "144",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ScrollCellTest/CustomTableViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "26644"
}
],
"symlink_target": ""
} |
package us.kbase.wholegenomealignment;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* <p>Original spec-file type: MugsyParams</p>
* <pre>
* Run Mugsy.
* workspace_name - the name of the workspace for input/output
* input_genome_refs - input list of references to genome objects
* output_alignment_name - the name of the output alignment
* minlength - minimum span of an aligned region in a colinear block (bp), default 30
* distance - maximum distance along a single sequence (bp) for chaining
* anchors into locally colinear blocks (LCBs), default 1000
* @optional minlength
* @optional distance
* </pre>
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
"workspace_name",
"input_genome_names",
"minlength",
"distance"
})
public class MugsyParams {
@JsonProperty("workspace_name")
private java.lang.String workspaceName;
@JsonProperty("input_genome_names")
private List<String> inputGenomeNames;
@JsonProperty("minlength")
private Long minlength;
@JsonProperty("distance")
private Long distance;
private Map<java.lang.String, Object> additionalProperties = new HashMap<java.lang.String, Object>();
@JsonProperty("workspace_name")
public java.lang.String getWorkspaceName() {
return workspaceName;
}
@JsonProperty("workspace_name")
public void setWorkspaceName(java.lang.String workspaceName) {
this.workspaceName = workspaceName;
}
public MugsyParams withWorkspaceName(java.lang.String workspaceName) {
this.workspaceName = workspaceName;
return this;
}
@JsonProperty("input_genome_names")
public List<String> getInputGenomeNames() {
return inputGenomeNames;
}
@JsonProperty("input_genome_names")
public void setInputGenomeNames(List<String> inputGenomeNames) {
this.inputGenomeNames = inputGenomeNames;
}
public MugsyParams withInputGenomeNames(List<String> inputGenomeNames) {
this.inputGenomeNames = inputGenomeNames;
return this;
}
@JsonProperty("minlength")
public Long getMinlength() {
return minlength;
}
@JsonProperty("minlength")
public void setMinlength(Long minlength) {
this.minlength = minlength;
}
public MugsyParams withMinlength(Long minlength) {
this.minlength = minlength;
return this;
}
@JsonProperty("distance")
public Long getDistance() {
return distance;
}
@JsonProperty("distance")
public void setDistance(Long distance) {
this.distance = distance;
}
public MugsyParams withDistance(Long distance) {
this.distance = distance;
return this;
}
@JsonAnyGetter
public Map<java.lang.String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperties(java.lang.String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public java.lang.String toString() {
return ((((((((((("MugsyParams"+" [workspaceName=")+ workspaceName)+", inputGenomeNames=")+ inputGenomeNames)+", minlength=")+ minlength)+", distance=")+ distance)+", additionalProperties=")+ additionalProperties)+"]");
}
}
| {
"content_hash": "6dacdf7fa243d2341389364c3e3ea741",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 227,
"avg_line_length": 29.936,
"alnum_prop": 0.6932121859967931,
"repo_name": "levinas/kb_wga",
"id": "41066cd995ad4e61fc2cd12e182102fa26cbf2c6",
"size": "3742",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/src/us/kbase/wholegenomealignment/MugsyParams.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "11618"
},
{
"name": "JavaScript",
"bytes": "3696"
},
{
"name": "Makefile",
"bytes": "2791"
},
{
"name": "Perl",
"bytes": "10696"
},
{
"name": "Python",
"bytes": "57696"
},
{
"name": "Ruby",
"bytes": "1444"
},
{
"name": "Shell",
"bytes": "1645"
}
],
"symlink_target": ""
} |
*New console commands*:
Basic stuff you can call by typing `/<command>` in OA game console.
```
- bet <horse>[red,blue] <amount> <currency>[BTC,OAC]
- unbet <bet_ID>
- pastBets
- pastBets elder
- betsSummary
- ready
- help
- shareBalance
- shareBalance <currency>[BTC,OAC]
- timeout
- timein
```
*New Cvars*
**Server-side:**<br>
- `g_enableBetting`<br>
1 to enable *all* the betting features, 1 by default.
- `g_backendAddr`<br>
The address (IP:port) string of oatot backend.
This Cvar has the same defaults as backend's `grpc-addr` flag.
- `g_makingBetsTime`<br>
The duration of MAKING_BETS in mins, 2 by default.
- `g_easyItemPickup`<br>
1 for easy item pickup (high items), 1 by default.
- `g_scoreboardDefaultSeason`<br>
Season which will be set as default scoreboard season on clients, 1 by default.
0 - no season, 1 - winter, 2 - spring, 3 - summer, 4 - autumn.
- `g_allowTimeouts`<br>
Allows all players to use `/timeout` cmd, 1 by default.
- `g_afterTimeoutTime`<br>
Time to wait after `/timein` cmd (in seconds).
**Client-side:**<br>
- `cg_scoreboardEffects`<br>
1 to enable additional scoreboard effects, 0 by default.
- `cg_scoreboardSeason`<br>
Scoreboard season, `g_scoreboardDefaultSeason` (server-side Cvar) by default.
0 - no season, 1 - winter, 2 - spring, 3 - summer, 4 - autumn.
Set to -1 in order to set server defaults again.
Will be forced updated when default changes on the server.
- `cg_scoreboardAggressive`<br>
1 to enable aggressive scoreboard effects. Incompatible with `cg_scoreboardSeason != 0`.
0 by default.
- `cg_hudFlagStyle`<br>
0 to disable new flag status HUD.
1 by default.
| {
"content_hash": "a3dfc1c7be24b53112bf870b40058f7c",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 92,
"avg_line_length": 33.61538461538461,
"alnum_prop": 0.6670480549199085,
"repo_name": "GuildDio/oatot",
"id": "8ec550a86e7db816b42b765a390d8a364642a8ad",
"size": "1748",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mod_doc.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "12490"
},
{
"name": "Awk",
"bytes": "1281"
},
{
"name": "Batchfile",
"bytes": "12237"
},
{
"name": "C",
"bytes": "5158342"
},
{
"name": "C++",
"bytes": "122101"
},
{
"name": "Go",
"bytes": "28190"
},
{
"name": "HTML",
"bytes": "69260"
},
{
"name": "Makefile",
"bytes": "81856"
},
{
"name": "Objective-C",
"bytes": "5946"
},
{
"name": "Roff",
"bytes": "21060"
},
{
"name": "ShaderLab",
"bytes": "1045"
},
{
"name": "Shell",
"bytes": "554"
},
{
"name": "XSLT",
"bytes": "1109"
},
{
"name": "Yacc",
"bytes": "4247"
}
],
"symlink_target": ""
} |
@interface GPPromotion : NSObject
@property (copy, nonatomic) NSString *color;
@property (copy, nonatomic) NSString *icon_url;
@property (copy, nonatomic) NSString *ID;
@property (copy, nonatomic) NSString *target_url;
@property (copy, nonatomic) NSString *title;
@end
| {
"content_hash": "faa7bcd6410d06b1cfa32692a208165a",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 49,
"avg_line_length": 38.42857142857143,
"alnum_prop": 0.758364312267658,
"repo_name": "yslwjj/GiftPick",
"id": "03546046f967c1ae67cb539da6ebf046e77883c5",
"size": "439",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "礼物说/Classes/Gift(礼物说)/Model/GPPromotion.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "344406"
},
{
"name": "Ruby",
"bytes": "197"
}
],
"symlink_target": ""
} |
class Text < ActiveRecord::Base
attr_accessible :title, :text, :section_title, :section_order
def Text.mission_statement_sections
#get distinct mission statement sections
statements = Text.where(:section_title => "Mission Statement").order(:section_order)
statement_ids = Hash[statements.map{|statement| [statement.section_order, statement]}]
statement_ids.values
end
end
| {
"content_hash": "fc953816f9b91226976bf51fec2f117e",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 90,
"avg_line_length": 39.5,
"alnum_prop": 0.7443037974683544,
"repo_name": "eabartlett/ratemypup",
"id": "eee9da8caaceb40d992080b4dcf595fea5c4db4e",
"size": "395",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/text.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12829"
},
{
"name": "CoffeeScript",
"bytes": "229"
},
{
"name": "Cucumber",
"bytes": "21514"
},
{
"name": "HTML",
"bytes": "29039"
},
{
"name": "JavaScript",
"bytes": "39867"
},
{
"name": "Ruby",
"bytes": "118974"
},
{
"name": "Shell",
"bytes": "191"
}
],
"symlink_target": ""
} |
package demo.catalog.coursera.org.courserademoapp.network;
import com.google.gson.Gson;
import java.util.List;
import javax.inject.Inject;
import demo.catalog.coursera.org.courserademoapp.BuildConfig;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
import retrofit.http.GET;
import rx.Observable;
public class CourseraNetworkServiceImpl implements CourseraNetworkService {
public CatalogAPIService mCatalogAPIService;
RestAdapter catalogRestAdapter;
public CourseraNetworkServiceImpl() {
catalogRestAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.coursera.org")
.setConverter(new GsonConverter(new Gson()))
.setLogLevel((BuildConfig.DEBUG ?
RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE))
.build();
mCatalogAPIService = catalogRestAdapter.create(CatalogAPIService.class);
}
@Override
public Observable<JSCourseResponse> getCourses() {
return mCatalogAPIService.getCourses();
}
public interface CatalogAPIService {
@GET("/api/catalog.v1/courses?fields=smallIcon")
Observable<JSCourseResponse> getCourses();
}
}
| {
"content_hash": "06c8f5e3d37f05c5ee7ddbe0bd2b0e01",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 80,
"avg_line_length": 30.7,
"alnum_prop": 0.7125407166123778,
"repo_name": "Eagles2F/CourseraDemoApp",
"id": "ffd0e69144f06208e80d3ee0c36cdc935362ae17",
"size": "1228",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/src/main/java/demo/catalog/coursera/org/courserademoapp/network/CourseraNetworkServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "28842"
}
],
"symlink_target": ""
} |
const context = {};
global.w = Object.create(context);
w.proto = context;
const Module = require('module');
//const orig_require = Module.prototype.require;
//Module.prototype.require = function(id){ return orig_require(id); }
//Module.prototype.require = function(id){ return orig_require.call(this, id); }
//create context prototype
////const context = {};
//context.proto = context;
//create global work context
////const w = Module.prototype.work = Object.create(context);
////w.proto = context;
require("./doc.js");
require("./dependencies.js");
w.mw = {};
w.cache = {};
//work_require for autoreload in development mode defaults to require
Module.prototype.work_require = Module.prototype.require;
w.proto.rootdir = process.cwd();
w.proto.coredir = __dirname.replace("/core", "");
w.conf = {};
require("../CONF");
require(w.rootdir+"/CONF");
require("./work.js");
require("./logger.js");
w.log("WorkJS starting >>> " + w.conf.name);
if (w.conf.servermode.toUpperCase() == "DEVELOPMENT") {
Module.prototype.work_require = function requireUncached(module){
delete require.cache[require.resolve(module)];
return require.call(w, module);
};
};
w.verbs = [];
w.flags = {};
for (var i = 0; i<w.conf.verbs.length; ++i) {
var verb = w.conf.verbs[i];
w.verbs.push(verb);
w.flags[verb] = w.conf.flags[verb] || w.conf.flags["default"]
};
//load templating subsystem
///w.templating = module.require('./templating.js')({
/// searchpaths: [w.rootdir, w.rootdir+'/LAYOUT']
///});
//load database subsystem
//w.dbm = require('./pg_native.js')({dburl:w.conf.db_url, poolsize:w.conf.db_poolsize});
//w.db = w.dbm.db;
//install required DB contents
w.dep.syncho(function setup() {
require('./pg.js');
require('./db.js');
require('./cookies.js');
//load global db fkts
///// deleted !! var dbfkt = require("./db.js");
require('./util.js');
//load session subsystem
require('./session.js');
//load user+auth subsystem
require('./auth.js');
require('./groups.js');
//load email subsystem
require('./smtp.js');
//load content repository subsystem
require('./repo.js');
require('./work-socket.js');
try { w.dependencies.fs.mkdirSync(w.conf.uploaddir); } catch (e) { };
/////YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
//w.Work = require("./Work.js");
//w.Work.prototype.work = w;
require("./body_parser.js");
//parse packages into route map
w.map = {};
w.packages = {};
require("./package_parser.js");
//start requests processor
require("./request_processor.js");
w.api_doc.init();
});
| {
"content_hash": "a3c35a2a6911c09e5a605338e99f1ece",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 88,
"avg_line_length": 22.663716814159294,
"alnum_prop": 0.6548223350253807,
"repo_name": "workjs/workjs",
"id": "6ad0f2874ab9377b4345570e07ecea20d8834158",
"size": "2635",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/bootstrap.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "341"
},
{
"name": "HTML",
"bytes": "1627"
},
{
"name": "JavaScript",
"bytes": "74499"
}
],
"symlink_target": ""
} |
Store app settings
[](https://travis-ci.org/woodstage/node-app-settings)
[](https://coveralls.io/github/woodstage/node-app-settings)
[](https://www.npmjs.org/package/node-app-settings)
[](https://npmjs.org/package/node-app-settings)
[](http://isitmaintained.com/project/woodstage/node-app-settings "Average time to resolve an issue")
## Supported Types
* JSON
* INI
* YAML
## Usage
You can create settings object by providing setting file path and type. If the file doesn't exist, a new file will be created on the path.
```javascript
const appSettings = require('node-app-settings');
let iniSetting = appSettings.create('settings.ini', 'INI');
let jsonSetting = appSettings.create('settings.json', 'JSON');
let yamlSetting = appSettings.create('settings.yml', 'YAML');
```
You can then get/update settings on the object. And if you want to store any settings, don't forget to call **flush** before exit.
```javascript
let settings = appSettings.create('settings.json');//Absolute path or relative path
let config = settings.config; //Get the setting data object
config.user = 'Bob';
config.password = 'xxx';
settings.flush((err => {
console.log(err);
})); //Save to file asynchronous
settings.flushSync(); //Save to file
```
## LICENSE
MIT
| {
"content_hash": "f25f47bb00f212207e75bf9d16dbc211",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 211,
"avg_line_length": 42.8,
"alnum_prop": 0.7470794392523364,
"repo_name": "woodstage/node-app-settings",
"id": "f078f8760e4ef11d43d51970433acec5dcb2fc29",
"size": "1732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "937"
},
{
"name": "TypeScript",
"bytes": "8921"
}
],
"symlink_target": ""
} |
package org.apache.accumulo.test.continuous;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.cli.BatchScannerOpts;
import org.apache.accumulo.core.cli.ClientOnDefaultTable;
import org.apache.accumulo.core.cli.ScannerOpts;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.hadoop.io.Text;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.validators.PositiveInteger;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
public class ContinuousBatchWalker {
static class Opts extends ContinuousWalk.Opts {
@Parameter(names = "--numToScan", description = "Number rows to scan between sleeps", required = true, validateWith = PositiveInteger.class)
long numToScan = 0;
}
public static void main(String[] args) throws Exception {
Opts opts = new Opts();
ScannerOpts scanOpts = new ScannerOpts();
BatchScannerOpts bsOpts = new BatchScannerOpts();
ClientOnDefaultTable clientOpts = new ClientOnDefaultTable("ci");
clientOpts.parseArgs(ContinuousBatchWalker.class.getName(), args, scanOpts, bsOpts, opts);
Random r = new Random();
Authorizations auths = opts.randomAuths.getAuths(r);
Connector conn = clientOpts.getConnector();
Scanner scanner = ContinuousUtil.createScanner(conn, clientOpts.getTableName(), auths);
scanner.setBatchSize(scanOpts.scanBatchSize);
while (true) {
BatchScanner bs = conn.createBatchScanner(clientOpts.getTableName(), auths, bsOpts.scanThreads);
bs.setTimeout(bsOpts.scanTimeout, TimeUnit.MILLISECONDS);
Set<Text> batch = getBatch(scanner, opts.min, opts.max, scanOpts.scanBatchSize, r);
List<Range> ranges = new ArrayList<Range>(batch.size());
for (Text row : batch) {
ranges.add(new Range(row));
}
runBatchScan(scanOpts.scanBatchSize, bs, batch, ranges);
sleepUninterruptibly(opts.sleepTime, TimeUnit.MILLISECONDS);
}
}
private static void runBatchScan(int batchSize, BatchScanner bs, Set<Text> batch, List<Range> ranges) {
bs.setRanges(ranges);
Set<Text> rowsSeen = new HashSet<Text>();
int count = 0;
long t1 = System.currentTimeMillis();
for (Entry<Key,Value> entry : bs) {
ContinuousWalk.validate(entry.getKey(), entry.getValue());
rowsSeen.add(entry.getKey().getRow());
addRow(batchSize, entry.getValue());
count++;
}
bs.close();
long t2 = System.currentTimeMillis();
if (!rowsSeen.equals(batch)) {
HashSet<Text> copy1 = new HashSet<Text>(rowsSeen);
HashSet<Text> copy2 = new HashSet<Text>(batch);
copy1.removeAll(batch);
copy2.removeAll(rowsSeen);
System.out.printf("DIF %d %d %d%n", t1, copy1.size(), copy2.size());
System.err.printf("DIF %d %d %d%n", t1, copy1.size(), copy2.size());
System.err.println("Extra seen : " + copy1);
System.err.println("Not seen : " + copy2);
} else {
System.out.printf("BRQ %d %d %d %d %d%n", t1, (t2 - t1), rowsSeen.size(), count, (int) (rowsSeen.size() / ((t2 - t1) / 1000.0)));
}
}
private static void addRow(int batchSize, Value v) {
byte[] val = v.get();
int offset = ContinuousWalk.getPrevRowOffset(val);
if (offset > 1) {
Text prevRow = new Text();
prevRow.set(val, offset, 16);
if (rowsToQuery.size() < 3 * batchSize) {
rowsToQuery.add(prevRow);
}
}
}
private static HashSet<Text> rowsToQuery = new HashSet<Text>();
private static Set<Text> getBatch(Scanner scanner, long min, long max, int batchSize, Random r) {
while (rowsToQuery.size() < batchSize) {
byte[] scanStart = ContinuousIngest.genRow(min, max, r);
scanner.setRange(new Range(new Text(scanStart), null));
int count = 0;
long t1 = System.currentTimeMillis();
Iterator<Entry<Key,Value>> iter = scanner.iterator();
while (iter.hasNext() && rowsToQuery.size() < 3 * batchSize) {
Entry<Key,Value> entry = iter.next();
ContinuousWalk.validate(entry.getKey(), entry.getValue());
addRow(batchSize, entry.getValue());
count++;
}
long t2 = System.currentTimeMillis();
System.out.println("FSB " + t1 + " " + (t2 - t1) + " " + count);
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
HashSet<Text> ret = new HashSet<Text>();
Iterator<Text> iter = rowsToQuery.iterator();
for (int i = 0; i < batchSize; i++) {
ret.add(iter.next());
iter.remove();
}
return ret;
}
}
| {
"content_hash": "038e2826982b0b58bb0ca1c2f9c4ee7e",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 144,
"avg_line_length": 31.41875,
"alnum_prop": 0.6781380545056693,
"repo_name": "dhutchis/accumulo",
"id": "dc77f37cc33cb0b049fe7ea815e9deab2cda554f",
"size": "5828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/src/main/java/org/apache/accumulo/test/continuous/ContinuousBatchWalker.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2423"
},
{
"name": "C++",
"bytes": "2274937"
},
{
"name": "CSS",
"bytes": "5933"
},
{
"name": "Groovy",
"bytes": "1385"
},
{
"name": "HTML",
"bytes": "11698"
},
{
"name": "Java",
"bytes": "22224331"
},
{
"name": "JavaScript",
"bytes": "249600"
},
{
"name": "Makefile",
"bytes": "2560"
},
{
"name": "Perl",
"bytes": "28190"
},
{
"name": "Protocol Buffer",
"bytes": "1325"
},
{
"name": "Python",
"bytes": "1005923"
},
{
"name": "Ruby",
"bytes": "272223"
},
{
"name": "Shell",
"bytes": "201208"
},
{
"name": "Thrift",
"bytes": "62455"
}
],
"symlink_target": ""
} |
. /etc/profile
# disable ipv6 to bypass Linode apt issue
sysctl -w net.ipv6.conf.all.disable_ipv6=1
sysctl -w net.ipv6.conf.default.disable_ipv6=1
apt-get -y update && apt-get -y upgrade
## File : update_ubuntu_system.sh ends
| {
"content_hash": "f35ff877b1a6d08bad44268d5ebd17f7",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 46,
"avg_line_length": 37.666666666666664,
"alnum_prop": 0.7433628318584071,
"repo_name": "TOTVS/mdmpublic",
"id": "eda46b0411fc21cfbcbaa07668c0f2dabd353478",
"size": "561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chef/update_ubuntu_system.sh",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "2022"
},
{
"name": "CSS",
"bytes": "232815"
},
{
"name": "Emacs Lisp",
"bytes": "370404"
},
{
"name": "Erlang",
"bytes": "162029"
},
{
"name": "HTML",
"bytes": "344417"
},
{
"name": "JavaScript",
"bytes": "1548603"
},
{
"name": "Makefile",
"bytes": "30654"
},
{
"name": "Python",
"bytes": "1227549"
},
{
"name": "Ruby",
"bytes": "1576"
},
{
"name": "Shell",
"bytes": "467880"
},
{
"name": "Tcl",
"bytes": "9372"
},
{
"name": "XSLT",
"bytes": "197715"
}
],
"symlink_target": ""
} |
using System;
using Microsoft.TeamFoundation.Client;
using NSubstitute;
using Rainbow.Tfs.Tests.SourceControl.Helpers;
using Xunit;
namespace Rainbow.Tfs.Tests.SourceControl
{
public class TfsFileHandlerTests
{
private const string Filename = "edit-me.yml";
private readonly Uri _uri = new Uri("http://google.com");
[Fact]
public void CheckoutFileForEdit_FileDoesNotExistOnServer_ThrowsException()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, false, false, false);
Assert.Throws<Exception>(() => handler.CheckoutFileForEdit());
}
[Fact]
public void AddFile_FileExistOnServer_ThrowsException()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, true, true, false);
Assert.Throws<Exception>(() => handler.AddFile());
}
[Fact]
public void AddFile_FileDoesNotExistOnFileSystem_ThrowsException()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, true, false, false);
Assert.Throws<Exception>(() => handler.AddFile());
}
[Fact]
public void AddFile_ZeroFilesUpdated_ReturnsFalse()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, false, true, false, 0);
bool success = handler.AddFile();
Assert.False(success);
}
[Fact]
public void AddFile_OneFileUpdated_ReturnsFalse()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, false, true, false, 1);
bool success = handler.AddFile();
Assert.True(success);
}
[Fact]
public void CheckoutFileForEdit_ZeroFilesUpdated_ReturnsFalse()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, true, true, false, 0);
bool success = handler.CheckoutFileForEdit();
Assert.False(success);
}
[Fact]
public void CheckoutFileForEdit_OneFileUpdated_ReturnsFalse()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, true, true, false, 1);
bool success = handler.CheckoutFileForEdit();
Assert.True(success);
}
[Fact]
public void CheckoutFileForDelete_ZeroFilesUpdated_ReturnsFalse()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, true, true, false, 0);
bool success = handler.CheckoutFileForDelete();
Assert.False(success);
}
[Fact]
public void CheckoutFileForDelete_OneFileUpdated_ReturnsFalse()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, true, true, false, 1);
bool success = handler.CheckoutFileForDelete();
Assert.True(success);
}
[Fact]
public void CheckoutFileForEdit_HasPendingEditChanges_ReturnsTrue()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, true, true, true, 0);
bool success = handler.CheckoutFileForEdit();
Assert.True(success);
}
[Fact]
public void CheckoutFileForDelete_HasPendingEditChanges_ReturnsTrue()
{
var collection = Substitute.For<TfsTeamProjectCollection>(_uri);
var handler = new TestableTfsFileHandler(collection, Filename, true, true, true, 0);
bool success = handler.CheckoutFileForDelete();
Assert.True(success);
}
}
}
| {
"content_hash": "766a2e5b71ce18145162123ee3c24f12",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 89,
"avg_line_length": 30.793388429752067,
"alnum_prop": 0.7428878153515834,
"repo_name": "PetersonDave/Rainbow.Tfs",
"id": "06f32708e206d6cae9fe360d6b59448ab8c2ad7c",
"size": "3728",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Src/Rainbow.Tfs.Tests/SourceControl/TfsFileHandlerTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "117"
},
{
"name": "C#",
"bytes": "32532"
},
{
"name": "PowerShell",
"bytes": "656"
}
],
"symlink_target": ""
} |
import numpy as np
import cv2
import sys
from video import Video
import os
if __name__ == "__main__":
videopath = sys.argv[1]
video = Video(videopath)
video.negate()
| {
"content_hash": "a26068e4ff5c81b8cdaa194fc6aa4050",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 28,
"avg_line_length": 15.153846153846153,
"alnum_prop": 0.5989847715736041,
"repo_name": "adobe-research/video-lecture-summaries",
"id": "da8c04e4d49673a02332477243ae8ad89faf6e64",
"size": "219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Scripts/negatevideo.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "6400"
},
{
"name": "BlitzBasic",
"bytes": "63"
},
{
"name": "CSS",
"bytes": "43297"
},
{
"name": "HTML",
"bytes": "15459294"
},
{
"name": "JavaScript",
"bytes": "239670"
},
{
"name": "PostScript",
"bytes": "3330579"
},
{
"name": "Python",
"bytes": "738196"
},
{
"name": "Ruby",
"bytes": "573"
},
{
"name": "TeX",
"bytes": "10314"
}
],
"symlink_target": ""
} |
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_THUNK_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_THUNK_H_
#include <memory>
#include <vector>
#include "tensorflow/compiler/xla/service/gpu/buffer_allocations.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/stream_executor_no_cuda.h"
namespace xla {
namespace gpu {
class GpuExecutable;
// Thunk acts as the bridge between IrEmitter and GpuExecutable. It stores the
// metadata IrEmitter generates for GpuExecutable to invoke an HloInstruction.
//
// Thunk provides the Initialize and ExecuteOnStream interface for GpuExecutable
// to initialize and execute the invocation respectively. Its subclasses are
// supposed to override these interfaces to launch a generated kernel or call an
// external library function (such as operations in cuBLAS).
//
// This is thread-compatible.
class Thunk {
public:
enum class Kind {
kConditional,
kConvolution,
kCopy,
kCudnnBatchNormBackward,
kCudnnBatchNormForwardInference,
kCudnnBatchNormForwardTraining,
kFft,
kGemm,
kInfeed,
kKernel,
kMemset32BitValue,
kMemzero,
kSequential,
kTuple,
kWhile,
};
// The hlo_instruction argument is meant to be the instruction this thunk was
// generated from, but Thunk never uses this argument other than to save it
// to Thunk::hlo_instruction, so it can be null.
explicit Thunk(Kind kind, const HloInstruction* hlo_instruction)
: kind_(kind), hlo_instruction_(hlo_instruction) {}
virtual ~Thunk() {}
Thunk(const Thunk&) = delete;
Thunk& operator=(const Thunk&) = delete;
Kind kind() const { return kind_; }
const HloInstruction* hlo_instruction() const { return hlo_instruction_; }
// Prepares the thunk for execution on the given StreamExecutor.
//
// This may be called multiple times. Its main purpose is to give us a chance
// to do initialization outside of ExecuteOnStream() so that the
// time spent initializing doesn't count towards our execution profile.
virtual Status Initialize(const GpuExecutable& /*executable*/,
se::StreamExecutor* /*executor*/) {
return Status::OK();
}
// Users of Thunk should call ShouldHaltAllActivityBeforeRunning(stream)
// before calling ExecuteOnStream(stream). If it returns true, it's the
// user's responsibility to wait for all activity on the GPU to finish before
// calling ExecuteOnStream.
//
// This value is not required to be constant for a given Thunk. For example,
// a Thunk that performs autotuning may return true for its first run and
// false thereafter.
virtual bool ShouldHaltAllActivityBeforeRunning(se::Stream* /*stream*/) {
return false;
}
// Execute the kernel for the thunk on the given stream. This method must be
// called after Initialize and can be called multiple times over Thunk's
// lifetime. Stream argument must be non-null.
//
// Precondition: Initialize(stream->parent()) has been called.
virtual Status ExecuteOnStream(const BufferAllocations& buffer_allocations,
se::Stream* stream) = 0;
private:
Kind kind_;
const HloInstruction* hlo_instruction_;
};
// A sequence of thunks.
using ThunkSequence = std::vector<std::unique_ptr<Thunk>>;
} // namespace gpu
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_THUNK_H_
| {
"content_hash": "22ac78b462e3d372b5f835d4b81d20bd",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 80,
"avg_line_length": 34.26732673267327,
"alnum_prop": 0.7243571222190118,
"repo_name": "nburn42/tensorflow",
"id": "931c0bffab850362dbd2df975657dd47d9cbd3ae",
"size": "4129",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "tensorflow/compiler/xla/service/gpu/thunk.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9274"
},
{
"name": "C",
"bytes": "341132"
},
{
"name": "C++",
"bytes": "39824558"
},
{
"name": "CMake",
"bytes": "194702"
},
{
"name": "Go",
"bytes": "1046987"
},
{
"name": "HTML",
"bytes": "4680032"
},
{
"name": "Java",
"bytes": "590137"
},
{
"name": "Jupyter Notebook",
"bytes": "1940883"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "48231"
},
{
"name": "Objective-C",
"bytes": "12456"
},
{
"name": "Objective-C++",
"bytes": "94385"
},
{
"name": "PHP",
"bytes": "2140"
},
{
"name": "Perl",
"bytes": "6179"
},
{
"name": "Perl 6",
"bytes": "1357"
},
{
"name": "PureBasic",
"bytes": "25356"
},
{
"name": "Python",
"bytes": "33704964"
},
{
"name": "Ruby",
"bytes": "533"
},
{
"name": "Shell",
"bytes": "426212"
}
],
"symlink_target": ""
} |
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'CBA'
copyright = u'2016-2017, Kai Diefenbach'
author = u'Kai Diefenbach'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'0.1'
# The full version, including alpha/beta/rc tags.
release = u'0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = u'CBA v0.1'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'CBAdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'CBA.tex', u'CBA Documentation',
u'Kai Diefenbach', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'cba', u'CBA Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'CBA', u'CBA Documentation',
author, 'CBA', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
| {
"content_hash": "65d259a03a469cdc96161de39b819728",
"timestamp": "",
"source": "github",
"line_count": 322,
"max_line_length": 80,
"avg_line_length": 28.267080745341616,
"alnum_prop": 0.6855636123928807,
"repo_name": "diefenbach/django-cba",
"id": "52b040a94ac639291fbedee56e7edc34d940facf",
"size": "9758",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/conf.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "3021200"
},
{
"name": "HTML",
"bytes": "24065"
},
{
"name": "JavaScript",
"bytes": "3163620"
},
{
"name": "Python",
"bytes": "41129"
}
],
"symlink_target": ""
} |
'use strict';
timing_test(function() {
var polyfillCircle = document.getElementById('polyfillCircle');
var nativeCircle = document.getElementById('nativeCircle');
at(0, 'cx', 300, polyfillCircle, nativeCircle);
at(1000, 'cy', 275, polyfillCircle, nativeCircle);
at(2000, 'r', 150, polyfillCircle, nativeCircle);
at(2000, 'fill-opacity', [0.75, undefined], polyfillCircle, nativeCircle);
at(3000, 'cx', 225, polyfillCircle, nativeCircle);
at(3750, 'cy', 206.25, polyfillCircle, nativeCircle);
at(3750, 'cx', 212.5, polyfillCircle, nativeCircle);
at(4000, 'cy', 200, polyfillCircle, nativeCircle);
at(5000, 'r', 100, polyfillCircle, nativeCircle);
}, 'animate circle');
| {
"content_hash": "c46fc1d85f690b25214a0a8dce8db2a6",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 76,
"avg_line_length": 40.76470588235294,
"alnum_prop": 0.7085137085137085,
"repo_name": "smil-in-javascript/smil-in-javascript",
"id": "736471cbc10ef7fdda084f6a79cfbd240f66368f",
"size": "693",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/testcases/circle-check.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1474"
},
{
"name": "JavaScript",
"bytes": "425587"
},
{
"name": "Python",
"bytes": "1754"
},
{
"name": "Shell",
"bytes": "594"
}
],
"symlink_target": ""
} |
drop table if exists `sys_user`;;
drop table if exists `sys_user_status_history`;;
drop trigger if exists `trigger_sys_user_off_online`;;
drop table if exists `sys_user_online`;;
drop table if exists `sys_user_last_online`;;
drop table if exists `sys_organization`;;
drop table if exists `sys_job`;;
drop table if exists `sys_user_organization_job`;;
drop table if exists `sys_resource`;;
drop table if exists `sys_permission`;;
drop table if exists `sys_role`;;
drop table if exists `sys_role_resource_permission`;;
drop table if exists `sys_group`;;
drop table if exists `sys_group_relation`;;
drop table if exists `sys_auth`;;
##user
create table `sys_user`(
`id` bigint not null auto_increment,
`username` varchar(100),
`email` varchar(100),
`mobile_phone_number` varchar(20),
`password` varchar(100),
`salt` varchar(10),
`create_date` timestamp default 0,
`status` varchar(50),
`deleted` bool,
`admin` bool,
constraint `pk_sys_user` primary key(`id`),
constraint `unique_sys_user_username` unique(`username`),
constraint `unique_sys_user_email` unique(`email`),
constraint `unique_sys_user_mobile_phone_number` unique(`mobile_phone_number`),
index `idx_sys_user_status` (`status`)
) charset=utf8 ENGINE=InnoDB;;
alter table `sys_user` auto_increment=1000;;
create table `sys_user_status_history`(
`id` bigint not null auto_increment,
`user_id` bigint,
`status` varchar(50),
`reason` varchar(200),
`op_user_id` bigint,
`op_date` timestamp default 0 ,
constraint `pk_sys_user_block_history` primary key(`id`),
index `idx_sys_user_block_history_user_id_block_date` (`user_id`,`op_date`),
index `idx_sys_user_block_history_op_user_id_op_date` (`op_user_id`, `op_date`)
) charset=utf8 ENGINE=InnoDB;;
create table `sys_user_online`(
`id` varchar(100) not null,
`user_id` bigint default 0,
`username` varchar(100),
`host` varchar(100),
`system_host` varchar(100),
`user_agent` varchar(200),
`status` varchar(50),
`start_timestsamp` timestamp default 0 ,
`last_access_time` timestamp default 0 ,
`timeout` bigint ,
`session` mediumtext,
constraint `pk_sys_user_online` primary key(`id`),
index `idx_sys_user_online_sys_user_id` (`user_id`),
index `idx_sys_user_online_username` (`username`),
index `idx_sys_user_online_host` (`host`),
index `idx_sys_user_online_system_host` (`system_host`),
index `idx_sys_user_online_start_timestsamp` (`start_timestsamp`),
index `idx_sys_user_online_last_access_time` (`last_access_time`),
index `idx_sys_user_online_user_agent` (`user_agent`)
) charset=utf8 ENGINE=InnoDB;;
create table `sys_user_last_online`(
`id` bigint not null auto_increment,
`user_id` bigint,
`username` varchar(100),
`uid` varchar(100),
`host` varchar(100),
`user_agent` varchar(200),
`system_host` varchar(100),
`last_login_timestamp` timestamp default 0 ,
`last_stop_timestamp` timestamp default 0 ,
`login_count` bigint ,
`total_online_time` bigint,
constraint `pk_sys_user_last_online` primary key(`id`),
constraint `unique_sys_user_last_online_sys_user_id` unique(`user_id`),
index `idx_sys_user_last_online_username` (`username`),
index `idx_sys_user_last_online_host` (`host`),
index `idx_sys_user_last_online_system_host` (`system_host`),
index `idx_sys_user_last_online_last_login_timestamp` (`last_login_timestamp`),
index `idx_sys_user_last_online_last_stop_timestamp` (`last_stop_timestamp`),
index `idx_sys_user_last_online_user_agent` (`user_agent`)
) charset=utf8 ENGINE=InnoDB;;
create trigger `trigger_sys_user_off_online`
after delete on `sys_user_online` for each row
begin
if OLD.`user_id` is not null then
if not exists(select `user_id` from `sys_user_last_online` where `user_id` = OLD.`user_id`) then
insert into `sys_user_last_online`
(`user_id`, `username`, `uid`, `host`, `user_agent`, `system_host`,
`last_login_timestamp`, `last_stop_timestamp`, `login_count`, `total_online_time`)
values
(OLD.`user_id`,OLD.`username`, OLD.`id`, OLD.`host`, OLD.`user_agent`, OLD.`system_host`,
OLD.`start_timestsamp`, OLD.`last_access_time`,
1, (OLD.`last_access_time` - OLD.`start_timestsamp`));
else
update `sys_user_last_online`
set `username` = OLD.`username`, `uid` = OLD.`id`, `host` = OLD.`host`, `user_agent` = OLD.`user_agent`,
`system_host` = OLD.`system_host`, `last_login_timestamp` = OLD.`start_timestsamp`,
`last_stop_timestamp` = OLD.`last_access_time`, `login_count` = `login_count` + 1,
`total_online_time` = `total_online_time` + (OLD.`last_access_time` - OLD.`start_timestsamp`)
where `user_id` = OLD.`user_id`;
end if ;
end if;
end;;
create table `sys_organization`(
`id` bigint not null auto_increment,
`name` varchar(100),
`type` varchar(20),
`parent_id` bigint,
`parent_ids` varchar(200) default '',
`icon` varchar(200),
`weight` int,
`is_show` bool,
constraint `pk_sys_organization` primary key(`id`),
index `idx_sys_organization_name` (`name`),
index `idx_sys_organization_type` (`type`),
index `idx_sys_organization_parent_id` (`parent_id`),
index `idx_sys_organization_parent_ids_weight` (`parent_ids`, `weight`)
) charset=utf8 ENGINE=InnoDB;;
alter table `sys_organization` auto_increment=1000;;
create table `sys_job`(
`id` bigint not null auto_increment,
`name` varchar(100),
`parent_id` bigint,
`parent_ids` varchar(200) default '',
`icon` varchar(200),
`weight` int,
`is_show` bool,
constraint `pk_sys_job` primary key(`id`),
index `idx_sys_job_nam` (`name`),
index `idx_sys_job_parent_id` (`parent_id`),
index `idx_sys_job_parent_ids_weight` (`parent_ids`, `weight`)
) charset=utf8 ENGINE=InnoDB;;
alter table `sys_job` auto_increment=1000;;
create table `sys_user_organization_job`(
`id` bigint not null auto_increment,
`user_id` bigint,
`organization_id` bigint,
`job_id` bigint,
constraint `pk_sys_user_organization_job` primary key(`id`),
constraint `unique_sys_user_organization_job` unique(`user_id`, `organization_id`, `job_id`)
) charset=utf8 ENGINE=InnoDB;;
create table `sys_resource`(
`id` bigint not null auto_increment,
`name` varchar(100),
`identity` varchar(100),
`url` varchar(200),
`parent_id` bigint,
`parent_ids` varchar(200) default '',
`icon` varchar(200),
`weight` int,
`is_show` bool,
constraint `pk_sys_resource` primary key(`id`),
index `idx_sys_resource_name` (`name`),
index `idx_sys_resource_identity` (`identity`),
index `idx_sys_resource_user` (`url`),
index `idx_sys_resource_parent_id` (`parent_id`),
index `idx_sys_resource_parent_ids_weight` (`parent_ids`, `weight`)
) charset=utf8 ENGINE=InnoDB;;
alter table `sys_resource` auto_increment=1000;;
create table `sys_permission`(
`id` bigint not null auto_increment,
`name` varchar(100),
`permission` varchar(100),
`description` varchar(200),
`is_show` bool,
constraint `pk_sys_permission` primary key(`id`),
index idx_sys_permission_name (`name`),
index idx_sys_permission_permission (`permission`),
index idx_sys_permission_show (`is_show`)
) charset=utf8 ENGINE=InnoDB;;
alter table `sys_permission` auto_increment=1000;;
create table `sys_role`(
`id` bigint not null auto_increment,
`name` varchar(100),
`role` varchar(100),
`description` varchar(200),
`is_show` bool,
constraint `pk_sys_role` primary key(`id`),
index `idx_sys_role_name` (`name`),
index `idx_sys_role_role` (`role`),
index `idx_sys_role_show` (`is_show`)
) charset=utf8 ENGINE=InnoDB;;
alter table `sys_role` auto_increment=1000;;
create table `sys_role_resource_permission`(
`id` bigint not null auto_increment,
`role_id` bigint,
`resource_id` bigint,
`permission_ids` varchar(500),
constraint `pk_sys_role_resource_permission` primary key(`id`),
constraint `unique_sys_role_resource_permission` unique(`role_id`, `resource_id`)
) charset=utf8 ENGINE=InnoDB;;
alter table `sys_role_resource_permission` auto_increment=1000;;
create table `sys_group`(
`id` bigint not null auto_increment,
`name` varchar(100),
`type` varchar(50),
`is_show` bool,
`default_group` bool,
constraint `pk_sys_group` primary key(`id`),
index `idx_sys_group_type` (`type`),
index `idx_sys_group_show` (`is_show`),
index `idx_sys_group_default_group` (`default_group`)
) charset=utf8 ENGINE=InnoDB;;
create table `sys_group_relation`(
`id` bigint not null auto_increment,
`group_id` bigint,
`organization_id` bigint,
`user_id` bigint,
`start_user_id` bigint,
`end_user_id` bigint,
constraint `pk_sys_group_relation` primary key(`id`),
index `idx_sys_group_relation_group` (`group_id`),
index `idx_sys_group_relation_organization` (`organization_id`),
index `idx_sys_group_relation_user` (`user_id`),
index `idx_sys_group_relation_start_user_id` (`start_user_id`),
index `idx_sys_group_relation_end_user_id` (`end_user_id`)
) charset=utf8 ENGINE=InnoDB;;
create table `sys_auth`(
`id` bigint not null auto_increment,
`organization_id` bigint,
`job_id` bigint,
`user_id` bigint,
`group_id` bigint,
`role_ids` varchar(500),
`type` varchar(50),
constraint `pk_sys_auth` primary key(`id`),
index `idx_sys_auth_organization` (`organization_id`),
index `idx_sys_auth_job` (`job_id`),
index `idx_sys_auth_user` (`user_id`),
index `idx_sys_auth_group` (`group_id`),
index `idx_sys_auth_type` (`type`)
) charset=utf8 ENGINE=InnoDB;;
alter table `sys_auth` auto_increment=1000;;
| {
"content_hash": "034ed334ada4189b77115296f25f99b3",
"timestamp": "",
"source": "github",
"line_count": 265,
"max_line_length": 114,
"avg_line_length": 38.77358490566038,
"alnum_prop": 0.6337712895377129,
"repo_name": "xxs/es-shop",
"id": "3e1d766e6dae698bccf56a2cf4ff803d80e65d55",
"size": "10332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/sql/schema/init-system-schema.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "3753"
},
{
"name": "ApacheConf",
"bytes": "768"
},
{
"name": "Batchfile",
"bytes": "2260"
},
{
"name": "CSS",
"bytes": "995523"
},
{
"name": "FreeMarker",
"bytes": "12470"
},
{
"name": "HTML",
"bytes": "3217360"
},
{
"name": "Java",
"bytes": "1953370"
},
{
"name": "JavaScript",
"bytes": "8151405"
},
{
"name": "PHP",
"bytes": "8060"
},
{
"name": "PLSQL",
"bytes": "38298"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
The MIT License
Copyright (c) 2014-2016 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.20.0-SNAPSHOT</version>
</parent>
<artifactId>resource-acquisition-is-initialization</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "07e761534469e8a59b6dbd22101d2e59",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 149,
"avg_line_length": 41.07692307692308,
"alnum_prop": 0.7176966292134831,
"repo_name": "StefanHeimberg/java-design-patterns",
"id": "c69db95005476b7f837b6345f9ef88741ac58f1e",
"size": "2138",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "resource-acquisition-is-initialization/pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5808"
},
{
"name": "Gherkin",
"bytes": "1078"
},
{
"name": "HTML",
"bytes": "38429"
},
{
"name": "Java",
"bytes": "2576417"
},
{
"name": "JavaScript",
"bytes": "1191"
},
{
"name": "Shell",
"bytes": "1718"
}
],
"symlink_target": ""
} |
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function( root, jQuery ) {
if ( jQuery === undefined ) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if ( typeof window !== 'undefined' ) {
jQuery = require('jquery');
}
else {
jQuery = require('jquery')(root);
}
}
factory(jQuery);
return jQuery;
};
} else {
// Browser globals
factory(root.jQuery || root.Zepto);
}
}(typeof self !== 'undefined' ? self : this, function (jQuery) {
/*
zepto.js
Monkey patch for Zepto to add some methods ImageMapster needs
*/
(function ($) {
'use strict';
var origStop = $.fn.stop;
if (!origStop) {
$.fn.stop = function () {
return this;
};
}
$.each(['Height', 'Width'], function (_, name) {
var funcName = 'outer' + name,
origFunc = $.fn[funcName];
if (!origFunc) {
$.fn[funcName] = function () {
return this[name.toLowerCase()]();
};
}
});
})(jQuery);
/*
jqueryextensions.js
Extend/intercept jquery behavior
*/
(function ($) {
'use strict';
function setupPassiveListeners() {
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function () {
supportsPassive = true;
return true;
}
});
window.addEventListener('testPassive.mapster', function () {}, opts);
window.removeEventListener('testPassive.mapster', function () {}, opts);
} catch (e) {
// intentionally ignored
}
if (supportsPassive) {
// In order to not interrupt scrolling on touch devices
// we commit to not calling preventDefault from within listeners
// There is a plan to handle this natively in jQuery 4.0 but for
// now we are on our own.
// TODO: Migrate to jQuery 4.0 approach if/when released
// https://www.chromestatus.com/feature/5745543795965952
// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
// https://github.com/jquery/jquery/issues/2871#issuecomment-175175180
// https://jsbin.com/bupesajoza/edit?html,js,output
var setupListener = function (ns, type, listener) {
if (ns.includes('noPreventDefault')) {
window.addEventListener(type, listener, { passive: true });
} else {
console.warn('non-passive events - listener not added');
return false;
}
};
// special events for noPreventDefault
$.event.special.touchstart = {
setup: function (_, ns, listener) {
return setupListener(ns, 'touchstart', listener);
}
};
$.event.special.touchend = {
setup: function (_, ns, listener) {
return setupListener(ns, 'touchend', listener);
}
};
}
}
function supportsSpecialEvents() {
return $.event && $.event.special;
}
// Zepto does not support special events
// TODO: Remove when Zepto support is removed
if (supportsSpecialEvents()) {
setupPassiveListeners();
}
})(jQuery);
/*
core.js
ImageMapster core
*/
(function ($) {
'use strict';
var mapster_version = '1.5.4';
// all public functions in $.mapster.impl are methods
$.fn.mapster = function (method) {
var m = $.mapster.impl;
if ($.mapster.utils.isFunction(m[method])) {
return m[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return m.bind.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.mapster');
}
};
$.mapster = {
version: mapster_version,
render_defaults: {
isSelectable: true,
isDeselectable: true,
fade: false,
fadeDuration: 150,
fill: true,
fillColor: '000000',
fillColorMask: 'FFFFFF',
fillOpacity: 0.7,
highlight: true,
stroke: false,
strokeColor: 'ff0000',
strokeOpacity: 1,
strokeWidth: 1,
includeKeys: '',
altImage: null,
altImageId: null, // used internally
altImages: {}
},
defaults: {
clickNavigate: false,
navigateMode: 'location', // location|open
wrapClass: null,
wrapCss: null,
onGetList: null,
sortList: false,
listenToList: false,
mapKey: '',
mapValue: '',
singleSelect: false,
listKey: 'value',
listSelectedAttribute: 'selected',
listSelectedClass: null,
onClick: null,
onMouseover: null,
onMouseout: null,
mouseoutDelay: 0,
onStateChange: null,
boundList: null,
onConfigured: null,
configTimeout: 30000,
noHrefIsMask: true,
scaleMap: true,
enableAutoResizeSupport: false, // TODO: Remove in next major release
autoResize: false,
autoResizeDelay: 0,
autoResizeDuration: 0,
onAutoResize: null,
safeLoad: false,
areas: []
},
shared_defaults: {
render_highlight: { fade: true },
render_select: { fade: false },
staticState: null,
selected: null
},
area_defaults: {
includeKeys: '',
isMask: false
},
canvas_style: {
position: 'absolute',
left: 0,
top: 0,
padding: 0,
border: 0
},
hasCanvas: null,
map_cache: [],
hooks: {},
addHook: function (name, callback) {
this.hooks[name] = (this.hooks[name] || []).push(callback);
},
callHooks: function (name, context) {
$.each(this.hooks[name] || [], function (_, e) {
e.apply(context);
});
},
utils: {
when: {
all: function (deferredArray) {
// TODO: Promise breaks ES5 support
// eslint-disable-next-line no-undef
return Promise.all(deferredArray);
},
defer: function () {
// Deferred is frequently referred to as an anti-pattern largely
// due to error handling, however to avoid reworking existing
// APIs and support backwards compat, creating a "deferred"
// polyfill via native promise
var Deferred = function () {
// TODO: Promise breaks ES5 support
// eslint-disable-next-line no-undef
this.promise = new Promise(
function (resolve, reject) {
this.resolve = resolve;
this.reject = reject;
}.bind(this)
);
this.then = this.promise.then.bind(this.promise);
this.catch = this.promise.catch.bind(this.promise);
};
return new Deferred();
}
},
defer: function () {
return this.when.defer();
},
// extends the constructor, returns a new object prototype. Does not refer to the
// original constructor so is protected if the original object is altered. This way you
// can "extend" an object by replacing it with its subclass.
subclass: function (BaseClass, constr) {
var Subclass = function () {
var me = this,
args = Array.prototype.slice.call(arguments, 0);
me.base = BaseClass.prototype;
me.base.init = function () {
BaseClass.prototype.constructor.apply(me, args);
};
constr.apply(me, args);
};
Subclass.prototype = new BaseClass();
Subclass.prototype.constructor = Subclass;
return Subclass;
},
asArray: function (obj) {
return obj.constructor === Array ? obj : this.split(obj);
},
// clean split: no padding or empty elements
split: function (text, cb) {
var i,
el,
arr = text.split(',');
for (i = 0; i < arr.length; i++) {
// backwards compat for $.trim which would return empty string on null
// which theoertically should not happen here
el = arr[i] ? arr[i].trim() : '';
if (el === '') {
arr.splice(i, 1);
} else {
arr[i] = cb ? cb(el) : el;
}
}
return arr;
},
// similar to $.extend but does not add properties (only updates), unless the
// first argument is an empty object, then all properties will be copied
updateProps: function (_target, _template) {
var onlyProps,
target = _target || {},
template = $.isEmptyObject(target) ? _template : _target;
//if (template) {
onlyProps = [];
$.each(template, function (prop) {
onlyProps.push(prop);
});
//}
$.each(Array.prototype.slice.call(arguments, 1), function (_, src) {
$.each(src || {}, function (prop) {
if (!onlyProps || $.inArray(prop, onlyProps) >= 0) {
var p = src[prop];
if ($.isPlainObject(p)) {
// not recursive - only copies 1 level of subobjects, and always merges
target[prop] = $.extend(target[prop] || {}, p);
} else if (p && p.constructor === Array) {
target[prop] = p.slice(0);
} else if (typeof p !== 'undefined') {
target[prop] = src[prop];
}
}
});
});
return target;
},
isElement: function (o) {
return typeof HTMLElement === 'object'
? o instanceof HTMLElement
: o &&
typeof o === 'object' &&
o.nodeType === 1 &&
typeof o.nodeName === 'string';
},
/**
* Basic indexOf implementation for IE7-8. Though we use $.inArray, some jQuery versions will try to
* use a prototpye on the calling object, defeating the purpose of using $.inArray in the first place.
*
* This will be replaced with the array prototype if it's available.
*
* @param {Array} arr The array to search
* @param {Object} target The item to search for
* @return {Number} The index of the item, or -1 if not found
*/
indexOf: function (arr, target) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(arr, target);
} else {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
},
// finds element of array or object with a property "prop" having value "val"
// if prop is not defined, then just looks for property with value "val"
indexOfProp: function (obj, prop, val) {
var result = obj.constructor === Array ? -1 : null;
$.each(obj, function (i, e) {
if (e && (prop ? e[prop] : e) === val) {
result = i;
return false;
}
});
return result;
},
// returns "obj" if true or false, or "def" if not true/false
boolOrDefault: function (obj, def) {
return this.isBool(obj) ? obj : def || false;
},
isBool: function (obj) {
return typeof obj === 'boolean';
},
isUndef: function (obj) {
return typeof obj === 'undefined';
},
isFunction: function (obj) {
return typeof obj === 'function';
},
// evaluates "obj", if function, calls it with args
// (todo - update this to handle variable lenght/more than one arg)
ifFunction: function (obj, that, args) {
if (this.isFunction(obj)) {
obj.call(that, args);
}
},
size: function (image, raw) {
var u = $.mapster.utils;
return {
width: raw
? image.width || image.naturalWidth
: u.imgWidth(image, true),
height: raw
? image.height || image.naturalHeight
: u.imgHeight(image, true),
complete: function () {
return !!this.height && !!this.width;
}
};
},
/**
* Set the opacity of the element. This is an IE<8 specific function for handling VML.
* When using VML we must override the "setOpacity" utility function (monkey patch ourselves).
* jQuery does not deal with opacity correctly for VML elements. This deals with that.
*
* @param {Element} el The DOM element
* @param {double} opacity A value between 0 and 1 inclusive.
*/
setOpacity: function (el, opacity) {
if ($.mapster.hasCanvas()) {
el.style.opacity = opacity;
} else {
$(el).each(function (_, e) {
if (typeof e.opacity !== 'undefined') {
e.opacity = opacity;
} else {
$(e).css('opacity', opacity);
}
});
}
},
// fade "el" from opacity "op" to "endOp" over a period of time "duration"
fader: (function () {
var elements = {},
lastKey = 0,
fade_func = function (el, op, endOp, duration) {
var index,
cbIntervals = duration / 15,
obj,
u = $.mapster.utils;
if (typeof el === 'number') {
obj = elements[el];
if (!obj) {
return;
}
} else {
index = u.indexOfProp(elements, null, el);
if (index) {
delete elements[index];
}
elements[++lastKey] = obj = el;
el = lastKey;
}
endOp = endOp || 1;
op =
op + endOp / cbIntervals > endOp - 0.01
? endOp
: op + endOp / cbIntervals;
u.setOpacity(obj, op);
if (op < endOp) {
setTimeout(function () {
fade_func(el, op, endOp, duration);
}, 15);
}
};
return fade_func;
})(),
getShape: function (areaEl) {
// per HTML spec, invalid value and missing value default is 'rect'
// Handling as follows:
// - Missing/Empty value will be treated as 'rect' per spec
// - Avoid handling invalid values do to perf impact
// Note - IM currently does not support shape of 'default' so while its technically
// a valid attribute value it should not be used.
// https://html.spec.whatwg.org/multipage/image-maps.html#the-area-element
return (areaEl.shape || 'rect').toLowerCase();
},
hasAttribute: function (el, attrName) {
var attr = $(el).attr(attrName);
// For some browsers, `attr` is undefined; for others, `attr` is false.
return typeof attr !== 'undefined' && attr !== false;
}
},
getBoundList: function (opts, key_list) {
if (!opts.boundList) {
return null;
}
var index,
key,
result = $(),
list = $.mapster.utils.split(key_list);
opts.boundList.each(function (_, e) {
for (index = 0; index < list.length; index++) {
key = list[index];
if ($(e).is('[' + opts.listKey + '="' + key + '"]')) {
result = result.add(e);
}
}
});
return result;
},
getMapDataIndex: function (obj) {
var img, id;
switch (obj.tagName && obj.tagName.toLowerCase()) {
case 'area':
id = $(obj).parent().attr('name');
img = $("img[usemap='#" + id + "']")[0];
break;
case 'img':
img = obj;
break;
}
return img ? this.utils.indexOfProp(this.map_cache, 'image', img) : -1;
},
getMapData: function (obj) {
var index = this.getMapDataIndex(obj.length ? obj[0] : obj);
if (index >= 0) {
return index >= 0 ? this.map_cache[index] : null;
}
},
/**
* Queue a command to be run after the active async operation has finished
* @param {MapData} map_data The target MapData object
* @param {jQuery} that jQuery object on which the command was invoked
* @param {string} command the ImageMapster method name
* @param {object[]} args arguments passed to the method
* @return {bool} true if the command was queued, false if not (e.g. there was no need to)
*/
queueCommand: function (map_data, that, command, args) {
if (!map_data) {
return false;
}
if (!map_data.complete || map_data.currentAction) {
map_data.commands.push({
that: that,
command: command,
args: args
});
return true;
}
return false;
},
unload: function () {
this.impl.unload();
this.utils = null;
this.impl = null;
$.fn.mapster = null;
$.mapster = null;
return $('*').off('.mapster');
}
};
// Config for object prototypes
// first: use only first object (for things that should not apply to lists)
/// calls back one of two fuinctions, depending on whether an area was obtained.
// opts: {
// name: 'method name',
// key: 'key,
// args: 'args'
//
//}
// name: name of method (required)
// args: arguments to re-call with
// Iterates through all the objects passed, and determines whether it's an area or an image, and calls the appropriate
// callback for each. If anything is returned from that callback, the process is stopped and that data return. Otherwise,
// the object itself is returned.
var m = $.mapster,
u = m.utils,
ap = Array.prototype;
// jQuery's width() and height() are broken on IE9 in some situations. This tries everything.
$.each(['width', 'height'], function (_, e) {
var capProp = e.substr(0, 1).toUpperCase() + e.substr(1);
// when jqwidth parm is passed, it also checks the jQuery width()/height() property
// the issue is that jQUery width() can report a valid size before the image is loaded in some browsers
// without it, we can read zero even when image is loaded in other browsers if its not visible
// we must still check because stuff like adblock can temporarily block it
// what a goddamn headache
u['img' + capProp] = function (img, jqwidth) {
return (
(jqwidth ? $(img)[e]() : 0) ||
img[e] ||
img['natural' + capProp] ||
img['client' + capProp] ||
img['offset' + capProp]
);
};
});
/**
* The Method object encapsulates the process of testing an ImageMapster method to see if it's being
* invoked on an image, or an area; then queues the command if the MapData is in an active state.
*
* @param {[jQuery]} that The target of the invocation
* @param {[function]} func_map The callback if the target is an imagemap
* @param {[function]} func_area The callback if the target is an area
* @param {[object]} opt Options: { key: a map key if passed explicitly
* name: the command name, if it can be queued,
* args: arguments to the method
* }
*/
m.Method = function (that, func_map, func_area, opts) {
var me = this;
me.name = opts.name;
me.output = that;
me.input = that;
me.first = opts.first || false;
me.args = opts.args ? ap.slice.call(opts.args, 0) : [];
me.key = opts.key;
me.func_map = func_map;
me.func_area = func_area;
//$.extend(me, opts);
me.name = opts.name;
me.allowAsync = opts.allowAsync || false;
};
m.Method.prototype = {
constructor: m.Method,
go: function () {
var i,
data,
ar,
len,
result,
src = this.input,
area_list = [],
me = this;
len = src.length;
for (i = 0; i < len; i++) {
data = $.mapster.getMapData(src[i]);
if (data) {
if (
!me.allowAsync &&
m.queueCommand(data, me.input, me.name, me.args)
) {
if (this.first) {
result = '';
}
continue;
}
ar = data.getData(src[i].nodeName === 'AREA' ? src[i] : this.key);
if (ar) {
if ($.inArray(ar, area_list) < 0) {
area_list.push(ar);
}
} else {
result = this.func_map.apply(data, me.args);
}
if (this.first || typeof result !== 'undefined') {
break;
}
}
}
// if there were areas, call the area function for each unique group
$(area_list).each(function (_, e) {
result = me.func_area.apply(e, me.args);
});
if (typeof result !== 'undefined') {
return result;
} else {
return this.output;
}
}
};
$.mapster.impl = (function () {
var me = {},
addMap = function (map_data) {
return m.map_cache.push(map_data) - 1;
},
removeMap = function (map_data) {
m.map_cache.splice(map_data.index, 1);
for (var i = m.map_cache.length - 1; i >= map_data.index; i--) {
m.map_cache[i].index--;
}
};
/**
* Test whether the browser supports VML. Credit: google.
* http://stackoverflow.com/questions/654112/how-do-you-detect-support-for-vml-or-svg-in-a-browser
*
* @return {bool} true if vml is supported, false if not
*/
function hasVml() {
var a = $('<div />').appendTo('body');
a.html('<v:shape id="vml_flag1" adj="1" />');
var b = a[0].firstChild;
b.style.behavior = 'url(#default#VML)';
var has = b ? typeof b.adj === 'object' : true;
a.remove();
return has;
}
/**
* Return a reference to the IE namespaces object, if available, or an empty object otherwise
* @return {obkect} The document.namespaces object.
*/
function namespaces() {
return typeof document.namespaces === 'object'
? document.namespaces
: null;
}
/**
* Test for the presence of HTML5 Canvas support. This also checks to see if excanvas.js has been
* loaded and is faking it; if so, we assume that canvas is not supported.
*
* @return {bool} true if HTML5 canvas support, false if not
*/
function hasCanvas() {
var d = namespaces();
// when g_vml_ is present, then we can be sure excanvas is active, meaning there's not a real canvas.
return d && d.g_vml_
? false
: $('<canvas />')[0].getContext
? true
: false;
}
/**
* Merge new area data into existing area options on a MapData object. Used for rebinding.
*
* @param {[MapData]} map_data The MapData object
* @param {[object[]]} areas areas array to merge
*/
function merge_areas(map_data, areas) {
var ar,
index,
map_areas = map_data.options.areas;
if (areas) {
$.each(areas, function (_, e) {
// Issue #68 - ignore invalid data in areas array
if (!e || !e.key) {
return;
}
index = u.indexOfProp(map_areas, 'key', e.key);
if (index >= 0) {
$.extend(map_areas[index], e);
} else {
map_areas.push(e);
}
ar = map_data.getDataForKey(e.key);
if (ar) {
$.extend(ar.options, e);
}
});
}
}
function merge_options(map_data, options) {
var temp_opts = u.updateProps({}, options);
delete temp_opts.areas;
u.updateProps(map_data.options, temp_opts);
merge_areas(map_data, options.areas);
// refresh the area_option template
u.updateProps(map_data.area_options, map_data.options);
}
// Most methods use the "Method" object which handles figuring out whether it's an image or area called and
// parsing key parameters. The constructor wants:
// this, the jQuery object
// a function that is called when an image was passed (with a this context of the MapData)
// a function that is called when an area was passed (with a this context of the AreaData)
// options: first = true means only the first member of a jQuery object is handled
// key = the key parameters passed
// defaultReturn: a value to return other than the jQuery object (if its not chainable)
// args: the arguments
// Returns a comma-separated list of user-selected areas. "staticState" areas are not considered selected for the purposes of this method.
me.get = function (key) {
var md = m.getMapData(this);
if (!(md && md.complete)) {
throw "Can't access data until binding complete.";
}
return new m.Method(
this,
function () {
// map_data return
return this.getSelected();
},
function () {
return this.isSelected();
},
{
name: 'get',
args: arguments,
key: key,
first: true,
allowAsync: true,
defaultReturn: ''
}
).go();
};
me.data = function (key) {
return new m.Method(
this,
null,
function () {
return this;
},
{ name: 'data', args: arguments, key: key }
).go();
};
// Set or return highlight state.
// $(img).mapster('highlight') -- return highlighted area key, or null if none
// $(area).mapster('highlight') -- highlight an area
// $(img).mapster('highlight','area_key') -- highlight an area
// $(img).mapster('highlight',false) -- remove highlight
me.highlight = function (key) {
return new m.Method(
this,
function () {
if (key === false) {
this.ensureNoHighlight();
} else {
var id = this.highlightId;
return id >= 0 ? this.data[id].key : null;
}
},
function () {
this.highlight();
},
{ name: 'highlight', args: arguments, key: key, first: true }
).go();
};
// Return the primary keys for an area or group key.
// $(area).mapster('key')
// includes all keys (not just primary keys)
// $(area).mapster('key',true)
// $(img).mapster('key','group-key')
// $(img).mapster('key','group-key', true)
me.keys = function (key, all) {
var keyList = [],
md = m.getMapData(this);
if (!(md && md.complete)) {
throw "Can't access data until binding complete.";
}
function addUniqueKeys(ad) {
var areas,
keys = [];
if (!all) {
keys.push(ad.key);
} else {
areas = ad.areas();
$.each(areas, function (_, e) {
keys = keys.concat(e.keys);
});
}
$.each(keys, function (_, e) {
if ($.inArray(e, keyList) < 0) {
keyList.push(e);
}
});
}
if (!(md && md.complete)) {
return '';
}
if (typeof key === 'string') {
if (all) {
addUniqueKeys(md.getDataForKey(key));
} else {
keyList = [md.getKeysForGroup(key)];
}
} else {
all = key;
this.each(function (_, e) {
if (e.nodeName === 'AREA') {
addUniqueKeys(md.getDataForArea(e));
}
});
}
return keyList.join(',');
};
me.select = function () {
me.set.call(this, true);
};
me.deselect = function () {
me.set.call(this, false);
};
/**
* Select or unselect areas. Areas can be identified by a single string key, a comma-separated list of keys,
* or an array of strings.
*
*
* @param {boolean} selected Determines whether areas are selected or deselected
* @param {string|string[]} key A string, comma-separated string, or array of strings indicating
* the areas to select or deselect
* @param {object} options Rendering options to apply when selecting an area
*/
me.set = function (selected, key, options) {
var lastMap,
map_data,
opts = options,
key_list,
area_list; // array of unique areas passed
function setSelection(ar) {
var newState = selected;
if (ar) {
switch (selected) {
case true:
ar.select(opts);
break;
case false:
ar.deselect(true);
break;
default:
newState = ar.toggle(opts);
break;
}
return newState;
}
}
function addArea(ar) {
if (ar && $.inArray(ar, area_list) < 0) {
area_list.push(ar);
key_list += (key_list === '' ? '' : ',') + ar.key;
}
}
// Clean up after a group that applied to the same map
function finishSetForMap(map_data) {
$.each(area_list, function (_, el) {
setSelection(el);
});
if (!selected) {
map_data.removeSelectionFinish();
}
}
this.filter('img,area').each(function (_, e) {
var keys;
map_data = m.getMapData(e);
if (map_data !== lastMap) {
if (lastMap) {
finishSetForMap(lastMap);
}
area_list = [];
key_list = '';
}
if (map_data) {
keys = '';
if (e.nodeName.toUpperCase() === 'IMG') {
if (!m.queueCommand(map_data, $(e), 'set', [selected, key, opts])) {
if (key instanceof Array) {
if (key.length) {
keys = key.join(',');
}
} else {
keys = key;
}
if (keys) {
$.each(u.split(keys), function (_, key) {
addArea(map_data.getDataForKey(key.toString()));
lastMap = map_data;
});
}
}
} else {
opts = key;
if (!m.queueCommand(map_data, $(e), 'set', [selected, opts])) {
addArea(map_data.getDataForArea(e));
lastMap = map_data;
}
}
}
});
if (map_data) {
finishSetForMap(map_data);
}
return this;
};
me.unbind = function (preserveState) {
return new m.Method(
this,
function () {
this.clearEvents();
this.clearMapData(preserveState);
removeMap(this);
},
null,
{ name: 'unbind', args: arguments }
).go();
};
// refresh options and update selection information.
me.rebind = function (options) {
return new m.Method(
this,
function () {
var me = this;
me.complete = false;
me.configureOptions(options);
me.bindImages().then(function () {
me.buildDataset(true);
me.complete = true;
me.onConfigured();
});
//this.redrawSelections();
},
null,
{
name: 'rebind',
args: arguments
}
).go();
};
// get options. nothing or false to get, or "true" to get effective options (versus passed options)
me.get_options = function (key, effective) {
var eff = u.isBool(key) ? key : effective; // allow 2nd parm as "effective" when no key
return new m.Method(
this,
function () {
var opts = $.extend({}, this.options);
if (eff) {
opts.render_select = u.updateProps(
{},
m.render_defaults,
opts,
opts.render_select
);
opts.render_highlight = u.updateProps(
{},
m.render_defaults,
opts,
opts.render_highlight
);
}
return opts;
},
function () {
return eff ? this.effectiveOptions() : this.options;
},
{
name: 'get_options',
args: arguments,
first: true,
allowAsync: true,
key: key
}
).go();
};
// set options - pass an object with options to set,
me.set_options = function (options) {
return new m.Method(
this,
function () {
merge_options(this, options);
},
null,
{
name: 'set_options',
args: arguments
}
).go();
};
me.unload = function () {
var i;
for (i = m.map_cache.length - 1; i >= 0; i--) {
if (m.map_cache[i]) {
me.unbind.call($(m.map_cache[i].image));
}
}
me.graphics = null;
};
me.snapshot = function () {
return new m.Method(
this,
function () {
$.each(this.data, function (_, e) {
e.selected = false;
});
this.base_canvas = this.graphics.createVisibleCanvas(this);
$(this.image).before(this.base_canvas);
},
null,
{ name: 'snapshot' }
).go();
};
// do not queue this function
me.state = function () {
var md,
result = null;
$(this).each(function (_, e) {
if (e.nodeName === 'IMG') {
md = m.getMapData(e);
if (md) {
result = md.state();
}
return false;
}
});
return result;
};
me.bind = function (options) {
return this.each(function (_, e) {
var img, map, usemap, md;
// save ref to this image even if we can't access it yet. commands will be queued
img = $(e);
md = m.getMapData(e);
// if already bound completely, do a total rebind
if (md) {
me.unbind.apply(img);
if (!md.complete) {
// will be queued
return true;
}
md = null;
}
// ensure it's a valid image
// jQuery bug with Opera, results in full-url#usemap being returned from jQuery's attr.
// So use raw getAttribute instead.
usemap = this.getAttribute('usemap');
map = usemap && $('map[name="' + usemap.substr(1) + '"]');
if (!(img.is('img') && usemap && map.length > 0)) {
return true;
}
// sorry - your image must have border:0, things are too unpredictable otherwise.
img.css('border', 0);
if (!md) {
md = new m.MapData(this, options);
md.index = addMap(md);
md.map = map;
md.bindImages().then(function () {
md.initialize();
});
}
});
};
me.init = function (useCanvas) {
var style, shapes;
// for testing/debugging, use of canvas can be forced by initializing
// manually with "true" or "false". But generally we test for it.
m.hasCanvas = function () {
if (!u.isBool(m.hasCanvas.value)) {
m.hasCanvas.value = u.isBool(useCanvas) ? useCanvas : hasCanvas();
}
return m.hasCanvas.value;
};
m.hasVml = function () {
if (!u.isBool(m.hasVml.value)) {
// initialize VML the first time we detect its presence.
var d = namespaces();
if (d && !d.v) {
d.add('v', 'urn:schemas-microsoft-com:vml');
style = document.createStyleSheet();
shapes = [
'shape',
'rect',
'oval',
'circ',
'fill',
'stroke',
'imagedata',
'group',
'textbox'
];
$.each(shapes, function (_, el) {
style.addRule(
'v\\:' + el,
'behavior: url(#default#VML); antialias:true'
);
});
}
m.hasVml.value = hasVml();
}
return m.hasVml.value;
};
$.extend(m.defaults, m.render_defaults, m.shared_defaults);
$.extend(m.area_defaults, m.render_defaults, m.shared_defaults);
};
me.test = function (obj) {
return eval(obj);
};
return me;
})();
$.mapster.impl.init();
})(jQuery);
/*
graphics.js
Graphics object handles all rendering.
*/
(function ($) {
'use strict';
var p,
m = $.mapster,
u = m.utils,
canvasMethods,
vmlMethods;
/**
* Implemenation to add each area in an AreaData object to the canvas
* @param {Graphics} graphics The target graphics object
* @param {AreaData} areaData The AreaData object (a collection of area elements and metadata)
* @param {object} options Rendering options to apply when rendering this group of areas
*/
function addShapeGroupImpl(graphics, areaData, options) {
var me = graphics,
md = me.map_data,
isMask = options.isMask;
// first get area options. Then override fade for selecting, and finally merge in the
// "select" effect options.
$.each(areaData.areas(), function (_, e) {
options.isMask = isMask || (e.nohref && md.options.noHrefIsMask);
me.addShape(e, options);
});
// it's faster just to manipulate the passed options isMask property and restore it, than to
// copy the object each time
options.isMask = isMask;
}
/**
* Convert a hex value to decimal
* @param {string} hex A hexadecimal toString
* @return {int} Integer represenation of the hex string
*/
function hex_to_decimal(hex) {
return Math.max(0, Math.min(parseInt(hex, 16), 255));
}
function css3color(color, opacity) {
return (
'rgba(' +
hex_to_decimal(color.substr(0, 2)) +
',' +
hex_to_decimal(color.substr(2, 2)) +
',' +
hex_to_decimal(color.substr(4, 2)) +
',' +
opacity +
')'
);
}
/**
* An object associated with a particular map_data instance to manage renderin.
* @param {MapData} map_data The MapData object bound to this instance
*/
m.Graphics = function (map_data) {
//$(window).unload($.mapster.unload);
// create graphics functions for canvas and vml browsers. usage:
// 1) init with map_data, 2) call begin with canvas to be used (these are separate b/c may not require canvas to be specified
// 3) call add_shape_to for each shape or mask, 4) call render() to finish
var me = this;
me.active = false;
me.canvas = null;
me.width = 0;
me.height = 0;
me.shapes = [];
me.masks = [];
me.map_data = map_data;
};
p = m.Graphics.prototype = {
constructor: m.Graphics,
/**
* Initiate a graphics request for a canvas
* @param {Element} canvas The canvas element that is the target of this operation
* @param {string} [elementName] The name to assign to the element (VML only)
*/
begin: function (canvas, elementName) {
var c = $(canvas);
this.elementName = elementName;
this.canvas = canvas;
this.width = c.width();
this.height = c.height();
this.shapes = [];
this.masks = [];
this.active = true;
},
/**
* Add an area to be rendered to this canvas.
* @param {MapArea} mapArea The MapArea object to render
* @param {object} options An object containing any rendering options that should override the
* defaults for the area
*/
addShape: function (mapArea, options) {
var addto = options.isMask ? this.masks : this.shapes;
addto.push({ mapArea: mapArea, options: options });
},
/**
* Create a canvas that is sized and styled for the MapData object
* @param {MapData} mapData The MapData object that will receive this new canvas
* @return {Element} A canvas element
*/
createVisibleCanvas: function (mapData) {
return $(this.createCanvasFor(mapData))
.addClass('mapster_el')
.css(m.canvas_style)[0];
},
/**
* Add a group of shapes from an AreaData object to the canvas
*
* @param {AreaData} areaData An AreaData object (a set of area elements)
* @param {string} mode The rendering mode, "select" or "highlight". This determines the target
* canvas and which default options to use.
* @param {striong} options Rendering options
*/
addShapeGroup: function (areaData, mode, options) {
// render includeKeys first - because they could be masks
var me = this,
list,
name,
canvas,
map_data = this.map_data,
opts = areaData.effectiveRenderOptions(mode);
if (options) {
$.extend(opts, options);
}
if (mode === 'select') {
name = 'static_' + areaData.areaId.toString();
canvas = map_data.base_canvas;
} else {
canvas = map_data.overlay_canvas;
}
me.begin(canvas, name);
if (opts.includeKeys) {
list = u.split(opts.includeKeys);
$.each(list, function (_, e) {
var areaData = map_data.getDataForKey(e.toString());
addShapeGroupImpl(
me,
areaData,
areaData.effectiveRenderOptions(mode)
);
});
}
addShapeGroupImpl(me, areaData, opts);
me.render();
if (opts.fade) {
// fading requires special handling for IE. We must access the fill elements directly. The fader also has to deal with
// the "opacity" attribute (not css)
u.fader(
m.hasCanvas()
? canvas
: $(canvas).find('._fill').not('.mapster_mask'),
0,
m.hasCanvas() ? 1 : opts.fillOpacity,
opts.fadeDuration
);
}
}
// These prototype methods are implementation dependent
};
function noop() {}
// configure remaining prototype methods for ie or canvas-supporting browser
canvasMethods = {
renderShape: function (context, mapArea, offset) {
var i,
c = mapArea.coords(null, offset);
switch (mapArea.shape) {
case 'rect':
case 'rectangle':
context.rect(c[0], c[1], c[2] - c[0], c[3] - c[1]);
break;
case 'poly':
case 'polygon':
context.moveTo(c[0], c[1]);
for (i = 2; i < mapArea.length; i += 2) {
context.lineTo(c[i], c[i + 1]);
}
context.lineTo(c[0], c[1]);
break;
case 'circ':
case 'circle':
context.arc(c[0], c[1], c[2], 0, Math.PI * 2, false);
break;
}
},
addAltImage: function (context, image, mapArea, options) {
context.beginPath();
this.renderShape(context, mapArea);
context.closePath();
context.clip();
context.globalAlpha = options.altImageOpacity || options.fillOpacity;
context.drawImage(
image,
0,
0,
mapArea.owner.scaleInfo.width,
mapArea.owner.scaleInfo.height
);
},
render: function () {
// firefox 6.0 context.save() seems to be broken. to work around, we have to draw the contents on one temp canvas,
// the mask on another, and merge everything. ugh. fixed in 1.2.2. unfortunately this is a lot more code for masks,
// but no other way around it that i can see.
var maskCanvas,
maskContext,
me = this,
md = me.map_data,
hasMasks = me.masks.length,
shapeCanvas = me.createCanvasFor(md),
shapeContext = shapeCanvas.getContext('2d'),
context = me.canvas.getContext('2d');
if (hasMasks) {
maskCanvas = me.createCanvasFor(md);
maskContext = maskCanvas.getContext('2d');
maskContext.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
$.each(me.masks, function (_, e) {
maskContext.save();
maskContext.beginPath();
me.renderShape(maskContext, e.mapArea);
maskContext.closePath();
maskContext.clip();
maskContext.lineWidth = 0;
maskContext.fillStyle = '#000';
maskContext.fill();
maskContext.restore();
});
}
$.each(me.shapes, function (_, s) {
shapeContext.save();
if (s.options.fill) {
if (s.options.altImageId) {
me.addAltImage(
shapeContext,
md.images[s.options.altImageId],
s.mapArea,
s.options
);
} else {
shapeContext.beginPath();
me.renderShape(shapeContext, s.mapArea);
shapeContext.closePath();
//shapeContext.clip();
shapeContext.fillStyle = css3color(
s.options.fillColor,
s.options.fillOpacity
);
shapeContext.fill();
}
}
shapeContext.restore();
});
// render strokes at end since masks get stroked too
$.each(me.shapes.concat(me.masks), function (_, s) {
var offset = s.options.strokeWidth === 1 ? 0.5 : 0;
// offset applies only when stroke width is 1 and stroke would render between pixels.
if (s.options.stroke) {
shapeContext.save();
shapeContext.strokeStyle = css3color(
s.options.strokeColor,
s.options.strokeOpacity
);
shapeContext.lineWidth = s.options.strokeWidth;
shapeContext.beginPath();
me.renderShape(shapeContext, s.mapArea, offset);
shapeContext.closePath();
shapeContext.stroke();
shapeContext.restore();
}
});
if (hasMasks) {
// render the new shapes against the mask
maskContext.globalCompositeOperation = 'source-out';
maskContext.drawImage(shapeCanvas, 0, 0);
// flatten into the main canvas
context.drawImage(maskCanvas, 0, 0);
} else {
context.drawImage(shapeCanvas, 0, 0);
}
me.active = false;
return me.canvas;
},
// create a canvas mimicing dimensions of an existing element
createCanvasFor: function (md) {
return $(
'<canvas width="' +
md.scaleInfo.width +
'" height="' +
md.scaleInfo.height +
'"></canvas>'
)[0];
},
clearHighlight: function () {
var c = this.map_data.overlay_canvas;
c.getContext('2d').clearRect(0, 0, c.width, c.height);
},
// Draw all items from selected_list to a new canvas, then swap with the old one. This is used to delete items when using canvases.
refreshSelections: function () {
var canvas_temp,
map_data = this.map_data;
// draw new base canvas, then swap with the old one to avoid flickering
canvas_temp = map_data.base_canvas;
map_data.base_canvas = this.createVisibleCanvas(map_data);
$(map_data.base_canvas).hide();
$(canvas_temp).before(map_data.base_canvas);
map_data.redrawSelections();
$(map_data.base_canvas).show();
$(canvas_temp).remove();
}
};
vmlMethods = {
renderShape: function (mapArea, options, cssclass) {
var me = this,
fill,
stroke,
e,
t_fill,
el_name,
el_class,
template,
c = mapArea.coords();
el_name = me.elementName ? 'name="' + me.elementName + '" ' : '';
el_class = cssclass ? 'class="' + cssclass + '" ' : '';
t_fill =
'<v:fill color="#' +
options.fillColor +
'" class="_fill" opacity="' +
(options.fill ? options.fillOpacity : 0) +
'" /><v:stroke class="_fill" opacity="' +
options.strokeOpacity +
'"/>';
stroke = options.stroke
? ' strokeweight=' +
options.strokeWidth +
' stroked="t" strokecolor="#' +
options.strokeColor +
'"'
: ' stroked="f"';
fill = options.fill ? ' filled="t"' : ' filled="f"';
switch (mapArea.shape) {
case 'rect':
case 'rectangle':
template =
'<v:rect ' +
el_class +
el_name +
fill +
stroke +
' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:' +
c[0] +
'px;top:' +
c[1] +
'px;width:' +
(c[2] - c[0]) +
'px;height:' +
(c[3] - c[1]) +
'px;">' +
t_fill +
'</v:rect>';
break;
case 'poly':
case 'polygon':
template =
'<v:shape ' +
el_class +
el_name +
fill +
stroke +
' coordorigin="0,0" coordsize="' +
me.width +
',' +
me.height +
'" path="m ' +
c[0] +
',' +
c[1] +
' l ' +
c.slice(2).join(',') +
' x e" style="zoom:1;margin:0;padding:0;display:block;position:absolute;top:0px;left:0px;width:' +
me.width +
'px;height:' +
me.height +
'px;">' +
t_fill +
'</v:shape>';
break;
case 'circ':
case 'circle':
template =
'<v:oval ' +
el_class +
el_name +
fill +
stroke +
' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:' +
(c[0] - c[2]) +
'px;top:' +
(c[1] - c[2]) +
'px;width:' +
c[2] * 2 +
'px;height:' +
c[2] * 2 +
'px;">' +
t_fill +
'</v:oval>';
break;
}
e = $(template);
$(me.canvas).append(e);
return e;
},
render: function () {
var opts,
me = this;
$.each(this.shapes, function (_, e) {
me.renderShape(e.mapArea, e.options);
});
if (this.masks.length) {
$.each(this.masks, function (_, e) {
opts = u.updateProps({}, e.options, {
fillOpacity: 1,
fillColor: e.options.fillColorMask
});
me.renderShape(e.mapArea, opts, 'mapster_mask');
});
}
this.active = false;
return this.canvas;
},
createCanvasFor: function (md) {
var w = md.scaleInfo.width,
h = md.scaleInfo.height;
return $(
'<var width="' +
w +
'" height="' +
h +
'" style="zoom:1;overflow:hidden;display:block;width:' +
w +
'px;height:' +
h +
'px;"></var>'
)[0];
},
clearHighlight: function () {
$(this.map_data.overlay_canvas).children().remove();
},
// remove single or all selections
removeSelections: function (area_id) {
if (area_id >= 0) {
$(this.map_data.base_canvas)
.find('[name="static_' + area_id.toString() + '"]')
.remove();
} else {
$(this.map_data.base_canvas).children().remove();
}
}
};
// for all methods with two implemenatations, add a function that will automatically replace itself with the correct
// method on first invocation
$.each(
[
'renderShape',
'addAltImage',
'render',
'createCanvasFor',
'clearHighlight',
'removeSelections',
'refreshSelections'
],
function (_, e) {
p[e] = (function (method) {
return function () {
p[method] =
(m.hasCanvas() ? canvasMethods[method] : vmlMethods[method]) ||
noop;
return p[method].apply(this, arguments);
};
})(e);
}
);
})(jQuery);
/*
mapimage.js
The MapImage object, repesents an instance of a single bound imagemap
*/
(function ($) {
'use strict';
var m = $.mapster,
u = m.utils,
ap = [];
/**
* An object encapsulating all the images used by a MapData.
*/
m.MapImages = function (owner) {
this.owner = owner;
this.clear();
};
m.MapImages.prototype = {
constructor: m.MapImages,
/* interface to make this array-like */
slice: function () {
return ap.slice.apply(this, arguments);
},
splice: function () {
ap.slice.apply(this.status, arguments);
var result = ap.slice.apply(this, arguments);
return result;
},
/**
* a boolean value indicates whether all images are done loading
* @return {bool} true when all are done
*/
complete: function () {
return $.inArray(false, this.status) < 0;
},
/**
* Save an image in the images array and return its index
* @param {Image} image An Image object
* @return {int} the index of the image
*/
_add: function (image) {
var index = ap.push.call(this, image) - 1;
this.status[index] = false;
return index;
},
/**
* Return the index of an Image within the images array
* @param {Image} img An Image
* @return {int} the index within the array, or -1 if it was not found
*/
indexOf: function (image) {
return u.indexOf(this, image);
},
/**
* Clear this object and reset it to its initial state after binding.
*/
clear: function () {
var me = this;
if (me.ids && me.ids.length > 0) {
$.each(me.ids, function (_, e) {
delete me[e];
});
}
/**
* A list of the cross-reference IDs bound to this object
* @type {string[]}
*/
me.ids = [];
/**
* Length property for array-like behavior, set to zero when initializing. Array prototype
* methods will update it after that.
*
* @type {int}
*/
me.length = 0;
/**
* the loaded status of the corresponding image
* @type {boolean[]}
*/
me.status = [];
// actually erase the images
me.splice(0);
},
/**
* Bind an image to the map and add it to the queue to be loaded; return an ID that
* can be used to reference the
*
* @param {Image|string} image An Image object or a URL to an image
* @param {string} [id] An id to refer to this image
* @returns {int} an ID referencing the index of the image object in
* map_data.images
*/
add: function (image, id) {
var index,
src,
me = this;
if (!image) {
return;
}
if (typeof image === 'string') {
src = image;
image = me[src];
if (typeof image === 'object') {
return me.indexOf(image);
}
image = $('<img />').addClass('mapster_el').hide();
index = me._add(image[0]);
image
.on('load.mapster', function (e) {
me.imageLoaded.call(me, e);
})
.on('error.mapster', function (e) {
me.imageLoadError.call(me, e);
});
image.attr('src', src);
} else {
// use attr because we want the actual source, not the resolved path the browser will return directly calling image.src
index = me._add($(image)[0]);
}
if (id) {
if (this[id]) {
throw (
id + ' is already used or is not available as an altImage alias.'
);
}
me.ids.push(id);
me[id] = me[index];
}
return index;
},
/**
* Bind the images in this object,
* @return {Promise} a promise that resolves when the images have finished loading
*/
bind: function () {
var me = this,
promise,
triesLeft = me.owner.options.configTimeout / 200,
/* A recursive function to continue checking that the images have been
loaded until a timeout has elapsed */
check = function () {
var i;
// refresh status of images
i = me.length;
while (i-- > 0) {
if (!me.isLoaded(i)) {
break;
}
}
// check to see if every image has already been loaded
if (me.complete()) {
me.resolve();
} else {
// to account for failure of onLoad to fire in rare situations
if (triesLeft-- > 0) {
me.imgTimeout = window.setTimeout(function () {
check.call(me, true);
}, 50);
} else {
me.imageLoadError.call(me);
}
}
};
promise = me.deferred = u.defer();
check();
return promise;
},
resolve: function () {
var me = this,
resolver = me.deferred;
if (resolver) {
// Make a copy of the resolver before calling & removing it to ensure
// it is not called twice
me.deferred = null;
resolver.resolve();
}
},
/**
* Event handler for image onload
* @param {object} e jQuery event data
*/
imageLoaded: function (e) {
var me = this,
index = me.indexOf(e.target);
if (index >= 0) {
me.status[index] = true;
if ($.inArray(false, me.status) < 0) {
me.resolve();
}
}
},
/**
* Event handler for onload error
* @param {object} e jQuery event data
*/
imageLoadError: function (e) {
clearTimeout(this.imgTimeout);
this.triesLeft = 0;
var err = e
? 'The image ' + e.target.src + ' failed to load.'
: 'The images never seemed to finish loading. You may just need to increase the configTimeout if images could take a long time to load.';
throw err;
},
/**
* Test if the image at specificed index has finished loading
* @param {int} index The image index
* @return {boolean} true if loaded, false if not
*/
isLoaded: function (index) {
var img,
me = this,
status = me.status;
if (status[index]) {
return true;
}
img = me[index];
if (typeof img.complete !== 'undefined') {
status[index] = img.complete;
} else {
status[index] = !!u.imgWidth(img);
}
// if complete passes, the image is loaded, but may STILL not be available because of stuff like adblock.
// make sure it is.
return status[index];
}
};
})(jQuery);
/*
mapdata.js
The MapData object, repesents an instance of a single bound imagemap
*/
(function ($) {
'use strict';
var m = $.mapster,
u = m.utils;
/**
* Set default values for MapData object properties
* @param {MapData} me The MapData object
*/
function initializeDefaults(me) {
$.extend(me, {
complete: false, // (bool) when configuration is complete
map: null, // ($) the image map
base_canvas: null, // (canvas|var) where selections are rendered
overlay_canvas: null, // (canvas|var) where highlights are rendered
commands: [], // {} commands that were run before configuration was completed (b/c images weren't loaded)
data: [], // MapData[] area groups
mapAreas: [], // MapArea[] list. AreaData entities contain refs to this array, so options are stored with each.
_xref: {}, // (int) xref of mapKeys to data[]
highlightId: -1, // (int) the currently highlighted element.
currentAreaId: -1,
_tooltip_events: [], // {} info on events we bound to a tooltip container, so we can properly unbind them
scaleInfo: null, // {} info about the image size, scaling, defaults
index: -1, // index of this in map_cache - so we have an ID to use for wraper div
activeAreaEvent: null,
autoResizeTimer: null // tracks autoresize timer based on options.autoResizeDelay
});
}
/**
* Return an array of all image-containing options from an options object;
* that is, containers that may have an "altImage" property
*
* @param {object} obj An options object
* @return {object[]} An array of objects
*/
function getOptionImages(obj) {
return [obj, obj.render_highlight, obj.render_select];
}
/**
* Parse all the altImage references, adding them to the library so they can be preloaded
* and aliased.
*
* @param {MapData} me The MapData object on which to operate
*/
function configureAltImages(me) {
var opts = me.options,
mi = me.images;
// add alt images
if (m.hasCanvas()) {
// map altImage library first
$.each(opts.altImages || {}, function (i, e) {
mi.add(e, i);
});
// now find everything else
$.each([opts].concat(opts.areas), function (_, e) {
$.each(getOptionImages(e), function (_, e2) {
if (e2 && e2.altImage) {
e2.altImageId = mi.add(e2.altImage);
}
});
});
}
// set area_options
me.area_options = u.updateProps(
{}, // default options for any MapArea
m.area_defaults,
opts
);
}
/**
* Queue a mouse move action based on current delay settings
* (helper for mouseover/mouseout handlers)
*
* @param {MapData} me The MapData context
* @param {number} delay The number of milliseconds to delay the action
* @param {AreaData} area AreaData affected
* @param {Deferred} deferred A deferred object to return (instead of a new one)
* @return {Promise} A promise that resolves when the action is completed
*/
function queueMouseEvent(me, delay, area, deferred) {
deferred = deferred || u.when.defer();
function cbFinal(areaId) {
if (me.currentAreaId !== areaId && me.highlightId >= 0) {
deferred.resolve({ completeAction: true });
}
}
if (me.activeAreaEvent) {
window.clearTimeout(me.activeAreaEvent);
me.activeAreaEvent = 0;
}
if (delay < 0) {
deferred.resolve({ completeAction: false });
} else {
if (area.owner.currentAction || delay) {
me.activeAreaEvent = window.setTimeout(
(function () {
return function () {
queueMouseEvent(me, 0, area, deferred);
};
})(area),
delay || 100
);
} else {
cbFinal(area.areaId);
}
}
return deferred;
}
function shouldNavigateTo(href) {
return !!href && href !== '#';
}
/**
* Mousedown event. This is captured only to prevent browser from drawing an outline around an
* area when it's clicked.
*
* @param {EventData} e jQuery event data
*/
function mousedown(e) {
if (!m.hasCanvas()) {
this.blur();
}
e.preventDefault();
}
/**
* Mouseover event. Handle highlight rendering and client callback on mouseover
*
* @param {MapData} me The MapData context
* @param {EventData} e jQuery event data
* @return {[type]} [description]
*/
function mouseover(me, e) {
var arData = me.getAllDataForArea(this),
ar = arData.length ? arData[0] : null;
// mouseover events are ignored entirely while resizing, though we do care about mouseout events
// and must queue the action to keep things clean.
if (!ar || ar.isNotRendered() || ar.owner.currentAction) {
return;
}
if (me.currentAreaId === ar.areaId) {
return;
}
if (me.highlightId !== ar.areaId) {
me.clearEffects();
ar.highlight();
if (me.options.showToolTip) {
$.each(arData, function (_, e) {
if (e.effectiveOptions().toolTip) {
e.showToolTip();
}
});
}
}
me.currentAreaId = ar.areaId;
if (u.isFunction(me.options.onMouseover)) {
me.options.onMouseover.call(this, {
e: e,
options: ar.effectiveOptions(),
key: ar.key,
selected: ar.isSelected()
});
}
}
/**
* Mouseout event.
*
* @param {MapData} me The MapData context
* @param {EventData} e jQuery event data
* @return {[type]} [description]
*/
function mouseout(me, e) {
var newArea,
ar = me.getDataForArea(this),
opts = me.options;
if (me.currentAreaId < 0 || !ar) {
return;
}
newArea = me.getDataForArea(e.relatedTarget);
if (newArea === ar) {
return;
}
me.currentAreaId = -1;
ar.area = null;
queueMouseEvent(me, opts.mouseoutDelay, ar).then(function (result) {
if (!result.completeAction) {
return;
}
me.clearEffects();
});
if (u.isFunction(opts.onMouseout)) {
opts.onMouseout.call(this, {
e: e,
options: opts,
key: ar.key,
selected: ar.isSelected()
});
}
}
/**
* Clear any active tooltip or highlight
*
* @param {MapData} me The MapData context
* @param {EventData} e jQuery event data
* @return {[type]} [description]
*/
function clearEffects(me) {
var opts = me.options;
me.ensureNoHighlight();
if (
opts.toolTipClose &&
$.inArray('area-mouseout', opts.toolTipClose) >= 0 &&
me.activeToolTip
) {
me.clearToolTip();
}
}
/**
* Mouse click event handler
*
* @param {MapData} me The MapData context
* @param {EventData} e jQuery event data
* @return {[type]} [description]
*/
function click(me, e) {
var list,
list_target,
newSelectionState,
canChangeState,
cbResult,
that = this,
ar = me.getDataForArea(this),
opts = me.options,
navDetails,
areaOpts;
function navigateTo(mode, href, target) {
switch (mode) {
// if no target is specified, use legacy
// behavior and change current window
case 'open':
window.open(href, target || '_self');
return;
// default legacy behavior of ImageMapster
default:
window.location.href = href;
return;
}
}
function getNavDetails(ar, mode, defaultHref) {
if (mode === 'open') {
var elHref = $(ar.area).attr('href'),
useEl = shouldNavigateTo(elHref);
return {
href: useEl ? elHref : ar.href,
target: useEl ? $(ar.area).attr('target') : ar.hrefTarget
};
}
return {
href: defaultHref
};
}
function clickArea(ar) {
var target;
canChangeState =
ar.isSelectable() && (ar.isDeselectable() || !ar.isSelected());
if (canChangeState) {
newSelectionState = !ar.isSelected();
} else {
newSelectionState = ar.isSelected();
}
list_target = m.getBoundList(opts, ar.key);
if (u.isFunction(opts.onClick)) {
cbResult = opts.onClick.call(that, {
e: e,
listTarget: list_target,
key: ar.key,
selected: newSelectionState
});
if (u.isBool(cbResult)) {
if (!cbResult) {
return false;
}
target = getNavDetails(
ar,
opts.navigateMode,
$(ar.area).attr('href')
);
if (shouldNavigateTo(target.href)) {
navigateTo(opts.navigateMode, target.href, target.target);
return false;
}
}
}
if (canChangeState) {
ar.toggle();
}
}
mousedown.call(this, e);
navDetails = getNavDetails(ar, opts.navigateMode, ar.href);
if (opts.clickNavigate && shouldNavigateTo(navDetails.href)) {
navigateTo(opts.navigateMode, navDetails.href, navDetails.target);
return;
}
if (ar && !ar.owner.currentAction) {
opts = me.options;
clickArea(ar);
areaOpts = ar.effectiveOptions();
if (areaOpts.includeKeys) {
list = u.split(areaOpts.includeKeys);
$.each(list, function (_, e) {
var ar = me.getDataForKey(e.toString());
if (!ar.options.isMask) {
clickArea(ar);
}
});
}
}
}
/**
* Prototype for a MapData object, representing an ImageMapster bound object
* @param {Element} image an IMG element
* @param {object} options ImageMapster binding options
*/
m.MapData = function (image, options) {
var me = this;
// (Image) main map image
me.image = image;
me.images = new m.MapImages(me);
me.graphics = new m.Graphics(me);
// save the initial style of the image for unbinding. This is problematic, chrome
// duplicates styles when assigning, and cssText is apparently not universally supported.
// Need to do something more robust to make unbinding work universally.
me.imgCssText = image.style.cssText || null;
initializeDefaults(me);
me.configureOptions(options);
// create context-bound event handlers from our private functions
me.mouseover = function (e) {
mouseover.call(this, me, e);
};
me.mouseout = function (e) {
mouseout.call(this, me, e);
};
me.click = function (e) {
click.call(this, me, e);
};
me.clearEffects = function (e) {
clearEffects.call(this, me, e);
};
me.mousedown = function (e) {
mousedown.call(this, e);
};
};
m.MapData.prototype = {
constructor: m.MapData,
/**
* Set target.options from defaults + options
* @param {[type]} target The target
* @param {[type]} options The options to merge
*/
configureOptions: function (options) {
this.options = u.updateProps({}, m.defaults, options);
},
/**
* Ensure all images are loaded
* @return {Promise} A promise that resolves when the images have finished loading (or fail)
*/
bindImages: function () {
var me = this,
mi = me.images;
// reset the images if this is a rebind
if (mi.length > 2) {
mi.splice(2);
} else if (mi.length === 0) {
// add the actual main image
mi.add(me.image);
// will create a duplicate of the main image, we need this to get raw size info
mi.add(me.image.src);
}
configureAltImages(me);
return me.images.bind();
},
/**
* Test whether an async action is currently in progress
* @return {Boolean} true or false indicating state
*/
isActive: function () {
return !this.complete || this.currentAction;
},
/**
* Return an object indicating the various states. This isn't really used by
* production code.
*
* @return {object} An object with properties for various states
*/
state: function () {
return {
complete: this.complete,
resizing: this.currentAction === 'resizing',
zoomed: this.zoomed,
zoomedArea: this.zoomedArea,
scaleInfo: this.scaleInfo
};
},
/**
* Get a unique ID for the wrapper of this imagemapster
* @return {string} A string that is unique to this image
*/
wrapId: function () {
return 'mapster_wrap_' + this.index;
},
instanceEventNamespace: function () {
return '.mapster.' + this.wrapId();
},
_idFromKey: function (key) {
return typeof key === 'string' &&
Object.prototype.hasOwnProperty.call(this._xref, key)
? this._xref[key]
: -1;
},
/**
* Return a comma-separated string of all selected keys
* @return {string} CSV of all keys that are currently selected
*/
getSelected: function () {
var result = '';
$.each(this.data, function (_, e) {
if (e.isSelected()) {
result += (result ? ',' : '') + this.key;
}
});
return result;
},
/**
* Get an array of MapAreas associated with a specific AREA based on the keys for that area
* @param {Element} area An HTML AREA
* @param {number} atMost A number limiting the number of areas to be returned (typically 1 or 0 for no limit)
* @return {MapArea[]} Array of MapArea objects
*/
getAllDataForArea: function (area, atMost) {
var i,
ar,
result,
me = this,
key = $(area).filter('area').attr(me.options.mapKey);
if (key) {
result = [];
key = u.split(key);
for (i = 0; i < (atMost || key.length); i++) {
ar = me.data[me._idFromKey(key[i])];
if (ar) {
ar.area = area.length ? area[0] : area;
// set the actual area moused over/selected
// TODO: this is a brittle model for capturing which specific area - if this method was not used,
// ar.area could have old data. fix this.
result.push(ar);
}
}
}
return result;
},
getDataForArea: function (area) {
var ar = this.getAllDataForArea(area, 1);
return ar ? ar[0] || null : null;
},
getDataForKey: function (key) {
return this.data[this._idFromKey(key)];
},
/**
* Get the primary keys associated with an area group.
* If this is a primary key, it will be returned.
*
* @param {string key An area key
* @return {string} A CSV of area keys
*/
getKeysForGroup: function (key) {
var ar = this.getDataForKey(key);
return !ar
? ''
: ar.isPrimary
? ar.key
: this.getPrimaryKeysForMapAreas(ar.areas()).join(',');
},
/**
* given an array of MapArea object, return an array of its unique primary keys
* @param {MapArea[]} areas The areas to analyze
* @return {string[]} An array of unique primary keys
*/
getPrimaryKeysForMapAreas: function (areas) {
var keys = [];
$.each(areas, function (_, e) {
if ($.inArray(e.keys[0], keys) < 0) {
keys.push(e.keys[0]);
}
});
return keys;
},
getData: function (obj) {
if (typeof obj === 'string') {
return this.getDataForKey(obj);
} else if ((obj && obj.mapster) || u.isElement(obj)) {
return this.getDataForArea(obj);
} else {
return null;
}
},
// remove highlight if present, raise event
ensureNoHighlight: function () {
var ar;
if (this.highlightId >= 0) {
this.graphics.clearHighlight();
ar = this.data[this.highlightId];
ar.changeState('highlight', false);
this.setHighlightId(-1);
}
},
setHighlightId: function (id) {
this.highlightId = id;
},
/**
* Clear all active selections on this map
*/
clearSelections: function () {
$.each(this.data, function (_, e) {
if (e.selected) {
e.deselect(true);
}
});
this.removeSelectionFinish();
},
/**
* Set area options from an array of option data.
*
* @param {object[]} areas An array of objects containing area-specific options
*/
setAreaOptions: function (areas) {
var i, area_options, ar;
areas = areas || [];
// refer by: map_data.options[map_data.data[x].area_option_id]
for (i = areas.length - 1; i >= 0; i--) {
area_options = areas[i];
if (area_options) {
ar = this.getDataForKey(area_options.key);
if (ar) {
u.updateProps(ar.options, area_options);
// TODO: will not deselect areas that were previously selected, so this only works
// for an initial bind.
if (u.isBool(area_options.selected)) {
ar.selected = area_options.selected;
}
}
}
}
},
// keys: a comma-separated list
drawSelections: function (keys) {
var i,
key_arr = u.asArray(keys);
for (i = key_arr.length - 1; i >= 0; i--) {
this.data[key_arr[i]].drawSelection();
}
},
redrawSelections: function () {
$.each(this.data, function (_, e) {
if (e.isSelectedOrStatic()) {
e.drawSelection();
}
});
},
// Causes changes to the bound list based on the user action (select or deselect)
// area: the jQuery area object
// returns the matching elements from the bound list for the first area passed
// (normally only one should be passed, but a list can be passed)
setBoundListProperties: function (opts, target, selected) {
target.each(function (_, e) {
if (opts.listSelectedClass) {
if (selected) {
$(e).addClass(opts.listSelectedClass);
} else {
$(e).removeClass(opts.listSelectedClass);
}
}
if (opts.listSelectedAttribute) {
$(e).prop(opts.listSelectedAttribute, selected);
}
});
},
clearBoundListProperties: function (opts) {
var me = this;
if (!opts.boundList) {
return;
}
me.setBoundListProperties(opts, opts.boundList, false);
},
refreshBoundList: function (opts) {
var me = this;
me.clearBoundListProperties(opts);
me.setBoundListProperties(
opts,
m.getBoundList(opts, me.getSelected()),
true
);
},
setBoundList: function (opts) {
var me = this,
sorted_list = me.data.slice(0),
sort_func;
if (opts.sortList) {
if (opts.sortList === 'desc') {
sort_func = function (a, b) {
return a === b ? 0 : a > b ? -1 : 1;
};
} else {
sort_func = function (a, b) {
return a === b ? 0 : a < b ? -1 : 1;
};
}
sorted_list.sort(function (a, b) {
a = a.value;
b = b.value;
return sort_func(a, b);
});
}
me.options.boundList = opts.onGetList.call(me.image, sorted_list);
},
///called when images are done loading
initialize: function () {
var imgCopy,
base_canvas,
overlay_canvas,
wrap,
parentId,
css,
i,
size,
img,
scale,
me = this,
opts = me.options;
if (me.complete) {
return;
}
img = $(me.image);
parentId = img.parent().attr('id');
// create a div wrapper only if there's not already a wrapper, otherwise, own it
if (
parentId &&
parentId.length >= 12 &&
parentId.substring(0, 12) === 'mapster_wrap'
) {
wrap = img.parent();
wrap.attr('id', me.wrapId());
} else {
wrap = $('<div id="' + me.wrapId() + '"></div>');
if (opts.wrapClass) {
if (opts.wrapClass === true) {
wrap.addClass(img[0].className);
} else {
wrap.addClass(opts.wrapClass);
}
}
}
me.wrapper = wrap;
// me.images[1] is the copy of the original image. It should be loaded & at its native size now so we can obtain the true
// width & height. This is needed to scale the imagemap if not being shown at its native size. It is also needed purely
// to finish binding in case the original image was not visible. It can be impossible in some browsers to obtain the
// native size of a hidden image.
me.scaleInfo = scale = u.scaleMap(
me.images[0],
me.images[1],
opts.scaleMap
);
me.base_canvas = base_canvas = me.graphics.createVisibleCanvas(me);
me.overlay_canvas = overlay_canvas = me.graphics.createVisibleCanvas(me);
// Now we got what we needed from the copy -clone from the original image again to make sure any other attributes are copied
imgCopy = $(me.images[1])
.addClass('mapster_el ' + me.images[0].className)
.attr({ id: null, usemap: null });
size = u.size(me.images[0]);
if (size.complete) {
imgCopy.css({
width: size.width,
height: size.height
});
}
me.buildDataset();
// now that we have processed all the areas, set css for wrapper, scale map if needed
css = $.extend(
{
display: 'block',
position: 'relative',
padding: 0
},
opts.enableAutoResizeSupport === true
? {}
: {
width: scale.width,
height: scale.height
}
);
if (opts.wrapCss) {
$.extend(css, opts.wrapCss);
}
// if we were rebinding with an existing wrapper, the image will aready be in it
if (img.parent()[0] !== me.wrapper[0]) {
img.before(me.wrapper);
}
wrap.css(css);
// move all generated images into the wrapper for easy removal later
$(me.images.slice(2)).hide();
for (i = 1; i < me.images.length; i++) {
wrap.append(me.images[i]);
}
//me.images[1].style.cssText = me.image.style.cssText;
wrap
.append(base_canvas)
.append(overlay_canvas)
.append(img.css(m.canvas_style));
// images[0] is the original image with map, images[1] is the copy/background that is visible
u.setOpacity(me.images[0], 0);
$(me.images[1]).show();
u.setOpacity(me.images[1], 1);
me.complete = true;
me.processCommandQueue();
if (opts.enableAutoResizeSupport === true) {
me.configureAutoResize();
}
me.onConfigured();
},
onConfigured: function () {
var me = this,
$img = $(me.image),
opts = me.options;
if (opts.onConfigured && typeof opts.onConfigured === 'function') {
opts.onConfigured.call($img, true);
}
},
// when rebind is true, the MapArea data will not be rebuilt.
buildDataset: function (rebind) {
var sel,
areas,
j,
area_id,
$area,
area,
curKey,
mapArea,
key,
keys,
mapAreaId,
group_value,
dataItem,
href,
me = this,
opts = me.options,
default_group;
function addAreaData(key, value) {
var dataItem = new m.AreaData(me, key, value);
dataItem.areaId = me._xref[key] = me.data.push(dataItem) - 1;
return dataItem.areaId;
}
me._xref = {};
me.data = [];
if (!rebind) {
me.mapAreas = [];
}
default_group = !opts.mapKey;
if (default_group) {
opts.mapKey = 'data-mapster-key';
}
// the [attribute] selector is broken on old IE with jQuery. hasVml() is a quick and dirty
// way to test for that
sel = m.hasVml()
? 'area'
: default_group
? 'area[coords]'
: 'area[' + opts.mapKey + ']';
areas = $(me.map).find(sel).off('.mapster');
for (mapAreaId = 0; mapAreaId < areas.length; mapAreaId++) {
area_id = 0;
area = areas[mapAreaId];
$area = $(area);
// skip areas with no coords - selector broken for older ie
if (!area.coords) {
continue;
}
// Create a key if none was assigned by the user
if (default_group) {
curKey = String(mapAreaId);
$area.attr('data-mapster-key', curKey);
} else {
curKey = area.getAttribute(opts.mapKey);
}
// conditions for which the area will be bound to mouse events
// only bind to areas that don't have nohref. ie 6&7 cannot detect the presence of nohref, so we have to also not bind if href is missing.
if (rebind) {
mapArea = me.mapAreas[$area.data('mapster') - 1];
mapArea.configure(curKey);
mapArea.areaDataXref = [];
} else {
mapArea = new m.MapArea(me, area, curKey);
me.mapAreas.push(mapArea);
}
keys = mapArea.keys; // converted to an array by mapArea
// Iterate through each mapKey assigned to this area
for (j = keys.length - 1; j >= 0; j--) {
key = keys[j];
if (opts.mapValue) {
group_value = $area.attr(opts.mapValue);
}
if (default_group) {
// set an attribute so we can refer to the area by index from the DOM object if no key
area_id = addAreaData(me.data.length, group_value);
dataItem = me.data[area_id];
dataItem.key = key = area_id.toString();
} else {
area_id = me._xref[key];
if (area_id >= 0) {
dataItem = me.data[area_id];
if (group_value && !me.data[area_id].value) {
dataItem.value = group_value;
}
} else {
area_id = addAreaData(key, group_value);
dataItem = me.data[area_id];
dataItem.isPrimary = j === 0;
}
}
mapArea.areaDataXref.push(area_id);
dataItem.areasXref.push(mapAreaId);
}
href = $area.attr('href');
if (shouldNavigateTo(href) && !dataItem.href) {
dataItem.href = href;
dataItem.hrefTarget = $area.attr('target');
}
if (!mapArea.nohref) {
$area
.on('click.mapster', me.click)
.on(
'mouseover.mapster touchstart.mapster.noPreventDefault',
me.mouseover
)
.on(
'mouseout.mapster touchend.mapster.noPreventDefault',
me.mouseout
)
.on('mousedown.mapster', me.mousedown);
}
// store an ID with each area.
$area.data('mapster', mapAreaId + 1);
}
// TODO listenToList
// if (opts.listenToList && opts.nitG) {
// opts.nitG.bind('click.mapster', event_hooks[map_data.hooks_index].listclick_hook);
// }
// populate areas from config options
me.setAreaOptions(opts.areas);
if (opts.onGetList) {
me.setBoundList(opts);
}
if (opts.boundList && opts.boundList.length > 0) {
me.refreshBoundList(opts);
}
if (rebind) {
me.graphics.removeSelections();
me.graphics.refreshSelections();
} else {
me.redrawSelections();
}
},
processCommandQueue: function () {
var cur,
me = this;
while (!me.currentAction && me.commands.length) {
cur = me.commands[0];
me.commands.splice(0, 1);
m.impl[cur.command].apply(cur.that, cur.args);
}
},
clearEvents: function () {
$(this.map).find('area').off('.mapster');
$(this.images).off('.mapster');
$(window).off(this.instanceEventNamespace());
$(window.document).off(this.instanceEventNamespace());
},
_clearCanvases: function (preserveState) {
// remove the canvas elements created
if (!preserveState) {
$(this.base_canvas).remove();
}
$(this.overlay_canvas).remove();
},
clearMapData: function (preserveState) {
var me = this;
this._clearCanvases(preserveState);
// release refs to DOM elements
$.each(this.data, function (_, e) {
e.reset();
});
this.data = null;
if (!preserveState) {
// get rid of everything except the original image
this.image.style.cssText = this.imgCssText;
$(this.wrapper).before(this.image).remove();
}
me.images.clear();
if (me.autoResizeTimer) {
clearTimeout(me.autoResizeTimer);
}
me.autoResizeTimer = null;
this.image = null;
u.ifFunction(this.clearToolTip, this);
},
// Compelete cleanup process for deslecting items. Called after a batch operation, or by AreaData for single
// operations not flagged as "partial"
removeSelectionFinish: function () {
var g = this.graphics;
g.refreshSelections();
// do not call ensure_no_highlight- we don't really want to unhilight it, just remove the effect
g.clearHighlight();
}
};
})(jQuery);
/* areadata.js
AreaData and MapArea protoypes
*/
(function ($) {
'use strict';
var m = $.mapster,
u = m.utils;
function optsAreEqual(opts1, opts2) {
// deep compare is not trivial and current testing framework
// doesn't provide a way to detect this accurately so only
// implementing basic compare at this time.
// TODO: Implement deep obj compare or for perf reasons shallow
// with a short-circuit if deep is required for full compare
// since config options should only require shallow
return opts1 === opts2;
}
/**
* Update selected state of this area
*
* @param {boolean} selected Determines whether areas are selected or deselected
*/
function updateSelected(selected) {
var me = this,
prevSelected = me.selected;
me.selected = selected;
me.staticStateOverridden = u.isBool(me.effectiveOptions().staticState)
? true
: false;
return prevSelected !== selected;
}
/**
* Select this area
*
* @param {AreaData} me AreaData context
* @param {object} options Options for rendering the selection
*/
function select(options) {
function buildOptions() {
// map the altImageId if an altimage was passed
return $.extend(me.effectiveRenderOptions('select'), options, {
altImageId: o.images.add(options.altImage)
});
}
var me = this,
o = me.owner,
hasOptions = !$.isEmptyObject(options),
newOptsCache = hasOptions ? buildOptions() : null,
// Per docs, options changed via set_options for an area that is
// already selected will not be reflected until the next time
// the area becomes selected.
changeOptions = hasOptions
? !optsAreEqual(me.optsCache, newOptsCache)
: false,
selectedHasChanged = false,
isDrawn = me.isSelectedOrStatic();
// This won't clear staticState === true areas that have not been overridden via API set/select/deselect.
// This could be optimized to only clear if we are the only one selected. However, there are scenarios
// that do not respect singleSelect (e.g. initialization) so we force clear if there should only be one.
// TODO: Only clear if we aren't the only one selected (depends on #370)
if (o.options.singleSelect) {
o.clearSelections();
// we may (staticState === true) or may not still be visible
isDrawn = me.isSelectedOrStatic();
}
if (changeOptions) {
me.optsCache = newOptsCache;
}
// Update before we start drawing for methods
// that rely on internal selected value.
// Force update because area can be selected
// at multiple levels (selected / area_options.selected / staticState / etc.)
// and could have been cleared.
selectedHasChanged = me.updateSelected(true);
if (isDrawn && changeOptions) {
// no way to remove just this area from canvas so must refresh everything
// explicitly remove vml element since it uses removeSelections instead of refreshSelections
// TODO: Not sure why removeSelections isn't incorporated in to refreshSelections
// need to investigate and possibly consolidate
o.graphics.removeSelections(me.areaId);
o.graphics.refreshSelections();
} else if (!isDrawn) {
me.drawSelection();
}
// don't fire until everything is done
if (selectedHasChanged) {
me.changeState('select', true);
}
}
/**
* Deselect this area, optionally deferring finalization so additional areas can be deselected
* in a single operation
*
* @param {boolean} partial when true, the caller must invoke "finishRemoveSelection" to render
*/
function deselect(partial) {
var me = this,
selectedHasChanged = false;
// update before we start drawing for methods
// that rely on internal selected value
// force update because area can be selected
// at multiple levels (selected / area_options.selected / staticState / etc.)
selectedHasChanged = me.updateSelected(false);
// release information about last area options when deselecting.
me.optsCache = null;
me.owner.graphics.removeSelections(me.areaId);
// Complete selection removal process. This is separated because it's very inefficient to perform the whole
// process for multiple removals, as the canvas must be totally redrawn at the end of the process.ar.remove
if (!partial) {
me.owner.removeSelectionFinish();
}
// don't fire until everything is done
if (selectedHasChanged) {
me.changeState('select', false);
}
}
/**
* Toggle the selection state of this area
* @param {object} options Rendering options, if toggling on
* @return {bool} The new selection state
*/
function toggle(options) {
var me = this;
if (!me.isSelected()) {
me.select(options);
} else {
me.deselect();
}
return me.isSelected();
}
function isNoHref(areaEl) {
var $area = $(areaEl);
return u.hasAttribute($area, 'nohref') || !u.hasAttribute($area, 'href');
}
/**
* An AreaData object; represents a conceptual area that can be composed of
* one or more MapArea objects
*
* @param {MapData} owner The MapData object to which this belongs
* @param {string} key The key for this area
* @param {string} value The mapValue string for this area
*/
m.AreaData = function (owner, key, value) {
$.extend(this, {
owner: owner,
key: key || '',
// means this represents the first key in a list of keys (it's the area group that gets highlighted on mouseover)
isPrimary: true,
areaId: -1,
href: '',
hrefTarget: null,
value: value || '',
options: {},
// "null" means unchanged. Use "isSelected" method to just test true/false
selected: null,
// "true" means selected has been set via API AND staticState is true/false
staticStateOverridden: false,
// xref to MapArea objects
areasXref: [],
// (temporary storage) - the actual area moused over
area: null,
// the last options used to render this. Cache so when re-drawing after a remove, changes in options won't
// break already selected things.
optsCache: null
});
};
/**
* The public API for AreaData object
*/
m.AreaData.prototype = {
constuctor: m.AreaData,
select: select,
deselect: deselect,
toggle: toggle,
updateSelected: updateSelected,
areas: function () {
var i,
result = [];
for (i = 0; i < this.areasXref.length; i++) {
result.push(this.owner.mapAreas[this.areasXref[i]]);
}
return result;
},
// return all coordinates for all areas
coords: function (offset) {
var coords = [];
$.each(this.areas(), function (_, el) {
coords = coords.concat(el.coords(offset));
});
return coords;
},
reset: function () {
$.each(this.areas(), function (_, e) {
e.reset();
});
this.areasXref = [];
this.options = null;
},
// Return the effective selected state of an area, incorporating staticState
isSelectedOrStatic: function () {
var o = this.effectiveOptions();
return !u.isBool(o.staticState) || this.staticStateOverridden
? this.isSelected()
: o.staticState;
},
isSelected: function () {
return u.isBool(this.selected)
? this.selected
: u.isBool(this.owner.area_options.selected)
? this.owner.area_options.selected
: false;
},
isSelectable: function () {
return u.isBool(this.effectiveOptions().staticState)
? false
: u.isBool(this.owner.options.staticState)
? false
: u.boolOrDefault(this.effectiveOptions().isSelectable, true);
},
isDeselectable: function () {
return u.isBool(this.effectiveOptions().staticState)
? false
: u.isBool(this.owner.options.staticState)
? false
: u.boolOrDefault(this.effectiveOptions().isDeselectable, true);
},
isNotRendered: function () {
return isNoHref(this.area) || this.effectiveOptions().isMask;
},
/**
* Return the overall options effective for this area.
* This should get the default options, and merge in area-specific options, finally
* overlaying options passed by parameter
*
* @param {[type]} options options which will supercede all other options for this area
* @return {[type]} the combined options
*/
effectiveOptions: function (options) {
var opts = u.updateProps(
{},
this.owner.area_options,
this.options,
options || {},
{
id: this.areaId
}
);
opts.selected = this.isSelected();
return opts;
},
/**
* Return the options effective for this area for a "render" or "highlight" mode.
* This should get the default options, merge in the areas-specific options,
* and then the mode-specific options.
* @param {string} mode 'render' or 'highlight'
* @param {[type]} options options which will supercede all other options for this area
* @return {[type]} the combined options
*/
effectiveRenderOptions: function (mode, options) {
var allOpts,
opts = this.optsCache;
if (!opts || mode === 'highlight') {
allOpts = this.effectiveOptions(options);
opts = u.updateProps({}, allOpts, allOpts['render_' + mode]);
if (mode !== 'highlight') {
this.optsCache = opts;
}
}
return $.extend({}, opts);
},
// Fire callback on area state change
changeState: function (state_type, state) {
if (u.isFunction(this.owner.options.onStateChange)) {
this.owner.options.onStateChange.call(this.owner.image, {
key: this.key,
state: state_type,
selected: state
});
}
if (state_type === 'select' && this.owner.options.boundList) {
this.owner.setBoundListProperties(
this.owner.options,
m.getBoundList(this.owner.options, this.key),
state
);
}
},
// highlight this area
highlight: function (options) {
var o = this.owner;
o.ensureNoHighlight();
if (this.effectiveOptions().highlight) {
o.graphics.addShapeGroup(this, 'highlight', options);
}
o.setHighlightId(this.areaId);
this.changeState('highlight', true);
},
// select this area. if "callEvent" is true then the state change event will be called. (This method can be used
// during config operations, in which case no event is indicated)
drawSelection: function () {
this.owner.graphics.addShapeGroup(this, 'select');
}
};
// represents an HTML area
m.MapArea = function (owner, areaEl, keys) {
if (!owner) {
return;
}
var me = this;
me.owner = owner; // a MapData object
me.area = areaEl;
me.areaDataXref = []; // a list of map_data.data[] id's for each areaData object containing this
me.originalCoords = [];
$.each(u.split(areaEl.coords), function (_, el) {
me.originalCoords.push(parseFloat(el));
});
me.length = me.originalCoords.length;
me.shape = u.getShape(areaEl);
me.nohref = isNoHref(areaEl);
me.configure(keys);
};
m.MapArea.prototype = {
constructor: m.MapArea,
configure: function (keys) {
this.keys = u.split(keys);
},
reset: function () {
this.area = null;
},
coords: function (offset) {
return $.map(this.originalCoords, function (e) {
return offset ? e : e + offset;
});
}
};
})(jQuery);
/* areacorners.js
determine the best place to put a box of dimensions (width,height) given a circle, rect or poly
*/
(function ($) {
'use strict';
var u = $.mapster.utils;
/**
* Compute positions that will place a target with dimensions [width,height] outside
* but near the boundaries of the elements "elements". When an imagemap is passed, the
*
* @param {Element|Element[]} elements An element or an array of elements (such as a jQuery object)
* @param {Element} image The image to which area elements are bound, if this is an image map.
* @param {Element} container The contianer in which the target must be constrained (or document, if missing)
* @param {int} width The width of the target object
* @return {object} a structure with the x and y positions
*/
u.areaCorners = function (elements, image, container, width, height) {
var pos,
found,
minX,
minY,
maxX,
maxY,
bestMinX,
bestMaxX,
bestMinY,
bestMaxY,
curX,
curY,
nest,
j,
offsetx = 0,
offsety = 0,
rootx,
rooty,
iCoords,
radius,
angle,
el,
coords = [];
// if a single element was passed, map it to an array
elements = elements.length ? elements : [elements];
container = container ? $(container) : $(document.body);
// get the relative root of calculation
pos = container.offset();
rootx = pos.left;
rooty = pos.top;
// with areas, all we know about is relative to the top-left corner of the image. We need to add an offset compared to
// the actual container. After this calculation, offsetx/offsety can be added to either the area coords, or the target's
// absolute position to get the correct top/left boundaries of the container.
if (image) {
pos = $(image).offset();
offsetx = pos.left;
offsety = pos.top;
}
// map the coordinates of any type of shape to a poly and use the logic. simpler than using three different
// calculation methods. Circles use a 20 degree increment for this estimation.
for (j = 0; j < elements.length; j++) {
el = elements[j];
if (el.nodeName === 'AREA') {
iCoords = u.split(el.coords, parseInt);
switch (u.getShape(el)) {
case 'circle':
case 'circ':
curX = iCoords[0];
curY = iCoords[1];
radius = iCoords[2];
coords = [];
for (j = 0; j < 360; j += 20) {
angle = (j * Math.PI) / 180;
coords.push(
curX + radius * Math.cos(angle),
curY + radius * Math.sin(angle)
);
}
break;
case 'rectangle':
case 'rect':
coords.push(
iCoords[0],
iCoords[1],
iCoords[2],
iCoords[1],
iCoords[2],
iCoords[3],
iCoords[0],
iCoords[3]
);
break;
default:
coords = coords.concat(iCoords);
break;
}
// map area positions to it's real position in the container
for (j = 0; j < coords.length; j += 2) {
coords[j] = parseInt(coords[j], 10) + offsetx;
coords[j + 1] = parseInt(coords[j + 1], 10) + offsety;
}
} else {
el = $(el);
pos = el.position();
coords.push(
pos.left,
pos.top,
pos.left + el.width(),
pos.top,
pos.left + el.width(),
pos.top + el.height(),
pos.left,
pos.top + el.height()
);
}
}
minX = minY = bestMinX = bestMinY = 999999;
maxX = maxY = bestMaxX = bestMaxY = -1;
for (j = coords.length - 2; j >= 0; j -= 2) {
curX = coords[j];
curY = coords[j + 1];
if (curX < minX) {
minX = curX;
bestMaxY = curY;
}
if (curX > maxX) {
maxX = curX;
bestMinY = curY;
}
if (curY < minY) {
minY = curY;
bestMaxX = curX;
}
if (curY > maxY) {
maxY = curY;
bestMinX = curX;
}
}
// try to figure out the best place for the tooltip
if (width && height) {
found = false;
$.each(
[
[bestMaxX - width, minY - height],
[bestMinX, minY - height],
[minX - width, bestMaxY - height],
[minX - width, bestMinY],
[maxX, bestMaxY - height],
[maxX, bestMinY],
[bestMaxX - width, maxY],
[bestMinX, maxY]
],
function (_, e) {
if (!found && e[0] > rootx && e[1] > rooty) {
nest = e;
found = true;
return false;
}
}
);
// default to lower-right corner if nothing fit inside the boundaries of the image
if (!found) {
nest = [maxX, maxY];
}
}
return nest;
};
})(jQuery);
/*
scale.js
Resize and zoom functionality
Requires areacorners.js
*/
(function ($) {
'use strict';
var m = $.mapster,
u = m.utils,
p = m.MapArea.prototype;
m.utils.getScaleInfo = function (eff, actual) {
var pct;
if (!actual) {
pct = 1;
actual = eff;
} else {
pct = eff.width / actual.width || eff.height / actual.height;
// make sure a float error doesn't muck us up
if (pct > 0.98 && pct < 1.02) {
pct = 1;
}
}
return {
scale: pct !== 1,
scalePct: pct,
realWidth: actual.width,
realHeight: actual.height,
width: eff.width,
height: eff.height,
ratio: eff.width / eff.height
};
};
// Scale a set of AREAs, return old data as an array of objects
m.utils.scaleMap = function (image, imageRaw, scale) {
// stunningly, jQuery width can return zero even as width does not, seems to happen only
// with adBlock or maybe other plugins. These must interfere with onload events somehow.
var vis = u.size(image),
raw = u.size(imageRaw, true);
if (!raw.complete()) {
throw 'Another script, such as an extension, appears to be interfering with image loading. Please let us know about this.';
}
if (!vis.complete()) {
vis = raw;
}
return this.getScaleInfo(vis, scale ? raw : null);
};
/**
* Resize the image map. Only one of newWidth and newHeight should be passed to preserve scale
*
* @param {int} width The new width OR an object containing named parameters matching this function sig
* @param {int} height The new height
* @param {int} effectDuration Time in ms for the resize animation, or zero for no animation
* @param {function} callback A function to invoke when the operation finishes
* @return {promise} NOT YET IMPLEMENTED
*/
m.MapData.prototype.resize = function (width, height, duration, callback) {
var p,
promises,
newsize,
els,
highlightId,
ratio,
me = this;
// allow omitting duration
callback = callback || duration;
function sizeCanvas(canvas, w, h) {
if (m.hasCanvas()) {
canvas.width = w;
canvas.height = h;
} else {
$(canvas).width(w);
$(canvas).height(h);
}
}
// Finalize resize action, do callback, pass control to command queue
function cleanupAndNotify() {
me.currentAction = '';
if (u.isFunction(callback)) {
callback();
}
me.processCommandQueue();
}
// handle cleanup after the inner elements are resized
function finishResize() {
sizeCanvas(me.overlay_canvas, width, height);
// restore highlight state if it was highlighted before
if (highlightId >= 0) {
var areaData = me.data[highlightId];
areaData.tempOptions = { fade: false };
me.getDataForKey(areaData.key).highlight();
areaData.tempOptions = null;
}
sizeCanvas(me.base_canvas, width, height);
me.redrawSelections();
cleanupAndNotify();
}
function resizeMapData() {
$(me.image).css(newsize);
// start calculation at the same time as effect
me.scaleInfo = u.getScaleInfo(
{
width: width,
height: height
},
{
width: me.scaleInfo.realWidth,
height: me.scaleInfo.realHeight
}
);
$.each(me.data, function (_, e) {
$.each(e.areas(), function (_, e) {
e.resize();
});
});
}
if (me.scaleInfo.width === width && me.scaleInfo.height === height) {
return;
}
highlightId = me.highlightId;
if (!width) {
ratio = height / me.scaleInfo.realHeight;
width = Math.round(me.scaleInfo.realWidth * ratio);
}
if (!height) {
ratio = width / me.scaleInfo.realWidth;
height = Math.round(me.scaleInfo.realHeight * ratio);
}
newsize = { width: String(width) + 'px', height: String(height) + 'px' };
if (!m.hasCanvas()) {
$(me.base_canvas).children().remove();
}
// resize all the elements that are part of the map except the image itself (which is not visible)
// but including the div wrapper
els = $(me.wrapper).find('.mapster_el');
if (me.options.enableAutoResizeSupport !== true) {
els = els.add(me.wrapper);
}
if (duration) {
promises = [];
me.currentAction = 'resizing';
els.filter(':visible').each(function (_, e) {
p = u.defer();
promises.push(p);
$(e).animate(newsize, {
duration: duration,
complete: p.resolve,
easing: 'linear'
});
});
els.filter(':hidden').css(newsize);
p = u.defer();
promises.push(p);
// though resizeMapData is not async, it needs to be finished just the same as the animations,
// so add it to the "to do" list.
u.when.all(promises).then(finishResize);
resizeMapData();
p.resolve();
} else {
els.css(newsize);
resizeMapData();
finishResize();
}
};
m.MapData.prototype.autoResize = function (duration, callback) {
var me = this;
me.resize($(me.wrapper).width(), null, duration, callback);
};
m.MapData.prototype.configureAutoResize = function () {
var me = this,
ns = me.instanceEventNamespace();
function resizeMap() {
// Evaluate this at runtime to allow for set_options
// to change behavior as set_options intentionally
// does not change any rendering behavior when invoked.
// To improve perf, in next major release this should
// be refactored to add/remove listeners when autoResize
// changes rather than always having listeners attached
// and conditionally resizing
if (me.options.autoResize !== true) {
return;
}
me.autoResize(me.options.autoResizeDuration, me.options.onAutoResize);
}
function debounce() {
if (me.autoResizeTimer) {
clearTimeout(me.autoResizeTimer);
}
me.autoResizeTimer = setTimeout(resizeMap, me.options.autoResizeDelay);
}
$(me.image).on('load' + ns, resizeMap); //Detect late image loads in IE11
$(window).on('focus' + ns, resizeMap);
$(window).on('resize' + ns, debounce);
$(window).on('readystatechange' + ns, resizeMap);
$(window.document).on('fullscreenchange' + ns, resizeMap);
resizeMap();
};
m.MapArea = u.subclass(m.MapArea, function () {
//change the area tag data if needed
this.base.init();
if (this.owner.scaleInfo.scale) {
this.resize();
}
});
p.coords = function (percent, coordOffset) {
var j,
newCoords = [],
pct = percent || this.owner.scaleInfo.scalePct,
offset = coordOffset || 0;
if (pct === 1 && coordOffset === 0) {
return this.originalCoords;
}
for (j = 0; j < this.length; j++) {
//amount = j % 2 === 0 ? xPct : yPct;
newCoords.push(Math.round(this.originalCoords[j] * pct) + offset);
}
return newCoords;
};
p.resize = function () {
this.area.coords = this.coords().join(',');
};
p.reset = function () {
this.area.coords = this.coords(1).join(',');
};
m.impl.resize = function (width, height, duration, callback) {
var x = new m.Method(
this,
function () {
var me = this,
noDimensions = !width && !height,
isAutoResize =
me.options.enableAutoResizeSupport &&
me.options.autoResize &&
noDimensions;
if (isAutoResize) {
me.autoResize(duration, callback);
return;
}
if (noDimensions) {
return false;
}
me.resize(width, height, duration, callback);
},
null,
{
name: 'resize',
args: arguments
}
).go();
return x;
};
/*
m.impl.zoom = function (key, opts) {
var options = opts || {};
function zoom(areaData) {
// this will be MapData object returned by Method
var scroll, corners, height, width, ratio,
diffX, diffY, ratioX, ratioY, offsetX, offsetY, newWidth, newHeight, scrollLeft, scrollTop,
padding = options.padding || 0,
scrollBarSize = areaData ? 20 : 0,
me = this,
zoomOut = false;
if (areaData) {
// save original state on first zoom operation
if (!me.zoomed) {
me.zoomed = true;
me.preZoomWidth = me.scaleInfo.width;
me.preZoomHeight = me.scaleInfo.height;
me.zoomedArea = areaData;
if (options.scroll) {
me.wrapper.css({ overflow: 'auto' });
}
}
corners = $.mapster.utils.areaCorners(areaData.coords(1, 0));
width = me.wrapper.innerWidth() - scrollBarSize - padding * 2;
height = me.wrapper.innerHeight() - scrollBarSize - padding * 2;
diffX = corners.maxX - corners.minX;
diffY = corners.maxY - corners.minY;
ratioX = width / diffX;
ratioY = height / diffY;
ratio = Math.min(ratioX, ratioY);
offsetX = (width - diffX * ratio) / 2;
offsetY = (height - diffY * ratio) / 2;
newWidth = me.scaleInfo.realWidth * ratio;
newHeight = me.scaleInfo.realHeight * ratio;
scrollLeft = (corners.minX) * ratio - padding - offsetX;
scrollTop = (corners.minY) * ratio - padding - offsetY;
} else {
if (!me.zoomed) {
return;
}
zoomOut = true;
newWidth = me.preZoomWidth;
newHeight = me.preZoomHeight;
scrollLeft = null;
scrollTop = null;
}
this.resize({
width: newWidth,
height: newHeight,
duration: options.duration,
scroll: scroll,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
// closure so we can be sure values are correct
callback: (function () {
var isZoomOut = zoomOut,
scroll = options.scroll,
areaD = areaData;
return function () {
if (isZoomOut) {
me.preZoomWidth = null;
me.preZoomHeight = null;
me.zoomed = false;
me.zoomedArea = false;
if (scroll) {
me.wrapper.css({ overflow: 'inherit' });
}
} else {
// just to be sure it wasn't canceled & restarted
me.zoomedArea = areaD;
}
};
} ())
});
}
return (new m.Method(this,
function (opts) {
zoom.call(this);
},
function () {
zoom.call(this.owner, this);
},
{
name: 'zoom',
args: arguments,
first: true,
key: key
}
)).go();
};
*/
})(jQuery);
/*
tooltip.js
Tooltip functionality
Requires areacorners.js
*/
(function ($) {
'use strict';
var m = $.mapster,
u = m.utils;
$.extend(m.defaults, {
toolTipContainer:
'<div style="border: 2px solid black; background: #EEEEEE; width:160px; padding:4px; margin: 4px; -moz-box-shadow: 3px 3px 5px #535353; ' +
'-webkit-box-shadow: 3px 3px 5px #535353; box-shadow: 3px 3px 5px #535353; -moz-border-radius: 6px 6px 6px 6px; -webkit-border-radius: 6px; ' +
'border-radius: 6px 6px 6px 6px; opacity: 0.9;"></div>',
showToolTip: false,
toolTip: null,
toolTipFade: true,
toolTipClose: ['area-mouseout', 'image-mouseout', 'generic-mouseout'],
onShowToolTip: null,
onHideToolTip: null
});
$.extend(m.area_defaults, {
toolTip: null,
toolTipClose: null
});
/**
* Show a tooltip positioned near this area.
*
* @param {string|jquery} html A string of html or a jQuery object containing the tooltip content.
* @param {string|jquery} [template] The html template in which to wrap the content
* @param {string|object} [css] CSS to apply to the outermost element of the tooltip
* @return {jquery} The tooltip that was created
*/
function createToolTip(html, template, css) {
var tooltip;
// wrap the template in a jQuery object, or clone the template if it's already one.
// This assumes that anything other than a string is a jQuery object; if it's not jQuery will
// probably throw an error.
if (template) {
tooltip =
typeof template === 'string' ? $(template) : $(template).clone();
tooltip.append(html);
} else {
tooltip = $(html);
}
// always set display to block, or the positioning css won't work if the end user happened to
// use a non-block type element.
tooltip
.css(
$.extend(css || {}, {
display: 'block',
position: 'absolute'
})
)
.hide();
$('body').append(tooltip);
// we must actually add the tooltip to the DOM and "show" it in order to figure out how much space it
// consumes, and then reposition it with that knowledge.
// We also cache the actual opacity setting to restore finally.
tooltip.attr('data-opacity', tooltip.css('opacity')).css('opacity', 0);
// doesn't really show it because opacity=0
return tooltip.show();
}
/**
* Show a tooltip positioned near this area.
*
* @param {jquery} tooltip The tooltip
* @param {object} [options] options for displaying the tooltip.
* @config {int} [left] The 0-based absolute x position for the tooltip
* @config {int} [top] The 0-based absolute y position for the tooltip
* @config {string|object} [css] CSS to apply to the outermost element of the tooltip
* @config {bool} [fadeDuration] When non-zero, the duration in milliseconds of a fade-in effect for the tooltip.
*/
function showToolTipImpl(tooltip, options) {
var tooltipCss = {
left: options.left + 'px',
top: options.top + 'px'
},
actalOpacity = tooltip.attr('data-opacity') || 0,
zindex = tooltip.css('z-index');
if (parseInt(zindex, 10) === 0 || zindex === 'auto') {
tooltipCss['z-index'] = 9999;
}
tooltip.css(tooltipCss).addClass('mapster_tooltip');
if (options.fadeDuration && options.fadeDuration > 0) {
u.fader(tooltip[0], 0, actalOpacity, options.fadeDuration);
} else {
u.setOpacity(tooltip[0], actalOpacity);
}
}
/**
* Hide and remove active tooltips
*
* @param {MapData} this The mapdata object to which the tooltips belong
*/
m.MapData.prototype.clearToolTip = function () {
if (this.activeToolTip) {
this.activeToolTip.stop().remove();
this.activeToolTip = null;
this.activeToolTipID = null;
u.ifFunction(this.options.onHideToolTip, this);
}
};
/**
* Configure the binding between a named tooltip closing option, and a mouse event.
*
* If a callback is passed, it will be called when the activating event occurs, and the tooltip will
* only closed if it returns true.
*
* @param {MapData} [this] The MapData object to which this tooltip belongs.
* @param {String} option The name of the tooltip closing option
* @param {String} event UI event to bind to this option
* @param {Element} target The DOM element that is the target of the event
* @param {Function} [beforeClose] Callback when the tooltip is closed
* @param {Function} [onClose] Callback when the tooltip is closed
*/
function bindToolTipClose(
options,
bindOption,
event,
target,
beforeClose,
onClose
) {
var tooltip_ns = '.mapster.tooltip',
event_name = event + tooltip_ns;
if ($.inArray(bindOption, options) >= 0) {
target.off(event_name).on(event_name, function (e) {
if (!beforeClose || beforeClose.call(this, e)) {
target.off(tooltip_ns);
if (onClose) {
onClose.call(this);
}
}
});
return {
object: target,
event: event_name
};
}
}
/**
* Show a tooltip.
*
* @param {string|jquery} [tooltip] A string of html or a jQuery object containing the tooltip content.
*
* @param {string|jquery} [target] The target of the tooltip, to be used to determine positioning. If null,
* absolute position values must be passed with left and top.
*
* @param {string|jquery} [image] If target is an [area] the image that owns it
*
* @param {string|jquery} [container] An element within which the tooltip must be bounded
*
* @param {object|string|jQuery} [options] options to apply when creating this tooltip
* @config {int} [offsetx] the horizontal amount to offset the tooltip
* @config {int} [offsety] the vertical amount to offset the tooltip
* @config {string|object} [css] CSS to apply to the outermost element of the tooltip
* @config {bool} [fadeDuration] When non-zero, the duration in milliseconds of a fade-in effect for the tooltip.
* @config {int} [left] The 0-based absolute x position for the tooltip (only used if target is not specified)
* @config {int} [top] The 0-based absolute y position for the tooltip (only used if target it not specified)
*/
function showToolTip(tooltip, target, image, container, options) {
var corners,
ttopts = {};
options = options || {};
if (target) {
corners = u.areaCorners(
target,
image,
container,
tooltip.outerWidth(true),
tooltip.outerHeight(true)
);
// Try to upper-left align it first, if that doesn't work, change the parameters
ttopts.left = corners[0];
ttopts.top = corners[1];
} else {
ttopts.left = options.left;
ttopts.top = options.top;
}
ttopts.left += options.offsetx || 0;
ttopts.top += options.offsety || 0;
ttopts.css = options.css;
ttopts.fadeDuration = options.fadeDuration;
showToolTipImpl(tooltip, ttopts);
return tooltip;
}
/**
* Show a tooltip positioned near this area.
*
* @param {string|jquery|function} [content] A string of html, jQuery object or function that returns same containing the tooltip content.
* @param {object} [options] options to apply when creating this tooltip
* @config {string|jquery} [container] An element within which the tooltip must be bounded
* @config {bool} [template] a template to use instead of the default. If this property exists and is null,
* then no template will be used.
* @config {string} [closeEvents] A string with one or more comma-separated values that determine when the tooltip
* closes: 'area-click','tooltip-click','image-mouseout','image-click' are valid values
* then no template will be used.
* @config {int} [offsetx] the horizontal amount to offset the tooltip
* @config {int} [offsety] the vertical amount to offset the tooltip
* @config {string|object} [css] CSS to apply to the outermost element of the tooltip
* @config {bool} [fadeDuration] When non-zero, the duration in milliseconds of a fade-in effect for the tooltip.
*/
m.AreaData.prototype.showToolTip = function (content, options) {
var tooltip,
closeOpts,
target,
tipClosed,
template,
ttopts = {},
ad = this,
md = ad.owner,
areaOpts = ad.effectiveOptions();
// copy the options object so we can update it
options = options ? $.extend({}, options) : {};
content = content || areaOpts.toolTip;
closeOpts =
options.closeEvents ||
areaOpts.toolTipClose ||
md.options.toolTipClose ||
'tooltip-click';
template =
typeof options.template !== 'undefined'
? options.template
: md.options.toolTipContainer;
options.closeEvents =
typeof closeOpts === 'string'
? (closeOpts = u.split(closeOpts))
: closeOpts;
options.fadeDuration =
options.fadeDuration ||
(md.options.toolTipFade
? md.options.fadeDuration || areaOpts.fadeDuration
: 0);
target = ad.area
? ad.area
: $.map(ad.areas(), function (e) {
return e.area;
});
if (md.activeToolTipID === ad.areaId) {
return;
}
md.clearToolTip();
var effectiveContent = u.isFunction(content)
? content({ key: this.key, target: target })
: content;
if (!effectiveContent) {
return;
}
md.activeToolTip = tooltip = createToolTip(
effectiveContent,
template,
options.css
);
md.activeToolTipID = ad.areaId;
tipClosed = function () {
md.clearToolTip();
};
bindToolTipClose(
closeOpts,
'area-click',
'click',
$(md.map),
null,
tipClosed
);
bindToolTipClose(
closeOpts,
'tooltip-click',
'click',
tooltip,
null,
tipClosed
);
bindToolTipClose(
closeOpts,
'image-mouseout',
'mouseout',
$(md.image),
function (e) {
return (
e.relatedTarget &&
e.relatedTarget.nodeName !== 'AREA' &&
e.relatedTarget !== ad.area
);
},
tipClosed
);
bindToolTipClose(
closeOpts,
'image-click',
'click',
$(md.image),
null,
tipClosed
);
showToolTip(tooltip, target, md.image, options.container, options);
u.ifFunction(md.options.onShowToolTip, ad.area, {
toolTip: tooltip,
options: ttopts,
areaOptions: areaOpts,
key: ad.key,
selected: ad.isSelected()
});
return tooltip;
};
/**
* Parse an object that could be a string, a jquery object, or an object with a "contents" property
* containing html or a jQuery object.
*
* @param {object|string|jQuery} options The parameter to parse
* @return {string|jquery} A string or jquery object
*/
function getHtmlFromOptions(options) {
// see if any html was passed as either the options object itself, or the content property
return options
? typeof options === 'string' || options.jquery || u.isFunction(options)
? options
: options.content
: null;
}
function getOptionsFromOptions(options) {
return options
? typeof options == 'string' || options.jquery || u.isFunction(options)
? { content: options }
: options
: {};
}
/**
* Activate or remove a tooltip for an area. When this method is called on an area, the
* key parameter doesn't apply and "options" is the first parameter.
*
* When called with no parameters, or "key" is a falsy value, any active tooltip is cleared.
*
* When only a key is provided, the default tooltip for the area is used.
*
* When html is provided, this is used instead of the default tooltip.
*
* When "noTemplate" is true, the default tooltip template will not be used either, meaning only
* the actual html passed will be used.
*
* @param {string|AreaElement|HTMLElement} key The area key or element for which to activate a tooltip, or a DOM element/selector.
*
* @param {object|string|jquery} [options] options to apply when creating this tooltip - OR -
* The markup, or a jquery object, containing the data for the tooltip
* @config {string|jQuery|function} [content] the inner content of the tooltip; the tooltip text, HTML or function that returns same
* @config {Element|jQuery} [container] the inner content of the tooltip; the tooltip text or HTML
* @config {bool} [template] a template to use instead of the default. If this property exists and is null,
* then no template will be used.
* @config {string} [closeEvents] A string with one or more comma-separated values that determine when the tooltip
* closes: 'area-click','tooltip-click','image-mouseout','image-click','generic-click','generic-mouseout' are valid values
* @config {int} [offsetx] the horizontal amount to offset the tooltip.
* @config {int} [offsety] the vertical amount to offset the tooltip.
* @config {string|object} [css] CSS to apply to the outermost element of the tooltip
* @config {bool} [fadeDuration] When non-zero, the duration in milliseconds of a fade-in effect for the tooltip.
* @return {jQuery} The jQuery object
*/
m.impl.tooltip = function (key, options) {
return new m.Method(
this,
function mapData() {
var tooltip,
target,
defaultTarget,
closeOpts,
tipClosed,
md = this;
if (!key) {
md.clearToolTip();
} else {
target = $(key);
defaultTarget = target && target.length > 0 ? target[0] : null;
if (md.activeToolTipID === defaultTarget) {
return;
}
md.clearToolTip();
if (!defaultTarget) {
return;
}
var content = getHtmlFromOptions(options),
effectiveContent = u.isFunction(content)
? content({ key: this.key, target: target })
: content;
if (!effectiveContent) {
return;
}
options = getOptionsFromOptions(options);
closeOpts =
options.closeEvents || md.options.toolTipClose || 'tooltip-click';
options.closeEvents =
typeof closeOpts === 'string'
? (closeOpts = u.split(closeOpts))
: closeOpts;
options.fadeDuration =
options.fadeDuration ||
(md.options.toolTipFade ? md.options.fadeDuration : 0);
tipClosed = function () {
md.clearToolTip();
};
md.activeToolTip = tooltip = createToolTip(
effectiveContent,
options.template || md.options.toolTipContainer,
options.css
);
md.activeToolTipID = defaultTarget;
bindToolTipClose(
closeOpts,
'tooltip-click',
'click',
tooltip,
null,
tipClosed
);
bindToolTipClose(
closeOpts,
'generic-mouseout',
'mouseout',
target,
null,
tipClosed
);
bindToolTipClose(
closeOpts,
'generic-click',
'click',
target,
null,
tipClosed
);
md.activeToolTip = tooltip = showToolTip(
tooltip,
target,
md.image,
options.container,
options
);
}
},
function areaData() {
if ($.isPlainObject(key) && !options) {
options = key;
}
this.showToolTip(
getHtmlFromOptions(options),
getOptionsFromOptions(options)
);
},
{
name: 'tooltip',
args: arguments,
key: key
}
).go();
};
})(jQuery);
})); | {
"content_hash": "2d1da5a057badf465f7604fd7067a364",
"timestamp": "",
"source": "github",
"line_count": 4628,
"max_line_length": 164,
"avg_line_length": 28.98076923076923,
"alnum_prop": 0.5448879014039352,
"repo_name": "cdnjs/cdnjs",
"id": "cdd493a335395f468942ad5d10d7be073bc56370",
"size": "134268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/imagemapster/1.5.4/jquery.imagemapster.zepto.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.WindowsApplication1.Form1
End Sub
End Class
End Namespace
| {
"content_hash": "e5aea489dd3154ba5ccf845619a41029",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 112,
"avg_line_length": 38.44736842105263,
"alnum_prop": 0.6262833675564682,
"repo_name": "umyuu/Sample",
"id": "bcdfdfd812320a48dd50cee247ccc1305b78510b",
"size": "1463",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/VB.NET/Q103121/WindowsApplication1/WindowsApplication1/My Project/Application.Designer.vb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2427"
},
{
"name": "CSS",
"bytes": "60"
},
{
"name": "HTML",
"bytes": "14520"
},
{
"name": "Java",
"bytes": "54389"
},
{
"name": "JavaScript",
"bytes": "9836"
},
{
"name": "Python",
"bytes": "134026"
},
{
"name": "Visual Basic",
"bytes": "2043"
}
],
"symlink_target": ""
} |
package org.apache.pdfbox.examples.pdmodel;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* This is an example on how to get a documents metadata information.
*
* Usage: java org.apache.pdfbox.examples.pdmodel.PrintDocumentMetaData <input-pdf>
*
* @author Ben Litchfield
*
*/
public class PrintDocumentMetaData
{
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws Exception If there is an error parsing the document.
*/
public static void main( String[] args ) throws Exception
{
if( args.length != 1 )
{
usage();
}
else
{
PDDocument document = null;
try
{
document = PDDocument.load( new File(args[0]));
PrintDocumentMetaData meta = new PrintDocumentMetaData();
meta.printMetadata( document );
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java org.apache.pdfbox.examples.pdmodel.PrintDocumentMetaData <input-pdf>" );
}
/**
* This will print the documents data to System.out.
*
* @param document The document to get the metadata from.
*
* @throws IOException If there is an error getting the page count.
*/
public void printMetadata( PDDocument document ) throws IOException
{
PDDocumentInformation info = document.getDocumentInformation();
PDDocumentCatalog cat = document.getDocumentCatalog();
PDMetadata metadata = cat.getMetadata();
System.out.println( "Page Count=" + document.getNumberOfPages() );
System.out.println( "Title=" + info.getTitle() );
System.out.println( "Author=" + info.getAuthor() );
System.out.println( "Subject=" + info.getSubject() );
System.out.println( "Keywords=" + info.getKeywords() );
System.out.println( "Creator=" + info.getCreator() );
System.out.println( "Producer=" + info.getProducer() );
System.out.println( "Creation Date=" + formatDate( info.getCreationDate() ) );
System.out.println( "Modification Date=" + formatDate( info.getModificationDate() ) );
System.out.println( "Trapped=" + info.getTrapped() );
if( metadata != null )
{
String string = new String( metadata.toByteArray(), "ISO-8859-1" );
System.out.println( "Metadata=" + string );
}
}
/**
* This will format a date object.
*
* @param date The date to format.
*
* @return A string representation of the date.
*/
private String formatDate( Calendar date )
{
String retval = null;
if( date != null )
{
SimpleDateFormat formatter = new SimpleDateFormat();
retval = formatter.format( date.getTime() );
}
return retval;
}
}
| {
"content_hash": "e9674cbed5a1699ee28847622427eef6",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 113,
"avg_line_length": 31.00900900900901,
"alnum_prop": 0.5950029052876235,
"repo_name": "ChunghwaTelecom/pdfbox",
"id": "284c6bfb4f386231ee41b6734fa7316694ad8950",
"size": "4244",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintDocumentMetaData.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "67828"
},
{
"name": "Java",
"bytes": "6420645"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="page-heading">{% block heading %}{% endblock %}</h1>
{% block config-content %}
{% endblock %}
</div>
</div>
{% endblock %}
| {
"content_hash": "947040b427b87bc158394625e5f4f7ce",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 67,
"avg_line_length": 23.545454545454547,
"alnum_prop": 0.555984555984556,
"repo_name": "Kvoti/ditto",
"id": "90d9094bcccd9582f3b9b69c933020ad1ef496fc",
"size": "259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ditto/templates/configuration/walkthrough/base.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "315024"
},
{
"name": "HTML",
"bytes": "1012831"
},
{
"name": "JavaScript",
"bytes": "539187"
},
{
"name": "Python",
"bytes": "200035"
},
{
"name": "Ruby",
"bytes": "1183"
},
{
"name": "Shell",
"bytes": "895"
}
],
"symlink_target": ""
} |
.class public Lcom/nvidia/NvCamera;
.super Landroid/hardware/Camera;
.source "NvCamera.java"
# annotations
.annotation system Ldalvik/annotation/MemberClasses;
value = {
Lcom/nvidia/NvCamera$NvParameters;,
Lcom/nvidia/NvCamera$NvVideoPreviewFps;,
Lcom/nvidia/NvCamera$NvWindow;,
Lcom/nvidia/NvCamera$NvCameraInfo;
}
.end annotation
# static fields
.field private static final TAG:Ljava/lang/String; = "NvCamera"
# direct methods
.method constructor <init>(I)V
.locals 0
.parameter "cameraId"
.prologue
.line 1778
invoke-direct {p0, p1}, Landroid/hardware/Camera;-><init>(I)V
.line 1779
return-void
.end method
.method public static native getNvCameraInfo(ILcom/nvidia/NvCamera$NvCameraInfo;)V
.end method
.method private final native native_getCustomParameters()Ljava/lang/String;
.end method
.method private final native native_setCustomParameters(Ljava/lang/String;)V
.end method
.method public static open()Lcom/nvidia/NvCamera;
.locals 4
.prologue
.line 1766
invoke-static {}, Lcom/nvidia/NvCamera;->getNumberOfCameras()I
move-result v2
.line 1767
.local v2, numberOfCameras:I
new-instance v0, Lcom/nvidia/NvCamera$NvCameraInfo;
invoke-direct {v0}, Lcom/nvidia/NvCamera$NvCameraInfo;-><init>()V
.line 1768
.local v0, cameraInfo:Lcom/nvidia/NvCamera$NvCameraInfo;
const/4 v1, 0x0
.local v1, i:I
:goto_0
if-ge v1, v2, :cond_1
.line 1769
invoke-static {v1, v0}, Lcom/nvidia/NvCamera;->getCameraInfo(ILandroid/hardware/Camera$CameraInfo;)V
.line 1770
iget v3, v0, Landroid/hardware/Camera$CameraInfo;->facing:I
if-nez v3, :cond_0
.line 1771
new-instance v3, Lcom/nvidia/NvCamera;
invoke-direct {v3, v1}, Lcom/nvidia/NvCamera;-><init>(I)V
.line 1774
:goto_1
return-object v3
.line 1768
:cond_0
add-int/lit8 v1, v1, 0x1
goto :goto_0
.line 1774
:cond_1
const/4 v3, 0x0
goto :goto_1
.end method
.method public static open(I)Lcom/nvidia/NvCamera;
.locals 1
.parameter "cameraId"
.prologue
.line 1757
new-instance v0, Lcom/nvidia/NvCamera;
invoke-direct {v0, p0}, Lcom/nvidia/NvCamera;-><init>(I)V
return-object v0
.end method
# virtual methods
.method public bridge synthetic getParameters()Landroid/hardware/Camera$Parameters;
.locals 1
.prologue
.line 76
invoke-virtual {p0}, Lcom/nvidia/NvCamera;->getParameters()Lcom/nvidia/NvCamera$NvParameters;
move-result-object v0
return-object v0
.end method
.method public getParameters()Lcom/nvidia/NvCamera$NvParameters;
.locals 5
.prologue
.line 269
new-instance v0, Lcom/nvidia/NvCamera$NvParameters;
invoke-direct {v0, p0}, Lcom/nvidia/NvCamera$NvParameters;-><init>(Lcom/nvidia/NvCamera;)V
.line 270
.local v0, p:Lcom/nvidia/NvCamera$NvParameters;
const/4 v2, 0x0
.line 271
.local v2, s:Ljava/lang/String;
const-string/jumbo v3, "mv1920"
const-string/jumbo v4, "nvidia"
invoke-virtual {v3, v4}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z
move-result v3
if-eqz v3, :cond_0
.line 272
invoke-direct {p0}, Lcom/nvidia/NvCamera;->native_getCustomParameters()Ljava/lang/String;
move-result-object v2
.line 277
:goto_0
invoke-virtual {v0, v2}, Landroid/hardware/Camera$Parameters;->unflatten(Ljava/lang/String;)V
.line 278
return-object v0
.line 274
:cond_0
invoke-super {p0}, Landroid/hardware/Camera;->getParameters()Landroid/hardware/Camera$Parameters;
move-result-object v1
.line 275
.local v1, param:Landroid/hardware/Camera$Parameters;
invoke-virtual {v1}, Landroid/hardware/Camera$Parameters;->flatten()Ljava/lang/String;
move-result-object v2
goto :goto_0
.end method
.method public newNvWindow()Lcom/nvidia/NvCamera$NvWindow;
.locals 1
.prologue
.line 162
new-instance v0, Lcom/nvidia/NvCamera$NvWindow;
invoke-direct {v0}, Lcom/nvidia/NvCamera$NvWindow;-><init>()V
return-object v0
.end method
.method public setParameters(Lcom/nvidia/NvCamera$NvParameters;)V
.locals 4
.parameter "params"
.prologue
.line 258
const-string/jumbo v2, "mv1920"
const-string/jumbo v3, "nvidia"
invoke-virtual {v2, v3}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z
move-result v2
if-eqz v2, :cond_0
.line 259
invoke-virtual {p1}, Landroid/hardware/Camera$Parameters;->flatten()Ljava/lang/String;
move-result-object v2
invoke-direct {p0, v2}, Lcom/nvidia/NvCamera;->native_setCustomParameters(Ljava/lang/String;)V
.line 266
:goto_0
return-void
.line 261
:cond_0
invoke-virtual {p1}, Landroid/hardware/Camera$Parameters;->flatten()Ljava/lang/String;
move-result-object v1
.line 262
.local v1, s:Ljava/lang/String;
invoke-super {p0}, Landroid/hardware/Camera;->getParameters()Landroid/hardware/Camera$Parameters;
move-result-object v0
.line 263
.local v0, p:Landroid/hardware/Camera$Parameters;
invoke-virtual {v0, v1}, Landroid/hardware/Camera$Parameters;->unflatten(Ljava/lang/String;)V
.line 264
invoke-super {p0, v0}, Landroid/hardware/Camera;->setParameters(Landroid/hardware/Camera$Parameters;)V
goto :goto_0
.end method
| {
"content_hash": "5c00b22e0a1fd244727a0028942e068b",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 106,
"avg_line_length": 22.95299145299145,
"alnum_prop": 0.6907466021225098,
"repo_name": "baidurom/devices-Coolpad8720L",
"id": "73145ccaf3c8aa2223906f8c6d00d9f65fdec625",
"size": "5371",
"binary": false,
"copies": "2",
"ref": "refs/heads/coron-4.3",
"path": "framework.jar.out/smali/com/nvidia/NvCamera.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "13619"
},
{
"name": "Shell",
"bytes": "1917"
}
],
"symlink_target": ""
} |
package net.jeremycasey.hamiltonheatalert.heatstatus;
import net.jeremycasey.hamiltonheatalert.datetime.TimeProvider;
import org.joda.time.DateTime;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ServerHeatStatusIsImportantCheckerTest {
@Test
public void testShouldNotifyIfImportanceChange() {
HeatStatus lastHeatStatus = newHeatStatus(1, newDateTime(1, 12));
assertTrue(new ServerHeatStatusIsImportantChecker(2, newTimeProvider(1, 13))
.shouldNotify(lastHeatStatus, lastHeatStatus));
}
@Test
public void testShouldNotifyIfLongerThanADay() {
HeatStatus lastHeatStatus = newHeatStatus(2, newDateTime(2, 12));
HeatStatus lastNotifiedHeatStatus = newHeatStatus(2, newDateTime(1, 12));
assertTrue(new ServerHeatStatusIsImportantChecker(2, newTimeProvider(2, 13))
.shouldNotify(lastHeatStatus, lastNotifiedHeatStatus));
}
@Test
public void testShouldNotifyIfFirstImportantStatus() {
assertTrue(new ServerHeatStatusIsImportantChecker(1, newTimeProvider(1, 0))
.shouldNotify(null, null));
}
@Test
public void testShouldNotNotifyIfNotSerious() {
assertFalse(new ServerHeatStatusIsImportantChecker(0, newTimeProvider(1, 0))
.shouldNotify(null, null));
}
@Test
public void testShouldNotNotifyIfSameStatusAsTheHeatStatusJustRecentlyFetched() {
HeatStatus lastHeatStatus = newHeatStatus(1, newDateTime(1, 15));
assertFalse(new ServerHeatStatusIsImportantChecker(1, newTimeProvider(1, 16))
.shouldNotify(lastHeatStatus, lastHeatStatus));
}
@Test
public void testShouldPrioritizeMorningAlerts() {
HeatStatus lastHeatStatus = newHeatStatus(1, newDateTime(2, 5));
HeatStatus lastNotifiedHeatStatus = newHeatStatus(1, newDateTime(1, 10));
assertTrue(new ServerHeatStatusIsImportantChecker(1, newTimeProvider(2, 6))
.shouldNotify(lastHeatStatus, lastNotifiedHeatStatus));
}
@Test
public void testDoNotPrioritizeMorningAlertsIfNotificationWasRecent() {
HeatStatus lastHeatStatus = newHeatStatus(1, newDateTime(2, 5));
HeatStatus lastNotifiedHeatStatus = newHeatStatus(1, newDateTime(2, 2));
assertFalse(new ServerHeatStatusIsImportantChecker(1, newTimeProvider(2, 6))
.shouldNotify(lastHeatStatus, lastNotifiedHeatStatus));
}
private HeatStatus newHeatStatus(int stage, DateTime dateTime) {
HeatStatus lastNotifiedHeatStatus = new HeatStatus();
lastNotifiedHeatStatus.setStage(stage);
lastNotifiedHeatStatus.setFetchDate(dateTime.getMillis());
return lastNotifiedHeatStatus;
}
private DateTime newDateTime(int day, int hour) {
return new DateTime(2015, 4, day, hour, 0);
}
private TimeProvider newTimeProvider(final int day, final int hour) {
return new TimeProvider() {
@Override
public DateTime now() {
return new DateTime(2015, 4, day, hour, 0);
}
};
}
}
| {
"content_hash": "0cdaef643d4b3f383028196dc719d000",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 85,
"avg_line_length": 39.20987654320987,
"alnum_prop": 0.7030856423173804,
"repo_name": "jeremy8883/hamilton-heat-alert",
"id": "eec305426a2878900213d6c094ba257b56e1506b",
"size": "3176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/test/java/net/jeremycasey/hamiltonheatalert/heatstatus/ServerHeatStatusIsImportantCheckerTest.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "78389"
}
],
"symlink_target": ""
} |
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-change-detection-page',
templateUrl: './change-detection-page.component.html',
styleUrls: ['./change-detection-page.component.css']
})
export class ChangeDetectionPageComponent {
selectedIndex: number = 0;
}
| {
"content_hash": "3fd3aa88a14977a6d0f38a57fc7d374a",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 56,
"avg_line_length": 27,
"alnum_prop": 0.7306397306397306,
"repo_name": "awerlang/angular-show-off",
"id": "abf601ab1f668e25e0e540d7d5a972633b1fd294",
"size": "297",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/change-detection-page/change-detection-page.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "880"
},
{
"name": "HTML",
"bytes": "2235"
},
{
"name": "JavaScript",
"bytes": "1884"
},
{
"name": "TypeScript",
"bytes": "13678"
}
],
"symlink_target": ""
} |
stanza.ml package
=================
stanza.ml.tensorflow_utils module
---------------------------------
.. automodule:: stanza.ml.tensorflow_utils
:members:
:special-members:
:show-inheritance:
| {
"content_hash": "e2790518a31b24cedf410ddd65edccc3",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 42,
"avg_line_length": 20.8,
"alnum_prop": 0.5432692307692307,
"repo_name": "arunchaganty/presidential-debates",
"id": "7dde105257882926bb74c16dec2d2543ad7a385c",
"size": "208",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "third-party/stanza/docs/stanza.ml.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4165"
},
{
"name": "Java",
"bytes": "807"
},
{
"name": "JavaScript",
"bytes": "10159"
},
{
"name": "Python",
"bytes": "42221"
},
{
"name": "Shell",
"bytes": "6367"
}
],
"symlink_target": ""
} |
package it.wsie.twitteranalyzer.model.tasks.classification.sentiment;
/**
* @author Simone Papandrea
*
*/
public enum Sentiment {
SUPPORTER, OPPONENT, NEUTRAL;
} | {
"content_hash": "019a6dbd7ef6c7b8b56ffcb1281a47ef",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 69,
"avg_line_length": 16.7,
"alnum_prop": 0.7485029940119761,
"repo_name": "SIMON3P/TwitterAnalyzer",
"id": "c8899693a5a9b313c1b81db1b4ae8004cb7f9288",
"size": "167",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/it/wsie/twitteranalyzer/model/tasks/classification/sentiment/Sentiment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "162520"
},
{
"name": "Makefile",
"bytes": "18747"
}
],
"symlink_target": ""
} |
'use strict';
const expect = require('chai').expect;
const sinon = require('sinon');
const proxyquire = require('proxyquire');
require('chai').use(require('sinon-chai'));
describe('getPlaylists', () => {
let system;
let resultMock;
let success;
const getPlaylists = require('../../../../lib/prototypes/SonosSystem/getPlaylists.js');
describe('When calling getPlaylists', () => {
let player;
before(() => {
resultMock = {
items: [],
startIndex: 0,
numberReturned: 0,
totalMatches: 0
};
player = {
browseAll: sinon.stub().resolves(resultMock.items)
};
system = {
getAnyPlayer: sinon.stub().returns(player)
};
success = sinon.spy();
return getPlaylists.call(system)
.then(success);
});
it('Has called browseAll', () => {
expect(player.browseAll).calledOnce;
expect(player.browseAll.firstCall.args).eql(['SQ:']);
});
it('Returns the expected result', () => {
expect(success.firstCall.args[0]).eql(resultMock.items);
});
});
});
| {
"content_hash": "7f6b4e97663e9773ce6de81da1cd4dd0",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 89,
"avg_line_length": 21.96,
"alnum_prop": 0.5801457194899818,
"repo_name": "jishi/node-sonos-discovery",
"id": "9d551e912b14c044ed5b15651bc3ec79b1aa71ca",
"size": "1098",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/unit/prototypes/SonosSystem/getPlaylists.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "130091"
}
],
"symlink_target": ""
} |
'use strict';
const nock = require('nock');
const expect = require('expect');
const fastly = require('fastly-promises');
const domains = require('../src/domains');
const services = require('./response/services.response');
const response = require('./response/domains.response');
describe('domains.js', () => {
describe('Valid function invocation', () => {
const fastlyInstance = fastly('923b6bd5266a7f932e41962755bd4254', null);
let res;
nock('https://api.fastly.com')
.get('/service/20Esr3c2mP2IO4661htKVo/version/2/domain')
.reply(200, response.domainList.body);
before(async () => {
res = await domains(fastlyInstance, services.serviceList.body);
});
it('return value should exist', () => {
expect(res).toExist();
});
it('return value should be an object', () => {
expect(res).toBeA('object');
});
it('return value should have domains, number_of_domains, and number_of_services properties', () => {
expect(res).toIncludeKeys(['domains', 'number_of_domains', 'number_of_services']);
});
});
describe('Invalid function invocation - no or invalid token', () => {
const fastlyInstance = fastly(null, null);
let error;
nock('https://api.fastly.com')
.get('/service/20Esr3c2mP2IO4661htKVo/version/2/domain')
.reply(401);
before(async () => {
try {
await domains(fastlyInstance, services.serviceList.body);
} catch (e) {
error = response.domainList.error[401];
}
});
it('return value should exist', () => {
expect(error).toExist();
});
it('return value should be an string', () => {
expect(error).toBeA('string');
});
it('return value should be the error message for status 401', () => {
expect(error).toBe(response.domainList.error[401]);
});
});
describe('Invalid function invocation - invalid service_id', () => {
const fastlyInstance = fastly('923b6bd5266a7f932e41962755bd4254', null);
let error;
nock('https://api.fastly.com')
.get('/service/invalid_service_id/version/2/domain')
.reply(404);
before(async () => {
try {
await domains(fastlyInstance, [{
version: 2,
id: 'invalid_service_id'
}]);
} catch (e) {
error = response.domainList.error[404];
}
});
it('return value should exist', () => {
expect(error).toExist();
});
it('return value should be an string', () => {
expect(error).toBeA('string');
});
it('return value should be the error message for status 404', () => {
expect(error).toBe(response.domainList.error[404]);
});
});
});
| {
"content_hash": "7744cb1e6855d4c0ef0c26aa9af2f653",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 104,
"avg_line_length": 28.291666666666668,
"alnum_prop": 0.5957290132547864,
"repo_name": "philippschulte/fastly-domains",
"id": "7ed748ec1abb32c8a8b9c7b0e0f697d7ced1b619",
"size": "2716",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/domains.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "11295"
}
],
"symlink_target": ""
} |
// -------------------------------------------------------------------------- \\
// File: Tap.js \\
// Module: Touch \\
// Requires: Gesture.js \\
// Author: Neil Jenkins \\
// License: © 2010-2015 FastMail Pty Ltd. MIT Licensed. \\
// -------------------------------------------------------------------------- \\
"use strict";
( function ( NS ) {
/* We can't just call preventDefault on touch(start|move), as this would
prevent scrolling and also prevent links we want to act as normal from
working. So we use this hack instead to capture the subsequent click and
remove it from the app's existence.
*/
var MouseEventRemover = NS.Class({
init: function ( target, defaultPrevented ) {
this.target = target;
this.stop = defaultPrevented;
this.time = Date.now();
NS.ViewEventsController.addEventTarget( this, 40 );
},
fire: function ( type, event ) {
var isClick = ( type === 'click' ) && !event.originalType,
isMouse = isClick || /^mouse/.test( type );
if ( type === 'touchstart' || Date.now() - this.time > 1000 ) {
NS.ViewEventsController.removeEventTarget( this );
isMouse = false;
}
if ( isMouse && ( this.stop || event.target !== this.target ) ) {
event.preventDefault();
}
event.propagationStopped = isMouse;
}
});
var TapEvent = NS.Class({
Extends: NS.Event,
originalType: 'tap'
});
var TrackedTouch = function ( x, y, time, target ) {
this.x = x;
this.y = y;
this.time = time;
var activeEls = this.activeEls = [];
do {
if ( /^(?:A|BUTTON|INPUT|LABEL)$/.test( target.nodeName ) ) {
activeEls.push( target );
NS.Element.addClass( target, 'tap-active' );
}
} while ( target = target.parentNode );
};
TrackedTouch.prototype.done = function () {
var activeEls = this.activeEls,
i, l;
for ( i = 0, l = activeEls.length; i < l; i += 1 ) {
NS.Element.removeClass( activeEls[i], 'tap-active' );
}
};
/* A tap is defined as a touch which:
* Lasts less than 200ms.
* Moves less than 5px from the initial touch point.
There may be other touches occurring at the same time (e.g. you could be
holding one button and tap another; the tap gesture will still be
recognised).
*/
NS.Tap = new NS.Gesture({
_tracking: {},
cancel: function () {
var tracking = this._tracking,
id;
for ( id in tracking ) {
tracking[ id ].done();
}
this._tracking = {};
},
start: function ( event ) {
var touches = event.changedTouches,
tracking = this._tracking,
now = Date.now(),
i, l, touch, id;
for ( i = 0, l = touches.length; i < l; i += 1 ) {
touch = touches[i];
id = touch.identifier;
if ( !tracking[ id ] ) {
tracking[ id ] = new TrackedTouch(
touch.screenX, touch.screenY, now, touch.target );
}
}
},
move: function ( event ) {
var touches = event.changedTouches,
tracking = this._tracking,
i, l, touch, id, trackedTouch, deltaX, deltaY;
for ( i = 0, l = touches.length; i < l; i += 1 ) {
touch = touches[i];
id = touch.identifier;
trackedTouch = tracking[ id ];
if ( trackedTouch ) {
deltaX = touch.screenX - trackedTouch.x;
deltaY = touch.screenY - trackedTouch.y;
if ( deltaX * deltaX + deltaY * deltaY > 25 ) {
trackedTouch.done();
delete tracking[ id ];
}
}
}
},
end: function ( event ) {
var touches = event.changedTouches,
tracking = this._tracking,
now = Date.now(),
i, l, touch, id, trackedTouch, target, tapEvent, clickEvent,
nodeName,
ViewEventsController = NS.ViewEventsController;
for ( i = 0, l = touches.length; i < l; i += 1 ) {
touch = touches[i];
id = touch.identifier;
trackedTouch = tracking[ id ];
if ( trackedTouch ) {
if ( now - trackedTouch.time < 200 ) {
target = touch.target;
tapEvent = new TapEvent( 'tap', target );
ViewEventsController.handleEvent( tapEvent );
clickEvent = new TapEvent( 'click', target );
clickEvent.defaultPrevented = tapEvent.defaultPrevented;
ViewEventsController.handleEvent( clickEvent );
// The tap could trigger a UI change. When the click event
// is fired 300ms later, if there is now an input under the
// area the touch took place, in iOS the keyboard will
// appear, even though the preventDefault on the click event
// stops it actually being focussed. Calling preventDefault
// on the touchend event stops this happening, however we
// must not do this if the user actually taps an input!
nodeName = target.nodeName;
if ( nodeName !== 'INPUT' && nodeName !== 'TEXTAREA' &&
nodeName !== 'SELECT' ) {
event.preventDefault();
}
new MouseEventRemover( target, clickEvent.defaultPrevented );
}
trackedTouch.done();
delete tracking[ id ];
}
}
}
});
}( O ) );
| {
"content_hash": "8637cccb852f4a4b3f0d91132f503b0c",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 81,
"avg_line_length": 36.74233128834356,
"alnum_prop": 0.4857238270161964,
"repo_name": "adityab/overture",
"id": "316c93ff9a4ef9be1e28bccada071c9725e3c2e3",
"size": "5990",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/Overture/touch/Tap.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1001054"
},
{
"name": "Makefile",
"bytes": "578"
}
],
"symlink_target": ""
} |
package org.sakaiproject.nakamura.session;
import static org.easymock.EasyMock.and;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reset;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertEquals;
import org.easymock.Capture;
import org.junit.Test;
import org.sakaiproject.nakamura.api.memory.Cache;
import org.sakaiproject.nakamura.api.memory.CacheManagerService;
import org.sakaiproject.nakamura.api.memory.CacheScope;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class TestSessionManagement {
@Test
@SuppressWarnings("unchecked")
public void testSessionCachingHandlesNull() {
CacheManagerService cacheService = createMock(CacheManagerService.class);
Cache<Object> cache = createMock(Cache.class);
SessionManagerServiceImpl service = new SessionManagerServiceImpl();
service.bindCacheManagerService(cacheService);
Capture<String> requestKey = new Capture<String>();
Capture<String> requestCache = new Capture<String>();
expect(
cacheService
.getCache(and(isA(String.class), capture(requestCache)), eq(CacheScope.REQUEST)))
.andReturn(cache);
expect(cache.get(and(isA(String.class), capture(requestKey)))).andReturn(null);
replay(cache, cacheService);
assertNull("Expected request to be null", service.getCurrentRequest());
verify(cache, cacheService);
reset(cache, cacheService);
expect(cacheService.getCache(eq(requestCache.getValue()), eq(CacheScope.REQUEST))).andReturn(
cache);
expectLastCall().anyTimes();
expect(cache.get(eq(requestKey.getValue()))).andReturn(null);
expectLastCall().anyTimes();
replay(cache, cacheService);
assertNull("Expected session to be null", service.getCurrentSession());
assertNull("Expected user to be null", service.getCurrentUserId());
verify(cache, cacheService);
service.unbindCacheManagerService(cacheService);
}
@Test
@SuppressWarnings("unchecked")
public void testSessionCachingCachesSession() {
CacheManagerService cacheService = createMock(CacheManagerService.class);
Cache<Object> cache = createMock(Cache.class);
SessionManagerServiceImpl service = new SessionManagerServiceImpl();
service.bindCacheManagerService(cacheService);
Capture<String> requestKey = new Capture<String>();
Capture<String> requestCache = new Capture<String>();
expect(
cacheService
.getCache(and(isA(String.class), capture(requestCache)), eq(CacheScope.REQUEST)))
.andReturn(cache);
expect(cache.get(and(isA(String.class), capture(requestKey)))).andReturn(null);
replay(cache, cacheService);
assertNull("Expected request to be null", service.getCurrentRequest());
verify(cache, cacheService);
reset(cache, cacheService);
HttpServletRequest currentRequest = createMock(HttpServletRequest.class);
HttpSession currentSession = createMock(HttpSession.class);
String testUser = "bob";
expect(cacheService.getCache(eq(requestCache.getValue()), eq(CacheScope.REQUEST))).andReturn(
cache);
expectLastCall().anyTimes();
expect(cache.put(eq(requestKey.getValue()), eq(currentRequest))).andReturn(currentRequest);
expect(cache.get(eq(requestKey.getValue()))).andReturn(currentRequest);
expectLastCall().anyTimes();
expect(currentRequest.getSession()).andReturn(currentSession);
expectLastCall().anyTimes();
expect(currentRequest.getRemoteUser()).andReturn(testUser);
expectLastCall().anyTimes();
replay(cache, cacheService, currentRequest, currentSession);
service.bindRequest(currentRequest);
assertEquals("Expected request to be set", currentRequest, service.getCurrentRequest());
assertEquals("Expected session to be set", currentSession, service.getCurrentSession());
assertEquals("Expected user to be set", testUser, service.getCurrentUserId());
verify(cache, cacheService, currentRequest, currentSession);
service.unbindCacheManagerService(cacheService);
}
}
| {
"content_hash": "1d1ceb4d3cd430938e19082dd65055ff",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 97,
"avg_line_length": 40.842592592592595,
"alnum_prop": 0.7560643844933121,
"repo_name": "dylanswartz/nakamura",
"id": "63c9a89a25ba73b47199e742b0c9ce66fbf6f292",
"size": "5202",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/session/src/test/java/org/sakaiproject/nakamura/session/TestSessionManagement.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.elasticsearch.search.internal;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.OriginalIndices;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchTask;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.transport.TransportRequest;
import java.io.IOException;
/**
* Shard level search request that represents an actual search sent from the coordinating node to the nodes holding
* the shards where the query needs to be executed. Holds the same info as {@link org.elasticsearch.search.internal.ShardSearchLocalRequest}
* but gets sent over the transport and holds also the indices coming from the original request that generated it, plus its headers and context.
*/
public class ShardSearchTransportRequest extends TransportRequest implements ShardSearchRequest, IndicesRequest {
private OriginalIndices originalIndices;
private ShardSearchLocalRequest shardSearchLocalRequest;
public ShardSearchTransportRequest(){
}
public ShardSearchTransportRequest(OriginalIndices originalIndices, SearchRequest searchRequest, ShardId shardId, int numberOfShards,
AliasFilter aliasFilter, float indexBoost, long nowInMillis) {
this.shardSearchLocalRequest = new ShardSearchLocalRequest(searchRequest, shardId, numberOfShards, aliasFilter, indexBoost,
nowInMillis);
this.originalIndices = originalIndices;
}
public void searchType(SearchType searchType) {
shardSearchLocalRequest.setSearchType(searchType);
}
@Override
public String[] indices() {
if (originalIndices == null) {
return null;
}
return originalIndices.indices();
}
@Override
public IndicesOptions indicesOptions() {
if (originalIndices == null) {
return null;
}
return originalIndices.indicesOptions();
}
@Override
public ShardId shardId() {
return shardSearchLocalRequest.shardId();
}
@Override
public String[] types() {
return shardSearchLocalRequest.types();
}
@Override
public SearchSourceBuilder source() {
return shardSearchLocalRequest.source();
}
@Override
public void source(SearchSourceBuilder source) {
shardSearchLocalRequest.source(source);
}
@Override
public int numberOfShards() {
return shardSearchLocalRequest.numberOfShards();
}
@Override
public SearchType searchType() {
return shardSearchLocalRequest.searchType();
}
@Override
public QueryBuilder filteringAliases() {
return shardSearchLocalRequest.filteringAliases();
}
@Override
public float indexBoost() {
return shardSearchLocalRequest.indexBoost();
}
@Override
public long nowInMillis() {
return shardSearchLocalRequest.nowInMillis();
}
@Override
public Boolean requestCache() {
return shardSearchLocalRequest.requestCache();
}
@Override
public Scroll scroll() {
return shardSearchLocalRequest.scroll();
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardSearchLocalRequest = new ShardSearchLocalRequest();
shardSearchLocalRequest.innerReadFrom(in);
originalIndices = OriginalIndices.readOriginalIndices(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
shardSearchLocalRequest.innerWriteTo(out, false);
OriginalIndices.writeOriginalIndices(originalIndices, out);
}
@Override
public BytesReference cacheKey() throws IOException {
return shardSearchLocalRequest.cacheKey();
}
@Override
public void setProfile(boolean profile) {
shardSearchLocalRequest.setProfile(profile);
}
@Override
public boolean isProfile() {
return shardSearchLocalRequest.isProfile();
}
@Override
public void rewrite(QueryShardContext context) throws IOException {
shardSearchLocalRequest.rewrite(context);
}
@Override
public Task createTask(long id, String type, String action, TaskId parentTaskId) {
return new SearchTask(id, type, action, getDescription(), parentTaskId);
}
@Override
public String getDescription() {
// Shard id is enough here, the request itself can be found by looking at the parent task description
return "shardId[" + shardSearchLocalRequest.shardId() + "]";
}
}
| {
"content_hash": "b4f2c776c4210a9c901397e4c44efb81",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 144,
"avg_line_length": 31.379518072289155,
"alnum_prop": 0.7204837780764062,
"repo_name": "naveenhooda2000/elasticsearch",
"id": "e841172448993c656971c884bf0ac69dbffca2fb",
"size": "5997",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/elasticsearch/search/internal/ShardSearchTransportRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "13592"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "330267"
},
{
"name": "HTML",
"bytes": "2186"
},
{
"name": "Java",
"bytes": "42370504"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "54395"
},
{
"name": "Shell",
"bytes": "108747"
}
],
"symlink_target": ""
} |
#define NISERR() VISERR(nfa->v)
#define NERR(e) VERR(nfa->v, (e))
/*
* newnfa - set up an NFA
*/
static struct nfa * /* the NFA, or NULL */
newnfa(struct vars *v,
struct colormap *cm,
struct nfa *parent) /* NULL if primary NFA */
{
struct nfa *nfa;
nfa = (struct nfa *) MALLOC(sizeof(struct nfa));
if (nfa == NULL)
{
ERR(REG_ESPACE);
return NULL;
}
nfa->states = NULL;
nfa->slast = NULL;
nfa->free = NULL;
nfa->nstates = 0;
nfa->cm = cm;
nfa->v = v;
nfa->bos[0] = nfa->bos[1] = COLORLESS;
nfa->eos[0] = nfa->eos[1] = COLORLESS;
nfa->parent = parent; /* Precedes newfstate so parent is valid. */
nfa->post = newfstate(nfa, '@'); /* number 0 */
nfa->pre = newfstate(nfa, '>'); /* number 1 */
nfa->init = newstate(nfa); /* may become invalid later */
nfa->final = newstate(nfa);
if (ISERR())
{
freenfa(nfa);
return NULL;
}
rainbow(nfa, nfa->cm, PLAIN, COLORLESS, nfa->pre, nfa->init);
newarc(nfa, '^', 1, nfa->pre, nfa->init);
newarc(nfa, '^', 0, nfa->pre, nfa->init);
rainbow(nfa, nfa->cm, PLAIN, COLORLESS, nfa->final, nfa->post);
newarc(nfa, '$', 1, nfa->final, nfa->post);
newarc(nfa, '$', 0, nfa->final, nfa->post);
if (ISERR())
{
freenfa(nfa);
return NULL;
}
return nfa;
}
/*
* freenfa - free an entire NFA
*/
static void
freenfa(struct nfa *nfa)
{
struct state *s;
while ((s = nfa->states) != NULL)
{
s->nins = s->nouts = 0; /* don't worry about arcs */
freestate(nfa, s);
}
while ((s = nfa->free) != NULL)
{
nfa->free = s->next;
destroystate(nfa, s);
}
nfa->slast = NULL;
nfa->nstates = -1;
nfa->pre = NULL;
nfa->post = NULL;
FREE(nfa);
}
/*
* newstate - allocate an NFA state, with zero flag value
*/
static struct state * /* NULL on error */
newstate(struct nfa *nfa)
{
struct state *s;
/*
* This is a handy place to check for operation cancel during regex
* compilation, since no code path will go very long without making a new
* state or arc.
*/
if (CANCEL_REQUESTED(nfa->v->re))
{
NERR(REG_CANCEL);
return NULL;
}
if (nfa->free != NULL)
{
s = nfa->free;
nfa->free = s->next;
}
else
{
if (nfa->v->spaceused >= REG_MAX_COMPILE_SPACE)
{
NERR(REG_ETOOBIG);
return NULL;
}
s = (struct state *) MALLOC(sizeof(struct state));
if (s == NULL)
{
NERR(REG_ESPACE);
return NULL;
}
nfa->v->spaceused += sizeof(struct state);
s->oas.next = NULL;
s->free = NULL;
s->noas = 0;
}
assert(nfa->nstates >= 0);
s->no = nfa->nstates++;
s->flag = 0;
if (nfa->states == NULL)
nfa->states = s;
s->nins = 0;
s->ins = NULL;
s->nouts = 0;
s->outs = NULL;
s->tmp = NULL;
s->next = NULL;
if (nfa->slast != NULL)
{
assert(nfa->slast->next == NULL);
nfa->slast->next = s;
}
s->prev = nfa->slast;
nfa->slast = s;
return s;
}
/*
* newfstate - allocate an NFA state with a specified flag value
*/
static struct state * /* NULL on error */
newfstate(struct nfa *nfa, int flag)
{
struct state *s;
s = newstate(nfa);
if (s != NULL)
s->flag = (char) flag;
return s;
}
/*
* dropstate - delete a state's inarcs and outarcs and free it
*/
static void
dropstate(struct nfa *nfa,
struct state *s)
{
struct arc *a;
while ((a = s->ins) != NULL)
freearc(nfa, a);
while ((a = s->outs) != NULL)
freearc(nfa, a);
freestate(nfa, s);
}
/*
* freestate - free a state, which has no in-arcs or out-arcs
*/
static void
freestate(struct nfa *nfa,
struct state *s)
{
assert(s != NULL);
assert(s->nins == 0 && s->nouts == 0);
s->no = FREESTATE;
s->flag = 0;
if (s->next != NULL)
s->next->prev = s->prev;
else
{
assert(s == nfa->slast);
nfa->slast = s->prev;
}
if (s->prev != NULL)
s->prev->next = s->next;
else
{
assert(s == nfa->states);
nfa->states = s->next;
}
s->prev = NULL;
s->next = nfa->free; /* don't delete it, put it on the free list */
nfa->free = s;
}
/*
* destroystate - really get rid of an already-freed state
*/
static void
destroystate(struct nfa *nfa,
struct state *s)
{
struct arcbatch *ab;
struct arcbatch *abnext;
assert(s->no == FREESTATE);
for (ab = s->oas.next; ab != NULL; ab = abnext)
{
abnext = ab->next;
FREE(ab);
nfa->v->spaceused -= sizeof(struct arcbatch);
}
s->ins = NULL;
s->outs = NULL;
s->next = NULL;
FREE(s);
nfa->v->spaceused -= sizeof(struct state);
}
/*
* newarc - set up a new arc within an NFA
*
* This function checks to make sure that no duplicate arcs are created.
* In general we never want duplicates.
*/
static void
newarc(struct nfa *nfa,
int t,
color co,
struct state *from,
struct state *to)
{
struct arc *a;
assert(from != NULL && to != NULL);
/*
* This is a handy place to check for operation cancel during regex
* compilation, since no code path will go very long without making a new
* state or arc.
*/
if (CANCEL_REQUESTED(nfa->v->re))
{
NERR(REG_CANCEL);
return;
}
/* check for duplicate arc, using whichever chain is shorter */
if (from->nouts <= to->nins)
{
for (a = from->outs; a != NULL; a = a->outchain)
if (a->to == to && a->co == co && a->type == t)
return;
}
else
{
for (a = to->ins; a != NULL; a = a->inchain)
if (a->from == from && a->co == co && a->type == t)
return;
}
/* no dup, so create the arc */
createarc(nfa, t, co, from, to);
}
/*
* createarc - create a new arc within an NFA
*
* This function must *only* be used after verifying that there is no existing
* identical arc (same type/color/from/to).
*/
static void
createarc(struct nfa *nfa,
int t,
color co,
struct state *from,
struct state *to)
{
struct arc *a;
/* the arc is physically allocated within its from-state */
a = allocarc(nfa, from);
if (NISERR())
return;
assert(a != NULL);
a->type = t;
a->co = co;
a->to = to;
a->from = from;
/*
* Put the new arc on the beginning, not the end, of the chains; it's
* simpler here, and freearc() is the same cost either way. See also the
* logic in moveins() and its cohorts, as well as fixempties().
*/
a->inchain = to->ins;
a->inchainRev = NULL;
if (to->ins)
to->ins->inchainRev = a;
to->ins = a;
a->outchain = from->outs;
a->outchainRev = NULL;
if (from->outs)
from->outs->outchainRev = a;
from->outs = a;
from->nouts++;
to->nins++;
if (COLORED(a) && nfa->parent == NULL)
colorchain(nfa->cm, a);
}
/*
* allocarc - allocate a new out-arc within a state
*/
static struct arc * /* NULL for failure */
allocarc(struct nfa *nfa,
struct state *s)
{
struct arc *a;
/* shortcut */
if (s->free == NULL && s->noas < ABSIZE)
{
a = &s->oas.a[s->noas];
s->noas++;
return a;
}
/* if none at hand, get more */
if (s->free == NULL)
{
struct arcbatch *newAb;
int i;
if (nfa->v->spaceused >= REG_MAX_COMPILE_SPACE)
{
NERR(REG_ETOOBIG);
return NULL;
}
newAb = (struct arcbatch *) MALLOC(sizeof(struct arcbatch));
if (newAb == NULL)
{
NERR(REG_ESPACE);
return NULL;
}
nfa->v->spaceused += sizeof(struct arcbatch);
newAb->next = s->oas.next;
s->oas.next = newAb;
for (i = 0; i < ABSIZE; i++)
{
newAb->a[i].type = 0;
newAb->a[i].freechain = &newAb->a[i + 1];
}
newAb->a[ABSIZE - 1].freechain = NULL;
s->free = &newAb->a[0];
}
assert(s->free != NULL);
a = s->free;
s->free = a->freechain;
return a;
}
/*
* freearc - free an arc
*/
static void
freearc(struct nfa *nfa,
struct arc *victim)
{
struct state *from = victim->from;
struct state *to = victim->to;
struct arc *predecessor;
assert(victim->type != 0);
/* take it off color chain if necessary */
if (COLORED(victim) && nfa->parent == NULL)
uncolorchain(nfa->cm, victim);
/* take it off source's out-chain */
assert(from != NULL);
predecessor = victim->outchainRev;
if (predecessor == NULL)
{
assert(from->outs == victim);
from->outs = victim->outchain;
}
else
{
assert(predecessor->outchain == victim);
predecessor->outchain = victim->outchain;
}
if (victim->outchain != NULL)
{
assert(victim->outchain->outchainRev == victim);
victim->outchain->outchainRev = predecessor;
}
from->nouts--;
/* take it off target's in-chain */
assert(to != NULL);
predecessor = victim->inchainRev;
if (predecessor == NULL)
{
assert(to->ins == victim);
to->ins = victim->inchain;
}
else
{
assert(predecessor->inchain == victim);
predecessor->inchain = victim->inchain;
}
if (victim->inchain != NULL)
{
assert(victim->inchain->inchainRev == victim);
victim->inchain->inchainRev = predecessor;
}
to->nins--;
/* clean up and place on from-state's free list */
victim->type = 0;
victim->from = NULL; /* precautions... */
victim->to = NULL;
victim->inchain = NULL;
victim->inchainRev = NULL;
victim->outchain = NULL;
victim->outchainRev = NULL;
victim->freechain = from->free;
from->free = victim;
}
/*
* changearctarget - flip an arc to have a different to state
*
* Caller must have verified that there is no pre-existing duplicate arc.
*
* Note that because we store arcs in their from state, we can't easily have
* a similar changearcsource function.
*/
static void
changearctarget(struct arc *a, struct state *newto)
{
struct state *oldto = a->to;
struct arc *predecessor;
assert(oldto != newto);
/* take it off old target's in-chain */
assert(oldto != NULL);
predecessor = a->inchainRev;
if (predecessor == NULL)
{
assert(oldto->ins == a);
oldto->ins = a->inchain;
}
else
{
assert(predecessor->inchain == a);
predecessor->inchain = a->inchain;
}
if (a->inchain != NULL)
{
assert(a->inchain->inchainRev == a);
a->inchain->inchainRev = predecessor;
}
oldto->nins--;
a->to = newto;
/* prepend it to new target's in-chain */
a->inchain = newto->ins;
a->inchainRev = NULL;
if (newto->ins)
newto->ins->inchainRev = a;
newto->ins = a;
newto->nins++;
}
/*
* hasnonemptyout - Does state have a non-EMPTY out arc?
*/
static int
hasnonemptyout(struct state *s)
{
struct arc *a;
for (a = s->outs; a != NULL; a = a->outchain)
{
if (a->type != EMPTY)
return 1;
}
return 0;
}
/*
* findarc - find arc, if any, from given source with given type and color
* If there is more than one such arc, the result is random.
*/
static struct arc *
findarc(struct state *s,
int type,
color co)
{
struct arc *a;
for (a = s->outs; a != NULL; a = a->outchain)
if (a->type == type && a->co == co)
return a;
return NULL;
}
/*
* cparc - allocate a new arc within an NFA, copying details from old one
*/
static void
cparc(struct nfa *nfa,
struct arc *oa,
struct state *from,
struct state *to)
{
newarc(nfa, oa->type, oa->co, from, to);
}
/*
* sortins - sort the in arcs of a state by from/color/type
*/
static void
sortins(struct nfa *nfa,
struct state *s)
{
struct arc **sortarray;
struct arc *a;
int n = s->nins;
int i;
if (n <= 1)
return; /* nothing to do */
/* make an array of arc pointers ... */
sortarray = (struct arc **) MALLOC(n * sizeof(struct arc *));
if (sortarray == NULL)
{
NERR(REG_ESPACE);
return;
}
i = 0;
for (a = s->ins; a != NULL; a = a->inchain)
sortarray[i++] = a;
assert(i == n);
/* ... sort the array */
qsort(sortarray, n, sizeof(struct arc *), sortins_cmp);
/* ... and rebuild arc list in order */
/* it seems worth special-casing first and last items to simplify loop */
a = sortarray[0];
s->ins = a;
a->inchain = sortarray[1];
a->inchainRev = NULL;
for (i = 1; i < n - 1; i++)
{
a = sortarray[i];
a->inchain = sortarray[i + 1];
a->inchainRev = sortarray[i - 1];
}
a = sortarray[i];
a->inchain = NULL;
a->inchainRev = sortarray[i - 1];
FREE(sortarray);
}
static int
sortins_cmp(const void *a, const void *b)
{
const struct arc *aa = *((const struct arc *const *) a);
const struct arc *bb = *((const struct arc *const *) b);
/* we check the fields in the order they are most likely to be different */
if (aa->from->no < bb->from->no)
return -1;
if (aa->from->no > bb->from->no)
return 1;
if (aa->co < bb->co)
return -1;
if (aa->co > bb->co)
return 1;
if (aa->type < bb->type)
return -1;
if (aa->type > bb->type)
return 1;
return 0;
}
/*
* sortouts - sort the out arcs of a state by to/color/type
*/
static void
sortouts(struct nfa *nfa,
struct state *s)
{
struct arc **sortarray;
struct arc *a;
int n = s->nouts;
int i;
if (n <= 1)
return; /* nothing to do */
/* make an array of arc pointers ... */
sortarray = (struct arc **) MALLOC(n * sizeof(struct arc *));
if (sortarray == NULL)
{
NERR(REG_ESPACE);
return;
}
i = 0;
for (a = s->outs; a != NULL; a = a->outchain)
sortarray[i++] = a;
assert(i == n);
/* ... sort the array */
qsort(sortarray, n, sizeof(struct arc *), sortouts_cmp);
/* ... and rebuild arc list in order */
/* it seems worth special-casing first and last items to simplify loop */
a = sortarray[0];
s->outs = a;
a->outchain = sortarray[1];
a->outchainRev = NULL;
for (i = 1; i < n - 1; i++)
{
a = sortarray[i];
a->outchain = sortarray[i + 1];
a->outchainRev = sortarray[i - 1];
}
a = sortarray[i];
a->outchain = NULL;
a->outchainRev = sortarray[i - 1];
FREE(sortarray);
}
static int
sortouts_cmp(const void *a, const void *b)
{
const struct arc *aa = *((const struct arc *const *) a);
const struct arc *bb = *((const struct arc *const *) b);
/* we check the fields in the order they are most likely to be different */
if (aa->to->no < bb->to->no)
return -1;
if (aa->to->no > bb->to->no)
return 1;
if (aa->co < bb->co)
return -1;
if (aa->co > bb->co)
return 1;
if (aa->type < bb->type)
return -1;
if (aa->type > bb->type)
return 1;
return 0;
}
/*
* Common decision logic about whether to use arc-by-arc operations or
* sort/merge. If there's just a few source arcs we cannot recoup the
* cost of sorting the destination arc list, no matter how large it is.
* Otherwise, limit the number of arc-by-arc comparisons to about 1000
* (a somewhat arbitrary choice, but the breakeven point would probably
* be machine dependent anyway).
*/
#define BULK_ARC_OP_USE_SORT(nsrcarcs, ndestarcs) \
((nsrcarcs) < 4 ? 0 : ((nsrcarcs) > 32 || (ndestarcs) > 32))
/*
* moveins - move all in arcs of a state to another state
*
* You might think this could be done better by just updating the
* existing arcs, and you would be right if it weren't for the need
* for duplicate suppression, which makes it easier to just make new
* ones to exploit the suppression built into newarc.
*
* However, if we have a whole lot of arcs to deal with, retail duplicate
* checks become too slow. In that case we proceed by sorting and merging
* the arc lists, and then we can indeed just update the arcs in-place.
*/
static void
moveins(struct nfa *nfa,
struct state *oldState,
struct state *newState)
{
assert(oldState != newState);
if (!BULK_ARC_OP_USE_SORT(oldState->nins, newState->nins))
{
/* With not too many arcs, just do them one at a time */
struct arc *a;
while ((a = oldState->ins) != NULL)
{
cparc(nfa, a, a->from, newState);
freearc(nfa, a);
}
}
else
{
/*
* With many arcs, use a sort-merge approach. Note changearctarget()
* will put the arc onto the front of newState's chain, so it does not
* break our walk through the sorted part of the chain.
*/
struct arc *oa;
struct arc *na;
/*
* Because we bypass newarc() in this code path, we'd better include a
* cancel check.
*/
if (CANCEL_REQUESTED(nfa->v->re))
{
NERR(REG_CANCEL);
return;
}
sortins(nfa, oldState);
sortins(nfa, newState);
if (NISERR())
return; /* might have failed to sort */
oa = oldState->ins;
na = newState->ins;
while (oa != NULL && na != NULL)
{
struct arc *a = oa;
switch (sortins_cmp(&oa, &na))
{
case -1:
/* newState does not have anything matching oa */
oa = oa->inchain;
/*
* Rather than doing createarc+freearc, we can just unlink
* and relink the existing arc struct.
*/
changearctarget(a, newState);
break;
case 0:
/* match, advance in both lists */
oa = oa->inchain;
na = na->inchain;
/* ... and drop duplicate arc from oldState */
freearc(nfa, a);
break;
case +1:
/* advance only na; oa might have a match later */
na = na->inchain;
break;
default:
assert(NOTREACHED);
}
}
while (oa != NULL)
{
/* newState does not have anything matching oa */
struct arc *a = oa;
oa = oa->inchain;
changearctarget(a, newState);
}
}
assert(oldState->nins == 0);
assert(oldState->ins == NULL);
}
/*
* copyins - copy in arcs of a state to another state
*/
static void
copyins(struct nfa *nfa,
struct state *oldState,
struct state *newState)
{
assert(oldState != newState);
if (!BULK_ARC_OP_USE_SORT(oldState->nins, newState->nins))
{
/* With not too many arcs, just do them one at a time */
struct arc *a;
for (a = oldState->ins; a != NULL; a = a->inchain)
cparc(nfa, a, a->from, newState);
}
else
{
/*
* With many arcs, use a sort-merge approach. Note that createarc()
* will put new arcs onto the front of newState's chain, so it does
* not break our walk through the sorted part of the chain.
*/
struct arc *oa;
struct arc *na;
/*
* Because we bypass newarc() in this code path, we'd better include a
* cancel check.
*/
if (CANCEL_REQUESTED(nfa->v->re))
{
NERR(REG_CANCEL);
return;
}
sortins(nfa, oldState);
sortins(nfa, newState);
if (NISERR())
return; /* might have failed to sort */
oa = oldState->ins;
na = newState->ins;
while (oa != NULL && na != NULL)
{
struct arc *a = oa;
switch (sortins_cmp(&oa, &na))
{
case -1:
/* newState does not have anything matching oa */
oa = oa->inchain;
createarc(nfa, a->type, a->co, a->from, newState);
break;
case 0:
/* match, advance in both lists */
oa = oa->inchain;
na = na->inchain;
break;
case +1:
/* advance only na; oa might have a match later */
na = na->inchain;
break;
default:
assert(NOTREACHED);
}
}
while (oa != NULL)
{
/* newState does not have anything matching oa */
struct arc *a = oa;
oa = oa->inchain;
createarc(nfa, a->type, a->co, a->from, newState);
}
}
}
/*
* mergeins - merge a list of inarcs into a state
*
* This is much like copyins, but the source arcs are listed in an array,
* and are not guaranteed unique. It's okay to clobber the array contents.
*/
static void
mergeins(struct nfa *nfa,
struct state *s,
struct arc **arcarray,
int arccount)
{
struct arc *na;
int i;
int j;
if (arccount <= 0)
return;
/*
* Because we bypass newarc() in this code path, we'd better include a
* cancel check.
*/
if (CANCEL_REQUESTED(nfa->v->re))
{
NERR(REG_CANCEL);
return;
}
/* Sort existing inarcs as well as proposed new ones */
sortins(nfa, s);
if (NISERR())
return; /* might have failed to sort */
qsort(arcarray, arccount, sizeof(struct arc *), sortins_cmp);
/*
* arcarray very likely includes dups, so we must eliminate them. (This
* could be folded into the next loop, but it's not worth the trouble.)
*/
j = 0;
for (i = 1; i < arccount; i++)
{
switch (sortins_cmp(&arcarray[j], &arcarray[i]))
{
case -1:
/* non-dup */
arcarray[++j] = arcarray[i];
break;
case 0:
/* dup */
break;
default:
/* trouble */
assert(NOTREACHED);
}
}
arccount = j + 1;
/*
* Now merge into s' inchain. Note that createarc() will put new arcs
* onto the front of s's chain, so it does not break our walk through the
* sorted part of the chain.
*/
i = 0;
na = s->ins;
while (i < arccount && na != NULL)
{
struct arc *a = arcarray[i];
switch (sortins_cmp(&a, &na))
{
case -1:
/* s does not have anything matching a */
createarc(nfa, a->type, a->co, a->from, s);
i++;
break;
case 0:
/* match, advance in both lists */
i++;
na = na->inchain;
break;
case +1:
/* advance only na; array might have a match later */
na = na->inchain;
break;
default:
assert(NOTREACHED);
}
}
while (i < arccount)
{
/* s does not have anything matching a */
struct arc *a = arcarray[i];
createarc(nfa, a->type, a->co, a->from, s);
i++;
}
}
/*
* moveouts - move all out arcs of a state to another state
*/
static void
moveouts(struct nfa *nfa,
struct state *oldState,
struct state *newState)
{
assert(oldState != newState);
if (!BULK_ARC_OP_USE_SORT(oldState->nouts, newState->nouts))
{
/* With not too many arcs, just do them one at a time */
struct arc *a;
while ((a = oldState->outs) != NULL)
{
cparc(nfa, a, newState, a->to);
freearc(nfa, a);
}
}
else
{
/*
* With many arcs, use a sort-merge approach. Note that createarc()
* will put new arcs onto the front of newState's chain, so it does
* not break our walk through the sorted part of the chain.
*/
struct arc *oa;
struct arc *na;
/*
* Because we bypass newarc() in this code path, we'd better include a
* cancel check.
*/
if (CANCEL_REQUESTED(nfa->v->re))
{
NERR(REG_CANCEL);
return;
}
sortouts(nfa, oldState);
sortouts(nfa, newState);
if (NISERR())
return; /* might have failed to sort */
oa = oldState->outs;
na = newState->outs;
while (oa != NULL && na != NULL)
{
struct arc *a = oa;
switch (sortouts_cmp(&oa, &na))
{
case -1:
/* newState does not have anything matching oa */
oa = oa->outchain;
createarc(nfa, a->type, a->co, newState, a->to);
freearc(nfa, a);
break;
case 0:
/* match, advance in both lists */
oa = oa->outchain;
na = na->outchain;
/* ... and drop duplicate arc from oldState */
freearc(nfa, a);
break;
case +1:
/* advance only na; oa might have a match later */
na = na->outchain;
break;
default:
assert(NOTREACHED);
}
}
while (oa != NULL)
{
/* newState does not have anything matching oa */
struct arc *a = oa;
oa = oa->outchain;
createarc(nfa, a->type, a->co, newState, a->to);
freearc(nfa, a);
}
}
assert(oldState->nouts == 0);
assert(oldState->outs == NULL);
}
/*
* copyouts - copy out arcs of a state to another state
*/
static void
copyouts(struct nfa *nfa,
struct state *oldState,
struct state *newState)
{
assert(oldState != newState);
if (!BULK_ARC_OP_USE_SORT(oldState->nouts, newState->nouts))
{
/* With not too many arcs, just do them one at a time */
struct arc *a;
for (a = oldState->outs; a != NULL; a = a->outchain)
cparc(nfa, a, newState, a->to);
}
else
{
/*
* With many arcs, use a sort-merge approach. Note that createarc()
* will put new arcs onto the front of newState's chain, so it does
* not break our walk through the sorted part of the chain.
*/
struct arc *oa;
struct arc *na;
/*
* Because we bypass newarc() in this code path, we'd better include a
* cancel check.
*/
if (CANCEL_REQUESTED(nfa->v->re))
{
NERR(REG_CANCEL);
return;
}
sortouts(nfa, oldState);
sortouts(nfa, newState);
if (NISERR())
return; /* might have failed to sort */
oa = oldState->outs;
na = newState->outs;
while (oa != NULL && na != NULL)
{
struct arc *a = oa;
switch (sortouts_cmp(&oa, &na))
{
case -1:
/* newState does not have anything matching oa */
oa = oa->outchain;
createarc(nfa, a->type, a->co, newState, a->to);
break;
case 0:
/* match, advance in both lists */
oa = oa->outchain;
na = na->outchain;
break;
case +1:
/* advance only na; oa might have a match later */
na = na->outchain;
break;
default:
assert(NOTREACHED);
}
}
while (oa != NULL)
{
/* newState does not have anything matching oa */
struct arc *a = oa;
oa = oa->outchain;
createarc(nfa, a->type, a->co, newState, a->to);
}
}
}
/*
* cloneouts - copy out arcs of a state to another state pair, modifying type
*/
static void
cloneouts(struct nfa *nfa,
struct state *old,
struct state *from,
struct state *to,
int type)
{
struct arc *a;
assert(old != from);
for (a = old->outs; a != NULL; a = a->outchain)
newarc(nfa, type, a->co, from, to);
}
/*
* delsub - delete a sub-NFA, updating subre pointers if necessary
*
* This uses a recursive traversal of the sub-NFA, marking already-seen
* states using their tmp pointer.
*/
static void
delsub(struct nfa *nfa,
struct state *lp, /* the sub-NFA goes from here... */
struct state *rp) /* ...to here, *not* inclusive */
{
assert(lp != rp);
rp->tmp = rp; /* mark end */
deltraverse(nfa, lp, lp);
if (NISERR())
return; /* asserts might not hold after failure */
assert(lp->nouts == 0 && rp->nins == 0); /* did the job */
assert(lp->no != FREESTATE && rp->no != FREESTATE); /* no more */
rp->tmp = NULL; /* unmark end */
lp->tmp = NULL; /* and begin, marked by deltraverse */
}
/*
* deltraverse - the recursive heart of delsub
* This routine's basic job is to destroy all out-arcs of the state.
*/
static void
deltraverse(struct nfa *nfa,
struct state *leftend,
struct state *s)
{
struct arc *a;
struct state *to;
/* Since this is recursive, it could be driven to stack overflow */
if (STACK_TOO_DEEP(nfa->v->re))
{
NERR(REG_ETOOBIG);
return;
}
if (s->nouts == 0)
return; /* nothing to do */
if (s->tmp != NULL)
return; /* already in progress */
s->tmp = s; /* mark as in progress */
while ((a = s->outs) != NULL)
{
to = a->to;
deltraverse(nfa, leftend, to);
if (NISERR())
return; /* asserts might not hold after failure */
assert(to->nouts == 0 || to->tmp != NULL);
freearc(nfa, a);
if (to->nins == 0 && to->tmp == NULL)
{
assert(to->nouts == 0);
freestate(nfa, to);
}
}
assert(s->no != FREESTATE); /* we're still here */
assert(s == leftend || s->nins != 0); /* and still reachable */
assert(s->nouts == 0); /* but have no outarcs */
s->tmp = NULL; /* we're done here */
}
/*
* dupnfa - duplicate sub-NFA
*
* Another recursive traversal, this time using tmp to point to duplicates
* as well as mark already-seen states. (You knew there was a reason why
* it's a state pointer, didn't you? :-))
*/
static void
dupnfa(struct nfa *nfa,
struct state *start, /* duplicate of subNFA starting here */
struct state *stop, /* and stopping here */
struct state *from, /* stringing duplicate from here */
struct state *to) /* to here */
{
if (start == stop)
{
newarc(nfa, EMPTY, 0, from, to);
return;
}
stop->tmp = to;
duptraverse(nfa, start, from);
/* done, except for clearing out the tmp pointers */
stop->tmp = NULL;
cleartraverse(nfa, start);
}
/*
* duptraverse - recursive heart of dupnfa
*/
static void
duptraverse(struct nfa *nfa,
struct state *s,
struct state *stmp) /* s's duplicate, or NULL */
{
struct arc *a;
/* Since this is recursive, it could be driven to stack overflow */
if (STACK_TOO_DEEP(nfa->v->re))
{
NERR(REG_ETOOBIG);
return;
}
if (s->tmp != NULL)
return; /* already done */
s->tmp = (stmp == NULL) ? newstate(nfa) : stmp;
if (s->tmp == NULL)
{
assert(NISERR());
return;
}
for (a = s->outs; a != NULL && !NISERR(); a = a->outchain)
{
duptraverse(nfa, a->to, (struct state *) NULL);
if (NISERR())
break;
assert(a->to->tmp != NULL);
cparc(nfa, a, s->tmp, a->to->tmp);
}
}
/*
* cleartraverse - recursive cleanup for algorithms that leave tmp ptrs set
*/
static void
cleartraverse(struct nfa *nfa,
struct state *s)
{
struct arc *a;
/* Since this is recursive, it could be driven to stack overflow */
if (STACK_TOO_DEEP(nfa->v->re))
{
NERR(REG_ETOOBIG);
return;
}
if (s->tmp == NULL)
return;
s->tmp = NULL;
for (a = s->outs; a != NULL; a = a->outchain)
cleartraverse(nfa, a->to);
}
/*
* single_color_transition - does getting from s1 to s2 cross one PLAIN arc?
*
* If traversing from s1 to s2 requires a single PLAIN match (possibly of any
* of a set of colors), return a state whose outarc list contains only PLAIN
* arcs of those color(s). Otherwise return NULL.
*
* This is used before optimizing the NFA, so there may be EMPTY arcs, which
* we should ignore; the possibility of an EMPTY is why the result state could
* be different from s1.
*
* It's worth troubling to handle multiple parallel PLAIN arcs here because a
* bracket construct such as [abc] might yield either one or several parallel
* PLAIN arcs depending on earlier atoms in the expression. We'd rather that
* that implementation detail not create user-visible performance differences.
*/
static struct state *
single_color_transition(struct state *s1, struct state *s2)
{
struct arc *a;
/* Ignore leading EMPTY arc, if any */
if (s1->nouts == 1 && s1->outs->type == EMPTY)
s1 = s1->outs->to;
/* Likewise for any trailing EMPTY arc */
if (s2->nins == 1 && s2->ins->type == EMPTY)
s2 = s2->ins->from;
/* Perhaps we could have a single-state loop in between, if so reject */
if (s1 == s2)
return NULL;
/* s1 must have at least one outarc... */
if (s1->outs == NULL)
return NULL;
/* ... and they must all be PLAIN arcs to s2 */
for (a = s1->outs; a != NULL; a = a->outchain)
{
if (a->type != PLAIN || a->to != s2)
return NULL;
}
/* OK, return s1 as the possessor of the relevant outarcs */
return s1;
}
/*
* specialcolors - fill in special colors for an NFA
*/
static void
specialcolors(struct nfa *nfa)
{
/* false colors for BOS, BOL, EOS, EOL */
if (nfa->parent == NULL)
{
nfa->bos[0] = pseudocolor(nfa->cm);
nfa->bos[1] = pseudocolor(nfa->cm);
nfa->eos[0] = pseudocolor(nfa->cm);
nfa->eos[1] = pseudocolor(nfa->cm);
}
else
{
assert(nfa->parent->bos[0] != COLORLESS);
nfa->bos[0] = nfa->parent->bos[0];
assert(nfa->parent->bos[1] != COLORLESS);
nfa->bos[1] = nfa->parent->bos[1];
assert(nfa->parent->eos[0] != COLORLESS);
nfa->eos[0] = nfa->parent->eos[0];
assert(nfa->parent->eos[1] != COLORLESS);
nfa->eos[1] = nfa->parent->eos[1];
}
}
/*
* optimize - optimize an NFA
*
* The main goal of this function is not so much "optimization" (though it
* does try to get rid of useless NFA states) as reducing the NFA to a form
* the regex executor can handle. The executor, and indeed the cNFA format
* that is its input, can only handle PLAIN and LACON arcs. The output of
* the regex parser also includes EMPTY (do-nothing) arcs, as well as
* ^, $, AHEAD, and BEHIND constraint arcs, which we must get rid of here.
* We first get rid of EMPTY arcs and then deal with the constraint arcs.
* The hardest part of either job is to get rid of circular loops of the
* target arc type. We would have to do that in any case, though, as such a
* loop would otherwise allow the executor to cycle through the loop endlessly
* without making any progress in the input string.
*/
static long /* re_info bits */
optimize(struct nfa *nfa,
FILE *f) /* for debug output; NULL none */
{
#ifdef REG_DEBUG
int verbose = (f != NULL) ? 1 : 0;
if (verbose)
fprintf(f, "\ninitial cleanup:\n");
#endif
cleanup(nfa); /* may simplify situation */
#ifdef REG_DEBUG
if (verbose)
dumpnfa(nfa, f);
if (verbose)
fprintf(f, "\nempties:\n");
#endif
fixempties(nfa, f); /* get rid of EMPTY arcs */
#ifdef REG_DEBUG
if (verbose)
fprintf(f, "\nconstraints:\n");
#endif
fixconstraintloops(nfa, f); /* get rid of constraint loops */
pullback(nfa, f); /* pull back constraints backward */
pushfwd(nfa, f); /* push fwd constraints forward */
#ifdef REG_DEBUG
if (verbose)
fprintf(f, "\nfinal cleanup:\n");
#endif
cleanup(nfa); /* final tidying */
#ifdef REG_DEBUG
if (verbose)
dumpnfa(nfa, f);
#endif
return analyze(nfa); /* and analysis */
}
/*
* pullback - pull back constraints backward to eliminate them
*/
static void
pullback(struct nfa *nfa,
FILE *f) /* for debug output; NULL none */
{
struct state *s;
struct state *nexts;
struct arc *a;
struct arc *nexta;
struct state *intermediates;
int progress;
/* find and pull until there are no more */
do
{
progress = 0;
for (s = nfa->states; s != NULL && !NISERR(); s = nexts)
{
nexts = s->next;
intermediates = NULL;
for (a = s->outs; a != NULL && !NISERR(); a = nexta)
{
nexta = a->outchain;
if (a->type == '^' || a->type == BEHIND)
if (pull(nfa, a, &intermediates))
progress = 1;
}
/* clear tmp fields of intermediate states created here */
while (intermediates != NULL)
{
struct state *ns = intermediates->tmp;
intermediates->tmp = NULL;
intermediates = ns;
}
/* if s is now useless, get rid of it */
if ((s->nins == 0 || s->nouts == 0) && !s->flag)
dropstate(nfa, s);
}
if (progress && f != NULL)
dumpnfa(nfa, f);
} while (progress && !NISERR());
if (NISERR())
return;
/*
* Any ^ constraints we were able to pull to the start state can now be
* replaced by PLAIN arcs referencing the BOS or BOL colors. There should
* be no other ^ or BEHIND arcs left in the NFA, though we do not check
* that here (compact() will fail if so).
*/
for (a = nfa->pre->outs; a != NULL; a = nexta)
{
nexta = a->outchain;
if (a->type == '^')
{
assert(a->co == 0 || a->co == 1);
newarc(nfa, PLAIN, nfa->bos[a->co], a->from, a->to);
freearc(nfa, a);
}
}
}
/*
* pull - pull a back constraint backward past its source state
*
* Returns 1 if successful (which it always is unless the source is the
* start state or we have an internal error), 0 if nothing happened.
*
* A significant property of this function is that it deletes no pre-existing
* states, and no outarcs of the constraint's from state other than the given
* constraint arc. This makes the loops in pullback() safe, at the cost that
* we may leave useless states behind. Therefore, we leave it to pullback()
* to delete such states.
*
* If the from state has multiple back-constraint outarcs, and/or multiple
* compatible constraint inarcs, we only need to create one new intermediate
* state per combination of predecessor and successor states. *intermediates
* points to a list of such intermediate states for this from state (chained
* through their tmp fields).
*/
static int
pull(struct nfa *nfa,
struct arc *con,
struct state **intermediates)
{
struct state *from = con->from;
struct state *to = con->to;
struct arc *a;
struct arc *nexta;
struct state *s;
assert(from != to); /* should have gotten rid of this earlier */
if (from->flag) /* can't pull back beyond start */
return 0;
if (from->nins == 0)
{ /* unreachable */
freearc(nfa, con);
return 1;
}
/*
* First, clone from state if necessary to avoid other outarcs. This may
* seem wasteful, but it simplifies the logic, and we'll get rid of the
* clone state again at the bottom.
*/
if (from->nouts > 1)
{
s = newstate(nfa);
if (NISERR())
return 0;
copyins(nfa, from, s); /* duplicate inarcs */
cparc(nfa, con, s, to); /* move constraint arc */
freearc(nfa, con);
if (NISERR())
return 0;
from = s;
con = from->outs;
}
assert(from->nouts == 1);
/* propagate the constraint into the from state's inarcs */
for (a = from->ins; a != NULL && !NISERR(); a = nexta)
{
nexta = a->inchain;
switch (combine(con, a))
{
case INCOMPATIBLE: /* destroy the arc */
freearc(nfa, a);
break;
case SATISFIED: /* no action needed */
break;
case COMPATIBLE: /* swap the two arcs, more or less */
/* need an intermediate state, but might have one already */
for (s = *intermediates; s != NULL; s = s->tmp)
{
assert(s->nins > 0 && s->nouts > 0);
if (s->ins->from == a->from && s->outs->to == to)
break;
}
if (s == NULL)
{
s = newstate(nfa);
if (NISERR())
return 0;
s->tmp = *intermediates;
*intermediates = s;
}
cparc(nfa, con, a->from, s);
cparc(nfa, a, s, to);
freearc(nfa, a);
break;
default:
assert(NOTREACHED);
break;
}
}
/* remaining inarcs, if any, incorporate the constraint */
moveins(nfa, from, to);
freearc(nfa, con);
/* from state is now useless, but we leave it to pullback() to clean up */
return 1;
}
/*
* pushfwd - push forward constraints forward to eliminate them
*/
static void
pushfwd(struct nfa *nfa,
FILE *f) /* for debug output; NULL none */
{
struct state *s;
struct state *nexts;
struct arc *a;
struct arc *nexta;
struct state *intermediates;
int progress;
/* find and push until there are no more */
do
{
progress = 0;
for (s = nfa->states; s != NULL && !NISERR(); s = nexts)
{
nexts = s->next;
intermediates = NULL;
for (a = s->ins; a != NULL && !NISERR(); a = nexta)
{
nexta = a->inchain;
if (a->type == '$' || a->type == AHEAD)
if (push(nfa, a, &intermediates))
progress = 1;
}
/* clear tmp fields of intermediate states created here */
while (intermediates != NULL)
{
struct state *ns = intermediates->tmp;
intermediates->tmp = NULL;
intermediates = ns;
}
/* if s is now useless, get rid of it */
if ((s->nins == 0 || s->nouts == 0) && !s->flag)
dropstate(nfa, s);
}
if (progress && f != NULL)
dumpnfa(nfa, f);
} while (progress && !NISERR());
if (NISERR())
return;
/*
* Any $ constraints we were able to push to the post state can now be
* replaced by PLAIN arcs referencing the EOS or EOL colors. There should
* be no other $ or AHEAD arcs left in the NFA, though we do not check
* that here (compact() will fail if so).
*/
for (a = nfa->post->ins; a != NULL; a = nexta)
{
nexta = a->inchain;
if (a->type == '$')
{
assert(a->co == 0 || a->co == 1);
newarc(nfa, PLAIN, nfa->eos[a->co], a->from, a->to);
freearc(nfa, a);
}
}
}
/*
* push - push a forward constraint forward past its destination state
*
* Returns 1 if successful (which it always is unless the destination is the
* post state or we have an internal error), 0 if nothing happened.
*
* A significant property of this function is that it deletes no pre-existing
* states, and no inarcs of the constraint's to state other than the given
* constraint arc. This makes the loops in pushfwd() safe, at the cost that
* we may leave useless states behind. Therefore, we leave it to pushfwd()
* to delete such states.
*
* If the to state has multiple forward-constraint inarcs, and/or multiple
* compatible constraint outarcs, we only need to create one new intermediate
* state per combination of predecessor and successor states. *intermediates
* points to a list of such intermediate states for this to state (chained
* through their tmp fields).
*/
static int
push(struct nfa *nfa,
struct arc *con,
struct state **intermediates)
{
struct state *from = con->from;
struct state *to = con->to;
struct arc *a;
struct arc *nexta;
struct state *s;
assert(to != from); /* should have gotten rid of this earlier */
if (to->flag) /* can't push forward beyond end */
return 0;
if (to->nouts == 0)
{ /* dead end */
freearc(nfa, con);
return 1;
}
/*
* First, clone to state if necessary to avoid other inarcs. This may
* seem wasteful, but it simplifies the logic, and we'll get rid of the
* clone state again at the bottom.
*/
if (to->nins > 1)
{
s = newstate(nfa);
if (NISERR())
return 0;
copyouts(nfa, to, s); /* duplicate outarcs */
cparc(nfa, con, from, s); /* move constraint arc */
freearc(nfa, con);
if (NISERR())
return 0;
to = s;
con = to->ins;
}
assert(to->nins == 1);
/* propagate the constraint into the to state's outarcs */
for (a = to->outs; a != NULL && !NISERR(); a = nexta)
{
nexta = a->outchain;
switch (combine(con, a))
{
case INCOMPATIBLE: /* destroy the arc */
freearc(nfa, a);
break;
case SATISFIED: /* no action needed */
break;
case COMPATIBLE: /* swap the two arcs, more or less */
/* need an intermediate state, but might have one already */
for (s = *intermediates; s != NULL; s = s->tmp)
{
assert(s->nins > 0 && s->nouts > 0);
if (s->ins->from == from && s->outs->to == a->to)
break;
}
if (s == NULL)
{
s = newstate(nfa);
if (NISERR())
return 0;
s->tmp = *intermediates;
*intermediates = s;
}
cparc(nfa, con, s, a->to);
cparc(nfa, a, from, s);
freearc(nfa, a);
break;
default:
assert(NOTREACHED);
break;
}
}
/* remaining outarcs, if any, incorporate the constraint */
moveouts(nfa, to, from);
freearc(nfa, con);
/* to state is now useless, but we leave it to pushfwd() to clean up */
return 1;
}
/*
* combine - constraint lands on an arc, what happens?
*
* #def INCOMPATIBLE 1 // destroys arc
* #def SATISFIED 2 // constraint satisfied
* #def COMPATIBLE 3 // compatible but not satisfied yet
*/
static int
combine(struct arc *con,
struct arc *a)
{
#define CA(ct,at) (((ct)<<CHAR_BIT) | (at))
switch (CA(con->type, a->type))
{
case CA('^', PLAIN): /* newlines are handled separately */
case CA('$', PLAIN):
return INCOMPATIBLE;
break;
case CA(AHEAD, PLAIN): /* color constraints meet colors */
case CA(BEHIND, PLAIN):
if (con->co == a->co)
return SATISFIED;
return INCOMPATIBLE;
break;
case CA('^', '^'): /* collision, similar constraints */
case CA('$', '$'):
case CA(AHEAD, AHEAD):
case CA(BEHIND, BEHIND):
if (con->co == a->co) /* true duplication */
return SATISFIED;
return INCOMPATIBLE;
break;
case CA('^', BEHIND): /* collision, dissimilar constraints */
case CA(BEHIND, '^'):
case CA('$', AHEAD):
case CA(AHEAD, '$'):
return INCOMPATIBLE;
break;
case CA('^', '$'): /* constraints passing each other */
case CA('^', AHEAD):
case CA(BEHIND, '$'):
case CA(BEHIND, AHEAD):
case CA('$', '^'):
case CA('$', BEHIND):
case CA(AHEAD, '^'):
case CA(AHEAD, BEHIND):
case CA('^', LACON):
case CA(BEHIND, LACON):
case CA('$', LACON):
case CA(AHEAD, LACON):
return COMPATIBLE;
break;
}
assert(NOTREACHED);
return INCOMPATIBLE; /* for benefit of blind compilers */
}
/*
* fixempties - get rid of EMPTY arcs
*/
static void
fixempties(struct nfa *nfa,
FILE *f) /* for debug output; NULL none */
{
struct state *s;
struct state *s2;
struct state *nexts;
struct arc *a;
struct arc *nexta;
int totalinarcs;
struct arc **inarcsorig;
struct arc **arcarray;
int arccount;
int prevnins;
int nskip;
/*
* First, get rid of any states whose sole out-arc is an EMPTY, since
* they're basically just aliases for their successor. The parsing
* algorithm creates enough of these that it's worth special-casing this.
*/
for (s = nfa->states; s != NULL && !NISERR(); s = nexts)
{
nexts = s->next;
if (s->flag || s->nouts != 1)
continue;
a = s->outs;
assert(a != NULL && a->outchain == NULL);
if (a->type != EMPTY)
continue;
if (s != a->to)
moveins(nfa, s, a->to);
dropstate(nfa, s);
}
/*
* Similarly, get rid of any state with a single EMPTY in-arc, by folding
* it into its predecessor.
*/
for (s = nfa->states; s != NULL && !NISERR(); s = nexts)
{
nexts = s->next;
/* while we're at it, ensure tmp fields are clear for next step */
assert(s->tmp == NULL);
if (s->flag || s->nins != 1)
continue;
a = s->ins;
assert(a != NULL && a->inchain == NULL);
if (a->type != EMPTY)
continue;
if (s != a->from)
moveouts(nfa, s, a->from);
dropstate(nfa, s);
}
if (NISERR())
return;
/*
* For each remaining NFA state, find all other states from which it is
* reachable by a chain of one or more EMPTY arcs. Then generate new arcs
* that eliminate the need for each such chain.
*
* We could replace a chain of EMPTY arcs that leads from a "from" state
* to a "to" state either by pushing non-EMPTY arcs forward (linking
* directly from "from"'s predecessors to "to") or by pulling them back
* (linking directly from "from" to "to"'s successors). We choose to
* always do the former; this choice is somewhat arbitrary, but the
* approach below requires that we uniformly do one or the other.
*
* Suppose we have a chain of N successive EMPTY arcs (where N can easily
* approach the size of the NFA). All of the intermediate states must
* have additional inarcs and outarcs, else they'd have been removed by
* the steps above. Assuming their inarcs are mostly not empties, we will
* add O(N^2) arcs to the NFA, since a non-EMPTY inarc leading to any one
* state in the chain must be duplicated to lead to all its successor
* states as well. So there is no hope of doing less than O(N^2) work;
* however, we should endeavor to keep the big-O cost from being even
* worse than that, which it can easily become without care. In
* particular, suppose we were to copy all S1's inarcs forward to S2, and
* then also to S3, and then later we consider pushing S2's inarcs forward
* to S3. If we include the arcs already copied from S1 in that, we'd be
* doing O(N^3) work. (The duplicate-arc elimination built into newarc()
* and its cohorts would get rid of the extra arcs, but not without cost.)
*
* We can avoid this cost by treating only arcs that existed at the start
* of this phase as candidates to be pushed forward. To identify those,
* we remember the first inarc each state had to start with. We rely on
* the fact that newarc() and friends put new arcs on the front of their
* to-states' inchains, and that this phase never deletes arcs, so that
* the original arcs must be the last arcs in their to-states' inchains.
*
* So the process here is that, for each state in the NFA, we gather up
* all non-EMPTY inarcs of states that can reach the target state via
* EMPTY arcs. We then sort, de-duplicate, and merge these arcs into the
* target state's inchain. (We can safely use sort-merge for this as long
* as we update each state's original-arcs pointer after we add arcs to
* it; the sort step of mergeins probably changed the order of the old
* arcs.)
*
* Another refinement worth making is that, because we only add non-EMPTY
* arcs during this phase, and all added arcs have the same from-state as
* the non-EMPTY arc they were cloned from, we know ahead of time that any
* states having only EMPTY outarcs will be useless for lack of outarcs
* after we drop the EMPTY arcs. (They cannot gain non-EMPTY outarcs if
* they had none to start with.) So we need not bother to update the
* inchains of such states at all.
*/
/* Remember the states' first original inarcs */
/* ... and while at it, count how many old inarcs there are altogether */
inarcsorig = (struct arc **) MALLOC(nfa->nstates * sizeof(struct arc *));
if (inarcsorig == NULL)
{
NERR(REG_ESPACE);
return;
}
totalinarcs = 0;
for (s = nfa->states; s != NULL; s = s->next)
{
inarcsorig[s->no] = s->ins;
totalinarcs += s->nins;
}
/*
* Create a workspace for accumulating the inarcs to be added to the
* current target state. totalinarcs is probably a considerable
* overestimate of the space needed, but the NFA is unlikely to be large
* enough at this point to make it worth being smarter.
*/
arcarray = (struct arc **) MALLOC(totalinarcs * sizeof(struct arc *));
if (arcarray == NULL)
{
NERR(REG_ESPACE);
FREE(inarcsorig);
return;
}
/* And iterate over the target states */
for (s = nfa->states; s != NULL && !NISERR(); s = s->next)
{
/* Ignore target states without non-EMPTY outarcs, per note above */
if (!s->flag && !hasnonemptyout(s))
continue;
/* Find predecessor states and accumulate their original inarcs */
arccount = 0;
for (s2 = emptyreachable(nfa, s, s, inarcsorig); s2 != s; s2 = nexts)
{
/* Add s2's original inarcs to arcarray[], but ignore empties */
for (a = inarcsorig[s2->no]; a != NULL; a = a->inchain)
{
if (a->type != EMPTY)
arcarray[arccount++] = a;
}
/* Reset the tmp fields as we walk back */
nexts = s2->tmp;
s2->tmp = NULL;
}
s->tmp = NULL;
assert(arccount <= totalinarcs);
/* Remember how many original inarcs this state has */
prevnins = s->nins;
/* Add non-duplicate inarcs to target state */
mergeins(nfa, s, arcarray, arccount);
/* Now we must update the state's inarcsorig pointer */
nskip = s->nins - prevnins;
a = s->ins;
while (nskip-- > 0)
a = a->inchain;
inarcsorig[s->no] = a;
}
FREE(arcarray);
FREE(inarcsorig);
if (NISERR())
return;
/*
* Now remove all the EMPTY arcs, since we don't need them anymore.
*/
for (s = nfa->states; s != NULL; s = s->next)
{
for (a = s->outs; a != NULL; a = nexta)
{
nexta = a->outchain;
if (a->type == EMPTY)
freearc(nfa, a);
}
}
/*
* And remove any states that have become useless. (This cleanup is not
* very thorough, and would be even less so if we tried to combine it with
* the previous step; but cleanup() will take care of anything we miss.)
*/
for (s = nfa->states; s != NULL; s = nexts)
{
nexts = s->next;
if ((s->nins == 0 || s->nouts == 0) && !s->flag)
dropstate(nfa, s);
}
if (f != NULL)
dumpnfa(nfa, f);
}
/*
* emptyreachable - recursively find all states that can reach s by EMPTY arcs
*
* The return value is the last such state found. Its tmp field links back
* to the next-to-last such state, and so on back to s, so that all these
* states can be located without searching the whole NFA.
*
* Since this is only used in fixempties(), we pass in the inarcsorig[] array
* maintained by that function. This lets us skip over all new inarcs, which
* are certainly not EMPTY arcs.
*
* The maximum recursion depth here is equal to the length of the longest
* loop-free chain of EMPTY arcs, which is surely no more than the size of
* the NFA ... but that could still be enough to cause trouble.
*/
static struct state *
emptyreachable(struct nfa *nfa,
struct state *s,
struct state *lastfound,
struct arc **inarcsorig)
{
struct arc *a;
/* Since this is recursive, it could be driven to stack overflow */
if (STACK_TOO_DEEP(nfa->v->re))
{
NERR(REG_ETOOBIG);
return lastfound;
}
s->tmp = lastfound;
lastfound = s;
for (a = inarcsorig[s->no]; a != NULL; a = a->inchain)
{
if (a->type == EMPTY && a->from->tmp == NULL)
lastfound = emptyreachable(nfa, a->from, lastfound, inarcsorig);
}
return lastfound;
}
/*
* isconstraintarc - detect whether an arc is of a constraint type
*/
static inline int
isconstraintarc(struct arc *a)
{
switch (a->type)
{
case '^':
case '$':
case BEHIND:
case AHEAD:
case LACON:
return 1;
}
return 0;
}
/*
* hasconstraintout - does state have a constraint out arc?
*/
static int
hasconstraintout(struct state *s)
{
struct arc *a;
for (a = s->outs; a != NULL; a = a->outchain)
{
if (isconstraintarc(a))
return 1;
}
return 0;
}
/*
* fixconstraintloops - get rid of loops containing only constraint arcs
*
* A loop of states that contains only constraint arcs is useless, since
* passing around the loop represents no forward progress. Moreover, it
* would cause infinite looping in pullback/pushfwd, so we need to get rid
* of such loops before doing that.
*/
static void
fixconstraintloops(struct nfa *nfa,
FILE *f) /* for debug output; NULL none */
{
struct state *s;
struct state *nexts;
struct arc *a;
struct arc *nexta;
int hasconstraints;
/*
* In the trivial case of a state that loops to itself, we can just drop
* the constraint arc altogether. This is worth special-casing because
* such loops are far more common than loops containing multiple states.
* While we're at it, note whether any constraint arcs survive.
*/
hasconstraints = 0;
for (s = nfa->states; s != NULL && !NISERR(); s = nexts)
{
nexts = s->next;
/* while we're at it, ensure tmp fields are clear for next step */
assert(s->tmp == NULL);
for (a = s->outs; a != NULL && !NISERR(); a = nexta)
{
nexta = a->outchain;
if (isconstraintarc(a))
{
if (a->to == s)
freearc(nfa, a);
else
hasconstraints = 1;
}
}
/* If we removed all the outarcs, the state is useless. */
if (s->nouts == 0 && !s->flag)
dropstate(nfa, s);
}
/* Nothing to do if no remaining constraint arcs */
if (NISERR() || !hasconstraints)
return;
/*
* Starting from each remaining NFA state, search outwards for a
* constraint loop. If we find a loop, break the loop, then start the
* search over. (We could possibly retain some state from the first scan,
* but it would complicate things greatly, and multi-state constraint
* loops are rare enough that it's not worth optimizing the case.)
*/
restart:
for (s = nfa->states; s != NULL && !NISERR(); s = s->next)
{
if (findconstraintloop(nfa, s))
goto restart;
}
if (NISERR())
return;
/*
* Now remove any states that have become useless. (This cleanup is not
* very thorough, and would be even less so if we tried to combine it with
* the previous step; but cleanup() will take care of anything we miss.)
*
* Because findconstraintloop intentionally doesn't reset all tmp fields,
* we have to clear them after it's done. This is a convenient place to
* do that, too.
*/
for (s = nfa->states; s != NULL; s = nexts)
{
nexts = s->next;
s->tmp = NULL;
if ((s->nins == 0 || s->nouts == 0) && !s->flag)
dropstate(nfa, s);
}
if (f != NULL)
dumpnfa(nfa, f);
}
/*
* findconstraintloop - recursively find a loop of constraint arcs
*
* If we find a loop, break it by calling breakconstraintloop(), then
* return 1; otherwise return 0.
*
* State tmp fields are guaranteed all NULL on a success return, because
* breakconstraintloop does that. After a failure return, any state that
* is known not to be part of a loop is marked with s->tmp == s; this allows
* us not to have to re-prove that fact on later calls. (This convention is
* workable because we already eliminated single-state loops.)
*
* Note that the found loop doesn't necessarily include the first state we
* are called on. Any loop reachable from that state will do.
*
* The maximum recursion depth here is one more than the length of the longest
* loop-free chain of constraint arcs, which is surely no more than the size
* of the NFA ... but that could still be enough to cause trouble.
*/
static int
findconstraintloop(struct nfa *nfa, struct state *s)
{
struct arc *a;
/* Since this is recursive, it could be driven to stack overflow */
if (STACK_TOO_DEEP(nfa->v->re))
{
NERR(REG_ETOOBIG);
return 1; /* to exit as quickly as possible */
}
if (s->tmp != NULL)
{
/* Already proven uninteresting? */
if (s->tmp == s)
return 0;
/* Found a loop involving s */
breakconstraintloop(nfa, s);
/* The tmp fields have been cleaned up by breakconstraintloop */
return 1;
}
for (a = s->outs; a != NULL; a = a->outchain)
{
if (isconstraintarc(a))
{
struct state *sto = a->to;
assert(sto != s);
s->tmp = sto;
if (findconstraintloop(nfa, sto))
return 1;
}
}
/*
* If we get here, no constraint loop exists leading out from s. Mark it
* with s->tmp == s so we need not rediscover that fact again later.
*/
s->tmp = s;
return 0;
}
/*
* breakconstraintloop - break a loop of constraint arcs
*
* sinitial is any one member state of the loop. Each loop member's tmp
* field links to its successor within the loop. (Note that this function
* will reset all the tmp fields to NULL.)
*
* We can break the loop by, for any one state S1 in the loop, cloning its
* loop successor state S2 (and possibly following states), and then moving
* all S1->S2 constraint arcs to point to the cloned S2. The cloned S2 should
* copy any non-constraint outarcs of S2. Constraint outarcs should be
* dropped if they point back to S1, else they need to be copied as arcs to
* similarly cloned states S3, S4, etc. In general, each cloned state copies
* non-constraint outarcs, drops constraint outarcs that would lead to itself
* or any earlier cloned state, and sends other constraint outarcs to newly
* cloned states. No cloned state will have any inarcs that aren't constraint
* arcs or do not lead from S1 or earlier-cloned states. It's okay to drop
* constraint back-arcs since they would not take us to any state we've not
* already been in; therefore, no new constraint loop is created. In this way
* we generate a modified NFA that can still represent every useful state
* sequence, but not sequences that represent state loops with no consumption
* of input data. Note that the set of cloned states will certainly include
* all of the loop member states other than S1, and it may also include
* non-loop states that are reachable from S2 via constraint arcs. This is
* important because there is no guarantee that findconstraintloop found a
* maximal loop (and searching for one would be NP-hard, so don't try).
* Frequently the "non-loop states" are actually part of a larger loop that
* we didn't notice, and indeed there may be several overlapping loops.
* This technique ensures convergence in such cases, while considering only
* the originally-found loop does not.
*
* If there is only one S1->S2 constraint arc, then that constraint is
* certainly satisfied when we enter any of the clone states. This means that
* in the common case where many of the constraint arcs are identically
* labeled, we can merge together clone states linked by a similarly-labeled
* constraint: if we can get to the first one we can certainly get to the
* second, so there's no need to distinguish. This greatly reduces the number
* of new states needed, so we preferentially break the given loop at a state
* pair where this is true.
*
* Furthermore, it's fairly common to find that a cloned successor state has
* no outarcs, especially if we're a bit aggressive about removing unnecessary
* outarcs. If that happens, then there is simply not any interesting state
* that can be reached through the predecessor's loop arcs, which means we can
* break the loop just by removing those loop arcs, with no new states added.
*/
static void
breakconstraintloop(struct nfa *nfa, struct state *sinitial)
{
struct state *s;
struct state *shead;
struct state *stail;
struct state *sclone;
struct state *nexts;
struct arc *refarc;
struct arc *a;
struct arc *nexta;
/*
* Start by identifying which loop step we want to break at.
* Preferentially this is one with only one constraint arc. (XXX are
* there any other secondary heuristics we want to use here?) Set refarc
* to point to the selected lone constraint arc, if there is one.
*/
refarc = NULL;
s = sinitial;
do
{
nexts = s->tmp;
assert(nexts != s); /* should not see any one-element loops */
if (refarc == NULL)
{
int narcs = 0;
for (a = s->outs; a != NULL; a = a->outchain)
{
if (a->to == nexts && isconstraintarc(a))
{
refarc = a;
narcs++;
}
}
assert(narcs > 0);
if (narcs > 1)
refarc = NULL; /* multiple constraint arcs here, no good */
}
s = nexts;
} while (s != sinitial);
if (refarc)
{
/* break at the refarc */
shead = refarc->from;
stail = refarc->to;
assert(stail == shead->tmp);
}
else
{
/* for lack of a better idea, break after sinitial */
shead = sinitial;
stail = sinitial->tmp;
}
/*
* Reset the tmp fields so that we can use them for local storage in
* clonesuccessorstates. (findconstraintloop won't mind, since it's just
* going to abandon its search anyway.)
*/
for (s = nfa->states; s != NULL; s = s->next)
s->tmp = NULL;
/*
* Recursively build clone state(s) as needed.
*/
sclone = newstate(nfa);
if (sclone == NULL)
{
assert(NISERR());
return;
}
clonesuccessorstates(nfa, stail, sclone, shead, refarc,
NULL, NULL, nfa->nstates);
if (NISERR())
return;
/*
* It's possible that sclone has no outarcs at all, in which case it's
* useless. (We don't try extremely hard to get rid of useless states
* here, but this is an easy and fairly common case.)
*/
if (sclone->nouts == 0)
{
freestate(nfa, sclone);
sclone = NULL;
}
/*
* Move shead's constraint-loop arcs to point to sclone, or just drop them
* if we discovered we don't need sclone.
*/
for (a = shead->outs; a != NULL; a = nexta)
{
nexta = a->outchain;
if (a->to == stail && isconstraintarc(a))
{
if (sclone)
cparc(nfa, a, shead, sclone);
freearc(nfa, a);
if (NISERR())
break;
}
}
}
/*
* clonesuccessorstates - create a tree of constraint-arc successor states
*
* ssource is the state to be cloned, and sclone is the state to copy its
* outarcs into. sclone's inarcs, if any, should already be set up.
*
* spredecessor is the original predecessor state that we are trying to build
* successors for (it may not be the immediate predecessor of ssource).
* refarc, if not NULL, is the original constraint arc that is known to have
* been traversed out of spredecessor to reach the successor(s).
*
* For each cloned successor state, we transiently create a "donemap" that is
* a boolean array showing which source states we've already visited for this
* clone state. This prevents infinite recursion as well as useless repeat
* visits to the same state subtree (which can add up fast, since typical NFAs
* have multiple redundant arc pathways). Each donemap is a char array
* indexed by state number. The donemaps are all of the same size "nstates",
* which is nfa->nstates as of the start of the recursion. This is enough to
* have entries for all pre-existing states, but *not* entries for clone
* states created during the recursion. That's okay since we have no need to
* mark those.
*
* curdonemap is NULL when recursing to a new sclone state, or sclone's
* donemap when we are recursing without having created a new state (which we
* do when we decide we can merge a successor state into the current clone
* state). outerdonemap is NULL at the top level and otherwise the parent
* clone state's donemap.
*
* The successor states we create and fill here form a strict tree structure,
* with each state having exactly one predecessor, except that the toplevel
* state has no inarcs as yet (breakconstraintloop will add its inarcs from
* spredecessor after we're done). Thus, we can examine sclone's inarcs back
* to the root, plus refarc if any, to identify the set of constraints already
* known valid at the current point. This allows us to avoid generating extra
* successor states.
*/
static void
clonesuccessorstates(struct nfa *nfa,
struct state *ssource,
struct state *sclone,
struct state *spredecessor,
struct arc *refarc,
char *curdonemap,
char *outerdonemap,
int nstates)
{
char *donemap;
struct arc *a;
/* Since this is recursive, it could be driven to stack overflow */
if (STACK_TOO_DEEP(nfa->v->re))
{
NERR(REG_ETOOBIG);
return;
}
/* If this state hasn't already got a donemap, create one */
donemap = curdonemap;
if (donemap == NULL)
{
donemap = (char *) MALLOC(nstates * sizeof(char));
if (donemap == NULL)
{
NERR(REG_ESPACE);
return;
}
if (outerdonemap != NULL)
{
/*
* Not at outermost recursion level, so copy the outer level's
* donemap; this ensures that we see states in process of being
* visited at outer levels, or already merged into predecessor
* states, as ones we shouldn't traverse back to.
*/
memcpy(donemap, outerdonemap, nstates * sizeof(char));
}
else
{
/* At outermost level, only spredecessor is off-limits */
memset(donemap, 0, nstates * sizeof(char));
assert(spredecessor->no < nstates);
donemap[spredecessor->no] = 1;
}
}
/* Mark ssource as visited in the donemap */
assert(ssource->no < nstates);
assert(donemap[ssource->no] == 0);
donemap[ssource->no] = 1;
/*
* We proceed by first cloning all of ssource's outarcs, creating new
* clone states as needed but not doing more with them than that. Then in
* a second pass, recurse to process the child clone states. This allows
* us to have only one child clone state per reachable source state, even
* when there are multiple outarcs leading to the same state. Also, when
* we do visit a child state, its set of inarcs is known exactly, which
* makes it safe to apply the constraint-is-already-checked optimization.
* Also, this ensures that we've merged all the states we can into the
* current clone before we recurse to any children, thus possibly saving
* them from making extra images of those states.
*
* While this function runs, child clone states of the current state are
* marked by setting their tmp fields to point to the original state they
* were cloned from. This makes it possible to detect multiple outarcs
* leading to the same state, and also makes it easy to distinguish clone
* states from original states (which will have tmp == NULL).
*/
for (a = ssource->outs; a != NULL && !NISERR(); a = a->outchain)
{
struct state *sto = a->to;
/*
* We do not consider cloning successor states that have no constraint
* outarcs; just link to them as-is. They cannot be part of a
* constraint loop so there is no need to make copies. In particular,
* this rule keeps us from trying to clone the post state, which would
* be a bad idea.
*/
if (isconstraintarc(a) && hasconstraintout(sto))
{
struct state *prevclone;
int canmerge;
struct arc *a2;
/*
* Back-link constraint arcs must not be followed. Nor is there a
* need to revisit states previously merged into this clone.
*/
assert(sto->no < nstates);
if (donemap[sto->no] != 0)
continue;
/*
* Check whether we already have a child clone state for this
* source state.
*/
prevclone = NULL;
for (a2 = sclone->outs; a2 != NULL; a2 = a2->outchain)
{
if (a2->to->tmp == sto)
{
prevclone = a2->to;
break;
}
}
/*
* If this arc is labeled the same as refarc, or the same as any
* arc we must have traversed to get to sclone, then no additional
* constraints need to be met to get to sto, so we should just
* merge its outarcs into sclone.
*/
if (refarc && a->type == refarc->type && a->co == refarc->co)
canmerge = 1;
else
{
struct state *s;
canmerge = 0;
for (s = sclone; s->ins; s = s->ins->from)
{
if (s->nins == 1 &&
a->type == s->ins->type && a->co == s->ins->co)
{
canmerge = 1;
break;
}
}
}
if (canmerge)
{
/*
* We can merge into sclone. If we previously made a child
* clone state, drop it; there's no need to visit it. (This
* can happen if ssource has multiple pathways to sto, and we
* only just now found one that is provably a no-op.)
*/
if (prevclone)
dropstate(nfa, prevclone); /* kills our outarc, too */
/* Recurse to merge sto's outarcs into sclone */
clonesuccessorstates(nfa,
sto,
sclone,
spredecessor,
refarc,
donemap,
outerdonemap,
nstates);
/* sto should now be marked as previously visited */
assert(NISERR() || donemap[sto->no] == 1);
}
else if (prevclone)
{
/*
* We already have a clone state for this successor, so just
* make another arc to it.
*/
cparc(nfa, a, sclone, prevclone);
}
else
{
/*
* We need to create a new successor clone state.
*/
struct state *stoclone;
stoclone = newstate(nfa);
if (stoclone == NULL)
{
assert(NISERR());
break;
}
/* Mark it as to what it's a clone of */
stoclone->tmp = sto;
/* ... and add the outarc leading to it */
cparc(nfa, a, sclone, stoclone);
}
}
else
{
/*
* Non-constraint outarcs just get copied to sclone, as do outarcs
* leading to states with no constraint outarc.
*/
cparc(nfa, a, sclone, sto);
}
}
/*
* If we are at outer level for this clone state, recurse to all its child
* clone states, clearing their tmp fields as we go. (If we're not
* outermost for sclone, leave this to be done by the outer call level.)
* Note that if we have multiple outarcs leading to the same clone state,
* it will only be recursed-to once.
*/
if (curdonemap == NULL)
{
for (a = sclone->outs; a != NULL && !NISERR(); a = a->outchain)
{
struct state *stoclone = a->to;
struct state *sto = stoclone->tmp;
if (sto != NULL)
{
stoclone->tmp = NULL;
clonesuccessorstates(nfa,
sto,
stoclone,
spredecessor,
refarc,
NULL,
donemap,
nstates);
}
}
/* Don't forget to free sclone's donemap when done with it */
FREE(donemap);
}
}
/*
* cleanup - clean up NFA after optimizations
*/
static void
cleanup(struct nfa *nfa)
{
struct state *s;
struct state *nexts;
int n;
if (NISERR())
return;
/* clear out unreachable or dead-end states */
/* use pre to mark reachable, then post to mark can-reach-post */
markreachable(nfa, nfa->pre, (struct state *) NULL, nfa->pre);
markcanreach(nfa, nfa->post, nfa->pre, nfa->post);
for (s = nfa->states; s != NULL && !NISERR(); s = nexts)
{
nexts = s->next;
if (s->tmp != nfa->post && !s->flag)
dropstate(nfa, s);
}
assert(NISERR() || nfa->post->nins == 0 || nfa->post->tmp == nfa->post);
cleartraverse(nfa, nfa->pre);
assert(NISERR() || nfa->post->nins == 0 || nfa->post->tmp == NULL);
/* the nins==0 (final unreachable) case will be caught later */
/* renumber surviving states */
n = 0;
for (s = nfa->states; s != NULL; s = s->next)
s->no = n++;
nfa->nstates = n;
}
/*
* markreachable - recursive marking of reachable states
*/
static void
markreachable(struct nfa *nfa,
struct state *s,
struct state *okay, /* consider only states with this mark */
struct state *mark) /* the value to mark with */
{
struct arc *a;
/* Since this is recursive, it could be driven to stack overflow */
if (STACK_TOO_DEEP(nfa->v->re))
{
NERR(REG_ETOOBIG);
return;
}
if (s->tmp != okay)
return;
s->tmp = mark;
for (a = s->outs; a != NULL; a = a->outchain)
markreachable(nfa, a->to, okay, mark);
}
/*
* markcanreach - recursive marking of states which can reach here
*/
static void
markcanreach(struct nfa *nfa,
struct state *s,
struct state *okay, /* consider only states with this mark */
struct state *mark) /* the value to mark with */
{
struct arc *a;
/* Since this is recursive, it could be driven to stack overflow */
if (STACK_TOO_DEEP(nfa->v->re))
{
NERR(REG_ETOOBIG);
return;
}
if (s->tmp != okay)
return;
s->tmp = mark;
for (a = s->ins; a != NULL; a = a->inchain)
markcanreach(nfa, a->from, okay, mark);
}
/*
* analyze - ascertain potentially-useful facts about an optimized NFA
*/
static long /* re_info bits to be ORed in */
analyze(struct nfa *nfa)
{
struct arc *a;
struct arc *aa;
if (NISERR())
return 0;
if (nfa->pre->outs == NULL)
return REG_UIMPOSSIBLE;
for (a = nfa->pre->outs; a != NULL; a = a->outchain)
for (aa = a->to->outs; aa != NULL; aa = aa->outchain)
if (aa->to == nfa->post)
return REG_UEMPTYMATCH;
return 0;
}
/*
* compact - construct the compact representation of an NFA
*/
static void
compact(struct nfa *nfa,
struct cnfa *cnfa)
{
struct state *s;
struct arc *a;
size_t nstates;
size_t narcs;
struct carc *ca;
struct carc *first;
assert(!NISERR());
nstates = 0;
narcs = 0;
for (s = nfa->states; s != NULL; s = s->next)
{
nstates++;
narcs += s->nouts + 1; /* need one extra for endmarker */
}
cnfa->stflags = (char *) MALLOC(nstates * sizeof(char));
cnfa->states = (struct carc **) MALLOC(nstates * sizeof(struct carc *));
cnfa->arcs = (struct carc *) MALLOC(narcs * sizeof(struct carc));
if (cnfa->stflags == NULL || cnfa->states == NULL || cnfa->arcs == NULL)
{
if (cnfa->stflags != NULL)
FREE(cnfa->stflags);
if (cnfa->states != NULL)
FREE(cnfa->states);
if (cnfa->arcs != NULL)
FREE(cnfa->arcs);
NERR(REG_ESPACE);
return;
}
cnfa->nstates = nstates;
cnfa->pre = nfa->pre->no;
cnfa->post = nfa->post->no;
cnfa->bos[0] = nfa->bos[0];
cnfa->bos[1] = nfa->bos[1];
cnfa->eos[0] = nfa->eos[0];
cnfa->eos[1] = nfa->eos[1];
cnfa->ncolors = maxcolor(nfa->cm) + 1;
cnfa->flags = 0;
ca = cnfa->arcs;
for (s = nfa->states; s != NULL; s = s->next)
{
assert((size_t) s->no < nstates);
cnfa->stflags[s->no] = 0;
cnfa->states[s->no] = ca;
first = ca;
for (a = s->outs; a != NULL; a = a->outchain)
switch (a->type)
{
case PLAIN:
ca->co = a->co;
ca->to = a->to->no;
ca++;
break;
case LACON:
assert(s->no != cnfa->pre);
ca->co = (color) (cnfa->ncolors + a->co);
ca->to = a->to->no;
ca++;
cnfa->flags |= HASLACONS;
break;
default:
NERR(REG_ASSERT);
break;
}
carcsort(first, ca - first);
ca->co = COLORLESS;
ca->to = 0;
ca++;
}
assert(ca == &cnfa->arcs[narcs]);
assert(cnfa->nstates != 0);
/* mark no-progress states */
for (a = nfa->pre->outs; a != NULL; a = a->outchain)
cnfa->stflags[a->to->no] = CNFA_NOPROGRESS;
cnfa->stflags[nfa->pre->no] = CNFA_NOPROGRESS;
}
/*
* carcsort - sort compacted-NFA arcs by color
*/
static void
carcsort(struct carc *first, size_t n)
{
if (n > 1)
qsort(first, n, sizeof(struct carc), carc_cmp);
}
static int
carc_cmp(const void *a, const void *b)
{
const struct carc *aa = (const struct carc *) a;
const struct carc *bb = (const struct carc *) b;
if (aa->co < bb->co)
return -1;
if (aa->co > bb->co)
return +1;
if (aa->to < bb->to)
return -1;
if (aa->to > bb->to)
return +1;
return 0;
}
/*
* freecnfa - free a compacted NFA
*/
static void
freecnfa(struct cnfa *cnfa)
{
assert(cnfa->nstates != 0); /* not empty already */
cnfa->nstates = 0;
FREE(cnfa->stflags);
FREE(cnfa->states);
FREE(cnfa->arcs);
}
/*
* dumpnfa - dump an NFA in human-readable form
*/
static void
dumpnfa(struct nfa *nfa,
FILE *f)
{
#ifdef REG_DEBUG
struct state *s;
int nstates = 0;
int narcs = 0;
fprintf(f, "pre %d, post %d", nfa->pre->no, nfa->post->no);
if (nfa->bos[0] != COLORLESS)
fprintf(f, ", bos [%ld]", (long) nfa->bos[0]);
if (nfa->bos[1] != COLORLESS)
fprintf(f, ", bol [%ld]", (long) nfa->bos[1]);
if (nfa->eos[0] != COLORLESS)
fprintf(f, ", eos [%ld]", (long) nfa->eos[0]);
if (nfa->eos[1] != COLORLESS)
fprintf(f, ", eol [%ld]", (long) nfa->eos[1]);
fprintf(f, "\n");
for (s = nfa->states; s != NULL; s = s->next)
{
dumpstate(s, f);
nstates++;
narcs += s->nouts;
}
fprintf(f, "total of %d states, %d arcs\n", nstates, narcs);
if (nfa->parent == NULL)
dumpcolors(nfa->cm, f);
fflush(f);
#endif
}
#ifdef REG_DEBUG /* subordinates of dumpnfa */
/*
* dumpstate - dump an NFA state in human-readable form
*/
static void
dumpstate(struct state *s,
FILE *f)
{
struct arc *a;
fprintf(f, "%d%s%c", s->no, (s->tmp != NULL) ? "T" : "",
(s->flag) ? s->flag : '.');
if (s->prev != NULL && s->prev->next != s)
fprintf(f, "\tstate chain bad\n");
if (s->nouts == 0)
fprintf(f, "\tno out arcs\n");
else
dumparcs(s, f);
fflush(f);
for (a = s->ins; a != NULL; a = a->inchain)
{
if (a->to != s)
fprintf(f, "\tlink from %d to %d on %d's in-chain\n",
a->from->no, a->to->no, s->no);
}
}
/*
* dumparcs - dump out-arcs in human-readable form
*/
static void
dumparcs(struct state *s,
FILE *f)
{
int pos;
struct arc *a;
/* printing oldest arcs first is usually clearer */
a = s->outs;
assert(a != NULL);
while (a->outchain != NULL)
a = a->outchain;
pos = 1;
do
{
dumparc(a, s, f);
if (pos == 5)
{
fprintf(f, "\n");
pos = 1;
}
else
pos++;
a = a->outchainRev;
} while (a != NULL);
if (pos != 1)
fprintf(f, "\n");
}
/*
* dumparc - dump one outarc in readable form, including prefixing tab
*/
static void
dumparc(struct arc *a,
struct state *s,
FILE *f)
{
struct arc *aa;
struct arcbatch *ab;
fprintf(f, "\t");
switch (a->type)
{
case PLAIN:
fprintf(f, "[%ld]", (long) a->co);
break;
case AHEAD:
fprintf(f, ">%ld>", (long) a->co);
break;
case BEHIND:
fprintf(f, "<%ld<", (long) a->co);
break;
case LACON:
fprintf(f, ":%ld:", (long) a->co);
break;
case '^':
case '$':
fprintf(f, "%c%d", a->type, (int) a->co);
break;
case EMPTY:
break;
default:
fprintf(f, "0x%x/0%lo", a->type, (long) a->co);
break;
}
if (a->from != s)
fprintf(f, "?%d?", a->from->no);
for (ab = &a->from->oas; ab != NULL; ab = ab->next)
{
for (aa = &ab->a[0]; aa < &ab->a[ABSIZE]; aa++)
if (aa == a)
break; /* NOTE BREAK OUT */
if (aa < &ab->a[ABSIZE]) /* propagate break */
break; /* NOTE BREAK OUT */
}
if (ab == NULL)
fprintf(f, "?!?"); /* not in allocated space */
fprintf(f, "->");
if (a->to == NULL)
{
fprintf(f, "NULL");
return;
}
fprintf(f, "%d", a->to->no);
for (aa = a->to->ins; aa != NULL; aa = aa->inchain)
if (aa == a)
break; /* NOTE BREAK OUT */
if (aa == NULL)
fprintf(f, "?!?"); /* missing from in-chain */
}
#endif /* REG_DEBUG */
/*
* dumpcnfa - dump a compacted NFA in human-readable form
*/
#ifdef REG_DEBUG
static void
dumpcnfa(struct cnfa *cnfa,
FILE *f)
{
int st;
fprintf(f, "pre %d, post %d", cnfa->pre, cnfa->post);
if (cnfa->bos[0] != COLORLESS)
fprintf(f, ", bos [%ld]", (long) cnfa->bos[0]);
if (cnfa->bos[1] != COLORLESS)
fprintf(f, ", bol [%ld]", (long) cnfa->bos[1]);
if (cnfa->eos[0] != COLORLESS)
fprintf(f, ", eos [%ld]", (long) cnfa->eos[0]);
if (cnfa->eos[1] != COLORLESS)
fprintf(f, ", eol [%ld]", (long) cnfa->eos[1]);
if (cnfa->flags & HASLACONS)
fprintf(f, ", haslacons");
fprintf(f, "\n");
for (st = 0; st < cnfa->nstates; st++)
dumpcstate(st, cnfa, f);
fflush(f);
}
#endif
#ifdef REG_DEBUG /* subordinates of dumpcnfa */
/*
* dumpcstate - dump a compacted-NFA state in human-readable form
*/
static void
dumpcstate(int st,
struct cnfa *cnfa,
FILE *f)
{
struct carc *ca;
int pos;
fprintf(f, "%d%s", st, (cnfa->stflags[st] & CNFA_NOPROGRESS) ? ":" : ".");
pos = 1;
for (ca = cnfa->states[st]; ca->co != COLORLESS; ca++)
{
if (ca->co < cnfa->ncolors)
fprintf(f, "\t[%ld]->%d", (long) ca->co, ca->to);
else
fprintf(f, "\t:%ld:->%d", (long) (ca->co - cnfa->ncolors), ca->to);
if (pos == 5)
{
fprintf(f, "\n");
pos = 1;
}
else
pos++;
}
if (ca == cnfa->states[st] || pos != 1)
fprintf(f, "\n");
fflush(f);
}
#endif /* REG_DEBUG */
| {
"content_hash": "31105b6b6f05ce6fcddf89608395fd56",
"timestamp": "",
"source": "github",
"line_count": 3145,
"max_line_length": 78,
"avg_line_length": 25.11001589825119,
"alnum_prop": 0.626255207607856,
"repo_name": "lisakowen/gpdb",
"id": "92c9c4d795d1a4d32a4677c4e00e25123506b072",
"size": "80681",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "src/backend/regex/regc_nfa.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3266"
},
{
"name": "Awk",
"bytes": "836"
},
{
"name": "Batchfile",
"bytes": "15613"
},
{
"name": "C",
"bytes": "48331196"
},
{
"name": "C++",
"bytes": "12756630"
},
{
"name": "CMake",
"bytes": "41334"
},
{
"name": "DTrace",
"bytes": "3833"
},
{
"name": "Emacs Lisp",
"bytes": "4164"
},
{
"name": "Fortran",
"bytes": "14873"
},
{
"name": "GDB",
"bytes": "576"
},
{
"name": "Gherkin",
"bytes": "497626"
},
{
"name": "HTML",
"bytes": "215381"
},
{
"name": "JavaScript",
"bytes": "23969"
},
{
"name": "Lex",
"bytes": "254578"
},
{
"name": "M4",
"bytes": "133878"
},
{
"name": "Makefile",
"bytes": "510527"
},
{
"name": "PLpgSQL",
"bytes": "9268532"
},
{
"name": "Perl",
"bytes": "1161283"
},
{
"name": "PowerShell",
"bytes": "422"
},
{
"name": "Python",
"bytes": "3396518"
},
{
"name": "Roff",
"bytes": "30385"
},
{
"name": "Ruby",
"bytes": "299639"
},
{
"name": "SCSS",
"bytes": "339"
},
{
"name": "Shell",
"bytes": "404184"
},
{
"name": "XS",
"bytes": "7098"
},
{
"name": "XSLT",
"bytes": "448"
},
{
"name": "Yacc",
"bytes": "747692"
},
{
"name": "sed",
"bytes": "1231"
}
],
"symlink_target": ""
} |
package org.springframework.boot.actuate.autoconfigure.amqp;
import org.junit.Test;
import org.springframework.boot.actuate.amqp.RabbitHealthIndicator;
import org.springframework.boot.actuate.autoconfigure.health.HealthIndicatorAutoConfiguration;
import org.springframework.boot.actuate.health.ApplicationHealthIndicator;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link RabbitHealthIndicatorAutoConfiguration}.
*
* @author Phillip Webb
*/
public class RabbitHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class,
RabbitHealthIndicatorAutoConfiguration.class,
HealthIndicatorAutoConfiguration.class));
@Test
public void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context)
.hasSingleBean(RabbitHealthIndicator.class)
.doesNotHaveBean(ApplicationHealthIndicator.class));
}
@Test
public void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.rabbit.enabled:false")
.run((context) -> assertThat(context)
.doesNotHaveBean(RabbitHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class));
}
}
| {
"content_hash": "0d85cd18c947b6ec5ec867e1ccac6bdf",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 94,
"avg_line_length": 35.72093023255814,
"alnum_prop": 0.8248697916666666,
"repo_name": "hello2009chen/spring-boot",
"id": "dad54f968eef2793bd40d7fc0e2fec8b0c5b02aa",
"size": "2156",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1948"
},
{
"name": "CSS",
"bytes": "5774"
},
{
"name": "Groovy",
"bytes": "46492"
},
{
"name": "HTML",
"bytes": "70389"
},
{
"name": "Java",
"bytes": "7092425"
},
{
"name": "JavaScript",
"bytes": "37789"
},
{
"name": "Ruby",
"bytes": "1305"
},
{
"name": "SQLPL",
"bytes": "20085"
},
{
"name": "Shell",
"bytes": "8165"
},
{
"name": "Smarty",
"bytes": "3276"
},
{
"name": "XSLT",
"bytes": "33894"
}
],
"symlink_target": ""
} |
set( MANIFEST
${SOURCE_DIR}/totalisator.cpp
${SOURCE_DIR}/detail/totalisator_impl.cpp
)
| {
"content_hash": "ddea622df92e8bfcc4765d9f9e226581",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 46,
"avg_line_length": 24.5,
"alnum_prop": 0.6836734693877551,
"repo_name": "ben-crowhurst/tote-betting-totalisator",
"id": "3320aadc4f8b21efc6bffe6038d9f7f3b97f6375",
"size": "99",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cmake/manifest.cmake",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "23295"
},
{
"name": "CMake",
"bytes": "5511"
},
{
"name": "Shell",
"bytes": "2059"
}
],
"symlink_target": ""
} |
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Information about MPEG-4 files, Descriptors
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
#ifndef MediaInfo_Mpeg4_DescriptorsH
#define MediaInfo_Mpeg4_DescriptorsH
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/File__Analyze.h"
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
enum audio_profile
{
NoProfile,
Main_Audio,
Scalable_Audio,
Speech_Audio,
Synthesis_Audio,
High_Quality_Audio,
Low_Delay_Audio,
Natural_Audio,
Mobile_Audio_Internetworking,
AAC,
High_Efficiency_AAC,
High_Efficiency_AAC_v2,
Low_Delay_AAC,
Baseline_MPEG_Surround,
High_Definition_AAC,
ALS_Simple,
Baseline_USAC,
Extended_HE_AAC,
AudioProfile_Max,
#if MEDIAINFO_CONFORMANCE
AudioProfile_Unspecified,
AudioProfile_NoAudio,
#endif
};
struct profilelevel_struct
{
audio_profile profile;
int8u level;
};
//***************************************************************************
// Class File_Mpeg4_Descriptors
//***************************************************************************
class File_Mpeg4_Descriptors : public File__Analyze
{
public :
//In
stream_t KindOfStream;
size_t PosOfStream;
bool Parser_DoNotFreeIt; //If you want to keep the Parser
bool SLConfig_DoNotFreeIt; //If you want to keep the SLConfig
//Out
File__Analyze* Parser;
int16u ES_ID;
struct es_id_info
{
stream_t StreamKind;
Ztring ProfileLevelString;
int8u ProfileLevel[5];
es_id_info() :
StreamKind(Stream_Max)
{}
};
typedef map<int32u, es_id_info> es_id_infos;
es_id_infos ES_ID_Infos;
// Conformance
#if MEDIAINFO_CONFORMANCE
int16u SamplingRate;
#endif
struct slconfig
{
bool useAccessUnitStartFlag;
bool useAccessUnitEndFlag;
bool useRandomAccessPointFlag;
bool hasRandomAccessUnitsOnlyFlag;
bool usePaddingFlag;
bool useTimeStampsFlag;
bool useIdleFlag;
bool durationFlag;
int32u timeStampResolution;
int32u OCRResolution;
int8u timeStampLength;
int8u OCRLength;
int8u AU_Length;
int8u instantBitrateLength;
int8u degradationPriorityLength;
int8u AU_seqNumLength;
int8u packetSeqNumLength;
int32u timeScale;
int16u accessUnitDuration;
int16u compositionUnitDuration;
int64u startDecodingTimeStamp;
int64u startCompositionTimeStamp;
};
slconfig* SLConfig;
public :
//Constructor/Destructor
File_Mpeg4_Descriptors();
~File_Mpeg4_Descriptors();
private :
//Buffer
void Header_Parse();
void Data_Parse();
//Elements
void Descriptor_00() {Skip_XX(Element_Size, "Data");};
void Descriptor_01();
void Descriptor_02() {Descriptor_01();}
void Descriptor_03();
void Descriptor_04();
void Descriptor_05();
void Descriptor_06();
void Descriptor_07() {Skip_XX(Element_Size, "Data");};
void Descriptor_08() {Skip_XX(Element_Size, "Data");};
void Descriptor_09();
void Descriptor_0A() {Skip_XX(Element_Size, "Data");};
void Descriptor_0B() {Skip_XX(Element_Size, "Data");};
void Descriptor_0C() {Skip_XX(Element_Size, "Data");};
void Descriptor_0D() {Skip_XX(Element_Size, "Data");};
void Descriptor_0E();
void Descriptor_0F();
void Descriptor_10();
void Descriptor_11();
void Descriptor_12() {Skip_XX(Element_Size, "Data");};
void Descriptor_13() {Skip_XX(Element_Size, "Data");};
void Descriptor_14() {Skip_XX(Element_Size, "Data");};
void Descriptor_40() {Skip_XX(Element_Size, "Data");};
void Descriptor_41() {Skip_XX(Element_Size, "Data");};
void Descriptor_42() {Skip_XX(Element_Size, "Data");};
void Descriptor_43() {Skip_XX(Element_Size, "Data");};
void Descriptor_44() {Skip_XX(Element_Size, "Data");};
void Descriptor_45() {Skip_XX(Element_Size, "Data");};
void Descriptor_46() {Skip_XX(Element_Size, "Data");};
void Descriptor_47() {Skip_XX(Element_Size, "Data");};
void Descriptor_48() {Skip_XX(Element_Size, "Data");};
void Descriptor_49() {Skip_XX(Element_Size, "Data");};
void Descriptor_4A() {Skip_XX(Element_Size, "Data");};
void Descriptor_4B() {Skip_XX(Element_Size, "Data");};
void Descriptor_4C() {Skip_XX(Element_Size, "Data");};
void Descriptor_60() {Skip_XX(Element_Size, "Data");};
void Descriptor_61() {Skip_XX(Element_Size, "Data");};
void Descriptor_62() {Skip_XX(Element_Size, "Data");};
void Descriptor_63() {Skip_XX(Element_Size, "Data");};
void Descriptor_64() {Skip_XX(Element_Size, "Data");};
void Descriptor_65() {Skip_XX(Element_Size, "Data");};
void Descriptor_66() {Skip_XX(Element_Size, "Data");};
void Descriptor_67() {Skip_XX(Element_Size, "Data");};
void Descriptor_68() {Skip_XX(Element_Size, "Data");};
void Descriptor_69() {Skip_XX(Element_Size, "Data");};
//Temp
int8u ObjectTypeId;
};
} //NameSpace
#endif
| {
"content_hash": "ea18477ccf9ec909105e0db5768b06a8",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 77,
"avg_line_length": 31.553072625698324,
"alnum_prop": 0.5440864022662889,
"repo_name": "MediaArea/MediaInfoLib",
"id": "026fa65c33e52e6cc941295c96044f2f98132054",
"size": "5859",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/MediaInfo/Multiple/File_Mpeg4_Descriptors.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP.NET",
"bytes": "7721"
},
{
"name": "AutoIt",
"bytes": "5982"
},
{
"name": "Batchfile",
"bytes": "48643"
},
{
"name": "C",
"bytes": "50514"
},
{
"name": "C#",
"bytes": "108365"
},
{
"name": "C++",
"bytes": "11178253"
},
{
"name": "CMake",
"bytes": "29075"
},
{
"name": "HTML",
"bytes": "12031"
},
{
"name": "Java",
"bytes": "117793"
},
{
"name": "JavaScript",
"bytes": "5140"
},
{
"name": "Kotlin",
"bytes": "4606"
},
{
"name": "M4",
"bytes": "81392"
},
{
"name": "Makefile",
"bytes": "21863"
},
{
"name": "NSIS",
"bytes": "11873"
},
{
"name": "Pascal",
"bytes": "13620"
},
{
"name": "PureBasic",
"bytes": "13384"
},
{
"name": "Python",
"bytes": "54732"
},
{
"name": "QMake",
"bytes": "26782"
},
{
"name": "Shell",
"bytes": "51652"
},
{
"name": "VBA",
"bytes": "10256"
},
{
"name": "VBScript",
"bytes": "2771"
},
{
"name": "Visual Basic .NET",
"bytes": "24066"
},
{
"name": "Visual Basic 6.0",
"bytes": "9861"
}
],
"symlink_target": ""
} |
$(function () { SUBMITTER.options.init(); });
| {
"content_hash": "6805879e366edff8fd239dedcaf63cab",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 45,
"avg_line_length": 46,
"alnum_prop": 0.6086956521739131,
"repo_name": "pshevtsov/chrome-submitter",
"id": "2ee5a8a8e9a64219d4322ad0e48f5aacaf809c2f",
"size": "46",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/options-init.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "56"
},
{
"name": "CSS",
"bytes": "14083"
},
{
"name": "JavaScript",
"bytes": "28431"
},
{
"name": "Shell",
"bytes": "978"
}
],
"symlink_target": ""
} |
package org.springframework.cloud.cli.command.url;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* Capture output from System.out and System.err.
*
* @author Phillip Webb
*/
public class OutputCapture implements TestRule {
private CaptureOutputStream captureOut;
private CaptureOutputStream captureErr;
private ByteArrayOutputStream copy;
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
captureOutput();
try {
base.evaluate();
}
finally {
releaseOutput();
}
}
};
}
protected void captureOutput() {
this.copy = new ByteArrayOutputStream();
this.captureOut = new CaptureOutputStream(System.out, this.copy);
this.captureErr = new CaptureOutputStream(System.err, this.copy);
System.setOut(new PrintStream(this.captureOut));
System.setErr(new PrintStream(this.captureErr));
}
protected void releaseOutput() {
System.setOut(this.captureOut.getOriginal());
System.setErr(this.captureErr.getOriginal());
this.copy = null;
}
public void flush() {
try {
this.captureOut.flush();
this.captureErr.flush();
}
catch (IOException ex) {
// ignore
}
}
@Override
public String toString() {
flush();
return this.copy.toString();
}
private static class CaptureOutputStream extends OutputStream {
private final PrintStream original;
private final OutputStream copy;
CaptureOutputStream(PrintStream original, OutputStream copy) {
this.original = original;
this.copy = copy;
}
@Override
public void write(int b) throws IOException {
this.copy.write(b);
this.original.write(b);
this.original.flush();
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.copy.write(b, off, len);
this.original.write(b, off, len);
}
public PrintStream getOriginal() {
return this.original;
}
@Override
public void flush() throws IOException {
this.copy.flush();
this.original.flush();
}
}
}
| {
"content_hash": "633d632be8163e16b4008ef63c9fcc93",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 72,
"avg_line_length": 20.893805309734514,
"alnum_prop": 0.7098686997035154,
"repo_name": "spring-cloud/spring-cloud-cli",
"id": "fcb141ee799cf303180bdf9988766c24fd7c77f0",
"size": "2982",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "spring-cloud-cli/src/test/java/org/springframework/cloud/cli/command/url/OutputCapture.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "664"
},
{
"name": "Java",
"bytes": "126530"
},
{
"name": "Ruby",
"bytes": "454"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2012 Google 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-parent</artifactId>
<!--<version>0.13.1-FAIRPAY</version>-->
<version>0.13.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>bitcoinj-tools</artifactId>
<name>bitcoinj Tools</name>
<description>A collection of useful tools that use the bitcoinj library to perform wallet operations</description>
<build>
<plugins>
<!-- Create wallet-tool.jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<!-- Remove dead classes -->
<minimizeJar>true</minimizeJar>
<filters>
<filter>
<!-- exclude signatures, the bundling process breaks them for some reason -->
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.bitcoinj.tools.WalletTool</mainClass>
</transformer>
</transformers>
<outputFile>target/wallet-tool.jar</outputFile>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jopt-simple</groupId>
<artifactId>jopt-simple</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.167</version>
</dependency>
</dependencies>
</project>
| {
"content_hash": "84a664716121c1f6e4282c3f9e235460",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 120,
"avg_line_length": 36.01020408163265,
"alnum_prop": 0.5613488240294701,
"repo_name": "seoulcoin/seoulcoin-bitcoinj",
"id": "dcbf9c7c2a0583f9ffe4a350f95cbaedb74db918",
"size": "3529",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1838"
},
{
"name": "Java",
"bytes": "4267453"
},
{
"name": "Protocol Buffer",
"bytes": "37938"
}
],
"symlink_target": ""
} |
import * as assert from 'assert'
import { symbol, InvalidSymbolError } from '../../rulr'
test('symbol should allow symbol', () => {
const input = Symbol()
const output: symbol = symbol(input)
assert.strictEqual(output, input)
})
test('symbol should allow non-symbol value', () => {
assert.throws(() => symbol(''), InvalidSymbolError)
})
| {
"content_hash": "c824b1644176800ea3e685959c4d64f8",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 55,
"avg_line_length": 28.583333333333332,
"alnum_prop": 0.6763848396501457,
"repo_name": "ryansmith94/rulr",
"id": "ba80ea960ee91cbab86aa157e1dbd32c59e92ee9",
"size": "343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/valueRules/symbol/symbol.test.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "238"
},
{
"name": "TypeScript",
"bytes": "89960"
}
],
"symlink_target": ""
} |
title: 25/09/17
layout: post
author: nivethan.thavaraj
permalink: /25/09/17/
source-id: 1Qhg-cAT0tXW8X65EkvooqjIhOe29uD3jjQEzKO8D54w
published: true
---
<table>
<tr>
<td>25/09/17</td>
</tr>
<tr>
<td>Coding with sheets
</td>
</tr>
<tr>
<td>Today we carried on with our 'Order Form' sheet. Today we added some new sections which were: Subtotal, Delivery, Discount, VAT and Grandtotal. The delivery and VAT costs were the easiest parts as all we needed to do was multiply the number by a negative or decimal number to subtract a certain amount off the total. However, the discount was the harder part. The discount took a very long time as it there was many steps to getting the actual code. First we had to create a random code which was very easy but it had to have a specific start for the first two letters or numbers. This would make it easier to validate the discount codes. We created a table which had a code’s beginning two figures and the how much the discount was for that code. We validated the code by using the =LEFT formula and found out the first two figures of the code. Then we put in that discount into the discount section.
</td>
</tr>
</table>
| {
"content_hash": "bf79e6a68ac67b815afb59192c53faa9",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 909,
"avg_line_length": 49.583333333333336,
"alnum_prop": 0.7504201680672269,
"repo_name": "me-and-IT/me-and-it.github.io",
"id": "db87c75817b36f3725976b4eed04260cefb41422",
"size": "1196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2017-10-25-25/09/17.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "63405"
},
{
"name": "HTML",
"bytes": "6248"
}
],
"symlink_target": ""
} |
This is very much an educational project in javascript heavy web apps. This is my attempt at creating a simple launch list web app. There are many check list apps out there but this is mine. I wouldn't take anything here and use in production as I'm new to js heavy apps, js templates, Backbone.js, etc. This is a personal experiment app.
I'm using Backbone.js along with localStorage to store tasks. Currently the app is very much incomplete.
## License
MIT Licensed | {
"content_hash": "446274765f21d29ee82683f3c4b26c29",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 338,
"avg_line_length": 67.14285714285714,
"alnum_prop": 0.7851063829787234,
"repo_name": "fleeting/Launch-Status-Check",
"id": "b2ef2fb62abb322c5896a0e663c361748819f318",
"size": "491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "readme.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "92384"
}
],
"symlink_target": ""
} |
package com.iflytek.rocket.spark.streaming
import com.iflytek.rocket.uitl.KafkaProducer
import org.apache.spark.streaming._
import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.streaming.kafka._
import org.apache.spark.SparkConf
import java.util.Calendar
//import spray.json._
//import DefaultJsonProtocol._
case class ViewTrace(user: String, action: String, productId: String, productType: String)
//object ViewTraceProtocol extends DefaultJsonProtocol {
// implicit val viewTraceFormat = jsonFormat4(ViewTrace)
//}
object Kafka {
def main(args: Array[String]) {
StreamingLogger.setStreamingLogLevels();
//val Array(zkQuorum, group, topics, numThreads) = args
val zkQuorum = "localhost:2181"
val group = "test-group"
val topics = "test"
val numThreads = 2
val sparkConf = new SparkConf().setAppName("KafkaWordCount").setMaster("local[*]")
val ssc = new StreamingContext(sparkConf, Seconds(2))
ssc.checkpoint("checkpoint")
val topicMap = topics.split(" ").map((_,numThreads.toInt)).toMap
val stream = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap);
//import ViewTraceProtocol._
//val traces = stream.map(_._2.parseJson.convertTo[ViewTrace])
//
// val pv = traces.map(x => (x.productType, 1)).reduceByKey(_ + _).map(
// x => (Calendar.getInstance().getTime().toString(), x._1, "PV", x._2)).map(_.toString())
// pv.foreachRDD( rdd =>
// rdd.foreachPartition(partitionOfRecords => {
// val producer = new KafkaProducer("stats", "localhost:9092")
// partitionOfRecords.foreach(record => producer.send(record.toString))
// })
// );
//
// val uv_grpd = traces.map(x => (x.productType, Set(x.user))).groupByKey();
// val uv = uv_grpd.foreachRDD(rdd => {
// rdd.filter(_._2.size > 0)
// .map(x => (Calendar.getInstance().getTime().toString(), x._1, "UV", x._2.size))
// .foreachPartition(partitionOfRecords => {
// val producer = new KafkaProducer("stats", "localhost:9092")
// partitionOfRecords.foreach(record => producer.send(record.toString))
// })
// }
// )
ssc.start()
ssc.awaitTermination()
}
} | {
"content_hash": "5d8e23317ead7e3790a86ccaab04855e",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 95,
"avg_line_length": 36.483333333333334,
"alnum_prop": 0.6683417085427136,
"repo_name": "seawalkermiaoer/rocket",
"id": "450c770e678e611b8f91e53edbcdb9d673956919",
"size": "2189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "streaming/project/src/main/scala/com/iflytek/rocket/spark/streaming/Kafka.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "110"
},
{
"name": "HTML",
"bytes": "908"
},
{
"name": "JavaScript",
"bytes": "7683"
},
{
"name": "Scala",
"bytes": "5313"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("04.Rectangles")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04.Rectangles")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cb58c872-f51d-4509-921c-e5b72dfa6ab5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "5b86d243b2e27fc6596544b2750930cd",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.861111111111114,
"alnum_prop": 0.7441029306647605,
"repo_name": "b-slavov/Telerik-Software-Academy",
"id": "5c2bec700d56f06eb873bc0eaf22ca3ada9c945f",
"size": "1402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "01.C# Part 1/03.Operators-and-Expressions/04.Rectangles/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "775"
},
{
"name": "Batchfile",
"bytes": "19"
},
{
"name": "C#",
"bytes": "3486914"
},
{
"name": "CSS",
"bytes": "125546"
},
{
"name": "HTML",
"bytes": "258600"
},
{
"name": "JavaScript",
"bytes": "519510"
},
{
"name": "SQLPL",
"bytes": "4671"
},
{
"name": "XSLT",
"bytes": "2997"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.