code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
#!/usr/bin/env python
# Copyright (c) 2012 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.
"""Tests for jni_generator.py.
This test suite contains various tests for the JNI generator.
It exercises the low-level parser all the way up to the
code generator and ensures the output matches a golden
file.
"""
import difflib
import inspect
import optparse
import os
import sys
import unittest
import jni_generator
from jni_generator import CalledByNative, JniParams, NativeMethod, Param
SCRIPT_NAME = 'base/android/jni_generator/jni_generator.py'
INCLUDES = (
'base/android/jni_generator/jni_generator_helper.h'
)
# Set this environment variable in order to regenerate the golden text
# files.
REBASELINE_ENV = 'REBASELINE'
class TestOptions(object):
"""The mock options object which is passed to the jni_generator.py script."""
def __init__(self):
self.namespace = None
self.script_name = SCRIPT_NAME
self.includes = INCLUDES
self.ptr_type = 'long'
self.cpp = 'cpp'
self.javap = 'javap'
self.native_exports = False
self.native_exports_optional = False
class TestGenerator(unittest.TestCase):
def assertObjEquals(self, first, second):
dict_first = first.__dict__
dict_second = second.__dict__
self.assertEquals(dict_first.keys(), dict_second.keys())
for key, value in dict_first.iteritems():
if (type(value) is list and len(value) and
isinstance(type(value[0]), object)):
self.assertListEquals(value, second.__getattribute__(key))
else:
actual = second.__getattribute__(key)
self.assertEquals(value, actual,
'Key ' + key + ': ' + str(value) + '!=' + str(actual))
def assertListEquals(self, first, second):
self.assertEquals(len(first), len(second))
for i in xrange(len(first)):
if isinstance(first[i], object):
self.assertObjEquals(first[i], second[i])
else:
self.assertEquals(first[i], second[i])
def assertTextEquals(self, golden_text, generated_text):
if not self.compareText(golden_text, generated_text):
self.fail('Golden text mismatch.')
def compareText(self, golden_text, generated_text):
def FilterText(text):
return [
l.strip() for l in text.split('\n')
if not l.startswith('// Copyright')
]
stripped_golden = FilterText(golden_text)
stripped_generated = FilterText(generated_text)
if stripped_golden == stripped_generated:
return True
print self.id()
for line in difflib.context_diff(stripped_golden, stripped_generated):
print line
print '\n\nGenerated'
print '=' * 80
print generated_text
print '=' * 80
print 'Run with:'
print 'REBASELINE=1', sys.argv[0]
print 'to regenerate the data files.'
def _ReadGoldenFile(self, golden_file):
if not os.path.exists(golden_file):
return None
with file(golden_file, 'r') as f:
return f.read()
def assertGoldenTextEquals(self, generated_text):
script_dir = os.path.dirname(sys.argv[0])
# This is the caller test method.
caller = inspect.stack()[1][3]
self.assertTrue(caller.startswith('test'),
'assertGoldenTextEquals can only be called from a '
'test* method, not %s' % caller)
golden_file = os.path.join(script_dir, caller + '.golden')
golden_text = self._ReadGoldenFile(golden_file)
if os.environ.get(REBASELINE_ENV):
if golden_text != generated_text:
with file(golden_file, 'w') as f:
f.write(generated_text)
return
self.assertTextEquals(golden_text, generated_text)
def testInspectCaller(self):
def willRaise():
# This function can only be called from a test* method.
self.assertGoldenTextEquals('')
self.assertRaises(AssertionError, willRaise)
def testNatives(self):
test_data = """"
interface OnFrameAvailableListener {}
private native int nativeInit();
private native void nativeDestroy(int nativeChromeBrowserProvider);
private native long nativeAddBookmark(
int nativeChromeBrowserProvider,
String url, String title, boolean isFolder, long parentId);
private static native String nativeGetDomainAndRegistry(String url);
private static native void nativeCreateHistoricalTabFromState(
byte[] state, int tab_index);
private native byte[] nativeGetStateAsByteArray(View view);
private static native String[] nativeGetAutofillProfileGUIDs();
private native void nativeSetRecognitionResults(
int sessionId, String[] results);
private native long nativeAddBookmarkFromAPI(
int nativeChromeBrowserProvider,
String url, Long created, Boolean isBookmark,
Long date, byte[] favicon, String title, Integer visits);
native int nativeFindAll(String find);
private static native OnFrameAvailableListener nativeGetInnerClass();
private native Bitmap nativeQueryBitmap(
int nativeChromeBrowserProvider,
String[] projection, String selection,
String[] selectionArgs, String sortOrder);
private native void nativeGotOrientation(
int nativeDataFetcherImplAndroid,
double alpha, double beta, double gamma);
private static native Throwable nativeMessWithJavaException(Throwable e);
"""
jni_generator.JniParams.SetFullyQualifiedClass(
'org/chromium/example/jni_generator/SampleForTests')
jni_generator.JniParams.ExtractImportsAndInnerClasses(test_data)
natives = jni_generator.ExtractNatives(test_data, 'int')
golden_natives = [
NativeMethod(return_type='int', static=False,
name='Init',
params=[],
java_class_name=None,
type='function'),
NativeMethod(return_type='void', static=False, name='Destroy',
params=[Param(datatype='int',
name='nativeChromeBrowserProvider')],
java_class_name=None,
type='method',
p0_type='ChromeBrowserProvider'),
NativeMethod(return_type='long', static=False, name='AddBookmark',
params=[Param(datatype='int',
name='nativeChromeBrowserProvider'),
Param(datatype='String',
name='url'),
Param(datatype='String',
name='title'),
Param(datatype='boolean',
name='isFolder'),
Param(datatype='long',
name='parentId')],
java_class_name=None,
type='method',
p0_type='ChromeBrowserProvider'),
NativeMethod(return_type='String', static=True,
name='GetDomainAndRegistry',
params=[Param(datatype='String',
name='url')],
java_class_name=None,
type='function'),
NativeMethod(return_type='void', static=True,
name='CreateHistoricalTabFromState',
params=[Param(datatype='byte[]',
name='state'),
Param(datatype='int',
name='tab_index')],
java_class_name=None,
type='function'),
NativeMethod(return_type='byte[]', static=False,
name='GetStateAsByteArray',
params=[Param(datatype='View', name='view')],
java_class_name=None,
type='function'),
NativeMethod(return_type='String[]', static=True,
name='GetAutofillProfileGUIDs', params=[],
java_class_name=None,
type='function'),
NativeMethod(return_type='void', static=False,
name='SetRecognitionResults',
params=[Param(datatype='int', name='sessionId'),
Param(datatype='String[]', name='results')],
java_class_name=None,
type='function'),
NativeMethod(return_type='long', static=False,
name='AddBookmarkFromAPI',
params=[Param(datatype='int',
name='nativeChromeBrowserProvider'),
Param(datatype='String',
name='url'),
Param(datatype='Long',
name='created'),
Param(datatype='Boolean',
name='isBookmark'),
Param(datatype='Long',
name='date'),
Param(datatype='byte[]',
name='favicon'),
Param(datatype='String',
name='title'),
Param(datatype='Integer',
name='visits')],
java_class_name=None,
type='method',
p0_type='ChromeBrowserProvider'),
NativeMethod(return_type='int', static=False,
name='FindAll',
params=[Param(datatype='String',
name='find')],
java_class_name=None,
type='function'),
NativeMethod(return_type='OnFrameAvailableListener', static=True,
name='GetInnerClass',
params=[],
java_class_name=None,
type='function'),
NativeMethod(return_type='Bitmap',
static=False,
name='QueryBitmap',
params=[Param(datatype='int',
name='nativeChromeBrowserProvider'),
Param(datatype='String[]',
name='projection'),
Param(datatype='String',
name='selection'),
Param(datatype='String[]',
name='selectionArgs'),
Param(datatype='String',
name='sortOrder'),
],
java_class_name=None,
type='method',
p0_type='ChromeBrowserProvider'),
NativeMethod(return_type='void', static=False,
name='GotOrientation',
params=[Param(datatype='int',
name='nativeDataFetcherImplAndroid'),
Param(datatype='double',
name='alpha'),
Param(datatype='double',
name='beta'),
Param(datatype='double',
name='gamma'),
],
java_class_name=None,
type='method',
p0_type='content::DataFetcherImplAndroid'),
NativeMethod(return_type='Throwable', static=True,
name='MessWithJavaException',
params=[Param(datatype='Throwable', name='e')],
java_class_name=None,
type='function')
]
self.assertListEquals(golden_natives, natives)
h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
natives, [], [], TestOptions())
self.assertGoldenTextEquals(h.GetContent())
def testInnerClassNatives(self):
test_data = """
class MyInnerClass {
@NativeCall("MyInnerClass")
private native int nativeInit();
}
"""
natives = jni_generator.ExtractNatives(test_data, 'int')
golden_natives = [
NativeMethod(return_type='int', static=False,
name='Init', params=[],
java_class_name='MyInnerClass',
type='function')
]
self.assertListEquals(golden_natives, natives)
h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
natives, [], [], TestOptions())
self.assertGoldenTextEquals(h.GetContent())
def testInnerClassNativesMultiple(self):
test_data = """
class MyInnerClass {
@NativeCall("MyInnerClass")
private native int nativeInit();
}
class MyOtherInnerClass {
@NativeCall("MyOtherInnerClass")
private native int nativeInit();
}
"""
natives = jni_generator.ExtractNatives(test_data, 'int')
golden_natives = [
NativeMethod(return_type='int', static=False,
name='Init', params=[],
java_class_name='MyInnerClass',
type='function'),
NativeMethod(return_type='int', static=False,
name='Init', params=[],
java_class_name='MyOtherInnerClass',
type='function')
]
self.assertListEquals(golden_natives, natives)
h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
natives, [], [], TestOptions())
self.assertGoldenTextEquals(h.GetContent())
def testInnerClassNativesBothInnerAndOuter(self):
test_data = """
class MyOuterClass {
private native int nativeInit();
class MyOtherInnerClass {
@NativeCall("MyOtherInnerClass")
private native int nativeInit();
}
}
"""
natives = jni_generator.ExtractNatives(test_data, 'int')
golden_natives = [
NativeMethod(return_type='int', static=False,
name='Init', params=[],
java_class_name=None,
type='function'),
NativeMethod(return_type='int', static=False,
name='Init', params=[],
java_class_name='MyOtherInnerClass',
type='function')
]
self.assertListEquals(golden_natives, natives)
h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
natives, [], [], TestOptions())
self.assertGoldenTextEquals(h.GetContent())
def testCalledByNatives(self):
test_data = """"
import android.graphics.Bitmap;
import android.view.View;
import java.io.InputStream;
import java.util.List;
class InnerClass {}
@CalledByNative
InnerClass showConfirmInfoBar(int nativeInfoBar,
String buttonOk, String buttonCancel, String title, Bitmap icon) {
InfoBar infobar = new ConfirmInfoBar(nativeInfoBar, mContext,
buttonOk, buttonCancel,
title, icon);
return infobar;
}
@CalledByNative
InnerClass showAutoLoginInfoBar(int nativeInfoBar,
String realm, String account, String args) {
AutoLoginInfoBar infobar = new AutoLoginInfoBar(nativeInfoBar, mContext,
realm, account, args);
if (infobar.displayedAccountCount() == 0)
infobar = null;
return infobar;
}
@CalledByNative("InfoBar")
void dismiss();
@SuppressWarnings("unused")
@CalledByNative
private static boolean shouldShowAutoLogin(View view,
String realm, String account, String args) {
AccountManagerContainer accountManagerContainer =
new AccountManagerContainer((Activity)contentView.getContext(),
realm, account, args);
String[] logins = accountManagerContainer.getAccountLogins(null);
return logins.length != 0;
}
@CalledByNative
static InputStream openUrl(String url) {
return null;
}
@CalledByNative
private void activateHardwareAcceleration(final boolean activated,
final int iPid, final int iType,
final int iPrimaryID, final int iSecondaryID) {
if (!activated) {
return
}
}
@CalledByNativeUnchecked
private void uncheckedCall(int iParam);
@CalledByNative
public byte[] returnByteArray();
@CalledByNative
public boolean[] returnBooleanArray();
@CalledByNative
public char[] returnCharArray();
@CalledByNative
public short[] returnShortArray();
@CalledByNative
public int[] returnIntArray();
@CalledByNative
public long[] returnLongArray();
@CalledByNative
public double[] returnDoubleArray();
@CalledByNative
public Object[] returnObjectArray();
@CalledByNative
public byte[][] returnArrayOfByteArray();
@CalledByNative
public Bitmap.CompressFormat getCompressFormat();
@CalledByNative
public List<Bitmap.CompressFormat> getCompressFormatList();
"""
jni_generator.JniParams.SetFullyQualifiedClass('org/chromium/Foo')
jni_generator.JniParams.ExtractImportsAndInnerClasses(test_data)
called_by_natives = jni_generator.ExtractCalledByNatives(test_data)
golden_called_by_natives = [
CalledByNative(
return_type='InnerClass',
system_class=False,
static=False,
name='showConfirmInfoBar',
method_id_var_name='showConfirmInfoBar',
java_class_name='',
params=[Param(datatype='int', name='nativeInfoBar'),
Param(datatype='String', name='buttonOk'),
Param(datatype='String', name='buttonCancel'),
Param(datatype='String', name='title'),
Param(datatype='Bitmap', name='icon')],
env_call=('Object', ''),
unchecked=False,
),
CalledByNative(
return_type='InnerClass',
system_class=False,
static=False,
name='showAutoLoginInfoBar',
method_id_var_name='showAutoLoginInfoBar',
java_class_name='',
params=[Param(datatype='int', name='nativeInfoBar'),
Param(datatype='String', name='realm'),
Param(datatype='String', name='account'),
Param(datatype='String', name='args')],
env_call=('Object', ''),
unchecked=False,
),
CalledByNative(
return_type='void',
system_class=False,
static=False,
name='dismiss',
method_id_var_name='dismiss',
java_class_name='InfoBar',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='boolean',
system_class=False,
static=True,
name='shouldShowAutoLogin',
method_id_var_name='shouldShowAutoLogin',
java_class_name='',
params=[Param(datatype='View', name='view'),
Param(datatype='String', name='realm'),
Param(datatype='String', name='account'),
Param(datatype='String', name='args')],
env_call=('Boolean', ''),
unchecked=False,
),
CalledByNative(
return_type='InputStream',
system_class=False,
static=True,
name='openUrl',
method_id_var_name='openUrl',
java_class_name='',
params=[Param(datatype='String', name='url')],
env_call=('Object', ''),
unchecked=False,
),
CalledByNative(
return_type='void',
system_class=False,
static=False,
name='activateHardwareAcceleration',
method_id_var_name='activateHardwareAcceleration',
java_class_name='',
params=[Param(datatype='boolean', name='activated'),
Param(datatype='int', name='iPid'),
Param(datatype='int', name='iType'),
Param(datatype='int', name='iPrimaryID'),
Param(datatype='int', name='iSecondaryID'),
],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='void',
system_class=False,
static=False,
name='uncheckedCall',
method_id_var_name='uncheckedCall',
java_class_name='',
params=[Param(datatype='int', name='iParam')],
env_call=('Void', ''),
unchecked=True,
),
CalledByNative(
return_type='byte[]',
system_class=False,
static=False,
name='returnByteArray',
method_id_var_name='returnByteArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='boolean[]',
system_class=False,
static=False,
name='returnBooleanArray',
method_id_var_name='returnBooleanArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='char[]',
system_class=False,
static=False,
name='returnCharArray',
method_id_var_name='returnCharArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='short[]',
system_class=False,
static=False,
name='returnShortArray',
method_id_var_name='returnShortArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='int[]',
system_class=False,
static=False,
name='returnIntArray',
method_id_var_name='returnIntArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='long[]',
system_class=False,
static=False,
name='returnLongArray',
method_id_var_name='returnLongArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='double[]',
system_class=False,
static=False,
name='returnDoubleArray',
method_id_var_name='returnDoubleArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='Object[]',
system_class=False,
static=False,
name='returnObjectArray',
method_id_var_name='returnObjectArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='byte[][]',
system_class=False,
static=False,
name='returnArrayOfByteArray',
method_id_var_name='returnArrayOfByteArray',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='Bitmap.CompressFormat',
system_class=False,
static=False,
name='getCompressFormat',
method_id_var_name='getCompressFormat',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
CalledByNative(
return_type='List<Bitmap.CompressFormat>',
system_class=False,
static=False,
name='getCompressFormatList',
method_id_var_name='getCompressFormatList',
java_class_name='',
params=[],
env_call=('Void', ''),
unchecked=False,
),
]
self.assertListEquals(golden_called_by_natives, called_by_natives)
h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
[], called_by_natives, [],
TestOptions())
self.assertGoldenTextEquals(h.GetContent())
def testCalledByNativeParseError(self):
try:
jni_generator.ExtractCalledByNatives("""
@CalledByNative
public static int foo(); // This one is fine
@CalledByNative
scooby doo
""")
self.fail('Expected a ParseError')
except jni_generator.ParseError, e:
self.assertEquals(('@CalledByNative', 'scooby doo'), e.context_lines)
def testFullyQualifiedClassName(self):
contents = """
// Copyright (c) 2010 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.content.browser;
import org.chromium.base.BuildInfo;
"""
self.assertEquals('org/chromium/content/browser/Foo',
jni_generator.ExtractFullyQualifiedJavaClassName(
'org/chromium/content/browser/Foo.java', contents))
self.assertEquals('org/chromium/content/browser/Foo',
jni_generator.ExtractFullyQualifiedJavaClassName(
'frameworks/Foo.java', contents))
self.assertRaises(SyntaxError,
jni_generator.ExtractFullyQualifiedJavaClassName,
'com/foo/Bar', 'no PACKAGE line')
def testMethodNameMangling(self):
self.assertEquals('closeV',
jni_generator.GetMangledMethodName('close', [], 'void'))
self.assertEquals('readI_AB_I_I',
jni_generator.GetMangledMethodName('read',
[Param(name='p1',
datatype='byte[]'),
Param(name='p2',
datatype='int'),
Param(name='p3',
datatype='int'),],
'int'))
self.assertEquals('openJIIS_JLS',
jni_generator.GetMangledMethodName('open',
[Param(name='p1',
datatype='java/lang/String'),],
'java/io/InputStream'))
def testFromJavaPGenerics(self):
contents = """
public abstract class java.util.HashSet<T> extends java.util.AbstractSet<E>
implements java.util.Set<E>, java.lang.Cloneable, java.io.Serializable {
public void dummy();
Signature: ()V
}
"""
jni_from_javap = jni_generator.JNIFromJavaP(contents.split('\n'),
TestOptions())
self.assertEquals(1, len(jni_from_javap.called_by_natives))
self.assertGoldenTextEquals(jni_from_javap.GetContent())
def testSnippnetJavap6_7_8(self):
content_javap6 = """
public class java.util.HashSet {
public boolean add(java.lang.Object);
Signature: (Ljava/lang/Object;)Z
}
"""
content_javap7 = """
public class java.util.HashSet {
public boolean add(E);
Signature: (Ljava/lang/Object;)Z
}
"""
content_javap8 = """
public class java.util.HashSet {
public boolean add(E);
descriptor: (Ljava/lang/Object;)Z
}
"""
jni_from_javap6 = jni_generator.JNIFromJavaP(content_javap6.split('\n'),
TestOptions())
jni_from_javap7 = jni_generator.JNIFromJavaP(content_javap7.split('\n'),
TestOptions())
jni_from_javap8 = jni_generator.JNIFromJavaP(content_javap8.split('\n'),
TestOptions())
self.assertTrue(jni_from_javap6.GetContent())
self.assertTrue(jni_from_javap7.GetContent())
self.assertTrue(jni_from_javap8.GetContent())
# Ensure the javap7 is correctly parsed and uses the Signature field rather
# than the "E" parameter.
self.assertTextEquals(jni_from_javap6.GetContent(),
jni_from_javap7.GetContent())
# Ensure the javap8 is correctly parsed and uses the descriptor field.
self.assertTextEquals(jni_from_javap7.GetContent(),
jni_from_javap8.GetContent())
def testFromJavaP(self):
contents = self._ReadGoldenFile(os.path.join(os.path.dirname(sys.argv[0]),
'testInputStream.javap'))
jni_from_javap = jni_generator.JNIFromJavaP(contents.split('\n'),
TestOptions())
self.assertEquals(10, len(jni_from_javap.called_by_natives))
self.assertGoldenTextEquals(jni_from_javap.GetContent())
def testConstantsFromJavaP(self):
for f in ['testMotionEvent.javap', 'testMotionEvent.javap7']:
contents = self._ReadGoldenFile(os.path.join(os.path.dirname(sys.argv[0]),
f))
jni_from_javap = jni_generator.JNIFromJavaP(contents.split('\n'),
TestOptions())
self.assertEquals(86, len(jni_from_javap.called_by_natives))
self.assertGoldenTextEquals(jni_from_javap.GetContent())
def testREForNatives(self):
# We should not match "native SyncSetupFlow" inside the comment.
test_data = """
/**
* Invoked when the setup process is complete so we can disconnect from the
* native-side SyncSetupFlowHandler.
*/
public void destroy() {
Log.v(TAG, "Destroying native SyncSetupFlow");
if (mNativeSyncSetupFlow != 0) {
nativeSyncSetupEnded(mNativeSyncSetupFlow);
mNativeSyncSetupFlow = 0;
}
}
private native void nativeSyncSetupEnded(
int nativeAndroidSyncSetupFlowHandler);
"""
jni_from_java = jni_generator.JNIFromJavaSource(
test_data, 'foo/bar', TestOptions())
def testRaisesOnNonJNIMethod(self):
test_data = """
class MyInnerClass {
private int Foo(int p0) {
}
}
"""
self.assertRaises(SyntaxError,
jni_generator.JNIFromJavaSource,
test_data, 'foo/bar', TestOptions())
def testJniSelfDocumentingExample(self):
script_dir = os.path.dirname(sys.argv[0])
content = file(os.path.join(script_dir,
'java/src/org/chromium/example/jni_generator/SampleForTests.java')
).read()
golden_file = os.path.join(script_dir, 'golden_sample_for_tests_jni.h')
golden_content = file(golden_file).read()
jni_from_java = jni_generator.JNIFromJavaSource(
content, 'org/chromium/example/jni_generator/SampleForTests',
TestOptions())
generated_text = jni_from_java.GetContent()
if not self.compareText(golden_content, generated_text):
if os.environ.get(REBASELINE_ENV):
with file(golden_file, 'w') as f:
f.write(generated_text)
return
self.fail('testJniSelfDocumentingExample')
def testNoWrappingPreprocessorLines(self):
test_data = """
package com.google.lookhowextremelylongiam.snarf.icankeepthisupallday;
class ReallyLongClassNamesAreAllTheRage {
private static native int nativeTest();
}
"""
jni_from_java = jni_generator.JNIFromJavaSource(
test_data, ('com/google/lookhowextremelylongiam/snarf/'
'icankeepthisupallday/ReallyLongClassNamesAreAllTheRage'),
TestOptions())
jni_lines = jni_from_java.GetContent().split('\n')
line = filter(lambda line: line.lstrip().startswith('#ifndef'),
jni_lines)[0]
self.assertTrue(len(line) > 80,
('Expected #ifndef line to be > 80 chars: ', line))
def testImports(self):
import_header = """
// Copyright (c) 2012 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.content.app;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.RemoteException;
import android.util.Log;
import android.view.Surface;
import java.util.ArrayList;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.content.app.ContentMain;
import org.chromium.content.browser.SandboxedProcessConnection;
import org.chromium.content.common.ISandboxedProcessCallback;
import org.chromium.content.common.ISandboxedProcessService;
import org.chromium.content.common.WillNotRaise.AnException;
import org.chromium.content.common.WillRaise.AnException;
import static org.chromium.Bar.Zoo;
class Foo {
public static class BookmarkNode implements Parcelable {
}
public interface PasswordListObserver {
}
}
"""
jni_generator.JniParams.SetFullyQualifiedClass(
'org/chromium/content/app/Foo')
jni_generator.JniParams.ExtractImportsAndInnerClasses(import_header)
self.assertTrue('Lorg/chromium/content/common/ISandboxedProcessService' in
jni_generator.JniParams._imports)
self.assertTrue('Lorg/chromium/Bar/Zoo' in
jni_generator.JniParams._imports)
self.assertTrue('Lorg/chromium/content/app/Foo$BookmarkNode' in
jni_generator.JniParams._inner_classes)
self.assertTrue('Lorg/chromium/content/app/Foo$PasswordListObserver' in
jni_generator.JniParams._inner_classes)
self.assertEquals('Lorg/chromium/content/app/ContentMain$Inner;',
jni_generator.JniParams.JavaToJni('ContentMain.Inner'))
self.assertRaises(SyntaxError,
jni_generator.JniParams.JavaToJni,
'AnException')
def testJniParamsJavaToJni(self):
self.assertTextEquals('I', JniParams.JavaToJni('int'))
self.assertTextEquals('[B', JniParams.JavaToJni('byte[]'))
self.assertTextEquals(
'[Ljava/nio/ByteBuffer;', JniParams.JavaToJni('java/nio/ByteBuffer[]'))
def testNativesLong(self):
test_options = TestOptions()
test_options.ptr_type = 'long'
test_data = """"
private native void nativeDestroy(long nativeChromeBrowserProvider);
"""
jni_generator.JniParams.ExtractImportsAndInnerClasses(test_data)
natives = jni_generator.ExtractNatives(test_data, test_options.ptr_type)
golden_natives = [
NativeMethod(return_type='void', static=False, name='Destroy',
params=[Param(datatype='long',
name='nativeChromeBrowserProvider')],
java_class_name=None,
type='method',
p0_type='ChromeBrowserProvider',
ptr_type=test_options.ptr_type),
]
self.assertListEquals(golden_natives, natives)
h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
natives, [], [], test_options)
self.assertGoldenTextEquals(h.GetContent())
def runNativeExportsOption(self, optional):
test_data = """
package org.chromium.example.jni_generator;
/** The pointer to the native Test. */
long nativeTest;
class Test {
private static native int nativeStaticMethod(long nativeTest, int arg1);
private native int nativeMethod(long nativeTest, int arg1);
@CalledByNative
private void testMethodWithParam(int iParam);
@CalledByNative
private String testMethodWithParamAndReturn(int iParam);
@CalledByNative
private static int testStaticMethodWithParam(int iParam);
@CalledByNative
private static double testMethodWithNoParam();
@CalledByNative
private static String testStaticMethodWithNoParam();
class MyInnerClass {
@NativeCall("MyInnerClass")
private native int nativeInit();
}
class MyOtherInnerClass {
@NativeCall("MyOtherInnerClass")
private native int nativeInit();
}
}
"""
options = TestOptions()
options.native_exports = True
options.native_exports_optional = optional
jni_from_java = jni_generator.JNIFromJavaSource(
test_data, 'org/chromium/example/jni_generator/SampleForTests', options)
return jni_from_java.GetContent()
def testNativeExportsOption(self):
content = self.runNativeExportsOption(False)
self.assertGoldenTextEquals(content)
def testNativeExportsOptionalOption(self):
content = self.runNativeExportsOption(True)
self.assertGoldenTextEquals(content)
def testOuterInnerRaises(self):
test_data = """
package org.chromium.media;
@CalledByNative
static int getCaptureFormatWidth(VideoCapture.CaptureFormat format) {
return format.getWidth();
}
"""
def willRaise():
jni_generator.JNIFromJavaSource(
test_data,
'org/chromium/media/VideoCaptureFactory',
TestOptions())
self.assertRaises(SyntaxError, willRaise)
def testSingleJNIAdditionalImport(self):
test_data = """
package org.chromium.foo;
@JNIAdditionalImport(Bar.class)
class Foo {
@CalledByNative
private static void calledByNative(Bar.Callback callback) {
}
private static native void nativeDoSomething(Bar.Callback callback);
}
"""
jni_from_java = jni_generator.JNIFromJavaSource(test_data,
'org/chromium/foo/Foo',
TestOptions())
self.assertGoldenTextEquals(jni_from_java.GetContent())
def testMultipleJNIAdditionalImport(self):
test_data = """
package org.chromium.foo;
@JNIAdditionalImport({Bar1.class, Bar2.class})
class Foo {
@CalledByNative
private static void calledByNative(Bar1.Callback callback1,
Bar2.Callback callback2) {
}
private static native void nativeDoSomething(Bar1.Callback callback1,
Bar2.Callback callback2);
}
"""
jni_from_java = jni_generator.JNIFromJavaSource(test_data,
'org/chromium/foo/Foo',
TestOptions())
self.assertGoldenTextEquals(jni_from_java.GetContent())
def TouchStamp(stamp_path):
dir_name = os.path.dirname(stamp_path)
if not os.path.isdir(dir_name):
os.makedirs()
with open(stamp_path, 'a'):
os.utime(stamp_path, None)
def main(argv):
parser = optparse.OptionParser()
parser.add_option('--stamp', help='Path to touch on success.')
options, _ = parser.parse_args(argv[1:])
test_result = unittest.main(argv=argv[0:1], exit=False)
if test_result.result.wasSuccessful() and options.stamp:
TouchStamp(options.stamp)
return not test_result.result.wasSuccessful()
if __name__ == '__main__':
sys.exit(main(sys.argv))
| heke123/chromium-crosswalk | base/android/jni_generator/jni_generator_tests.py | Python | bsd-3-clause | 39,812 |
/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/loader/ThreadableLoader.h"
#include "core/dom/Document.h"
#include "core/dom/ExecutionContext.h"
#include "core/loader/DocumentThreadableLoader.h"
#include "core/loader/ThreadableLoaderClientWrapper.h"
#include "core/loader/WorkerThreadableLoader.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerThread.h"
namespace blink {
PassOwnPtr<ThreadableLoader> ThreadableLoader::create(ExecutionContext& context, ThreadableLoaderClient* client, const ThreadableLoaderOptions& options, const ResourceLoaderOptions& resourceLoaderOptions)
{
ASSERT(client);
if (context.isWorkerGlobalScope()) {
return WorkerThreadableLoader::create(toWorkerGlobalScope(context), client, options, resourceLoaderOptions);
}
return DocumentThreadableLoader::create(toDocument(context), client, options, resourceLoaderOptions);
}
void ThreadableLoader::loadResourceSynchronously(ExecutionContext& context, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options, const ResourceLoaderOptions& resourceLoaderOptions)
{
if (context.isWorkerGlobalScope()) {
WorkerThreadableLoader::loadResourceSynchronously(toWorkerGlobalScope(context), request, client, options, resourceLoaderOptions);
return;
}
DocumentThreadableLoader::loadResourceSynchronously(toDocument(context), request, client, options, resourceLoaderOptions);
}
} // namespace blink
| axinging/chromium-crosswalk | third_party/WebKit/Source/core/loader/ThreadableLoader.cpp | C++ | bsd-3-clause | 3,022 |
// package metadata file for Meteor.js
'use strict';
var packageName = 'gromo:jquery.scrollbar'; // https://atmospherejs.com/mediatainment/switchery
var where = 'client'; // where to install: 'client' or 'server'. For both, pass nothing.
Package.describe({
name: packageName,
version: '0.2.10',
// Brief, one-line summary of the package.
summary: 'Cross-browser CSS customizable scrollbar with advanced features.',
// URL to the Git repository containing the source code for this package.
git: 'git@github.com:gromo/jquery.scrollbar.git'
});
Package.onUse(function (api) {
api.versionsFrom(['METEOR@0.9.0', 'METEOR@1.0']);
api.use('jquery', where);
api.addFiles(['jquery.scrollbar.js', 'jquery.scrollbar.css'], where);
});
Package.onTest(function (api) {
api.use([packageName, 'sanjo:jasmine'], where);
api.use(['webapp','tinytest'], where);
api.addFiles('meteor/tests.js', where); // testing specific files
});
| aivankovich/zo | vendor/jquery.scrollbar/package.js | JavaScript | bsd-3-clause | 964 |
Prism.languages.j={comment:{pattern:/\bNB\..*/,greedy:!0},string:{pattern:/'(?:''|[^'\r\n])*'/,greedy:!0},keyword:/\b(?:(?:CR|LF|adverb|conjunction|def|define|dyad|monad|noun|verb)\b|(?:assert|break|case|catch[dt]?|continue|do|else|elseif|end|fcase|for|for_\w+|goto_\w+|if|label_\w+|return|select|throw|try|while|whilst)\.)/,verb:{pattern:/(?!\^:|;\.|[=!][.:])(?:\{(?:\.|::?)?|p(?:\.\.?|:)|[=!\]]|[<>+*\-%$|,#][.:]?|[?^]\.?|[;\[]:?|[~}"i][.:]|[ACeEIjLor]\.|(?:[_\/\\qsux]|_?\d):)/,alias:"keyword"},number:/\b_?(?:(?!\d:)\d+(?:\.\d+)?(?:(?:ad|ar|[ejpx])_?\d+(?:\.\d+)?)*(?:b_?[\da-z]+(?:\.[\da-z]+)?)?|_\b(?!\.))/,adverb:{pattern:/[~}]|[\/\\]\.?|[bfM]\.|t[.:]/,alias:"builtin"},operator:/[=a][.:]|_\./,conjunction:{pattern:/&(?:\.:?|:)?|[.:@][.:]?|[!D][.:]|[;dHT]\.|`:?|[\^LS]:|"/,alias:"variable"},punctuation:/[()]/}; | netbek/chrys | demo/vendor/prismjs/components/prism-j.min.js | JavaScript | bsd-3-clause | 818 |
/*
* zClip :: jQuery ZeroClipboard v1.1.1
* http://steamdev.com/zclip
*
* Copyright 2011, SteamDev
* Released under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Date: Wed Jun 01, 2011
*/
(function ($) {
$.fn.zclip = function (params) {
if (typeof params == "object" && !params.length) {
var settings = $.extend({
path: 'ZeroClipboard.swf',
copy: null,
beforeCopy: null,
afterCopy: null,
clickAfter: true,
setHandCursor: true,
setCSSEffects: true
}, params);
return this.each(function () {
var o = $(this);
if (o.is(':visible') && (typeof settings.copy == 'string' || $.isFunction(settings.copy))) {
ZeroClipboard.setMoviePath(settings.path);
var clip = new ZeroClipboard.Client();
if($.isFunction(settings.copy)){
o.bind('zClip_copy',settings.copy);
}
if($.isFunction(settings.beforeCopy)){
o.bind('zClip_beforeCopy',settings.beforeCopy);
}
if($.isFunction(settings.afterCopy)){
o.bind('zClip_afterCopy',settings.afterCopy);
}
clip.setHandCursor(settings.setHandCursor);
clip.setCSSEffects(settings.setCSSEffects);
clip.addEventListener('mouseOver', function (client) {
o.trigger('mouseenter');
});
clip.addEventListener('mouseOut', function (client) {
o.trigger('mouseleave');
});
clip.addEventListener('mouseDown', function (client) {
o.trigger('mousedown');
if(!$.isFunction(settings.copy)){
clip.setText(settings.copy);
} else {
clip.setText(o.triggerHandler('zClip_copy'));
}
if ($.isFunction(settings.beforeCopy)) {
o.trigger('zClip_beforeCopy');
}
});
clip.addEventListener('complete', function (client, text) {
if ($.isFunction(settings.afterCopy)) {
o.trigger('zClip_afterCopy');
} else {
if (text.length > 500) {
text = text.substr(0, 500) + "...\n\n(" + (text.length - 500) + " characters not shown)";
}
o.removeClass('hover');
alert("Copied text to clipboard:\n\n " + text);
}
if (settings.clickAfter) {
o.trigger('click');
}
});
clip.glue(o[0], o.parent()[0]);
$(window).bind('load resize',function(){clip.reposition();});
}
});
} else if (typeof params == "string") {
return this.each(function () {
var o = $(this);
params = params.toLowerCase();
var zclipId = o.data('zclipId');
var clipElm = $('#' + zclipId + '.zclip');
if (params == "remove") {
clipElm.remove();
o.removeClass('active hover');
} else if (params == "hide") {
clipElm.hide();
o.removeClass('active hover');
} else if (params == "show") {
clipElm.show();
}
});
}
}
})(jQuery);
// ZeroClipboard
// Simple Set Clipboard System
// Author: Joseph Huckaby
var ZeroClipboard = {
version: "1.0.7",
clients: {},
// registered upload clients on page, indexed by id
moviePath: 'ZeroClipboard.swf',
// URL to movie
nextId: 1,
// ID of next movie
$: function (thingy) {
// simple DOM lookup utility function
if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
if (!thingy.addClass) {
// extend element with a few useful methods
thingy.hide = function () {
this.style.display = 'none';
};
thingy.show = function () {
this.style.display = '';
};
thingy.addClass = function (name) {
this.removeClass(name);
this.className += ' ' + name;
};
thingy.removeClass = function (name) {
var classes = this.className.split(/\s+/);
var idx = -1;
for (var k = 0; k < classes.length; k++) {
if (classes[k] == name) {
idx = k;
k = classes.length;
}
}
if (idx > -1) {
classes.splice(idx, 1);
this.className = classes.join(' ');
}
return this;
};
thingy.hasClass = function (name) {
return !!this.className.match(new RegExp("\\s*" + name + "\\s*"));
};
}
return thingy;
},
setMoviePath: function (path) {
// set path to ZeroClipboard.swf
this.moviePath = path;
},
dispatch: function (id, eventName, args) {
// receive event from flash movie, send to client
var client = this.clients[id];
if (client) {
client.receiveEvent(eventName, args);
}
},
register: function (id, client) {
// register new client to receive events
this.clients[id] = client;
},
getDOMObjectPosition: function (obj, stopObj) {
// get absolute coordinates for dom element
var info = {
left: 0,
top: 0,
width: obj.width ? obj.width : obj.offsetWidth,
height: obj.height ? obj.height : obj.offsetHeight
};
if (obj && (obj != stopObj)) {
info.left += obj.offsetLeft;
info.top += obj.offsetTop;
}
return info;
},
Client: function (elem) {
// constructor for new simple upload client
this.handlers = {};
// unique ID
this.id = ZeroClipboard.nextId++;
this.movieId = 'ZeroClipboardMovie_' + this.id;
// register client with singleton to receive flash events
ZeroClipboard.register(this.id, this);
// create movie
if (elem) this.glue(elem);
}
};
ZeroClipboard.Client.prototype = {
id: 0,
// unique ID for us
ready: false,
// whether movie is ready to receive events or not
movie: null,
// reference to movie object
clipText: '',
// text to copy to clipboard
handCursorEnabled: true,
// whether to show hand cursor, or default pointer cursor
cssEffects: true,
// enable CSS mouse effects on dom container
handlers: null,
// user event handlers
glue: function (elem, appendElem, stylesToAdd) {
// glue to DOM element
// elem can be ID or actual DOM element object
this.domElement = ZeroClipboard.$(elem);
// float just above object, or zIndex 99 if dom element isn't set
var zIndex = 99;
if (this.domElement.style.zIndex) {
zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
}
if (typeof(appendElem) == 'string') {
appendElem = ZeroClipboard.$(appendElem);
} else if (typeof(appendElem) == 'undefined') {
appendElem = document.getElementsByTagName('body')[0];
}
// find X/Y position of domElement
var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);
// create floating DIV above element
this.div = document.createElement('div');
this.div.className = "zclip";
this.div.id = "zclip-" + this.movieId;
$(this.domElement).data('zclipId', 'zclip-' + this.movieId);
var style = this.div.style;
style.position = 'absolute';
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
style.width = '' + box.width + 'px';
style.height = '' + box.height + 'px';
style.zIndex = zIndex;
if (typeof(stylesToAdd) == 'object') {
for (addedStyle in stylesToAdd) {
style[addedStyle] = stylesToAdd[addedStyle];
}
}
// style.backgroundColor = '#f00'; // debug
appendElem.appendChild(this.div);
this.div.innerHTML = this.getHTML(box.width, box.height);
},
getHTML: function (width, height) {
// return HTML for movie
var html = '';
var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height;
if (navigator.userAgent.match(/MSIE/)) {
// IE gets an OBJECT tag
var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="' + protocol + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + width + '" height="' + height + '" id="' + this.movieId + '" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="' + ZeroClipboard.moviePath + '" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="' + flashvars + '"/><param name="wmode" value="transparent"/></object>';
} else {
// all other browsers get an EMBED tag
html += '<embed id="' + this.movieId + '" src="' + ZeroClipboard.moviePath + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="' + this.movieId + '" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" wmode="transparent" />';
}
return html;
},
hide: function () {
// temporarily hide floater offscreen
if (this.div) {
this.div.style.left = '-2000px';
}
},
show: function () {
// show ourselves after a call to hide()
this.reposition();
},
destroy: function () {
// destroy control and floater
if (this.domElement && this.div) {
this.hide();
this.div.innerHTML = '';
var body = document.getElementsByTagName('body')[0];
try {
body.removeChild(this.div);
} catch (e) {;
}
this.domElement = null;
this.div = null;
}
},
reposition: function (elem) {
// reposition our floating div, optionally to new container
// warning: container CANNOT change size, only position
if (elem) {
this.domElement = ZeroClipboard.$(elem);
if (!this.domElement) this.hide();
}
if (this.domElement && this.div) {
var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
}
},
setText: function (newText) {
// set text to be copied to clipboard
this.clipText = newText;
if (this.ready) {
this.movie.setText(newText);
}
},
addEventListener: function (eventName, func) {
// add user event listener for event
// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
if (!this.handlers[eventName]) {
this.handlers[eventName] = [];
}
this.handlers[eventName].push(func);
},
setHandCursor: function (enabled) {
// enable hand cursor (true), or default arrow cursor (false)
this.handCursorEnabled = enabled;
if (this.ready) {
this.movie.setHandCursor(enabled);
}
},
setCSSEffects: function (enabled) {
// enable or disable CSS effects on DOM container
this.cssEffects = !! enabled;
},
receiveEvent: function (eventName, args) {
// receive event from flash
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
// special behavior for certain events
switch (eventName) {
case 'load':
// movie claims it is ready, but in IE this isn't always the case...
// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
this.movie = document.getElementById(this.movieId);
if (!this.movie) {
var self = this;
setTimeout(function () {
self.receiveEvent('load', null);
}, 1);
return;
}
// firefox on pc needs a "kick" in order to set these in certain cases
if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
var self = this;
setTimeout(function () {
self.receiveEvent('load', null);
}, 100);
this.ready = true;
return;
}
this.ready = true;
try {
this.movie.setText(this.clipText);
} catch (e) {}
try {
this.movie.setHandCursor(this.handCursorEnabled);
} catch (e) {}
break;
case 'mouseover':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('hover');
if (this.recoverActive) {
this.domElement.addClass('active');
}
}
break;
case 'mouseout':
if (this.domElement && this.cssEffects) {
this.recoverActive = false;
if (this.domElement.hasClass('active')) {
this.domElement.removeClass('active');
this.recoverActive = true;
}
this.domElement.removeClass('hover');
}
break;
case 'mousedown':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('active');
}
break;
case 'mouseup':
if (this.domElement && this.cssEffects) {
this.domElement.removeClass('active');
this.recoverActive = false;
}
break;
} // switch eventName
if (this.handlers[eventName]) {
for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
var func = this.handlers[eventName][idx];
if (typeof(func) == 'function') {
// actual function reference
func(this, args);
} else if ((typeof(func) == 'object') && (func.length == 2)) {
// PHP style object + method, i.e. [myObject, 'myMethod']
func[0][func[1]](this, args);
} else if (typeof(func) == 'string') {
// name of function
window[func](this, args);
}
} // foreach event handler defined
} // user defined handler for event
}
};
| xantage/code | vilya/static/js/lib/jquery.zclip.js | JavaScript | bsd-3-clause | 16,750 |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OrchardCore.Environment.Shell.Descriptor.Models;
namespace OrchardCore.Environment.Shell.Descriptor.Settings
{
/// <summary>
/// Implements <see cref="IShellDescriptorManager"/> by returning a single tenant with a specified set
/// of features. This class can be registered as a singleton as its state never changes.
/// </summary>
public class SetFeaturesShellDescriptorManager : IShellDescriptorManager
{
private readonly IEnumerable<ShellFeature> _shellFeatures;
private ShellDescriptor _shellDescriptor;
public SetFeaturesShellDescriptorManager(IEnumerable<ShellFeature> shellFeatures)
{
_shellFeatures = shellFeatures;
}
public Task<ShellDescriptor> GetShellDescriptorAsync()
{
if (_shellDescriptor == null)
{
_shellDescriptor = new ShellDescriptor
{
Features = _shellFeatures.Distinct().ToList()
};
}
return Task.FromResult(_shellDescriptor);
}
public Task UpdateShellDescriptorAsync(int priorSerialNumber, IEnumerable<ShellFeature> enabledFeatures, IEnumerable<ShellParameter> parameters)
{
return Task.CompletedTask;
}
}
}
| OrchardCMS/Brochard | src/OrchardCore/OrchardCore/Shell/Descriptor/Settings/SetFeaturesShellDescriptorManager.cs | C# | bsd-3-clause | 1,381 |
// mksyscall.pl -l32 syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
package syscall
import "unsafe"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setgroups(ngid int, gid *_Gid_t) (err error) {
_, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) {
r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
wpid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socket(domain int, typ int, proto int) (fd int, err error) {
r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
_, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Shutdown(s int, how int) (err error) {
_, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
var _p0 unsafe.Pointer
if len(mib) > 0 {
_p0 = unsafe.Pointer(&mib[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimes(path string, timeval *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func futimes(fd int, timeval *[2]Timeval) (err error) {
_, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) {
_, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe() (r int, w int, err error) {
r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
r = int(r0)
w = int(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kill(pid int, signum int, posix int) (err error) {
_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Access(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chflags(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chmod(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
_, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(fd int) (nfd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup2(from int, to int) (err error) {
_, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exchangedata(path1 string, path2 string, options int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path1)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(path2)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
use(unsafe.Pointer(_p0))
use(unsafe.Pointer(_p1))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exit(code int) {
Syscall(SYS_EXIT, uintptr(code), 0, 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchdir(fd int) (err error) {
_, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchflags(fd int, flags int) (err error) {
_, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmod(fd int, mode uint32) (err error) {
_, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchown(fd int, uid int, gid int) (err error) {
_, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Flock(fd int, how int) (err error) {
_, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fpathconf(fd int, name int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatfs(fd int, stat *Statfs_t) (err error) {
_, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fsync(fd int) (err error) {
_, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Ftruncate(fd int, length int64) (err error) {
_, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), uintptr(length>>32))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdtablesize() (size int) {
r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
size = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getegid() (egid int) {
r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
egid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Geteuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getgid() (gid int) {
r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgid(pid int) (pgid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgrp() (pgrp int) {
r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
pgrp = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpid() (pid int) {
r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getppid() (ppid int) {
r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0)
ppid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpriority(which int, who int) (prio int, err error) {
r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getsid(pid int) (sid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Issetugid() (tainted bool) {
r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0)
tainted = bool(r0 != 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kqueue() (fd int, err error) {
r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lchown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Link(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
use(unsafe.Pointer(_p0))
use(unsafe.Pointer(_p1))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Listen(s int, backlog int) (err error) {
_, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lstat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlockall(flags int) (err error) {
_, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mprotect(b []byte, prot int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlockall() (err error) {
_, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
use(unsafe.Pointer(_p0))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pathconf(path string, name int) (val int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
use(unsafe.Pointer(_p0))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func read(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)))
use(unsafe.Pointer(_p0))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rename(from string, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
use(unsafe.Pointer(_p0))
use(unsafe.Pointer(_p1))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Revoke(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rmdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0)
newoffset = int64(int64(r1)<<32 | int64(r0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
_, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setegid(egid int) (err error) {
_, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seteuid(euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setgid(gid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setlogin(name string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpgid(pid int, pgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpriority(which int, who int, prio int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setprivexec(flag int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setregid(rgid int, egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setreuid(ruid int, euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setsid() (pid int, err error) {
r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0)
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Settimeofday(tp *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setuid(uid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Stat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Statfs(path string, stat *Statfs_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlink(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
use(unsafe.Pointer(_p0))
use(unsafe.Pointer(_p1))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Sync() (err error) {
_, _, e1 := Syscall(SYS_SYNC, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Truncate(path string, length int64) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32))
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Umask(newmask int) (oldmask int) {
r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
oldmask = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Undelete(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlink(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unmount(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
use(unsafe.Pointer(_p0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func write(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0)
ret = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func munmap(addr uintptr, length uintptr) (err error) {
_, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) {
r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
sec = int32(r0)
usec = int32(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
| AnuchitPrasertsang/go | src/syscall/zsyscall_darwin_arm.go | GO | bsd-3-clause | 33,695 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>U+2500-U+257F: Box Drawing</title>
<link rel="next" href="2580.html">
<link rel="prev" href="2460.html">
<link rel="contents" href="./">
</head>
<body>
<table>
<caption>Box Drawing</caption>
<tr><th> <th>0<th>1<th>2<th>3<th>4<th>5<th>6<th>7<th>8<th>9<th>A<th>B<th>C<th>D<th>E<th>F
<tr><th>2500<td> ─ <td> ━ <td> │ <td> ┃ <td> ┄ <td> ┅ <td> ┆ <td> ┇ <td> ┈ <td> ┉ <td> ┊ <td> ┋ <td> ┌ <td> ┍ <td> ┎ <td> ┏
<tr><th>2510<td> ┐ <td> ┑ <td> ┒ <td> ┓ <td> └ <td> ┕ <td> ┖ <td> ┗ <td> ┘ <td> ┙ <td> ┚ <td> ┛ <td> ├ <td> ┝ <td> ┞ <td> ┟
<tr><th>2520<td> ┠ <td> ┡ <td> ┢ <td> ┣ <td> ┤ <td> ┥ <td> ┦ <td> ┧ <td> ┨ <td> ┩ <td> ┪ <td> ┫ <td> ┬ <td> ┭ <td> ┮ <td> ┯
<tr><th>2530<td> ┰ <td> ┱ <td> ┲ <td> ┳ <td> ┴ <td> ┵ <td> ┶ <td> ┷ <td> ┸ <td> ┹ <td> ┺ <td> ┻ <td> ┼ <td> ┽ <td> ┾ <td> ┿
<tr><th>2540<td> ╀ <td> ╁ <td> ╂ <td> ╃ <td> ╄ <td> ╅ <td> ╆ <td> ╇ <td> ╈ <td> ╉ <td> ╊ <td> ╋ <td> ╌ <td> ╍ <td> ╎ <td> ╏
<tr><th>2550<td> ═ <td> ║ <td> ╒ <td> ╓ <td> ╔ <td> ╕ <td> ╖ <td> ╗ <td> ╘ <td> ╙ <td> ╚ <td> ╛ <td> ╜ <td> ╝ <td> ╞ <td> ╟
<tr><th>2560<td> ╠ <td> ╡ <td> ╢ <td> ╣ <td> ╤ <td> ╥ <td> ╦ <td> ╧ <td> ╨ <td> ╩ <td> ╪ <td> ╫ <td> ╬ <td> ╭ <td> ╮ <td> ╯
<tr><th>2570<td> ╰ <td> ╱ <td> ╲ <td> ╳ <td> ╴ <td> ╵ <td> ╶ <td> ╷ <td> ╸ <td> ╹ <td> ╺ <td> ╻ <td> ╼ <td> ╽ <td> ╾ <td> ╿
</table>
</body>
</html>
| frivoal/presto-testo | imported/peter/unicode/tables/utf8/2500.html | HTML | bsd-3-clause | 1,699 |
/**
* Copyright (c) 2014,
* Charles Prud'homme (TASC, INRIA Rennes, LINA CNRS UMR 6241),
* Jean-Guillaume Fages (COSLING S.A.S.).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.chocosolver.solver.thread;
/**
* Slave born to be mastered and work in parallel
*
* @author Jean-Guillaume Fages
*/
public abstract class AbstractParallelSlave<P extends AbstractParallelMaster> {
//***********************************************************************************
// VARIABLES
//***********************************************************************************
public P master;
public final int id;
//***********************************************************************************
// CONSTRUCTORS
//***********************************************************************************
/**
* Create a slave born to be mastered and work in parallel
*
* @param master master solver
* @param id slave unique name
*/
public AbstractParallelSlave(P master, int id) {
this.master = master;
this.id = id;
}
//***********************************************************************************
// SUB-PROBLEM SOLVING
//***********************************************************************************
/**
* Creates a new thread to work in parallel
*/
public void workInParallel() {
Thread t = new Thread() {
@Override
public void run() {
work();
master.wishGranted();
}
};
t.start();
}
/**
* do something
*/
public abstract void work();
}
| piyushsh/choco3 | choco-solver/src/main/java/org/chocosolver/solver/thread/AbstractParallelSlave.java | Java | bsd-3-clause | 3,193 |
<!DOCTYPE html>
<title>drag & drop - event sequence for draggable elements</title>
<script type="text/javascript" src="/resources/testharness.js"></script>
<style type="text/css">
/* use margins instead of padding to make sure the body begins at the top of the page */
html, body {
margin: 0;
}
body {
padding: 116px 8px 8px;
}
#testhere div {
height: 100px;
width: 100px;
position: absolute;
top: 8px;
}
#orange {
background-color: orange;
left: 8px;
}
#fuchsia {
background-color: fuchsia;
left: 158px;
}
#yellow {
background-color: yellow;
left: 308px;
}
#blue {
background-color: navy;
left: 458px;
}
</style>
<script>
setup(function () {},{explicit_done:true,timeout:30000});
window.onload = function () {
var orange = document.querySelector('#orange')
var fuchsia = document.querySelector('#fuchsia')
var yellow = document.querySelector('#yellow')
var blue = document.querySelector('#blue')
var body = document.body;
var events = new Array
orange.ondragstart = function (e) {
events.push('orange.ondragstart');
e.dataTransfer.effectAllowed = 'copy';
e.dataTransfer.setData('Text', 'foo');
};
orange.ondrag = function () { events.push('orange.ondrag'); };
orange.ondragenter = function () { events.push('orange.ondragenter'); };
orange.ondragover = function () { events.push('orange.ondragover'); };
orange.ondragleave = function () { events.push('orange.ondragleave'); };
orange.ondrop = function () { events.push('orange.ondrop'); return false; };
orange.ondragend = function () { events.push('orange.ondragend'); };
orange.onmousedown = function () { events.push('orange.onmousedown'); };
orange.onmouseup = function () { events.push('orange.onmouseup'); };
/* Events for the fuchsia box */
fuchsia.ondragstart = function () { events.push('pink.ondragstart'); };
fuchsia.ondrag = function () { events.push('pink.ondrag'); };
fuchsia.ondragenter = function () { events.push('pink.ondragenter'); };
fuchsia.ondragover = function () { events.push('pink.ondragover'); };
fuchsia.ondragleave = function () { events.push('pink.ondragleave'); };
fuchsia.ondrop = function () { events.push('pink.ondrop'); return false; };
fuchsia.ondragend = function () { events.push('pink.ondragend'); };
fuchsia.onmousedown = function () { events.push('pink.onmousedown'); };
fuchsia.onmouseup = function () { events.push('pink.onmouseup'); };
/* Events for the fuchsia box */
yellow.ondragstart = function () { events.push('yellow.ondragstart'); };
yellow.ondrag = function () { events.push('yellow.ondrag'); };
yellow.ondragenter = function () { events.push('yellow.ondragenter'); return false; };
yellow.ondragover = function () { events.push('yellow.ondragover'); return false; };
yellow.ondragleave = function () { events.push('yellow.ondragleave'); };
yellow.ondrop = function () { events.push('yellow.ondrop'); return false; };
yellow.ondragend = function () { events.push('yellow.ondragend'); };
yellow.onmousedown = function () { events.push('yellow.onmousedown'); };
yellow.onmouseup = function () { events.push('yellow.onmouseup'); };
/* Events for the blue box (droppable) */
blue.ondragstart = function () { events.push('blue.ondragstart'); };
blue.ondrag = function () { events.push('blue.ondrag'); };
blue.ondragenter = function () { events.push('blue.ondragenter'); return false; };
blue.ondragover = function () { events.push('blue.ondragover'); return false; };
blue.ondragleave = function () { events.push('blue.ondragleave'); };
blue.ondrop = function () { events.push('blue.ondrop'); return false; };
blue.ondragend = function () { events.push('blue.ondragend'); };
blue.onmousedown = function () { events.push('blue.onmousedown'); };
blue.onmouseup = function () { events.push('blue.onmouseup'); };
/* Events for the page body */
body.ondragstart = function (e) { events.push( ( e.target == body ) ? 'body.ondragstart': 'bubble.ondragstart' ); };
body.ondrag = function (e) { events.push( ( e.target == body ) ? 'body.ondrag': 'bubble.ondrag' ); };
body.ondragenter = function (e) { events.push( ( e.target == body ) ? 'body.ondragenter': 'bubble.ondragenter' ); };
body.ondragover = function (e) { events.push( ( e.target == body ) ? 'body.ondragover': 'bubble.ondragover' ); };
body.ondragleave = function (e) { events.push( ( e.target == body ) ? 'body.ondragleave': 'bubble.ondragleave' ); };
body.ondrop = function (e) { events.push( ( e.target == body ) ? 'body.ondrop': 'bubble.ondrop' ); };
body.ondragend = function (e) { events.push( ( e.target == body ) ? 'body.ondragend': 'bubble.ondragend' ); setTimeout(finish,100); };
body.onmousedown = function (e) { events.push( ( e.target == body ) ? 'body.onmousedown': 'bubble.onmousedown' ); };
body.onmouseup = function (e) { events.push( ( e.target == body ) ? 'body.onmouseup': 'bubble.onmouseup' ); };
function finish(e) {
var i, evindex;
events = events.join('-');
/*
Normalise; reduce repeating event sequences to only 2 occurrences.
This makes the final event sequence predictable, no matter how many times the drag->dragover sequences repeat.
Two occurrances are kept in each case to allow testing to make sure the sequence really is repeating.
*/
//spec compliant - div dragenter is not cancelled, so body dragenter fires and body becomes current target
//repeats while drag is over orange or fuchsia or the body
events = events.replace(/(-orange\.ondrag-bubble\.ondrag-body\.ondragover){3,}/g,'$1$1');
//repeats while dragging over yellow
events = events.replace(/(-orange\.ondrag-bubble\.ondrag-yellow\.ondragover-bubble\.ondragover){3,}/g,'$1$1');
//repeats while dragging over blue
events = events.replace(/(-orange\.ondrag-bubble\.ondrag-blue\.ondragover-bubble\.ondragover){3,}/g,'$1$1');
//non-spec-compliant repeats while dragging over orange
events = events.replace(/(-orange\.ondrag-bubble\.ondrag-orange\.ondragover-bubble\.ondragover){3,}/g,'$1$1');
//non-spec-compliant repeats while dragging over fuchsia
events = events.replace(/(-orange\.ondrag-bubble\.ondrag-pink\.ondragover-bubble\.ondragover){3,}/g,'$1$1');
events = events.split(/-/g);
test(function () { assert_equals( events.length, 74 ); }, "Normalised number of events");
test(function () {
assert_equals(events.join(','),
/* 1 */ 'orange.onmousedown,'+ //mouse down
/* 2 */ 'bubble.onmousedown,'+
/* 3 */ 'orange.ondragstart,'+ //dragging begins
/* 4 */ 'bubble.ondragstart,'+
/* 5 */ 'orange.ondrag,'+ //mouse is over orange
/* 6 */ 'bubble.ondrag,'+
/* 7 */ 'orange.ondragenter,'+ //not cancelled
/* 8 */ 'bubble.ondragenter,'+
/* 9 */ 'body.ondragenter,'+ //so body becomes current target, and the event fires there as well
/* 10 */ 'body.ondragover,'+
/* 11 */ 'orange.ondrag,'+ //start repeating (some over orange, some over body)
/* 12 */ 'bubble.ondrag,'+
/* 13 */ 'body.ondragover,'+
/* 14 */ 'orange.ondrag,'+ //...twice to make sure it actually repeats
/* 15 */ 'bubble.ondrag,'+
/* 16 */ 'body.ondragover,'+ //end repeating
/* 17 */ 'orange.ondrag,'+ //mouse moves over pink
/* 18 */ 'bubble.ondrag,'+
/* 19 */ 'pink.ondragenter,'+ //not cancelled
/* 20 */ 'bubble.ondragenter,'+
/* 21 */ 'body.ondragover,'+ //so body becomes current target, but since it was already the target, dragenter does not need to fire again
/* 22 */ 'orange.ondrag,'+ //start repeating (some over pink, some over body)
/* 23 */ 'bubble.ondrag,'+
/* 24 */ 'body.ondragover,'+
/* 25 */ 'orange.ondrag,'+ //...twice to make sure it actually repeats
/* 26 */ 'bubble.ondrag,'+
/* 27 */ 'body.ondragover,'+ //end repeating
/* 28 */ 'orange.ondrag,'+ //mouse moves over yellow
/* 29 */ 'bubble.ondrag,'+
/* 30 */ 'yellow.ondragenter,'+
/* 31 */ 'bubble.ondragenter,'+
/* 32 */ 'body.ondragleave,'+
/* 33 */ 'yellow.ondragover,'+
/* 34 */ 'bubble.ondragover,'+
/* 35 */ 'orange.ondrag,'+ //start repeating (over yellow)
/* 36 */ 'bubble.ondrag,'+
/* 37 */ 'yellow.ondragover,'+
/* 38 */ 'bubble.ondragover,'+
/* 39 */ 'orange.ondrag,'+ //...twice to make sure it actually repeats
/* 40 */ 'bubble.ondrag,'+
/* 41 */ 'yellow.ondragover,'+
/* 42 */ 'bubble.ondragover,'+ //end repeating
/* 43 */ 'orange.ondrag,'+ //mouse moves over body
/* 44 */ 'bubble.ondrag,'+
/* 45 */ 'body.ondragenter,'+ //not cancelled
/* 46 */ 'body.ondragenter,'+ //so it fires again and sets body as current target
/* 47 */ 'yellow.ondragleave,'+
/* 48 */ 'bubble.ondragleave,'+
/* 49 */ 'body.ondragover,'+
/* 50 */ 'orange.ondrag,'+ //start repeating (over body)
/* 51 */ 'bubble.ondrag,'+
/* 52 */ 'body.ondragover,'+
/* 53 */ 'orange.ondrag,'+ //...twice to make sure it actually repeats
/* 54 */ 'bubble.ondrag,'+
/* 55 */ 'body.ondragover,'+ //end repeating
/* 56 */ 'orange.ondrag,'+ //mouse moves over blue
/* 57 */ 'bubble.ondrag,'+
/* 58 */ 'blue.ondragenter,'+
/* 59 */ 'bubble.ondragenter,'+
/* 60 */ 'body.ondragleave,'+
/* 61 */ 'blue.ondragover,'+
/* 62 */ 'bubble.ondragover,'+
/* 63 */ 'orange.ondrag,'+ //start repeating (over blue)
/* 64 */ 'bubble.ondrag,'+
/* 65 */ 'blue.ondragover,'+
/* 66 */ 'bubble.ondragover,'+
/* 67 */ 'orange.ondrag,'+ //...twice to make sure it actually repeats
/* 68 */ 'bubble.ondrag,'+
/* 69 */ 'blue.ondragover,'+
/* 70 */ 'bubble.ondragover,'+ //end repeating
/* 71 */ 'blue.ondrop,'+ //release
/* 72 */ 'bubble.ondrop,'+
/* 73 */ 'orange.ondragend,'+
/* 74 */ 'bubble.ondragend'
);
}, 'Overall sequence');
/* ondragstart */
test(function () { assert_true( events.indexOf('orange.ondragstart') != -1 ); }, "orange.ondragstart should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'orange.ondragstart') return e; }).length, 1); }, "orange.ondragstart should fire 1 time");
test(function () { assert_equals( events[2], 'orange.ondragstart' ); }, "orange.ondragstart should be event handler #3");
test(function () { assert_equals( events.indexOf('pink.ondragstart'), -1 ); }, "pink.ondragstart should not fire");
test(function () { assert_equals( events.indexOf('yellow.ondragstart'), -1 ); }, "yellow.ondragstart should not fire");
test(function () { assert_equals( events.indexOf('blue.ondragstart'), -1 ); }, "blue.ondragstart should not fire");
test(function () { assert_equals( events.indexOf('body.ondragstart'), -1 ); }, "ondragstart should not fire at the body");
test(function () { assert_true( events.indexOf('bubble.ondragstart') != -1 ); }, "ondragstart should bubble to body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'bubble.ondragstart') return e; }).length, 1); }, "ondragstart should only bubble to body 1 time");
test(function () { assert_equals( events[3], 'bubble.ondragstart' ); }, "ondragstart should bubble to body as event handler #4");
/* ondrag */
test(function () { assert_true( events.indexOf('orange.ondrag') != -1 ); }, "orange.ondrag should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'orange.ondrag') return e; }).length, 15); }, "orange.ondrag should fire 15 times");
for( var i = 0, evindex = [4,10,13,16,21,24,27,34,38,42,49,52,55,62,66]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'orange.ondrag' ); }, "orange.ondrag should be event handler #"+(evindex[i]+1));
}
test(function () { assert_equals( events.indexOf('pink.ondrag'), -1 ); }, "pink.ondrag should not fire");
test(function () { assert_equals( events.indexOf('yellow.ondrag'), -1 ); }, "yellow.ondrag should not fire");
test(function () { assert_equals( events.indexOf('blue.ondrag'), -1 ); }, "blue.ondrag should not fire");
test(function () { assert_equals( events.indexOf('body.ondrag'), -1 ); }, "ondrag should not fire at the body");
test(function () { assert_true( events.indexOf('bubble.ondrag') != -1 ); }, "ondrag should bubble to body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'bubble.ondrag') return e; }).length, 15); }, "ondrag should bubble to body 15 times");
for( var i = 0, evindex = [5,11,14,17,22,25,28,35,39,43,50,53,56,63,67]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'bubble.ondrag' ); }, "ondrag should bubble to body as event handler #"+(evindex[i]+1));
}
/* ondragenter */
test(function () { assert_true( events.indexOf('orange.ondragenter') != -1 ); }, "orange.ondragenter should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'orange.ondragenter') return e; }).length, 1); }, "orange.ondragenter should fire 1 time");
test(function () { assert_equals( events[6], 'orange.ondragenter' ); }, "orange.ondragenter should be event handler #7");
test(function () { assert_true( events.indexOf('pink.ondragenter') != -1 ); }, "pink.ondragenter should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'pink.ondragenter') return e; }).length, 1); }, "pink.ondragenter should fire 1 time");
test(function () { assert_equals( events[18], 'pink.ondragenter' ); }, "pink.ondragenter should be event handler #19");
test(function () { assert_true( events.indexOf('yellow.ondragenter') != -1 ); }, "yellow.ondragenter should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'yellow.ondragenter') return e; }).length, 1); }, "yellow.ondragenter should fire 1 time");
test(function () { assert_equals( events[29], 'yellow.ondragenter' ); }, "yellow.ondragenter should be event handler #30");
test(function () { assert_true( events.indexOf('blue.ondragenter') != -1 ); }, "blue.ondragenter should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'blue.ondragenter') return e; }).length, 1); }, "blue.ondragenter should fire 1 time");
test(function () { assert_equals( events[57], 'blue.ondragenter' ); }, "blue.ondragenter should be event handler #58");
test(function () { assert_true( events.indexOf('body.ondragenter') != -1 ); }, "ondragenter should fire at body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'body.ondragenter') return e; }).length, 3); }, "ondragenter should fire at body 2 times");
for( var i = 0, evindex = [8,44,45]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'body.ondragenter' ); }, "ondragenter should fire at body as event handler #"+(evindex[i]+1));
}
test(function () { assert_true( events.indexOf('bubble.ondragenter') != -1 ); }, "ondragenter should bubble to body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'bubble.ondragenter') return e; }).length, 4); }, "ondragenter should bubble to body 4 times");
for( var i = 0, evindex = [7,19,30,58]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'bubble.ondragenter' ); }, "ondragenter should bubble to body as event handler #"+(evindex[i]+1));
}
/* ondragover */
test(function () { assert_equals( events.indexOf('orange.ondragover'), -1 ); }, "orange.ondragover should not fire");
test(function () { assert_equals( events.indexOf('pink.ondragover'), -1 ); }, "pink.ondragover should not fire");
test(function () { assert_true( events.indexOf('yellow.ondragover') != -1 ); }, "yellow.ondragover should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'yellow.ondragover') return e; }).length, 3); }, "yellow.ondragover should fire 3 times");
for( var i = 0, evindex = [32,36,40]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'yellow.ondragover' ); }, "yellow.ondragover should be event handler #"+(evindex[i]+1));
}
test(function () { assert_true( events.indexOf('blue.ondragover') != -1 ); }, "blue.ondragover should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'blue.ondragover') return e; }).length, 3); }, "blue.ondragover should fire 9 times");
for( var i = 0, evindex = [60,64,68]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'blue.ondragover' ); }, "blue.ondragover should be event handler #"+(evindex[i]+1));
}
test(function () { assert_true( events.indexOf('body.ondragover') != -1 ); }, "ondragover should fire at body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'body.ondragover') return e; }).length, 9); }, "ondragover should fire at body 2 times");
for( var i = 0, evindex = [9,12,15,20,23,26,48,51,54]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'body.ondragover' ); }, "ondragover should fire at body as event handler #"+(evindex[i]+1));
}
test(function () { assert_true( events.indexOf('bubble.ondragover') != -1 ); }, "ondragover should bubble to body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'bubble.ondragover') return e; }).length, 6); }, "ondragover should bubble to body 6 times");
for( var i = 0, evindex = [33,37,41,61,65,69]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'bubble.ondragover' ); }, "ondragover should bubble to body as event handler #"+(evindex[i]+1));
}
/* ondragleave */
test(function () { assert_equals( events.indexOf('orange.ondragleave'), -1 ); }, "orange.ondragleave should not fire");
test(function () { assert_equals( events.indexOf('pink.ondragleave'), -1 ); }, "pink.ondragleave should not fire");
test(function () { assert_true( events.indexOf('yellow.ondragleave') != -1 ); }, "yellow.ondragleave should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'yellow.ondragleave') return e; }).length, 1); }, "yellow.ondragleave should fire 1 time");
test(function () { assert_equals( events[46], 'yellow.ondragleave' ); }, "yellow.ondragleave should be event handler #47");
test(function () { assert_equals( events.indexOf('blue.ondragleave'), -1 ); }, "blue.ondragleave should not fire");
test(function () { assert_true( events.indexOf('body.ondragleave') != -1 ); }, "ondragleave should fire at body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'body.ondragleave') return e; }).length, 2); }, "ondragleave should fire at body 2 times");
for( var i = 0, evindex = [31,59]; i < evindex.length; i++ ) {
test(function () { assert_equals( events[evindex[i]], 'body.ondragleave' ); }, "ondragleave should fire at body as event handler #"+(evindex[i]+1));
}
test(function () { assert_true( events.indexOf('bubble.ondragleave') != -1 ); }, "ondragleave should bubble to body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'bubble.ondragleave') return e; }).length, 1); }, "ondragleave should bubble to body 1 time");
test(function () { assert_equals( events[47], 'bubble.ondragleave' ); }, "ondragleave should bubble to body as event handler #48");
/* ondrop */
test(function () { assert_equals( events.indexOf('orange.ondrop'), -1 ); }, "orange.ondrop should not fire");
test(function () { assert_equals( events.indexOf('pink.ondrop'), -1 ); }, "pink.ondrop should not fire");
test(function () { assert_equals( events.indexOf('yellow.ondrop'), -1 ); }, "yellow.ondrop should not fire");
test(function () { assert_true( events.indexOf('blue.ondrop') != -1 ); }, "blue.ondrop should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'blue.ondrop') return e; }).length, 1); }, "blue.ondrop should fire 1 time");
test(function () { assert_equals( events[70], 'blue.ondrop' ); }, "blue.ondrop should be event handler #71");
test(function () { assert_equals( events.indexOf('body.ondrop'), -1 ); }, "ondrop should not fire at body");
test(function () { assert_true( events.indexOf('bubble.ondrop') != -1 ); }, "ondrop should bubble to body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'bubble.ondrop') return e; }).length, 1); }, "ondrop should bubble to body 1 time");
test(function () { assert_equals( events[71], 'bubble.ondrop' ); }, "ondrop should bubble to body as event handler #72");
/* ondragend */
test(function () { assert_true( events.indexOf('orange.ondragend') != -1 ); }, "orange.ondragend should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'orange.ondragend') return e; }).length, 1); }, "orange.ondragend should fire 1 time");
test(function () { assert_equals( events[72], 'orange.ondragend' ); }, "orange.ondragend should be event handler #73");
test(function () { assert_equals( events.indexOf('pink.ondragend'), -1 ); }, "pink.ondragend should not fire");
test(function () { assert_equals( events.indexOf('yellow.ondragend'), -1 ); }, "yellow.ondragend should not fire");
test(function () { assert_equals( events.indexOf('blue.ondragend'), -1 ); }, "blue.ondragend should not fire");
test(function () { assert_equals( events.indexOf('body.ondragend'), -1 ); }, "ondragend should not fire at body");
test(function () { assert_true( events.indexOf('bubble.ondragend') != -1 ); }, "ondragend should bubble to body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'bubble.ondragend') return e; }).length, 1); }, "ondragend should bubble to body 1 time");
test(function () { assert_equals( events[73], 'bubble.ondragend' ); }, "ondragend should bubble to body as event handler #74");
/* onmousedown */
test(function () { assert_true( events.indexOf('orange.onmousedown') != -1 ); }, "orange.onmousedown should fire");
test(function () { assert_equals( events.filter(function (e) { if (e == 'orange.onmousedown') return e; }).length, 1); }, "orange.onmousedown should fire 1 time");
test(function () { assert_equals( events[0], 'orange.onmousedown' ); }, "orange.onmousedown should be event handler #1");
test(function () { assert_equals( events.indexOf('pink.onmousedown'), -1 ); }, "pink.onmousedown should not fire");
test(function () { assert_equals( events.indexOf('yellow.onmousedown'), -1 ); }, "yellow.onmousedown should not fire");
test(function () { assert_equals( events.indexOf('blue.onmousedown'), -1 ); }, "blue.onmousedown should not fire");
test(function () { assert_equals( events.indexOf('body.onmousedown'), -1 ); }, "onmousedown should not fire at body");
test(function () { assert_true( events.indexOf('bubble.onmousedown') != -1 ); }, "onmousedown should bubble to body");
test(function () { assert_equals( events.filter(function (e) { if (e == 'bubble.onmousedown') return e; }).length, 1); }, "onmousedown should bubble to body 1 time");
test(function () { assert_equals( events[1], 'bubble.onmousedown' ); }, "onmousedown should bubble to body as event handler #1");
/* onmouseup */
test(function () { assert_equals( events.indexOf('orange.onmouseup'), -1 ); }, "orange.onmouseup should not fire");
test(function () { assert_equals( events.indexOf('pink.onmouseup'), -1 ); }, "pink.onmouseup should not fire");
test(function () { assert_equals( events.indexOf('yellow.onmouseup'), -1 ); }, "yellow.onmouseup should not fire");
test(function () { assert_equals( events.indexOf('blue.onmouseup'), -1 ); }, "blue.onmouseup should not fire");
test(function () { assert_equals( events.indexOf('body.onmouseup'), -1 ); }, "onmouseup should not fire at body");
test(function () { assert_equals( events.indexOf('bubble.onmouseup'), -1 ); }, "onmouseup should not bubble to body");
done();
}
};
</script>
<div id="testhere">
<div draggable='true' id='orange'></div>
<div id='fuchsia'></div>
<div id='yellow'></div>
<div id='blue'></div>
</div>
<p>If you have already clicked on this page, reload it.</p>
<p>Use your pointing device to slowly drag the orange square over the pink square then the yellow square, then the blue square, and release it over the blue square (make sure the mouse remains over each square for at least 1 second, and over the gaps between squares for at least 1 second). Fail if no new text appears below.</p>
<div id="log"></div>
| frivoal/presto-testo | core/standards/dnd/events/events-suite.html | HTML | bsd-3-clause | 24,906 |
import json
import mock
from sentry.plugins.helpers import get_option, set_option
from sentry.testutils import TestCase
from sentry.models import set_sentry_version, Option
from sentry.tasks.check_update import check_update, PYPI_URL
class CheckUpdateTest(TestCase):
OLD = '5.0.0'
CURRENT = '5.5.0-DEV'
NEW = '1000000000.5.1'
KEY = 'sentry:latest_version'
def test_run_check_update_task(self):
with mock.patch('sentry.tasks.check_update.fetch_url_content') as fetch:
fetch.return_value = (
None, None, json.dumps({'info': {'version': self.NEW}})
)
check_update() # latest_version > current_version
fetch.assert_called_once_with(PYPI_URL)
self.assertEqual(get_option(key=self.KEY), self.NEW)
def test_run_check_update_task_with_bad_response(self):
with mock.patch('sentry.tasks.check_update.fetch_url_content') as fetch:
fetch.return_value = (None, None, '')
check_update() # latest_version == current_version
fetch.assert_called_once_with(PYPI_URL)
self.assertEqual(get_option(key=self.KEY), None)
def test_set_sentry_version_empty_latest(self):
set_sentry_version(latest=self.NEW)
self.assertEqual(get_option(key=self.KEY), self.NEW)
def test_set_sentry_version_new(self):
set_option(self.KEY, self.OLD)
with mock.patch('sentry.get_version') as get_version:
get_version.return_value = self.CURRENT
set_sentry_version(latest=self.NEW)
self.assertEqual(Option.objects.get_value(key=self.KEY), self.NEW)
def test_set_sentry_version_old(self):
set_option(self.KEY, self.NEW)
with mock.patch('sentry.get_version') as get_version:
get_version.return_value = self.CURRENT
set_sentry_version(latest=self.OLD)
self.assertEqual(Option.objects.get_value(key=self.KEY), self.NEW)
| beni55/sentry | tests/sentry/tasks/check_update/tests.py | Python | bsd-3-clause | 1,970 |
// Copyright 2016 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.
#include "chrome/renderer/chrome_render_frame_observer.h"
#include "base/test/histogram_tester.h"
#include "chrome/test/base/chrome_render_view_test.h"
#include "components/translate/content/common/translate_messages.h"
#include "components/translate/content/renderer/translate_helper.h"
#include "components/translate/core/common/translate_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "third_party/WebKit/public/web/WebView.h"
// Constants for UMA statistic collection.
static const char kTranslateCaptureText[] = "Translate.CaptureText";
class ChromeRenderFrameObserverTest : public ChromeRenderViewTest {};
TEST_F(ChromeRenderFrameObserverTest, SkipCapturingSubFrames) {
base::HistogramTester histogram_tester;
LoadHTML(
"<!DOCTYPE html><body>"
"This is a main document"
"<iframe srcdoc=\"This a document in an iframe.\">"
"</body>");
view_->GetWebView()->updateAllLifecyclePhases();
const IPC::Message* message = render_thread_->sink().GetUniqueMessageMatching(
ChromeFrameHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeFrameHostMsg_TranslateLanguageDetermined::Param params;
ChromeFrameHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_TRUE(base::get<1>(params)) << "Page should be translatable.";
// Should have 2 samples: one for preliminary capture, one for final capture.
// If there are more, then subframes are being captured more than once.
histogram_tester.ExpectTotalCount(kTranslateCaptureText, 2);
}
| axinging/chromium-crosswalk | chrome/renderer/chrome_render_frame_observer_browsertest.cc | C++ | bsd-3-clause | 1,787 |
var clientid = '4c3b2c1b-364c-4ceb-9416-8371dd4ebe3a';
if (/^#access_token=/.test(location.hash)) {
location.assign('/Home/index?auto=1&ss=0' +
'&cors=1' +
'&client_id=' + clientid+
'&origins=https://webdir.online.lync.com/autodiscover/autodiscoverservice.svc/root');
}
$('.loginForm').submit(function (event) {
event.preventDefault();
if (location.hash == '') {
location.assign('https://login.windows.net/common/oauth2/authorize?response_type=token' +
'&client_id=' + clientid+
'&redirect_uri=http://healthcarenocc.azurewebsites.net/' +
'&resource=https://webdir.online.lync.com');
}
});
| unixcbt/demos | LamnaHealthCare-Patient/obj/Release/Package/PackageTmp/Scripts/onlinesignin.js | JavaScript | bsd-3-clause | 698 |
<?php
$this->title = 'Update Country Detail: ' . ' ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => 'Countries', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="countries-update">
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| 61ds/aging | _protected/backend/views/countries/update.php | PHP | bsd-3-clause | 405 |
---
title: Modify an Object Nested Within an Object
localeTitle: تعديل كائن متداخل داخل كائن
---
## تعديل كائن متداخل داخل كائن
طريقة:
* تذكر أن الكائن الذي تريد تغييره هو مستويين عميقين ، ومن السهل استخدام `dot-notation` في هذه الحالة.
* ببساطة ، قم بتعريف الكائن ثم استخدم `dot-notation` للوصول إلى الكائن الثاني وأخيرًا العنصر الأخير الذي ترغب في تعديله.
## مثال:
`let myObject = {
level_1: 'outside',
first_level_object: {
level_2: '2 levels deep',
second_level_object: {
level_3: '3 levels deep'
}
}
};
//The following line of code will modify the data found in level_2.
myObject.first_level_object.level_2 = 'level-2 has been reached';
`
## حل:
`let userActivity = {
id: 23894201352,
date: 'January 1, 2017',
data: {
totalUsers: 51,
online: 42
}
};
// change code below this line
userActivity.data.online = 45;
// change code above this line
console.log(userActivity);
` | otavioarc/freeCodeCamp | guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-object-nested-within-an-object/index.md | Markdown | bsd-3-clause | 1,177 |
/* ../netlib/dgehrd.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */
#include "FLA_f2c.h" /* Table of constant values */
static integer c__1 = 1;
static integer c_n1 = -1;
static integer c__3 = 3;
static integer c__2 = 2;
static integer c__65 = 65;
static doublereal c_b25 = -1.;
static doublereal c_b26 = 1.;
/* > \brief \b DGEHRD */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DGEHRD + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dgehrd. f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dgehrd. f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dgehrd. f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE DGEHRD( N, ILO, IHI, A, LDA, TAU, WORK, LWORK, INFO ) */
/* .. Scalar Arguments .. */
/* INTEGER IHI, ILO, INFO, LDA, LWORK, N */
/* .. */
/* .. Array Arguments .. */
/* DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) */
/* .. */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > DGEHRD reduces a real general matrix A to upper Hessenberg form H by */
/* > an orthogonal similarity transformation: Q**T * A * Q = H . */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] ILO */
/* > \verbatim */
/* > ILO is INTEGER */
/* > \endverbatim */
/* > */
/* > \param[in] IHI */
/* > \verbatim */
/* > IHI is INTEGER */
/* > */
/* > It is assumed that A is already upper triangular in rows */
/* > and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally */
/* > set by a previous call to DGEBAL;
otherwise they should be */
/* > set to 1 and N respectively. See Further Details. */
/* > 1 <= ILO <= IHI <= N, if N > 0;
ILO=1 and IHI=0, if N=0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is DOUBLE PRECISION array, dimension (LDA,N) */
/* > On entry, the N-by-N general matrix to be reduced. */
/* > On exit, the upper triangle and the first subdiagonal of A */
/* > are overwritten with the upper Hessenberg matrix H, and the */
/* > elements below the first subdiagonal, with the array TAU, */
/* > represent the orthogonal matrix Q as a product of elementary */
/* > reflectors. See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] TAU */
/* > \verbatim */
/* > TAU is DOUBLE PRECISION array, dimension (N-1) */
/* > The scalar factors of the elementary reflectors (see Further */
/* > Details). Elements 1:ILO-1 and IHI:N-1 of TAU are set to */
/* > zero. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is DOUBLE PRECISION array, dimension (LWORK) */
/* > On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */
/* > \endverbatim */
/* > */
/* > \param[in] LWORK */
/* > \verbatim */
/* > LWORK is INTEGER */
/* > The length of the array WORK. LWORK >= max(1,N). */
/* > For optimum performance LWORK >= N*NB, where NB is the */
/* > optimal blocksize. */
/* > */
/* > If LWORK = -1, then a workspace query is assumed;
the routine */
/* > only calculates the optimal size of the WORK array, returns */
/* > this value as the first entry of the WORK array, and no error */
/* > message related to LWORK is issued by XERBLA. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date November 2011 */
/* > \ingroup doubleGEcomputational */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > The matrix Q is represented as a product of (ihi-ilo) elementary */
/* > reflectors */
/* > */
/* > Q = H(ilo) H(ilo+1) . . . H(ihi-1). */
/* > */
/* > Each H(i) has the form */
/* > */
/* > H(i) = I - tau * v * v**T */
/* > */
/* > where tau is a real scalar, and v is a real vector with */
/* > v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0;
v(i+2:ihi) is stored on */
/* > exit in A(i+2:ihi,i), and tau in TAU(i). */
/* > */
/* > The contents of A are illustrated by the following example, with */
/* > n = 7, ilo = 2 and ihi = 6: */
/* > */
/* > on entry, on exit, */
/* > */
/* > ( a a a a a a a ) ( a a h h h h a ) */
/* > ( a a a a a a ) ( a h h h h a ) */
/* > ( a a a a a a ) ( h h h h h h ) */
/* > ( a a a a a a ) ( v2 h h h h h ) */
/* > ( a a a a a a ) ( v2 v3 h h h h ) */
/* > ( a a a a a a ) ( v2 v3 v4 h h h ) */
/* > ( a ) ( a ) */
/* > */
/* > where a denotes an element of the original matrix A, h denotes a */
/* > modified element of the upper Hessenberg matrix H, and vi denotes an */
/* > element of the vector defining H(i). */
/* > */
/* > This file is a slight modification of LAPACK-3.0's DGEHRD */
/* > subroutine incorporating improvements proposed by Quintana-Orti and */
/* > Van de Geijn (2006). (See DLAHR2.) */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */
int dgehrd_(integer *n, integer *ilo, integer *ihi, doublereal *a, integer *lda, doublereal *tau, doublereal *work, integer *lwork, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3, i__4;
/* Local variables */
integer i__, j;
doublereal t[4160] /* was [65][64] */
;
integer ib;
doublereal ei;
integer nb, nh, nx, iws;
extern /* Subroutine */
int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *);
integer nbmin, iinfo;
extern /* Subroutine */
int dtrmm_(char *, char *, char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), daxpy_( integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dgehd2_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlahr2_( integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *);
extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *);
integer ldwork, lwkopt;
logical lquery;
/* -- LAPACK computational routine (version 3.4.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* November 2011 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. Local Arrays .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Test the input parameters */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--tau;
--work;
/* Function Body */
*info = 0;
/* Computing MIN */
i__1 = 64;
i__2 = ilaenv_(&c__1, "DGEHRD", " ", n, ilo, ihi, &c_n1); // , expr subst
nb = min(i__1,i__2);
lwkopt = *n * nb;
work[1] = (doublereal) lwkopt;
lquery = *lwork == -1;
if (*n < 0)
{
*info = -1;
}
else if (*ilo < 1 || *ilo > max(1,*n))
{
*info = -2;
}
else if (*ihi < min(*ilo,*n) || *ihi > *n)
{
*info = -3;
}
else if (*lda < max(1,*n))
{
*info = -5;
}
else if (*lwork < max(1,*n) && ! lquery)
{
*info = -8;
}
if (*info != 0)
{
i__1 = -(*info);
xerbla_("DGEHRD", &i__1);
return 0;
}
else if (lquery)
{
return 0;
}
/* Set elements 1:ILO-1 and IHI:N-1 of TAU to zero */
i__1 = *ilo - 1;
for (i__ = 1;
i__ <= i__1;
++i__)
{
tau[i__] = 0.;
/* L10: */
}
i__1 = *n - 1;
for (i__ = max(1,*ihi);
i__ <= i__1;
++i__)
{
tau[i__] = 0.;
/* L20: */
}
/* Quick return if possible */
nh = *ihi - *ilo + 1;
if (nh <= 1)
{
work[1] = 1.;
return 0;
}
/* Determine the block size */
/* Computing MIN */
i__1 = 64;
i__2 = ilaenv_(&c__1, "DGEHRD", " ", n, ilo, ihi, &c_n1); // , expr subst
nb = min(i__1,i__2);
nbmin = 2;
iws = 1;
if (nb > 1 && nb < nh)
{
/* Determine when to cross over from blocked to unblocked code */
/* (last block is always handled by unblocked code) */
/* Computing MAX */
i__1 = nb;
i__2 = ilaenv_(&c__3, "DGEHRD", " ", n, ilo, ihi, &c_n1); // , expr subst
nx = max(i__1,i__2);
if (nx < nh)
{
/* Determine if workspace is large enough for blocked code */
iws = *n * nb;
if (*lwork < iws)
{
/* Not enough workspace to use optimal NB: determine the */
/* minimum value of NB, and reduce NB or force use of */
/* unblocked code */
/* Computing MAX */
i__1 = 2;
i__2 = ilaenv_(&c__2, "DGEHRD", " ", n, ilo, ihi, & c_n1); // , expr subst
nbmin = max(i__1,i__2);
if (*lwork >= *n * nbmin)
{
nb = *lwork / *n;
}
else
{
nb = 1;
}
}
}
}
ldwork = *n;
if (nb < nbmin || nb >= nh)
{
/* Use unblocked code below */
i__ = *ilo;
}
else
{
/* Use blocked code */
i__1 = *ihi - 1 - nx;
i__2 = nb;
for (i__ = *ilo;
i__2 < 0 ? i__ >= i__1 : i__ <= i__1;
i__ += i__2)
{
/* Computing MIN */
i__3 = nb;
i__4 = *ihi - i__; // , expr subst
ib = min(i__3,i__4);
/* Reduce columns i:i+ib-1 to Hessenberg form, returning the */
/* matrices V and T of the block reflector H = I - V*T*V**T */
/* which performs the reduction, and also the matrix Y = A*V*T */
dlahr2_(ihi, &i__, &ib, &a[i__ * a_dim1 + 1], lda, &tau[i__], t, & c__65, &work[1], &ldwork);
/* Apply the block reflector H to A(1:ihi,i+ib:ihi) from the */
/* right, computing A := A - Y * V**T. V(i+ib,ib-1) must be set */
/* to 1 */
ei = a[i__ + ib + (i__ + ib - 1) * a_dim1];
a[i__ + ib + (i__ + ib - 1) * a_dim1] = 1.;
i__3 = *ihi - i__ - ib + 1;
dgemm_("No transpose", "Transpose", ihi, &i__3, &ib, &c_b25, & work[1], &ldwork, &a[i__ + ib + i__ * a_dim1], lda, & c_b26, &a[(i__ + ib) * a_dim1 + 1], lda);
a[i__ + ib + (i__ + ib - 1) * a_dim1] = ei;
/* Apply the block reflector H to A(1:i,i+1:i+ib-1) from the */
/* right */
i__3 = ib - 1;
dtrmm_("Right", "Lower", "Transpose", "Unit", &i__, &i__3, &c_b26, &a[i__ + 1 + i__ * a_dim1], lda, &work[1], &ldwork);
i__3 = ib - 2;
for (j = 0;
j <= i__3;
++j)
{
daxpy_(&i__, &c_b25, &work[ldwork * j + 1], &c__1, &a[(i__ + j + 1) * a_dim1 + 1], &c__1);
/* L30: */
}
/* Apply the block reflector H to A(i+1:ihi,i+ib:n) from the */
/* left */
i__3 = *ihi - i__;
i__4 = *n - i__ - ib + 1;
dlarfb_("Left", "Transpose", "Forward", "Columnwise", &i__3, & i__4, &ib, &a[i__ + 1 + i__ * a_dim1], lda, t, &c__65, &a[ i__ + 1 + (i__ + ib) * a_dim1], lda, &work[1], &ldwork);
/* L40: */
}
}
/* Use unblocked code to reduce the rest of the matrix */
dgehd2_(n, &i__, ihi, &a[a_offset], lda, &tau[1], &work[1], &iinfo);
work[1] = (doublereal) iws;
return 0;
/* End of DGEHRD */
}
/* dgehrd_ */
| alishakiba/libflame | src/map/lapack2flamec/f2c/c/dgehrd.c | C | bsd-3-clause | 13,475 |
package org.buildmlearn.toolkit.flashcardtemplate.data;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* Created by Anupam (opticod) on 10/8/16.
*/
/**
* @brief Contains xml data utils for flash card template's simulator.
*/
public class DataUtils {
public static String[] readTitleAuthor() {
String result[] = new String[2];
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db;
Document doc;
try {
File fXmlFile = new File(org.buildmlearn.toolkit.flashcardtemplate.Constants.XMLFileName);
db = dbf.newDocumentBuilder();
doc = db.parse(fXmlFile);
doc.normalize();
result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
.item(0).getNodeValue();
result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
.item(0).getNodeValue();
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
return result;
}
}
| opticod/BuildmLearn-Toolkit-Android | source-code/app/src/main/java/org/buildmlearn/toolkit/flashcardtemplate/data/DataUtils.java | Java | bsd-3-clause | 1,360 |
var vows = require('vows'),
assert = require('assert'),
path = require('path'),
fs = require('fs'),
exec = require('child_process').exec,
base = path.join(__dirname, 'assets/badmodule/'),
buildBase = path.join(base, 'build'),
srcBase = path.join(base, 'src/foo'),
rimraf = require('rimraf');
var tests = {
'clean build': {
topic: function() {
rimraf(path.join(buildBase, 'foo'), this.callback);
},
'should not have build dir and': {
topic: function() {
var self = this;
fs.stat(path.join(buildBase, 'foo'), function(err) {
self.callback(null, err);
});
},
'should not have build/foo': function(foo, err) {
assert.isNotNull(err);
assert.equal(err.code, 'ENOENT');
},
'should build foo and': {
topic: function() {
var self = this,
child;
process.chdir(path.resolve(base, srcBase));
child = exec('../../../../../bin/shifter --no-global-config', function (error, stdout, stderr) {
self.callback(null, {
error: error,
stderr: stderr
});
});
},
'should fail with an error code 1': function (topic) {
assert.equal(topic.error.code, 1);
},
'should fail with an error message': function(topic) {
assert.isNotNull(topic.stderr);
}
}
}
}
};
vows.describe('building badmodule with UglifyJS via command line').addBatch(tests).export(module);
| wf2/shifter | tests/14-builder-uglify-badmodule-cmd.js | JavaScript | bsd-3-clause | 1,833 |
// Copyright (c) 2012 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.
#ifndef UI_GFX_IMAGE_SKIA_OPERATIONS_H_
#define UI_GFX_IMAGE_SKIA_OPERATIONS_H_
#include "base/gtest_prod_util.h"
#include "skia/ext/image_operations.h"
#include "ui/base/ui_export.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/shadow_value.h"
namespace gfx {
class ImageSkia;
class Rect;
class Size;
class UI_EXPORT ImageSkiaOperations {
public:
// Create an image that is a blend of two others. The alpha argument
// specifies the opacity of the second imag. The provided image must
// use the kARGB_8888_Config config and be of equal dimensions.
static ImageSkia CreateBlendedImage(const ImageSkia& first,
const ImageSkia& second,
double alpha);
// Creates an image that is the original image with opacity set to |alpha|.
static ImageSkia CreateTransparentImage(const ImageSkia& image, double alpha);
// Creates new image by painting first and second image respectively.
// The second image is centered in respect to the first image.
static ImageSkia CreateSuperimposedImage(const ImageSkia& first,
const ImageSkia& second);
// Create an image that is the original image masked out by the mask defined
// in the alpha image. The images must use the kARGB_8888_Config config and
// be of equal dimensions.
static ImageSkia CreateMaskedImage(const ImageSkia& first,
const ImageSkia& alpha);
// Create an image that is cropped from another image. This is special
// because it tiles the original image, so your coordinates can extend
// outside the bounds of the original image.
static ImageSkia CreateTiledImage(const ImageSkia& image,
int src_x, int src_y,
int dst_w, int dst_h);
// Shift an image's HSL values. The shift values are in the range of 0-1,
// with the option to specify -1 for 'no change'. The shift values are
// defined as:
// hsl_shift[0] (hue): The absolute hue value for the image - 0 and 1 map
// to 0 and 360 on the hue color wheel (red).
// hsl_shift[1] (saturation): A saturation shift for the image, with the
// following key values:
// 0 = remove all color.
// 0.5 = leave unchanged.
// 1 = fully saturate the image.
// hsl_shift[2] (lightness): A lightness shift for the image, with the
// following key values:
// 0 = remove all lightness (make all pixels black).
// 0.5 = leave unchanged.
// 1 = full lightness (make all pixels white).
static ImageSkia CreateHSLShiftedImage(const gfx::ImageSkia& image,
const color_utils::HSL& hsl_shift);
// Creates a button background image by compositing the color and image
// together, then applying the mask. This is a highly specialized composite
// operation that is the equivalent of drawing a background in |color|,
// tiling |image| over the top, and then masking the result out with |mask|.
// The images must use kARGB_8888_Config config.
static ImageSkia CreateButtonBackground(SkColor color,
const gfx::ImageSkia& image,
const gfx::ImageSkia& mask);
// Returns an image which is a subset of |image| with bounds |subset_bounds|.
// The |image| cannot use kA1_Config config.
static ImageSkia ExtractSubset(const gfx::ImageSkia& image,
const gfx::Rect& subset_bounds);
// Creates an image by resizing |source| to given |target_dip_size|.
static ImageSkia CreateResizedImage(const ImageSkia& source,
skia::ImageOperations::ResizeMethod methd,
const Size& target_dip_size);
// Creates an image with drop shadow defined in |shadows| for |source|.
static ImageSkia CreateImageWithDropShadow(const ImageSkia& source,
const ShadowValues& shadows);
private:
ImageSkiaOperations(); // Class for scoping only.
};
} // namespace gfx
#endif // UI_GFX_IMAGE_IMAGE_SKIA_OPERATIONS_H_
| leighpauls/k2cro4 | ui/gfx/image/image_skia_operations.h | C | bsd-3-clause | 4,370 |
use std::ops::Mul;
use num::One;
use structs::mat;
use traits::operations::{Inv, Transpose};
use traits::geometry::{Translate, Rotate, Transform, AbsoluteRotate};
impl One for mat::Identity {
#[inline]
fn one() -> mat::Identity {
mat::Identity::new()
}
}
impl Inv for mat::Identity {
fn inv(&self) -> Option<mat::Identity> {
Some(mat::Identity::new())
}
fn inv_mut(&mut self) -> bool {
true
}
}
impl<T: Clone> Mul<T> for mat::Identity {
type Output = T;
#[inline]
fn mul(self, other: T) -> T {
other
}
}
impl Transpose for mat::Identity {
#[inline]
fn transpose(&self) -> mat::Identity {
mat::Identity::new()
}
#[inline]
fn transpose_mut(&mut self) {
}
}
impl<V: Clone> Translate<V> for mat::Identity {
#[inline]
fn translate(&self, v: &V) -> V {
v.clone()
}
#[inline]
fn inv_translate(&self, v: &V) -> V {
v.clone()
}
}
impl<V: Clone> Rotate<V> for mat::Identity {
#[inline]
fn rotate(&self, v: &V) -> V {
v.clone()
}
#[inline]
fn inv_rotate(&self, v: &V) -> V {
v.clone()
}
}
impl<V: Clone> AbsoluteRotate<V> for mat::Identity {
#[inline]
fn absolute_rotate(&self, v: &V) -> V {
v.clone()
}
}
impl<V: Clone> Transform<V> for mat::Identity {
#[inline]
fn transform(&self, v: &V) -> V {
v.clone()
}
#[inline]
fn inv_transform(&self, v: &V) -> V {
v.clone()
}
}
| jaredly/nalgebra | src/structs/spec/identity.rs | Rust | bsd-3-clause | 1,523 |
/* jshint multistr:true */
/* jshint -W040 */
'use strict';
var envify = require('envify/custom');
var es3ify = require('es3ify');
var grunt = require('grunt');
var UglifyJS = require('uglify-js');
var uglifyify = require('uglifyify');
var derequire = require('derequire');
var collapser = require('bundle-collapser/plugin');
var SIMPLE_TEMPLATE =
'/**\n\
* @PACKAGE@ v@VERSION@\n\
*/';
var LICENSE_TEMPLATE =
'/**\n\
* @PACKAGE@ v@VERSION@\n\
*\n\
* Copyright 2013-2014, Facebook, Inc.\n\
* All rights reserved.\n\
*\n\
* This source code is licensed under the BSD-style license found in the\n\
* LICENSE file in the root directory of this source tree. An additional grant\n\
* of patent rights can be found in the PATENTS file in the same directory.\n\
*\n\
*/';
function minify(src) {
return UglifyJS.minify(src, { fromString: true }).code;
}
// TODO: move this out to another build step maybe.
function bannerify(src) {
var version = grunt.config.data.pkg.version;
var packageName = this.data.packageName || this.data.standalone;
return LICENSE_TEMPLATE.replace('@PACKAGE@', packageName)
.replace('@VERSION@', version) +
'\n' + src;
}
function simpleBannerify(src) {
var version = grunt.config.data.pkg.version;
var packageName = this.data.packageName || this.data.standalone;
return SIMPLE_TEMPLATE.replace('@PACKAGE@', packageName)
.replace('@VERSION@', version) +
'\n' + src;
}
// Our basic config which we'll add to to make our other builds
var basic = {
entries: [
'./build/modules/React.js'
],
outfile: './build/react.js',
debug: false,
standalone: 'React',
transforms: [envify({NODE_ENV: 'development'})],
plugins: [collapser],
after: [es3ify.transform, derequire, simpleBannerify]
};
var min = {
entries: [
'./build/modules/React.js'
],
outfile: './build/react.min.js',
debug: false,
standalone: 'React',
transforms: [envify({NODE_ENV: 'production'}), uglifyify],
plugins: [collapser],
after: [es3ify.transform, derequire, minify, bannerify]
};
var transformer = {
entries:[
'./vendor/browser-transforms.js'
],
outfile: './build/JSXTransformer.js',
debug: false,
standalone: 'JSXTransformer',
transforms: [],
plugins: [collapser],
after: [es3ify.transform, derequire, simpleBannerify]
};
var addons = {
entries: [
'./build/modules/ReactWithAddons.js'
],
outfile: './build/react-with-addons.js',
debug: false,
standalone: 'React',
packageName: 'React (with addons)',
transforms: [envify({NODE_ENV: 'development'})],
plugins: [collapser],
after: [es3ify.transform, derequire, simpleBannerify]
};
var addonsMin = {
entries: [
'./build/modules/ReactWithAddons.js'
],
outfile: './build/react-with-addons.min.js',
debug: false,
standalone: 'React',
packageName: 'React (with addons)',
transforms: [envify({NODE_ENV: 'production'}), uglifyify],
plugins: [collapser],
after: [es3ify.transform, derequire, minify, bannerify]
};
var withCodeCoverageLogging = {
entries: [
'./build/modules/React.js'
],
outfile: './build/react.js',
debug: true,
standalone: 'React',
transforms: [
envify({NODE_ENV: 'development'}),
require('coverify')
],
plugins: [collapser]
};
module.exports = {
basic: basic,
min: min,
transformer: transformer,
addons: addons,
addonsMin: addonsMin,
withCodeCoverageLogging: withCodeCoverageLogging
};
| kchia/react | grunt/config/browserify.js | JavaScript | bsd-3-clause | 3,473 |
"""
Tests for structural time series models
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import pandas as pd
import os
import warnings
from statsmodels.datasets import macrodata
from statsmodels.tsa.statespace import structural
from statsmodels.tsa.statespace.structural import UnobservedComponents
from .results import results_structural
from statsmodels.tools import add_constant
from numpy.testing import assert_equal, assert_almost_equal, assert_raises, assert_allclose
from nose.exc import SkipTest
try:
import matplotlib.pyplot as plt
have_matplotlib = True
except ImportError:
have_matplotlib = False
dta = macrodata.load_pandas().data
dta.index = pd.date_range(start='1959-01-01', end='2009-07-01', freq='QS')
def run_ucm(name):
true = getattr(results_structural, name)
for model in true['models']:
kwargs = model.copy()
kwargs.update(true['kwargs'])
# Make a copy of the data
values = dta.copy()
freq = kwargs.pop('freq', None)
if freq is not None:
values.index = pd.date_range(start='1959-01-01', periods=len(dta),
freq=freq)
# Test pandas exog
if 'exog' in kwargs:
# Default value here is pd.Series object
exog = np.log(values['realgdp'])
# Also allow a check with a 1-dim numpy array
if kwargs['exog'] == 'numpy':
exog = exog.values.squeeze()
kwargs['exog'] = exog
# Create the model
mod = UnobservedComponents(values['unemp'], **kwargs)
# Smoke test for starting parameters, untransform, transform
# Also test that transform and untransform are inverses
mod.start_params
assert_allclose(mod.start_params, mod.transform_params(mod.untransform_params(mod.start_params)))
# Fit the model at the true parameters
res_true = mod.filter(true['params'])
# Check that the cycle bounds were computed correctly
freqstr = freq[0] if freq is not None else values.index.freqstr[0]
if freqstr == 'A':
cycle_period_bounds = (1.5, 12)
elif freqstr == 'Q':
cycle_period_bounds = (1.5*4, 12*4)
elif freqstr == 'M':
cycle_period_bounds = (1.5*12, 12*12)
else:
# If we have no information on data frequency, require the
# cycle frequency to be between 0 and pi
cycle_period_bounds = (2, np.inf)
# Test that the cycle frequency bound is correct
assert_equal(mod.cycle_frequency_bound,
(2*np.pi / cycle_period_bounds[1],
2*np.pi / cycle_period_bounds[0])
)
# Test that the likelihood is correct
rtol = true.get('rtol', 1e-7)
atol = true.get('atol', 0)
assert_allclose(res_true.llf, true['llf'], rtol=rtol, atol=atol)
# Smoke test for plot_components
if have_matplotlib:
fig = res_true.plot_components()
plt.close(fig)
# Now fit the model via MLE
with warnings.catch_warnings(record=True) as w:
res = mod.fit(disp=-1)
# If we found a higher likelihood, no problem; otherwise check
# that we're very close to that found by R
if res.llf <= true['llf']:
assert_allclose(res.llf, true['llf'], rtol=1e-4)
# Smoke test for summary
res.summary()
def test_irregular():
run_ucm('irregular')
def test_fixed_intercept():
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
run_ucm('fixed_intercept')
message = ("Specified model does not contain a stochastic element;"
" irregular component added.")
assert_equal(str(w[0].message), message)
def test_deterministic_constant():
run_ucm('deterministic_constant')
def test_random_walk():
run_ucm('random_walk')
def test_local_level():
run_ucm('local_level')
def test_fixed_slope():
run_ucm('fixed_slope')
def test_fixed_slope():
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
run_ucm('fixed_slope')
message = ("Specified model does not contain a stochastic element;"
" irregular component added.")
assert_equal(str(w[0].message), message)
def test_deterministic_trend():
run_ucm('deterministic_trend')
def test_random_walk_with_drift():
run_ucm('random_walk_with_drift')
def test_local_linear_deterministic_trend():
run_ucm('local_linear_deterministic_trend')
def test_local_linear_trend():
run_ucm('local_linear_trend')
def test_smooth_trend():
run_ucm('smooth_trend')
def test_random_trend():
run_ucm('random_trend')
def test_cycle():
run_ucm('cycle')
def test_seasonal():
run_ucm('seasonal')
def test_reg():
run_ucm('reg')
def test_rtrend_ar1():
run_ucm('rtrend_ar1')
def test_lltrend_cycle_seasonal_reg_ar1():
run_ucm('lltrend_cycle_seasonal_reg_ar1')
def test_mle_reg():
endog = np.arange(100)*1.0
exog = endog*2
# Make the fit not-quite-perfect
endog[::2] += 0.01
endog[1::2] -= 0.01
with warnings.catch_warnings(record=True) as w:
mod1 = UnobservedComponents(endog, irregular=True, exog=exog, mle_regression=False)
res1 = mod1.fit(disp=-1)
mod2 = UnobservedComponents(endog, irregular=True, exog=exog, mle_regression=True)
res2 = mod2.fit(disp=-1)
assert_allclose(res1.regression_coefficients.filtered[0, -1], 0.5, atol=1e-5)
assert_allclose(res2.params[1], 0.5, atol=1e-5)
def test_specifications():
endog = [1, 2]
# Test that when nothing specified, a warning is issued and the model that
# is fit is one with irregular=True and nothing else.
warnings.simplefilter("always")
with warnings.catch_warnings(record=True) as w:
mod = UnobservedComponents(endog)
message = ("Specified model does not contain a stochastic element;"
" irregular component added.")
assert_equal(str(w[0].message), message)
assert_equal(mod.trend_specification, 'irregular')
# Test an invalid string trend specification
assert_raises(ValueError, UnobservedComponents, endog, 'invalid spec')
# Test that if a trend component is specified without a level component,
# a warning is issued and a deterministic level component is added
with warnings.catch_warnings(record=True) as w:
mod = UnobservedComponents(endog, trend=True, irregular=True)
message = ("Trend component specified without level component;"
" deterministic level component added.")
assert_equal(str(w[0].message), message)
assert_equal(mod.trend_specification, 'deterministic trend')
# Test that if a string specification is provided, a warning is issued if
# the boolean attributes are also specified
trend_attributes = ['irregular', 'trend', 'stochastic_level',
'stochastic_trend']
for attribute in trend_attributes:
with warnings.catch_warnings(record=True) as w:
kwargs = {attribute: True}
mod = UnobservedComponents(endog, 'deterministic trend', **kwargs)
message = ("Value of `%s` may be overridden when the trend"
" component is specified using a model string."
% attribute)
assert_equal(str(w[0].message), message)
# Test that a seasonal with period less than two is invalid
assert_raises(ValueError, UnobservedComponents, endog, seasonal=1)
def test_start_params():
# Test that the behavior is correct for multiple exogenous and / or
# autoregressive components
# Parameters
nobs = int(1e4)
beta = np.r_[10, -2]
phi = np.r_[0.5, 0.1]
# Generate data
np.random.seed(1234)
exog = np.c_[np.ones(nobs), np.arange(nobs)*1.0]
eps = np.random.normal(size=nobs)
endog = np.zeros(nobs+2)
for t in range(1, nobs):
endog[t+1] = phi[0] * endog[t] + phi[1] * endog[t-1] + eps[t]
endog = endog[2:]
endog += np.dot(exog, beta)
# Now just test that the starting parameters are approximately what they
# ought to be (could make this arbitrarily precise by increasing nobs,
# but that would slow down the test for no real gain)
mod = UnobservedComponents(endog, exog=exog, autoregressive=2)
assert_allclose(mod.start_params, [1., 0.5, 0.1, 10, -2], atol=1e-1)
def test_forecast():
endog = np.arange(50) + 10
exog = np.arange(50)
mod = UnobservedComponents(endog, exog=exog, level='dconstant')
res = mod.smooth([1e-15, 1])
actual = res.forecast(10, exog=np.arange(50,60)[:,np.newaxis])
desired = np.arange(50,60) + 10
assert_allclose(actual, desired)
| saketkc/statsmodels | statsmodels/tsa/statespace/tests/test_structural.py | Python | bsd-3-clause | 9,003 |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// testAPI.cpp : Defines the entry point for the console application.
//
// NOTES:
// 1. MediaFile library and testAPI.cpp must be built in DEBUG mode for testing.
//
#include <iostream>
#include <stdio.h>
#include <assert.h>
#ifdef WIN32
#include <windows.h>
#include <tchar.h>
#endif
#include "common_types.h"
#include "trace.h"
#include "Engineconfigurations.h"
#include "media_file.h"
#include "file_player.h"
#include "file_recorder.h"
bool notify = false, playing = false, recording = false;
// callback class for FileModule
class MyFileModuleCallback : public FileCallback
{
public:
virtual void PlayNotification( const WebRtc_Word32 id,
const WebRtc_UWord32 durationMs )
{
printf("\tReceived PlayNotification from module %ld, durationMs = %ld\n",
id, durationMs);
notify = true;
};
virtual void RecordNotification( const WebRtc_Word32 id,
const WebRtc_UWord32 durationMs )
{
printf("\tReceived RecordNotification from module %ld, durationMs = %ld\n",
id, durationMs);
notify = true;
};
virtual void PlayFileEnded(const WebRtc_Word32 id)
{
printf("\tReceived PlayFileEnded notification from module %ld.\n", id);
playing = false;
};
virtual void RecordFileEnded(const WebRtc_Word32 id)
{
printf("\tReceived RecordFileEnded notification from module %ld.\n", id);
recording = false;
}
};
// main test app
#ifdef WIN32
int _tmain(int argc, _TCHAR* argv[])
#else
int main(int /*argc*/, char** /*argv*/)
#endif
{
Trace::CreateTrace();
Trace::SetTraceFile("testTrace.txt");
Trace::SetEncryptedTraceFile("testTraceDebug.txt");
int playId = 1;
int recordId = 2;
printf("Welcome to test of FilePlayer and FileRecorder\n");
///////////////////////////////////////////////
//
// avi test case 1
//
///////////////////////////////////////////////
// todo PW we need more AVI tests Mp4
{
FilePlayer& filePlayer(*FilePlayer::CreateFilePlayer(1, webrtc::kFileFormatAviFile));
FileRecorder& fileRecorder(*FileRecorder::CreateFileRecorder(1, webrtc::kFileFormatAviFile));
const char* KFileName = "./tmpAviFileTestCase1_audioI420CIF30fps.avi";
printf("\tReading from an avi file and writing the information to another \n");
printf("\tin the same format (I420 CIF 30fps) \n");
printf("\t\t check file named %s\n", KFileName);
assert(filePlayer.StartPlayingVideoFile(
"../../../MediaFile/main/test/files/aviTestCase1_audioI420CIF30fps.avi",
false, false) == 0);
// init codecs
webrtc::VideoCodec videoCodec;
webrtc::VideoCodec recVideoCodec;
webrtc::CodecInst audioCodec;
assert(filePlayer.VideoCodec( videoCodec ) == 0);
assert(filePlayer.AudioCodec( audioCodec) == 0);
recVideoCodec = videoCodec;
assert( fileRecorder.StartRecordingVideoFile(KFileName,
audioCodec,
recVideoCodec) == 0);
assert(fileRecorder.IsRecording());
webrtc::I420VideoFrame videoFrame;
videoFrame.CreateEmptyFrame(videoCodec.width, videoCodec.height,
videoCodec.width,
(videoCodec.width + 1) / 2,
(videoCodec.width + 1) / 2);
int frameCount = 0;
bool audioNotDone = true;
bool videoNotDone = true;
AudioFrame audioFrame;
while( audioNotDone || videoNotDone)
{
if(filePlayer.TimeUntilNextVideoFrame() <= 0)
{
if(filePlayer.GetVideoFromFile( videoFrame) != 0)
{
// no more video frames
break;
}
frameCount++;
videoNotDone = !videoFrame.IsZeroSize();
videoFrame.SetRenderTime(TickTime::MillisecondTimestamp());
if( videoNotDone)
{
assert(fileRecorder.RecordVideoToFile(videoFrame) == 0);
::Sleep(10);
}
}
WebRtc_UWord32 decodedDataLengthInSamples;
if( 0 != filePlayer.Get10msAudioFromFile( audioFrame.data_, decodedDataLengthInSamples, audioCodec.plfreq))
{
audioNotDone = false;
} else
{
audioFrame.sample_rate_hz_ = filePlayer.Frequency();
audioFrame.samples_per_channel_ = (WebRtc_UWord16)decodedDataLengthInSamples;
fileRecorder.RecordAudioToFile(audioFrame, &TickTime::Now());
}
}
::Sleep(100);
assert(fileRecorder.StopRecording() == 0);
assert( !fileRecorder.IsRecording());
assert(frameCount == 135);
printf("\tGenerated %s\n\n", KFileName);
}
///////////////////////////////////////////////
//
// avi test case 2
//
///////////////////////////////////////////////
{
FilePlayer& filePlayer(*FilePlayer::CreateFilePlayer(2, webrtc::kFileFormatAviFile));
FileRecorder& fileRecorder(*FileRecorder::CreateFileRecorder(2, webrtc::kFileFormatAviFile));
const char* KFileName = "./tmpAviFileTestCase2_audioI420CIF20fps.avi";
printf("\tWriting information to a avi file and check the written file by \n");
printf("\treopening it and control codec information.\n");
printf("\t\t check file named %s all frames should be light green.\n", KFileName);
// init codecs
webrtc::VideoCodec videoCodec;
webrtc::CodecInst audioCodec;
memset(&videoCodec, 0, sizeof(videoCodec));
const char* KVideoCodecName = "I420";
strcpy(videoCodec.plName, KVideoCodecName);
videoCodec.plType = 124;
videoCodec.maxFramerate = 20;
videoCodec.height = 288;
videoCodec.width = 352;
const char* KAudioCodecName = "PCMU";
strcpy(audioCodec.plname, KAudioCodecName);
audioCodec.pltype = 0;
audioCodec.plfreq = 8000;
audioCodec.pacsize = 80;
audioCodec.channels = 1;
audioCodec.rate = 64000;
assert( fileRecorder.StartRecordingVideoFile(
KFileName,
audioCodec,
videoCodec) == 0);
assert(fileRecorder.IsRecording());
const WebRtc_UWord32 KVideoWriteSize = static_cast< WebRtc_UWord32>( (videoCodec.width * videoCodec.height * 3) / 2);
webrtc::VideoFrame videoFrame;
// 10 ms
AudioFrame audioFrame;
audioFrame.samples_per_channel_ = audioCodec.plfreq/100;
memset(audioFrame.data_, 0, 2*audioFrame.samples_per_channel_);
audioFrame.sample_rate_hz_ = 8000;
// prepare the video frame
int half_width = (videoCodec.width + 1) / 2;
int half_height = (videoCodec.height + 1) / 2;
videoFrame.CreateEmptyFrame(videoCodec.width, videoCodec.height,
videoCodec.width, half_width, half_width);
memset(videoFrame.buffer(kYPlane), 127,
videoCodec.width * videoCodec.height);
memset(videoFrame.buffer(kUPlane), 0, half_width * half_height);
memset(videoFrame.buffer(kVPlane), 0, half_width * half_height);
// write avi file, with 20 video frames
const int KWriteNumFrames = 20;
int writeFrameCount = 0;
while(writeFrameCount < KWriteNumFrames)
{
// add a video frame
assert(fileRecorder.RecordVideoToFile(videoFrame) == 0);
// add 50 ms of audio
for(int i=0; i<5; i++)
{
assert( fileRecorder.RecordAudioToFile(audioFrame) == 0);
}// for i
writeFrameCount++;
}
::Sleep(10); // enough tim eto write the queued data to the file
assert(writeFrameCount == 20);
assert(fileRecorder.StopRecording() == 0);
assert( ! fileRecorder.IsRecording());
assert(filePlayer.StartPlayingVideoFile(KFileName,false, false) == 0);
assert(filePlayer.IsPlayingFile( ));
// compare codecs read from file to the ones used when writing the file
webrtc::VideoCodec readVideoCodec;
assert(filePlayer.VideoCodec( readVideoCodec ) == 0);
assert(strcmp(readVideoCodec.plName, videoCodec.plName) == 0);
assert(readVideoCodec.width == videoCodec.width);
assert(readVideoCodec.height == videoCodec.height);
assert(readVideoCodec.maxFramerate == videoCodec.maxFramerate);
webrtc::CodecInst readAudioCodec;
assert(filePlayer.AudioCodec( readAudioCodec) == 0);
assert(strcmp(readAudioCodec.plname, audioCodec.plname) == 0);
assert(readAudioCodec.pltype == audioCodec.pltype);
assert(readAudioCodec.plfreq == audioCodec.plfreq);
assert(readAudioCodec.pacsize == audioCodec.pacsize);
assert(readAudioCodec.channels == audioCodec.channels);
assert(readAudioCodec.rate == audioCodec.rate);
assert(filePlayer.StopPlayingFile() == 0);
assert( ! filePlayer.IsPlayingFile());
printf("\tGenerated %s\n\n", KFileName);
}
///////////////////////////////////////////////
//
// avi test case 3
//
///////////////////////////////////////////////
{
FilePlayer& filePlayer(*FilePlayer::CreateFilePlayer(2, webrtc::kFileFormatAviFile));
FileRecorder& fileRecorder(*FileRecorder::CreateFileRecorder(3, webrtc::kFileFormatAviFile));
printf("\tReading from an avi file and writing the information to another \n");
printf("\tin a different format (H.263 CIF 30fps) \n");
printf("\t\t check file named tmpAviFileTestCase1_audioH263CIF30fps.avi\n");
assert(filePlayer.StartPlayingVideoFile(
"../../../MediaFile/main/test/files/aviTestCase1_audioI420CIF30fps.avi",
false,
false) == 0);
// init codecs
webrtc::VideoCodec videoCodec;
webrtc::VideoCodec recVideoCodec;
webrtc::CodecInst audioCodec;
assert(filePlayer.VideoCodec( videoCodec ) == 0);
assert(filePlayer.AudioCodec( audioCodec) == 0);
recVideoCodec = videoCodec;
memcpy(recVideoCodec.plName, "H263",5);
recVideoCodec.startBitrate = 1000;
recVideoCodec.codecSpecific.H263.quality = 1;
recVideoCodec.plType = 34;
recVideoCodec.codecType = webrtc::kVideoCodecH263;
assert( fileRecorder.StartRecordingVideoFile(
"./tmpAviFileTestCase1_audioH263CIF30fps.avi",
audioCodec,
recVideoCodec) == 0);
assert(fileRecorder.IsRecording());
webrtc::I420VideoFrame videoFrame;
videoFrame.CreateEmptyFrame(videoCodec.width, videoCodec.height,
videoCodec.width, half_width,half_width);
int videoFrameCount = 0;
int audioFrameCount = 0;
bool audioNotDone = true;
bool videoNotDone = true;
AudioFrame audioFrame;
while( audioNotDone || videoNotDone)
{
if(filePlayer.TimeUntilNextVideoFrame() <= 0)
{
if(filePlayer.GetVideoFromFile(videoFrame) != 0)
{
break;
}
videoFrameCount++;
videoNotDone = !videoFrame.IsZeroSize();
if( videoNotDone)
{
assert(fileRecorder.RecordVideoToFile(videoFrame) == 0);
}
}
WebRtc_UWord32 decodedDataLengthInSamples;
if( 0 != filePlayer.Get10msAudioFromFile( audioFrame.data_, decodedDataLengthInSamples, audioCodec.plfreq))
{
audioNotDone = false;
} else
{
::Sleep(5);
audioFrame.sample_rate_hz_ = filePlayer.Frequency();
audioFrame.samples_per_channel_ = (WebRtc_UWord16)decodedDataLengthInSamples;
assert(0 == fileRecorder.RecordAudioToFile(audioFrame));
audioFrameCount++;
}
}
assert(videoFrameCount == 135);
assert(audioFrameCount == 446); // we will start & stop with a video frame
assert(fileRecorder.StopRecording() == 0);
assert( !fileRecorder.IsRecording());
printf("\tGenerated ./tmpAviFileTestCase1_audioH263CIF30fps.avi\n\n");
}
printf("\nTEST completed.\n");
Trace::ReturnTrace();
return 0;
}
| leighpauls/k2cro4 | third_party/webrtc/modules/utility/test/testAPI.cc | C++ | bsd-3-clause | 13,298 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Forms :: textarea : padding</title>
<style type="text/css">
form * {
font-family: Ahem;
font-size: 1em;
line-height: 1em;
}
fieldset, form>div {
padding: 0;
margin: 10px;
border: none;
}
textarea, div div {
color: black;
background: lime;
padding: 2em;
margin: 0;
border: none;
width: 1em;
height: 1em;
overflow: hidden;
resize: none;
}
</style>
</head>
<body>
<h4>Ahem font required for this test</h4>
<p>there should be two identical patterns below</p>
<form action="">
<fieldset>
<textarea rows="" cols="">x</textarea>
</fieldset>
<div>
<div>x</div>
</div>
</form>
</body>
</html> | frivoal/presto-testo | core/standards/forms/textarea-padding.html | HTML | bsd-3-clause | 681 |
// Copyright (c) 2012 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.
#ifndef BASE_ANDROID_BUILD_INFO_H_
#define BASE_ANDROID_BUILD_INFO_H_
#include <jni.h>
#include <string>
#include "base/base_export.h"
#include "base/memory/singleton.h"
namespace base {
namespace android {
// This enumeration maps to the values returned by BuildInfo::sdk_int(),
// indicating the Android release associated with a given SDK version.
enum SdkVersion {
SDK_VERSION_ICE_CREAM_SANDWICH = 14,
SDK_VERSION_ICE_CREAM_SANDWICH_MR1 = 15,
SDK_VERSION_JELLY_BEAN = 16,
SDK_VERSION_JELLY_BEAN_MR1 = 17,
SDK_VERSION_JELLY_BEAN_MR2 = 18,
SDK_VERSION_KITKAT = 19,
SDK_VERSION_KITKAT_WEAR = 20,
SDK_VERSION_LOLLIPOP = 21,
SDK_VERSION_LOLLIPOP_MR1 = 22
};
// BuildInfo is a singleton class that stores android build and device
// information. It will be called from Android specific code and gets used
// primarily in crash reporting.
// It is also used to store the last java exception seen during JNI.
// TODO(nileshagrawal): Find a better place to store this info.
class BASE_EXPORT BuildInfo {
public:
~BuildInfo() {}
// Static factory method for getting the singleton BuildInfo instance.
// Note that ownership is not conferred on the caller and the BuildInfo in
// question isn't actually freed until shutdown. This is ok because there
// should only be one instance of BuildInfo ever created.
static BuildInfo* GetInstance();
// Const char* is used instead of std::strings because these values must be
// available even if the process is in a crash state. Sadly
// std::string.c_str() doesn't guarantee that memory won't be allocated when
// it is called.
const char* device() const {
return device_;
}
const char* manufacturer() const {
return manufacturer_;
}
const char* model() const {
return model_;
}
const char* brand() const {
return brand_;
}
const char* android_build_id() const {
return android_build_id_;
}
const char* android_build_fp() const {
return android_build_fp_;
}
const char* package_version_code() const {
return package_version_code_;
}
const char* package_version_name() const {
return package_version_name_;
}
const char* package_label() const {
return package_label_;
}
const char* package_name() const {
return package_name_;
}
const char* build_type() const {
return build_type_;
}
int sdk_int() const {
return sdk_int_;
}
int has_language_apk_splits() const {
return has_language_apk_splits_;
}
const char* java_exception_info() const {
return java_exception_info_;
}
void SetJavaExceptionInfo(const std::string& info);
void ClearJavaExceptionInfo();
static bool RegisterBindings(JNIEnv* env);
private:
friend struct BuildInfoSingletonTraits;
explicit BuildInfo(JNIEnv* env);
// Const char* is used instead of std::strings because these values must be
// available even if the process is in a crash state. Sadly
// std::string.c_str() doesn't guarantee that memory won't be allocated when
// it is called.
const char* const device_;
const char* const manufacturer_;
const char* const model_;
const char* const brand_;
const char* const android_build_id_;
const char* const android_build_fp_;
const char* const package_version_code_;
const char* const package_version_name_;
const char* const package_label_;
const char* const package_name_;
const char* const build_type_;
const int sdk_int_;
const bool has_language_apk_splits_;
// This is set via set_java_exception_info, not at constructor time.
const char* java_exception_info_;
DISALLOW_COPY_AND_ASSIGN(BuildInfo);
};
} // namespace android
} // namespace base
#endif // BASE_ANDROID_BUILD_INFO_H_
| TheTypoMaster/chromium-crosswalk | base/android/build_info.h | C | bsd-3-clause | 3,897 |
/*
Copyright (C) 2014, The University of Texas at Austin
This file is part of libflame and is available under the 3-Clause
BSD license, which can be found in the LICENSE file at the top-level
directory, or at http://opensource.org/licenses/BSD-3-Clause
*/
#include "FLAME.h"
FLA_Error FLA_Bsvd_find_split( FLA_Obj d, FLA_Obj e )
{
FLA_Datatype datatype;
int m_A;
int inc_d;
int inc_e;
datatype = FLA_Obj_datatype( d );
m_A = FLA_Obj_vector_dim( d );
inc_d = FLA_Obj_vector_inc( d );
inc_e = FLA_Obj_vector_inc( e );
switch ( datatype )
{
case FLA_FLOAT:
{
float* buff_d = FLA_FLOAT_PTR( d );
float* buff_e = FLA_FLOAT_PTR( e );
FLA_Bsvd_find_split_ops( m_A,
buff_d, inc_d,
buff_e, inc_e );
break;
}
case FLA_DOUBLE:
{
double* buff_d = FLA_DOUBLE_PTR( d );
double* buff_e = FLA_DOUBLE_PTR( e );
FLA_Bsvd_find_split_opd( m_A,
buff_d, inc_d,
buff_e, inc_e );
break;
}
}
return FLA_SUCCESS;
}
FLA_Error FLA_Bsvd_find_split_ops( int m_A,
float* buff_d, int inc_d,
float* buff_e, int inc_e )
{
FLA_Check_error_code( FLA_NOT_YET_IMPLEMENTED );
return FLA_SUCCESS;
}
FLA_Error FLA_Bsvd_find_split_opd( int m_A,
double* buff_d, int inc_d,
double* buff_e, int inc_e )
{
int i;
for ( i = 0; i < m_A - 1; ++i )
{
double* epsilon1 = buff_e + (i )*inc_e;
if ( *epsilon1 == 0.0 )
{
// Return index of split as i+1 since e_i is in the same
// column as d_(i+1).
return i + 1;
}
}
// Return with no split found found.
return FLA_FAILURE;
}
| yaowee/libflame | src/lapack/dec/bsvd/v/flamec/old/FLA_Bsvd_find_split.c | C | bsd-3-clause | 1,885 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>A quick animation test</title>
</head>
<body>
<table>
<tr>
<td align="center">SVG Image</td>
<td align="center">Reference Image</td>
</tr>
<tr>
<td align="right">
<object data="../svggen/animate-elem-20-t.svg" width="480" height="360" type="image/svg+xml"/>
</td>
<td align="left">
<img alt="raster image of animate-elem-20-t" src="../png/full-animate-elem-20-t.png" width="480" height="360"/>
</td>
</tr>
</table>
<p>
Click on "fade in", after completed animation compare with the reference image and then click on "fade out".
With a second click on "fade in" the red square goes from white to red, and then goes back from red to white.
</p>
</body>
</html>
| frivoal/presto-testo | SVG/Testsuites/W3C/tiny/full-animate-elem-20-t.html | HTML | bsd-3-clause | 950 |
/*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TALK_XMPP_JID_H_
#define TALK_XMPP_JID_H_
#include <string>
#include "webrtc/libjingle/xmllite/xmlconstants.h"
#include "webrtc/base/basictypes.h"
namespace buzz {
// The Jid class encapsulates and provides parsing help for Jids. A Jid
// consists of three parts: the node, the domain and the resource, e.g.:
//
// node@domain/resource
//
// The node and resource are both optional. A valid jid is defined to have
// a domain. A bare jid is defined to not have a resource and a full jid
// *does* have a resource.
class Jid {
public:
explicit Jid();
explicit Jid(const std::string& jid_string);
explicit Jid(const std::string& node_name,
const std::string& domain_name,
const std::string& resource_name);
~Jid();
const std::string & node() const { return node_name_; }
const std::string & domain() const { return domain_name_; }
const std::string & resource() const { return resource_name_; }
std::string Str() const;
Jid BareJid() const;
bool IsEmpty() const;
bool IsValid() const;
bool IsBare() const;
bool IsFull() const;
bool BareEquals(const Jid& other) const;
void CopyFrom(const Jid& jid);
bool operator==(const Jid& other) const;
bool operator!=(const Jid& other) const { return !operator==(other); }
bool operator<(const Jid& other) const { return Compare(other) < 0; };
bool operator>(const Jid& other) const { return Compare(other) > 0; };
int Compare(const Jid & other) const;
private:
void ValidateOrReset();
static std::string PrepNode(const std::string& node, bool* valid);
static char PrepNodeAscii(char ch, bool* valid);
static std::string PrepResource(const std::string& start, bool* valid);
static char PrepResourceAscii(char ch, bool* valid);
static std::string PrepDomain(const std::string& domain, bool* valid);
static void PrepDomain(const std::string& domain,
std::string* buf, bool* valid);
static void PrepDomainLabel(
std::string::const_iterator start, std::string::const_iterator end,
std::string* buf, bool* valid);
static char PrepDomainLabelAscii(char ch, bool *valid);
std::string node_name_;
std::string domain_name_;
std::string resource_name_;
};
}
#endif // TALK_XMPP_JID_H_
| Omegaphora/external_chromium_org_third_party_libjingle_source_talk | xmpp/jid.h | C | bsd-3-clause | 3,740 |
#!/usr/bin/python
# encoding: utf-8
# Jan 2011 (markus kossner) Cleaned up the code, added some documentation
# somwhere around Aug 2008 (markus kossner) created
#
# This script extracts the molecular framework for a database of molecules.
# You can use two modes (hard coded):
# - Scaff: The molecular frame is extracted
# - RedScaff: All linking chains between rings are deleted. The rings are directly connected.
#
# You can comment in/out the code snippets indicated by the comments
# to force each atom of the frame to be a Carbon.
#
# Usage: Frames.py <database.sdf>
# Output:
# - sd files containing all molecules belonging to one frame (1.sdf, 2.sdf etc)
# - frames.smi containing the (caninical) smiles and count of occurrence
#
from __future__ import print_function
import os,sys
from Chem import AllChem as Chem
def flatten(x):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all nested sub-sequences (iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
def GetFrame(mol, mode='Scaff'):
'''return a ganeric molecule defining the reduced scaffold of the input mol.
mode can be 'Scaff' or 'RedScaff':
Scaff -> chop off the side chains and return the scaffold
RedScaff -> remove all linking chains and connect the rings
directly at the atoms where the linker was
'''
ring = mol.GetRingInfo()
RingAtoms = flatten(ring.AtomRings())
NonRingAtoms = [ atom.GetIdx() for atom in mol.GetAtoms() if atom.GetIdx() not in RingAtoms ]
RingNeighbors = []
Paths = []
for NonRingAtom in NonRingAtoms:
for neighbor in mol.GetAtomWithIdx(NonRingAtom).GetNeighbors():
if neighbor.GetIdx() in RingAtoms:
RingNeighbors.append(NonRingAtom)
Paths.append([neighbor.GetIdx(),NonRingAtom]) #The ring Atoms having a non ring Nieghbor will be the start of a walk
break
PosConnectors = [x for x in NonRingAtoms if x not in RingNeighbors] #Only these Atoms are potential starting points of a Linker chain
#print 'PosConnectors:'
#print PosConnectors
Framework = [ x for x in RingAtoms ]
#Start a list of pathways which we will have to walk
#print 'Path atoms:'
#print Paths
Linkers = []
while len(Paths)>0:
NewPaths = []
for P in Paths:
if P == None:
print('ooh')
else:
for neighbor in mol.GetAtomWithIdx(P[-1]).GetNeighbors():
if neighbor.GetIdx() not in P:
if neighbor.GetIdx() in NonRingAtoms:
n = P[:]
n.append(neighbor.GetIdx())
NewPaths.append(n[:])
elif neighbor.GetIdx() in RingAtoms:
#print 'adding the following path to Framework:'
#print P
n = P[:]
n.append(neighbor.GetIdx())
Linkers.append(n)
Framework=Framework+P[:]
Paths = NewPaths[:]
#print 'Linkers:',Linkers
#print 'RingAtoms:',RingAtoms
#em.AddBond(3,4,Chem.BondType.SINGLE)
if mode == 'RedScaff':
Framework = list(set(Framework))
todel = []
NonRingAtoms.sort(reverse=True)
em = Chem.EditableMol(mol)
BondsToAdd = [ sorted([i[0],i[-1]]) for i in Linkers ]
mem = []
for i in BondsToAdd:
if i not in mem:
em.AddBond(i[0],i[1],Chem.BondType.SINGLE)
mem.append(i)
for i in NonRingAtoms:
todel.append(i)
for i in todel:
em.RemoveAtom(i)
m = em.GetMol()
#===================================#
# Now do the flattening of atoms and bonds!
# Any heavy atom will become a carbon and any bond will become a single bond! #
#===================================#
# for atom in m.GetAtoms(): #
# atom.SetAtomicNum(6) #
# atom.SetFormalCharge(0) #
# for bond in m.GetBonds(): #
# bond.SetBondType(Chem.BondType.SINGLE) #
# Chem.SanitizeMol(m) #
#===================================#
return m
if mode == 'Scaff':
Framework = list(set(Framework))
todel = []
NonRingAtoms.sort(reverse=True)
for i in NonRingAtoms:
if i != None:
if i not in Framework:
todel.append(i)
em = Chem.EditableMol(mol)
for i in todel:
em.RemoveAtom(i)
m = em.GetMol()
#===================================#
# Now do the flattening of atoms and bonds!
# Any heavy atom will become a carbon and any bond will become a single bond!! #
#===================================#
# for atom in m.GetAtoms(): #
# atom.SetAtomicNum(6) #
# atom.SetFormalCharge(0) #
# for bond in m.GetBonds(): #
# bond.SetBondType(Chem.BondType.SINGLE) #
# Chem.SanitizeMol(m) #
#===================================#
return m
if __name__=='__main__':
if len(sys.argv) < 2:
print("No input file provided: Frames.py filetosprocess.ext")
sys.exit(1)
suppl = Chem.SDMolSupplier(sys.argv[1])
FrameDict = {}
for mol in suppl:
m = GetFrame(mol)
cansmiles = Chem.MolToSmiles(m, isomericSmiles=True)
if FrameDict.has_key(cansmiles):
FrameDict[cansmiles].append(mol)
else:
FrameDict[cansmiles]=[mol,]
counter=0
w=open('frames.smi','w')
for key,item in FrameDict.items():
counter+=1
d=Chem.SDWriter(str(counter)+'.sdf')
for i in item:
i.SetProp('Scaffold',key)
i.SetProp('Cluster',str(counter))
d.write(i)
print(key,len(item))
w.write(key+'\t'+str(len(item))+'\n')
w.close
print('number of Clusters: %d' %(counter))
| soerendip42/rdkit | Contrib/M_Kossner/Frames.py | Python | bsd-3-clause | 6,124 |
// Copyright (c) 2012 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.
#ifndef CHROME_BROWSER_BROWSING_DATA_BROWSING_DATA_LOCAL_STORAGE_HELPER_H_
#define CHROME_BROWSER_BROWSING_DATA_BROWSING_DATA_LOCAL_STORAGE_HELPER_H_
#include <list>
#include <set>
#include <vector>
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/lock.h"
#include "base/time.h"
#include "content/public/browser/dom_storage_context.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"
class Profile;
// This class fetches local storage information and provides a
// means to delete the data associated with an origin.
class BrowsingDataLocalStorageHelper
: public base::RefCounted<BrowsingDataLocalStorageHelper> {
public:
// Contains detailed information about local storage.
struct LocalStorageInfo {
LocalStorageInfo(
const GURL& origin_url,
int64 size,
base::Time last_modified);
~LocalStorageInfo();
GURL origin_url;
int64 size;
base::Time last_modified;
};
explicit BrowsingDataLocalStorageHelper(Profile* profile);
// Starts the fetching process, which will notify its completion via
// callback. This must be called only in the UI thread.
virtual void StartFetching(
const base::Callback<void(const std::list<LocalStorageInfo>&)>& callback);
// Deletes the local storage for the |origin|.
virtual void DeleteOrigin(const GURL& origin);
protected:
friend class base::RefCounted<BrowsingDataLocalStorageHelper>;
virtual ~BrowsingDataLocalStorageHelper();
void CallCompletionCallback();
content::DOMStorageContext* dom_storage_context_; // Owned by the profile
base::Callback<void(const std::list<LocalStorageInfo>&)> completion_callback_;
bool is_fetching_;
std::list<LocalStorageInfo> local_storage_info_;
private:
void GetUsageInfoCallback(
const std::vector<dom_storage::LocalStorageUsageInfo>& infos);
DISALLOW_COPY_AND_ASSIGN(BrowsingDataLocalStorageHelper);
};
// This class is a thin wrapper around BrowsingDataLocalStorageHelper that does
// not fetch its information from the local storage tracker, but gets them
// passed as a parameter during construction.
class CannedBrowsingDataLocalStorageHelper
: public BrowsingDataLocalStorageHelper {
public:
explicit CannedBrowsingDataLocalStorageHelper(Profile* profile);
// Return a copy of the local storage helper. Only one consumer can use the
// StartFetching method at a time, so we need to create a copy of the helper
// every time we instantiate a cookies tree model for it.
CannedBrowsingDataLocalStorageHelper* Clone();
// Add a local storage to the set of canned local storages that is returned
// by this helper.
void AddLocalStorage(const GURL& origin);
// Clear the list of canned local storages.
void Reset();
// True if no local storages are currently stored.
bool empty() const;
// Returns the number of local storages currently stored.
size_t GetLocalStorageCount() const;
// Returns the set of origins that use local storage.
const std::set<GURL>& GetLocalStorageInfo() const;
// BrowsingDataLocalStorageHelper implementation.
virtual void StartFetching(
const base::Callback<void(const std::list<LocalStorageInfo>&)>& callback)
OVERRIDE;
private:
virtual ~CannedBrowsingDataLocalStorageHelper();
// Convert the pending local storage info to local storage info objects.
void ConvertPendingInfo();
std::set<GURL> pending_local_storage_info_;
Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(CannedBrowsingDataLocalStorageHelper);
};
#endif // CHROME_BROWSER_BROWSING_DATA_BROWSING_DATA_LOCAL_STORAGE_HELPER_H_
| leiferikb/bitpop-private | chrome/browser/browsing_data/browsing_data_local_storage_helper.h | C | bsd-3-clause | 3,884 |
/* The latency monitor allows to easily observe the sources of latency
* in a Redis instance using the LATENCY command. Different latency
* sources are monitored, like disk I/O, execution of commands, fork
* system call, and so forth.
*
* ----------------------------------------------------------------------------
*
* Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "redis.h"
/* Dictionary type for latency events. */
int dictStringKeyCompare(void *privdata, const void *key1, const void *key2) {
REDIS_NOTUSED(privdata);
return strcmp(key1,key2) == 0;
}
unsigned int dictStringHash(const void *key) {
return dictGenHashFunction(key, (int)strlen(key)); WIN_PORT_FIX /* cast (int) */
}
void dictVanillaFree(void *privdata, void *val);
dictType latencyTimeSeriesDictType = {
dictStringHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictStringKeyCompare, /* key compare */
dictVanillaFree, /* key destructor */
dictVanillaFree /* val destructor */
};
/* ------------------------- Utility functions ------------------------------ */
#ifdef __linux__
/* Returns 1 if Transparent Huge Pages support is enabled in the kernel.
* Otherwise (or if we are unable to check) 0 is returned. */
int THPIsEnabled(void) {
char buf[1024];
FILE *fp = fopen("/sys/kernel/mm/transparent_hugepage/enabled","r");
if (!fp) return 0;
if (fgets(buf,sizeof(buf),fp) == NULL) {
fclose(fp);
return 0;
}
fclose(fp);
return (strstr(buf,"[never]") == NULL) ? 1 : 0;
}
#endif
/* Report the amount of AnonHugePages in smap, in bytes. If the return
* value of the function is non-zero, the process is being targeted by
* THP support, and is likely to have memory usage / latency issues. */
int THPGetAnonHugePagesSize(void) {
return (int)zmalloc_get_smap_bytes_by_field("AnonHugePages:"); WIN_PORT_FIX /* cast (int) */
}
/* ---------------------------- Latency API --------------------------------- */
/* Latency monitor initialization. We just need to create the dictionary
* of time series, each time serie is craeted on demand in order to avoid
* having a fixed list to maintain. */
void latencyMonitorInit(void) {
server.latency_events = dictCreate(&latencyTimeSeriesDictType,NULL);
}
/* Add the specified sample to the specified time series "event".
* This function is usually called via latencyAddSampleIfNeeded(), that
* is a macro that only adds the sample if the latency is higher than
* server.latency_monitor_threshold. */
void latencyAddSample(char *event, mstime_t latency) {
struct latencyTimeSeries *ts = dictFetchValue(server.latency_events,event);
time_t now = time(NULL);
int prev;
/* Create the time series if it does not exist. */
if (ts == NULL) {
ts = zmalloc(sizeof(*ts));
ts->idx = 0;
ts->max = 0;
memset(ts->samples,0,sizeof(ts->samples));
dictAdd(server.latency_events,zstrdup(event),ts);
}
/* If the previous sample is in the same second, we update our old sample
* if this latency is > of the old one, or just return. */
prev = (ts->idx + LATENCY_TS_LEN - 1) % LATENCY_TS_LEN;
if (ts->samples[prev].time == now) {
if (latency > ts->samples[prev].latency)
ts->samples[prev].latency = (int32_t)latency; WIN_PORT_FIX /* cast (int32_t) */
return;
}
ts->samples[ts->idx].time = (int32_t)time(NULL); WIN_PORT_FIX /* cast (int32_t) */
ts->samples[ts->idx].latency = (int32_t)latency; WIN_PORT_FIX /* cast (int32_t) */
if (latency > ts->max) ts->max = (int32_t)latency; WIN_PORT_FIX /* cast (int32_t) */
ts->idx++;
if (ts->idx == LATENCY_TS_LEN) ts->idx = 0;
}
/* Reset data for the specified event, or all the events data if 'event' is
* NULL.
*
* Note: this is O(N) even when event_to_reset is not NULL because makes
* the code simpler and we have a small fixed max number of events. */
int latencyResetEvent(char *event_to_reset) {
dictIterator *di;
dictEntry *de;
int resets = 0;
di = dictGetSafeIterator(server.latency_events);
while((de = dictNext(di)) != NULL) {
char *event = dictGetKey(de);
if (event_to_reset == NULL || strcasecmp(event,event_to_reset) == 0) {
dictDelete(server.latency_events, event);
resets++;
}
}
dictReleaseIterator(di);
return resets;
}
/* ------------------------ Latency reporting (doctor) ---------------------- */
/* Analyze the samples avaialble for a given event and return a structure
* populate with different metrics, average, MAD, min, max, and so forth.
* Check latency.h definition of struct latenctStat for more info.
* If the specified event has no elements the structure is populate with
* zero values. */
void analyzeLatencyForEvent(char *event, struct latencyStats *ls) {
struct latencyTimeSeries *ts = dictFetchValue(server.latency_events,event);
int j;
uint64_t sum;
ls->all_time_high = ts ? ts->max : 0;
ls->avg = 0;
ls->min = 0;
ls->max = 0;
ls->mad = 0;
ls->samples = 0;
ls->period = 0;
if (!ts) return;
/* First pass, populate everything but the MAD. */
sum = 0;
for (j = 0; j < LATENCY_TS_LEN; j++) {
if (ts->samples[j].time == 0) continue;
ls->samples++;
if (ls->samples == 1) {
ls->min = ls->max = ts->samples[j].latency;
} else {
if (ls->min > ts->samples[j].latency)
ls->min = ts->samples[j].latency;
if (ls->max < ts->samples[j].latency)
ls->max = ts->samples[j].latency;
}
sum += ts->samples[j].latency;
/* Track the oldest event time in ls->period. */
if (ls->period == 0 || ts->samples[j].time < ls->period)
ls->period = ts->samples[j].time;
}
/* So far avg is actually the sum of the latencies, and period is
* the oldest event time. We need to make the first an average and
* the second a range of seconds. */
if (ls->samples) {
ls->avg = (int32_t)(sum / ls->samples); WIN_PORT_FIX /* cast (int32_t) */
ls->period = time(NULL) - ls->period;
if (ls->period == 0) ls->period = 1;
}
/* Second pass, compute MAD. */
sum = 0;
for (j = 0; j < LATENCY_TS_LEN; j++) {
int64_t delta;
if (ts->samples[j].time == 0) continue;
delta = (int64_t)ls->avg - ts->samples[j].latency;
if (delta < 0) delta = -delta;
sum += delta;
}
if (ls->samples) ls->mad = (int32_t)(sum / ls->samples); WIN_PORT_FIX /* cast (int32_t) */
}
/* Create a human readable report of latency events for this Redis instance. */
sds createLatencyReport(void) {
sds report = sdsempty();
int advise_better_vm = 0; /* Better virtual machines. */
int advise_slowlog_enabled = 0; /* Enable slowlog. */
int advise_slowlog_tuning = 0; /* Reconfigure slowlog. */
int advise_slowlog_inspect = 0; /* Check your slowlog. */
int advise_disk_contention = 0; /* Try to lower disk contention. */
int advise_scheduler = 0; /* Intrinsic latency. */
int advise_data_writeback = 0; /* data=writeback. */
int advise_no_appendfsync = 0; /* don't fsync during rewrites. */
int advise_local_disk = 0; /* Avoid remote disks. */
int advise_ssd = 0; /* Use an SSD drive. */
int advise_write_load_info = 0; /* Print info about AOF and write load. */
int advise_hz = 0; /* Use higher HZ. */
int advise_large_objects = 0; /* Deletion of large objects. */
int advise_mass_eviction = 0; /* Avoid mass eviction of keys. */
int advise_relax_fsync_policy = 0; /* appendfsync always is slow. */
int advise_disable_thp = 0; /* AnonHugePages detected. */
int advices = 0;
/* Return ASAP if the latency engine is disabled and it looks like it
* was never enabled so far. */
if (dictSize(server.latency_events) == 0 &&
server.latency_monitor_threshold == 0)
{
report = sdscat(report,"I'm sorry, Dave, I can't do that. Latency monitoring is disabled in this Redis instance. You may use \"CONFIG SET latency-monitor-threshold <milliseconds>.\" in order to enable it. If we weren't in a deep space mission I'd suggest to take a look at http://redis.io/topics/latency-monitor.\n");
return report;
}
/* Show all the events stats and add for each event some event-related
* comment depending on the values. */
dictIterator *di;
dictEntry *de;
int eventnum = 0;
di = dictGetSafeIterator(server.latency_events);
while((de = dictNext(di)) != NULL) {
char *event = dictGetKey(de);
struct latencyTimeSeries *ts = dictGetVal(de);
struct latencyStats ls;
if (ts == NULL) continue;
eventnum++;
if (eventnum == 1) {
report = sdscat(report,"Dave, I have observed latency spikes in this Redis instance. You don't mind talking about it, do you Dave?\n\n");
}
analyzeLatencyForEvent(event,&ls);
report = sdscatprintf(report,
"%d. %s: %d latency spikes (average %lums, mean deviation %lums, period %.2f sec). Worst all time event %lums.",
eventnum, event,
ls.samples,
(PORT_ULONG) ls.avg,
(PORT_ULONG) ls.mad,
(double) ls.period/ls.samples,
(PORT_ULONG) ts->max);
/* Fork */
if (!strcasecmp(event,"fork")) {
char *fork_quality;
if (server.stat_fork_rate < 10) {
fork_quality = "terrible";
advise_better_vm = 1;
advices++;
} else if (server.stat_fork_rate < 25) {
fork_quality = "poor";
advise_better_vm = 1;
advices++;
} else if (server.stat_fork_rate < 100) {
fork_quality = "good";
} else {
fork_quality = "excellent";
}
report = sdscatprintf(report,
" Fork rate is %.2f GB/sec (%s).", server.stat_fork_rate,
fork_quality);
}
/* Potentially commands. */
if (!strcasecmp(event,"command")) {
if (server.slowlog_log_slower_than == 0) {
advise_slowlog_enabled = 1;
advices++;
} else if (server.slowlog_log_slower_than/1000 >
server.latency_monitor_threshold)
{
advise_slowlog_tuning = 1;
advices++;
}
advise_slowlog_inspect = 1;
advise_large_objects = 1;
advices += 2;
}
/* fast-command. */
if (!strcasecmp(event,"fast-command")) {
advise_scheduler = 1;
advices++;
}
/* AOF and I/O. */
if (!strcasecmp(event,"aof-write-pending-fsync")) {
advise_local_disk = 1;
advise_disk_contention = 1;
advise_ssd = 1;
advise_data_writeback = 1;
advices += 4;
}
if (!strcasecmp(event,"aof-write-active-child")) {
advise_no_appendfsync = 1;
advise_data_writeback = 1;
advise_ssd = 1;
advices += 3;
}
if (!strcasecmp(event,"aof-write-alone")) {
advise_local_disk = 1;
advise_data_writeback = 1;
advise_ssd = 1;
advices += 3;
}
if (!strcasecmp(event,"aof-fsync-always")) {
advise_relax_fsync_policy = 1;
advices++;
}
if (!strcasecmp(event,"aof-fstat") ||
!strcasecmp(event,"rdb-unlik-temp-file")) {
advise_disk_contention = 1;
advise_local_disk = 1;
advices += 2;
}
if (!strcasecmp(event,"aof-rewrite-diff-write") ||
!strcasecmp(event,"aof-rename")) {
advise_write_load_info = 1;
advise_data_writeback = 1;
advise_ssd = 1;
advise_local_disk = 1;
advices += 4;
}
/* Expire cycle. */
if (!strcasecmp(event,"expire-cycle")) {
advise_hz = 1;
advise_large_objects = 1;
advices += 2;
}
/* Eviction cycle. */
if (!strcasecmp(event,"eviction-del")) {
advise_large_objects = 1;
advices++;
}
if (!strcasecmp(event,"eviction-cycle")) {
advise_mass_eviction = 1;
advices++;
}
report = sdscatlen(report,"\n",1);
}
dictReleaseIterator(di);
/* Add non event based advices. */
if (THPGetAnonHugePagesSize() > 0) {
advise_disable_thp = 1;
advices++;
}
if (eventnum == 0 && advices == 0) {
report = sdscat(report,"Dave, no latency spike was observed during the lifetime of this Redis instance, not in the slightest bit. I honestly think you ought to sit down calmly, take a stress pill, and think things over.\n");
} else if (eventnum > 0 && advices == 0) {
report = sdscat(report,"\nWhile there are latency events logged, I'm not able to suggest any easy fix. Please use the Redis community to get some help, providing this report in your help request.\n");
} else {
/* Add all the suggestions accumulated so far. */
/* Better VM. */
report = sdscat(report,"\nI have a few advices for you:\n\n");
if (advise_better_vm) {
report = sdscat(report,"- If you are using a virtual machine, consider upgrading it with a faster one using an hypervisior that provides less latency during fork() calls. Xen is known to have poor fork() performance. Even in the context of the same VM provider, certain kinds of instances can execute fork faster than others.\n");
}
/* Slow log. */
if (advise_slowlog_enabled) {
report = sdscatprintf(report,"- There are latency issues with potentially slow commands you are using. Try to enable the Slow Log Redis feature using the command 'CONFIG SET slowlog-log-slower-than %llu'. If the Slow log is disabled Redis is not able to log slow commands execution for you.\n", (PORT_ULONGLONG)server.latency_monitor_threshold*1000);
}
if (advise_slowlog_tuning) {
report = sdscatprintf(report,"- Your current Slow Log configuration only logs events that are slower than your configured latency monitor threshold. Please use 'CONFIG SET slowlog-log-slower-than %llu'.\n", (PORT_ULONGLONG)server.latency_monitor_threshold*1000);
}
if (advise_slowlog_inspect) {
report = sdscat(report,"- Check your Slow Log to understand what are the commands you are running which are too slow to execute. Please check http://redis.io/commands/slowlog for more information.\n");
}
/* Intrinsic latency. */
if (advise_scheduler) {
report = sdscat(report,"- The system is slow to execute Redis code paths not containing system calls. This usually means the system does not provide Redis CPU time to run for long periods. You should try to:\n"
" 1) Lower the system load.\n"
" 2) Use a computer / VM just for Redis if you are running other softawre in the same system.\n"
" 3) Check if you have a \"noisy neighbour\" problem.\n"
" 4) Check with 'redis-cli --intrinsic-latency 100' what is the intrinsic latency in your system.\n"
" 5) Check if the problem is allocator-related by recompiling Redis with MALLOC=libc, if you are using Jemalloc. However this may create fragmentation problems.\n");
}
/* AOF / Disk latency. */
if (advise_local_disk) {
report = sdscat(report,"- It is strongly advised to use local disks for persistence, especially if you are using AOF. Remote disks provided by platform-as-a-service providers are known to be slow.\n");
}
if (advise_ssd) {
report = sdscat(report,"- SSD disks are able to reduce fsync latency, and total time needed for snapshotting and AOF log rewriting (resulting in smaller memory usage and smaller final AOF rewrite buffer flushes). With extremely high write load SSD disks can be a good option. However Redis should perform reasonably with high load using normal disks. Use this advice as a last resort.\n");
}
if (advise_data_writeback) {
report = sdscat(report,"- Mounting ext3/4 filesystems with data=writeback can provide a performance boost compared to data=ordered, however this mode of operation provides less guarantees, and sometimes it can happen that after a hard crash the AOF file will have an half-written command at the end and will require to be repaired before Redis restarts.\n");
}
if (advise_disk_contention) {
report = sdscat(report,"- Try to lower the disk contention. This is often caused by other disk intensive processes running in the same computer (including other Redis instances).\n");
}
if (advise_no_appendfsync) {
report = sdscat(report,"- Assuming from the point of view of data safety this is viable in your environment, you could try to enable the 'no-appendfsync-on-rewrite' option, so that fsync will not be performed while there is a child rewriting the AOF file or producing an RDB file (the moment where there is high disk contention).\n");
}
if (advise_relax_fsync_policy && server.aof_fsync == AOF_FSYNC_ALWAYS) {
report = sdscat(report,"- Your fsync policy is set to 'always'. It is very hard to get good performances with such a setup, if possible try to relax the fsync policy to 'onesec'.\n");
}
if (advise_write_load_info) {
report = sdscat(report,"- Latency during the AOF atomic rename operation or when the final difference is flushed to the AOF file at the end of the rewrite, sometimes is caused by very high write load, causing the AOF buffer to get very large. If possible try to send less commands to accomplish the same work, or use Lua scripts to group multiple operations into a single EVALSHA call.\n");
}
if (advise_hz && server.hz < 100) {
report = sdscat(report,"- In order to make the Redis keys expiring process more incremental, try to set the 'hz' configuration parameter to 100 using 'CONFIG SET hz 100'.\n");
}
if (advise_large_objects) {
report = sdscat(report,"- Deleting, expiring or evicting (because of maxmemory policy) large objects is a blocking operation. If you have very large objects that are often deleted, expired, or evicted, try to fragment those objects into multiple smaller objects.\n");
}
if (advise_mass_eviction) {
report = sdscat(report,"- Sudden changes to the 'maxmemory' setting via 'CONFIG SET', or allocation of large objects via sets or sorted sets intersections, STORE option of SORT, Redis Cluster large keys migrations (RESTORE command), may create sudden memory pressure forcing the server to block trying to evict keys. \n");
}
if (advise_disable_thp) {
report = sdscat(report,"- I detected a non zero amount of anonymous huge pages used by your process. This creates very serious latency events in different conditions, especially when Redis is persisting on disk. To disable THP support use the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled', make sure to also add it into /etc/rc.local so that the command will be executed again after a reboot. Note that even if you have already disabled THP, you still need to restart the Redis process to get rid of the huge pages already created.\n");
}
}
return report;
}
/* ---------------------- Latency command implementation -------------------- */
/* latencyCommand() helper to produce a time-delay reply for all the samples
* in memory for the specified time series. */
void latencyCommandReplyWithSamples(redisClient *c, struct latencyTimeSeries *ts) {
void *replylen = addDeferredMultiBulkLength(c);
int samples = 0, j;
for (j = 0; j < LATENCY_TS_LEN; j++) {
int i = (ts->idx + j) % LATENCY_TS_LEN;
if (ts->samples[i].time == 0) continue;
addReplyMultiBulkLen(c,2);
addReplyLongLong(c,ts->samples[i].time);
addReplyLongLong(c,ts->samples[i].latency);
samples++;
}
setDeferredMultiBulkLength(c,replylen,samples);
}
/* latencyCommand() helper to produce the reply for the LATEST subcommand,
* listing the last latency sample for every event type registered so far. */
void latencyCommandReplyWithLatestEvents(redisClient *c) {
dictIterator *di;
dictEntry *de;
addReplyMultiBulkLen(c,dictSize(server.latency_events));
di = dictGetIterator(server.latency_events);
while((de = dictNext(di)) != NULL) {
char *event = dictGetKey(de);
struct latencyTimeSeries *ts = dictGetVal(de);
int last = (ts->idx + LATENCY_TS_LEN - 1) % LATENCY_TS_LEN;
addReplyMultiBulkLen(c,4);
addReplyBulkCString(c,event);
addReplyLongLong(c,ts->samples[last].time);
addReplyLongLong(c,ts->samples[last].latency);
addReplyLongLong(c,ts->max);
}
dictReleaseIterator(di);
}
#define LATENCY_GRAPH_COLS 80
sds latencyCommandGenSparkeline(char *event, struct latencyTimeSeries *ts) {
int j;
struct sequence *seq = createSparklineSequence();
sds graph = sdsempty();
uint32_t min = 0, max = 0;
for (j = 0; j < LATENCY_TS_LEN; j++) {
int i = (ts->idx + j) % LATENCY_TS_LEN;
int elapsed;
char buf[64];
if (ts->samples[i].time == 0) continue;
/* Update min and max. */
if (seq->length == 0) {
min = max = ts->samples[i].latency;
} else {
if (ts->samples[i].latency > max) max = ts->samples[i].latency;
if (ts->samples[i].latency < min) min = ts->samples[i].latency;
}
/* Use as label the number of seconds / minutes / hours / days
* ago the event happened. */
elapsed = (int)(time(NULL) - ts->samples[i].time); WIN_PORT_FIX /* cast (int) */
if (elapsed < 60)
snprintf(buf,sizeof(buf),"%ds",elapsed);
else if (elapsed < 3600)
snprintf(buf,sizeof(buf),"%dm",elapsed/60);
else if (elapsed < 3600*24)
snprintf(buf,sizeof(buf),"%dh",elapsed/3600);
else
snprintf(buf,sizeof(buf),"%dd",elapsed/(3600*24));
sparklineSequenceAddSample(seq,ts->samples[i].latency,buf);
}
graph = sdscatprintf(graph,
"%s - high %Iu ms, low %Iu ms (all time high %Iu ms)\n", event, WIN_PORT_FIX /* %ld -> %Id, %lu -> %Iu */
(PORT_ULONG) max, (PORT_ULONG) min, (PORT_ULONG) ts->max);
for (j = 0; j < LATENCY_GRAPH_COLS; j++)
graph = sdscatlen(graph,"-",1);
graph = sdscatlen(graph,"\n",1);
graph = sparklineRender(graph,seq,LATENCY_GRAPH_COLS,4,SPARKLINE_FILL);
freeSparklineSequence(seq);
return graph;
}
/* LATENCY command implementations.
*
* LATENCY SAMPLES: return time-latency samples for the specified event.
* LATENCY LATEST: return the latest latency for all the events classes.
* LATENCY DOCTOR: returns an human readable analysis of instance latency.
* LATENCY GRAPH: provide an ASCII graph of the latency of the specified event.
*/
void latencyCommand(redisClient *c) {
struct latencyTimeSeries *ts;
if (!strcasecmp(c->argv[1]->ptr,"history") && c->argc == 3) {
/* LATENCY HISTORY <event> */
ts = dictFetchValue(server.latency_events,c->argv[2]->ptr);
if (ts == NULL) {
addReplyMultiBulkLen(c,0);
} else {
latencyCommandReplyWithSamples(c,ts);
}
} else if (!strcasecmp(c->argv[1]->ptr,"graph") && c->argc == 3) {
/* LATENCY GRAPH <event> */
sds graph;
dictEntry *de;
char *event;
de = dictFind(server.latency_events,c->argv[2]->ptr);
if (de == NULL) goto nodataerr;
ts = dictGetVal(de);
event = dictGetKey(de);
graph = latencyCommandGenSparkeline(event,ts);
addReplyBulkCString(c,graph);
sdsfree(graph);
} else if (!strcasecmp(c->argv[1]->ptr,"latest") && c->argc == 2) {
/* LATENCY LATEST */
latencyCommandReplyWithLatestEvents(c);
} else if (!strcasecmp(c->argv[1]->ptr,"doctor") && c->argc == 2) {
/* LATENCY DOCTOR */
sds report = createLatencyReport();
addReplyBulkCBuffer(c,report,sdslen(report));
sdsfree(report);
} else if (!strcasecmp(c->argv[1]->ptr,"reset") && c->argc >= 2) {
/* LATENCY RESET */
if (c->argc == 2) {
addReplyLongLong(c,latencyResetEvent(NULL));
} else {
int j, resets = 0;
for (j = 2; j < c->argc; j++)
resets += latencyResetEvent(c->argv[j]->ptr);
addReplyLongLong(c,resets);
}
} else {
addReply(c,shared.syntaxerr);
}
return;
nodataerr:
/* Common error when the user asks for an event we have no latency
* information about. */
addReplyErrorFormat(c,
"No samples available for event '%s'", (char*) c->argv[2]->ptr);
}
| Zheaoli/redis_read | src/latency.c | C | bsd-3-clause | 27,309 |
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
SimpleFileParsing.h
Abstract:
Function prototypes and defines for the simple file parsing routines.
--*/
#ifndef _SIMPLE_FILE_PARSING_H_
#define _SIMPLE_FILE_PARSING_H_
#define T_CHAR char
STATUS
SFPInit (
VOID
)
;
STATUS
SFPOpenFile (
char *FileName
)
;
BOOLEAN
SFPIsKeyword (
T_CHAR *Str
)
;
BOOLEAN
SFPIsToken (
T_CHAR *Str
)
;
BOOLEAN
SFPGetNextToken (
T_CHAR *Str,
unsigned int Len
)
;
BOOLEAN
SFPGetGuidToken (
T_CHAR *Str,
UINT32 Len
)
;
#define PARSE_GUID_STYLE_5_FIELDS 0
BOOLEAN
SFPGetGuid (
int GuidStyle,
EFI_GUID *Value
)
;
BOOLEAN
SFPSkipToToken (
T_CHAR *Str
)
;
BOOLEAN
SFPGetNumber (
unsigned int *Value
)
;
BOOLEAN
SFPGetQuotedString (
T_CHAR *Str,
int Length
)
;
BOOLEAN
SFPIsEOF (
VOID
)
;
STATUS
SFPCloseFile (
VOID
)
;
unsigned
int
SFPGetLineNumber (
VOID
)
;
T_CHAR *
SFPGetFileName (
VOID
)
;
#endif // #ifndef _SIMPLE_FILE_PARSING_H_
| kontais/EFI-MIPS | Sample/Tools/Source/Common/SimpleFileParsing.h | C | bsd-3-clause | 1,740 |
/*
Copyright (c) 2003-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_BENCODE_HPP_INCLUDED
#define TORRENT_BENCODE_HPP_INCLUDED
// OVERVIEW
//
// Bencoding is a common representation in bittorrent used for
// for dictionary, list, int and string hierarchies. It's used
// to encode .torrent files and some messages in the network
// protocol. libtorrent also uses it to store settings, resume
// data and other state between sessions.
//
// Strings in bencoded structures are not necessarily representing
// text. Strings are raw byte buffers of a certain length. If a
// string is meant to be interpreted as text, it is required to
// be UTF-8 encoded. See `BEP 3`_.
//
// There are two mechanims to *decode* bencoded buffers in libtorrent.
//
// The most flexible one is bdecode(), which returns a structure
// represented by entry. When a buffer is decoded with this function,
// it can be discarded. The entry does not contain any references back
// to it. This means that bdecode() actually copies all the data out
// of the buffer and into its own hierarchy. This makes this
// function potentially expensive, if you're parsing large amounts
// of data.
//
// Another consideration is that bdecode() is a recursive parser.
// For this reason, in order to avoid DoS attacks by triggering
// a stack overflow, there is a recursion limit. This limit is
// a sanity check to make sure it doesn't run the risk of
// busting the stack.
//
// The second mechanism is lazy_bdecode(), which returns a
// bencoded structure represented by lazy_entry. This function
// builds a tree that points back into the original buffer.
// The returned lazy_entry will not be valid once the buffer
// it was parsed out of is discarded.
//
// Not only is this function more efficient because of less
// memory allocation and data copy, the parser is also not
// recursive, which means it probably performs a little bit
// better and can have a higher recursion limit on the structures
// it's parsing.
#include <stdlib.h>
#include <string>
#include <exception>
#include <iterator> // for distance
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/static_assert.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/escape_string.hpp"
#include "libtorrent/io.hpp" // for write_string
namespace libtorrent
{
#ifndef TORRENT_NO_DEPRECATE
// thrown by bdecode() if the provided bencoded buffer does not contain
// valid encoding.
struct TORRENT_EXPORT invalid_encoding: std::exception
{
// hidden
virtual const char* what() const throw() { return "invalid bencoding"; }
};
#endif
namespace detail
{
// this is used in the template, so it must be available to the client
TORRENT_EXPORT char const* integer_to_str(char* buf, int size
, entry::integer_type val);
template <class OutIt>
int write_integer(OutIt& out, entry::integer_type val)
{
// the stack allocated buffer for keeping the
// decimal representation of the number can
// not hold number bigger than this:
BOOST_STATIC_ASSERT(sizeof(entry::integer_type) <= 8);
char buf[21];
int ret = 0;
for (char const* str = integer_to_str(buf, 21, val);
*str != 0; ++str)
{
*out = *str;
++out;
++ret;
}
return ret;
}
template <class OutIt>
void write_char(OutIt& out, char c)
{
*out = c;
++out;
}
template <class InIt>
std::string read_until(InIt& in, InIt end, char end_token, bool& err)
{
std::string ret;
if (in == end)
{
err = true;
return ret;
}
while (*in != end_token)
{
ret += *in;
++in;
if (in == end)
{
err = true;
return ret;
}
}
return ret;
}
template<class InIt>
void read_string(InIt& in, InIt end, int len, std::string& str, bool& err)
{
TORRENT_ASSERT(len >= 0);
for (int i = 0; i < len; ++i)
{
if (in == end)
{
err = true;
return;
}
str += *in;
++in;
}
}
template<class OutIt>
int bencode_recursive(OutIt& out, const entry& e)
{
int ret = 0;
switch(e.type())
{
case entry::int_t:
write_char(out, 'i');
ret += write_integer(out, e.integer());
write_char(out, 'e');
ret += 2;
break;
case entry::string_t:
ret += write_integer(out, e.string().length());
write_char(out, ':');
ret += write_string(e.string(), out);
ret += 1;
break;
case entry::list_t:
write_char(out, 'l');
for (entry::list_type::const_iterator i = e.list().begin(); i != e.list().end(); ++i)
ret += bencode_recursive(out, *i);
write_char(out, 'e');
ret += 2;
break;
case entry::dictionary_t:
write_char(out, 'd');
for (entry::dictionary_type::const_iterator i = e.dict().begin();
i != e.dict().end(); ++i)
{
// write key
ret += write_integer(out, i->first.length());
write_char(out, ':');
ret += write_string(i->first, out);
// write value
ret += bencode_recursive(out, i->second);
ret += 1;
}
write_char(out, 'e');
ret += 2;
break;
default:
// trying to encode a structure with uninitialized values!
TORRENT_ASSERT_VAL(false, e.type());
// do nothing
break;
}
return ret;
}
template<class InIt>
void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth)
{
if (depth >= 100)
{
err = true;
return;
}
if (in == end)
{
err = true;
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
switch (*in)
{
// ----------------------------------------------
// integer
case 'i':
{
++in; // 'i'
std::string val = read_until(in, end, 'e', err);
if (err) return;
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
ret = entry(entry::int_t);
char* end_pointer;
ret.integer() = strtoll(val.c_str(), &end_pointer, 10);
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
if (end_pointer == val.c_str())
{
err = true;
return;
}
} break;
// ----------------------------------------------
// list
case 'l':
{
ret = entry(entry::list_t);
++in; // 'l'
while (*in != 'e')
{
ret.list().push_back(entry());
entry& e = ret.list().back();
bdecode_recursive(in, end, e, err, depth + 1);
if (err)
{
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
if (in == end)
{
err = true;
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
}
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// dictionary
case 'd':
{
ret = entry(entry::dictionary_t);
++in; // 'd'
while (*in != 'e')
{
entry key;
bdecode_recursive(in, end, key, err, depth + 1);
if (err || key.type() != entry::string_t)
{
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
entry& e = ret[key.string()];
bdecode_recursive(in, end, e, err, depth + 1);
if (err)
{
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
if (in == end)
{
err = true;
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
}
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// string
default:
if (is_digit((unsigned char)*in))
{
std::string len_s = read_until(in, end, ':', err);
if (err)
{
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
TORRENT_ASSERT(*in == ':');
++in; // ':'
int len = atoi(len_s.c_str());
ret = entry(entry::string_t);
read_string(in, end, len, ret.string(), err);
if (err)
{
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
}
else
{
err = true;
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
return;
}
#ifdef TORRENT_DEBUG
ret.m_type_queried = false;
#endif
}
}
}
// These functions will encode data to bencoded_ or decode bencoded_ data.
//
// If possible, lazy_bdecode() should be preferred over ``bdecode()``.
//
// The entry_ class is the internal representation of the bencoded data
// and it can be used to retrieve information, an entry_ can also be build by
// the program and given to ``bencode()`` to encode it into the ``OutIt``
// iterator.
//
// The ``OutIt`` and ``InIt`` are iterators
// (InputIterator_ and OutputIterator_ respectively). They
// are templates and are usually instantiated as ostream_iterator_,
// back_insert_iterator_ or istream_iterator_. These
// functions will assume that the iterator refers to a character
// (``char``). So, if you want to encode entry ``e`` into a buffer
// in memory, you can do it like this::
//
// std::vector<char> buffer;
// bencode(std::back_inserter(buf), e);
//
// .. _InputIterator: http://www.sgi.com/tech/stl/InputIterator.html
// .. _OutputIterator: http://www.sgi.com/tech/stl/OutputIterator.html
// .. _ostream_iterator: http://www.sgi.com/tech/stl/ostream_iterator.html
// .. _back_insert_iterator: http://www.sgi.com/tech/stl/back_insert_iterator.html
// .. _istream_iterator: http://www.sgi.com/tech/stl/istream_iterator.html
//
// If you want to decode a torrent file from a buffer in memory, you can do it like this::
//
// std::vector<char> buffer;
// // ...
// entry e = bdecode(buf.begin(), buf.end());
//
// Or, if you have a raw char buffer::
//
// const char* buf;
// // ...
// entry e = bdecode(buf, buf + data_size);
//
// Now we just need to know how to retrieve information from the entry.
//
// If ``bdecode()`` encounters invalid encoded data in the range given to it
// it will return a default constructed ``entry`` object.
template<class OutIt> int bencode(OutIt out, const entry& e)
{
return detail::bencode_recursive(out, e);
}
template<class InIt> entry bdecode(InIt start, InIt end)
{
entry e;
bool err = false;
detail::bdecode_recursive(start, end, e, err, 0);
#ifdef TORRENT_DEBUG
TORRENT_ASSERT(e.m_type_queried == false);
#endif
if (err) return entry();
return e;
}
template<class InIt> entry bdecode(InIt start, InIt end, int& len)
{
entry e;
bool err = false;
InIt s = start;
detail::bdecode_recursive(start, end, e, err, 0);
len = std::distance(s, start);
TORRENT_ASSERT(len >= 0);
if (err) return entry();
return e;
}
}
#endif // TORRENT_BENCODE_HPP_INCLUDED
| mirror/libtorrent | include/libtorrent/bencode.hpp | C++ | bsd-3-clause | 12,312 |
---
title: SQL and Operator
localeTitle: SQL和运算符
---
## SQL AND运算符
AND在WHERE子句或GROUP BY HAVING子句中用于限制从执行语句返回的行。当需要满足多个条件时使用AND。
我们将使用student表来展示示例。
这是没有WHERE子句的student表:
```sql
select * from student;
```

现在添加了WHERE子句以仅显示编程学生:
```sql
select * from student
where programOfStudy = 'Programming';
```

现在,使用AND更新WHERE子句,以显示SAT分数大于800的编程学生的结果:
```sql
select * from student
where programOfStudy = 'Programming'
and sat_score > 800;
```

这是广告系列投稿表中更复杂的示例。此示例具有带有HAVING子句的GROUP BY子句,该子句使用AND将返回的记录限制为2016年的奖金,总额为300万美元到1800万美元。
```sql
select Candidate, Office_Sought, Election_Year, FORMAT(sum(Total_$),2) from combined_party_data
where Office_Sought = 'PRESIDENT / VICE PRESIDENT'
group by Candidate, Office_Sought, Election_Year
having Election_Year = 2016 and sum(Total_$) between 3000000 and 18000000
order by sum(Total_$) desc;
```
 | otavioarc/freeCodeCamp | guide/chinese/sql/sql-and-operator/index.md | Markdown | bsd-3-clause | 1,586 |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapSearchModule")]
public class MapSearchModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Scene m_scene = null; // only need one for communication with GridService
List<Scene> m_scenes = new List<Scene>();
List<UUID> m_Clients;
IWorldMapModule m_WorldMap;
IWorldMapModule WorldMap
{
get
{
if (m_WorldMap == null)
m_WorldMap = m_scene.RequestModuleInterface<IWorldMapModule>();
return m_WorldMap;
}
}
#region ISharedRegionModule Members
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
{
m_scene = scene;
}
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
m_Clients = new List<UUID>();
}
public void RemoveRegion(Scene scene)
{
m_scenes.Remove(scene);
if (m_scene == scene && m_scenes.Count > 0)
m_scene = m_scenes[0];
scene.EventManager.OnNewClient -= OnNewClient;
}
public void PostInitialise()
{
}
public void Close()
{
m_scene = null;
m_scenes.Clear();
}
public string Name
{
get { return "MapSearchModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void RegionLoaded(Scene scene)
{
}
#endregion
private void OnNewClient(IClientAPI client)
{
client.OnMapNameRequest += OnMapNameRequestHandler;
}
private void OnMapNameRequestHandler(IClientAPI remoteClient, string mapName, uint flags)
{
lock (m_Clients)
{
if (m_Clients.Contains(remoteClient.AgentId))
return;
m_Clients.Add(remoteClient.AgentId);
}
OnMapNameRequest(remoteClient, mapName, flags);
}
private void OnMapNameRequest(IClientAPI remoteClient, string mapName, uint flags)
{
Util.FireAndForget(x =>
{
try
{
List<MapBlockData> blocks = new List<MapBlockData>();
if (mapName.Length < 3 || (mapName.EndsWith("#") && mapName.Length < 4))
{
// final block, closing the search result
AddFinalBlock(blocks,mapName);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
remoteClient.SendAlertMessage("Use a search string with at least 3 characters");
return;
}
//m_log.DebugFormat("MAP NAME=({0})", mapName);
// Hack to get around the fact that ll V3 now drops the port from the
// map name. See https://jira.secondlife.com/browse/VWR-28570
//
// Caller, use this magic form instead:
// secondlife://http|!!mygrid.com|8002|Region+Name/128/128
// or url encode if possible.
// the hacks we do with this viewer...
//
bool needOriginalName = false;
string mapNameOrig = mapName;
if (mapName.Contains("|"))
{
mapName = mapName.Replace('|', ':');
needOriginalName = true;
}
if (mapName.Contains("+"))
{
mapName = mapName.Replace('+', ' ');
needOriginalName = true;
}
if (mapName.Contains("!"))
{
mapName = mapName.Replace('!', '/');
needOriginalName = true;
}
if (mapName.Contains("."))
needOriginalName = true;
// try to fetch from GridServer
List<GridRegion> regionInfos = m_scene.GridService.GetRegionsByName(m_scene.RegionInfo.ScopeID, mapName, 20);
// if (regionInfos.Count == 0)
// remoteClient.SendAlertMessage("Hyperlink could not be established.");
//m_log.DebugFormat("[MAPSEARCHMODULE]: search {0} returned {1} regions", mapName, regionInfos.Count);
MapBlockData data;
if (regionInfos != null && regionInfos.Count > 0)
{
foreach (GridRegion info in regionInfos)
{
data = new MapBlockData();
data.Agents = 0;
data.Access = info.Access;
MapBlockData block = new MapBlockData();
WorldMap.MapBlockFromGridRegion(block, info, flags);
if (flags == 2 && regionInfos.Count == 1 && needOriginalName)
block.Name = mapNameOrig;
blocks.Add(block);
}
}
// final block, closing the search result
AddFinalBlock(blocks,mapNameOrig);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
// send extra user messages for V3
// because the UI is very confusing
// while we don't fix the hard-coded urls
if (flags == 2)
{
if (regionInfos == null || regionInfos.Count == 0)
remoteClient.SendAgentAlertMessage("No regions found with that name.", true);
// else if (regionInfos.Count == 1)
// remoteClient.SendAgentAlertMessage("Region found!", false);
}
}
finally
{
lock (m_Clients)
m_Clients.Remove(remoteClient.AgentId);
}
});
}
private void AddFinalBlock(List<MapBlockData> blocks,string name)
{
// final block, closing the search result
MapBlockData data = new MapBlockData();
data.Agents = 0;
data.Access = (byte)SimAccess.NonExistent;
data.MapImageId = UUID.Zero;
data.Name = name;
data.RegionFlags = 0;
data.WaterHeight = 0; // not used
data.X = 0;
data.Y = 0;
blocks.Add(data);
}
// private Scene GetClientScene(IClientAPI client)
// {
// foreach (Scene s in m_scenes)
// {
// if (client.Scene.RegionInfo.RegionHandle == s.RegionInfo.RegionHandle)
// return s;
// }
// return m_scene;
// }
}
}
| TomDataworks/opensim | OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs | C# | bsd-3-clause | 9,856 |
// Copyright 2011 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.
#include "cc/layers/tiled_layer.h"
#include <algorithm>
#include <vector>
#include "base/auto_reset.h"
#include "base/basictypes.h"
#include "build/build_config.h"
#include "cc/layers/layer_impl.h"
#include "cc/layers/tiled_layer_impl.h"
#include "cc/resources/layer_updater.h"
#include "cc/resources/prioritized_resource.h"
#include "cc/resources/priority_calculator.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/occlusion_tracker.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "ui/gfx/rect_conversions.h"
namespace cc {
// Maximum predictive expansion of the visible area.
static const int kMaxPredictiveTilesCount = 2;
// Number of rows/columns of tiles to pre-paint.
// We should increase these further as all textures are
// prioritized and we insure performance doesn't suffer.
static const int kPrepaintRows = 4;
static const int kPrepaintColumns = 2;
class UpdatableTile : public LayerTilingData::Tile {
public:
static scoped_ptr<UpdatableTile> Create(
scoped_ptr<LayerUpdater::Resource> updater_resource) {
return make_scoped_ptr(new UpdatableTile(updater_resource.Pass()));
}
LayerUpdater::Resource* updater_resource() { return updater_resource_.get(); }
PrioritizedResource* managed_resource() {
return updater_resource_->texture();
}
bool is_dirty() const { return !dirty_rect.IsEmpty(); }
// Reset update state for the current frame. This should occur before painting
// for all layers. Since painting one layer can invalidate another layer after
// it has already painted, mark all non-dirty tiles as valid before painting
// such that invalidations during painting won't prevent them from being
// pushed.
void ResetUpdateState() {
update_rect = gfx::Rect();
occluded = false;
partial_update = false;
valid_for_frame = !is_dirty();
}
// This promises to update the tile and therefore also guarantees the tile
// will be valid for this frame. dirty_rect is copied into update_rect so we
// can continue to track re-entrant invalidations that occur during painting.
void MarkForUpdate() {
valid_for_frame = true;
update_rect = dirty_rect;
dirty_rect = gfx::Rect();
}
gfx::Rect dirty_rect;
gfx::Rect update_rect;
bool partial_update;
bool valid_for_frame;
bool occluded;
private:
explicit UpdatableTile(scoped_ptr<LayerUpdater::Resource> updater_resource)
: partial_update(false),
valid_for_frame(false),
occluded(false),
updater_resource_(updater_resource.Pass()) {}
scoped_ptr<LayerUpdater::Resource> updater_resource_;
DISALLOW_COPY_AND_ASSIGN(UpdatableTile);
};
TiledLayer::TiledLayer()
: ContentsScalingLayer(),
texture_format_(RGBA_8888),
skips_draw_(false),
failed_update_(false),
tiling_option_(AUTO_TILE) {
tiler_ =
LayerTilingData::Create(gfx::Size(), LayerTilingData::HAS_BORDER_TEXELS);
}
TiledLayer::~TiledLayer() {}
scoped_ptr<LayerImpl> TiledLayer::CreateLayerImpl(LayerTreeImpl* tree_impl) {
return TiledLayerImpl::Create(tree_impl, id()).PassAs<LayerImpl>();
}
void TiledLayer::UpdateTileSizeAndTilingOption() {
DCHECK(layer_tree_host());
gfx::Size default_tile_size = layer_tree_host()->settings().default_tile_size;
gfx::Size max_untiled_layer_size =
layer_tree_host()->settings().max_untiled_layer_size;
int layer_width = content_bounds().width();
int layer_height = content_bounds().height();
gfx::Size tile_size(std::min(default_tile_size.width(), layer_width),
std::min(default_tile_size.height(), layer_height));
// Tile if both dimensions large, or any one dimension large and the other
// extends into a second tile but the total layer area isn't larger than that
// of the largest possible untiled layer. This heuristic allows for long
// skinny layers (e.g. scrollbars) that are Nx1 tiles to minimize wasted
// texture space but still avoids creating very large tiles.
bool any_dimension_large = layer_width > max_untiled_layer_size.width() ||
layer_height > max_untiled_layer_size.height();
bool any_dimension_one_tile =
(layer_width <= default_tile_size.width() ||
layer_height <= default_tile_size.height()) &&
(layer_width * layer_height) <= (max_untiled_layer_size.width() *
max_untiled_layer_size.height());
bool auto_tiled = any_dimension_large && !any_dimension_one_tile;
bool is_tiled;
if (tiling_option_ == ALWAYS_TILE)
is_tiled = true;
else if (tiling_option_ == NEVER_TILE)
is_tiled = false;
else
is_tiled = auto_tiled;
gfx::Size requested_size = is_tiled ? tile_size : content_bounds();
const int max_size =
layer_tree_host()->GetRendererCapabilities().max_texture_size;
requested_size.SetToMin(gfx::Size(max_size, max_size));
SetTileSize(requested_size);
}
void TiledLayer::UpdateBounds() {
gfx::Size old_tiling_size = tiler_->tiling_size();
gfx::Size new_tiling_size = content_bounds();
if (old_tiling_size == new_tiling_size)
return;
tiler_->SetTilingSize(new_tiling_size);
// Invalidate any areas that the new bounds exposes.
Region new_region =
SubtractRegions(gfx::Rect(new_tiling_size), gfx::Rect(old_tiling_size));
for (Region::Iterator new_rects(new_region); new_rects.has_rect();
new_rects.next())
InvalidateContentRect(new_rects.rect());
UpdateDrawsContent(HasDrawableContent());
}
void TiledLayer::SetTileSize(const gfx::Size& size) {
tiler_->SetTileSize(size);
UpdateDrawsContent(HasDrawableContent());
}
void TiledLayer::SetBorderTexelOption(
LayerTilingData::BorderTexelOption border_texel_option) {
tiler_->SetBorderTexelOption(border_texel_option);
UpdateDrawsContent(HasDrawableContent());
}
bool TiledLayer::HasDrawableContent() const {
bool has_more_than_one_tile =
(tiler_->num_tiles_x() > 1) || (tiler_->num_tiles_y() > 1);
return !(tiling_option_ == NEVER_TILE && has_more_than_one_tile) &&
ContentsScalingLayer::HasDrawableContent();
}
void TiledLayer::ReduceMemoryUsage() {
if (Updater())
Updater()->ReduceMemoryUsage();
}
void TiledLayer::SetIsMask(bool is_mask) {
set_tiling_option(is_mask ? NEVER_TILE : AUTO_TILE);
}
void TiledLayer::PushPropertiesTo(LayerImpl* layer) {
ContentsScalingLayer::PushPropertiesTo(layer);
TiledLayerImpl* tiled_layer = static_cast<TiledLayerImpl*>(layer);
tiled_layer->set_skips_draw(skips_draw_);
tiled_layer->SetTilingData(*tiler_);
std::vector<UpdatableTile*> invalid_tiles;
for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
iter != tiler_->tiles().end();
++iter) {
int i = iter->first.first;
int j = iter->first.second;
UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
// TODO(enne): This should not ever be null.
if (!tile)
continue;
if (!tile->managed_resource()->have_backing_texture()) {
// Evicted tiles get deleted from both layers
invalid_tiles.push_back(tile);
continue;
}
if (!tile->valid_for_frame) {
// Invalidated tiles are set so they can get different debug colors.
tiled_layer->PushInvalidTile(i, j);
continue;
}
tiled_layer->PushTileProperties(
i,
j,
tile->managed_resource()->resource_id(),
tile->opaque_rect(),
tile->managed_resource()->contents_swizzled());
}
for (std::vector<UpdatableTile*>::const_iterator iter = invalid_tiles.begin();
iter != invalid_tiles.end();
++iter)
tiler_->TakeTile((*iter)->i(), (*iter)->j());
// TiledLayer must push properties every frame, since viewport state and
// occlusion from anywhere in the tree can change what the layer decides to
// push to the impl tree.
needs_push_properties_ = true;
}
PrioritizedResourceManager* TiledLayer::ResourceManager() {
if (!layer_tree_host())
return NULL;
return layer_tree_host()->contents_texture_manager();
}
const PrioritizedResource* TiledLayer::ResourceAtForTesting(int i,
int j) const {
UpdatableTile* tile = TileAt(i, j);
if (!tile)
return NULL;
return tile->managed_resource();
}
void TiledLayer::SetLayerTreeHost(LayerTreeHost* host) {
if (host && host != layer_tree_host()) {
for (LayerTilingData::TileMap::const_iterator
iter = tiler_->tiles().begin();
iter != tiler_->tiles().end();
++iter) {
UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
// TODO(enne): This should not ever be null.
if (!tile)
continue;
tile->managed_resource()->SetTextureManager(
host->contents_texture_manager());
}
}
ContentsScalingLayer::SetLayerTreeHost(host);
}
UpdatableTile* TiledLayer::TileAt(int i, int j) const {
return static_cast<UpdatableTile*>(tiler_->TileAt(i, j));
}
UpdatableTile* TiledLayer::CreateTile(int i, int j) {
CreateUpdaterIfNeeded();
scoped_ptr<UpdatableTile> tile(
UpdatableTile::Create(Updater()->CreateResource(ResourceManager())));
tile->managed_resource()->SetDimensions(tiler_->tile_size(), texture_format_);
UpdatableTile* added_tile = tile.get();
tiler_->AddTile(tile.PassAs<LayerTilingData::Tile>(), i, j);
added_tile->dirty_rect = tiler_->TileRect(added_tile);
// Temporary diagnostic crash.
CHECK(added_tile);
CHECK(TileAt(i, j));
return added_tile;
}
void TiledLayer::SetNeedsDisplayRect(const gfx::RectF& dirty_rect) {
InvalidateContentRect(LayerRectToContentRect(dirty_rect));
ContentsScalingLayer::SetNeedsDisplayRect(dirty_rect);
}
void TiledLayer::InvalidateContentRect(const gfx::Rect& content_rect) {
UpdateBounds();
if (tiler_->is_empty() || content_rect.IsEmpty() || skips_draw_)
return;
for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
iter != tiler_->tiles().end();
++iter) {
UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
DCHECK(tile);
// TODO(enne): This should not ever be null.
if (!tile)
continue;
gfx::Rect bound = tiler_->TileRect(tile);
bound.Intersect(content_rect);
tile->dirty_rect.Union(bound);
}
}
// Returns true if tile is dirty and only part of it needs to be updated.
bool TiledLayer::TileOnlyNeedsPartialUpdate(UpdatableTile* tile) {
return !tile->dirty_rect.Contains(tiler_->TileRect(tile)) &&
tile->managed_resource()->have_backing_texture();
}
bool TiledLayer::UpdateTiles(int left,
int top,
int right,
int bottom,
ResourceUpdateQueue* queue,
const OcclusionTracker<Layer>* occlusion,
bool* updated) {
CreateUpdaterIfNeeded();
bool ignore_occlusions = !occlusion;
if (!HaveTexturesForTiles(left, top, right, bottom, ignore_occlusions)) {
failed_update_ = true;
return false;
}
gfx::Rect update_rect;
gfx::Rect paint_rect;
MarkTilesForUpdate(
&update_rect, &paint_rect, left, top, right, bottom, ignore_occlusions);
if (paint_rect.IsEmpty())
return true;
*updated = true;
UpdateTileTextures(
update_rect, paint_rect, left, top, right, bottom, queue, occlusion);
return true;
}
void TiledLayer::MarkOcclusionsAndRequestTextures(
int left,
int top,
int right,
int bottom,
const OcclusionTracker<Layer>* occlusion) {
int occluded_tile_count = 0;
bool succeeded = true;
for (int j = top; j <= bottom; ++j) {
for (int i = left; i <= right; ++i) {
UpdatableTile* tile = TileAt(i, j);
DCHECK(tile); // Did SetTexturePriorities get skipped?
// TODO(enne): This should not ever be null.
if (!tile)
continue;
// Did ResetUpdateState get skipped? Are we doing more than one occlusion
// pass?
DCHECK(!tile->occluded);
gfx::Rect visible_tile_rect = gfx::IntersectRects(
tiler_->tile_bounds(i, j), visible_content_rect());
if (!draw_transform_is_animating() && occlusion &&
occlusion->Occluded(
render_target(), visible_tile_rect, draw_transform())) {
tile->occluded = true;
occluded_tile_count++;
} else {
succeeded &= tile->managed_resource()->RequestLate();
}
}
}
}
bool TiledLayer::HaveTexturesForTiles(int left,
int top,
int right,
int bottom,
bool ignore_occlusions) {
for (int j = top; j <= bottom; ++j) {
for (int i = left; i <= right; ++i) {
UpdatableTile* tile = TileAt(i, j);
DCHECK(tile); // Did SetTexturePriorites get skipped?
// TODO(enne): This should not ever be null.
if (!tile)
continue;
// Ensure the entire tile is dirty if we don't have the texture.
if (!tile->managed_resource()->have_backing_texture())
tile->dirty_rect = tiler_->TileRect(tile);
// If using occlusion and the visible region of the tile is occluded,
// don't reserve a texture or update the tile.
if (tile->occluded && !ignore_occlusions)
continue;
if (!tile->managed_resource()->can_acquire_backing_texture())
return false;
}
}
return true;
}
void TiledLayer::MarkTilesForUpdate(gfx::Rect* update_rect,
gfx::Rect* paint_rect,
int left,
int top,
int right,
int bottom,
bool ignore_occlusions) {
for (int j = top; j <= bottom; ++j) {
for (int i = left; i <= right; ++i) {
UpdatableTile* tile = TileAt(i, j);
DCHECK(tile); // Did SetTexturePriorites get skipped?
// TODO(enne): This should not ever be null.
if (!tile)
continue;
if (tile->occluded && !ignore_occlusions)
continue;
// Prepare update rect from original dirty rects.
update_rect->Union(tile->dirty_rect);
// TODO(reveman): Decide if partial update should be allowed based on cost
// of update. https://bugs.webkit.org/show_bug.cgi?id=77376
if (tile->is_dirty() &&
!layer_tree_host()->AlwaysUsePartialTextureUpdates()) {
// If we get a partial update, we use the same texture, otherwise return
// the current texture backing, so we don't update visible textures
// non-atomically. If the current backing is in-use, it won't be
// deleted until after the commit as the texture manager will not allow
// deletion or recycling of in-use textures.
if (TileOnlyNeedsPartialUpdate(tile) &&
layer_tree_host()->RequestPartialTextureUpdate()) {
tile->partial_update = true;
} else {
tile->dirty_rect = tiler_->TileRect(tile);
tile->managed_resource()->ReturnBackingTexture();
}
}
paint_rect->Union(tile->dirty_rect);
tile->MarkForUpdate();
}
}
}
void TiledLayer::UpdateTileTextures(const gfx::Rect& update_rect,
const gfx::Rect& paint_rect,
int left,
int top,
int right,
int bottom,
ResourceUpdateQueue* queue,
const OcclusionTracker<Layer>* occlusion) {
// The update_rect should be in layer space. So we have to convert the
// paint_rect from content space to layer space.
float width_scale =
paint_properties().bounds.width() /
static_cast<float>(content_bounds().width());
float height_scale =
paint_properties().bounds.height() /
static_cast<float>(content_bounds().height());
update_rect_ = gfx::ScaleRect(update_rect, width_scale, height_scale);
// Calling PrepareToUpdate() calls into WebKit to paint, which may have the
// side effect of disabling compositing, which causes our reference to the
// texture updater to be deleted. However, we can't free the memory backing
// the SkCanvas until the paint finishes, so we grab a local reference here to
// hold the updater alive until the paint completes.
scoped_refptr<LayerUpdater> protector(Updater());
gfx::Rect painted_opaque_rect;
Updater()->PrepareToUpdate(paint_rect,
tiler_->tile_size(),
1.f / width_scale,
1.f / height_scale,
&painted_opaque_rect);
for (int j = top; j <= bottom; ++j) {
for (int i = left; i <= right; ++i) {
UpdatableTile* tile = TileAt(i, j);
DCHECK(tile); // Did SetTexturePriorites get skipped?
// TODO(enne): This should not ever be null.
if (!tile)
continue;
gfx::Rect tile_rect = tiler_->tile_bounds(i, j);
// Use update_rect as the above loop copied the dirty rect for this frame
// to update_rect.
gfx::Rect dirty_rect = tile->update_rect;
if (dirty_rect.IsEmpty())
continue;
// Save what was painted opaque in the tile. Keep the old area if the
// paint didn't touch it, and didn't paint some other part of the tile
// opaque.
gfx::Rect tile_painted_rect = gfx::IntersectRects(tile_rect, paint_rect);
gfx::Rect tile_painted_opaque_rect =
gfx::IntersectRects(tile_rect, painted_opaque_rect);
if (!tile_painted_rect.IsEmpty()) {
gfx::Rect paint_inside_tile_opaque_rect =
gfx::IntersectRects(tile->opaque_rect(), tile_painted_rect);
bool paint_inside_tile_opaque_rect_is_non_opaque =
!paint_inside_tile_opaque_rect.IsEmpty() &&
!tile_painted_opaque_rect.Contains(paint_inside_tile_opaque_rect);
bool opaque_paint_not_inside_tile_opaque_rect =
!tile_painted_opaque_rect.IsEmpty() &&
!tile->opaque_rect().Contains(tile_painted_opaque_rect);
if (paint_inside_tile_opaque_rect_is_non_opaque ||
opaque_paint_not_inside_tile_opaque_rect)
tile->set_opaque_rect(tile_painted_opaque_rect);
}
// source_rect starts as a full-sized tile with border texels included.
gfx::Rect source_rect = tiler_->TileRect(tile);
source_rect.Intersect(dirty_rect);
// Paint rect not guaranteed to line up on tile boundaries, so
// make sure that source_rect doesn't extend outside of it.
source_rect.Intersect(paint_rect);
tile->update_rect = source_rect;
if (source_rect.IsEmpty())
continue;
const gfx::Point anchor = tiler_->TileRect(tile).origin();
// Calculate tile-space rectangle to upload into.
gfx::Vector2d dest_offset = source_rect.origin() - anchor;
CHECK_GE(dest_offset.x(), 0);
CHECK_GE(dest_offset.y(), 0);
// Offset from paint rectangle to this tile's dirty rectangle.
gfx::Vector2d paint_offset = source_rect.origin() - paint_rect.origin();
CHECK_GE(paint_offset.x(), 0);
CHECK_GE(paint_offset.y(), 0);
CHECK_LE(paint_offset.x() + source_rect.width(), paint_rect.width());
CHECK_LE(paint_offset.y() + source_rect.height(), paint_rect.height());
tile->updater_resource()->Update(
queue, source_rect, dest_offset, tile->partial_update);
}
}
}
// This picks a small animated layer to be anything less than one viewport. This
// is specifically for page transitions which are viewport-sized layers. The
// extra tile of padding is due to these layers being slightly larger than the
// viewport in some cases.
bool TiledLayer::IsSmallAnimatedLayer() const {
if (!draw_transform_is_animating() && !screen_space_transform_is_animating())
return false;
gfx::Size viewport_size =
layer_tree_host() ? layer_tree_host()->device_viewport_size()
: gfx::Size();
gfx::Rect content_rect(content_bounds());
return content_rect.width() <=
viewport_size.width() + tiler_->tile_size().width() &&
content_rect.height() <=
viewport_size.height() + tiler_->tile_size().height();
}
namespace {
// TODO(epenner): Remove this and make this based on distance once distance can
// be calculated for offscreen layers. For now, prioritize all small animated
// layers after 512 pixels of pre-painting.
void SetPriorityForTexture(const gfx::Rect& visible_rect,
const gfx::Rect& tile_rect,
bool draws_to_root,
bool is_small_animated_layer,
PrioritizedResource* texture) {
int priority = PriorityCalculator::LowestPriority();
if (!visible_rect.IsEmpty()) {
priority = PriorityCalculator::PriorityFromDistance(
visible_rect, tile_rect, draws_to_root);
}
if (is_small_animated_layer) {
priority = PriorityCalculator::max_priority(
priority, PriorityCalculator::SmallAnimatedLayerMinPriority());
}
if (priority != PriorityCalculator::LowestPriority())
texture->set_request_priority(priority);
}
} // namespace
void TiledLayer::SetTexturePriorities(const PriorityCalculator& priority_calc) {
UpdateBounds();
ResetUpdateState();
UpdateScrollPrediction();
if (tiler_->has_empty_bounds())
return;
bool draws_to_root = !render_target()->parent();
bool small_animated_layer = IsSmallAnimatedLayer();
// Minimally create the tiles in the desired pre-paint rect.
gfx::Rect create_tiles_rect = IdlePaintRect();
if (small_animated_layer)
create_tiles_rect = gfx::Rect(content_bounds());
if (!create_tiles_rect.IsEmpty()) {
int left, top, right, bottom;
tiler_->ContentRectToTileIndices(
create_tiles_rect, &left, &top, &right, &bottom);
for (int j = top; j <= bottom; ++j) {
for (int i = left; i <= right; ++i) {
if (!TileAt(i, j))
CreateTile(i, j);
}
}
}
// Now update priorities on all tiles we have in the layer, no matter where
// they are.
for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
iter != tiler_->tiles().end();
++iter) {
UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
// TODO(enne): This should not ever be null.
if (!tile)
continue;
gfx::Rect tile_rect = tiler_->TileRect(tile);
SetPriorityForTexture(predicted_visible_rect_,
tile_rect,
draws_to_root,
small_animated_layer,
tile->managed_resource());
}
}
Region TiledLayer::VisibleContentOpaqueRegion() const {
if (skips_draw_)
return Region();
if (contents_opaque())
return visible_content_rect();
return tiler_->OpaqueRegionInContentRect(visible_content_rect());
}
void TiledLayer::ResetUpdateState() {
skips_draw_ = false;
failed_update_ = false;
LayerTilingData::TileMap::const_iterator end = tiler_->tiles().end();
for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
iter != end;
++iter) {
UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
// TODO(enne): This should not ever be null.
if (!tile)
continue;
tile->ResetUpdateState();
}
}
namespace {
gfx::Rect ExpandRectByDelta(const gfx::Rect& rect, const gfx::Vector2d& delta) {
int width = rect.width() + std::abs(delta.x());
int height = rect.height() + std::abs(delta.y());
int x = rect.x() + ((delta.x() < 0) ? delta.x() : 0);
int y = rect.y() + ((delta.y() < 0) ? delta.y() : 0);
return gfx::Rect(x, y, width, height);
}
}
void TiledLayer::UpdateScrollPrediction() {
// This scroll prediction is very primitive and should be replaced by a
// a recursive calculation on all layers which uses actual scroll/animation
// velocities. To insure this doesn't miss-predict, we only use it to predict
// the visible_rect if:
// - content_bounds() hasn't changed.
// - visible_rect.size() hasn't changed.
// These two conditions prevent rotations, scales, pinch-zooms etc. where
// the prediction would be incorrect.
gfx::Vector2d delta = visible_content_rect().CenterPoint() -
previous_visible_rect_.CenterPoint();
predicted_scroll_ = -delta;
predicted_visible_rect_ = visible_content_rect();
if (previous_content_bounds_ == content_bounds() &&
previous_visible_rect_.size() == visible_content_rect().size()) {
// Only expand the visible rect in the major scroll direction, to prevent
// massive paints due to diagonal scrolls.
gfx::Vector2d major_scroll_delta =
(std::abs(delta.x()) > std::abs(delta.y())) ?
gfx::Vector2d(delta.x(), 0) :
gfx::Vector2d(0, delta.y());
predicted_visible_rect_ =
ExpandRectByDelta(visible_content_rect(), major_scroll_delta);
// Bound the prediction to prevent unbounded paints, and clamp to content
// bounds.
gfx::Rect bound = visible_content_rect();
bound.Inset(-tiler_->tile_size().width() * kMaxPredictiveTilesCount,
-tiler_->tile_size().height() * kMaxPredictiveTilesCount);
bound.Intersect(gfx::Rect(content_bounds()));
predicted_visible_rect_.Intersect(bound);
}
previous_content_bounds_ = content_bounds();
previous_visible_rect_ = visible_content_rect();
}
bool TiledLayer::Update(ResourceUpdateQueue* queue,
const OcclusionTracker<Layer>* occlusion) {
DCHECK(!skips_draw_ && !failed_update_); // Did ResetUpdateState get skipped?
// Tiled layer always causes commits to wait for activation, as it does
// not support pending trees.
SetNextCommitWaitsForActivation();
bool updated = false;
{
base::AutoReset<bool> ignore_set_needs_commit(&ignore_set_needs_commit_,
true);
updated |= ContentsScalingLayer::Update(queue, occlusion);
UpdateBounds();
}
if (tiler_->has_empty_bounds() || !DrawsContent())
return false;
// Animation pre-paint. If the layer is small, try to paint it all
// immediately whether or not it is occluded, to avoid paint/upload
// hiccups while it is animating.
if (IsSmallAnimatedLayer()) {
int left, top, right, bottom;
tiler_->ContentRectToTileIndices(gfx::Rect(content_bounds()),
&left,
&top,
&right,
&bottom);
UpdateTiles(left, top, right, bottom, queue, NULL, &updated);
if (updated)
return updated;
// This was an attempt to paint the entire layer so if we fail it's okay,
// just fallback on painting visible etc. below.
failed_update_ = false;
}
if (predicted_visible_rect_.IsEmpty())
return updated;
// Visible painting. First occlude visible tiles and paint the non-occluded
// tiles.
int left, top, right, bottom;
tiler_->ContentRectToTileIndices(
predicted_visible_rect_, &left, &top, &right, &bottom);
MarkOcclusionsAndRequestTextures(left, top, right, bottom, occlusion);
skips_draw_ = !UpdateTiles(
left, top, right, bottom, queue, occlusion, &updated);
if (skips_draw_)
tiler_->reset();
if (skips_draw_ || updated)
return true;
// If we have already painting everything visible. Do some pre-painting while
// idle.
gfx::Rect idle_paint_content_rect = IdlePaintRect();
if (idle_paint_content_rect.IsEmpty())
return updated;
// Prepaint anything that was occluded but inside the layer's visible region.
if (!UpdateTiles(left, top, right, bottom, queue, NULL, &updated) ||
updated)
return updated;
int prepaint_left, prepaint_top, prepaint_right, prepaint_bottom;
tiler_->ContentRectToTileIndices(idle_paint_content_rect,
&prepaint_left,
&prepaint_top,
&prepaint_right,
&prepaint_bottom);
// Then expand outwards one row/column at a time until we find a dirty
// row/column to update. Increment along the major and minor scroll directions
// first.
gfx::Vector2d delta = -predicted_scroll_;
delta = gfx::Vector2d(delta.x() == 0 ? 1 : delta.x(),
delta.y() == 0 ? 1 : delta.y());
gfx::Vector2d major_delta =
(std::abs(delta.x()) > std::abs(delta.y())) ? gfx::Vector2d(delta.x(), 0)
: gfx::Vector2d(0, delta.y());
gfx::Vector2d minor_delta =
(std::abs(delta.x()) <= std::abs(delta.y())) ? gfx::Vector2d(delta.x(), 0)
: gfx::Vector2d(0, delta.y());
gfx::Vector2d deltas[4] = { major_delta, minor_delta, -major_delta,
-minor_delta };
for (int i = 0; i < 4; i++) {
if (deltas[i].y() > 0) {
while (bottom < prepaint_bottom) {
++bottom;
if (!UpdateTiles(
left, bottom, right, bottom, queue, NULL, &updated) ||
updated)
return updated;
}
}
if (deltas[i].y() < 0) {
while (top > prepaint_top) {
--top;
if (!UpdateTiles(
left, top, right, top, queue, NULL, &updated) ||
updated)
return updated;
}
}
if (deltas[i].x() < 0) {
while (left > prepaint_left) {
--left;
if (!UpdateTiles(
left, top, left, bottom, queue, NULL, &updated) ||
updated)
return updated;
}
}
if (deltas[i].x() > 0) {
while (right < prepaint_right) {
++right;
if (!UpdateTiles(
right, top, right, bottom, queue, NULL, &updated) ||
updated)
return updated;
}
}
}
return updated;
}
void TiledLayer::OnOutputSurfaceCreated() {
// Ensure that all textures are of the right format.
for (LayerTilingData::TileMap::const_iterator iter = tiler_->tiles().begin();
iter != tiler_->tiles().end();
++iter) {
UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second);
if (!tile)
continue;
PrioritizedResource* resource = tile->managed_resource();
resource->SetDimensions(resource->size(), texture_format_);
}
}
bool TiledLayer::NeedsIdlePaint() {
// Don't trigger more paints if we failed (as we'll just fail again).
if (failed_update_ || visible_content_rect().IsEmpty() ||
tiler_->has_empty_bounds() || !DrawsContent())
return false;
gfx::Rect idle_paint_content_rect = IdlePaintRect();
if (idle_paint_content_rect.IsEmpty())
return false;
int left, top, right, bottom;
tiler_->ContentRectToTileIndices(
idle_paint_content_rect, &left, &top, &right, &bottom);
for (int j = top; j <= bottom; ++j) {
for (int i = left; i <= right; ++i) {
UpdatableTile* tile = TileAt(i, j);
DCHECK(tile); // Did SetTexturePriorities get skipped?
if (!tile)
continue;
bool updated = !tile->update_rect.IsEmpty();
bool can_acquire =
tile->managed_resource()->can_acquire_backing_texture();
bool dirty =
tile->is_dirty() || !tile->managed_resource()->have_backing_texture();
if (!updated && can_acquire && dirty)
return true;
}
}
return false;
}
gfx::Rect TiledLayer::IdlePaintRect() {
// Don't inflate an empty rect.
if (visible_content_rect().IsEmpty())
return gfx::Rect();
gfx::Rect prepaint_rect = visible_content_rect();
prepaint_rect.Inset(-tiler_->tile_size().width() * kPrepaintColumns,
-tiler_->tile_size().height() * kPrepaintRows);
gfx::Rect content_rect(content_bounds());
prepaint_rect.Intersect(content_rect);
return prepaint_rect;
}
} // namespace cc
| sencha/chromium-spacewalk | cc/layers/tiled_layer.cc | C++ | bsd-3-clause | 32,370 |
# cf-builder-card
> Cloudflare Card Builder
## Installation
```sh
$ npm install cf-builder-card
```
## Usage
```jsx
import React from 'react';
import { CardBuilder } from 'cf-builder-card';
import { Table, TableBody, TableRow, TableCell } from 'cf-component-table';
import { Button } from 'cf-component-button';
const EXAMPLE_CARD = 'EXAMPLE_CARD';
const MyButton = (
<Button type="default" onClick={() => console.log('Button clicked!')}>
Click me!
</Button>
);
const BuilderCard = () => (
<CardBuilder
cardName={EXAMPLE_CARD}
title="This is a Card"
description="This is the description of a card."
control={MyButton}
table={
<Table striped>
<TableBody>
<TableRow>
<TableCell>One</TableCell>
<TableCell>Two</TableCell>
</TableRow>
<TableRow>
<TableCell>Three</TableCell>
<TableCell>Four</TableCell>
</TableRow>
</TableBody>
</Table>
}
drawers={[
{
id: 'api',
name: 'API',
content: 'API Content'
},
{
id: 'help',
name: 'Help',
content: 'Help Content'
}
]}
/>
);
export default BuilderCard;
```
| jroyal/cf-ui | packages/cf-builder-card/README.md | Markdown | bsd-3-clause | 1,234 |
(function ($) {
$.Redactor.opts.langs['ua'] = {
html: 'Код',
video: 'Відео',
image: 'Зображення',
table: 'Таблиця',
link: 'Посилання',
link_insert: 'Вставити посилання ...',
link_edit: 'Edit link',
unlink: 'Видалити посилання',
formatting: 'Стилі',
paragraph: 'Звичайний текст',
quote: 'Цитата',
code: 'Код',
header1: 'Заголовок 1',
header2: 'Заголовок 2',
header3: 'Заголовок 3',
header4: 'Заголовок 4',
bold: 'Жирний',
italic: 'Похилий',
fontcolor: 'Колір тексту',
backcolor: 'Заливка тексту',
unorderedlist: 'Звичайний список',
orderedlist: 'Нумерований список',
outdent: 'Зменшити відступ',
indent: 'Збільшити відступ',
cancel: 'Скасувати',
insert: 'Вставити',
save: 'Зберегти',
_delete: 'Видалити',
insert_table: 'Вставити таблицю',
insert_row_above: 'Додати рядок зверху',
insert_row_below: 'Додати рядок знизу',
insert_column_left: 'Додати стовпець ліворуч',
insert_column_right: 'Додати стовпець праворуч',
delete_column: 'Видалити стовпець',
delete_row: 'Видалити рядок',
delete_table: 'Видалити таблицю',
rows: 'Рядки',
columns: 'Стовпці',
add_head: 'Додати заголовок',
delete_head: 'Видалити заголовок',
title: 'Підказка',
image_view: 'Завантажити зображення',
image_position: 'Обтікання текстом',
none: 'ні',
left: 'ліворуч',
right: 'праворуч',
image_web_link: 'Посилання на зображення',
text: 'Текст',
mailto: 'Ел. пошта',
web: 'URL',
video_html_code: 'Код відео ролика',
file: 'Файл',
upload: 'Завантажити',
download: 'Завантажити',
choose: 'Вибрати',
or_choose: 'Або виберіть',
drop_file_here: 'Перетягніть файл сюди',
align_left: 'По лівому краю',
align_center: 'По центру',
align_right: 'По правому краю',
align_justify: 'Вирівняти текст по ширині',
horizontalrule: 'Горизонтальная лінійка',
fullscreen: 'На весь екран',
deleted: 'Закреслений',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab',
underline: 'Underline',
alignment: 'Alignment',
filename: 'Name (optional)'
};
})( jQuery ); | elearninglondon/ematrix_2015 | themes/third_party/editor/redactor/lang/ua.js | JavaScript | mit | 2,697 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// Takes a value and returns the largest value which is a integral amount of the second value.
/// </summary>
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")]
public class IntegralConverter : IMultiValueConverter
{
/// <summary>
/// Takes a value and returns the largest value which is a integral amount of the second value.
/// </summary>
/// <param name="values">
/// The first value is the source. The second is the factor.
/// </param>
/// <param name="targetType">The parameter is not used.</param>
/// <param name="parameter">The padding to subtract from the first value.</param>
/// <param name="culture">The parameter is not used.</param>
/// <returns>
/// The integral value.
/// </returns>
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
if (values.Length != 2)
{
throw new ArgumentException("Two values expected", "values");
}
if (values[0] == DependencyProperty.UnsetValue ||
values[1] == DependencyProperty.UnsetValue)
{
return DependencyProperty.UnsetValue;
}
var source = (double)values[0];
var factor = (double)values[1];
double padding = 0;
if (parameter != null)
{
padding = double.Parse((string)parameter, CultureInfo.InvariantCulture);
}
var newSource = source - padding;
if (newSource < factor)
{
return source;
}
var remainder = newSource % factor;
var result = newSource - remainder;
return result;
}
/// <summary>
/// This method is not used.
/// </summary>
/// <param name="value">The parameter is not used.</param>
/// <param name="targetTypes">The parameter is not used.</param>
/// <param name="parameter">The parameter is not used.</param>
/// <param name="culture">The parameter is not used.</param>
/// <returns>The parameter is not used.</returns>
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| JamesWTruher/PowerShell-1 | src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs | C# | mit | 2,970 |
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
$.extend(frappe.model, {
docinfo: {},
sync: function(r) {
/* docs:
extract docs, docinfo (attachments, comments, assignments)
from incoming request and set in `locals` and `frappe.model.docinfo`
*/
var isPlain;
if(!r.docs && !r.docinfo) r = {docs:r};
isPlain = $.isPlainObject(r.docs);
if(isPlain) r.docs = [r.docs];
if(r.docs) {
var last_parent_name = null;
for(var i=0, l=r.docs.length; i<l; i++) {
var d = r.docs[i];
frappe.model.add_to_locals(d);
d.__last_sync_on = new Date();
if(d.doctype==="DocType") {
frappe.meta.sync(d);
}
if(cur_frm && cur_frm.doctype==d.doctype && cur_frm.docname==d.name) {
cur_frm.doc = d;
}
if(d.localname) {
frappe.model.new_names[d.localname] = d.name;
$(document).trigger('rename', [d.doctype, d.localname, d.name]);
delete locals[d.doctype][d.localname];
// update docinfo to new dict keys
if(i===0) {
frappe.model.docinfo[d.doctype][d.name] = frappe.model.docinfo[d.doctype][d.localname];
frappe.model.docinfo[d.doctype][d.localname] = undefined;
}
}
}
if(cur_frm && isPlain) cur_frm.dirty();
}
// set docinfo (comments, assign, attachments)
if(r.docinfo) {
if(r.docs) {
var doc = r.docs[0];
} else {
if(cur_frm)
var doc = cur_frm.doc;
}
if(doc) {
if(!frappe.model.docinfo[doc.doctype])
frappe.model.docinfo[doc.doctype] = {};
frappe.model.docinfo[doc.doctype][doc.name] = r.docinfo;
}
}
return r.docs;
},
add_to_locals: function(doc) {
if(!locals[doc.doctype])
locals[doc.doctype] = {};
if(!doc.name && doc.__islocal) { // get name (local if required)
if(!doc.parentfield) frappe.model.clear_doc(doc);
doc.name = frappe.model.get_new_name(doc.doctype);
if(!doc.parentfield) frappe.provide("frappe.model.docinfo." + doc.doctype + "." + doc.name);
}
locals[doc.doctype][doc.name] = doc;
// add child docs to locals
if(!doc.parentfield) {
for(var i in doc) {
var value = doc[i];
if($.isArray(value)) {
for (var x=0, y=value.length; x < y; x++) {
var d = value[x];
if(!d.parent)
d.parent = doc.name;
frappe.model.add_to_locals(d);
}
}
}
}
}
});
| bcornwellmott/frappe | frappe/public/js/frappe/model/sync.js | JavaScript | mit | 2,359 |
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
| niqdev/react-redux-bootstrap4 | src/modules/counter/CounterActionTypes.js | JavaScript | mit | 106 |
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
cout<<"\n";
printf('\n');
// your code goes here
return 0;
}
| aqfaridi/Code-Online-Judge | web/env/Main1122/Main1122.cpp | C++ | mit | 152 |
package org.knowm.xchange.bitmarket;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.knowm.xchange.bitmarket.dto.account.BitMarketBalance;
import org.knowm.xchange.bitmarket.dto.marketdata.BitMarketOrderBook;
import org.knowm.xchange.bitmarket.dto.marketdata.BitMarketTicker;
import org.knowm.xchange.bitmarket.dto.marketdata.BitMarketTrade;
import org.knowm.xchange.bitmarket.dto.trade.BitMarketOrder;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.UserTrade;
public class BitMarketAssert {
public static void assertEquals(Balance o1, Balance o2) {
assertThat(o1.getCurrency()).isEqualTo(o2.getCurrency());
assertThat(o1.getTotal()).isEqualTo(o2.getTotal());
assertThat(o1.getAvailable()).isEqualTo(o2.getAvailable());
assertThat(o1.getFrozen()).isEqualTo(o2.getFrozen());
}
public static void assertEquals(Trade o1, Trade o2) {
assertThat(o1.getType()).isEqualTo(o2.getType());
assertThat(o1.getOriginalAmount()).isEqualTo(o2.getOriginalAmount());
assertThat(o1.getCurrencyPair()).isEqualTo(o2.getCurrencyPair());
assertThat(o1.getPrice()).isEqualTo(o2.getPrice());
assertThat(o1.getTimestamp()).isEqualTo(o2.getTimestamp());
assertThat(o1.getId()).isEqualTo(o2.getId());
}
public static void assertEquals(UserTrade o1, UserTrade o2) {
assertThat(o1.getType()).isEqualTo(o2.getType());
assertThat(o1.getOriginalAmount()).isEqualTo(o2.getOriginalAmount());
assertThat(o1.getCurrencyPair()).isEqualTo(o2.getCurrencyPair());
assertThat(o1.getPrice()).isEqualTo(o2.getPrice());
assertThat(o1.getTimestamp()).isEqualTo(o2.getTimestamp());
assertThat(o1.getId()).isEqualTo(o2.getId());
assertThat(o1.getOrderId()).isEqualTo(o2.getOrderId());
assertThat(o1.getFeeAmount()).isEqualTo(o2.getFeeAmount());
assertThat(o1.getFeeCurrency()).isEqualTo(o2.getFeeCurrency());
}
public static void assertEquals(LimitOrder o1, LimitOrder o2) {
assertThat(o1.getId()).isEqualTo(o2.getId());
assertThat(o1.getType()).isEqualTo(o2.getType());
assertThat(o1.getCurrencyPair()).isEqualTo(o2.getCurrencyPair());
assertThat(o1.getLimitPrice()).isEqualTo(o2.getLimitPrice());
assertThat(o1.getOriginalAmount()).isEqualTo(o2.getOriginalAmount());
assertThat(o1.getTimestamp()).isEqualTo(o2.getTimestamp());
}
public static void assertEqualsWithoutTimestamp(LimitOrder o1, LimitOrder o2) {
assertThat(o1.getId()).isEqualTo(o2.getId());
assertThat(o1.getType()).isEqualTo(o2.getType());
assertThat(o1.getCurrencyPair()).isEqualTo(o2.getCurrencyPair());
assertThat(o1.getLimitPrice()).isEqualTo(o2.getLimitPrice());
assertThat(o1.getOriginalAmount()).isEqualTo(o2.getOriginalAmount());
}
public static void assertEquals(Ticker o1, Ticker o2) {
assertThat(o1.getBid()).isEqualTo(o2.getBid());
assertThat(o1.getAsk()).isEqualTo(o2.getAsk());
assertThat(o1.getCurrencyPair()).isEqualTo(o2.getCurrencyPair());
assertThat(o1.getHigh()).isEqualTo(o2.getHigh());
assertThat(o1.getLast()).isEqualTo(o2.getLast());
assertThat(o1.getLow()).isEqualTo(o2.getLow());
assertThat(o1.getTimestamp()).isEqualTo(o2.getTimestamp());
assertThat(o1.getVolume()).isEqualTo(o2.getVolume());
assertThat(o1.getVwap()).isEqualTo(o2.getVwap());
}
public static void assertEquals(OrderBook o1, OrderBook o2) {
assertThat(o1.getTimeStamp()).isEqualTo(o2.getTimeStamp());
assertEquals(o1.getAsks(), o2.getAsks());
assertEquals(o1.getBids(), o2.getBids());
}
public static void assertEquals(List<LimitOrder> o1, List<LimitOrder> o2) {
assertThat(o1.size()).isEqualTo(o2.size());
for (int i = 0; i < o1.size(); i++) {
assertEqualsWithoutTimestamp(o1.get(i), o2.get(i));
}
}
public static void assertEquals(BitMarketOrder o1, BitMarketOrder o2) {
assertThat(o1.getId()).isEqualTo(o2.getId());
assertThat(o1.getMarket()).isEqualTo(o2.getMarket());
assertThat(o1.getAmount()).isEqualTo(o2.getAmount());
assertThat(o1.getRate()).isEqualTo(o2.getRate());
assertThat(o1.getFiat()).isEqualTo(o2.getFiat());
assertThat(o1.getType()).isEqualTo(o2.getType());
assertThat(o1.getTime()).isEqualTo(o2.getTime());
}
public static void assertEquals(BitMarketOrderBook o1, BitMarketOrderBook o2) {
assertEquals(o1.getAsks(), o2.getAsks());
assertEquals(o1.getBids(), o2.getBids());
assertThat(o1.toString()).isEqualTo(o2.toString());
}
public static void assertEquals(BitMarketTicker o1, BitMarketTicker o2) {
assertThat(o1.getAsk()).isEqualTo(o2.getAsk());
assertThat(o1.getBid()).isEqualTo(o2.getBid());
assertThat(o1.getLast()).isEqualTo(o2.getLast());
assertThat(o1.getLow()).isEqualTo(o2.getLow());
assertThat(o1.getHigh()).isEqualTo(o2.getHigh());
assertThat(o1.getVwap()).isEqualTo(o2.getVwap());
assertThat(o1.getVolume()).isEqualTo(o2.getVolume());
assertThat(o1.toString()).isEqualTo(o2.toString());
}
public static void assertEquals(BitMarketTrade o1, BitMarketTrade o2) {
assertThat(o1.getTid()).isEqualTo(o2.getTid());
assertThat(o1.getPrice()).isEqualTo(o2.getPrice());
assertThat(o1.getAmount()).isEqualTo(o2.getAmount());
assertThat(o1.getDate()).isEqualTo(o2.getDate());
assertThat(o1.toString()).isEqualTo(o2.toString());
}
public static void assertEquals(BitMarketBalance o1, BitMarketBalance o2) {
assertEquals(o1.getAvailable(), o2.getAvailable());
assertEquals(o1.getBlocked(), o2.getBlocked());
}
private static void assertEquals(Map<String, BigDecimal> o1, Map<String, BigDecimal> o2) {
assertThat(o1.size()).isEqualTo(o2.size());
for (String key : o1.keySet()) {
assertThat(o1.get(key)).isEqualTo(o2.get(key));
}
}
private static void assertEquals(BigDecimal[][] o1, BigDecimal[][] o2) {
assertThat(o1.length).isEqualTo(o2.length);
for (int i = 0; i < o1.length; i++) {
assertThat(o1[i].length).isEqualTo(o2[i].length);
for (int j = 0; j < o1[i].length; j++) {
assertThat(o1[i][j]).isEqualTo(o2[i][j]);
}
}
}
}
| chrisrico/XChange | xchange-bitmarket/src/test/java/org/knowm/xchange/bitmarket/BitMarketAssert.java | Java | mit | 6,414 |
package org.knowm.xchange.test.exx;
import java.io.IOException;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.exx.EXXExchange;
import org.knowm.xchange.service.account.AccountService;
/**
* kevinobamatheus@gmail.com
*
* @author kevingates
*/
public class AccountServiceIntegration {
public static void main(String[] args) {
try {
getAssetInfo();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void getAssetInfo() throws IOException {
String apiKey = "";
String secretKey = "";
Exchange exchange = ExchangeFactory.INSTANCE.createExchange(EXXExchange.class.getName());
ExchangeSpecification exchangeSpecification = exchange.getDefaultExchangeSpecification();
exchangeSpecification.setSslUri("https://trade.exx.com");
exchangeSpecification.setApiKey(apiKey);
exchangeSpecification.setSecretKey(secretKey);
exchange.applySpecification(exchangeSpecification);
AccountService accountService = exchange.getAccountService();
try {
System.out.println("accountInfo");
System.out.println(accountService.getAccountInfo());
System.out.println(accountService.getAccountInfo().getWallets());
} catch (IOException e) {
e.printStackTrace();
}
}
}
| chrisrico/XChange | xchange-exx/src/test/java/org/knowm/xchange/test/exx/AccountServiceIntegration.java | Java | mit | 1,369 |
from django.shortcuts import render
def home(request):
return render(request, 'home.html', {})
| Traviskn/django_starter_template | {{cookiecutter.project_name}}/{{cookiecutter.project_name}}/views.py | Python | mit | 101 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.commons.math3.geometry.euclidean.twod.hull (Apache Commons Math 3.5 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.commons.math3.geometry.euclidean.twod.hull (Apache Commons Math 3.5 API)";
}
//-->
</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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></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 class="aboutLanguage"><em><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../../org/apache/commons/math3/geometry/euclidean/twod/package-summary.html">PREV PACKAGE</a></li>
<li><a href="../../../../../../../../org/apache/commons/math3/geometry/hull/package-summary.html">NEXT PACKAGE</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/apache/commons/math3/geometry/euclidean/twod/hull/package-summary.html" target="_top">FRAMES</a></li>
<li><a href="package-summary.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package org.apache.commons.math3.geometry.euclidean.twod.hull</h1>
<p class="subTitle">
<div class="block">
This package provides algorithms to generate the convex hull
for a set of points in an two-dimensional euclidean space.</div>
</p>
<p>See: <a href="#package_description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../../org/apache/commons/math3/geometry/euclidean/twod/hull/ConvexHullGenerator2D.html" title="interface in org.apache.commons.math3.geometry.euclidean.twod.hull">ConvexHullGenerator2D</a></td>
<td class="colLast">
<div class="block">Interface for convex hull generators in the two-dimensional euclidean space.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../../org/apache/commons/math3/geometry/euclidean/twod/hull/AklToussaintHeuristic.html" title="class in org.apache.commons.math3.geometry.euclidean.twod.hull">AklToussaintHeuristic</a></td>
<td class="colLast">
<div class="block">A simple heuristic to improve the performance of convex hull algorithms.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../../org/apache/commons/math3/geometry/euclidean/twod/hull/ConvexHull2D.html" title="class in org.apache.commons.math3.geometry.euclidean.twod.hull">ConvexHull2D</a></td>
<td class="colLast">
<div class="block">This class represents a convex hull in an two-dimensional euclidean space.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../../org/apache/commons/math3/geometry/euclidean/twod/hull/MonotoneChain.html" title="class in org.apache.commons.math3.geometry.euclidean.twod.hull">MonotoneChain</a></td>
<td class="colLast">
<div class="block">Implements Andrew's monotone chain method to generate the convex hull of a finite set of
points in the two-dimensional euclidean space.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package_description">
<!-- -->
</a>
<h2 title="Package org.apache.commons.math3.geometry.euclidean.twod.hull Description">Package org.apache.commons.math3.geometry.euclidean.twod.hull Description</h2>
<div class="block"><p>
This package provides algorithms to generate the convex hull
for a set of points in an two-dimensional euclidean space.
</p></div>
</div>
<!-- ======= 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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></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 class="aboutLanguage"><em><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../../org/apache/commons/math3/geometry/euclidean/twod/package-summary.html">PREV PACKAGE</a></li>
<li><a href="../../../../../../../../org/apache/commons/math3/geometry/hull/package-summary.html">NEXT PACKAGE</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/apache/commons/math3/geometry/euclidean/twod/hull/package-summary.html" target="_top">FRAMES</a></li>
<li><a href="package-summary.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2003–2015 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| AlexFiliakov/BlackScholesCalculator | src/com/alexfiliakov/blackscholescalc/commons-math3-3.5/docs/apidocs/org/apache/commons/math3/geometry/euclidean/twod/hull/package-summary.html | HTML | mit | 7,939 |
# Check the various features of the ShTest format.
#
# RUN: not %{lit} -j 1 -v %{inputs}/shtest-format > %t.out
# RUN: FileCheck < %t.out %s
#
# END.
# CHECK: -- Testing:
# CHECK: FAIL: shtest-format :: external_shell/fail.txt
# CHECK: *** TEST 'shtest-format :: external_shell/fail.txt' FAILED ***
# CHECK: Command Output (stderr):
# CHECK: cat: does-not-exist: No such file or directory
# CHECK: --
# CHECK: PASS: shtest-format :: external_shell/pass.txt
# CHECK: FAIL: shtest-format :: fail.txt
# CHECK: UNRESOLVED: shtest-format :: no-test-line.txt
# CHECK: PASS: shtest-format :: pass.txt
# CHECK: UNSUPPORTED: shtest-format :: requires-missing.txt
# CHECK: PASS: shtest-format :: requires-present.txt
# CHECK: UNSUPPORTED: shtest-format :: unsupported_dir/some-test.txt
# CHECK: XFAIL: shtest-format :: xfail-feature.txt
# CHECK: XFAIL: shtest-format :: xfail-target.txt
# CHECK: XFAIL: shtest-format :: xfail.txt
# CHECK: XPASS: shtest-format :: xpass.txt
# CHECK: Testing Time
# CHECK: Unexpected Passing Tests (1)
# CHECK: shtest-format :: xpass.txt
# CHECK: Failing Tests (2)
# CHECK: shtest-format :: external_shell/fail.txt
# CHECK: shtest-format :: fail.txt
# CHECK: Expected Passes : 3
# CHECK: Expected Failures : 3
# CHECK: Unsupported Tests : 2
# CHECK: Unresolved Tests : 1
# CHECK: Unexpected Passes : 1
# CHECK: Unexpected Failures: 2
| dbrumley/recfi | llvm-3.3/utils/lit/tests/shtest-format.py | Python | mit | 1,371 |
// Time Complexity: O(n^2)
// Space Complexity: O(1)
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > ans;
const int target = 0;
sort(num.begin(), num.end());
auto last = num.rend();
for(auto a = num.rbegin(); a < prev(last, 2); ++a) {
if(a > num.rbegin() && *a == *(a - 1))
continue;
auto b = next(a);
auto c = prev(last);
while(b < c) {
if(b > next(a) && *b == *(b - 1)) {
++b;
}
else if(c < prev(last) && *c == *(c + 1)) {
--c;
}
else {
const int sum = *a + *b + *c;
if(sum < target)
--c;
else if(sum > target)
++b;
else {
ans.push_back({ *c, *b, *a});
++b;
--c;
}
}
}
}
return ans;
}
};
| tudennis/LeetCode---kamyu104-11-24-2015 | C++/threeSum2.cpp | C++ | mit | 1,277 |
/*<html><pre> -<a href="qh-qhull.htm"
>-------------------------------</a><a name="TOP">-</a>
libqhull.c
Quickhull algorithm for convex hulls
qhull() and top-level routines
see qh-qhull.htm, libqhull.h, unix.c
see qhull_a.h for internal functions
Copyright (c) 1993-2015 The Geometry Center.
$Id: //main/2015/qhull/src/libqhull/libqhull.c#3 $$Change: 2047 $
$DateTime: 2016/01/04 22:03:18 $$Author: bbarber $
*/
#include "qhull_a.h"
/*============= functions in alphabetic order after qhull() =======*/
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="qhull">-</a>
qh_qhull()
compute DIM3 convex hull of qh.num_points starting at qh.first_point
qh contains all global options and variables
returns:
returns polyhedron
qh.facet_list, qh.num_facets, qh.vertex_list, qh.num_vertices,
returns global variables
qh.hulltime, qh.max_outside, qh.interior_point, qh.max_vertex, qh.min_vertex
returns precision constants
qh.ANGLEround, centrum_radius, cos_max, DISTround, MAXabs_coord, ONEmerge
notes:
unless needed for output
qh.max_vertex and qh.min_vertex are max/min due to merges
see:
to add individual points to either qh.num_points
use qh_addpoint()
if qh.GETarea
qh_produceoutput() returns qh.totarea and qh.totvol via qh_getarea()
design:
record starting time
initialize hull and partition points
build convex hull
unless early termination
update facet->maxoutside for vertices, coplanar, and near-inside points
error if temporary sets exist
record end time
*/
void qh_qhull(void) {
int numoutside;
qh hulltime= qh_CPUclock;
if (qh RERUN || qh JOGGLEmax < REALmax/2)
qh_build_withrestart();
else {
qh_initbuild();
qh_buildhull();
}
if (!qh STOPpoint && !qh STOPcone) {
if (qh ZEROall_ok && !qh TESTvneighbors && qh MERGEexact)
qh_checkzero( qh_ALL);
if (qh ZEROall_ok && !qh TESTvneighbors && !qh WAScoplanar) {
trace2((qh ferr, 2055, "qh_qhull: all facets are clearly convex and no coplanar points. Post-merging and check of maxout not needed.\n"));
qh DOcheckmax= False;
}else {
if (qh MERGEexact || (qh hull_dim > qh_DIMreduceBuild && qh PREmerge))
qh_postmerge("First post-merge", qh premerge_centrum, qh premerge_cos,
(qh POSTmerge ? False : qh TESTvneighbors));
else if (!qh POSTmerge && qh TESTvneighbors)
qh_postmerge("For testing vertex neighbors", qh premerge_centrum,
qh premerge_cos, True);
if (qh POSTmerge)
qh_postmerge("For post-merging", qh postmerge_centrum,
qh postmerge_cos, qh TESTvneighbors);
if (qh visible_list == qh facet_list) { /* i.e., merging done */
qh findbestnew= True;
qh_partitionvisible(/*qh.visible_list*/ !qh_ALL, &numoutside);
qh findbestnew= False;
qh_deletevisible(/*qh.visible_list*/);
qh_resetlists(False, qh_RESETvisible /*qh.visible_list newvertex_list newfacet_list */);
}
}
if (qh DOcheckmax){
if (qh REPORTfreq) {
qh_buildtracing(NULL, NULL);
qh_fprintf(qh ferr, 8115, "\nTesting all coplanar points.\n");
}
qh_check_maxout();
}
if (qh KEEPnearinside && !qh maxoutdone)
qh_nearcoplanar();
}
if (qh_setsize(qhmem.tempstack) != 0) {
qh_fprintf(qh ferr, 6164, "qhull internal error (qh_qhull): temporary sets not empty(%d)\n",
qh_setsize(qhmem.tempstack));
qh_errexit(qh_ERRqhull, NULL, NULL);
}
qh hulltime= qh_CPUclock - qh hulltime;
qh QHULLfinished= True;
trace1((qh ferr, 1036, "Qhull: algorithm completed\n"));
} /* qhull */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="addpoint">-</a>
qh_addpoint( furthest, facet, checkdist )
add point (usually furthest point) above facet to hull
if checkdist,
check that point is above facet.
if point is not outside of the hull, uses qh_partitioncoplanar()
assumes that facet is defined by qh_findbestfacet()
else if facet specified,
assumes that point is above facet (major damage if below)
for Delaunay triangulations,
Use qh_setdelaunay() to lift point to paraboloid and scale by 'Qbb' if needed
Do not use options 'Qbk', 'QBk', or 'QbB' since they scale the coordinates.
returns:
returns False if user requested an early termination
qh.visible_list, newfacet_list, delvertex_list, NEWfacets may be defined
updates qh.facet_list, qh.num_facets, qh.vertex_list, qh.num_vertices
clear qh.maxoutdone (will need to call qh_check_maxout() for facet->maxoutside)
if unknown point, adds a pointer to qh.other_points
do not deallocate the point's coordinates
notes:
assumes point is near its best facet and not at a local minimum of a lens
distributions. Use qh_findbestfacet to avoid this case.
uses qh.visible_list, qh.newfacet_list, qh.delvertex_list, qh.NEWfacets
see also:
qh_triangulate() -- triangulate non-simplicial facets
design:
add point to other_points if needed
if checkdist
if point not above facet
partition coplanar point
exit
exit if pre STOPpoint requested
find horizon and visible facets for point
make new facets for point to horizon
make hyperplanes for point
compute balance statistics
match neighboring new facets
update vertex neighbors and delete interior vertices
exit if STOPcone requested
merge non-convex new facets
if merge found, many merges, or 'Qf'
use qh_findbestnew() instead of qh_findbest()
partition outside points from visible facets
delete visible facets
check polyhedron if requested
exit if post STOPpoint requested
reset working lists of facets and vertices
*/
boolT qh_addpoint(pointT *furthest, facetT *facet, boolT checkdist) {
int goodvisible, goodhorizon;
vertexT *vertex;
facetT *newfacet;
realT dist, newbalance, pbalance;
boolT isoutside= False;
int numpart, numpoints, numnew, firstnew;
qh maxoutdone= False;
if (qh_pointid(furthest) == qh_IDunknown)
qh_setappend(&qh other_points, furthest);
if (!facet) {
qh_fprintf(qh ferr, 6213, "qhull internal error (qh_addpoint): NULL facet. Need to call qh_findbestfacet first\n");
qh_errexit(qh_ERRqhull, NULL, NULL);
}
if (checkdist) {
facet= qh_findbest(furthest, facet, !qh_ALL, !qh_ISnewfacets, !qh_NOupper,
&dist, &isoutside, &numpart);
zzadd_(Zpartition, numpart);
if (!isoutside) {
zinc_(Znotmax); /* last point of outsideset is no longer furthest. */
facet->notfurthest= True;
qh_partitioncoplanar(furthest, facet, &dist);
return True;
}
}
qh_buildtracing(furthest, facet);
if (qh STOPpoint < 0 && qh furthest_id == -qh STOPpoint-1) {
facet->notfurthest= True;
return False;
}
qh_findhorizon(furthest, facet, &goodvisible, &goodhorizon);
if (qh ONLYgood && !(goodvisible+goodhorizon) && !qh GOODclosest) {
zinc_(Znotgood);
facet->notfurthest= True;
/* last point of outsideset is no longer furthest. This is ok
since all points of the outside are likely to be bad */
qh_resetlists(False, qh_RESETvisible /*qh.visible_list newvertex_list newfacet_list */);
return True;
}
zzinc_(Zprocessed);
firstnew= qh facet_id;
vertex= qh_makenewfacets(furthest /*visible_list, attaches if !ONLYgood */);
qh_makenewplanes(/* newfacet_list */);
numnew= qh facet_id - firstnew;
newbalance= numnew - (realT) (qh num_facets-qh num_visible)
* qh hull_dim/qh num_vertices;
wadd_(Wnewbalance, newbalance);
wadd_(Wnewbalance2, newbalance * newbalance);
if (qh ONLYgood
&& !qh_findgood(qh newfacet_list, goodhorizon) && !qh GOODclosest) {
FORALLnew_facets
qh_delfacet(newfacet);
qh_delvertex(vertex);
qh_resetlists(True, qh_RESETvisible /*qh.visible_list newvertex_list newfacet_list */);
zinc_(Znotgoodnew);
facet->notfurthest= True;
return True;
}
if (qh ONLYgood)
qh_attachnewfacets(/*visible_list*/);
qh_matchnewfacets();
qh_updatevertices();
if (qh STOPcone && qh furthest_id == qh STOPcone-1) {
facet->notfurthest= True;
return False; /* visible_list etc. still defined */
}
qh findbestnew= False;
if (qh PREmerge || qh MERGEexact) {
qh_premerge(vertex, qh premerge_centrum, qh premerge_cos);
if (qh_USEfindbestnew)
qh findbestnew= True;
else {
FORALLnew_facets {
if (!newfacet->simplicial) {
qh findbestnew= True; /* use qh_findbestnew instead of qh_findbest*/
break;
}
}
}
}else if (qh BESToutside)
qh findbestnew= True;
qh_partitionvisible(/*qh.visible_list*/ !qh_ALL, &numpoints);
qh findbestnew= False;
qh findbest_notsharp= False;
zinc_(Zpbalance);
pbalance= numpoints - (realT) qh hull_dim /* assumes all points extreme */
* (qh num_points - qh num_vertices)/qh num_vertices;
wadd_(Wpbalance, pbalance);
wadd_(Wpbalance2, pbalance * pbalance);
qh_deletevisible(/*qh.visible_list*/);
zmax_(Zmaxvertex, qh num_vertices);
qh NEWfacets= False;
if (qh IStracing >= 4) {
if (qh num_facets < 2000)
qh_printlists();
qh_printfacetlist(qh newfacet_list, NULL, True);
qh_checkpolygon(qh facet_list);
}else if (qh CHECKfrequently) {
if (qh num_facets < 50)
qh_checkpolygon(qh facet_list);
else
qh_checkpolygon(qh newfacet_list);
}
if (qh STOPpoint > 0 && qh furthest_id == qh STOPpoint-1)
return False;
qh_resetlists(True, qh_RESETvisible /*qh.visible_list newvertex_list newfacet_list */);
/* qh_triangulate(); to test qh.TRInormals */
trace2((qh ferr, 2056, "qh_addpoint: added p%d new facets %d new balance %2.2g point balance %2.2g\n",
qh_pointid(furthest), numnew, newbalance, pbalance));
return True;
} /* addpoint */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="build_withrestart">-</a>
qh_build_withrestart()
allow restarts due to qh.JOGGLEmax while calling qh_buildhull()
qh_errexit always undoes qh_build_withrestart()
qh.FIRSTpoint/qh.NUMpoints is point array
it may be moved by qh_joggleinput()
*/
void qh_build_withrestart(void) {
int restart;
qh ALLOWrestart= True;
while (True) {
restart= setjmp(qh restartexit); /* simple statement for CRAY J916 */
if (restart) { /* only from qh_precision() */
zzinc_(Zretry);
wmax_(Wretrymax, qh JOGGLEmax);
/* QH7078 warns about using 'TCn' with 'QJn' */
qh STOPcone= qh_IDunknown; /* if break from joggle, prevents normal output */
}
if (!qh RERUN && qh JOGGLEmax < REALmax/2) {
if (qh build_cnt > qh_JOGGLEmaxretry) {
qh_fprintf(qh ferr, 6229, "qhull precision error: %d attempts to construct a convex hull\n\
with joggled input. Increase joggle above 'QJ%2.2g'\n\
or modify qh_JOGGLE... parameters in user.h\n",
qh build_cnt, qh JOGGLEmax);
qh_errexit(qh_ERRqhull, NULL, NULL);
}
if (qh build_cnt && !restart)
break;
}else if (qh build_cnt && qh build_cnt >= qh RERUN)
break;
qh STOPcone= 0;
qh_freebuild(True); /* first call is a nop */
qh build_cnt++;
if (!qh qhull_optionsiz)
qh qhull_optionsiz= (int)strlen(qh qhull_options); /* WARN64 */
else {
qh qhull_options [qh qhull_optionsiz]= '\0';
qh qhull_optionlen= qh_OPTIONline; /* starts a new line */
}
qh_option("_run", &qh build_cnt, NULL);
if (qh build_cnt == qh RERUN) {
qh IStracing= qh TRACElastrun; /* duplicated from qh_initqhull_globals */
if (qh TRACEpoint != qh_IDunknown || qh TRACEdist < REALmax/2 || qh TRACEmerge) {
qh TRACElevel= (qh IStracing? qh IStracing : 3);
qh IStracing= 0;
}
qhmem.IStracing= qh IStracing;
}
if (qh JOGGLEmax < REALmax/2)
qh_joggleinput();
qh_initbuild();
qh_buildhull();
if (qh JOGGLEmax < REALmax/2 && !qh MERGING)
qh_checkconvex(qh facet_list, qh_ALGORITHMfault);
}
qh ALLOWrestart= False;
} /* qh_build_withrestart */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="buildhull">-</a>
qh_buildhull()
construct a convex hull by adding outside points one at a time
returns:
notes:
may be called multiple times
checks facet and vertex lists for incorrect flags
to recover from STOPcone, call qh_deletevisible and qh_resetlists
design:
check visible facet and newfacet flags
check newlist vertex flags and qh.STOPcone/STOPpoint
for each facet with a furthest outside point
add point to facet
exit if qh.STOPcone or qh.STOPpoint requested
if qh.NARROWhull for initial simplex
partition remaining outside points to coplanar sets
*/
void qh_buildhull(void) {
facetT *facet;
pointT *furthest;
vertexT *vertex;
int id;
trace1((qh ferr, 1037, "qh_buildhull: start build hull\n"));
FORALLfacets {
if (facet->visible || facet->newfacet) {
qh_fprintf(qh ferr, 6165, "qhull internal error (qh_buildhull): visible or new facet f%d in facet list\n",
facet->id);
qh_errexit(qh_ERRqhull, facet, NULL);
}
}
FORALLvertices {
if (vertex->newlist) {
qh_fprintf(qh ferr, 6166, "qhull internal error (qh_buildhull): new vertex f%d in vertex list\n",
vertex->id);
qh_errprint("ERRONEOUS", NULL, NULL, NULL, vertex);
qh_errexit(qh_ERRqhull, NULL, NULL);
}
id= qh_pointid(vertex->point);
if ((qh STOPpoint>0 && id == qh STOPpoint-1) ||
(qh STOPpoint<0 && id == -qh STOPpoint-1) ||
(qh STOPcone>0 && id == qh STOPcone-1)) {
trace1((qh ferr, 1038,"qh_buildhull: stop point or cone P%d in initial hull\n", id));
return;
}
}
qh facet_next= qh facet_list; /* advance facet when processed */
while ((furthest= qh_nextfurthest(&facet))) {
qh num_outside--; /* if ONLYmax, furthest may not be outside */
if (!qh_addpoint(furthest, facet, qh ONLYmax))
break;
}
if (qh NARROWhull) /* move points from outsideset to coplanarset */
qh_outcoplanar( /* facet_list */ );
if (qh num_outside && !furthest) {
qh_fprintf(qh ferr, 6167, "qhull internal error (qh_buildhull): %d outside points were never processed.\n", qh num_outside);
qh_errexit(qh_ERRqhull, NULL, NULL);
}
trace1((qh ferr, 1039, "qh_buildhull: completed the hull construction\n"));
} /* buildhull */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="buildtracing">-</a>
qh_buildtracing( furthest, facet )
trace an iteration of qh_buildhull() for furthest point and facet
if !furthest, prints progress message
returns:
tracks progress with qh.lastreport
updates qh.furthest_id (-3 if furthest is NULL)
also resets visit_id, vertext_visit on wrap around
see:
qh_tracemerging()
design:
if !furthest
print progress message
exit
if 'TFn' iteration
print progress message
else if tracing
trace furthest point and facet
reset qh.visit_id and qh.vertex_visit if overflow may occur
set qh.furthest_id for tracing
*/
void qh_buildtracing(pointT *furthest, facetT *facet) {
realT dist= 0;
float cpu;
int total, furthestid;
time_t timedata;
struct tm *tp;
vertexT *vertex;
qh old_randomdist= qh RANDOMdist;
qh RANDOMdist= False;
if (!furthest) {
time(&timedata);
tp= localtime(&timedata);
cpu= (float)qh_CPUclock - (float)qh hulltime;
cpu /= (float)qh_SECticks;
total= zzval_(Ztotmerge) - zzval_(Zcyclehorizon) + zzval_(Zcyclefacettot);
qh_fprintf(qh ferr, 8118, "\n\
At %02d:%02d:%02d & %2.5g CPU secs, qhull has created %d facets and merged %d.\n\
The current hull contains %d facets and %d vertices. Last point was p%d\n",
tp->tm_hour, tp->tm_min, tp->tm_sec, cpu, qh facet_id -1,
total, qh num_facets, qh num_vertices, qh furthest_id);
return;
}
furthestid= qh_pointid(furthest);
if (qh TRACEpoint == furthestid) {
qh IStracing= qh TRACElevel;
qhmem.IStracing= qh TRACElevel;
}else if (qh TRACEpoint != qh_IDunknown && qh TRACEdist < REALmax/2) {
qh IStracing= 0;
qhmem.IStracing= 0;
}
if (qh REPORTfreq && (qh facet_id-1 > qh lastreport+qh REPORTfreq)) {
qh lastreport= qh facet_id-1;
time(&timedata);
tp= localtime(&timedata);
cpu= (float)qh_CPUclock - (float)qh hulltime;
cpu /= (float)qh_SECticks;
total= zzval_(Ztotmerge) - zzval_(Zcyclehorizon) + zzval_(Zcyclefacettot);
zinc_(Zdistio);
qh_distplane(furthest, facet, &dist);
qh_fprintf(qh ferr, 8119, "\n\
At %02d:%02d:%02d & %2.5g CPU secs, qhull has created %d facets and merged %d.\n\
The current hull contains %d facets and %d vertices. There are %d\n\
outside points. Next is point p%d(v%d), %2.2g above f%d.\n",
tp->tm_hour, tp->tm_min, tp->tm_sec, cpu, qh facet_id -1,
total, qh num_facets, qh num_vertices, qh num_outside+1,
furthestid, qh vertex_id, dist, getid_(facet));
}else if (qh IStracing >=1) {
cpu= (float)qh_CPUclock - (float)qh hulltime;
cpu /= (float)qh_SECticks;
qh_distplane(furthest, facet, &dist);
qh_fprintf(qh ferr, 8120, "qh_addpoint: add p%d(v%d) to hull of %d facets(%2.2g above f%d) and %d outside at %4.4g CPU secs. Previous was p%d.\n",
furthestid, qh vertex_id, qh num_facets, dist,
getid_(facet), qh num_outside+1, cpu, qh furthest_id);
}
zmax_(Zvisit2max, (int)qh visit_id/2);
if (qh visit_id > (unsigned) INT_MAX) { /* 31 bits */
zinc_(Zvisit);
qh visit_id= 0;
FORALLfacets
facet->visitid= 0;
}
zmax_(Zvvisit2max, (int)qh vertex_visit/2);
if (qh vertex_visit > (unsigned) INT_MAX) { /* 31 bits */
zinc_(Zvvisit);
qh vertex_visit= 0;
FORALLvertices
vertex->visitid= 0;
}
qh furthest_id= furthestid;
qh RANDOMdist= qh old_randomdist;
} /* buildtracing */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="errexit2">-</a>
qh_errexit2( exitcode, facet, otherfacet )
return exitcode to system after an error
report two facets
returns:
assumes exitcode non-zero
see:
normally use qh_errexit() in user.c(reports a facet and a ridge)
*/
void qh_errexit2(int exitcode, facetT *facet, facetT *otherfacet) {
qh_errprint("ERRONEOUS", facet, otherfacet, NULL, NULL);
qh_errexit(exitcode, NULL, NULL);
} /* errexit2 */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="findhorizon">-</a>
qh_findhorizon( point, facet, goodvisible, goodhorizon )
given a visible facet, find the point's horizon and visible facets
for all facets, !facet-visible
returns:
returns qh.visible_list/num_visible with all visible facets
marks visible facets with ->visible
updates count of good visible and good horizon facets
updates qh.max_outside, qh.max_vertex, facet->maxoutside
see:
similar to qh_delpoint()
design:
move facet to qh.visible_list at end of qh.facet_list
for all visible facets
for each unvisited neighbor of a visible facet
compute distance of point to neighbor
if point above neighbor
move neighbor to end of qh.visible_list
else if point is coplanar with neighbor
update qh.max_outside, qh.max_vertex, neighbor->maxoutside
mark neighbor coplanar (will create a samecycle later)
update horizon statistics
*/
void qh_findhorizon(pointT *point, facetT *facet, int *goodvisible, int *goodhorizon) {
facetT *neighbor, **neighborp, *visible;
int numhorizon= 0, coplanar= 0;
realT dist;
trace1((qh ferr, 1040,"qh_findhorizon: find horizon for point p%d facet f%d\n",qh_pointid(point),facet->id));
*goodvisible= *goodhorizon= 0;
zinc_(Ztotvisible);
qh_removefacet(facet); /* visible_list at end of qh facet_list */
qh_appendfacet(facet);
qh num_visible= 1;
if (facet->good)
(*goodvisible)++;
qh visible_list= facet;
facet->visible= True;
facet->f.replace= NULL;
if (qh IStracing >=4)
qh_errprint("visible", facet, NULL, NULL, NULL);
qh visit_id++;
FORALLvisible_facets {
if (visible->tricoplanar && !qh TRInormals) {
qh_fprintf(qh ferr, 6230, "Qhull internal error (qh_findhorizon): does not work for tricoplanar facets. Use option 'Q11'\n");
qh_errexit(qh_ERRqhull, visible, NULL);
}
visible->visitid= qh visit_id;
FOREACHneighbor_(visible) {
if (neighbor->visitid == qh visit_id)
continue;
neighbor->visitid= qh visit_id;
zzinc_(Znumvisibility);
qh_distplane(point, neighbor, &dist);
if (dist > qh MINvisible) {
zinc_(Ztotvisible);
qh_removefacet(neighbor); /* append to end of qh visible_list */
qh_appendfacet(neighbor);
neighbor->visible= True;
neighbor->f.replace= NULL;
qh num_visible++;
if (neighbor->good)
(*goodvisible)++;
if (qh IStracing >=4)
qh_errprint("visible", neighbor, NULL, NULL, NULL);
}else {
if (dist > - qh MAXcoplanar) {
neighbor->coplanar= True;
zzinc_(Zcoplanarhorizon);
qh_precision("coplanar horizon");
coplanar++;
if (qh MERGING) {
if (dist > 0) {
maximize_(qh max_outside, dist);
maximize_(qh max_vertex, dist);
#if qh_MAXoutside
maximize_(neighbor->maxoutside, dist);
#endif
}else
minimize_(qh min_vertex, dist); /* due to merge later */
}
trace2((qh ferr, 2057, "qh_findhorizon: point p%d is coplanar to horizon f%d, dist=%2.7g < qh MINvisible(%2.7g)\n",
qh_pointid(point), neighbor->id, dist, qh MINvisible));
}else
neighbor->coplanar= False;
zinc_(Ztothorizon);
numhorizon++;
if (neighbor->good)
(*goodhorizon)++;
if (qh IStracing >=4)
qh_errprint("horizon", neighbor, NULL, NULL, NULL);
}
}
}
if (!numhorizon) {
qh_precision("empty horizon");
qh_fprintf(qh ferr, 6168, "qhull precision error (qh_findhorizon): empty horizon\n\
QhullPoint p%d was above all facets.\n", qh_pointid(point));
qh_printfacetlist(qh facet_list, NULL, True);
qh_errexit(qh_ERRprec, NULL, NULL);
}
trace1((qh ferr, 1041, "qh_findhorizon: %d horizon facets(good %d), %d visible(good %d), %d coplanar\n",
numhorizon, *goodhorizon, qh num_visible, *goodvisible, coplanar));
if (qh IStracing >= 4 && qh num_facets < 50)
qh_printlists();
} /* findhorizon */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="nextfurthest">-</a>
qh_nextfurthest( visible )
returns next furthest point and visible facet for qh_addpoint()
starts search at qh.facet_next
returns:
removes furthest point from outside set
NULL if none available
advances qh.facet_next over facets with empty outside sets
design:
for each facet from qh.facet_next
if empty outside set
advance qh.facet_next
else if qh.NARROWhull
determine furthest outside point
if furthest point is not outside
advance qh.facet_next(point will be coplanar)
remove furthest point from outside set
*/
pointT *qh_nextfurthest(facetT **visible) {
facetT *facet;
int size, idx;
realT randr, dist;
pointT *furthest;
while ((facet= qh facet_next) != qh facet_tail) {
if (!facet->outsideset) {
qh facet_next= facet->next;
continue;
}
SETreturnsize_(facet->outsideset, size);
if (!size) {
qh_setfree(&facet->outsideset);
qh facet_next= facet->next;
continue;
}
if (qh NARROWhull) {
if (facet->notfurthest)
qh_furthestout(facet);
furthest= (pointT*)qh_setlast(facet->outsideset);
#if qh_COMPUTEfurthest
qh_distplane(furthest, facet, &dist);
zinc_(Zcomputefurthest);
#else
dist= facet->furthestdist;
#endif
if (dist < qh MINoutside) { /* remainder of outside set is coplanar for qh_outcoplanar */
qh facet_next= facet->next;
continue;
}
}
if (!qh RANDOMoutside && !qh VIRTUALmemory) {
if (qh PICKfurthest) {
qh_furthestnext(/* qh.facet_list */);
facet= qh facet_next;
}
*visible= facet;
return((pointT*)qh_setdellast(facet->outsideset));
}
if (qh RANDOMoutside) {
int outcoplanar = 0;
if (qh NARROWhull) {
FORALLfacets {
if (facet == qh facet_next)
break;
if (facet->outsideset)
outcoplanar += qh_setsize( facet->outsideset);
}
}
randr= qh_RANDOMint;
randr= randr/(qh_RANDOMmax+1);
idx= (int)floor((qh num_outside - outcoplanar) * randr);
FORALLfacet_(qh facet_next) {
if (facet->outsideset) {
SETreturnsize_(facet->outsideset, size);
if (!size)
qh_setfree(&facet->outsideset);
else if (size > idx) {
*visible= facet;
return((pointT*)qh_setdelnth(facet->outsideset, idx));
}else
idx -= size;
}
}
qh_fprintf(qh ferr, 6169, "qhull internal error (qh_nextfurthest): num_outside %d is too low\nby at least %d, or a random real %g >= 1.0\n",
qh num_outside, idx+1, randr);
qh_errexit(qh_ERRqhull, NULL, NULL);
}else { /* VIRTUALmemory */
facet= qh facet_tail->previous;
if (!(furthest= (pointT*)qh_setdellast(facet->outsideset))) {
if (facet->outsideset)
qh_setfree(&facet->outsideset);
qh_removefacet(facet);
qh_prependfacet(facet, &qh facet_list);
continue;
}
*visible= facet;
return furthest;
}
}
return NULL;
} /* nextfurthest */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="partitionall">-</a>
qh_partitionall( vertices, points, numpoints )
partitions all points in points/numpoints to the outsidesets of facets
vertices= vertices in qh.facet_list(!partitioned)
returns:
builds facet->outsideset
does not partition qh.GOODpoint
if qh.ONLYgood && !qh.MERGING,
does not partition qh.GOODvertex
notes:
faster if qh.facet_list sorted by anticipated size of outside set
design:
initialize pointset with all points
remove vertices from pointset
remove qh.GOODpointp from pointset (unless it's qh.STOPcone or qh.STOPpoint)
for all facets
for all remaining points in pointset
compute distance from point to facet
if point is outside facet
remove point from pointset (by not reappending)
update bestpoint
append point or old bestpoint to facet's outside set
append bestpoint to facet's outside set (furthest)
for all points remaining in pointset
partition point into facets' outside sets and coplanar sets
*/
void qh_partitionall(setT *vertices, pointT *points, int numpoints){
setT *pointset;
vertexT *vertex, **vertexp;
pointT *point, **pointp, *bestpoint;
int size, point_i, point_n, point_end, remaining, i, id;
facetT *facet;
realT bestdist= -REALmax, dist, distoutside;
trace1((qh ferr, 1042, "qh_partitionall: partition all points into outside sets\n"));
pointset= qh_settemp(numpoints);
qh num_outside= 0;
pointp= SETaddr_(pointset, pointT);
for (i=numpoints, point= points; i--; point += qh hull_dim)
*(pointp++)= point;
qh_settruncate(pointset, numpoints);
FOREACHvertex_(vertices) {
if ((id= qh_pointid(vertex->point)) >= 0)
SETelem_(pointset, id)= NULL;
}
id= qh_pointid(qh GOODpointp);
if (id >=0 && qh STOPcone-1 != id && -qh STOPpoint-1 != id)
SETelem_(pointset, id)= NULL;
if (qh GOODvertexp && qh ONLYgood && !qh MERGING) { /* matches qhull()*/
if ((id= qh_pointid(qh GOODvertexp)) >= 0)
SETelem_(pointset, id)= NULL;
}
if (!qh BESToutside) { /* matches conditional for qh_partitionpoint below */
distoutside= qh_DISToutside; /* multiple of qh.MINoutside & qh.max_outside, see user.h */
zval_(Ztotpartition)= qh num_points - qh hull_dim - 1; /*misses GOOD... */
remaining= qh num_facets;
point_end= numpoints;
FORALLfacets {
size= point_end/(remaining--) + 100;
facet->outsideset= qh_setnew(size);
bestpoint= NULL;
point_end= 0;
FOREACHpoint_i_(pointset) {
if (point) {
zzinc_(Zpartitionall);
qh_distplane(point, facet, &dist);
if (dist < distoutside)
SETelem_(pointset, point_end++)= point;
else {
qh num_outside++;
if (!bestpoint) {
bestpoint= point;
bestdist= dist;
}else if (dist > bestdist) {
qh_setappend(&facet->outsideset, bestpoint);
bestpoint= point;
bestdist= dist;
}else
qh_setappend(&facet->outsideset, point);
}
}
}
if (bestpoint) {
qh_setappend(&facet->outsideset, bestpoint);
#if !qh_COMPUTEfurthest
facet->furthestdist= bestdist;
#endif
}else
qh_setfree(&facet->outsideset);
qh_settruncate(pointset, point_end);
}
}
/* if !qh BESToutside, pointset contains points not assigned to outsideset */
if (qh BESToutside || qh MERGING || qh KEEPcoplanar || qh KEEPinside) {
qh findbestnew= True;
FOREACHpoint_i_(pointset) {
if (point)
qh_partitionpoint(point, qh facet_list);
}
qh findbestnew= False;
}
zzadd_(Zpartitionall, zzval_(Zpartition));
zzval_(Zpartition)= 0;
qh_settempfree(&pointset);
if (qh IStracing >= 4)
qh_printfacetlist(qh facet_list, NULL, True);
} /* partitionall */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="partitioncoplanar">-</a>
qh_partitioncoplanar( point, facet, dist )
partition coplanar point to a facet
dist is distance from point to facet
if dist NULL,
searches for bestfacet and does nothing if inside
if qh.findbestnew set,
searches new facets instead of using qh_findbest()
returns:
qh.max_ouside updated
if qh.KEEPcoplanar or qh.KEEPinside
point assigned to best coplanarset
notes:
facet->maxoutside is updated at end by qh_check_maxout
design:
if dist undefined
find best facet for point
if point sufficiently below facet (depends on qh.NEARinside and qh.KEEPinside)
exit
if keeping coplanar/nearinside/inside points
if point is above furthest coplanar point
append point to coplanar set (it is the new furthest)
update qh.max_outside
else
append point one before end of coplanar set
else if point is clearly outside of qh.max_outside and bestfacet->coplanarset
and bestfacet is more than perpendicular to facet
repartition the point using qh_findbest() -- it may be put on an outsideset
else
update qh.max_outside
*/
void qh_partitioncoplanar(pointT *point, facetT *facet, realT *dist) {
facetT *bestfacet;
pointT *oldfurthest;
realT bestdist, dist2= 0, angle;
int numpart= 0, oldfindbest;
boolT isoutside;
qh WAScoplanar= True;
if (!dist) {
if (qh findbestnew)
bestfacet= qh_findbestnew(point, facet, &bestdist, qh_ALL, &isoutside, &numpart);
else
bestfacet= qh_findbest(point, facet, qh_ALL, !qh_ISnewfacets, qh DELAUNAY,
&bestdist, &isoutside, &numpart);
zinc_(Ztotpartcoplanar);
zzadd_(Zpartcoplanar, numpart);
if (!qh DELAUNAY && !qh KEEPinside) { /* for 'd', bestdist skips upperDelaunay facets */
if (qh KEEPnearinside) {
if (bestdist < -qh NEARinside) {
zinc_(Zcoplanarinside);
trace4((qh ferr, 4062, "qh_partitioncoplanar: point p%d is more than near-inside facet f%d dist %2.2g findbestnew %d\n",
qh_pointid(point), bestfacet->id, bestdist, qh findbestnew));
return;
}
}else if (bestdist < -qh MAXcoplanar) {
trace4((qh ferr, 4063, "qh_partitioncoplanar: point p%d is inside facet f%d dist %2.2g findbestnew %d\n",
qh_pointid(point), bestfacet->id, bestdist, qh findbestnew));
zinc_(Zcoplanarinside);
return;
}
}
}else {
bestfacet= facet;
bestdist= *dist;
}
if (bestdist > qh max_outside) {
if (!dist && facet != bestfacet) {
zinc_(Zpartangle);
angle= qh_getangle(facet->normal, bestfacet->normal);
if (angle < 0) {
/* typically due to deleted vertex and coplanar facets, e.g.,
RBOX 1000 s Z1 G1e-13 t1001185205 | QHULL Tv */
zinc_(Zpartflip);
trace2((qh ferr, 2058, "qh_partitioncoplanar: repartition point p%d from f%d. It is above flipped facet f%d dist %2.2g\n",
qh_pointid(point), facet->id, bestfacet->id, bestdist));
oldfindbest= qh findbestnew;
qh findbestnew= False;
qh_partitionpoint(point, bestfacet);
qh findbestnew= oldfindbest;
return;
}
}
qh max_outside= bestdist;
if (bestdist > qh TRACEdist) {
qh_fprintf(qh ferr, 8122, "qh_partitioncoplanar: ====== p%d from f%d increases max_outside to %2.2g of f%d last p%d\n",
qh_pointid(point), facet->id, bestdist, bestfacet->id, qh furthest_id);
qh_errprint("DISTANT", facet, bestfacet, NULL, NULL);
}
}
if (qh KEEPcoplanar + qh KEEPinside + qh KEEPnearinside) {
oldfurthest= (pointT*)qh_setlast(bestfacet->coplanarset);
if (oldfurthest) {
zinc_(Zcomputefurthest);
qh_distplane(oldfurthest, bestfacet, &dist2);
}
if (!oldfurthest || dist2 < bestdist)
qh_setappend(&bestfacet->coplanarset, point);
else
qh_setappend2ndlast(&bestfacet->coplanarset, point);
}
trace4((qh ferr, 4064, "qh_partitioncoplanar: point p%d is coplanar with facet f%d(or inside) dist %2.2g\n",
qh_pointid(point), bestfacet->id, bestdist));
} /* partitioncoplanar */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="partitionpoint">-</a>
qh_partitionpoint( point, facet )
assigns point to an outside set, coplanar set, or inside set (i.e., dropt)
if qh.findbestnew
uses qh_findbestnew() to search all new facets
else
uses qh_findbest()
notes:
after qh_distplane(), this and qh_findbest() are most expensive in 3-d
design:
find best facet for point
(either exhaustive search of new facets or directed search from facet)
if qh.NARROWhull
retain coplanar and nearinside points as outside points
if point is outside bestfacet
if point above furthest point for bestfacet
append point to outside set (it becomes the new furthest)
if outside set was empty
move bestfacet to end of qh.facet_list (i.e., after qh.facet_next)
update bestfacet->furthestdist
else
append point one before end of outside set
else if point is coplanar to bestfacet
if keeping coplanar points or need to update qh.max_outside
partition coplanar point into bestfacet
else if near-inside point
partition as coplanar point into bestfacet
else is an inside point
if keeping inside points
partition as coplanar point into bestfacet
*/
void qh_partitionpoint(pointT *point, facetT *facet) {
realT bestdist;
boolT isoutside;
facetT *bestfacet;
int numpart;
#if qh_COMPUTEfurthest
realT dist;
#endif
if (qh findbestnew)
bestfacet= qh_findbestnew(point, facet, &bestdist, qh BESToutside, &isoutside, &numpart);
else
bestfacet= qh_findbest(point, facet, qh BESToutside, qh_ISnewfacets, !qh_NOupper,
&bestdist, &isoutside, &numpart);
zinc_(Ztotpartition);
zzadd_(Zpartition, numpart);
if (qh NARROWhull) {
if (qh DELAUNAY && !isoutside && bestdist >= -qh MAXcoplanar)
qh_precision("nearly incident point(narrow hull)");
if (qh KEEPnearinside) {
if (bestdist >= -qh NEARinside)
isoutside= True;
}else if (bestdist >= -qh MAXcoplanar)
isoutside= True;
}
if (isoutside) {
if (!bestfacet->outsideset
|| !qh_setlast(bestfacet->outsideset)) {
qh_setappend(&(bestfacet->outsideset), point);
if (!bestfacet->newfacet) {
qh_removefacet(bestfacet); /* make sure it's after qh facet_next */
qh_appendfacet(bestfacet);
}
#if !qh_COMPUTEfurthest
bestfacet->furthestdist= bestdist;
#endif
}else {
#if qh_COMPUTEfurthest
zinc_(Zcomputefurthest);
qh_distplane(oldfurthest, bestfacet, &dist);
if (dist < bestdist)
qh_setappend(&(bestfacet->outsideset), point);
else
qh_setappend2ndlast(&(bestfacet->outsideset), point);
#else
if (bestfacet->furthestdist < bestdist) {
qh_setappend(&(bestfacet->outsideset), point);
bestfacet->furthestdist= bestdist;
}else
qh_setappend2ndlast(&(bestfacet->outsideset), point);
#endif
}
qh num_outside++;
trace4((qh ferr, 4065, "qh_partitionpoint: point p%d is outside facet f%d new? %d (or narrowhull)\n",
qh_pointid(point), bestfacet->id, bestfacet->newfacet));
}else if (qh DELAUNAY || bestdist >= -qh MAXcoplanar) { /* for 'd', bestdist skips upperDelaunay facets */
zzinc_(Zcoplanarpart);
if (qh DELAUNAY)
qh_precision("nearly incident point");
if ((qh KEEPcoplanar + qh KEEPnearinside) || bestdist > qh max_outside)
qh_partitioncoplanar(point, bestfacet, &bestdist);
else {
trace4((qh ferr, 4066, "qh_partitionpoint: point p%d is coplanar to facet f%d (dropped)\n",
qh_pointid(point), bestfacet->id));
}
}else if (qh KEEPnearinside && bestdist > -qh NEARinside) {
zinc_(Zpartnear);
qh_partitioncoplanar(point, bestfacet, &bestdist);
}else {
zinc_(Zpartinside);
trace4((qh ferr, 4067, "qh_partitionpoint: point p%d is inside all facets, closest to f%d dist %2.2g\n",
qh_pointid(point), bestfacet->id, bestdist));
if (qh KEEPinside)
qh_partitioncoplanar(point, bestfacet, &bestdist);
}
} /* partitionpoint */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="partitionvisible">-</a>
qh_partitionvisible( allpoints, numoutside )
partitions points in visible facets to qh.newfacet_list
qh.visible_list= visible facets
for visible facets
1st neighbor (if any) points to a horizon facet or a new facet
if allpoints(!used),
repartitions coplanar points
returns:
updates outside sets and coplanar sets of qh.newfacet_list
updates qh.num_outside (count of outside points)
notes:
qh.findbest_notsharp should be clear (extra work if set)
design:
for all visible facets with outside set or coplanar set
select a newfacet for visible facet
if outside set
partition outside set into new facets
if coplanar set and keeping coplanar/near-inside/inside points
if allpoints
partition coplanar set into new facets, may be assigned outside
else
partition coplanar set into coplanar sets of new facets
for each deleted vertex
if allpoints
partition vertex into new facets, may be assigned outside
else
partition vertex into coplanar sets of new facets
*/
void qh_partitionvisible(/*qh.visible_list*/ boolT allpoints, int *numoutside) {
facetT *visible, *newfacet;
pointT *point, **pointp;
int coplanar=0, size;
unsigned count;
vertexT *vertex, **vertexp;
if (qh ONLYmax)
maximize_(qh MINoutside, qh max_vertex);
*numoutside= 0;
FORALLvisible_facets {
if (!visible->outsideset && !visible->coplanarset)
continue;
newfacet= visible->f.replace;
count= 0;
while (newfacet && newfacet->visible) {
newfacet= newfacet->f.replace;
if (count++ > qh facet_id)
qh_infiniteloop(visible);
}
if (!newfacet)
newfacet= qh newfacet_list;
if (newfacet == qh facet_tail) {
qh_fprintf(qh ferr, 6170, "qhull precision error (qh_partitionvisible): all new facets deleted as\n degenerate facets. Can not continue.\n");
qh_errexit(qh_ERRprec, NULL, NULL);
}
if (visible->outsideset) {
size= qh_setsize(visible->outsideset);
*numoutside += size;
qh num_outside -= size;
FOREACHpoint_(visible->outsideset)
qh_partitionpoint(point, newfacet);
}
if (visible->coplanarset && (qh KEEPcoplanar + qh KEEPinside + qh KEEPnearinside)) {
size= qh_setsize(visible->coplanarset);
coplanar += size;
FOREACHpoint_(visible->coplanarset) {
if (allpoints) /* not used */
qh_partitionpoint(point, newfacet);
else
qh_partitioncoplanar(point, newfacet, NULL);
}
}
}
FOREACHvertex_(qh del_vertices) {
if (vertex->point) {
if (allpoints) /* not used */
qh_partitionpoint(vertex->point, qh newfacet_list);
else
qh_partitioncoplanar(vertex->point, qh newfacet_list, NULL);
}
}
trace1((qh ferr, 1043,"qh_partitionvisible: partitioned %d points from outsidesets and %d points from coplanarsets\n", *numoutside, coplanar));
} /* partitionvisible */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="precision">-</a>
qh_precision( reason )
restart on precision errors if not merging and if 'QJn'
*/
void qh_precision(const char *reason) {
if (qh ALLOWrestart && !qh PREmerge && !qh MERGEexact) {
if (qh JOGGLEmax < REALmax/2) {
trace0((qh ferr, 26, "qh_precision: qhull restart because of %s\n", reason));
/* May be called repeatedly if qh->ALLOWrestart */
longjmp(qh restartexit, qh_ERRprec);
}
}
} /* qh_precision */
/*-<a href="qh-qhull.htm#TOC"
>-------------------------------</a><a name="printsummary">-</a>
qh_printsummary( fp )
prints summary to fp
notes:
not in io.c so that user_eg.c can prevent io.c from loading
qh_printsummary and qh_countfacets must match counts
design:
determine number of points, vertices, and coplanar points
print summary
*/
void qh_printsummary(FILE *fp) {
realT ratio, outerplane, innerplane;
float cpu;
int size, id, nummerged, numvertices, numcoplanars= 0, nonsimplicial=0;
int goodused;
facetT *facet;
const char *s;
int numdel= zzval_(Zdelvertextot);
int numtricoplanars= 0;
size= qh num_points + qh_setsize(qh other_points);
numvertices= qh num_vertices - qh_setsize(qh del_vertices);
id= qh_pointid(qh GOODpointp);
FORALLfacets {
if (facet->coplanarset)
numcoplanars += qh_setsize( facet->coplanarset);
if (facet->good) {
if (facet->simplicial) {
if (facet->keepcentrum && facet->tricoplanar)
numtricoplanars++;
}else if (qh_setsize(facet->vertices) != qh hull_dim)
nonsimplicial++;
}
}
if (id >=0 && qh STOPcone-1 != id && -qh STOPpoint-1 != id)
size--;
if (qh STOPcone || qh STOPpoint)
qh_fprintf(fp, 9288, "\nAt a premature exit due to 'TVn', 'TCn', 'TRn', or precision error with 'QJn'.");
if (qh UPPERdelaunay)
goodused= qh GOODvertex + qh GOODpoint + qh SPLITthresholds;
else if (qh DELAUNAY)
goodused= qh GOODvertex + qh GOODpoint + qh GOODthreshold;
else
goodused= qh num_good;
nummerged= zzval_(Ztotmerge) - zzval_(Zcyclehorizon) + zzval_(Zcyclefacettot);
if (qh VORONOI) {
if (qh UPPERdelaunay)
qh_fprintf(fp, 9289, "\n\
Furthest-site Voronoi vertices by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
else
qh_fprintf(fp, 9290, "\n\
Voronoi diagram by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
qh_fprintf(fp, 9291, " Number of Voronoi regions%s: %d\n",
qh ATinfinity ? " and at-infinity" : "", numvertices);
if (numdel)
qh_fprintf(fp, 9292, " Total number of deleted points due to merging: %d\n", numdel);
if (numcoplanars - numdel > 0)
qh_fprintf(fp, 9293, " Number of nearly incident points: %d\n", numcoplanars - numdel);
else if (size - numvertices - numdel > 0)
qh_fprintf(fp, 9294, " Total number of nearly incident points: %d\n", size - numvertices - numdel);
qh_fprintf(fp, 9295, " Number of%s Voronoi vertices: %d\n",
goodused ? " 'good'" : "", qh num_good);
if (nonsimplicial)
qh_fprintf(fp, 9296, " Number of%s non-simplicial Voronoi vertices: %d\n",
goodused ? " 'good'" : "", nonsimplicial);
}else if (qh DELAUNAY) {
if (qh UPPERdelaunay)
qh_fprintf(fp, 9297, "\n\
Furthest-site Delaunay triangulation by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
else
qh_fprintf(fp, 9298, "\n\
Delaunay triangulation by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
qh_fprintf(fp, 9299, " Number of input sites%s: %d\n",
qh ATinfinity ? " and at-infinity" : "", numvertices);
if (numdel)
qh_fprintf(fp, 9300, " Total number of deleted points due to merging: %d\n", numdel);
if (numcoplanars - numdel > 0)
qh_fprintf(fp, 9301, " Number of nearly incident points: %d\n", numcoplanars - numdel);
else if (size - numvertices - numdel > 0)
qh_fprintf(fp, 9302, " Total number of nearly incident points: %d\n", size - numvertices - numdel);
qh_fprintf(fp, 9303, " Number of%s Delaunay regions: %d\n",
goodused ? " 'good'" : "", qh num_good);
if (nonsimplicial)
qh_fprintf(fp, 9304, " Number of%s non-simplicial Delaunay regions: %d\n",
goodused ? " 'good'" : "", nonsimplicial);
}else if (qh HALFspace) {
qh_fprintf(fp, 9305, "\n\
Halfspace intersection by the convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
qh_fprintf(fp, 9306, " Number of halfspaces: %d\n", size);
qh_fprintf(fp, 9307, " Number of non-redundant halfspaces: %d\n", numvertices);
if (numcoplanars) {
if (qh KEEPinside && qh KEEPcoplanar)
s= "similar and redundant";
else if (qh KEEPinside)
s= "redundant";
else
s= "similar";
qh_fprintf(fp, 9308, " Number of %s halfspaces: %d\n", s, numcoplanars);
}
qh_fprintf(fp, 9309, " Number of intersection points: %d\n", qh num_facets - qh num_visible);
if (goodused)
qh_fprintf(fp, 9310, " Number of 'good' intersection points: %d\n", qh num_good);
if (nonsimplicial)
qh_fprintf(fp, 9311, " Number of%s non-simplicial intersection points: %d\n",
goodused ? " 'good'" : "", nonsimplicial);
}else {
qh_fprintf(fp, 9312, "\n\
Convex hull of %d points in %d-d:\n\n", size, qh hull_dim);
qh_fprintf(fp, 9313, " Number of vertices: %d\n", numvertices);
if (numcoplanars) {
if (qh KEEPinside && qh KEEPcoplanar)
s= "coplanar and interior";
else if (qh KEEPinside)
s= "interior";
else
s= "coplanar";
qh_fprintf(fp, 9314, " Number of %s points: %d\n", s, numcoplanars);
}
qh_fprintf(fp, 9315, " Number of facets: %d\n", qh num_facets - qh num_visible);
if (goodused)
qh_fprintf(fp, 9316, " Number of 'good' facets: %d\n", qh num_good);
if (nonsimplicial)
qh_fprintf(fp, 9317, " Number of%s non-simplicial facets: %d\n",
goodused ? " 'good'" : "", nonsimplicial);
}
if (numtricoplanars)
qh_fprintf(fp, 9318, " Number of triangulated facets: %d\n", numtricoplanars);
qh_fprintf(fp, 9319, "\nStatistics for: %s | %s",
qh rbox_command, qh qhull_command);
if (qh ROTATErandom != INT_MIN)
qh_fprintf(fp, 9320, " QR%d\n\n", qh ROTATErandom);
else
qh_fprintf(fp, 9321, "\n\n");
qh_fprintf(fp, 9322, " Number of points processed: %d\n", zzval_(Zprocessed));
qh_fprintf(fp, 9323, " Number of hyperplanes created: %d\n", zzval_(Zsetplane));
if (qh DELAUNAY)
qh_fprintf(fp, 9324, " Number of facets in hull: %d\n", qh num_facets - qh num_visible);
qh_fprintf(fp, 9325, " Number of distance tests for qhull: %d\n", zzval_(Zpartition)+
zzval_(Zpartitionall)+zzval_(Znumvisibility)+zzval_(Zpartcoplanar));
#if 0 /* NOTE: must print before printstatistics() */
{realT stddev, ave;
qh_fprintf(fp, 9326, " average new facet balance: %2.2g\n",
wval_(Wnewbalance)/zval_(Zprocessed));
stddev= qh_stddev(zval_(Zprocessed), wval_(Wnewbalance),
wval_(Wnewbalance2), &ave);
qh_fprintf(fp, 9327, " new facet standard deviation: %2.2g\n", stddev);
qh_fprintf(fp, 9328, " average partition balance: %2.2g\n",
wval_(Wpbalance)/zval_(Zpbalance));
stddev= qh_stddev(zval_(Zpbalance), wval_(Wpbalance),
wval_(Wpbalance2), &ave);
qh_fprintf(fp, 9329, " partition standard deviation: %2.2g\n", stddev);
}
#endif
if (nummerged) {
qh_fprintf(fp, 9330," Number of distance tests for merging: %d\n",zzval_(Zbestdist)+
zzval_(Zcentrumtests)+zzval_(Zdistconvex)+zzval_(Zdistcheck)+
zzval_(Zdistzero));
qh_fprintf(fp, 9331," Number of distance tests for checking: %d\n",zzval_(Zcheckpart));
qh_fprintf(fp, 9332," Number of merged facets: %d\n", nummerged);
}
if (!qh RANDOMoutside && qh QHULLfinished) {
cpu= (float)qh hulltime;
cpu /= (float)qh_SECticks;
wval_(Wcpu)= cpu;
qh_fprintf(fp, 9333, " CPU seconds to compute hull (after input): %2.4g\n", cpu);
}
if (qh RERUN) {
if (!qh PREmerge && !qh MERGEexact)
qh_fprintf(fp, 9334, " Percentage of runs with precision errors: %4.1f\n",
zzval_(Zretry)*100.0/qh build_cnt); /* careful of order */
}else if (qh JOGGLEmax < REALmax/2) {
if (zzval_(Zretry))
qh_fprintf(fp, 9335, " After %d retries, input joggled by: %2.2g\n",
zzval_(Zretry), qh JOGGLEmax);
else
qh_fprintf(fp, 9336, " Input joggled by: %2.2g\n", qh JOGGLEmax);
}
if (qh totarea != 0.0)
qh_fprintf(fp, 9337, " %s facet area: %2.8g\n",
zzval_(Ztotmerge) ? "Approximate" : "Total", qh totarea);
if (qh totvol != 0.0)
qh_fprintf(fp, 9338, " %s volume: %2.8g\n",
zzval_(Ztotmerge) ? "Approximate" : "Total", qh totvol);
if (qh MERGING) {
qh_outerinner(NULL, &outerplane, &innerplane);
if (outerplane > 2 * qh DISTround) {
qh_fprintf(fp, 9339, " Maximum distance of %spoint above facet: %2.2g",
(qh QHULLfinished ? "" : "merged "), outerplane);
ratio= outerplane/(qh ONEmerge + qh DISTround);
/* don't report ratio if MINoutside is large */
if (ratio > 0.05 && 2* qh ONEmerge > qh MINoutside && qh JOGGLEmax > REALmax/2)
qh_fprintf(fp, 9340, " (%.1fx)\n", ratio);
else
qh_fprintf(fp, 9341, "\n");
}
if (innerplane < -2 * qh DISTround) {
qh_fprintf(fp, 9342, " Maximum distance of %svertex below facet: %2.2g",
(qh QHULLfinished ? "" : "merged "), innerplane);
ratio= -innerplane/(qh ONEmerge+qh DISTround);
if (ratio > 0.05 && qh JOGGLEmax > REALmax/2)
qh_fprintf(fp, 9343, " (%.1fx)\n", ratio);
else
qh_fprintf(fp, 9344, "\n");
}
}
qh_fprintf(fp, 9345, "\n");
} /* printsummary */
| spirit-code/spirit | thirdparty/qhull/src/libqhull/libqhull.c | C | mit | 51,960 |
package gueei.binding;
import java.util.Collection;
import java.util.ArrayList;
public abstract class DependentObservable<T> extends Observable<T> implements Observer{
protected IObservable<?>[] mDependents;
public DependentObservable(Class<T> type, IObservable<?>... dependents) {
super(type);
for(IObservable<?> o : dependents){
o.subscribe(this);
}
this.mDependents = dependents;
this.onPropertyChanged(null, new ArrayList<Object>());
}
// This is provided in case the constructor can't be used.
// Not intended for normal usage
public void addDependents(IObservable<?>... dependents){
IObservable<?>[] temp = mDependents;
mDependents = new IObservable<?>[temp.length + dependents.length];
int len = temp.length;
for(int i=0; i<len; i++){
mDependents[i] = temp[i];
}
int len2 = dependents.length;
for(int i=0; i<len2; i++){
mDependents[i+len] = dependents[i];
dependents[i].subscribe(this);
}
this.onPropertyChanged(null, new ArrayList<Object>());
}
public abstract T calculateValue(Object... args) throws Exception;
public final void onPropertyChanged(IObservable<?> prop,
Collection<Object> initiators) {
dirty = true;
initiators.add(this);
this.notifyChanged(initiators);
}
private boolean dirty = false;
@Override
public T get() {
if (dirty){
int len = mDependents.length;
Object[] values = new Object[len];
for(int i=0; i<len; i++){
values[i] = mDependents[i].get();
}
try{
T value = this.calculateValue(values);
this.setWithoutNotify(value);
}catch(Exception e){
BindingLog.exception
("DependentObservable.CalculateValue()", e);
}
dirty = false;
}
return super.get();
}
public boolean isDirty() {
return dirty;
}
public void setDirty(boolean dirty) {
this.dirty = dirty;
}
} | yangqiang1223/AndroidBinding | Core/AndroidBinding/src/gueei/binding/DependentObservable.java | Java | mit | 1,894 |
error() {
echo " ! $*" >&2
exit 1
}
status() {
echo "-----> $*"
}
protip() {
echo
echo "PRO TIP: $*" | indent
echo "See https://devcenter.heroku.com/articles/nodejs-support" | indent
echo
}
# sed -l basically makes sed replace and buffer through stdin to stdout
# so you get updates while the command runs and dont wait for the end
# e.g. npm install | indent
indent() {
c='s/^/ /'
case $(uname) in
Darwin) sed -l "$c";; # mac/bsd sed: -l buffers on line boundaries
*) sed -u "$c";; # unix/gnu sed: -u unbuffered (arbitrary) chunks of data
esac
}
cat_npm_debug_log() {
test -f $build_dir/npm-debug.log && cat $build_dir/npm-debug.log
}
unique_array() {
echo "$*" | tr ' ' '\n' | sort -u | tr '\n' ' '
}
init_log_plex() {
for log_file in $*; do
echo "mkdir -p `dirname ${log_file}`"
done
for log_file in $*; do
echo "touch ${log_file}"
done
}
tail_log_plex() {
for log_file in $*; do
echo "tail -n 0 -qF --pid=\$\$ ${log_file} &"
done
}
# Show script name and line number when errors occur to make buildpack errors easier to debug
trap 'error "Script error in $0 on or near line ${LINENO}"' ERR
| penciu/apache | bin/common.sh | Shell | mit | 1,173 |
var expect = require('chai').expect;
var runner = require('../runner');
describe('nasm runner', function() {
describe('.run', function() {
it('should handle basic code evaluation (no libc)', function(done) {
runner.run({
language: 'nasm',
code: [
' global _start',
' section .text',
'_start:',
' mov rax, 1',
' mov rdi, 1',
' mov rsi, message',
' mov rdx, 25',
' syscall',
' mov eax, 60',
' xor rdi, rdi',
' syscall',
'message:',
'db "Hello, Netwide Assembler!", 25'
].join('\n')
}, function(buffer) {
expect(buffer.stdout).to.equal('Hello, Netwide Assembler!');
done();
});
});
it('should handle basic code evaluation (with libc)', function(done) {
runner.run({
language: 'nasm',
code: [
' global main',
' extern puts',
' section .text',
'main:',
' mov rdi, message',
' call puts',
' ret',
'message:',
'db "Netwide Assembler together with LIBC! Let\'s Port Codewars From Rails to THIS! \\m/", 0'
].join('\n')
}, function(buffer) {
expect(buffer.stdout).to.equal('Netwide Assembler together with LIBC! Let\'s Port Codewars From Rails to THIS! \\m/\n');
done();
});
});
});
});
| Codewars/codewars-runner | test/runners/nasm_spec.js | JavaScript | mit | 1,513 |
<!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=US-ASCII">
<title>Class template time_duration</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../date_time/doxy.html#header.boost.date_time.time_duration_hpp" title="Header <boost/date_time/time_duration.hpp>">
<link rel="prev" href="second_clock.html" title="Class template second_clock">
<link rel="next" href="subsecond_duration.html" title="Class template subsecond_duration">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="second_clock.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../date_time/doxy.html#header.boost.date_time.time_duration_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="subsecond_duration.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.date_time.time_duration"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Class template time_duration</span></h2>
<p>boost::date_time::time_duration — Represents some amount of elapsed time measure to a given resolution. </p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../date_time/doxy.html#header.boost.date_time.time_duration_hpp" title="Header <boost/date_time/time_duration.hpp>">boost/date_time/time_duration.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> T<span class="special">,</span> <span class="keyword">typename</span> rep_type<span class="special">></span>
<span class="keyword">class</span> <a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a> <span class="special">:</span>
<span class="keyword">private</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">less_than_comparable</span><span class="special"><</span> <span class="identifier">T</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">equality_comparable</span><span class="special"><</span> <span class="identifier">T</span> <span class="special">></span> <span class="special">></span>
<span class="special">{</span>
<span class="keyword">public</span><span class="special">:</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="keyword">void</span> <a name="boost.date_time.time_duration.is__1_3_14_15_3_47_1_1_1_5"></a><span class="identifier">_is_boost_date_time_duration</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">T</span> <a name="boost.date_time.time_duration.duration_type"></a><span class="identifier">duration_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">rep_type</span> <a name="boost.date_time.time_duration.traits_type"></a><span class="identifier">traits_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">rep_type</span><span class="special">::</span><span class="identifier">day_type</span> <a name="boost.date_time.time_duration.day_type"></a><span class="identifier">day_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">rep_type</span><span class="special">::</span><span class="identifier">hour_type</span> <a name="boost.date_time.time_duration.hour_type"></a><span class="identifier">hour_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">rep_type</span><span class="special">::</span><span class="identifier">min_type</span> <a name="boost.date_time.time_duration.min_type"></a><span class="identifier">min_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">rep_type</span><span class="special">::</span><span class="identifier">sec_type</span> <a name="boost.date_time.time_duration.sec_type"></a><span class="identifier">sec_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">rep_type</span><span class="special">::</span><span class="identifier">fractional_seconds_type</span> <a name="boost.date_time.time_duration.fractional_seconds_type"></a><span class="identifier">fractional_seconds_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">rep_type</span><span class="special">::</span><span class="identifier">tick_type</span> <a name="boost.date_time.time_duration.tick_type"></a><span class="identifier">tick_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">rep_type</span><span class="special">::</span><span class="identifier">impl_type</span> <a name="boost.date_time.time_duration.impl_type"></a><span class="identifier">impl_type</span><span class="special">;</span>
<span class="comment">// <a class="link" href="time_duration.html#boost.date_time.time_durationconstruct-copy-destruct">construct/copy/destruct</a></span>
<a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_16-bb"><span class="identifier">time_duration</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_17-bb"><span class="identifier">time_duration</span></a><span class="special">(</span><span class="identifier">hour_type</span><span class="special">,</span> <span class="identifier">min_type</span><span class="special">,</span> <span class="identifier">sec_type</span> <span class="special">=</span> <span class="number">0</span><span class="special">,</span>
<span class="identifier">fractional_seconds_type</span> <span class="special">=</span> <span class="number">0</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_18-bb"><span class="identifier">time_duration</span></a><span class="special">(</span><span class="keyword">const</span> <a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a><span class="special"><</span> <span class="identifier">T</span><span class="special">,</span> <span class="identifier">rep_type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_19-bb"><span class="identifier">time_duration</span></a><span class="special">(</span><span class="identifier">special_values</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">explicit</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_22-bb"><span class="identifier">time_duration</span></a><span class="special">(</span><span class="identifier">impl_type</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15-bb">public member functions</a></span>
<span class="identifier">hour_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_1-bb"><span class="identifier">hours</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">min_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_2-bb"><span class="identifier">minutes</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">sec_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_3-bb"><span class="identifier">seconds</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">sec_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_4-bb"><span class="identifier">total_seconds</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">tick_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_5-bb"><span class="identifier">total_milliseconds</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">tick_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_6-bb"><span class="identifier">total_nanoseconds</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">tick_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_7-bb"><span class="identifier">total_microseconds</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">fractional_seconds_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_8-bb"><span class="identifier">fractional_seconds</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_9-bb"><span class="identifier">invert_sign</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_10-bb"><span class="identifier">is_negative</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_11-bb"><span class="keyword">operator</span><span class="special"><</span></a><span class="special">(</span><span class="keyword">const</span> <a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_12-bb"><span class="keyword">operator</span><span class="special">==</span></a><span class="special">(</span><span class="keyword">const</span> <a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_13-bb"><span class="keyword">operator</span><span class="special">-</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_14-bb"><span class="keyword">operator</span><span class="special">-</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_15-bb"><span class="keyword">operator</span><span class="special">+</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_16-bb"><span class="keyword">operator</span><span class="special">/</span></a><span class="special">(</span><span class="keyword">int</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_17-bb"><span class="keyword">operator</span><span class="special">-=</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_18-bb"><span class="keyword">operator</span><span class="special">+=</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_19-bb"><span class="keyword">operator</span><span class="special">/=</span></a><span class="special">(</span><span class="keyword">int</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_20-bb"><span class="keyword">operator</span><span class="special">*</span></a><span class="special">(</span><span class="keyword">int</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_21-bb"><span class="keyword">operator</span><span class="special">*=</span></a><span class="special">(</span><span class="keyword">int</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">tick_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_22-bb"><span class="identifier">ticks</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_23-bb"><span class="identifier">is_special</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_24-bb"><span class="identifier">is_pos_infinity</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_25-bb"><span class="identifier">is_neg_infinity</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_26-bb"><span class="identifier">is_not_a_date_time</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">impl_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_15_27-bb"><span class="identifier">get_rep</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="comment">// <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_20-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="identifier">duration_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_20_1-bb"><span class="identifier">unit</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">tick_type</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_20_2-bb"><span class="identifier">ticks_per_second</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">time_resolutions</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_20_3-bb"><span class="identifier">resolution</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">unsigned</span> <span class="keyword">short</span> <a class="link" href="time_duration.html#id-1_3_14_15_3_47_1_1_1_20_4-bb"><span class="identifier">num_fractional_digits</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="id-1.3.14.15.3.46.3.4"></a><h2>Description</h2>
<p>This class represents a standard set of capabilities for all counted time durations. Time duration implementations should derive from this class passing their type as the first template parameter. This design allows the subclass duration types to provide custom construction policies or other custom features not provided here.</p>
<p>
</p>
<div class="refsect2">
<a name="id-1.3.14.15.3.46.3.4.4"></a><h3>
<a name="boost.date_time.time_durationconstruct-copy-destruct"></a><code class="computeroutput">time_duration</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><a name="id-1_3_14_15_3_47_1_1_1_16-bb"></a><span class="identifier">time_duration</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><a name="id-1_3_14_15_3_47_1_1_1_17-bb"></a><span class="identifier">time_duration</span><span class="special">(</span><span class="identifier">hour_type</span> hours_in<span class="special">,</span> <span class="identifier">min_type</span> minutes_in<span class="special">,</span>
<span class="identifier">sec_type</span> seconds_in <span class="special">=</span> <span class="number">0</span><span class="special">,</span>
<span class="identifier">fractional_seconds_type</span> frac_sec_in <span class="special">=</span> <span class="number">0</span><span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem">
<pre class="literallayout"><a name="id-1_3_14_15_3_47_1_1_1_18-bb"></a><span class="identifier">time_duration</span><span class="special">(</span><span class="keyword">const</span> <a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a><span class="special"><</span> <span class="identifier">T</span><span class="special">,</span> <span class="identifier">rep_type</span> <span class="special">></span> <span class="special">&</span> other<span class="special">)</span><span class="special">;</span></pre>Construct from another <code class="computeroutput"><a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a></code> (Copy constructor) </li>
<li class="listitem">
<pre class="literallayout"><a name="id-1_3_14_15_3_47_1_1_1_19-bb"></a><span class="identifier">time_duration</span><span class="special">(</span><span class="identifier">special_values</span> sv<span class="special">)</span><span class="special">;</span></pre>Construct from special_values. </li>
<li class="listitem"><pre class="literallayout"><span class="keyword">explicit</span> <a name="id-1_3_14_15_3_47_1_1_1_22-bb"></a><span class="identifier">time_duration</span><span class="special">(</span><span class="identifier">impl_type</span> in<span class="special">)</span><span class="special">;</span></pre></li>
</ol></div>
</div>
<div class="refsect2">
<a name="id-1.3.14.15.3.46.3.4.5"></a><h3>
<a name="id-1_3_14_15_3_47_1_1_1_15-bb"></a><code class="computeroutput">time_duration</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><span class="identifier">hour_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_1-bb"></a><span class="identifier">hours</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Returns number of hours in the duration. </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">min_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_2-bb"></a><span class="identifier">minutes</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Returns normalized number of minutes. </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">sec_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_3-bb"></a><span class="identifier">seconds</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Returns normalized number of seconds (0..60) </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">sec_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_4-bb"></a><span class="identifier">total_seconds</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Returns total number of seconds truncating any fractional seconds. </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">tick_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_5-bb"></a><span class="identifier">total_milliseconds</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Returns total number of milliseconds truncating any fractional seconds. </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">tick_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_6-bb"></a><span class="identifier">total_nanoseconds</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Returns total number of nanoseconds truncating any sub millisecond values. </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">tick_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_7-bb"></a><span class="identifier">total_microseconds</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Returns total number of microseconds truncating any sub microsecond values. </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">fractional_seconds_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_8-bb"></a><span class="identifier">fractional_seconds</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Returns count of fractional seconds at given resolution. </li>
<li class="listitem"><pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_9-bb"></a><span class="identifier">invert_sign</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">bool</span> <a name="id-1_3_14_15_3_47_1_1_1_15_10-bb"></a><span class="identifier">is_negative</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">bool</span> <a name="id-1_3_14_15_3_47_1_1_1_15_11-bb"></a><span class="keyword">operator</span><span class="special"><</span><span class="special">(</span><span class="keyword">const</span> <a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a> <span class="special">&</span> rhs<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">bool</span> <a name="id-1_3_14_15_3_47_1_1_1_15_12-bb"></a><span class="keyword">operator</span><span class="special">==</span><span class="special">(</span><span class="keyword">const</span> <a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a> <span class="special">&</span> rhs<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_13-bb"></a><span class="keyword">operator</span><span class="special">-</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>unary- Allows for <code class="computeroutput"><a class="link" href="time_duration.html" title="Class template time_duration">time_duration</a></code> td = -td1 </li>
<li class="listitem"><pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_14-bb"></a><span class="keyword">operator</span><span class="special">-</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&</span> d<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_15-bb"></a><span class="keyword">operator</span><span class="special">+</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&</span> d<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_16-bb"></a><span class="keyword">operator</span><span class="special">/</span><span class="special">(</span><span class="keyword">int</span> divisor<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_17-bb"></a><span class="keyword">operator</span><span class="special">-=</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&</span> d<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_18-bb"></a><span class="keyword">operator</span><span class="special">+=</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&</span> d<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_19-bb"></a><span class="keyword">operator</span><span class="special">/=</span><span class="special">(</span><span class="keyword">int</span> divisor<span class="special">)</span><span class="special">;</span></pre>Division operations on a duration with an integer. </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_20-bb"></a><span class="keyword">operator</span><span class="special">*</span><span class="special">(</span><span class="keyword">int</span> rhs<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Multiplication operations an a duration with an integer. </li>
<li class="listitem"><pre class="literallayout"><span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_21-bb"></a><span class="keyword">operator</span><span class="special">*=</span><span class="special">(</span><span class="keyword">int</span> divisor<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="identifier">tick_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_22-bb"></a><span class="identifier">ticks</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">bool</span> <a name="id-1_3_14_15_3_47_1_1_1_15_23-bb"></a><span class="identifier">is_special</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Is ticks_ a special value? </li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">bool</span> <a name="id-1_3_14_15_3_47_1_1_1_15_24-bb"></a><span class="identifier">is_pos_infinity</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Is duration pos-infinity. </li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">bool</span> <a name="id-1_3_14_15_3_47_1_1_1_15_25-bb"></a><span class="identifier">is_neg_infinity</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Is duration neg-infinity. </li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">bool</span> <a name="id-1_3_14_15_3_47_1_1_1_15_26-bb"></a><span class="identifier">is_not_a_date_time</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Is duration not-a-date-time. </li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">impl_type</span> <a name="id-1_3_14_15_3_47_1_1_1_15_27-bb"></a><span class="identifier">get_rep</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Used for special_values output. </li>
</ol></div>
</div>
<div class="refsect2">
<a name="id-1.3.14.15.3.46.3.4.6"></a><h3>
<a name="id-1_3_14_15_3_47_1_1_1_20-bb"></a><code class="computeroutput">time_duration</code> public static functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">duration_type</span> <a name="id-1_3_14_15_3_47_1_1_1_20_1-bb"></a><span class="identifier">unit</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre>Returns smallest representable duration. </li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">tick_type</span> <a name="id-1_3_14_15_3_47_1_1_1_20_2-bb"></a><span class="identifier">ticks_per_second</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre>Return the number of ticks in a second. </li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">time_resolutions</span> <a name="id-1_3_14_15_3_47_1_1_1_20_3-bb"></a><span class="identifier">resolution</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre>Provide the resolution of this duration type. </li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="keyword">unsigned</span> <span class="keyword">short</span> <a name="id-1_3_14_15_3_47_1_1_1_20_4-bb"></a><span class="identifier">num_fractional_digits</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre>Returns number of possible digits in fractional seconds. </li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2005 CrystalClear Software, Inc<p>Subject to the Boost Software License, Version 1.0. (See accompanying file
<code class="filename">LICENSE_1_0.txt</code> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="second_clock.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../date_time/doxy.html#header.boost.date_time.time_duration_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="subsecond_duration.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| nawawi/poedit | deps/boost/doc/html/boost/date_time/time_duration.html | HTML | mit | 36,009 |
/*
* scenerenderer.h
*
* Created on: 09.05.2012
* @author Ralph Schurade
*/
#ifndef NAVRENDERERSAGITTAL_H_
#define NAVRENDERERSAGITTAL_H_
#include "navrenderer.h"
class QGLShaderProgram;
class NavRendererSagittal : public NavRenderer
{
public:
NavRendererSagittal( QString name );
virtual ~NavRendererSagittal();
void draw();
void leftMouseDown( int x, int y );
void adjustRatios();
private:
void initGeometry();
QMatrix4x4 m_pMatrix;
QMatrix4x4 m_pMatrixWorkaround;
};
#endif /* SCENERENDERER_H_ */
| steelec/braingl | src/gui/gl/navrenderersagittal.h | C | mit | 561 |
/**
* error handling middleware loosely based off of the connect/errorHandler code. This handler chooses
* to render errors using Jade / Express instead of the manual templating used by the connect middleware
* sample. This may or may not be a good idea :-)
* @param options {object} array of options
**/
exports = module.exports = function errorHandler(options) {
options = options || {};
// defaults
var showStack = options.showStack || options.stack
, showMessage = options.showMessage || options.message
, dumpExceptions = options.dumpExceptions || options.dump
, formatUrl = options.formatUrl;
return function errorHandler(err, req, res, next) {
res.statusCode = 500;
if(dumpExceptions) console.error(err.stack);
var app = res.app;
if(err instanceof exports.NotFound) {
res.render('errors/404', { locals: {
title: '404 - Not Found'
}, status: 404
});
} else {
res.render('errors/500', { locals: {
title: 'The Server Encountered an Error'
, error: showStack ? err : undefined
}, status: 500
});
}
};
};
exports.NotFound = function(msg) {
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
| brendan1mcmanus/PennApps-Fall-2015 | middleware/errorHandler.js | JavaScript | mit | 1,381 |
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2019 Intel Corporation
*/
#include <unistd.h>
#include <inttypes.h>
#include <rte_mbuf.h>
#include "rte_rawdev.h"
#include "rte_ioat_rawdev.h"
#include "ioat_private.h"
#define MAX_SUPPORTED_RAWDEVS 64
#define TEST_SKIPPED 77
#define COPY_LEN 1024
int ioat_rawdev_test(uint16_t dev_id); /* pre-define to keep compiler happy */
static struct rte_mempool *pool;
static unsigned short expected_ring_size[MAX_SUPPORTED_RAWDEVS];
#define PRINT_ERR(...) print_err(__func__, __LINE__, __VA_ARGS__)
static inline int
__rte_format_printf(3, 4)
print_err(const char *func, int lineno, const char *format, ...)
{
va_list ap;
int ret;
ret = fprintf(stderr, "In %s:%d - ", func, lineno);
va_start(ap, format);
ret += vfprintf(stderr, format, ap);
va_end(ap);
return ret;
}
static int
do_multi_copies(int dev_id, int split_batches, int split_completions)
{
struct rte_mbuf *srcs[32], *dsts[32];
struct rte_mbuf *completed_src[64];
struct rte_mbuf *completed_dst[64];
unsigned int i, j;
for (i = 0; i < RTE_DIM(srcs); i++) {
char *src_data;
if (split_batches && i == RTE_DIM(srcs) / 2)
rte_ioat_perform_ops(dev_id);
srcs[i] = rte_pktmbuf_alloc(pool);
dsts[i] = rte_pktmbuf_alloc(pool);
src_data = rte_pktmbuf_mtod(srcs[i], char *);
for (j = 0; j < COPY_LEN; j++)
src_data[j] = rand() & 0xFF;
if (rte_ioat_enqueue_copy(dev_id,
srcs[i]->buf_iova + srcs[i]->data_off,
dsts[i]->buf_iova + dsts[i]->data_off,
COPY_LEN,
(uintptr_t)srcs[i],
(uintptr_t)dsts[i]) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_copy for buffer %u\n",
i);
return -1;
}
}
rte_ioat_perform_ops(dev_id);
usleep(100);
if (split_completions) {
/* gather completions in two halves */
uint16_t half_len = RTE_DIM(srcs) / 2;
if (rte_ioat_completed_ops(dev_id, half_len, NULL, NULL,
(void *)completed_src,
(void *)completed_dst) != half_len) {
PRINT_ERR("Error with rte_ioat_completed_ops - first half request\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
if (rte_ioat_completed_ops(dev_id, half_len, NULL, NULL,
(void *)&completed_src[half_len],
(void *)&completed_dst[half_len]) != half_len) {
PRINT_ERR("Error with rte_ioat_completed_ops - second half request\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
} else {
/* gather all completions in one go */
if (rte_ioat_completed_ops(dev_id, RTE_DIM(completed_src), NULL, NULL,
(void *)completed_src,
(void *)completed_dst) != RTE_DIM(srcs)) {
PRINT_ERR("Error with rte_ioat_completed_ops\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
}
for (i = 0; i < RTE_DIM(srcs); i++) {
char *src_data, *dst_data;
if (completed_src[i] != srcs[i]) {
PRINT_ERR("Error with source pointer %u\n", i);
return -1;
}
if (completed_dst[i] != dsts[i]) {
PRINT_ERR("Error with dest pointer %u\n", i);
return -1;
}
src_data = rte_pktmbuf_mtod(srcs[i], char *);
dst_data = rte_pktmbuf_mtod(dsts[i], char *);
for (j = 0; j < COPY_LEN; j++)
if (src_data[j] != dst_data[j]) {
PRINT_ERR("Error with copy of packet %u, byte %u\n",
i, j);
return -1;
}
rte_pktmbuf_free(srcs[i]);
rte_pktmbuf_free(dsts[i]);
}
return 0;
}
static int
test_enqueue_copies(int dev_id)
{
unsigned int i;
/* test doing a single copy */
do {
struct rte_mbuf *src, *dst;
char *src_data, *dst_data;
struct rte_mbuf *completed[2] = {0};
src = rte_pktmbuf_alloc(pool);
dst = rte_pktmbuf_alloc(pool);
src_data = rte_pktmbuf_mtod(src, char *);
dst_data = rte_pktmbuf_mtod(dst, char *);
for (i = 0; i < COPY_LEN; i++)
src_data[i] = rand() & 0xFF;
if (rte_ioat_enqueue_copy(dev_id,
src->buf_iova + src->data_off,
dst->buf_iova + dst->data_off,
COPY_LEN,
(uintptr_t)src,
(uintptr_t)dst) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_copy\n");
return -1;
}
rte_ioat_perform_ops(dev_id);
usleep(10);
if (rte_ioat_completed_ops(dev_id, 1, NULL, NULL, (void *)&completed[0],
(void *)&completed[1]) != 1) {
PRINT_ERR("Error with rte_ioat_completed_ops\n");
return -1;
}
if (completed[0] != src || completed[1] != dst) {
PRINT_ERR("Error with completions: got (%p, %p), not (%p,%p)\n",
completed[0], completed[1], src, dst);
return -1;
}
for (i = 0; i < COPY_LEN; i++)
if (dst_data[i] != src_data[i]) {
PRINT_ERR("Data mismatch at char %u [Got %02x not %02x]\n",
i, dst_data[i], src_data[i]);
return -1;
}
rte_pktmbuf_free(src);
rte_pktmbuf_free(dst);
/* check ring is now empty */
if (rte_ioat_completed_ops(dev_id, 1, NULL, NULL, (void *)&completed[0],
(void *)&completed[1]) != 0) {
PRINT_ERR("Error: got unexpected returned handles from rte_ioat_completed_ops\n");
return -1;
}
} while (0);
/* test doing a multiple single copies */
do {
const uint16_t max_ops = 4;
struct rte_mbuf *src, *dst;
char *src_data, *dst_data;
struct rte_mbuf *completed[32] = {0};
const uint16_t max_completions = RTE_DIM(completed) / 2;
src = rte_pktmbuf_alloc(pool);
dst = rte_pktmbuf_alloc(pool);
src_data = rte_pktmbuf_mtod(src, char *);
dst_data = rte_pktmbuf_mtod(dst, char *);
for (i = 0; i < COPY_LEN; i++)
src_data[i] = rand() & 0xFF;
/* perform the same copy <max_ops> times */
for (i = 0; i < max_ops; i++) {
if (rte_ioat_enqueue_copy(dev_id,
src->buf_iova + src->data_off,
dst->buf_iova + dst->data_off,
COPY_LEN,
(uintptr_t)src,
(uintptr_t)dst) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_copy\n");
return -1;
}
rte_ioat_perform_ops(dev_id);
}
usleep(10);
if (rte_ioat_completed_ops(dev_id, max_completions, NULL, NULL,
(void *)&completed[0],
(void *)&completed[max_completions]) != max_ops) {
PRINT_ERR("Error with rte_ioat_completed_ops\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
if (completed[0] != src || completed[max_completions] != dst) {
PRINT_ERR("Error with completions: got (%p, %p), not (%p,%p)\n",
completed[0], completed[max_completions], src, dst);
return -1;
}
for (i = 0; i < COPY_LEN; i++)
if (dst_data[i] != src_data[i]) {
PRINT_ERR("Data mismatch at char %u\n", i);
return -1;
}
rte_pktmbuf_free(src);
rte_pktmbuf_free(dst);
} while (0);
/* test doing multiple copies */
do_multi_copies(dev_id, 0, 0); /* enqueue and complete one batch at a time */
do_multi_copies(dev_id, 1, 0); /* enqueue 2 batches and then complete both */
do_multi_copies(dev_id, 0, 1); /* enqueue 1 batch, then complete in two halves */
return 0;
}
static int
test_enqueue_fill(int dev_id)
{
const unsigned int lengths[] = {8, 64, 1024, 50, 100, 89};
struct rte_mbuf *dst = rte_pktmbuf_alloc(pool);
char *dst_data = rte_pktmbuf_mtod(dst, char *);
struct rte_mbuf *completed[2] = {0};
uint64_t pattern = 0xfedcba9876543210;
unsigned int i, j;
for (i = 0; i < RTE_DIM(lengths); i++) {
/* reset dst_data */
memset(dst_data, 0, lengths[i]);
/* perform the fill operation */
if (rte_ioat_enqueue_fill(dev_id, pattern,
dst->buf_iova + dst->data_off, lengths[i],
(uintptr_t)dst) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_fill\n");
return -1;
}
rte_ioat_perform_ops(dev_id);
usleep(100);
if (rte_ioat_completed_ops(dev_id, 1, NULL, NULL, (void *)&completed[0],
(void *)&completed[1]) != 1) {
PRINT_ERR("Error with completed ops\n");
return -1;
}
/* check the result */
for (j = 0; j < lengths[i]; j++) {
char pat_byte = ((char *)&pattern)[j % 8];
if (dst_data[j] != pat_byte) {
PRINT_ERR("Error with fill operation (lengths = %u): got (%x), not (%x)\n",
lengths[i], dst_data[j], pat_byte);
return -1;
}
}
}
rte_pktmbuf_free(dst);
return 0;
}
static int
test_burst_capacity(int dev_id)
{
#define BURST_SIZE 64
const unsigned int ring_space = rte_ioat_burst_capacity(dev_id);
struct rte_mbuf *src, *dst;
unsigned int length = 1024;
unsigned int i, j, iter;
unsigned int old_cap, cap;
uintptr_t completions[BURST_SIZE];
src = rte_pktmbuf_alloc(pool);
dst = rte_pktmbuf_alloc(pool);
old_cap = ring_space;
/* to test capacity, we enqueue elements and check capacity is reduced
* by one each time - rebaselining the expected value after each burst
* as the capacity is only for a burst. We enqueue multiple bursts to
* fill up half the ring, before emptying it again. We do this twice to
* ensure that we get to test scenarios where we get ring wrap-around
*/
for (iter = 0; iter < 2; iter++) {
for (i = 0; i < ring_space / (2 * BURST_SIZE); i++) {
cap = rte_ioat_burst_capacity(dev_id);
if (cap > old_cap) {
PRINT_ERR("Error, avail ring capacity has gone up, not down\n");
return -1;
}
old_cap = cap;
for (j = 0; j < BURST_SIZE; j++) {
if (rte_ioat_enqueue_copy(dev_id, rte_pktmbuf_iova(src),
rte_pktmbuf_iova(dst), length, 0, 0) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_copy\n");
return -1;
}
if (cap - rte_ioat_burst_capacity(dev_id) != j + 1) {
PRINT_ERR("Error, ring capacity did not change as expected\n");
return -1;
}
}
rte_ioat_perform_ops(dev_id);
}
usleep(100);
for (i = 0; i < ring_space / (2 * BURST_SIZE); i++) {
if (rte_ioat_completed_ops(dev_id, BURST_SIZE,
NULL, NULL,
completions, completions) != BURST_SIZE) {
PRINT_ERR("Error with completions\n");
return -1;
}
}
if (rte_ioat_burst_capacity(dev_id) != ring_space) {
PRINT_ERR("Error, ring capacity has not reset to original value\n");
return -1;
}
old_cap = ring_space;
}
rte_pktmbuf_free(src);
rte_pktmbuf_free(dst);
return 0;
}
static int
test_completion_status(int dev_id)
{
#define COMP_BURST_SZ 16
const unsigned int fail_copy[] = {0, 7, 15};
struct rte_mbuf *srcs[COMP_BURST_SZ], *dsts[COMP_BURST_SZ];
struct rte_mbuf *completed_src[COMP_BURST_SZ * 2];
struct rte_mbuf *completed_dst[COMP_BURST_SZ * 2];
unsigned int length = 1024;
unsigned int i;
uint8_t not_ok = 0;
/* Test single full batch statuses */
for (i = 0; i < RTE_DIM(fail_copy); i++) {
uint32_t status[COMP_BURST_SZ] = {0};
unsigned int j;
for (j = 0; j < COMP_BURST_SZ; j++) {
srcs[j] = rte_pktmbuf_alloc(pool);
dsts[j] = rte_pktmbuf_alloc(pool);
if (rte_ioat_enqueue_copy(dev_id,
(j == fail_copy[i] ? (phys_addr_t)NULL :
(srcs[j]->buf_iova + srcs[j]->data_off)),
dsts[j]->buf_iova + dsts[j]->data_off,
length,
(uintptr_t)srcs[j],
(uintptr_t)dsts[j]) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_copy for buffer %u\n", j);
return -1;
}
}
rte_ioat_perform_ops(dev_id);
usleep(100);
if (rte_ioat_completed_ops(dev_id, COMP_BURST_SZ, status, ¬_ok,
(void *)completed_src, (void *)completed_dst) != COMP_BURST_SZ) {
PRINT_ERR("Error with rte_ioat_completed_ops\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
if (not_ok != 1 || status[fail_copy[i]] == RTE_IOAT_OP_SUCCESS) {
unsigned int j;
PRINT_ERR("Error, missing expected failed copy, %u\n", fail_copy[i]);
for (j = 0; j < COMP_BURST_SZ; j++)
printf("%u ", status[j]);
printf("<-- Statuses\n");
return -1;
}
for (j = 0; j < COMP_BURST_SZ; j++) {
rte_pktmbuf_free(completed_src[j]);
rte_pktmbuf_free(completed_dst[j]);
}
}
/* Test gathering status for two batches at once */
for (i = 0; i < RTE_DIM(fail_copy); i++) {
uint32_t status[COMP_BURST_SZ] = {0};
unsigned int batch, j;
unsigned int expected_failures = 0;
for (batch = 0; batch < 2; batch++) {
for (j = 0; j < COMP_BURST_SZ/2; j++) {
srcs[j] = rte_pktmbuf_alloc(pool);
dsts[j] = rte_pktmbuf_alloc(pool);
if (j == fail_copy[i])
expected_failures++;
if (rte_ioat_enqueue_copy(dev_id,
(j == fail_copy[i] ? (phys_addr_t)NULL :
(srcs[j]->buf_iova + srcs[j]->data_off)),
dsts[j]->buf_iova + dsts[j]->data_off,
length,
(uintptr_t)srcs[j],
(uintptr_t)dsts[j]) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_copy for buffer %u\n",
j);
return -1;
}
}
rte_ioat_perform_ops(dev_id);
}
usleep(100);
if (rte_ioat_completed_ops(dev_id, COMP_BURST_SZ, status, ¬_ok,
(void *)completed_src, (void *)completed_dst) != COMP_BURST_SZ) {
PRINT_ERR("Error with rte_ioat_completed_ops\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
if (not_ok != expected_failures) {
unsigned int j;
PRINT_ERR("Error, missing expected failed copy, got %u, not %u\n",
not_ok, expected_failures);
for (j = 0; j < COMP_BURST_SZ; j++)
printf("%u ", status[j]);
printf("<-- Statuses\n");
return -1;
}
for (j = 0; j < COMP_BURST_SZ; j++) {
rte_pktmbuf_free(completed_src[j]);
rte_pktmbuf_free(completed_dst[j]);
}
}
/* Test gathering status for half batch at a time */
for (i = 0; i < RTE_DIM(fail_copy); i++) {
uint32_t status[COMP_BURST_SZ] = {0};
unsigned int j;
for (j = 0; j < COMP_BURST_SZ; j++) {
srcs[j] = rte_pktmbuf_alloc(pool);
dsts[j] = rte_pktmbuf_alloc(pool);
if (rte_ioat_enqueue_copy(dev_id,
(j == fail_copy[i] ? (phys_addr_t)NULL :
(srcs[j]->buf_iova + srcs[j]->data_off)),
dsts[j]->buf_iova + dsts[j]->data_off,
length,
(uintptr_t)srcs[j],
(uintptr_t)dsts[j]) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_copy for buffer %u\n", j);
return -1;
}
}
rte_ioat_perform_ops(dev_id);
usleep(100);
if (rte_ioat_completed_ops(dev_id, COMP_BURST_SZ / 2, status, ¬_ok,
(void *)completed_src,
(void *)completed_dst) != (COMP_BURST_SZ / 2)) {
PRINT_ERR("Error with rte_ioat_completed_ops\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
if (fail_copy[i] < COMP_BURST_SZ / 2 &&
(not_ok != 1 || status[fail_copy[i]] == RTE_IOAT_OP_SUCCESS)) {
PRINT_ERR("Missing expected failure in first half-batch\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
if (rte_ioat_completed_ops(dev_id, COMP_BURST_SZ / 2, status, ¬_ok,
(void *)&completed_src[COMP_BURST_SZ / 2],
(void *)&completed_dst[COMP_BURST_SZ / 2]) != (COMP_BURST_SZ / 2)) {
PRINT_ERR("Error with rte_ioat_completed_ops\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
if (fail_copy[i] >= COMP_BURST_SZ / 2 && (not_ok != 1 ||
status[fail_copy[i] - (COMP_BURST_SZ / 2)]
== RTE_IOAT_OP_SUCCESS)) {
PRINT_ERR("Missing expected failure in second half-batch\n");
rte_rawdev_dump(dev_id, stdout);
return -1;
}
for (j = 0; j < COMP_BURST_SZ; j++) {
rte_pktmbuf_free(completed_src[j]);
rte_pktmbuf_free(completed_dst[j]);
}
}
/* Test gathering statuses with fence */
for (i = 1; i < RTE_DIM(fail_copy); i++) {
uint32_t status[COMP_BURST_SZ * 2] = {0};
unsigned int j;
uint16_t count;
for (j = 0; j < COMP_BURST_SZ; j++) {
srcs[j] = rte_pktmbuf_alloc(pool);
dsts[j] = rte_pktmbuf_alloc(pool);
/* always fail the first copy */
if (rte_ioat_enqueue_copy(dev_id,
(j == 0 ? (phys_addr_t)NULL :
(srcs[j]->buf_iova + srcs[j]->data_off)),
dsts[j]->buf_iova + dsts[j]->data_off,
length,
(uintptr_t)srcs[j],
(uintptr_t)dsts[j]) != 1) {
PRINT_ERR("Error with rte_ioat_enqueue_copy for buffer %u\n", j);
return -1;
}
/* put in a fence which will stop any further transactions
* because we had a previous failure.
*/
if (j == fail_copy[i])
rte_ioat_fence(dev_id);
}
rte_ioat_perform_ops(dev_id);
usleep(100);
count = rte_ioat_completed_ops(dev_id, COMP_BURST_SZ * 2, status, ¬_ok,
(void *)completed_src, (void *)completed_dst);
if (count != COMP_BURST_SZ) {
PRINT_ERR("Error with rte_ioat_completed_ops, got %u not %u\n",
count, COMP_BURST_SZ);
for (j = 0; j < count; j++)
printf("%u ", status[j]);
printf("<-- Statuses\n");
return -1;
}
if (not_ok != COMP_BURST_SZ - fail_copy[i]) {
PRINT_ERR("Unexpected failed copy count, got %u, expected %u\n",
not_ok, COMP_BURST_SZ - fail_copy[i]);
for (j = 0; j < COMP_BURST_SZ; j++)
printf("%u ", status[j]);
printf("<-- Statuses\n");
return -1;
}
if (status[0] == RTE_IOAT_OP_SUCCESS || status[0] == RTE_IOAT_OP_SKIPPED) {
PRINT_ERR("Error, op 0 unexpectedly did not fail.\n");
return -1;
}
for (j = 1; j <= fail_copy[i]; j++) {
if (status[j] != RTE_IOAT_OP_SUCCESS) {
PRINT_ERR("Error, op %u unexpectedly failed\n", j);
return -1;
}
}
for (j = fail_copy[i] + 1; j < COMP_BURST_SZ; j++) {
if (status[j] != RTE_IOAT_OP_SKIPPED) {
PRINT_ERR("Error, all descriptors after fence should be invalid\n");
return -1;
}
}
for (j = 0; j < COMP_BURST_SZ; j++) {
rte_pktmbuf_free(completed_src[j]);
rte_pktmbuf_free(completed_dst[j]);
}
}
return 0;
}
int
ioat_rawdev_test(uint16_t dev_id)
{
#define IOAT_TEST_RINGSIZE 512
const struct rte_idxd_rawdev *idxd =
(struct rte_idxd_rawdev *)rte_rawdevs[dev_id].dev_private;
const enum rte_ioat_dev_type ioat_type = idxd->type;
struct rte_ioat_rawdev_config p = { .ring_size = -1 };
struct rte_rawdev_info info = { .dev_private = &p };
struct rte_rawdev_xstats_name *snames = NULL;
uint64_t *stats = NULL;
unsigned int *ids = NULL;
unsigned int nb_xstats;
unsigned int i;
if (dev_id >= MAX_SUPPORTED_RAWDEVS) {
printf("Skipping test. Cannot test rawdevs with id's greater than %d\n",
MAX_SUPPORTED_RAWDEVS);
return TEST_SKIPPED;
}
rte_rawdev_info_get(dev_id, &info, sizeof(p));
if (p.ring_size != expected_ring_size[dev_id]) {
PRINT_ERR("Error, initial ring size is not as expected (Actual: %d, Expected: %d)\n",
(int)p.ring_size, expected_ring_size[dev_id]);
return -1;
}
p.ring_size = IOAT_TEST_RINGSIZE;
if (rte_rawdev_configure(dev_id, &info, sizeof(p)) != 0) {
PRINT_ERR("Error with rte_rawdev_configure()\n");
return -1;
}
rte_rawdev_info_get(dev_id, &info, sizeof(p));
if (p.ring_size != IOAT_TEST_RINGSIZE) {
PRINT_ERR("Error, ring size is not %d (%d)\n",
IOAT_TEST_RINGSIZE, (int)p.ring_size);
return -1;
}
expected_ring_size[dev_id] = p.ring_size;
if (rte_rawdev_start(dev_id) != 0) {
PRINT_ERR("Error with rte_rawdev_start()\n");
return -1;
}
pool = rte_pktmbuf_pool_create("TEST_IOAT_POOL",
p.ring_size * 2, /* n == num elements */
32, /* cache size */
0, /* priv size */
2048, /* data room size */
info.socket_id);
if (pool == NULL) {
PRINT_ERR("Error with mempool creation\n");
return -1;
}
/* allocate memory for xstats names and values */
nb_xstats = rte_rawdev_xstats_names_get(dev_id, NULL, 0);
snames = malloc(sizeof(*snames) * nb_xstats);
if (snames == NULL) {
PRINT_ERR("Error allocating xstat names memory\n");
goto err;
}
rte_rawdev_xstats_names_get(dev_id, snames, nb_xstats);
ids = malloc(sizeof(*ids) * nb_xstats);
if (ids == NULL) {
PRINT_ERR("Error allocating xstat ids memory\n");
goto err;
}
for (i = 0; i < nb_xstats; i++)
ids[i] = i;
stats = malloc(sizeof(*stats) * nb_xstats);
if (stats == NULL) {
PRINT_ERR("Error allocating xstat memory\n");
goto err;
}
/* run the test cases */
printf("Running Copy Tests\n");
for (i = 0; i < 100; i++) {
unsigned int j;
if (test_enqueue_copies(dev_id) != 0)
goto err;
rte_rawdev_xstats_get(dev_id, ids, stats, nb_xstats);
for (j = 0; j < nb_xstats; j++)
printf("%s: %"PRIu64" ", snames[j].name, stats[j]);
printf("\r");
}
printf("\n");
/* test enqueue fill operation */
printf("Running Fill Tests\n");
for (i = 0; i < 100; i++) {
unsigned int j;
if (test_enqueue_fill(dev_id) != 0)
goto err;
rte_rawdev_xstats_get(dev_id, ids, stats, nb_xstats);
for (j = 0; j < nb_xstats; j++)
printf("%s: %"PRIu64" ", snames[j].name, stats[j]);
printf("\r");
}
printf("\n");
printf("Running Burst Capacity Test\n");
if (test_burst_capacity(dev_id) != 0)
goto err;
/* only DSA devices report address errors, and we can only use null pointers
* to generate those errors when DPDK is in VA mode.
*/
if (rte_eal_iova_mode() == RTE_IOVA_VA && ioat_type == RTE_IDXD_DEV) {
printf("Running Completions Status Test\n");
if (test_completion_status(dev_id) != 0)
goto err;
}
rte_rawdev_stop(dev_id);
if (rte_rawdev_xstats_reset(dev_id, NULL, 0) != 0) {
PRINT_ERR("Error resetting xstat values\n");
goto err;
}
rte_mempool_free(pool);
free(snames);
free(stats);
free(ids);
return 0;
err:
rte_rawdev_stop(dev_id);
rte_rawdev_xstats_reset(dev_id, NULL, 0);
rte_mempool_free(pool);
free(snames);
free(stats);
free(ids);
return -1;
}
| john-mcnamara-intel/dpdk | drivers/raw/ioat/ioat_rawdev_test.c | C | mit | 20,614 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
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.
-----------------------------------------------------------------------------
*/
#include "OgreGLDepthBuffer.h"
#include "OgreGLHardwarePixelBuffer.h"
#include "OgreGLRenderSystem.h"
#include "OgreGLFrameBufferObject.h"
namespace Ogre
{
GLDepthBuffer::GLDepthBuffer( uint16 poolId, GLRenderSystem *renderSystem, GLContext *creatorContext,
GLRenderBuffer *depth, GLRenderBuffer *stencil,
uint32 width, uint32 height, uint32 fsaa, uint32 multiSampleQuality,
bool manual ) :
DepthBuffer( poolId, 0, width, height, fsaa, "", manual ),
mMultiSampleQuality( multiSampleQuality ),
mCreatorContext( creatorContext ),
mDepthBuffer( depth ),
mStencilBuffer( stencil ),
mRenderSystem( renderSystem )
{
if( mDepthBuffer )
{
switch( mDepthBuffer->getGLFormat() )
{
case GL_DEPTH_COMPONENT16:
mBitDepth = 16;
break;
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32:
case GL_DEPTH24_STENCIL8_EXT:
mBitDepth = 32;
break;
}
}
}
GLDepthBuffer::~GLDepthBuffer()
{
if( mStencilBuffer && mStencilBuffer != mDepthBuffer )
{
delete mStencilBuffer;
mStencilBuffer = 0;
}
if( mDepthBuffer )
{
delete mDepthBuffer;
mDepthBuffer = 0;
}
}
//---------------------------------------------------------------------
bool GLDepthBuffer::isCompatible( RenderTarget *renderTarget ) const
{
bool retVal = false;
//Check standard stuff first.
if( mRenderSystem->getCapabilities()->hasCapability( RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL ) )
{
if( !DepthBuffer::isCompatible( renderTarget ) )
return false;
}
else
{
if( this->getWidth() != renderTarget->getWidth() ||
this->getHeight() != renderTarget->getHeight() ||
this->getFsaa() != renderTarget->getFSAA() )
return false;
}
//Now check this is the appropriate format
GLFrameBufferObject *fbo = 0;
renderTarget->getCustomAttribute(GLRenderTexture::CustomAttributeString_FBO, &fbo);
if( !fbo )
{
GLContext *windowContext;
renderTarget->getCustomAttribute( GLRenderTexture::CustomAttributeString_GLCONTEXT, &windowContext );
//Non-FBO targets and FBO depth surfaces don't play along, only dummies which match the same
//context
if( !mDepthBuffer && !mStencilBuffer && mCreatorContext == windowContext )
retVal = true;
}
else
{
//Check this isn't a dummy non-FBO depth buffer with an FBO target, don't mix them.
//If you don't want depth buffer, use a Null Depth Buffer, not a dummy one.
if( mDepthBuffer || mStencilBuffer )
{
GLenum internalFormat = fbo->getFormat();
GLenum depthFormat, stencilFormat;
mRenderSystem->_getDepthStencilFormatFor( internalFormat, &depthFormat, &stencilFormat );
bool bSameDepth = false;
if( mDepthBuffer )
bSameDepth |= mDepthBuffer->getGLFormat() == depthFormat;
bool bSameStencil = false;
if( !mStencilBuffer || mStencilBuffer == mDepthBuffer )
bSameStencil = stencilFormat == GL_NONE;
else
{
if( mStencilBuffer )
bSameStencil = stencilFormat == mStencilBuffer->getGLFormat();
}
retVal = bSameDepth && bSameStencil;
}
}
return retVal;
}
}
| bhlzlx/ogre | RenderSystems/GL/src/OgreGLDepthBuffer.cpp | C++ | mit | 4,568 |
using Scharfrichter.Codec;
using Scharfrichter.Codec.Archives;
using Scharfrichter.Codec.Charts;
using Scharfrichter.Codec.Sounds;
using Scharfrichter.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ConvertHelper
{
static public class BemaniToBMS
{
private const string configFileName = "Convert";
private const string databaseFileName = "BeatmaniaDB";
static public void Convert(string[] inArgs, long unitNumerator, long unitDenominator)
{
// configuration
Configuration config = LoadConfig();
Configuration db = LoadDB();
int quantizeMeasure = config["BMS"].GetValue("QuantizeMeasure");
int quantizeNotes = config["BMS"].GetValue("QuantizeNotes");
// splash
Splash.Show("Bemani to BeMusic Script");
Console.WriteLine("Timing: " + unitNumerator.ToString() + "/" + unitDenominator.ToString());
Console.WriteLine("Measure Quantize: " + quantizeMeasure.ToString());
// args
string[] args;
if (inArgs.Length > 0)
args = Subfolder.Parse(inArgs);
else
args = inArgs;
// debug args (if applicable)
if (System.Diagnostics.Debugger.IsAttached && args.Length == 0)
{
Console.WriteLine();
Console.WriteLine("Debugger attached. Input file name:");
args = new string[] { Console.ReadLine() };
}
// show usage if no args provided
if (args.Length == 0)
{
Console.WriteLine();
Console.WriteLine("Usage: BemaniToBMS <input file>");
Console.WriteLine();
Console.WriteLine("Drag and drop with files and folders is fully supported for this application.");
Console.WriteLine();
Console.WriteLine("Supported formats:");
Console.WriteLine("1, 2DX, CS, SD9, SSP");
}
// process files
for (int i = 0; i < args.Length; i++)
{
if (File.Exists(args[i]))
{
Console.WriteLine();
Console.WriteLine("Processing File: " + args[i]);
string filename = args[i];
string IIDXDBName = Path.GetFileNameWithoutExtension(filename);
while (IIDXDBName.StartsWith("0"))
IIDXDBName = IIDXDBName.Substring(1);
byte[] data = File.ReadAllBytes(args[i]);
switch (Path.GetExtension(args[i]).ToUpper())
{
case @".1":
using (MemoryStream source = new MemoryStream(data))
{
Bemani1 archive = Bemani1.Read(source, unitNumerator, unitDenominator);
if (db[IIDXDBName]["TITLE"] != "")
{
for (int j = 0; j < archive.ChartCount; j++)
{
Chart chart = archive.Charts[j];
if (chart != null)
{
chart.Tags["TITLE"] = db[IIDXDBName]["TITLE"];
chart.Tags["ARTIST"] = db[IIDXDBName]["ARTIST"];
chart.Tags["GENRE"] = db[IIDXDBName]["GENRE"];
if (j < 6)
chart.Tags["PLAYLEVEL"] = db[IIDXDBName]["DIFFICULTYSP" + config["IIDX"]["DIFFICULTY" + j.ToString()]];
else if (j < 12)
chart.Tags["PLAYLEVEL"] = db[IIDXDBName]["DIFFICULTYDP" + config["IIDX"]["DIFFICULTY" + j.ToString()]];
}
}
}
ConvertArchive(archive, config, args[i]);
}
break;
case @".2DX":
using (MemoryStream source = new MemoryStream(data))
{
Console.WriteLine("Converting Samples");
Bemani2DX archive = Bemani2DX.Read(source);
ConvertSounds(archive.Sounds, filename, 0.6f);
}
break;
case @".CS":
using (MemoryStream source = new MemoryStream(data))
ConvertChart(BeatmaniaIIDXCSNew.Read(source), config, filename, -1, null);
break;
case @".CS2":
using (MemoryStream source = new MemoryStream(data))
ConvertChart(BeatmaniaIIDXCSOld.Read(source), config, filename, -1, null);
break;
case @".CS5":
using (MemoryStream source = new MemoryStream(data))
ConvertChart(Beatmania5Key.Read(source), config, filename, -1, null);
break;
case @".CS9":
break;
case @".SD9":
using (MemoryStream source = new MemoryStream(data))
{
Sound sound = BemaniSD9.Read(source);
string targetFile = Path.GetFileNameWithoutExtension(filename);
string targetPath = Path.Combine(Path.GetDirectoryName(filename), targetFile) + ".wav";
sound.WriteFile(targetPath, 1.0f);
}
break;
case @".SSP":
using (MemoryStream source = new MemoryStream(data))
ConvertSounds(BemaniSSP.Read(source).Sounds, filename, 1.0f);
break;
}
}
}
// wrap up
Console.WriteLine("BemaniToBMS finished.");
}
static public void ConvertArchive(Archive archive, Configuration config, string filename)
{
for (int j = 0; j < archive.ChartCount; j++)
{
if (archive.Charts[j] != null)
{
Console.WriteLine("Converting Chart " + j.ToString());
ConvertChart(archive.Charts[j], config, filename, j, null);
}
}
}
static public void ConvertChart(Chart chart, Configuration config, string filename, int index, int[] map)
{
if (config == null)
{
config = LoadConfig();
}
int quantizeNotes = config["BMS"].GetValue("QuantizeNotes");
int quantizeMeasure = config["BMS"].GetValue("QuantizeMeasure");
int difficulty = config["IIDX"].GetValue("Difficulty" + index.ToString());
string title = config["BMS"]["Players" + config["IIDX"]["Players" + index.ToString()]] + " " + config["BMS"]["Difficulty" + difficulty.ToString()];
title = title.Trim();
if (quantizeMeasure > 0)
chart.QuantizeMeasureLengths(quantizeMeasure);
using (MemoryStream mem = new MemoryStream())
{
BMS bms = new BMS();
bms.Charts = new Chart[] { chart };
string name = "";
if (chart.Tags.ContainsKey("TITLE"))
name = chart.Tags["TITLE"];
if (name == "")
name = Path.GetFileNameWithoutExtension(Path.GetFileName(filename)); //ex: "1204 [1P Another]"
// write some tags
bms.Charts[0].Tags["TITLE"] = name;
if (chart.Tags.ContainsKey("ARTIST"))
bms.Charts[0].Tags["ARTIST"] = chart.Tags["ARTIST"];
if (chart.Tags.ContainsKey("GENRE"))
bms.Charts[0].Tags["GENRE"] = chart.Tags["GENRE"];
if (difficulty > 0)
bms.Charts[0].Tags["DIFFICULTY"] = difficulty.ToString();
if (bms.Charts[0].Players > 1)
bms.Charts[0].Tags["PLAYER"] = "3";
else
bms.Charts[0].Tags["PLAYER"] = "1";
name = name.Replace(":", "_");
name = name.Replace("/", "_");
name = name.Replace("?", "_");
name = name.Replace("\\", "_");
if (title != null && title.Length > 0)
{
name += " [" + title + "]";
}
string output = Path.Combine(Path.GetDirectoryName(filename), @"@" + name + ".bms");
if (map == null)
bms.GenerateSampleMap();
else
bms.SampleMap = map;
if (quantizeNotes > 0)
bms.Charts[0].QuantizeNoteOffsets(quantizeNotes);
bms.GenerateSampleTags();
bms.Write(mem, true);
File.WriteAllBytes(output, mem.ToArray());
}
}
static public void ConvertSounds(Sound[] sounds, string filename, float volume)
{
string name = Path.GetFileNameWithoutExtension(Path.GetFileName(filename));
string targetPath = Path.Combine(Path.GetDirectoryName(filename), name);
if (!Directory.Exists(targetPath))
Directory.CreateDirectory(targetPath);
int count = sounds.Length;
for (int j = 0; j < count; j++)
{
int sampleIndex = j + 1;
sounds[j].WriteFile(Path.Combine(targetPath, Scharfrichter.Codec.Util.ConvertToBMEString(sampleIndex, 4) + @".wav"), volume);
}
}
static private Configuration LoadConfig()
{
Configuration config = Configuration.ReadFile(configFileName);
config["BMS"].SetDefaultValue("QuantizeMeasure", 16);
config["BMS"].SetDefaultValue("QuantizeNotes", 192);
config["BMS"].SetDefaultString("Difficulty1", "Beginner");
config["BMS"].SetDefaultString("Difficulty2", "Normal");
config["BMS"].SetDefaultString("Difficulty3", "Hyper");
config["BMS"].SetDefaultString("Difficulty4", "Another");
config["BMS"].SetDefaultString("Players1", "1P");
config["BMS"].SetDefaultString("Players2", "2P");
config["BMS"].SetDefaultString("Players3", "DP");
config["IIDX"].SetDefaultString("Difficulty0", "3");
config["IIDX"].SetDefaultString("Difficulty1", "2");
config["IIDX"].SetDefaultString("Difficulty2", "4");
config["IIDX"].SetDefaultString("Difficulty3", "1");
config["IIDX"].SetDefaultString("Difficulty6", "3");
config["IIDX"].SetDefaultString("Difficulty7", "2");
config["IIDX"].SetDefaultString("Difficulty8", "4");
config["IIDX"].SetDefaultString("Difficulty9", "1");
config["IIDX"].SetDefaultString("Players0", "1");
config["IIDX"].SetDefaultString("Players1", "1");
config["IIDX"].SetDefaultString("Players2", "1");
config["IIDX"].SetDefaultString("Players3", "1");
config["IIDX"].SetDefaultString("Players6", "3");
config["IIDX"].SetDefaultString("Players7", "3");
config["IIDX"].SetDefaultString("Players8", "3");
config["IIDX"].SetDefaultString("Players9", "3");
return config;
}
static private Configuration LoadDB()
{
Configuration config = Configuration.ReadFile(databaseFileName);
return config;
}
}
}
| heshuimu/scharfrichter | ConvertHelper/BemaniToBMS.cs | C# | mit | 12,651 |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using Windows.Security.EnterpriseData;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace EdpSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario1 : Page
{
private MainPage rootPage;
private static string m_EnterpriseId = "contoso.com";
public static string m_EnterpriseIdentity
{
get
{
return m_EnterpriseId;
}
}
public Scenario1()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
private void Setup_Click(object sender, RoutedEventArgs e)
{
m_EnterpriseId = EnterpriseIdentity.Text;
rootPage.NotifyUser("Enterprise Identity is set to: " + m_EnterpriseIdentity, NotifyType.StatusMessage);
}
}
}
| mobilecp/Windows-universal-samples | edpsamples/cs/scenario1_setup.xaml.cs | C# | mit | 1,622 |
package com.iluwatar;
public class Sergeant extends Unit {
public Sergeant(Unit ... children) {
super(children);
}
@Override
public void accept(UnitVisitor visitor) {
visitor.visitSergeant(this);
super.accept(visitor);
}
@Override
public String toString() {
return "sergeant";
}
}
| zfu/java-design-patterns | visitor/src/main/java/com/iluwatar/Sergeant.java | Java | mit | 321 |
/*
Copyright
*/
//go:generate rm -vf autogen/gen.go
//go:generate go-bindata -pkg autogen -o autogen/gen.go ./static/... ./templates/...
//go:generate mkdir -p vendor/github.com/docker/docker/autogen/dockerversion
//go:generate cp script/dockerversion vendor/github.com/docker/docker/autogen/dockerversion/dockerversion.go
package main
| dontrebootme/traefik | generate.go | GO | mit | 339 |
#ifndef vm_h
#define vm_h
#include "uv.h"
#include "wren.h"
// Executes the Wren script at [path] in a new VM.
//
// Exits if the script failed or could not be loaded.
void runFile(const char* path);
// Runs the Wren interactive REPL.
int runRepl();
// Gets the currently running VM.
WrenVM* getVM();
// Gets the event loop the VM is using.
uv_loop_t* getLoop();
// Set the exit code the CLI should exit with when done.
void setExitCode(int exitCode);
// Adds additional callbacks to use when binding foreign members from Wren.
//
// Used by the API test executable to let it wire up its own foreign functions.
// This must be called before calling [createVM()].
void setTestCallbacks(WrenBindForeignMethodFn bindMethod,
WrenBindForeignClassFn bindClass,
void (*afterLoad)(WrenVM* vm));
#endif
| foresterre/wren | src/cli/vm.h | C | mit | 846 |
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
Getting Started with Engines
============================
In this guide you will learn about engines and how they can be used to provide
additional functionality to their host applications through a clean and very
easy-to-use interface.
After reading this guide, you will know:
* What makes an engine.
* How to generate an engine.
* How to build features for the engine.
* How to hook the engine into an application.
* How to override engine functionality in the application.
* How to avoid loading Rails frameworks with Load and Configuration Hooks.
--------------------------------------------------------------------------------
What are Engines?
-----------------
Engines can be considered miniature applications that provide functionality to
their host applications. A Rails application is actually just a "supercharged"
engine, with the `Rails::Application` class inheriting a lot of its behavior
from `Rails::Engine`.
Therefore, engines and applications can be thought of as almost the same thing,
just with subtle differences, as you'll see throughout this guide. Engines and
applications also share a common structure.
Engines are also closely related to plugins. The two share a common `lib`
directory structure, and are both generated using the `rails plugin new`
generator. The difference is that an engine is considered a "full plugin" by
Rails (as indicated by the `--full` option that's passed to the generator
command). We'll actually be using the `--mountable` option here, which includes
all the features of `--full`, and then some. This guide will refer to these
"full plugins" simply as "engines" throughout. An engine **can** be a plugin,
and a plugin **can** be an engine.
The engine that will be created in this guide will be called "blorgh". This
engine will provide blogging functionality to its host applications, allowing
for new articles and comments to be created. At the beginning of this guide, you
will be working solely within the engine itself, but in later sections you'll
see how to hook it into an application.
Engines can also be isolated from their host applications. This means that an
application is able to have a path provided by a routing helper such as
`articles_path` and use an engine that also provides a path also called
`articles_path`, and the two would not clash. Along with this, controllers, models
and table names are also namespaced. You'll see how to do this later in this
guide.
It's important to keep in mind at all times that the application should
**always** take precedence over its engines. An application is the object that
has final say in what goes on in its environment. The engine should
only be enhancing it, rather than changing it drastically.
To see demonstrations of other engines, check out
[Devise](https://github.com/plataformatec/devise), an engine that provides
authentication for its parent applications, or
[Thredded](https://github.com/thredded/thredded), an engine that provides forum
functionality. There's also [Spree](https://github.com/spree/spree) which
provides an e-commerce platform, and
[Refinery CMS](https://github.com/refinery/refinerycms), a CMS engine.
Finally, engines would not have been possible without the work of James Adam,
Piotr Sarnacki, the Rails Core Team, and a number of other people. If you ever
meet them, don't forget to say thanks!
Generating an Engine
--------------------
To generate an engine, you will need to run the plugin generator and pass it
options as appropriate to the need. For the "blorgh" example, you will need to
create a "mountable" engine, running this command in a terminal:
```bash
$ rails plugin new blorgh --mountable
```
The full list of options for the plugin generator may be seen by typing:
```bash
$ rails plugin --help
```
The `--mountable` option tells the generator that you want to create a
"mountable" and namespace-isolated engine. This generator will provide the same
skeleton structure as would the `--full` option. The `--full` option tells the
generator that you want to create an engine, including a skeleton structure
that provides the following:
* An `app` directory tree
* A `config/routes.rb` file:
```ruby
Rails.application.routes.draw do
end
```
* A file at `lib/blorgh/engine.rb`, which is identical in function to a
standard Rails application's `config/application.rb` file:
```ruby
module Blorgh
class Engine < ::Rails::Engine
end
end
```
The `--mountable` option will add to the `--full` option:
* Asset manifest files (`blorgh_manifest.js` and `application.css`)
* A namespaced `ApplicationController` stub
* A namespaced `ApplicationHelper` stub
* A layout view template for the engine
* Namespace isolation to `config/routes.rb`:
```ruby
Blorgh::Engine.routes.draw do
end
```
* Namespace isolation to `lib/blorgh/engine.rb`:
```ruby
module Blorgh
class Engine < ::Rails::Engine
isolate_namespace Blorgh
end
end
```
Additionally, the `--mountable` option tells the generator to mount the engine
inside the dummy testing application located at `test/dummy` by adding the
following to the dummy application's routes file at
`test/dummy/config/routes.rb`:
```ruby
mount Blorgh::Engine => "/blorgh"
```
### Inside an Engine
#### Critical Files
At the root of this brand new engine's directory lives a `blorgh.gemspec` file.
When you include the engine into an application later on, you will do so with
this line in the Rails application's `Gemfile`:
```ruby
gem 'blorgh', path: 'engines/blorgh'
```
Don't forget to run `bundle install` as usual. By specifying it as a gem within
the `Gemfile`, Bundler will load it as such, parsing this `blorgh.gemspec` file
and requiring a file within the `lib` directory called `lib/blorgh.rb`. This
file requires the `blorgh/engine.rb` file (located at `lib/blorgh/engine.rb`)
and defines a base module called `Blorgh`.
```ruby
require "blorgh/engine"
module Blorgh
end
```
TIP: Some engines choose to use this file to put global configuration options
for their engine. It's a relatively good idea, so if you want to offer
configuration options, the file where your engine's `module` is defined is
perfect for that. Place the methods inside the module and you'll be good to go.
Within `lib/blorgh/engine.rb` is the base class for the engine:
```ruby
module Blorgh
class Engine < ::Rails::Engine
isolate_namespace Blorgh
end
end
```
By inheriting from the `Rails::Engine` class, this gem notifies Rails that
there's an engine at the specified path, and will correctly mount the engine
inside the application, performing tasks such as adding the `app` directory of
the engine to the load path for models, mailers, controllers, and views.
The `isolate_namespace` method here deserves special notice. This call is
responsible for isolating the controllers, models, routes, and other things into
their own namespace, away from similar components inside the application.
Without this, there is a possibility that the engine's components could "leak"
into the application, causing unwanted disruption, or that important engine
components could be overridden by similarly named things within the application.
One of the examples of such conflicts is helpers. Without calling
`isolate_namespace`, the engine's helpers would be included in an application's
controllers.
NOTE: It is **highly** recommended that the `isolate_namespace` line be left
within the `Engine` class definition. Without it, classes generated in an engine
**may** conflict with an application.
What this isolation of the namespace means is that a model generated by a call
to `bin/rails generate model`, such as `bin/rails generate model article`, won't be called `Article`, but
instead be namespaced and called `Blorgh::Article`. In addition, the table for the
model is namespaced, becoming `blorgh_articles`, rather than simply `articles`.
Similar to the model namespacing, a controller called `ArticlesController` becomes
`Blorgh::ArticlesController` and the views for that controller will not be at
`app/views/articles`, but `app/views/blorgh/articles` instead. Mailers, jobs
and helpers are namespaced as well.
Finally, routes will also be isolated within the engine. This is one of the most
important parts about namespacing, and is discussed later in the
[Routes](#routes) section of this guide.
#### `app` Directory
Inside the `app` directory are the standard `assets`, `controllers`, `helpers`,
`jobs`, `mailers`, `models`, and `views` directories that you should be familiar with
from an application. We'll look more into models in a future section, when we're writing the engine.
Within the `app/assets` directory, there are the `images` and
`stylesheets` directories which, again, you should be familiar with due to their
similarity to an application. One difference here, however, is that each
directory contains a sub-directory with the engine name. Because this engine is
going to be namespaced, its assets should be too.
Within the `app/controllers` directory there is a `blorgh` directory that
contains a file called `application_controller.rb`. This file will provide any
common functionality for the controllers of the engine. The `blorgh` directory
is where the other controllers for the engine will go. By placing them within
this namespaced directory, you prevent them from possibly clashing with
identically-named controllers within other engines or even within the
application.
NOTE: The `ApplicationController` class inside an engine is named just like a
Rails application in order to make it easier for you to convert your
applications into engines.
NOTE: If the parent application runs in `classic` mode, you may run into a
situation where your engine controller is inheriting from the main application
controller and not your engine's application controller. The best way to prevent
this is to switch to `zeitwerk` mode in the parent application. Otherwise, use
`require_dependency` to ensure that the engine's application controller is
loaded. For example:
```ruby
# ONLY NEEDED IN `classic` MODE.
require_dependency "blorgh/application_controller"
module Blorgh
class ArticlesController < ApplicationController
# ...
end
end
```
WARNING: Don't use `require` because it will break the automatic reloading of
classes in the development environment - using `require_dependency` ensures that
classes are loaded and unloaded in the correct manner.
Just like for `app/controllers`, you will find a `blorgh` subdirectory under
the `app/helpers`, `app/jobs`, `app/mailers` and `app/models` directories
containing the associated `application_*.rb` file for gathering common
functionalities. By placing your files under this subdirectory and namespacing
your objects, you prevent them from possibly clashing with identically-named
elements within other engines or even within the application.
Lastly, the `app/views` directory contains a `layouts` folder, which contains a
file at `blorgh/application.html.erb`. This file allows you to specify a layout
for the engine. If this engine is to be used as a stand-alone engine, then you
would add any customization to its layout in this file, rather than the
application's `app/views/layouts/application.html.erb` file.
If you don't want to force a layout on to users of the engine, then you can
delete this file and reference a different layout in the controllers of your
engine.
#### `bin` Directory
This directory contains one file, `bin/rails`, which enables you to use the
`rails` sub-commands and generators just like you would within an application.
This means that you will be able to generate new controllers and models for this
engine very easily by running commands like this:
```bash
$ bin/rails generate model
```
Keep in mind, of course, that anything generated with these commands inside of
an engine that has `isolate_namespace` in the `Engine` class will be namespaced.
#### `test` Directory
The `test` directory is where tests for the engine will go. To test the engine,
there is a cut-down version of a Rails application embedded within it at
`test/dummy`. This application will mount the engine in the
`test/dummy/config/routes.rb` file:
```ruby
Rails.application.routes.draw do
mount Blorgh::Engine => "/blorgh"
end
```
This line mounts the engine at the path `/blorgh`, which will make it accessible
through the application only at that path.
Inside the test directory there is the `test/integration` directory, where
integration tests for the engine should be placed. Other directories can be
created in the `test` directory as well. For example, you may wish to create a
`test/models` directory for your model tests.
Providing Engine Functionality
------------------------------
The engine that this guide covers provides submitting articles and commenting
functionality and follows a similar thread to the [Getting Started
Guide](getting_started.html), with some new twists.
NOTE: For this section, make sure to run the commands in the root of the
`blorgh` engine's directory.
### Generating an Article Resource
The first thing to generate for a blog engine is the `Article` model and related
controller. To quickly generate this, you can use the Rails scaffold generator.
```bash
$ bin/rails generate scaffold article title:string text:text
```
This command will output this information:
```
invoke active_record
create db/migrate/[timestamp]_create_blorgh_articles.rb
create app/models/blorgh/article.rb
invoke test_unit
create test/models/blorgh/article_test.rb
create test/fixtures/blorgh/articles.yml
invoke resource_route
route resources :articles
invoke scaffold_controller
create app/controllers/blorgh/articles_controller.rb
invoke erb
create app/views/blorgh/articles
create app/views/blorgh/articles/index.html.erb
create app/views/blorgh/articles/edit.html.erb
create app/views/blorgh/articles/show.html.erb
create app/views/blorgh/articles/new.html.erb
create app/views/blorgh/articles/_form.html.erb
invoke test_unit
create test/controllers/blorgh/articles_controller_test.rb
create test/system/blorgh/articles_test.rb
invoke helper
create app/helpers/blorgh/articles_helper.rb
invoke test_unit
```
The first thing that the scaffold generator does is invoke the `active_record`
generator, which generates a migration and a model for the resource. Note here,
however, that the migration is called `create_blorgh_articles` rather than the
usual `create_articles`. This is due to the `isolate_namespace` method called in
the `Blorgh::Engine` class's definition. The model here is also namespaced,
being placed at `app/models/blorgh/article.rb` rather than `app/models/article.rb` due
to the `isolate_namespace` call within the `Engine` class.
Next, the `test_unit` generator is invoked for this model, generating a model
test at `test/models/blorgh/article_test.rb` (rather than
`test/models/article_test.rb`) and a fixture at `test/fixtures/blorgh/articles.yml`
(rather than `test/fixtures/articles.yml`).
After that, a line for the resource is inserted into the `config/routes.rb` file
for the engine. This line is simply `resources :articles`, turning the
`config/routes.rb` file for the engine into this:
```ruby
Blorgh::Engine.routes.draw do
resources :articles
end
```
Note here that the routes are drawn upon the `Blorgh::Engine` object rather than
the `YourApp::Application` class. This is so that the engine routes are confined
to the engine itself and can be mounted at a specific point as shown in the
[test directory](#test-directory) section. It also causes the engine's routes to
be isolated from those routes that are within the application. The
[Routes](#routes) section of this guide describes it in detail.
Next, the `scaffold_controller` generator is invoked, generating a controller
called `Blorgh::ArticlesController` (at
`app/controllers/blorgh/articles_controller.rb`) and its related views at
`app/views/blorgh/articles`. This generator also generates tests for the
controller (`test/controllers/blorgh/articles_controller_test.rb` and `test/system/blorgh/articles_test.rb`) and a helper (`app/helpers/blorgh/articles_helper.rb`).
Everything this generator has created is neatly namespaced. The controller's
class is defined within the `Blorgh` module:
```ruby
module Blorgh
class ArticlesController < ApplicationController
# ...
end
end
```
NOTE: The `ArticlesController` class inherits from
`Blorgh::ApplicationController`, not the application's `ApplicationController`.
The helper inside `app/helpers/blorgh/articles_helper.rb` is also namespaced:
```ruby
module Blorgh
module ArticlesHelper
# ...
end
end
```
This helps prevent conflicts with any other engine or application that may have
an article resource as well.
You can see what the engine has so far by running `bin/rails db:migrate` at the root
of our engine to run the migration generated by the scaffold generator, and then
running `bin/rails server` in `test/dummy`. When you open
`http://localhost:3000/blorgh/articles` you will see the default scaffold that has
been generated. Click around! You've just generated your first engine's first
functions.
If you'd rather play around in the console, `bin/rails console` will also work just
like a Rails application. Remember: the `Article` model is namespaced, so to
reference it you must call it as `Blorgh::Article`.
```irb
irb> Blorgh::Article.find(1)
=> #<Blorgh::Article id: 1 ...>
```
One final thing is that the `articles` resource for this engine should be the root
of the engine. Whenever someone goes to the root path where the engine is
mounted, they should be shown a list of articles. This can be made to happen if
this line is inserted into the `config/routes.rb` file inside the engine:
```ruby
root to: "articles#index"
```
Now people will only need to go to the root of the engine to see all the articles,
rather than visiting `/articles`. This means that instead of
`http://localhost:3000/blorgh/articles`, you only need to go to
`http://localhost:3000/blorgh` now.
### Generating a Comments Resource
Now that the engine can create new articles, it only makes sense to add
commenting functionality as well. To do this, you'll need to generate a comment
model, a comment controller, and then modify the articles scaffold to display
comments and allow people to create new ones.
From the engine root, run the model generator. Tell it to generate a
`Comment` model, with the related table having two columns: an `article_id` integer
and `text` text column.
```bash
$ bin/rails generate model Comment article_id:integer text:text
```
This will output the following:
```
invoke active_record
create db/migrate/[timestamp]_create_blorgh_comments.rb
create app/models/blorgh/comment.rb
invoke test_unit
create test/models/blorgh/comment_test.rb
create test/fixtures/blorgh/comments.yml
```
This generator call will generate just the necessary model files it needs,
namespacing the files under a `blorgh` directory and creating a model class
called `Blorgh::Comment`. Now run the migration to create our blorgh_comments
table:
```bash
$ bin/rails db:migrate
```
To show the comments on an article, edit `app/views/blorgh/articles/show.html.erb` and
add this line before the "Edit" link:
```html+erb
<h3>Comments</h3>
<%= render @article.comments %>
```
This line will require there to be a `has_many` association for comments defined
on the `Blorgh::Article` model, which there isn't right now. To define one, open
`app/models/blorgh/article.rb` and add this line into the model:
```ruby
has_many :comments
```
Turning the model into this:
```ruby
module Blorgh
class Article < ApplicationRecord
has_many :comments
end
end
```
NOTE: Because the `has_many` is defined inside a class that is inside the
`Blorgh` module, Rails will know that you want to use the `Blorgh::Comment`
model for these objects, so there's no need to specify that using the
`:class_name` option here.
Next, there needs to be a form so that comments can be created on an article. To
add this, put this line underneath the call to `render @article.comments` in
`app/views/blorgh/articles/show.html.erb`:
```erb
<%= render "blorgh/comments/form" %>
```
Next, the partial that this line will render needs to exist. Create a new
directory at `app/views/blorgh/comments` and in it a new file called
`_form.html.erb` which has this content to create the required partial:
```html+erb
<h3>New comment</h3>
<%= form_with model: [@article, @article.comments.build] do |form| %>
<p>
<%= form.label :text %><br>
<%= form.text_area :text %>
</p>
<%= form.submit %>
<% end %>
```
When this form is submitted, it is going to attempt to perform a `POST` request
to a route of `/articles/:article_id/comments` within the engine. This route doesn't
exist at the moment, but can be created by changing the `resources :articles` line
inside `config/routes.rb` into these lines:
```ruby
resources :articles do
resources :comments
end
```
This creates a nested route for the comments, which is what the form requires.
The route now exists, but the controller that this route goes to does not. To
create it, run this command from the engine root:
```bash
$ bin/rails generate controller comments
```
This will generate the following things:
```
create app/controllers/blorgh/comments_controller.rb
invoke erb
exist app/views/blorgh/comments
invoke test_unit
create test/controllers/blorgh/comments_controller_test.rb
invoke helper
create app/helpers/blorgh/comments_helper.rb
invoke test_unit
```
The form will be making a `POST` request to `/articles/:article_id/comments`, which
will correspond with the `create` action in `Blorgh::CommentsController`. This
action needs to be created, which can be done by putting the following lines
inside the class definition in `app/controllers/blorgh/comments_controller.rb`:
```ruby
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(comment_params)
flash[:notice] = "Comment has been created!"
redirect_to articles_path
end
private
def comment_params
params.require(:comment).permit(:text)
end
```
This is the final step required to get the new comment form working. Displaying
the comments, however, is not quite right yet. If you were to create a comment
right now, you would see this error:
```
Missing partial blorgh/comments/_comment with {:handlers=>[:erb, :builder],
:formats=>[:html], :locale=>[:en, :en]}. Searched in: *
"/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" *
"/Users/ryan/Sites/side_projects/blorgh/app/views"
```
The engine is unable to find the partial required for rendering the comments.
Rails looks first in the application's (`test/dummy`) `app/views` directory and
then in the engine's `app/views` directory. When it can't find it, it will throw
this error. The engine knows to look for `blorgh/comments/_comment` because the
model object it is receiving is from the `Blorgh::Comment` class.
This partial will be responsible for rendering just the comment text, for now.
Create a new file at `app/views/blorgh/comments/_comment.html.erb` and put this
line inside it:
```erb
<%= comment_counter + 1 %>. <%= comment.text %>
```
The `comment_counter` local variable is given to us by the `<%= render
@article.comments %>` call, which will define it automatically and increment the
counter as it iterates through each comment. It's used in this example to
display a small number next to each comment when it's created.
That completes the comment function of the blogging engine. Now it's time to use
it within an application.
Hooking Into an Application
---------------------------
Using an engine within an application is very easy. This section covers how to
mount the engine into an application and the initial setup required, as well as
linking the engine to a `User` class provided by the application to provide
ownership for articles and comments within the engine.
### Mounting the Engine
First, the engine needs to be specified inside the application's `Gemfile`. If
there isn't an application handy to test this out in, generate one using the
`rails new` command outside of the engine directory like this:
```bash
$ rails new unicorn
```
Usually, specifying the engine inside the `Gemfile` would be done by specifying it
as a normal, everyday gem.
```ruby
gem 'devise'
```
However, because you are developing the `blorgh` engine on your local machine,
you will need to specify the `:path` option in your `Gemfile`:
```ruby
gem 'blorgh', path: 'engines/blorgh'
```
Then run `bundle` to install the gem.
As described earlier, by placing the gem in the `Gemfile` it will be loaded when
Rails is loaded. It will first require `lib/blorgh.rb` from the engine, then
`lib/blorgh/engine.rb`, which is the file that defines the major pieces of
functionality for the engine.
To make the engine's functionality accessible from within an application, it
needs to be mounted in that application's `config/routes.rb` file:
```ruby
mount Blorgh::Engine, at: "/blog"
```
This line will mount the engine at `/blog` in the application. Making it
accessible at `http://localhost:3000/blog` when the application runs with `bin/rails
server`.
NOTE: Other engines, such as Devise, handle this a little differently by making
you specify custom helpers (such as `devise_for`) in the routes. These helpers
do exactly the same thing, mounting pieces of the engines's functionality at a
pre-defined path which may be customizable.
### Engine Setup
The engine contains migrations for the `blorgh_articles` and `blorgh_comments`
table which need to be created in the application's database so that the
engine's models can query them correctly. To copy these migrations into the
application run the following command from the application's root:
```bash
$ bin/rails blorgh:install:migrations
```
If you have multiple engines that need migrations copied over, use
`railties:install:migrations` instead:
```bash
$ bin/rails railties:install:migrations
```
This command, when run for the first time, will copy over all the migrations
from the engine. When run the next time, it will only copy over migrations that
haven't been copied over already. The first run for this command will output
something such as this:
```
Copied migration [timestamp_1]_create_blorgh_articles.blorgh.rb from blorgh
Copied migration [timestamp_2]_create_blorgh_comments.blorgh.rb from blorgh
```
The first timestamp (`[timestamp_1]`) will be the current time, and the second
timestamp (`[timestamp_2]`) will be the current time plus a second. The reason
for this is so that the migrations for the engine are run after any existing
migrations in the application.
To run these migrations within the context of the application, simply run `bin/rails
db:migrate`. When accessing the engine through `http://localhost:3000/blog`, the
articles will be empty. This is because the table created inside the application is
different from the one created within the engine. Go ahead, play around with the
newly mounted engine. You'll find that it's the same as when it was only an
engine.
If you would like to run migrations only from one engine, you can do it by
specifying `SCOPE`:
```bash
$ bin/rails db:migrate SCOPE=blorgh
```
This may be useful if you want to revert engine's migrations before removing it.
To revert all migrations from blorgh engine you can run code such as:
```bash
$ bin/rails db:migrate SCOPE=blorgh VERSION=0
```
### Using a Class Provided by the Application
#### Using a Model Provided by the Application
When an engine is created, it may want to use specific classes from an
application to provide links between the pieces of the engine and the pieces of
the application. In the case of the `blorgh` engine, making articles and comments
have authors would make a lot of sense.
A typical application might have a `User` class that would be used to represent
authors for an article or a comment. But there could be a case where the
application calls this class something different, such as `Person`. For this
reason, the engine should not hardcode associations specifically for a `User`
class.
To keep it simple in this case, the application will have a class called `User`
that represents the users of the application (we'll get into making this
configurable further on). It can be generated using this command inside the
application:
```bash
$ bin/rails generate model user name:string
```
The `bin/rails db:migrate` command needs to be run here to ensure that our
application has the `users` table for future use.
Also, to keep it simple, the articles form will have a new text field called
`author_name`, where users can elect to put their name. The engine will then
take this name and either create a new `User` object from it, or find one that
already has that name. The engine will then associate the article with the found or
created `User` object.
First, the `author_name` text field needs to be added to the
`app/views/blorgh/articles/_form.html.erb` partial inside the engine. This can be
added above the `title` field with this code:
```html+erb
<div class="field">
<%= form.label :author_name %><br>
<%= form.text_field :author_name %>
</div>
```
Next, we need to update our `Blorgh::ArticlesController#article_params` method to
permit the new form parameter:
```ruby
def article_params
params.require(:article).permit(:title, :text, :author_name)
end
```
The `Blorgh::Article` model should then have some code to convert the `author_name`
field into an actual `User` object and associate it as that article's `author`
before the article is saved. It will also need to have an `attr_accessor` set up
for this field, so that the setter and getter methods are defined for it.
To do all this, you'll need to add the `attr_accessor` for `author_name`, the
association for the author and the `before_validation` call into
`app/models/blorgh/article.rb`. The `author` association will be hard-coded to the
`User` class for the time being.
```ruby
attr_accessor :author_name
belongs_to :author, class_name: "User"
before_validation :set_author
private
def set_author
self.author = User.find_or_create_by(name: author_name)
end
```
By representing the `author` association's object with the `User` class, a link
is established between the engine and the application. There needs to be a way
of associating the records in the `blorgh_articles` table with the records in the
`users` table. Because the association is called `author`, there should be an
`author_id` column added to the `blorgh_articles` table.
To generate this new column, run this command within the engine:
```bash
$ bin/rails generate migration add_author_id_to_blorgh_articles author_id:integer
```
NOTE: Due to the migration's name and the column specification after it, Rails
will automatically know that you want to add a column to a specific table and
write that into the migration for you. You don't need to tell it any more than
this.
This migration will need to be run on the application. To do that, it must first
be copied using this command:
```bash
$ bin/rails blorgh:install:migrations
```
Notice that only _one_ migration was copied over here. This is because the first
two migrations were copied over the first time this command was run.
```
NOTE Migration [timestamp]_create_blorgh_articles.blorgh.rb from blorgh has been skipped. Migration with the same name already exists.
NOTE Migration [timestamp]_create_blorgh_comments.blorgh.rb from blorgh has been skipped. Migration with the same name already exists.
Copied migration [timestamp]_add_author_id_to_blorgh_articles.blorgh.rb from blorgh
```
Run the migration using:
```bash
$ bin/rails db:migrate
```
Now with all the pieces in place, an action will take place that will associate
an author - represented by a record in the `users` table - with an article,
represented by the `blorgh_articles` table from the engine.
Finally, the author's name should be displayed on the article's page. Add this code
above the "Title" output inside `app/views/blorgh/articles/show.html.erb`:
```html+erb
<p>
<b>Author:</b>
<%= @article.author.name %>
</p>
```
#### Using a Controller Provided by the Application
Because Rails controllers generally share code for things like authentication
and accessing session variables, they inherit from `ApplicationController` by
default. Rails engines, however are scoped to run independently from the main
application, so each engine gets a scoped `ApplicationController`. This
namespace prevents code collisions, but often engine controllers need to access
methods in the main application's `ApplicationController`. An easy way to
provide this access is to change the engine's scoped `ApplicationController` to
inherit from the main application's `ApplicationController`. For our Blorgh
engine this would be done by changing
`app/controllers/blorgh/application_controller.rb` to look like:
```ruby
module Blorgh
class ApplicationController < ::ApplicationController
end
end
```
By default, the engine's controllers inherit from
`Blorgh::ApplicationController`. So, after making this change they will have
access to the main application's `ApplicationController`, as though they were
part of the main application.
This change does require that the engine is run from a Rails application that
has an `ApplicationController`.
### Configuring an Engine
This section covers how to make the `User` class configurable, followed by
general configuration tips for the engine.
#### Setting Configuration Settings in the Application
The next step is to make the class that represents a `User` in the application
customizable for the engine. This is because that class may not always be
`User`, as previously explained. To make this setting customizable, the engine
will have a configuration setting called `author_class` that will be used to
specify which class represents users inside the application.
To define this configuration setting, you should use a `mattr_accessor` inside
the `Blorgh` module for the engine. Add this line to `lib/blorgh.rb` inside the
engine:
```ruby
mattr_accessor :author_class
```
This method works like its siblings, `attr_accessor` and `cattr_accessor`, but
provides a setter and getter method on the module with the specified name. To
use it, it must be referenced using `Blorgh.author_class`.
The next step is to switch the `Blorgh::Article` model over to this new setting.
Change the `belongs_to` association inside this model
(`app/models/blorgh/article.rb`) to this:
```ruby
belongs_to :author, class_name: Blorgh.author_class
```
The `set_author` method in the `Blorgh::Article` model should also use this class:
```ruby
self.author = Blorgh.author_class.constantize.find_or_create_by(name: author_name)
```
To save having to call `constantize` on the `author_class` result all the time,
you could instead just override the `author_class` getter method inside the
`Blorgh` module in the `lib/blorgh.rb` file to always call `constantize` on the
saved value before returning the result:
```ruby
def self.author_class
@@author_class.constantize
end
```
This would then turn the above code for `set_author` into this:
```ruby
self.author = Blorgh.author_class.find_or_create_by(name: author_name)
```
Resulting in something a little shorter, and more implicit in its behavior. The
`author_class` method should always return a `Class` object.
Since we changed the `author_class` method to return a `Class` instead of a
`String`, we must also modify our `belongs_to` definition in the `Blorgh::Article`
model:
```ruby
belongs_to :author, class_name: Blorgh.author_class.to_s
```
To set this configuration setting within the application, an initializer should
be used. By using an initializer, the configuration will be set up before the
application starts and calls the engine's models, which may depend on this
configuration setting existing.
Create a new initializer at `config/initializers/blorgh.rb` inside the
application where the `blorgh` engine is installed and put this content in it:
```ruby
Blorgh.author_class = "User"
```
WARNING: It's very important here to use the `String` version of the class,
rather than the class itself. If you were to use the class, Rails would attempt
to load that class and then reference the related table. This could lead to
problems if the table didn't already exist. Therefore, a `String` should be
used and then converted to a class using `constantize` in the engine later on.
Go ahead and try to create a new article. You will see that it works exactly in the
same way as before, except this time the engine is using the configuration
setting in `config/initializers/blorgh.rb` to learn what the class is.
There are now no strict dependencies on what the class is, only what the API for
the class must be. The engine simply requires this class to define a
`find_or_create_by` method which returns an object of that class, to be
associated with an article when it's created. This object, of course, should have
some sort of identifier by which it can be referenced.
#### General Engine Configuration
Within an engine, there may come a time where you wish to use things such as
initializers, internationalization, or other configuration options. The great
news is that these things are entirely possible, because a Rails engine shares
much the same functionality as a Rails application. In fact, a Rails
application's functionality is actually a superset of what is provided by
engines!
If you wish to use an initializer - code that should run before the engine is
loaded - the place for it is the `config/initializers` folder. This directory's
functionality is explained in the [Initializers
section](configuring.html#initializers) of the Configuring guide, and works
precisely the same way as the `config/initializers` directory inside an
application. The same thing goes if you want to use a standard initializer.
For locales, simply place the locale files in the `config/locales` directory,
just like you would in an application.
Testing an Engine
-----------------
When an engine is generated, there is a smaller dummy application created inside
it at `test/dummy`. This application is used as a mounting point for the engine,
to make testing the engine extremely simple. You may extend this application by
generating controllers, models, or views from within the directory, and then use
those to test your engine.
The `test` directory should be treated like a typical Rails testing environment,
allowing for unit, functional, and integration tests.
### Functional Tests
A matter worth taking into consideration when writing functional tests is that
the tests are going to be running on an application - the `test/dummy`
application - rather than your engine. This is due to the setup of the testing
environment; an engine needs an application as a host for testing its main
functionality, especially controllers. This means that if you were to make a
typical `GET` to a controller in a controller's functional test like this:
```ruby
module Blorgh
class FooControllerTest < ActionDispatch::IntegrationTest
include Engine.routes.url_helpers
def test_index
get foos_url
# ...
end
end
end
```
It may not function correctly. This is because the application doesn't know how
to route these requests to the engine unless you explicitly tell it **how**. To
do this, you must set the `@routes` instance variable to the engine's route set
in your setup code:
```ruby
module Blorgh
class FooControllerTest < ActionDispatch::IntegrationTest
include Engine.routes.url_helpers
setup do
@routes = Engine.routes
end
def test_index
get foos_url
# ...
end
end
end
```
This tells the application that you still want to perform a `GET` request to the
`index` action of this controller, but you want to use the engine's route to get
there, rather than the application's one.
This also ensures that the engine's URL helpers will work as expected in your
tests.
Improving Engine Functionality
------------------------------
This section explains how to add and/or override engine MVC functionality in the
main Rails application.
### Overriding Models and Controllers
Engine models and controllers can be reopened by the parent application to extend or decorate them.
Overrides may be organized in a dedicated directory `app/overrides` that is preloaded in a `to_prepare` callback.
In `zeitwerk` mode you'd do this:
```ruby
# config/application.rb
module MyApp
class Application < Rails::Application
# ...
overrides = "#{Rails.root}/app/overrides"
Rails.autoloaders.main.ignore(overrides)
config.to_prepare do
Dir.glob("#{overrides}/**/*_override.rb").each do |override|
load override
end
end
end
end
```
and in `classic` mode this:
```ruby
# config/application.rb
module MyApp
class Application < Rails::Application
# ...
config.to_prepare do
Dir.glob("#{Rails.root}/app/overrides/**/*_override.rb").each do |override|
require_dependency override
end
end
end
end
```
#### Reopening existing classes using `class_eval`
For example, in order to override the engine model
```ruby
# Blorgh/app/models/blorgh/article.rb
module Blorgh
class Article < ApplicationRecord
has_many :comments
def summary
"#{title}"
end
end
end
```
you just create a file that _reopens_ that class:
```ruby
# MyApp/app/overrides/models/blorgh/article_override.rb
Blorgh::Article.class_eval do
def time_since_created
Time.current - created_at
end
def summary
"#{title} - #{truncate(text)}"
end
end
```
It is very important that the override _reopens_ the class or module. Using the `class` or `module` keywords would define them if they were not already in memory, which would be incorrect because the definition lives in the engine. Using `class_eval` as shown above ensures you are reopening.
#### Reopening existing classes using ActiveSupport::Concern
Using `Class#class_eval` is great for simple adjustments, but for more complex
class modifications, you might want to consider using [`ActiveSupport::Concern`]
(https://api.rubyonrails.org/classes/ActiveSupport/Concern.html).
ActiveSupport::Concern manages load order of interlinked dependent modules and
classes at run time allowing you to significantly modularize your code.
**Adding** `Article#time_since_created` and **Overriding** `Article#summary`:
```ruby
# MyApp/app/models/blorgh/article.rb
class Blorgh::Article < ApplicationRecord
include Blorgh::Concerns::Models::Article
def time_since_created
Time.current - created_at
end
def summary
"#{title} - #{truncate(text)}"
end
end
```
```ruby
# Blorgh/app/models/blorgh/article.rb
module Blorgh
class Article < ApplicationRecord
include Blorgh::Concerns::Models::Article
end
end
```
```ruby
# Blorgh/lib/concerns/models/article.rb
module Blorgh::Concerns::Models::Article
extend ActiveSupport::Concern
# 'included do' causes the included code to be evaluated in the
# context where it is included (article.rb), rather than being
# executed in the module's context (blorgh/concerns/models/article).
included do
attr_accessor :author_name
belongs_to :author, class_name: "User"
before_validation :set_author
private
def set_author
self.author = User.find_or_create_by(name: author_name)
end
end
def summary
"#{title}"
end
module ClassMethods
def some_class_method
'some class method string'
end
end
end
```
### Autoloading and Engines
Please check the [Autoloading and Reloading Constants](autoloading_and_reloading_constants.html#autoloading-and-engines)
guide for more information about autoloading and engines.
### Overriding Views
When Rails looks for a view to render, it will first look in the `app/views`
directory of the application. If it cannot find the view there, it will check in
the `app/views` directories of all engines that have this directory.
When the application is asked to render the view for `Blorgh::ArticlesController`'s
index action, it will first look for the path
`app/views/blorgh/articles/index.html.erb` within the application. If it cannot
find it, it will look inside the engine.
You can override this view in the application by simply creating a new file at
`app/views/blorgh/articles/index.html.erb`. Then you can completely change what
this view would normally output.
Try this now by creating a new file at `app/views/blorgh/articles/index.html.erb`
and put this content in it:
```html+erb
<h1>Articles</h1>
<%= link_to "New Article", new_article_path %>
<% @articles.each do |article| %>
<h2><%= article.title %></h2>
<small>By <%= article.author %></small>
<%= simple_format(article.text) %>
<hr>
<% end %>
```
### Routes
Routes inside an engine are isolated from the application by default. This is
done by the `isolate_namespace` call inside the `Engine` class. This essentially
means that the application and its engines can have identically named routes and
they will not clash.
Routes inside an engine are drawn on the `Engine` class within
`config/routes.rb`, like this:
```ruby
Blorgh::Engine.routes.draw do
resources :articles
end
```
By having isolated routes such as this, if you wish to link to an area of an
engine from within an application, you will need to use the engine's routing
proxy method. Calls to normal routing methods such as `articles_path` may end up
going to undesired locations if both the application and the engine have such a
helper defined.
For instance, the following example would go to the application's `articles_path`
if that template was rendered from the application, or the engine's `articles_path`
if it was rendered from the engine:
```erb
<%= link_to "Blog articles", articles_path %>
```
To make this route always use the engine's `articles_path` routing helper method,
we must call the method on the routing proxy method that shares the same name as
the engine.
```erb
<%= link_to "Blog articles", blorgh.articles_path %>
```
If you wish to reference the application inside the engine in a similar way, use
the `main_app` helper:
```erb
<%= link_to "Home", main_app.root_path %>
```
If you were to use this inside an engine, it would **always** go to the
application's root. If you were to leave off the `main_app` "routing proxy"
method call, it could potentially go to the engine's or application's root,
depending on where it was called from.
If a template rendered from within an engine attempts to use one of the
application's routing helper methods, it may result in an undefined method call.
If you encounter such an issue, ensure that you're not attempting to call the
application's routing methods without the `main_app` prefix from within the
engine.
### Assets
Assets within an engine work in an identical way to a full application. Because
the engine class inherits from `Rails::Engine`, the application will know to
look up assets in the engine's `app/assets` and `lib/assets` directories.
Like all of the other components of an engine, the assets should be namespaced.
This means that if you have an asset called `style.css`, it should be placed at
`app/assets/stylesheets/[engine name]/style.css`, rather than
`app/assets/stylesheets/style.css`. If this asset isn't namespaced, there is a
possibility that the host application could have an asset named identically, in
which case the application's asset would take precedence and the engine's one
would be ignored.
Imagine that you did have an asset located at
`app/assets/stylesheets/blorgh/style.css`. To include this asset inside an
application, just use `stylesheet_link_tag` and reference the asset as if it
were inside the engine:
```erb
<%= stylesheet_link_tag "blorgh/style.css" %>
```
You can also specify these assets as dependencies of other assets using Asset
Pipeline require statements in processed files:
```css
/*
*= require blorgh/style
*/
```
INFO. Remember that in order to use languages like Sass or CoffeeScript, you
should add the relevant library to your engine's `.gemspec`.
### Separate Assets and Precompiling
There are some situations where your engine's assets are not required by the
host application. For example, say that you've created an admin functionality
that only exists for your engine. In this case, the host application doesn't
need to require `admin.css` or `admin.js`. Only the gem's admin layout needs
these assets. It doesn't make sense for the host app to include
`"blorgh/admin.css"` in its stylesheets. In this situation, you should
explicitly define these assets for precompilation. This tells Sprockets to add
your engine assets when `bin/rails assets:precompile` is triggered.
You can define assets for precompilation in `engine.rb`:
```ruby
initializer "blorgh.assets.precompile" do |app|
app.config.assets.precompile += %w( admin.js admin.css )
end
```
For more information, read the [Asset Pipeline guide](asset_pipeline.html).
### Other Gem Dependencies
Gem dependencies inside an engine should be specified inside the `.gemspec` file
at the root of the engine. The reason is that the engine may be installed as a
gem. If dependencies were to be specified inside the `Gemfile`, these would not
be recognized by a traditional gem install and so they would not be installed,
causing the engine to malfunction.
To specify a dependency that should be installed with the engine during a
traditional `gem install`, specify it inside the `Gem::Specification` block
inside the `.gemspec` file in the engine:
```ruby
s.add_dependency "moo"
```
To specify a dependency that should only be installed as a development
dependency of the application, specify it like this:
```ruby
s.add_development_dependency "moo"
```
Both kinds of dependencies will be installed when `bundle install` is run inside
of the application. The development dependencies for the gem will only be used
when the development and tests for the engine are running.
Note that if you want to immediately require dependencies when the engine is
required, you should require them before the engine's initialization. For
example:
```ruby
require "other_engine/engine"
require "yet_another_engine/engine"
module MyEngine
class Engine < ::Rails::Engine
end
end
```
Load and Configuration Hooks
----------------------------
Rails code can often be referenced on load of an application. Rails is responsible for the load order of these frameworks, so when you load frameworks, such as `ActiveRecord::Base`, prematurely you are violating an implicit contract your application has with Rails. Moreover, by loading code such as `ActiveRecord::Base` on boot of your application you are loading entire frameworks which may slow down your boot time and could cause conflicts with load order and boot of your application.
Load and configuration hooks are the API that allow you to hook into this initialization process without violating the load contract with Rails. This will also mitigate boot performance degradation and avoid conflicts.
### Avoid loading Rails Frameworks
Since Ruby is a dynamic language, some code will cause different Rails frameworks to load. Take this snippet for instance:
```ruby
ActiveRecord::Base.include(MyActiveRecordHelper)
```
This snippet means that when this file is loaded, it will encounter `ActiveRecord::Base`. This encounter causes Ruby to look for the definition of that constant and will require it. This causes the entire Active Record framework to be loaded on boot.
`ActiveSupport.on_load` is a mechanism that can be used to defer the loading of code until it is actually needed. The snippet above can be changed to:
```ruby
ActiveSupport.on_load(:active_record) do
include MyActiveRecordHelper
end
```
This new snippet will only include `MyActiveRecordHelper` when `ActiveRecord::Base` is loaded.
### When are Hooks called?
In the Rails framework these hooks are called when a specific library is loaded. For example, when `ActionController::Base` is loaded, the `:action_controller_base` hook is called. This means that all `ActiveSupport.on_load` calls with `:action_controller_base` hooks will be called in the context of `ActionController::Base` (that means `self` will be an `ActionController::Base`).
### Modifying Code to use Load Hooks
Modifying code is generally straightforward. If you have a line of code that refers to a Rails framework such as `ActiveRecord::Base` you can wrap that code in a load hook.
**Modifying calls to `include`**
```ruby
ActiveRecord::Base.include(MyActiveRecordHelper)
```
becomes
```ruby
ActiveSupport.on_load(:active_record) do
# self refers to ActiveRecord::Base here,
# so we can call .include
include MyActiveRecordHelper
end
```
**Modifying calls to `prepend`**
```ruby
ActionController::Base.prepend(MyActionControllerHelper)
```
becomes
```ruby
ActiveSupport.on_load(:action_controller_base) do
# self refers to ActionController::Base here,
# so we can call .prepend
prepend MyActionControllerHelper
end
```
**Modifying calls to class methods**
```ruby
ActiveRecord::Base.include_root_in_json = true
```
becomes
```ruby
ActiveSupport.on_load(:active_record) do
# self refers to ActiveRecord::Base here
self.include_root_in_json = true
end
```
### Available Load Hooks
These are the load hooks you can use in your own code. To hook into the initialization process of one of the following classes use the available hook.
| Class | Hook |
| -------------------------------------| ------------------------------------ |
| `ActionCable` | `action_cable` |
| `ActionCable::Channel::Base` | `action_cable_channel` |
| `ActionCable::Connection::Base` | `action_cable_connection` |
| `ActionCable::Connection::TestCase` | `action_cable_connection_test_case` |
| `ActionController::API` | `action_controller_api` |
| `ActionController::API` | `action_controller` |
| `ActionController::Base` | `action_controller_base` |
| `ActionController::Base` | `action_controller` |
| `ActionController::TestCase` | `action_controller_test_case` |
| `ActionDispatch::IntegrationTest` | `action_dispatch_integration_test` |
| `ActionDispatch::Response` | `action_dispatch_response` |
| `ActionDispatch::Request` | `action_dispatch_request` |
| `ActionDispatch::SystemTestCase` | `action_dispatch_system_test_case` |
| `ActionMailbox::Base` | `action_mailbox` |
| `ActionMailbox::InboundEmail` | `action_mailbox_inbound_email` |
| `ActionMailbox::Record` | `action_mailbox_record` |
| `ActionMailbox::TestCase` | `action_mailbox_test_case` |
| `ActionMailer::Base` | `action_mailer` |
| `ActionMailer::TestCase` | `action_mailer_test_case` |
| `ActionText::Content` | `action_text_content` |
| `ActionText::Record` | `action_text_record` |
| `ActionText::RichText` | `action_text_rich_text` |
| `ActionView::Base` | `action_view` |
| `ActionView::TestCase` | `action_view_test_case` |
| `ActiveJob::Base` | `active_job` |
| `ActiveJob::TestCase` | `active_job_test_case` |
| `ActiveRecord::Base` | `active_record` |
| `ActiveStorage::Attachment` | `active_storage_attachment` |
| `ActiveStorage::VariantRecord` | `active_storage_variant_record` |
| `ActiveStorage::Blob` | `active_storage_blob` |
| `ActiveStorage::Record` | `active_storage_record` |
| `ActiveSupport::TestCase` | `active_support_test_case` |
| `i18n` | `i18n` |
### Available Configuration Hooks
Configuration hooks do not hook into any particular framework, but instead they run in context of the entire application.
| Hook | Use Case |
| ---------------------- | ---------------------------------------------------------------------------------- |
| `before_configuration` | First configurable block to run. Called before any initializers are run. |
| `before_initialize` | Second configurable block to run. Called before frameworks initialize. |
| `before_eager_load` | Third configurable block to run. Does not run if `config.eager_load` set to false. |
| `after_initialize` | Last configurable block to run. Called after frameworks initialize. |
Configuration hooks can be called in the Engine class.
```ruby
module Blorgh
class Engine < ::Rails::Engine
config.before_configuration do
puts 'I am called before any initializers'
end
end
end
```
| yasslab/railsguides.jp | guides/source/engines.md | Markdown | mit | 57,865 |
<p>Magra is a sans serif typeface designed for contexts in which both spatial economy and multiple composition styles are required. Its neutral personality and humanist features makes it a perfect candidate for corporate uses too. Its large x-height and robust stems provide good legibility and economy, plus great behavior in smaller sizes. Magra was selected to be part of the German editorial project Typodarium 2012.</p> | xErik/pdfmake-fonts-google | lib/ofl/magra/DESCRIPTION.en_us.html | HTML | mit | 424 |
title: SVG 图形
type: 示例
order: 5
---
> 这个示例展示了对自定义组件、计算属性、双向绑定和 SVG 支持的结合。
<iframe width="100%" height="500" src="http://jsfiddle.net/yyx990803/bbt0f3nz/embedded/result,html,js,css" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
| zyj1022/vuejs.org | source/examples/svg.md | Markdown | mit | 311 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace spec\Sylius\Bundle\CoreBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\User\Canonicalizer\CanonicalizerInterface;
/**
* @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
*/
final class CanonicalizerListenerSpec extends ObjectBehavior
{
function let(CanonicalizerInterface $canonicalizer): void
{
$this->beConstructedWith($canonicalizer);
}
function it_canonicalize_user_username_on_pre_persist_doctrine_event($canonicalizer, LifecycleEventArgs $event, ShopUserInterface $user): void
{
$event->getEntity()->willReturn($user);
$user->getUsername()->willReturn('testUser');
$user->getEmail()->willReturn('test@email.com');
$user->setUsernameCanonical('testuser')->shouldBeCalled();
$user->setEmailCanonical('test@email.com')->shouldBeCalled();
$canonicalizer->canonicalize('testUser')->willReturn('testuser')->shouldBeCalled();
$canonicalizer->canonicalize('test@email.com')->willReturn('test@email.com')->shouldBeCalled();
$this->prePersist($event);
}
function it_canonicalize_customer_email_on_pre_persist_doctrine_event($canonicalizer, LifecycleEventArgs $event, CustomerInterface $customer): void
{
$event->getEntity()->willReturn($customer);
$customer->getEmail()->willReturn('testUser@Email.com');
$customer->setEmailCanonical('testuser@email.com')->shouldBeCalled();
$canonicalizer->canonicalize('testUser@Email.com')->willReturn('testuser@email.com')->shouldBeCalled();
$this->prePersist($event);
}
function it_canonicalize_user_username_on_pre_update_doctrine_event($canonicalizer, LifecycleEventArgs $event, ShopUserInterface $user): void
{
$event->getEntity()->willReturn($user);
$user->getUsername()->willReturn('testUser');
$user->getEmail()->willReturn('test@email.com');
$user->setUsernameCanonical('testuser')->shouldBeCalled();
$user->setEmailCanonical('test@email.com')->shouldBeCalled();
$canonicalizer->canonicalize('testUser')->willReturn('testuser')->shouldBeCalled();
$canonicalizer->canonicalize('test@email.com')->willReturn('test@email.com')->shouldBeCalled();
$this->preUpdate($event);
}
function it_canonicalize_customer_email_on_pre_update_doctrine_event($canonicalizer, LifecycleEventArgs $event, CustomerInterface $customer): void
{
$event->getEntity()->willReturn($customer);
$customer->getEmail()->willReturn('testUser@Email.com');
$customer->setEmailCanonical('testuser@email.com')->shouldBeCalled();
$canonicalizer->canonicalize('testUser@Email.com')->willReturn('testuser@email.com')->shouldBeCalled();
$this->preUpdate($event);
}
function it_canonicalize_only_user_or_customer_interface_implementation_on_pre_presist($canonicalizer, LifecycleEventArgs $event): void
{
$item = new \stdClass();
$event->getEntity()->willReturn($item);
$canonicalizer->canonicalize(Argument::any())->shouldNotBeCalled();
$this->prePersist($event);
}
function it_canonicalize_only_user_or_customer_interface_implementation_on_pre_update($canonicalizer, LifecycleEventArgs $event): void
{
$item = new \stdClass();
$event->getEntity()->willReturn($item);
$canonicalizer->canonicalize(Argument::any())->shouldNotBeCalled();
$this->preUpdate($event);
}
}
| rainlike/justshop | vendor/sylius/sylius/src/Sylius/Bundle/CoreBundle/spec/EventListener/CanonicalizerListenerSpec.php | PHP | mit | 3,904 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<TITLE>
Uses of Class org.apache.poi.hmef.Attachment (POI API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.hmef.Attachment (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/poi/hmef/Attachment.html" title="class in org.apache.poi.hmef"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/hmef/\class-useAttachment.html" target="_top"><B>FRAMES</B></A>
<A HREF="Attachment.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.hmef.Attachment</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/poi/hmef/Attachment.html" title="class in org.apache.poi.hmef">Attachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.hmef"><B>org.apache.poi.hmef</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.hmef"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/poi/hmef/Attachment.html" title="class in org.apache.poi.hmef">Attachment</A> in <A HREF="../../../../../org/apache/poi/hmef/package-summary.html">org.apache.poi.hmef</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/apache/poi/hmef/package-summary.html">org.apache.poi.hmef</A> that return types with arguments of type <A HREF="../../../../../org/apache/poi/hmef/Attachment.html" title="class in org.apache.poi.hmef">Attachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List<<A HREF="../../../../../org/apache/poi/hmef/Attachment.html" title="class in org.apache.poi.hmef">Attachment</A>></CODE></FONT></TD>
<TD><CODE><B>HMEFMessage.</B><B><A HREF="../../../../../org/apache/poi/hmef/HMEFMessage.html#getAttachments()">getAttachments</A></B>()</CODE>
<BR>
Returns all the Attachments of the message.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/poi/hmef/Attachment.html" title="class in org.apache.poi.hmef"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/hmef/\class-useAttachment.html" target="_top"><B>FRAMES</B></A>
<A HREF="Attachment.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2016 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
| Sebaxtian/KDD | poi-3.14/docs/apidocs/org/apache/poi/hmef/class-use/Attachment.html | HTML | mit | 7,936 |
<h1>Pin audio file from SoundCloud</h1>
<form id="webaudioUploadFromComputer" name="webaudio_form" method="post" action="/webaudio_action" >
<p> </p>
Pin From :
<input type="radio" name="sub" value="local"/> Local
<input type="radio" name="sub" value="web" checked/> SoundCloud
<p> </p>
<select name="board_id" id="board_id" required class="inputText">
<option value="" selected="selected">Select Board</option>
{{#each boards}}
<option value="{{this._id}}">{{this.board_name}}</option>
{{/each}}
</select>
<p> </p>
<input type="text" class="inputText" name="audio_link" id="audio_link" value="" placeholder="Audio File Link" required/>
<!-- <input type="button" id="get_song" value="Find Song">-->
<div id="show_song" style="width:65%; margin:15px auto 0 15px;"></div>
<br />
<textarea name="description" id="description" placeholder="Description" required class="inputText" ></textarea>
<p> </p>
<!-- <input type="submit" name="upload_webaudio" id="upload_webaudio" value="Upload" />-->
</form>
<script>
$("input[type=radio][name=sub]").unbind('click').bind('click',function(){
var sub = $("input[type=radio][name=sub]:checked").val();
if(sub=='local'){
$("#pop_cont").load('/audio_upload',function(){
$('#get_img').html('Upload');
$('#get_img').unbind('click').bind('click',function(){
$("#audioUploadFromComputer").validate();
$('#audioUploadFromComputer').submit();
});
});
}
});
</script> | peishenwu/pcboy_myyna | application/views/default/pin_image/webaudio_form.html | HTML | mit | 1,753 |
<form name="deleteForm" ng-submit="confirmDelete(user.login)">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"
ng-click="clear()">×</button>
<h4 class="modal-title">Confirm delete operation</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this User?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="clear()">
<span class="glyphicon glyphicon-ban-circle"></span> <span>Cancel</span>
</button>
<button type="submit" ng-disabled="deleteForm.$invalid" class="btn btn-danger">
<span class="glyphicon glyphicon-remove-circle"></span> <span>Delete</span>
</button>
</div>
</form>
| spedepekka/skilldemon-server | src/main/webapp/scripts/app/admin/user-management/user-management-delete-dialog.html | HTML | mit | 853 |
<!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=US-ASCII">
<title>Class template visitor_ptr_t</title>
<link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../variant/reference.html#header.boost.variant.visitor_ptr_hpp" title="Header <boost/variant/visitor_ptr.hpp>">
<link rel="prev" href="static_visitor.html" title="Class template static_visitor">
<link rel="next" href="visitor_ptr.html" title="Function template visitor_ptr">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td>
<td align="center"><a href="../../../index.html">Home</a></td>
<td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="static_visitor.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../variant/reference.html#header.boost.variant.visitor_ptr_hpp"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="visitor_ptr.html"><img src="../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.visitor_ptr_t"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Class template visitor_ptr_t</span></h2>
<p>boost::visitor_ptr_t — Adapts a function pointer for use as a static visitor.</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../variant/reference.html#header.boost.variant.visitor_ptr_hpp" title="Header <boost/variant/visitor_ptr.hpp>">boost/variant/visitor_ptr.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> T<span class="special">,</span> <span class="keyword">typename</span> R<span class="special">></span>
<span class="keyword">class</span> <a class="link" href="visitor_ptr_t.html" title="Class template visitor_ptr_t">visitor_ptr_t</a> <span class="special">:</span> <span class="keyword">public</span> <a class="link" href="static_visitor.html" title="Class template static_visitor">static_visitor</a><span class="special"><</span><span class="identifier">R</span><span class="special">></span> <span class="special">{</span>
<span class="keyword">public</span><span class="special">:</span>
<span class="comment">// <a class="link" href="visitor_ptr_t.html#boost.visitor_ptr_tconstruct-copy-destruct">construct/copy/destruct</a></span>
<span class="keyword">explicit</span> <a class="link" href="visitor_ptr_t.html#id-1_3_46_5_13_1_1_5-bb"><span class="identifier">visitor_ptr_t</span></a><span class="special">(</span><span class="identifier">R</span> <span class="special">(</span><span class="special">*</span><span class="special">)</span><span class="special">(</span><span class="identifier">T</span><span class="special">)</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="visitor_ptr_t.html#id-1_3_46_5_13_1_1_6-bb">static visitor interfaces</a></span>
<span class="identifier">R</span> <a class="link" href="visitor_ptr_t.html#id-1_3_46_5_13_1_1_6_1_1-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="emphasis"><em><span class="identifier">unspecified</span><span class="special">-</span><span class="identifier">forwarding</span><span class="special">-</span><span class="identifier">type</span></em></span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> U<span class="special">></span> <span class="keyword">void</span> <a class="link" href="visitor_ptr_t.html#id-1_3_46_5_13_1_1_6_1_2-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">U</span><span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="id-1.3.46.5.14.3.4"></a><h2>Description</h2>
<p>Adapts the function given at construction for use as a
<a class="link" href="../variant/reference.html#variant.concepts.static-visitor" title="StaticVisitor">static visitor</a>
of type <code class="computeroutput">T</code> with result type <code class="computeroutput">R</code>.</p>
<div class="refsect2">
<a name="id-1.3.46.5.14.3.4.3"></a><h3>
<a name="boost.visitor_ptr_tconstruct-copy-destruct"></a><code class="computeroutput">visitor_ptr_t</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<pre class="literallayout"><span class="keyword">explicit</span> <a name="id-1_3_46_5_13_1_1_5-bb"></a><span class="identifier">visitor_ptr_t</span><span class="special">(</span><span class="identifier">R</span> <span class="special">(</span><span class="special">*</span><span class="special">)</span><span class="special">(</span><span class="identifier">T</span><span class="special">)</span><span class="special">)</span><span class="special">;</span></pre>
<div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody><tr>
<td><p><span class="term">Effects:</span></p></td>
<td>Constructs the visitor with the given function.</td>
</tr></tbody>
</table></div>
</li></ol></div>
</div>
<div class="refsect2">
<a name="id-1.3.46.5.14.3.4.4"></a><h3>
<a name="id-1_3_46_5_13_1_1_6-bb"></a><code class="computeroutput">visitor_ptr_t</code> static visitor interfaces</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<pre class="literallayout"><a name="id-1_3_46_5_13_1_1_6_1-bb"></a><span class="identifier">R</span> <a name="id-1_3_46_5_13_1_1_6_1_1-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="emphasis"><em><span class="identifier">unspecified</span><span class="special">-</span><span class="identifier">forwarding</span><span class="special">-</span><span class="identifier">type</span></em></span> operand<span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> U<span class="special">></span> <span class="keyword">void</span> <a name="id-1_3_46_5_13_1_1_6_1_2-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">U</span><span class="special">&</span><span class="special">)</span><span class="special">;</span></pre>
<div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term">Effects:</span></p></td>
<td>If passed a value or reference of type
<code class="computeroutput">T</code>, it invokes the function given at
construction, appropriately forwarding
<code class="computeroutput">operand</code>.</td>
</tr>
<tr>
<td><p><span class="term">Returns:</span></p></td>
<td>Returns the result of the function invocation.</td>
</tr>
<tr>
<td><p><span class="term">Throws:</span></p></td>
<td>The overload taking a value or reference of type
<code class="computeroutput">T</code> throws if the invoked function throws.
The overload taking all other values <span class="emphasis"><em>always</em></span>
throws <code class="computeroutput"><a class="link" href="bad_visit.html" title="Class bad_visit">bad_visit</a></code>.</td>
</tr>
</tbody>
</table></div>
</li></ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2002, 2003 Eric Friedman, Itay Maman<p>Distributed under the Boost Software License, Version 1.0.
(See accompanying file <code class="filename">LICENSE_1_0.txt</code> or copy at
<a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="static_visitor.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../variant/reference.html#header.boost.variant.visitor_ptr_hpp"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="visitor_ptr.html"><img src="../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| nawawi/poedit | deps/boost/doc/html/boost/visitor_ptr_t.html | HTML | mit | 10,060 |
using System;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using DotSpatial.Controls;
using DotSpatial.Controls.Header;
using DotSpatial.Symbology;
namespace DotSpatial.Plugins.Contourer
{
public class Snapin : Extension
{
public override void Activate()
{
AddMenuItems(App.HeaderControl);
base.Activate();
}
private void AddMenuItems(IHeaderControl header)
{
SimpleActionItem contourerItem = new SimpleActionItem("Contour...", menu_Click) { Key = "kC" };
header.Add(contourerItem);
}
private void menu_Click(object sender, EventArgs e)
{
using (FormContour frm = new FormContour())
{
frm.Layers = App.Map.GetRasterLayers();
if (frm.Layers.GetLength(0) <= 0)
{
MessageBox.Show("No raster layer found!");
return;
}
if (frm.ShowDialog() != DialogResult.OK) return;
IMapFeatureLayer fl = App.Map.Layers.Add(frm.Contours);
fl.LegendText = frm.LayerName + " - Contours";
int numlevs = frm.Lev.GetLength(0);
switch (frm.Contourtype)
{
case (Contour.ContourType.Line):
{
LineScheme ls = new LineScheme();
ls.Categories.Clear();
for (int i = 0; i < frm.Color.GetLength(0); i++)
{
LineCategory lc = new LineCategory(frm.Color[i], 2.0)
{
FilterExpression = "[Value] = " + frm.Lev[i],
LegendText = frm.Lev[i].ToString(CultureInfo.InvariantCulture)
};
ls.AddCategory(lc);
}
fl.Symbology = ls;
}
break;
case (Contour.ContourType.Polygon):
{
PolygonScheme ps = new PolygonScheme();
ps.Categories.Clear();
for (int i = 0; i < frm.Color.GetLength(0); i++)
{
PolygonCategory pc = new PolygonCategory(frm.Color[i], Color.Transparent, 0)
{
FilterExpression = "[Lev] = " + i,
LegendText = frm.Lev[i] + " - " + frm.Lev[i + 1]
};
ps.AddCategory(pc);
}
fl.Symbology = ps;
}
break;
}
}
}
}
} | swsglobal/DotSpatial | Source/DotSpatial.Plugins.Contourer/Snapin.cs | C# | mit | 3,106 |
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
if (!process.versions.openssl) {
console.error('Skipping because node compiled without OpenSSL.');
process.exit(0);
}
var common = require('../common');
var assert = require('assert');
var fs = require('fs');
var tls = require('tls');
var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem');
var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem');
tls.createServer({ key: key, cert: cert }, function(conn) {
conn.end();
this.close();
}).listen(0, function() {
var options = { port: this.address().port, rejectUnauthorized: true };
tls.connect(options).on('error', common.mustCall(function(err) {
assert.equal(err.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE');
assert.equal(err.message, 'unable to verify the first certificate');
this.destroy();
}));
});
| ptmt/flow-declarations | test/node/test-tls-friendly-error-message.js | JavaScript | mit | 1,945 |
Kanboard.App = function() {
this.controllers = {};
};
Kanboard.App.prototype.get = function(controller) {
return this.controllers[controller];
};
Kanboard.App.prototype.execute = function() {
for (var className in Kanboard) {
if (className !== "App") {
var controller = new Kanboard[className](this);
this.controllers[className] = controller;
if (typeof controller.execute === "function") {
controller.execute();
}
if (typeof controller.listen === "function") {
controller.listen();
}
if (typeof controller.focus === "function") {
controller.focus();
}
}
}
this.focus();
this.datePicker();
this.autoComplete();
this.tagAutoComplete();
};
Kanboard.App.prototype.focus = function() {
// Auto-select input fields
$(document).on('focus', '.auto-select', function() {
$(this).select();
});
// Workaround for chrome
$(document).on('mouseup', '.auto-select', function(e) {
e.preventDefault();
});
};
Kanboard.App.prototype.datePicker = function() {
var bodyElement = $("body");
var dateFormat = bodyElement.data("js-date-format");
var timeFormat = bodyElement.data("js-time-format");
var lang = bodyElement.data("js-lang");
$.datepicker.setDefaults($.datepicker.regional[lang]);
$.timepicker.setDefaults($.timepicker.regional[lang]);
// Datepicker
$(".form-date").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
dateFormat: dateFormat,
constrainInput: false
});
// Datetime picker
$(".form-datetime").datetimepicker({
dateFormat: dateFormat,
timeFormat: timeFormat,
constrainInput: false
});
};
Kanboard.App.prototype.tagAutoComplete = function() {
$(".tag-autocomplete").select2({
tags: true
});
};
Kanboard.App.prototype.autoComplete = function() {
$(".autocomplete").each(function() {
var input = $(this);
var field = input.data("dst-field");
var extraFields = input.data("dst-extra-fields");
if ($('#form-' + field).val() === '') {
input.parent().find("button[type=submit]").attr('disabled','disabled');
}
input.autocomplete({
source: input.data("search-url"),
minLength: 1,
select: function(event, ui) {
$("input[name=" + field + "]").val(ui.item.id);
if (extraFields) {
var fields = extraFields.split(',');
for (var i = 0; i < fields.length; i++) {
var fieldName = fields[i].trim();
$("input[name=" + fieldName + "]").val(ui.item[fieldName]);
}
}
input.parent().find("button[type=submit]").removeAttr('disabled');
}
});
});
};
Kanboard.App.prototype.hasId = function(id) {
return !!document.getElementById(id);
};
Kanboard.App.prototype.showLoadingIcon = function() {
$("body").append('<span id="app-loading-icon"> <i class="fa fa-spinner fa-spin"></i></span>');
};
Kanboard.App.prototype.hideLoadingIcon = function() {
$("#app-loading-icon").remove();
};
| fguillot/kanboard | assets/js/src/App.js | JavaScript | mit | 3,355 |
/*
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
module.exports = function(should, Assertion) {
/**
* Assert given object is NaN
* @name NaN
* @memberOf Assertion
* @category assertion numbers
* @example
*
* (10).should.not.be.NaN();
* NaN.should.be.NaN();
*/
Assertion.add('NaN', function() {
this.params = { operator: 'to be NaN' };
this.assert(this.obj !== this.obj);
});
/**
* Assert given object is not finite (positive or negative)
*
* @name Infinity
* @memberOf Assertion
* @category assertion numbers
* @example
*
* (10).should.not.be.Infinity();
* NaN.should.not.be.Infinity();
*/
Assertion.add('Infinity', function() {
this.params = { operator: 'to be Infinity' };
this.is.a.Number()
.and.not.a.NaN()
.and.assert(!isFinite(this.obj));
});
/**
* Assert given number between `start` and `finish` or equal one of them.
*
* @name within
* @memberOf Assertion
* @category assertion numbers
* @param {number} start Start number
* @param {number} finish Finish number
* @param {string} [description] Optional message
* @example
*
* (10).should.be.within(0, 20);
*/
Assertion.add('within', function(start, finish, description) {
this.params = { operator: 'to be within ' + start + '..' + finish, message: description };
this.assert(this.obj >= start && this.obj <= finish);
});
/**
* Assert given number near some other `value` within `delta`
*
* @name approximately
* @memberOf Assertion
* @category assertion numbers
* @param {number} value Center number
* @param {number} delta Radius
* @param {string} [description] Optional message
* @example
*
* (9.99).should.be.approximately(10, 0.1);
*/
Assertion.add('approximately', function(value, delta, description) {
this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description };
this.assert(Math.abs(this.obj - value) <= delta);
});
/**
* Assert given number above `n`.
*
* @name above
* @alias Assertion#greaterThan
* @memberOf Assertion
* @category assertion numbers
* @param {number} n Margin number
* @param {string} [description] Optional message
* @example
*
* (10).should.be.above(0);
*/
Assertion.add('above', function(n, description) {
this.params = { operator: 'to be above ' + n, message: description };
this.assert(this.obj > n);
});
/**
* Assert given number below `n`.
*
* @name below
* @alias Assertion#lessThan
* @memberOf Assertion
* @category assertion numbers
* @param {number} n Margin number
* @param {string} [description] Optional message
* @example
*
* (0).should.be.below(10);
*/
Assertion.add('below', function(n, description) {
this.params = { operator: 'to be below ' + n, message: description };
this.assert(this.obj < n);
});
Assertion.alias('above', 'greaterThan');
Assertion.alias('below', 'lessThan');
};
| XuanyuZhao1984/MeanJS_train1 | node_modules/should/lib/ext/number.js | JavaScript | mit | 3,086 |
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*/
class Solarium_Result_Select_FacetSetTest extends PHPUnit_Framework_TestCase
{
/**
* @var Solarium_Result_Select_FacetSet
*/
protected $_result;
protected $_facets;
public function setUp()
{
$this->_facets = array(
'facet1' => 'content1',
'facet2' => 'content2',
);
$this->_result = new Solarium_Result_Select_FacetSet($this->_facets);
}
public function testGetFacets()
{
$this->assertEquals($this->_facets, $this->_result->getFacets());
}
public function testGetFacet()
{
$this->assertEquals(
$this->_facets['facet2'],
$this->_result->getFacet('facet2')
);
}
public function testGetInvalidFacet()
{
$this->assertEquals(
null,
$this->_result->getFacet('invalid')
);
}
public function testIterator()
{
$items = array();
foreach($this->_result AS $key => $item)
{
$items[$key] = $item;
}
$this->assertEquals($this->_facets, $items);
}
public function testCount()
{
$this->assertEquals(count($this->_facets), count($this->_result));
}
}
| bitclaw/solr-test | www/vendor/solarium/solarium/tests/Solarium/Result/Select/FacetSetTest.php | PHP | mit | 2,846 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// JobOperations operations.
/// </summary>
public partial interface IJobOperations
{
/// <summary>
/// Gets lifetime summary statistics for all of the Jobs in the
/// specified Account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all Jobs that have ever existed in
/// the Account, from Account creation to the last update time of the
/// statistics. The statistics may not be immediately available. The
/// Batch service performs periodic roll-up of statistics. The typical
/// delay is about 30 minutes.
/// </remarks>
/// <param name='jobGetAllLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobStatistics,JobGetAllLifetimeStatisticsHeaders>> GetAllLifetimeStatisticsWithHttpMessagesAsync(JobGetAllLifetimeStatisticsOptions jobGetAllLifetimeStatisticsOptions = default(JobGetAllLifetimeStatisticsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a Job.
/// </summary>
/// <remarks>
/// Deleting a Job also deletes all Tasks that are part of that Job,
/// and all Job statistics. This also overrides the retention period
/// for Task data; that is, if the Job contains Tasks which are still
/// retained on Compute Nodes, the Batch services deletes those Tasks'
/// working directories and all their contents. When a Delete Job
/// request is received, the Batch service sets the Job to the deleting
/// state. All update operations on a Job that is in deleting state
/// will fail with status code 409 (Conflict), with additional
/// information indicating that the Job is being deleted.
/// </remarks>
/// <param name='jobId'>
/// The ID of the Job to delete.
/// </param>
/// <param name='jobDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobDeleteHeaders>> DeleteWithHttpMessagesAsync(string jobId, JobDeleteOptions jobDeleteOptions = default(JobDeleteOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified Job.
/// </summary>
/// <param name='jobId'>
/// The ID of the Job.
/// </param>
/// <param name='jobGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CloudJob,JobGetHeaders>> GetWithHttpMessagesAsync(string jobId, JobGetOptions jobGetOptions = default(JobGetOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the properties of the specified Job.
/// </summary>
/// <remarks>
/// This replaces only the Job properties specified in the request. For
/// example, if the Job has constraints, and a request does not specify
/// the constraints element, then the Job keeps the existing
/// constraints.
/// </remarks>
/// <param name='jobId'>
/// The ID of the Job whose properties you want to update.
/// </param>
/// <param name='jobPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobPatchHeaders>> PatchWithHttpMessagesAsync(string jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions = default(JobPatchOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the properties of the specified Job.
/// </summary>
/// <remarks>
/// This fully replaces all the updatable properties of the Job. For
/// example, if the Job has constraints associated with it and if
/// constraints is not specified with this request, then the Batch
/// service will remove the existing constraints.
/// </remarks>
/// <param name='jobId'>
/// The ID of the Job whose properties you want to update.
/// </param>
/// <param name='jobUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobUpdateHeaders>> UpdateWithHttpMessagesAsync(string jobId, JobUpdateParameter jobUpdateParameter, JobUpdateOptions jobUpdateOptions = default(JobUpdateOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disables the specified Job, preventing new Tasks from running.
/// </summary>
/// <remarks>
/// The Batch Service immediately moves the Job to the disabling state.
/// Batch then uses the disableTasks parameter to determine what to do
/// with the currently running Tasks of the Job. The Job remains in the
/// disabling state until the disable operation is completed and all
/// Tasks have been dealt with according to the disableTasks option;
/// the Job then moves to the disabled state. No new Tasks are started
/// under the Job until it moves back to active state. If you try to
/// disable a Job that is in any state other than active, disabling, or
/// disabled, the request fails with status code 409.
/// </remarks>
/// <param name='jobId'>
/// The ID of the Job to disable.
/// </param>
/// <param name='disableTasks'>
/// What to do with active Tasks associated with the Job. Possible
/// values include: 'requeue', 'terminate', 'wait'
/// </param>
/// <param name='jobDisableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobDisableHeaders>> DisableWithHttpMessagesAsync(string jobId, DisableJobOption disableTasks, JobDisableOptions jobDisableOptions = default(JobDisableOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Enables the specified Job, allowing new Tasks to run.
/// </summary>
/// <remarks>
/// When you call this API, the Batch service sets a disabled Job to
/// the enabling state. After the this operation is completed, the Job
/// moves to the active state, and scheduling of new Tasks under the
/// Job resumes. The Batch service does not allow a Task to remain in
/// the active state for more than 180 days. Therefore, if you enable a
/// Job containing active Tasks which were added more than 180 days
/// ago, those Tasks will not run.
/// </remarks>
/// <param name='jobId'>
/// The ID of the Job to enable.
/// </param>
/// <param name='jobEnableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobEnableHeaders>> EnableWithHttpMessagesAsync(string jobId, JobEnableOptions jobEnableOptions = default(JobEnableOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Terminates the specified Job, marking it as completed.
/// </summary>
/// <remarks>
/// When a Terminate Job request is received, the Batch service sets
/// the Job to the terminating state. The Batch service then terminates
/// any running Tasks associated with the Job and runs any required Job
/// release Tasks. Then the Job moves into the completed state. If
/// there are any Tasks in the Job in the active state, they will
/// remain in the active state. Once a Job is terminated, new Tasks
/// cannot be added and any remaining active Tasks will not be
/// scheduled.
/// </remarks>
/// <param name='jobId'>
/// The ID of the Job to terminate.
/// </param>
/// <param name='terminateReason'>
/// The text you want to appear as the Job's TerminateReason. The
/// default is 'UserTerminate'.
/// </param>
/// <param name='jobTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobTerminateHeaders>> TerminateWithHttpMessagesAsync(string jobId, string terminateReason = default(string), JobTerminateOptions jobTerminateOptions = default(JobTerminateOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Adds a Job to the specified Account.
/// </summary>
/// <remarks>
/// The Batch service supports two ways to control the work done as
/// part of a Job. In the first approach, the user specifies a Job
/// Manager Task. The Batch service launches this Task when it is ready
/// to start the Job. The Job Manager Task controls all other Tasks
/// that run under this Job, by using the Task APIs. In the second
/// approach, the user directly controls the execution of Tasks under
/// an active Job, by using the Task APIs. Also note: when naming Jobs,
/// avoid including sensitive information such as user names or secret
/// project names. This information may appear in telemetry logs
/// accessible to Microsoft Support engineers.
/// </remarks>
/// <param name='job'>
/// The Job to be added.
/// </param>
/// <param name='jobAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<JobAddHeaders>> AddWithHttpMessagesAsync(JobAddParameter job, JobAddOptions jobAddOptions = default(JobAddOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the Jobs in the specified Account.
/// </summary>
/// <param name='jobListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CloudJob>,JobListHeaders>> ListWithHttpMessagesAsync(JobListOptions jobListOptions = default(JobListOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Jobs that have been created under the specified Job
/// Schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The ID of the Job Schedule from which you want to get a list of
/// Jobs.
/// </param>
/// <param name='jobListFromJobScheduleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleWithHttpMessagesAsync(string jobScheduleId, JobListFromJobScheduleOptions jobListFromJobScheduleOptions = default(JobListFromJobScheduleOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release
/// Task for the specified Job across the Compute Nodes where the Job
/// has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release Task status on
/// all Compute Nodes that have run the Job Preparation or Job Release
/// Task. This includes Compute Nodes which have since been removed
/// from the Pool. If this API is invoked on a Job which has no Job
/// Preparation or Job Release Task, the Batch service returns HTTP
/// status code 409 (Conflict) with an error code of
/// JobPreparationTaskNotSpecified.
/// </remarks>
/// <param name='jobId'>
/// The ID of the Job.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusWithHttpMessagesAsync(string jobId, JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions = default(JobListPreparationAndReleaseTaskStatusOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the Task counts for the specified Job.
/// </summary>
/// <remarks>
/// Task counts provide a count of the Tasks by active, running or
/// completed Task state, and a count of Tasks which succeeded or
/// failed. Tasks in the preparing state are counted as running.
/// </remarks>
/// <param name='jobId'>
/// The ID of the Job.
/// </param>
/// <param name='jobGetTaskCountsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<TaskCountsResult,JobGetTaskCountsHeaders>> GetTaskCountsWithHttpMessagesAsync(string jobId, JobGetTaskCountsOptions jobGetTaskCountsOptions = default(JobGetTaskCountsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the Jobs in the specified Account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CloudJob>,JobListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, JobListNextOptions jobListNextOptions = default(JobListNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Jobs that have been created under the specified Job
/// Schedule.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListFromJobScheduleNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleNextWithHttpMessagesAsync(string nextPageLink, JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions = default(JobListFromJobScheduleNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release
/// Task for the specified Job across the Compute Nodes where the Job
/// has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release Task status on
/// all Compute Nodes that have run the Job Preparation or Job Release
/// Task. This includes Compute Nodes which have since been removed
/// from the Pool. If this API is invoked on a Job which has no Job
/// Preparation or Job Release Task, the Batch service returns HTTP
/// status code 409 (Conflict) with an error code of
/// JobPreparationTaskNotSpecified.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusNextWithHttpMessagesAsync(string nextPageLink, JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = default(JobListPreparationAndReleaseTaskStatusNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| ayeletshpigelman/azure-sdk-for-net | sdk/batch/Microsoft.Azure.Batch/src/GeneratedProtocol/IJobOperations.cs | C# | mit | 27,629 |
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
namespace Earlab
{
public delegate void LogCallback(String LogMessage);
/// <summary>
/// DesktopEarlabDLL is a wrapper class that wraps the DesktopEarlabDLL.dll functionality
/// and exposes it to C# applications
/// </summary>
class DesktopEarlabDLL
{
IntPtr theModel;
private const string DLLFileName = @"DesktopEarlabDLL.dll";
private string SavedPath;
[DllImport(DLLFileName, EntryPoint="CreateModel", CallingConvention=CallingConvention.Cdecl)]
private static extern IntPtr CreateModelExternal();
[DllImport(DLLFileName, EntryPoint="SetLogCallback", CallingConvention=CallingConvention.Cdecl)]
private static extern void SetLogCallbackExternal(IntPtr ModelPtr, LogCallback theCallback);
[DllImport(DLLFileName, EntryPoint="SetModuleDirectory", CallingConvention=CallingConvention.Cdecl)]
private static extern int SetModuleDirectoryExternal(IntPtr ModelPtr, string ModuleDirectoryPath);
[DllImport(DLLFileName, EntryPoint="SetInputDirectory", CallingConvention=CallingConvention.Cdecl)]
private static extern int SetInputDirectoryExternal(IntPtr ModelPtr, string InputDirectoryPath);
[DllImport(DLLFileName, EntryPoint="SetOutputDirectory", CallingConvention=CallingConvention.Cdecl)]
private static extern int SetOutputDirectoryExternal(IntPtr ModelPtr, string OutputDirectoryPath);
[DllImport(DLLFileName, EntryPoint="LoadModelConfigFile", CallingConvention=CallingConvention.Cdecl)]
private static extern int LoadModelConfigFileExternal(IntPtr ModelPtr, string ModelConfigFileName, float FrameSize_uS);
[DllImport(DLLFileName, EntryPoint="LoadModuleParameters", CallingConvention=CallingConvention.Cdecl)]
private static extern int LoadModuleParametersExternal(IntPtr ModelPtr, string ModuleParameterFileName);
[DllImport(DLLFileName, EntryPoint="StartModules", CallingConvention=CallingConvention.Cdecl)]
private static extern int StartModulesExternal(IntPtr ModelPtr);
[DllImport(DLLFileName, EntryPoint="RunModel", CallingConvention=CallingConvention.Cdecl)]
private static extern int RunModelExternal(IntPtr ModelPtr, int NumFrames);
[DllImport(DLLFileName, EntryPoint="AdvanceModules", CallingConvention=CallingConvention.Cdecl)]
private static extern int AdvanceModulesExternal(IntPtr ModelPtr);
[DllImport(DLLFileName, EntryPoint="StopModules", CallingConvention=CallingConvention.Cdecl)]
private static extern int StopModulesExternal(IntPtr ModelPtr);
[DllImport(DLLFileName, EntryPoint="UnloadModel", CallingConvention=CallingConvention.Cdecl)]
private static extern int UnloadModelExternal(IntPtr ModelPtr);
public DesktopEarlabDLL()
{
theModel = DesktopEarlabDLL.CreateModelExternal();
if (theModel == IntPtr.Zero)
throw new ApplicationException("Failed to initialize model");
}
public int SetModuleDirectory(string ModuleDirectoryPath)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.SetModuleDirectoryExternal(theModel, ModuleDirectoryPath);
}
public void SetInputDirectory(string InputDirectoryPath)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
DesktopEarlabDLL.SetInputDirectoryExternal(theModel, InputDirectoryPath);
}
public void SetOutputDirectory(string OutputDirectoryPath)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
DesktopEarlabDLL.SetOutputDirectoryExternal(theModel, OutputDirectoryPath);
}
public void SetLogCallback(LogCallback theCallback)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
DesktopEarlabDLL.SetLogCallbackExternal(theModel, theCallback);
}
public int LoadModelConfigFile(string ModelConfigFileName, float FrameSize_uS)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
SavedPath = Environment.CurrentDirectory;
Environment.CurrentDirectory = Path.GetDirectoryName(ModelConfigFileName);
return DesktopEarlabDLL.LoadModelConfigFileExternal(theModel, ModelConfigFileName, FrameSize_uS);
}
public int LoadModuleParameters(string ModuleParameterFileName)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.LoadModuleParametersExternal(theModel, ModuleParameterFileName);
}
public int StartModules()
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.StartModulesExternal(theModel);
}
public int RunModel(int NumFrames)
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.RunModelExternal(theModel, NumFrames);
}
public int AdvanceModules()
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.AdvanceModulesExternal(theModel);
}
public int StopModules()
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
return DesktopEarlabDLL.StopModulesExternal(theModel);
}
public int UnloadModel()
{
if (theModel == IntPtr.Zero)
throw new ApplicationException("Model not initialized");
Environment.CurrentDirectory = SavedPath;
return DesktopEarlabDLL.UnloadModelExternal(theModel);
}
}
}
| AuditoryBiophysicsLab/EarLab | tags/release-2.2/EarLab ExperimentManager/DesktopEarlabDLL.cs | C# | mit | 5,656 |
class SurveyMrqAnswer < ActiveRecord::Base
acts_as_paranoid
attr_accessible :user_course_id, :question_id, :option_id, :selected_options, :survey_submission_id
belongs_to :user_course
belongs_to :question, class_name: "SurveyQuestion"
belongs_to :option, class_name: "SurveyQuestionOption"
belongs_to :survey_submission
#TODO: not in use, can be removed
def options
SurveyQuestionOption.where(id: eval(selected_options))
end
end
| nusedutech/coursemology.org | app/models/survey_mrq_answer.rb | Ruby | mit | 455 |
<?php
namespace Kendo\UI;
class SchedulerMessagesRecurrenceEditorMonthly extends \Kendo\SerializableObject {
//>> Properties
/**
* The text similar to "Day " displayed in the scheduler recurrence editor.
* @param string $value
* @return \Kendo\UI\SchedulerMessagesRecurrenceEditorMonthly
*/
public function day($value) {
return $this->setProperty('day', $value);
}
/**
* The text similar to " month(s)" displayed in the scheduler recurrence editor.
* @param string $value
* @return \Kendo\UI\SchedulerMessagesRecurrenceEditorMonthly
*/
public function interval($value) {
return $this->setProperty('interval', $value);
}
/**
* The text similar to "Repeat every: " displayed in the scheduler recurrence editor.
* @param string $value
* @return \Kendo\UI\SchedulerMessagesRecurrenceEditorMonthly
*/
public function repeatEvery($value) {
return $this->setProperty('repeatEvery', $value);
}
/**
* The text similar to "Repeat on: " displayed in the scheduler recurrence editor.
* @param string $value
* @return \Kendo\UI\SchedulerMessagesRecurrenceEditorMonthly
*/
public function repeatOn($value) {
return $this->setProperty('repeatOn', $value);
}
//<< Properties
}
?>
| deviffy/laravel-kendo-ui | wrappers/php/lib/Kendo/UI/SchedulerMessagesRecurrenceEditorMonthly.php | PHP | mit | 1,316 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class template generated_by</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../index.html" title="Boost.Test">
<link rel="up" href="../../../../header/boost/test/data/monomorphic/generate_hpp.html" title="Header <boost/test/data/monomorphic/generate.hpp>">
<link rel="prev" href="../../../../header/boost/test/data/monomorphic/generate_hpp.html" title="Header <boost/test/data/monomorphic/generate.hpp>">
<link rel="next" href="generated_by/iterator.html" title="Struct iterator">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../../../header/boost/test/data/monomorphic/generate_hpp.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../../header/boost/test/data/monomorphic/generate_hpp.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="generated_by/iterator.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.unit_test.data.monomorphic.generated_by"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Class template generated_by</span></h2>
<p>boost::unit_test::data::monomorphic::generated_by — Generators interface. </p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../../header/boost/test/data/monomorphic/generate_hpp.html" title="Header <boost/test/data/monomorphic/generate.hpp>">boost/test/data/monomorphic/generate.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Generator<span class="special">></span>
<span class="keyword">class</span> <a class="link" href="generated_by.html" title="Class template generated_by">generated_by</a> <span class="special">{</span>
<span class="keyword">public</span><span class="special">:</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="identifier">Generator</span><span class="special">::</span><span class="identifier">sample</span> <a name="boost.unit_test.data.monomorphic.generated_by.sample"></a><span class="identifier">sample</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">Generator</span> <a name="boost.unit_test.data.monomorphic.generated_by.generator_type"></a><span class="identifier">generator_type</span><span class="special">;</span>
<span class="comment">// member classes/structs/unions</span>
<span class="keyword">struct</span> <a class="link" href="generated_by/iterator.html" title="Struct iterator">iterator</a> <span class="special">{</span>
<span class="comment">// <a class="link" href="generated_by/iterator.html#boost.unit_test.data.monomorphic.generated_by.iteratorconstruct-copy-destruct">construct/copy/destruct</a></span>
<span class="keyword">explicit</span> <a class="link" href="generated_by/iterator.html#idp68465456-bb"><span class="identifier">iterator</span></a><span class="special">(</span><span class="identifier">Generator</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="generated_by/iterator.html#idp68462768-bb">public member functions</a></span>
<span class="identifier">sample</span> <span class="keyword">const</span> <span class="special">&</span> <a class="link" href="generated_by/iterator.html#idp68463328-bb"><span class="keyword">operator</span><span class="special">*</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">void</span> <a class="link" href="generated_by/iterator.html#idp68464448-bb"><span class="keyword">operator</span><span class="special">++</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span>
<span class="keyword">enum</span> <a name="boost.unit_test.data.monomorphic.generated_by.@7"></a>@7 <span class="special">{</span> arity = = 1 <span class="special">}</span><span class="special">;</span>
<span class="comment">// <a class="link" href="generated_by.html#boost.unit_test.data.monomorphic.generated_byconstruct-copy-destruct">construct/copy/destruct</a></span>
<span class="keyword">explicit</span> <a class="link" href="generated_by.html#idp68473488-bb"><span class="identifier">generated_by</span></a><span class="special">(</span><span class="identifier">Generator</span> <span class="special">&&</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="generated_by.html#idp68474736-bb"><span class="identifier">generated_by</span></a><span class="special">(</span><a class="link" href="generated_by.html" title="Class template generated_by">generated_by</a> <span class="special">&&</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="generated_by.html#idp68469648-bb">public member functions</a></span>
<a class="link" href="../size_t.html" title="Class size_t">data::size_t</a> <a class="link" href="generated_by.html#idp68470208-bb"><span class="identifier">size</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<a class="link" href="generated_by/iterator.html" title="Struct iterator">iterator</a> <a class="link" href="generated_by.html#idp68471760-bb"><span class="identifier">begin</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp95917968"></a><h2>Description</h2>
<p>This class implements the dataset concept over a generator. Examples of generators are:</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem"><p><a class="link" href="xrange_t.html" title="Class template xrange_t">xrange_t</a></p></li>
<li class="listitem"><p><a class="link" href="random_t.html" title="Class template random_t">random_t</a></p></li>
</ul></div>
<p>
</p>
<p>The generator concept is the following:</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem"><p>the type of the generated samples is given by field <code class="computeroutput">sample</code> </p></li>
<li class="listitem"><p>the member function <code class="computeroutput">capacity</code> should return the size of the collection being generated (potentially infinite)</p></li>
<li class="listitem"><p>the member function <code class="computeroutput">next</code> should change the state of the generator to the next generated value</p></li>
<li class="listitem"><p>the member function <code class="computeroutput">reset</code> should put the state of the object in the same state as right after its instanciation </p></li>
</ul></div>
<p>
</p>
<div class="refsect2">
<a name="idp95926688"></a><h3>
<a name="boost.unit_test.data.monomorphic.generated_byconstruct-copy-destruct"></a><code class="computeroutput">generated_by</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><span class="keyword">explicit</span> <a name="idp68473488-bb"></a><span class="identifier">generated_by</span><span class="special">(</span><span class="identifier">Generator</span> <span class="special">&&</span> G<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><a name="idp68474736-bb"></a><span class="identifier">generated_by</span><span class="special">(</span><a class="link" href="generated_by.html" title="Class template generated_by">generated_by</a> <span class="special">&&</span> rhs<span class="special">)</span><span class="special">;</span></pre></li>
</ol></div>
</div>
<div class="refsect2">
<a name="idp95939952"></a><h3>
<a name="idp68469648-bb"></a><code class="computeroutput">generated_by</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><a class="link" href="../size_t.html" title="Class size_t">data::size_t</a> <a name="idp68470208-bb"></a><span class="identifier">size</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Size of the underlying dataset. </li>
<li class="listitem">
<pre class="literallayout"><a class="link" href="generated_by/iterator.html" title="Struct iterator">iterator</a> <a name="idp68471760-bb"></a><span class="identifier">begin</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>Iterator on the beginning of the dataset. </li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2018 Boost.Test contributors<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../../../header/boost/test/data/monomorphic/generate_hpp.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../../header/boost/test/data/monomorphic/generate_hpp.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="generated_by/iterator.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| nawawi/poedit | deps/boost/libs/test/doc/html/boost/unit_test/data/monomorphic/generated_by.html | HTML | mit | 11,554 |
// -------------------------------
// Copyright (c) Corman Technologies Inc.
// See LICENSE.txt for license information.
// -------------------------------
//
// File: plserver_internal.h
// Contents: Server internal functions for Corman Lisp
// History: 8/5/97 RGC Created.
//
#include "CharBuf.h"
extern IUnknown* ClientUnknown;
extern ICormanLispTextOutput* ClientTextOutput;
extern ICormanLispStatusMessage* ClientMessage;
extern CharBuf TerminalInputBuf;
| arbv/cormanlisp | CormanLispServer/include/plserver_internal.h | C | mit | 495 |
<p id="sherman_jason" data-toggle="tooltip" title="<img src='{{site.filesurl}}/people/sherman_jason.jpg' alt='Jason Sherman' />">
<span class="person">Jason Sherman</span> is an Oklahoma native, a
student of the liberal arts, and an IT Analyst at the University
of Oklahoma Libraries. He spends much of his time building
infrastructure for developers, but also pitches in by writing the
occasional integration module or migration script.
</p>
| ErinBecker/website | _includes/people/sherman_jason.html | HTML | mit | 463 |
package main
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
var (
bashPath string
debugging = false
erroring = false
maxprocs = 4
testPattern = regexp.MustCompile(`test[/\\]test-([a-z\-]+)\.sh$`)
)
func mainIntegration() {
if len(os.Getenv("DEBUG")) > 0 {
debugging = true
}
setBash()
if max, _ := strconv.Atoi(os.Getenv("GIT_LFS_TEST_MAXPROCS")); max > 0 {
maxprocs = max
}
fmt.Println("Running this maxprocs", maxprocs)
files := testFiles()
if len(files) == 0 {
fmt.Println("no tests to run")
os.Exit(1)
}
var wg sync.WaitGroup
tests := make(chan string, len(files))
output := make(chan string, len(files))
for _, file := range files {
tests <- file
}
go printOutput(output)
for i := 0; i < maxprocs; i++ {
wg.Add(1)
go worker(tests, output, &wg)
}
close(tests)
wg.Wait()
close(output)
printOutput(output)
if erroring {
os.Exit(1)
}
}
func runTest(output chan string, testname string) {
buf := &bytes.Buffer{}
cmd := exec.Command(bashPath, testname)
cmd.Stdout = buf
cmd.Stderr = buf
err := cmd.Start()
if err != nil {
sendTestOutput(output, testname, buf, err)
return
}
done := make(chan error)
go func() {
if err := cmd.Wait(); err != nil {
done <- err
}
close(done)
}()
select {
case err = <-done:
sendTestOutput(output, testname, buf, err)
return
case <-time.After(3 * time.Minute):
sendTestOutput(output, testname, buf, errors.New("Timed out"))
cmd.Process.Kill()
return
}
}
func sendTestOutput(output chan string, testname string, buf *bytes.Buffer, err error) {
cli := strings.TrimSpace(buf.String())
if len(cli) == 0 {
cli = fmt.Sprintf("<no output for %s>", testname)
}
if err == nil {
output <- cli
} else {
basetestname := filepath.Base(testname)
if debugging {
fmt.Printf("Error on %s: %s\n", basetestname, err)
}
erroring = true
output <- fmt.Sprintf("error: %s => %s\n%s", basetestname, err, cli)
}
}
func printOutput(output <-chan string) {
for {
select {
case out, ok := <-output:
if !ok {
return
}
fmt.Println(out)
}
}
}
func worker(tests <-chan string, output chan string, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case testname, ok := <-tests:
if !ok {
return
}
runTest(output, testname)
}
}
}
func testFiles() []string {
if len(os.Args) < 4 {
return allTestFiles()
}
fileMap := make(map[string]bool)
for _, file := range allTestFiles() {
fileMap[file] = true
}
files := make([]string, 0, len(os.Args)-3)
for _, arg := range os.Args {
fullname := "test/test-" + arg + ".sh"
if fileMap[fullname] {
files = append(files, fullname)
}
}
return files
}
func allTestFiles() []string {
files := make([]string, 0, 100)
filepath.Walk("test", func(path string, info os.FileInfo, err error) error {
if debugging {
fmt.Println("FOUND:", path)
}
if err != nil || info.IsDir() || !testPattern.MatchString(path) {
return nil
}
if debugging {
fmt.Println("MATCHING:", path)
}
files = append(files, path)
return nil
})
return files
}
func setBash() {
findcmd := "which"
if runtime.GOOS == "windows" {
// Can't use paths returned from which even if it's on PATH in Windows
// Because our Go binary is a separate Windows app & not MinGW, it
// can't understand paths like '/usr/bin/bash', needs Windows version
findcmd = "where"
}
out, err := exec.Command(findcmd, "bash").Output()
if err != nil {
fmt.Println("Unable to find bash:", err)
os.Exit(1)
}
if len(out) == 0 {
fmt.Printf("No output from '%s bash'\n", findcmd)
os.Exit(1)
}
bashPath = strings.TrimSpace(strings.Split(string(out), "\n")[0])
if debugging {
fmt.Println("Using", bashPath)
}
// Test
_, err = exec.Command(bashPath, "--version").CombinedOutput()
if err != nil {
fmt.Println("Error calling bash:", err)
os.Exit(1)
}
}
| Jericho25/-git-lfs_miilkyway | script/integration.go | GO | mit | 3,963 |
require 'oauth/signature/base'
module OAuth::Signature
class PLAINTEXT < Base
implements 'plaintext'
def signature
signature_base_string
end
def ==(cmp_signature)
signature == escape(cmp_signature)
end
def signature_base_string
secret
end
def secret
escape(super)
end
end
end
| maximilien/people_finder | vendor/plugins/oauth/lib/oauth/signature/plaintext.rb | Ruby | mit | 345 |
'use strict';
var APPLICATION_JSON = 'application/json';
var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
var JSON_START = /^\[|^\{(?!\{)/;
var JSON_ENDS = {
'[': /]$/,
'{': /}$/
};
var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $httpMinErr = minErr('$http');
var $httpMinErrLegacyFn = function(method) {
return function() {
throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
};
};
function serializeValue(v) {
if (isObject(v)) {
return isDate(v) ? v.toISOString() : toJson(v);
}
return v;
}
function $HttpParamSerializerProvider() {
/**
* @ngdoc service
* @name $httpParamSerializer
* @description
*
* Default {@link $http `$http`} params serializer that converts objects to strings
* according to the following rules:
*
* * `{'foo': 'bar'}` results in `foo=bar`
* * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
* * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
* * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
*
* Note that serializer will sort the request parameters alphabetically.
* */
this.$get = function() {
return function ngParamSerializer(params) {
if (!params) return '';
var parts = [];
forEachSorted(params, function(value, key) {
if (value === null || isUndefined(value)) return;
if (isArray(value)) {
forEach(value, function(v, k) {
parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
});
} else {
parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
}
});
return parts.join('&');
};
};
}
function $HttpParamSerializerJQLikeProvider() {
/**
* @ngdoc service
* @name $httpParamSerializerJQLike
* @description
*
* Alternative {@link $http `$http`} params serializer that follows
* jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
* The serializer will also sort the params alphabetically.
*
* To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
*
* ```js
* $http({
* url: myUrl,
* method: 'GET',
* params: myParams,
* paramSerializer: '$httpParamSerializerJQLike'
* });
* ```
*
* It is also possible to set it as the default `paramSerializer` in the
* {@link $httpProvider#defaults `$httpProvider`}.
*
* Additionally, you can inject the serializer and use it explicitly, for example to serialize
* form data for submission:
*
* ```js
* .controller(function($http, $httpParamSerializerJQLike) {
* //...
*
* $http({
* url: myUrl,
* method: 'POST',
* data: $httpParamSerializerJQLike(myData),
* headers: {
* 'Content-Type': 'application/x-www-form-urlencoded'
* }
* });
*
* });
* ```
*
* */
this.$get = function() {
return function jQueryLikeParamSerializer(params) {
if (!params) return '';
var parts = [];
serialize(params, '', true);
return parts.join('&');
function serialize(toSerialize, prefix, topLevel) {
if (toSerialize === null || isUndefined(toSerialize)) return;
if (isArray(toSerialize)) {
forEach(toSerialize, function(value, index) {
serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
});
} else if (isObject(toSerialize) && !isDate(toSerialize)) {
forEachSorted(toSerialize, function(value, key) {
serialize(value, prefix +
(topLevel ? '' : '[') +
key +
(topLevel ? '' : ']'));
});
} else {
parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
}
}
};
};
}
function defaultHttpResponseTransform(data, headers) {
if (isString(data)) {
// Strip json vulnerability protection prefix and trim whitespace
var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
if (tempData) {
var contentType = headers('Content-Type');
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
data = fromJson(tempData);
}
}
}
return data;
}
function isJsonLike(str) {
var jsonStart = str.match(JSON_START);
return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = createMap(), i;
function fillInParsed(key, val) {
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
if (isString(headers)) {
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
});
} else if (isObject(headers)) {
forEach(headers, function(headerVal, headerKey) {
fillInParsed(lowercase(headerKey), trim(headerVal));
});
}
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
var value = headersObj[lowercase(name)];
if (value === void 0) {
value = null;
}
return value;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers HTTP headers getter fn.
* @param {number} status HTTP status code of the response.
* @param {(Function|Array.<Function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, status, fns) {
if (isFunction(fns)) {
return fns(data, headers, status);
}
forEach(fns, function(fn) {
data = fn(data, headers, status);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
/**
* @ngdoc provider
* @name $httpProvider
* @description
* Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
* */
function $HttpProvider() {
/**
* @ngdoc property
* @name $httpProvider#defaults
* @description
*
* Object containing default values for all {@link ng.$http $http} requests.
*
* - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
* that will provide the cache for all requests who set their `cache` property to `true`.
* If you set the `defaults.cache = false` then only requests that specify their own custom
* cache object will be cached. See {@link $http#caching $http Caching} for more information.
*
* - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
* Defaults value is `'XSRF-TOKEN'`.
*
* - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
* XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
*
* - **`defaults.headers`** - {Object} - Default headers for all $http requests.
* Refer to {@link ng.$http#setting-http-headers $http} for documentation on
* setting default headers.
* - **`defaults.headers.common`**
* - **`defaults.headers.post`**
* - **`defaults.headers.put`**
* - **`defaults.headers.patch`**
*
*
* - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
* used to the prepare string representation of request parameters (specified as an object).
* If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
* Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
*
**/
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [defaultHttpResponseTransform],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
paramSerializer: '$httpParamSerializer'
};
var useApplyAsync = false;
/**
* @ngdoc method
* @name $httpProvider#useApplyAsync
* @description
*
* Configure $http service to combine processing of multiple http responses received at around
* the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
* significant performance improvement for bigger applications that make many HTTP requests
* concurrently (common during application bootstrap).
*
* Defaults to false. If no value is specified, returns the current configured value.
*
* @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
* "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
* to load and share the same digest cycle.
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
this.useApplyAsync = function(value) {
if (isDefined(value)) {
useApplyAsync = !!value;
return this;
}
return useApplyAsync;
};
var useLegacyPromise = true;
/**
* @ngdoc method
* @name $httpProvider#useLegacyPromiseExtensions
* @description
*
* Configure `$http` service to return promises without the shorthand methods `success` and `error`.
* This should be used to make sure that applications work without these methods.
*
* Defaults to true. If no value is specified, returns the current configured value.
*
* @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
this.useLegacyPromiseExtensions = function(value) {
if (isDefined(value)) {
useLegacyPromise = !!value;
return this;
}
return useLegacyPromise;
};
/**
* @ngdoc property
* @name $httpProvider#interceptors
* @description
*
* Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
* pre-processing of request or postprocessing of responses.
*
* These service factories are ordered by request, i.e. they are applied in the same order as the
* array, on request, but reverse order, on response.
*
* {@link ng.$http#interceptors Interceptors detailed info}
**/
var interceptorFactories = this.interceptors = [];
this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http');
/**
* Make sure that default param serializer is exposed as a function
*/
defaults.paramSerializer = isString(defaults.paramSerializer) ?
$injector.get(defaults.paramSerializer) : defaults.paramSerializer;
/**
* Interceptors stored in reverse order. Inner interceptors before outer interceptors.
* The reversal is needed so that we can build up the interception chain around the
* server request.
*/
var reversedInterceptors = [];
forEach(interceptorFactories, function(interceptorFactory) {
reversedInterceptors.unshift(isString(interceptorFactory)
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
});
/**
* @ngdoc service
* @kind function
* @name $http
* @requires ng.$httpBackend
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
* object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
* it is important to familiarize yourself with these APIs and the guarantees they provide.
*
*
* ## General usage
* The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
* that is used to generate an HTTP request and returns a {@link ng.$q promise}.
*
* ```js
* // Simple GET request example:
* $http({
* method: 'GET',
* url: '/someUrl'
* }).then(function successCallback(response) {
* // this callback will be called asynchronously
* // when the response is available
* }, function errorCallback(response) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
* The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform
* functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
* - **statusText** – `{string}` – HTTP status text of the response.
*
* A response status code between 200 and 299 is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
*
* ## Shortcut methods
*
* Shortcut methods are also available. All shortcut methods require passing in the URL, and
* request data must be passed in for POST/PUT requests. An optional config can be passed as the
* last argument.
*
* ```js
* $http.get('/someUrl', config).then(successCallback, errorCallback);
* $http.post('/someUrl', data, config).then(successCallback, errorCallback);
* ```
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
* - {@link ng.$http#patch $http.patch}
*
*
* ## Writing Unit Tests that use $http
* When unit testing (using {@link ngMock ngMock}), it is necessary to call
* {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
* request using trained responses.
*
* ```
* $httpBackend.expectGET(...);
* $http.get(...);
* $httpBackend.flush();
* ```
*
* ## Deprecation Notice
* <div class="alert alert-danger">
* The `$http` legacy promise methods `success` and `error` have been deprecated.
* Use the standard `then` method instead.
* If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
* `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
* </div>
*
* ## Setting HTTP Headers
*
* The $http service will automatically add certain HTTP headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from these configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with the lowercased HTTP method name as the key, e.g.
* `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
*
* The defaults can also be set at runtime via the `$http.defaults` object in the same
* fashion. For example:
*
* ```
* module.run(function($http) {
* $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
* });
* ```
*
* In addition, you can supply a `headers` property in the config object passed when
* calling `$http(config)`, which overrides the defaults without changing them globally.
*
* To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
* Use the `headers` property, setting the desired header to `undefined`. For example:
*
* ```js
* var req = {
* method: 'POST',
* url: 'http://example.com',
* headers: {
* 'Content-Type': undefined
* },
* data: { test: 'test' }
* }
*
* $http(req).then(function(){...}, function(){...});
* ```
*
* ## Transforming Requests and Responses
*
* Both requests and responses can be transformed using transformation functions: `transformRequest`
* and `transformResponse`. These properties can be a single function that returns
* the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
* which allows you to `push` or `unshift` a new transformation function into the transformation chain.
*
* ### Default Transformations
*
* The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
* `defaults.transformResponse` properties. If a request does not provide its own transformations
* then these will be applied.
*
* You can augment or replace the default transformations by modifying these properties by adding to or
* replacing the array.
*
* Angular provides the following default transformations:
*
* Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
*
* - If the `data` property of the request configuration object contains an object, serialize it
* into JSON format.
*
* Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
*
* - If XSRF prefix is detected, strip it (see Security Considerations section below).
* - If JSON response is detected, deserialize it using a JSON parser.
*
*
* ### Overriding the Default Transformations Per Request
*
* If you wish override the request/response transformations only for a single request then provide
* `transformRequest` and/or `transformResponse` properties on the configuration object passed
* into `$http`.
*
* Note that if you provide these properties on the config object the default transformations will be
* overwritten. If you wish to augment the default transformations then you must include them in your
* local transformation array.
*
* The following code demonstrates adding a new response transformation to be run after the default response
* transformations have been run.
*
* ```js
* function appendTransform(defaults, transform) {
*
* // We can't guarantee that the default transformation is an array
* defaults = angular.isArray(defaults) ? defaults : [defaults];
*
* // Append the new transformation to the defaults
* return defaults.concat(transform);
* }
*
* $http({
* url: '...',
* method: 'GET',
* transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
* return doTransform(value);
* })
* });
* ```
*
*
* ## Caching
*
* To enable caching, set the request configuration `cache` property to `true` (to use default
* cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
* When the cache is enabled, `$http` stores the response from the server in the specified
* cache. The next time the same request is made, the response is served from the cache without
* sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same URL that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response from the first request.
*
* You can change the default cache to a new object (built with
* {@link ng.$cacheFactory `$cacheFactory`}) by updating the
* {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
* their `cache` property to `true` will now use this cache object.
*
* If you set the default cache to `false` then only requests that specify their own custom
* cache object will be cached.
*
* ## Interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication, or any kind of synchronous or
* asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
* able to intercept requests before they are handed to the server and
* responses before they are handed over to the application code that
* initiated these requests. The interceptors leverage the {@link ng.$q
* promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
*
* The interceptors are service factories that are registered with the `$httpProvider` by
* adding them to the `$httpProvider.interceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor.
*
* There are two kinds of interceptors (and two kinds of rejection interceptors):
*
* * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
* modify the `config` object or create a new one. The function needs to return the `config`
* object directly, or a promise containing the `config` or a new `config` object.
* * `requestError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
* * `response`: interceptors get called with http `response` object. The function is free to
* modify the `response` object or create a new one. The function needs to return the `response`
* object directly, or as a promise containing the `response` or a new `response` object.
* * `responseError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
*
*
* ```js
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return {
* // optional method
* 'request': function(config) {
* // do something on success
* return config;
* },
*
* // optional method
* 'requestError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* },
*
*
*
* // optional method
* 'response': function(response) {
* // do something on success
* return response;
* },
*
* // optional method
* 'responseError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* }
* };
* });
*
* $httpProvider.interceptors.push('myHttpInterceptor');
*
*
* // alternatively, register the interceptor via an anonymous factory
* $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
* return {
* 'request': function(config) {
* // same as above
* },
*
* 'response': function(response) {
* // same as above
* }
* };
* });
* ```
*
* ## Security Considerations
*
* When designing web applications, consider security threats from:
*
* - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ### JSON Vulnerability Protection
*
* A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* allows third party website to turn your JSON resource URL into
* [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* ```js
* ['one','two']
* ```
*
* which is vulnerable to attack, your server can return:
* ```js
* )]}',
* ['one','two']
* ```
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ### Cross Site Request Forgery (XSRF) Protection
*
* [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
* an unauthorized site can gain your user's private data. Angular provides a mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
* JavaScript that runs on your domain could read the cookie, your server can be assured that
* the XHR came from JavaScript running on your domain. The header will not be set for
* cross-domain requests.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
* making up its own tokens). We recommend that the token is a digest of your site's
* authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
* for added security.
*
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
* or the per-request config object.
*
* In order to prevent collisions in environments where multiple Angular apps share the
* same domain or subdomain, we recommend that each application uses unique cookie name.
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
* with the `paramSerializer` and appended as GET parameters.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings or functions which return strings representing
* HTTP headers to send to the server. If the return value of a function is null, the
* header will not be sent. Functions accept a config object as an argument.
* - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
* - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
* - **transformRequest** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default Transformations}
* - **transformResponse** –
* `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body, headers and status and returns its transformed (typically deserialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default TransformationjqLiks}
* - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
* prepare the string representation of request parameters (specified as an object).
* If specified as string, it is interpreted as function registered with the
* {@link $injector $injector}, which means you can create your own serializer
* by registering it as a {@link auto.$provide#service service}.
* The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
* alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
* that should abort the request when resolved.
* - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
* XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
* for more information.
* - **responseType** - `{string}` - see
* [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
*
* @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
* when the request succeeds or fails.
*
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example module="httpExample">
<file name="index.html">
<div ng-controller="FetchController">
<select ng-model="method" aria-label="Request method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80" aria-label="URL" />
<button id="fetchbtn" ng-click="fetch()">fetch</button><br>
<button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button id="samplejsonpbtn"
ng-click="updateModel('JSONP',
'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button id="invalidjsonpbtn"
ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
}, function(response) {
$scope.data = response.data || "Request failed";
$scope.status = response.status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}]);
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="protractor.js" type="protractor">
var status = element(by.binding('status'));
var data = element(by.binding('data'));
var fetchBtn = element(by.id('fetchbtn'));
var sampleGetBtn = element(by.id('samplegetbtn'));
var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
it('should make an xhr GET request', function() {
sampleGetBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('200');
expect(data.getText()).toMatch(/Hello, \$http!/);
});
// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
// it('should make a JSONP request to angularjs.org', function() {
// sampleJsonpBtn.click();
// fetchBtn.click();
// expect(status.getText()).toMatch('200');
// expect(data.getText()).toMatch(/Super Hero!/);
// });
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
invalidJsonpBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('0');
expect(data.getText()).toMatch('Request failed');
});
</file>
</example>
*/
function $http(requestConfig) {
if (!isObject(requestConfig)) {
throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
}
var config = extend({
method: 'get',
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse,
paramSerializer: defaults.paramSerializer
}, requestConfig);
config.headers = mergeHeaders(requestConfig);
config.method = uppercase(config.method);
config.paramSerializer = isString(config.paramSerializer) ?
$injector.get(config.paramSerializer) : config.paramSerializer;
var serverRequest = function(config) {
var headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
// strip content-type if data is undefined
if (isUndefined(reqData)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
}
if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
config.withCredentials = defaults.withCredentials;
}
// send request
return sendReq(config, reqData).then(transformResponse, transformResponse);
};
var chain = [serverRequest, undefined];
var promise = $q.when(config);
// apply interceptors
forEach(reversedInterceptors, function(interceptor) {
if (interceptor.request || interceptor.requestError) {
chain.unshift(interceptor.request, interceptor.requestError);
}
if (interceptor.response || interceptor.responseError) {
chain.push(interceptor.response, interceptor.responseError);
}
});
while (chain.length) {
var thenFn = chain.shift();
var rejectFn = chain.shift();
promise = promise.then(thenFn, rejectFn);
}
if (useLegacyPromise) {
promise.success = function(fn) {
assertArgFn(fn, 'fn');
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
assertArgFn(fn, 'fn');
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
} else {
promise.success = $httpMinErrLegacyFn('success');
promise.error = $httpMinErrLegacyFn('error');
}
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response);
resp.data = transformData(response.data, response.headers, response.status,
config.transformResponse);
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
function executeHeaderFns(headers, config) {
var headerContent, processedHeaders = {};
forEach(headers, function(headerFn, header) {
if (isFunction(headerFn)) {
headerContent = headerFn(config);
if (headerContent != null) {
processedHeaders[header] = headerContent;
}
} else {
processedHeaders[header] = headerFn;
}
});
return processedHeaders;
}
function mergeHeaders(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName;
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
// execute if header value is a function for merged headers
return executeHeaderFns(reqHeaders, shallowCopy(config));
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name $http#get
*
* @description
* Shortcut method to perform `GET` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#delete
*
* @description
* Shortcut method to perform `DELETE` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#head
*
* @description
* Shortcut method to perform `HEAD` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#jsonp
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* The name of the callback should be the string `JSON_CALLBACK`.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name $http#post
*
* @description
* Shortcut method to perform `POST` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#put
*
* @description
* Shortcut method to perform `PUT` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#patch
*
* @description
* Shortcut method to perform `PATCH` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put', 'patch');
/**
* @ngdoc property
* @name $http#defaults
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers, withCredentials as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = defaults;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend({}, config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend({}, config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request.
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
reqHeaders = config.headers,
url = buildUrl(config.url, config.paramSerializer(config.params));
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = isObject(config.cache) ? config.cache
: isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (isDefined(cachedResp)) {
if (isPromiseLike(cachedResp)) {
// cached request has already been sent, but there is no response yet
cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
} else {
resolvePromise(cachedResp, 200, {}, 'OK');
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, set the xsrf headers and
// send the request to the backend
if (isUndefined(cachedResp)) {
var xsrfValue = urlIsSameOrigin(config.url)
? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials, config.responseType);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString, statusText) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString), statusText]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
function resolveHttpPromise() {
resolvePromise(response, status, headersString, statusText);
}
if (useApplyAsync) {
$rootScope.$applyAsync(resolveHttpPromise);
} else {
resolveHttpPromise();
if (!$rootScope.$$phase) $rootScope.$apply();
}
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers, statusText) {
//status: HTTP response status code, 0, -1 (aborted by timeout / promise)
status = status >= -1 ? status : 0;
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config,
statusText: statusText
});
}
function resolvePromiseWithResult(result) {
resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
}
function removePendingReq() {
var idx = $http.pendingRequests.indexOf(config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, serializedParams) {
if (serializedParams.length > 0) {
url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
}
return url;
}
}];
}
| evil-wolf/angular.js | src/ng/http.js | JavaScript | mit | 49,570 |
import { run } from '@ember/runloop';
import { guidFor, setName } from 'ember-utils';
import { context } from 'ember-environment';
import EmberObject from '../../../lib/system/object';
import Namespace from '../../../lib/system/namespace';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
let originalLookup = context.lookup;
let lookup;
moduleFor(
'system/object/toString',
class extends AbstractTestCase {
beforeEach() {
context.lookup = lookup = {};
}
afterEach() {
context.lookup = originalLookup;
}
['@test toString() returns the same value if called twice'](assert) {
let Foo = Namespace.create();
Foo.toString = function() {
return 'Foo';
};
Foo.Bar = EmberObject.extend();
assert.equal(Foo.Bar.toString(), 'Foo.Bar');
assert.equal(Foo.Bar.toString(), 'Foo.Bar');
let obj = Foo.Bar.create();
assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>');
assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>');
assert.equal(Foo.Bar.toString(), 'Foo.Bar');
run(Foo, 'destroy');
}
['@test toString on a class returns a useful value when nested in a namespace'](assert) {
let obj;
let Foo = Namespace.create();
Foo.toString = function() {
return 'Foo';
};
Foo.Bar = EmberObject.extend();
assert.equal(Foo.Bar.toString(), 'Foo.Bar');
obj = Foo.Bar.create();
assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>');
Foo.Baz = Foo.Bar.extend();
assert.equal(Foo.Baz.toString(), 'Foo.Baz');
obj = Foo.Baz.create();
assert.equal(obj.toString(), '<Foo.Baz:' + guidFor(obj) + '>');
obj = Foo.Bar.create();
assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>');
run(Foo, 'destroy');
}
['@test toString on a namespace finds the namespace in lookup'](assert) {
let Foo = (lookup.Foo = Namespace.create());
assert.equal(Foo.toString(), 'Foo');
run(Foo, 'destroy');
}
['@test toString on a namespace finds the namespace in lookup'](assert) {
let Foo = (lookup.Foo = Namespace.create());
let obj;
Foo.Bar = EmberObject.extend();
assert.equal(Foo.Bar.toString(), 'Foo.Bar');
obj = Foo.Bar.create();
assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>');
run(Foo, 'destroy');
}
['@test toString on a namespace falls back to modulePrefix, if defined'](assert) {
let Foo = Namespace.create({ modulePrefix: 'foo' });
assert.equal(Foo.toString(), 'foo');
run(Foo, 'destroy');
}
['@test toString includes toStringExtension if defined'](assert) {
let Foo = EmberObject.extend({
toStringExtension() {
return 'fooey';
},
});
let foo = Foo.create();
let Bar = EmberObject.extend({});
let bar = Bar.create();
// simulate these classes being defined on a Namespace
setName(Foo, 'Foo');
setName(Bar, 'Bar');
assert.equal(
bar.toString(),
'<Bar:' + guidFor(bar) + '>',
'does not include toStringExtension part'
);
assert.equal(
foo.toString(),
'<Foo:' + guidFor(foo) + ':fooey>',
'Includes toStringExtension result'
);
}
}
);
| csantero/ember.js | packages/ember-runtime/tests/system/object/toString_test.js | JavaScript | mit | 3,366 |
//
// Copyright 2011 Jeff Verkoeyen
//
// 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.
//
#import <UIKit/UIKit.h>
#if defined(DEBUG) || defined(NI_DEBUG)
@class NIOverviewPageView;
/**
* The root scrolling page view of the Overview.
*
* @ingroup Overview
*/
@interface NIOverviewView : UIView {
@private
UIImage* _backgroundImage;
// State
BOOL _translucent;
NSMutableArray* _pageViews;
// Views
UIScrollView* _pagingScrollView;
}
/**
* Whether the view has a translucent background or not.
*/
@property (nonatomic, readwrite, assign) BOOL translucent;
/**
* Prepends a new page to the Overview.
*/
- (void)prependPageView:(NIOverviewPageView *)page;
/**
* Adds a new page to the Overview.
*/
- (void)addPageView:(NIOverviewPageView *)page;
/**
* Removes a page from the Overview.
*/
- (void)removePageView:(NIOverviewPageView *)page;
/**
* Update all of the views.
*/
- (void)updatePages;
- (void)flashScrollIndicators;
@end
#endif
| jyotiness/ARTSDK | thirdparty/nimbus/src/overview/src/NIOverviewView.h | C | mit | 1,498 |
define(["../core","../manipulation"],function(e){function t(t,n){var o,a=e(n.createElement(t)).appendTo(n.body),d=window.getDefaultComputedStyle&&(o=window.getDefaultComputedStyle(a[0]))?o.display:e.css(a[0],"display");return a.detach(),d}function n(n){var d=document,r=a[n];return r||(r=t(n,d),"none"!==r&&r||(o=(o||e("<iframe frameborder='0' width='0' height='0'/>")).appendTo(d.documentElement),d=o[0].contentDocument,d.write(),d.close(),r=t(n,d),o.detach()),a[n]=r),r}var o,a={};return n}); | dandenney/dandenney.com | build/assets/javascripts/vendor/jquery/src/css/defaultDisplay.js | JavaScript | mit | 494 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template is_permutation</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost Algorithm Library">
<link rel="up" href="../../header/boost/algorithm/cxx11/is_permutation_hpp.html" title="Header <boost/algorithm/cxx11/is_permutation.hpp>">
<link rel="prev" href="../../header/boost/algorithm/cxx11/is_permutation_hpp.html" title="Header <boost/algorithm/cxx11/is_permutation.hpp>">
<link rel="next" href="is_permutation_idp41162768.html" title="Function template is_permutation">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../header/boost/algorithm/cxx11/is_permutation_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/algorithm/cxx11/is_permutation_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="is_permutation_idp41162768.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.algorithm.is_permutation_idp41153984"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function template is_permutation</span></h2>
<p>boost::algorithm::is_permutation — Tests to see if the sequence [first,last) is a permutation of the sequence starting at first2. </p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../header/boost/algorithm/cxx11/is_permutation_hpp.html" title="Header <boost/algorithm/cxx11/is_permutation.hpp>">boost/algorithm/cxx11/is_permutation.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> ForwardIterator1<span class="special">,</span> <span class="keyword">typename</span> ForwardIterator2<span class="special">,</span>
<span class="keyword">typename</span> BinaryPredicate<span class="special">></span>
<span class="keyword">bool</span> <span class="identifier">is_permutation</span><span class="special">(</span><span class="identifier">ForwardIterator1</span> first1<span class="special">,</span> <span class="identifier">ForwardIterator1</span> last1<span class="special">,</span>
<span class="identifier">ForwardIterator2</span> first2<span class="special">,</span> <span class="identifier">BinaryPredicate</span> p<span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp90182128"></a><h2>Description</h2>
<p>
</p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../../doc/src/images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>This function is part of the C++2011 standard library. We will use the standard one if it is available, otherwise we have our own implementation. </p></td></tr>
</table></div>
<p>
</p>
<div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody><tr>
<td><p><span class="term">Parameters:</span></p></td>
<td><div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><code class="computeroutput">first1</code></span></p></td>
<td><p>The start of the input sequence </p></td>
</tr>
<tr>
<td><p><span class="term"><code class="computeroutput">first2</code></span></p></td>
<td><p>The start of the second sequence </p></td>
</tr>
<tr>
<td><p><span class="term"><code class="computeroutput">last1</code></span></p></td>
<td><p>One past the end of the input sequence </p></td>
</tr>
<tr>
<td><p><span class="term"><code class="computeroutput">p</code></span></p></td>
<td><p>The predicate to compare elements with</p></td>
</tr>
</tbody>
</table></div></td>
</tr></tbody>
</table></div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2010-2012 Marshall Clow<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../header/boost/algorithm/cxx11/is_permutation_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/algorithm/cxx11/is_permutation_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="is_permutation_idp41162768.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| TyRoXx/cdm | original_sources/boost_1_59_0/libs/algorithm/doc/html/boost/algorithm/is_permutation_idp41153984.html | HTML | mit | 6,251 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using COM = System.Runtime.InteropServices.ComTypes;
// Disable obsolete warnings about VarEnum and COM-marshaling APIs in CoreCLR
#pragma warning disable 618
namespace System.Management.Automation
{
internal static class ComInvoker
{
// DISP HRESULTS - may be returned by IDispatch.Invoke
private const int DISP_E_EXCEPTION = unchecked((int)0x80020009);
// LCID for en-US culture
private const int LCID_DEFAULT = 0x0409;
// The dispatch identifier for a parameter that receives the value of an assignment in a PROPERTYPUT.
// See https://msdn.microsoft.com/library/windows/desktop/ms221242(v=vs.85).aspx for details.
private const int DISPID_PROPERTYPUT = -3;
// Alias of GUID_NULL. It's a GUID set to all zero
private static readonly Guid s_IID_NULL = new Guid();
// Size of the Variant struct
private static readonly int s_variantSize = Marshal.SizeOf<Variant>();
/// <summary>
/// Make a by-Ref VARIANT value based on the passed-in VARIANT argument.
/// </summary>
/// <param name="srcVariantPtr">The source Variant pointer.</param>
/// <param name="destVariantPtr">The destination Variant pointer.</param>
private static unsafe void MakeByRefVariant(IntPtr srcVariantPtr, IntPtr destVariantPtr)
{
var srcVariant = (Variant*)srcVariantPtr;
var destVariant = (Variant*)destVariantPtr;
switch ((VarEnum)srcVariant->_typeUnion._vt)
{
case VarEnum.VT_EMPTY:
case VarEnum.VT_NULL:
// These cannot combine with VT_BYREF. Should try passing as a variant reference
// We follow the code in ComBinder to handle 'VT_EMPTY' and 'VT_NULL'
destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant);
destVariant->_typeUnion._vt = (ushort)VarEnum.VT_VARIANT | (ushort)VarEnum.VT_BYREF;
return;
case VarEnum.VT_RECORD:
// Representation of record is the same with or without byref
destVariant->_typeUnion._unionTypes._record._record = srcVariant->_typeUnion._unionTypes._record._record;
destVariant->_typeUnion._unionTypes._record._recordInfo = srcVariant->_typeUnion._unionTypes._record._recordInfo;
break;
case VarEnum.VT_VARIANT:
destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant);
break;
case VarEnum.VT_DECIMAL:
destVariant->_typeUnion._unionTypes._byref = new IntPtr(&(srcVariant->_decimal));
break;
default:
// All the other cases start at the same offset (it's a Union) so using &_i4 should work.
// This is the same code as in CLR implementation. It could be &_i1, &_i2 and etc. CLR implementation just prefer using &_i4.
destVariant->_typeUnion._unionTypes._byref = new IntPtr(&(srcVariant->_typeUnion._unionTypes._i4));
break;
}
destVariant->_typeUnion._vt = (ushort)(srcVariant->_typeUnion._vt | (ushort)VarEnum.VT_BYREF);
}
/// <summary>
/// Alloc memory for a VARIANT array with the specified length.
/// Also initialize the VARIANT elements to be the type 'VT_EMPTY'.
/// </summary>
/// <param name="length">Array length.</param>
/// <returns>Pointer to the array.</returns>
private static unsafe IntPtr NewVariantArray(int length)
{
IntPtr variantArray = Marshal.AllocCoTaskMem(s_variantSize * length);
for (int i = 0; i < length; i++)
{
IntPtr currentVarPtr = variantArray + s_variantSize * i;
var currentVar = (Variant*)currentVarPtr;
currentVar->_typeUnion._vt = (ushort)VarEnum.VT_EMPTY;
}
return variantArray;
}
/// <summary>
/// Generate the ByRef array indicating whether the corresponding argument is by-reference.
/// </summary>
/// <param name="parameters">Parameters retrieved from metadata.</param>
/// <param name="argumentCount">Count of arguments to pass in IDispatch.Invoke.</param>
/// <param name="isPropertySet">Indicate if we are handling arguments for PropertyPut/PropertyPutRef.</param>
/// <returns></returns>
internal static bool[] GetByRefArray(ParameterInformation[] parameters, int argumentCount, bool isPropertySet)
{
if (parameters.Length == 0)
{
return null;
}
var byRef = new bool[argumentCount];
int argsToProcess = argumentCount;
if (isPropertySet)
{
// If it's PropertySet, then the last value in arguments is the right-hand side value.
// There is no corresponding parameter for that value, so it's for sure not by-ref.
// Hence, set the last item of byRef array to be false.
argsToProcess = argumentCount - 1;
byRef[argsToProcess] = false;
}
Diagnostics.Assert(parameters.Length >= argsToProcess,
"There might be more parameters than argsToProcess due unspecified optional arguments");
for (int i = 0; i < argsToProcess; i++)
{
byRef[i] = parameters[i].isByRef;
}
return byRef;
}
/// <summary>
/// Invoke the COM member.
/// </summary>
/// <param name="target">IDispatch object.</param>
/// <param name="dispId">Dispatch identifier that identifies the member.</param>
/// <param name="args">Arguments passed in.</param>
/// <param name="byRef">Boolean array that indicates by-Ref parameters.</param>
/// <param name="invokeKind">Invocation kind.</param>
/// <returns></returns>
internal static object Invoke(IDispatch target, int dispId, object[] args, bool[] byRef, COM.INVOKEKIND invokeKind)
{
Diagnostics.Assert(target != null, "Caller makes sure an IDispatch object passed in.");
Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length,
"If 'args' and 'byRef' are not null, then they should be one-on-one mapping.");
int argCount = args != null ? args.Length : 0;
int refCount = byRef != null ? byRef.Count(c => c) : 0;
IntPtr variantArgArray = IntPtr.Zero, dispIdArray = IntPtr.Zero, tmpVariants = IntPtr.Zero;
try
{
// Package arguments
if (argCount > 0)
{
variantArgArray = NewVariantArray(argCount);
int refIndex = 0;
for (int i = 0; i < argCount; i++)
{
// !! The arguments should be in REVERSED order!!
int actualIndex = argCount - i - 1;
IntPtr varArgPtr = variantArgArray + s_variantSize * actualIndex;
// If need to pass by ref, create a by-ref variant
if (byRef != null && byRef[i])
{
// Allocate memory for temporary VARIANTs used in by-ref marshalling
if (tmpVariants == IntPtr.Zero)
{
tmpVariants = NewVariantArray(refCount);
}
// Create a VARIANT that the by-ref VARIANT points to
IntPtr tmpVarPtr = tmpVariants + s_variantSize * refIndex;
Marshal.GetNativeVariantForObject(args[i], tmpVarPtr);
// Create the by-ref VARIANT
MakeByRefVariant(tmpVarPtr, varArgPtr);
refIndex++;
}
else
{
Marshal.GetNativeVariantForObject(args[i], varArgPtr);
}
}
}
var paramArray = new COM.DISPPARAMS[1];
paramArray[0].rgvarg = variantArgArray;
paramArray[0].cArgs = argCount;
if (invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUT || invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUTREF)
{
// For property putters, the first DISPID argument needs to be DISPID_PROPERTYPUT
dispIdArray = Marshal.AllocCoTaskMem(4); // Allocate 4 bytes to hold a 32-bit signed integer
Marshal.WriteInt32(dispIdArray, DISPID_PROPERTYPUT);
paramArray[0].cNamedArgs = 1;
paramArray[0].rgdispidNamedArgs = dispIdArray;
}
else
{
// Otherwise, no named parameters are necessary since powershell parser doesn't support named parameter
paramArray[0].cNamedArgs = 0;
paramArray[0].rgdispidNamedArgs = IntPtr.Zero;
}
// Make the call
EXCEPINFO info = default(EXCEPINFO);
object result = null;
try
{
// 'puArgErr' is set when IDispatch.Invoke fails with error code 'DISP_E_PARAMNOTFOUND' and 'DISP_E_TYPEMISMATCH'.
// Appropriate exceptions will be thrown in such cases, but FullCLR doesn't use 'puArgErr' in the exception handling, so we also ignore it.
uint puArgErrNotUsed = 0;
target.Invoke(dispId, s_IID_NULL, LCID_DEFAULT, invokeKind, paramArray, out result, out info, out puArgErrNotUsed);
}
catch (Exception innerException)
{
// When 'IDispatch.Invoke' returns error code, CLR will raise exception based on internal HR-to-Exception mapping.
// Description of the return code can be found at https://msdn.microsoft.com/library/windows/desktop/ms221479(v=vs.85).aspx
// According to CoreCLR team (yzha), the exception needs to be wrapped as an inner exception of TargetInvocationException.
string exceptionMsg = null;
if (innerException.HResult == DISP_E_EXCEPTION)
{
// Invoke was successful but the actual underlying method failed.
// In this case, we use EXCEPINFO to get additional error info.
// Use EXCEPINFO.scode or EXCEPINFO.wCode as HR to construct the correct exception.
int code = info.scode != 0 ? info.scode : info.wCode;
innerException = Marshal.GetExceptionForHR(code, IntPtr.Zero) ?? innerException;
// Get the richer error description if it's available.
if (info.bstrDescription != IntPtr.Zero)
{
exceptionMsg = Marshal.PtrToStringBSTR(info.bstrDescription);
Marshal.FreeBSTR(info.bstrDescription);
}
// Free the BSTRs
if (info.bstrSource != IntPtr.Zero)
{
Marshal.FreeBSTR(info.bstrSource);
}
if (info.bstrHelpFile != IntPtr.Zero)
{
Marshal.FreeBSTR(info.bstrHelpFile);
}
}
var outerException = exceptionMsg == null
? new TargetInvocationException(innerException)
: new TargetInvocationException(exceptionMsg, innerException);
throw outerException;
}
// Now back propagate the by-ref arguments
if (refCount > 0)
{
for (int i = 0; i < argCount; i++)
{
// !! The arguments should be in REVERSED order!!
int actualIndex = argCount - i - 1;
// If need to pass by ref, back propagate
if (byRef != null && byRef[i])
{
args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + s_variantSize * actualIndex);
}
}
}
return result;
}
finally
{
// Free the variant argument array
if (variantArgArray != IntPtr.Zero)
{
for (int i = 0; i < argCount; i++)
{
VariantClear(variantArgArray + s_variantSize * i);
}
Marshal.FreeCoTaskMem(variantArgArray);
}
// Free the dispId array
if (dispIdArray != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(dispIdArray);
}
// Free the temporary variants created when handling by-Ref arguments
if (tmpVariants != IntPtr.Zero)
{
for (int i = 0; i < refCount; i++)
{
VariantClear(tmpVariants + s_variantSize * i);
}
Marshal.FreeCoTaskMem(tmpVariants);
}
}
}
/// <summary>
/// Clear variables of type VARIANTARG (or VARIANT) before the memory containing the VARIANTARG is freed.
/// </summary>
/// <param name="pVariant"></param>
[DllImport("oleaut32.dll")]
internal static extern void VariantClear(IntPtr pVariant);
/// <summary>
/// We have to declare 'bstrSource', 'bstrDescription' and 'bstrHelpFile' as pointers because
/// CLR marshalling layer would try to free those BSTRs by default and that is not correct.
/// Therefore, manually marshalling might be needed to extract 'bstrDescription'.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct EXCEPINFO
{
public short wCode;
public short wReserved;
public IntPtr bstrSource;
public IntPtr bstrDescription;
public IntPtr bstrHelpFile;
public int dwHelpContext;
public IntPtr pvReserved;
public IntPtr pfnDeferredFillIn;
public int scode;
}
/// <summary>
/// VARIANT type used for passing arguments in COM interop.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Variant
{
// Most of the data types in the Variant are carried in _typeUnion
[FieldOffset(0)]
internal TypeUnion _typeUnion;
// Decimal is the largest data type and it needs to use the space that is normally unused in TypeUnion._wReserved1, etc.
// Hence, it is declared to completely overlap with TypeUnion. A Decimal does not use the first two bytes, and so
// TypeUnion._vt can still be used to encode the type.
[FieldOffset(0)]
internal Decimal _decimal;
[StructLayout(LayoutKind.Explicit)]
internal struct TypeUnion
{
[FieldOffset(0)]
internal ushort _vt;
[FieldOffset(2)]
internal ushort _wReserved1;
[FieldOffset(4)]
internal ushort _wReserved2;
[FieldOffset(6)]
internal ushort _wReserved3;
[FieldOffset(8)]
internal UnionTypes _unionTypes;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Record
{
internal IntPtr _record;
internal IntPtr _recordInfo;
}
[StructLayout(LayoutKind.Explicit)]
internal struct UnionTypes
{
[FieldOffset(0)]
internal sbyte _i1;
[FieldOffset(0)]
internal Int16 _i2;
[FieldOffset(0)]
internal Int32 _i4;
[FieldOffset(0)]
internal Int64 _i8;
[FieldOffset(0)]
internal byte _ui1;
[FieldOffset(0)]
internal UInt16 _ui2;
[FieldOffset(0)]
internal UInt32 _ui4;
[FieldOffset(0)]
internal UInt64 _ui8;
[FieldOffset(0)]
internal Int32 _int;
[FieldOffset(0)]
internal UInt32 _uint;
[FieldOffset(0)]
internal Int16 _bool;
[FieldOffset(0)]
internal Int32 _error;
[FieldOffset(0)]
internal Single _r4;
[FieldOffset(0)]
internal double _r8;
[FieldOffset(0)]
internal Int64 _cy;
[FieldOffset(0)]
internal double _date;
[FieldOffset(0)]
internal IntPtr _bstr;
[FieldOffset(0)]
internal IntPtr _unknown;
[FieldOffset(0)]
internal IntPtr _dispatch;
[FieldOffset(0)]
internal IntPtr _pvarVal;
[FieldOffset(0)]
internal IntPtr _byref;
[FieldOffset(0)]
internal Record _record;
}
}
}
}
| JamesWTruher/PowerShell-1 | src/System.Management.Automation/engine/COM/ComInvoker.cs | C# | mit | 18,455 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.CSharp
{
public static partial class SyntaxFacts
{
private sealed class SyntaxKindEqualityComparer : IEqualityComparer<SyntaxKind>
{
public bool Equals(SyntaxKind x, SyntaxKind y)
{
return x == y;
}
public int GetHashCode(SyntaxKind obj)
{
return (int)obj;
}
}
/// <summary>
/// A custom equality comparer for <see cref="SyntaxKind"/>
/// </summary>
/// <remarks>
/// PERF: The framework specializes EqualityComparer for enums, but only if the underlying type is System.Int32
/// Since SyntaxKind's underlying type is System.UInt16, ObjectEqualityComparer will be chosen instead.
/// </remarks>
public static IEqualityComparer<SyntaxKind> EqualityComparer { get; } = new SyntaxKindEqualityComparer();
}
}
| jmarolf/roslyn | src/Compilers/CSharp/Portable/Syntax/SyntaxKindEqualityComparer.cs | C# | mit | 1,204 |
#!/usr/bin/env node
'use strict';
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
chalk = require('chalk'),
Table = require('cli-table');
var fileNames = [
'abc',
'amazon',
//'eloquentjavascript',
//'es6-draft',
'es6-table',
'google',
'html-minifier',
'msn',
'newyorktimes',
'stackoverflow',
'wikipedia',
'es6'
];
fileNames = fileNames.sort().reverse();
var table = new Table({
head: ['File', 'Before', 'After', 'Savings', 'Time'],
colWidths: [20, 25, 25, 20, 20]
});
function toKb(size) {
return (size / 1024).toFixed(2);
}
function redSize(size) {
return chalk.red.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}
function greenSize(size) {
return chalk.green.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}
function blueSavings(oldSize, newSize) {
var savingsPercent = (1 - newSize / oldSize) * 100;
var savings = (oldSize - newSize) / 1024;
return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) + ' KB)');
}
function blueTime(time) {
return chalk.cyan.bold(time) + chalk.white(' ms');
}
function test(fileName, done) {
if (!fileName) {
console.log('\n' + table.toString());
return;
}
console.log('Processing...', fileName);
var filePath = path.join('benchmarks/', fileName + '.html');
var minifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html');
var gzFilePath = path.join('benchmarks/generated/', fileName + '.html.gz');
var gzMinifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html.gz');
var command = path.normalize('./cli.js') + ' ' + filePath + ' -c benchmark.conf' + ' -o ' + minifiedFilePath;
// Open and read the size of the original input
fs.stat(filePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + filePath);
}
var originalSize = stats.size;
exec('gzip --keep --force --best --stdout ' + filePath + ' > ' + gzFilePath, function () {
// Open and read the size of the gzipped original
fs.stat(gzFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + gzFilePath);
}
var gzOriginalSize = stats.size;
// Begin timing after gzipped fixtures have been created
var startTime = new Date();
exec('node ' + command, function () {
// Open and read the size of the minified output
fs.stat(minifiedFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + minifiedFilePath);
}
var minifiedSize = stats.size;
var minifiedTime = new Date() - startTime;
// Gzip the minified output
exec('gzip --keep --force --best --stdout ' + minifiedFilePath + ' > ' + gzMinifiedFilePath, function () {
// Open and read the size of the minified+gzipped output
fs.stat(gzMinifiedFilePath, function (err, stats) {
if (err) {
throw new Error('There was an error reading ' + gzMinifiedFilePath);
}
var gzMinifiedSize = stats.size;
var gzMinifiedTime = new Date() - startTime;
table.push([
[fileName, '+ gzipped'].join('\n'),
[redSize(originalSize), redSize(gzOriginalSize)].join('\n'),
[greenSize(minifiedSize), greenSize(gzMinifiedSize)].join('\n'),
[blueSavings(originalSize, minifiedSize), blueSavings(gzOriginalSize, gzMinifiedSize)].join('\n'),
[blueTime(minifiedTime), blueTime(gzMinifiedTime)].join('\n')
]);
done();
});
});
});
});
});
});
});
}
(function run() {
test(fileNames.pop(), run);
})();
| psychoss/html-minifier | benchmark.js | JavaScript | mit | 3,946 |
/*
* Copyright (c) 2001-2007, Tom St Denis
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file hmac_memory.c
LTC_HMAC support, process a block of memory, Tom St Denis/Dobes Vandermeer
*/
#ifdef LTC_HMAC
/**
LTC_HMAC a block of memory to produce the authentication tag
@param hash The index of the hash to use
@param key The secret key
@param keylen The length of the secret key (octets)
@param in The data to LTC_HMAC
@param inlen The length of the data to LTC_HMAC (octets)
@param out [out] Destination of the authentication tag
@param outlen [in/out] Max size and resulting size of authentication tag
@return CRYPT_OK if successful
*/
int hmac_memory(int hash,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen)
{
hmac_state *hmac;
int err;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(in != NULL);
LTC_ARGCHK(out != NULL);
LTC_ARGCHK(outlen != NULL);
/* make sure hash descriptor is valid */
if ((err = hash_is_valid(hash)) != CRYPT_OK) {
return err;
}
/* is there a descriptor? */
if (hash_descriptor[hash].hmac_block != NULL) {
return hash_descriptor[hash].hmac_block(key, keylen, in, inlen, out, outlen);
}
/* nope, so call the hmac functions */
/* allocate ram for hmac state */
hmac = XMALLOC(sizeof(hmac_state));
if (hmac == NULL) {
return CRYPT_MEM;
}
if ((err = hmac_init(hmac, hash, key, keylen)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hmac_process(hmac, in, inlen)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hmac_done(hmac, out, outlen)) != CRYPT_OK) {
goto LBL_ERR;
}
err = CRYPT_OK;
LBL_ERR:
#ifdef LTC_CLEAN_STACK
zeromem(hmac, sizeof(hmac_state));
#endif
XFREE(hmac);
return err;
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_memory.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2007/05/12 14:37:41 $ */
| sigma-random/libteecrypt | libteecrypt/lib/libtomcrypt/src/mac/hmac/hmac_memory.c | C | mit | 3,768 |
steal('can/util', 'can/observe', function(can) {
// ** - 'this' will be the deepest item changed
// * - 'this' will be any changes within *, but * will be the
// this returned
// tells if the parts part of a delegate matches the broken up props of the event
// gives the prop to use as 'this'
// - parts - the attribute name of the delegate split in parts ['foo','*']
// - props - the split props of the event that happened ['foo','bar','0']
// - returns - the attribute to delegate too ('foo.bar'), or null if not a match
var matches = function(parts, props){
//check props parts are the same or
var len = parts.length,
i =0,
// keeps the matched props we will use
matchedProps = [],
prop;
// if the event matches
for(i; i< len; i++){
prop = props[i]
// if no more props (but we should be matching them)
// return null
if( typeof prop !== 'string' ) {
return null;
} else
// if we have a "**", match everything
if( parts[i] == "**" ) {
return props.join(".");
} else
// a match, but we want to delegate to "*"
if (parts[i] == "*"){
// only do this if there is nothing after ...
matchedProps.push(prop);
}
else if( prop === parts[i] ) {
matchedProps.push(prop);
} else {
return null;
}
}
return matchedProps.join(".");
},
// gets a change event and tries to figure out which
// delegates to call
delegate = function(event, prop, how, newVal, oldVal){
// pre-split properties to save some regexp time
var props = prop.split("."),
delegates = (this._observe_delegates || []).slice(0),
delegate,
attr,
matchedAttr,
hasMatch,
valuesEqual;
event.attr = prop;
event.lastAttr = props[props.length -1 ];
// for each delegate
for(var i =0; delegate = delegates[i++];){
// if there is a batchNum, this means that this
// event is part of a series of events caused by a single
// attrs call. We don't want to issue the same event
// multiple times
// setting the batchNum happens later
if((event.batchNum && delegate.batchNum === event.batchNum) || delegate.undelegated ){
continue;
}
// reset match and values tests
hasMatch = undefined;
valuesEqual = true;
// for each attr in a delegate
for(var a =0 ; a < delegate.attrs.length; a++){
attr = delegate.attrs[a];
// check if it is a match
if(matchedAttr = matches(attr.parts, props)){
hasMatch = matchedAttr;
}
// if it has a value, make sure it's the right value
// if it's set, we should probably check that it has a
// value no matter what
if(attr.value && valuesEqual /* || delegate.hasValues */){
valuesEqual = attr.value === ""+this.attr(attr.attr)
} else if (valuesEqual && delegate.attrs.length > 1){
// if there are multiple attributes, each has to at
// least have some value
valuesEqual = this.attr(attr.attr) !== undefined
}
}
// if there is a match and valuesEqual ... call back
if(hasMatch && valuesEqual) {
// how to get to the changed property from the delegate
var from = prop.replace(hasMatch+".","");
// if this event is part of a batch, set it on the delegate
// to only send one event
if(event.batchNum ){
delegate.batchNum = event.batchNum
}
// if we listen to change, fire those with the same attrs
// TODO: the attrs should probably be using from
if( delegate.event === 'change' ){
arguments[1] = from;
event.curAttr = hasMatch;
delegate.callback.apply(this.attr(hasMatch), can.makeArray( arguments));
} else if(delegate.event === how ){
// if it's a match, callback with the location of the match
delegate.callback.apply(this.attr(hasMatch), [event,newVal, oldVal, from]);
} else if(delegate.event === 'set' &&
how == 'add' ) {
// if we are listening to set, we should also listen to add
delegate.callback.apply(this.attr(hasMatch), [event,newVal, oldVal, from]);
}
}
}
};
can.extend(can.Observe.prototype,{
/**
* @function can.Observe.prototype.delegate
* @parent can.Observe.delegate
* @plugin can/observe/delegate
*
* `delegate( selector, event, handler(ev,newVal,oldVal,from) )` listen for changes
* in a child attribute from the parent. The child attribute
* does not have to exist.
*
*
* // create an observable
* var observe = can.Observe({
* foo : {
* bar : "Hello World"
* }
* })
*
* //listen to changes on a property
* observe.delegate("foo.bar","change", function(ev, prop, how, newVal, oldVal){
* // foo.bar has been added, set, or removed
* this //->
* });
*
* // change the property
* observe.attr('foo.bar',"Goodbye Cruel World")
*
* ## Types of events
*
* Delegate lets you listen to add, set, remove, and change events on property.
*
* __add__
*
* An add event is fired when a new property has been added.
*
* var o = new can.Control({});
* o.delegate("name","add", function(ev, value){
* // called once
* can.$('#name').show()
* })
* o.attr('name',"Justin")
* o.attr('name',"Brian");
*
* Listening to add events is useful for 'setup' functionality (in this case
* showing the <code>#name</code> element.
*
* __set__
*
* Set events are fired when a property takes on a new value. set events are
* always fired after an add.
*
* o.delegate("name","set", function(ev, value){
* // called twice
* can.$('#name').text(value)
* })
* o.attr('name',"Justin")
* o.attr('name',"Brian");
*
* __remove__
*
* Remove events are fired after a property is removed.
*
* o.delegate("name","remove", function(ev){
* // called once
* $('#name').text(value)
* })
* o.attr('name',"Justin");
* o.removeAttr('name');
*
* ## Wildcards - matching multiple properties
*
* Sometimes, you want to know when any property within some part
* of an observe has changed. Delegate lets you use wildcards to
* match any property name. The following listens for any change
* on an attribute of the params attribute:
*
* var o = can.Control({
* options : {
* limit : 100,
* offset: 0,
* params : {
* parentId: 5
* }
* }
* })
* o.delegate('options.*','change', function(){
* alert('1');
* })
* o.delegate('options.**','change', function(){
* alert('2');
* })
*
* // alerts 1
* // alerts 2
* o.attr('options.offset',100)
*
* // alerts 2
* o.attr('options.params.parentId',6);
*
* Using a single wildcard (<code>*</code>) matches single level
* properties. Using a double wildcard (<code>**</code>) matches
* any deep property.
*
* ## Listening on multiple properties and values
*
* Delegate lets you listen on multiple values at once. The following listens
* for first and last name changes:
*
* var o = new can.Observe({
* name : {first: "Justin", last: "Meyer"}
* })
*
* o.bind("name.first,name.last",
* "set",
* function(ev,newVal,oldVal,from){
*
* })
*
* ## Listening when properties are a particular value
*
* Delegate lets you listen when a property is __set__ to a specific value:
*
* var o = new can.Observe({
* name : "Justin"
* })
*
* o.bind("name=Brian",
* "set",
* function(ev,newVal,oldVal,from){
*
* })
*
* @param {String} selector The attributes you want to listen for changes in.
*
* Selector should be the property or
* property names of the element you are searching. Examples:
*
* "name" - listens to the "name" property changing
* "name, address" - listens to "name" or "address" changing
* "name address" - listens to "name" or "address" changing
* "address.*" - listens to property directly in address
* "address.**" - listens to any property change in address
* "foo=bar" - listens when foo is "bar"
*
* @param {String} event The event name. One of ("set","add","remove","change")
* @param {Function} handler(ev,newVal,oldVal,prop) The callback handler
* called with:
*
* - newVal - the new value set on the observe
* - oldVal - the old value set on the observe
* - prop - the prop name that was changed
*
* @return {jQuery.Delegate} the delegate for chaining
*/
delegate : function(selector, event, handler){
selector = can.trim(selector);
var delegates = this._observe_delegates || (this._observe_delegates = []),
attrs = [];
// split selector by spaces
selector.replace(/([^\s=]+)=?([^\s]+)?/g, function(whole, attr, value){
attrs.push({
// the attribute name
attr: attr,
// the attribute's pre-split names (for speed)
parts: attr.split('.'),
// the value associated with this prop
value: value
})
});
// delegates has pre-processed info about the event
delegates.push({
// the attrs name for unbinding
selector : selector,
// an object of attribute names and values {type: 'recipe',id: undefined}
// undefined means a value was not defined
attrs : attrs,
callback : handler,
event: event
});
if(delegates.length === 1){
this.bind("change",delegate)
}
return this;
},
/**
* @function can.Observe.prototype.undelegate
* @parent can.Observe.delegate
*
* `undelegate( selector, event, handler )` removes a delegated event handler from an observe.
*
* observe.undelegate("name","set", handler )
*
* @param {String} selector the attribute name of the object you want to undelegate from.
* @param {String} event the event name
* @param {Function} handler the callback handler
* @return {jQuery.Delegate} the delegate for chaining
*/
undelegate : function(selector, event, handler){
selector = can.trim(selector);
var i =0,
delegates = this._observe_delegates || [],
delegateOb;
if(selector){
while(i < delegates.length){
delegateOb = delegates[i];
if( delegateOb.callback === handler ||
(!handler && delegateOb.selector === selector) ){
delegateOb.undelegated = true;
delegates.splice(i,1)
} else {
i++;
}
}
} else {
// remove all delegates
delegates = [];
}
if(!delegates.length){
//can.removeData(this, "_observe_delegates");
this.unbind("change",delegate)
}
return this;
}
});
// add helpers for testing ..
can.Observe.prototype.delegate.matches = matches;
return can.Observe;
})
| SpredfastLegacy/canjs | observe/delegate/delegate.js | JavaScript | mit | 11,161 |
//-----------------------------------------------------------------------
// Copyright © Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.PowerShell.Commands
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.PowerShell.Commands.ShowCommandExtension;
/// <summary>
/// Show-Command displays a GUI for a cmdlet, or for all cmdlets if no specific cmdlet is specified.
/// </summary>
[Cmdlet(VerbsCommon.Show, "Command", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217448")]
public class ShowCommandCommand : PSCmdlet, IDisposable
{
#region Private Fields
/// <summary>
/// Set to true when ProcessRecord is reached, since it will always open a window
/// </summary>
private bool _hasOpenedWindow;
/// <summary>
/// Determines if the command should be sent to the pipeline as a string instead of run.
/// </summary>
private bool _passThrough;
/// <summary>
/// Uses ShowCommandProxy to invoke WPF GUI object.
/// </summary>
private ShowCommandProxy _showCommandProxy;
/// <summary>
/// Data container for all cmdlets. This is populated when show-command is called with no command name.
/// </summary>
private List<ShowCommandCommandInfo> _commands;
/// <summary>
/// List of modules that have been loaded indexed by module name
/// </summary>
private Dictionary<string, ShowCommandModuleInfo> _importedModules;
/// <summary>
/// Record the EndProcessing error.
/// </summary>
private PSDataCollection<ErrorRecord> _errors = new PSDataCollection<ErrorRecord>();
/// <summary>
/// Field used for the NoCommonParameter parameter.
/// </summary>
private SwitchParameter _noCommonParameter;
/// <summary>
/// Object used for ShowCommand with a command name that holds the view model created for the command
/// </summary>
private object _commandViewModelObj;
#endregion
/// <summary>
/// Finalizes an instance of the ShowCommandCommand class
/// </summary>
~ShowCommandCommand()
{
this.Dispose(false);
}
#region Input Cmdlet Parameter
/// <summary>
/// Gets or sets the command name.
/// </summary>
[Parameter(Position = 0)]
[Alias("CommandName")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the Width.
/// </summary>
[Parameter]
[ValidateRange(300, Int32.MaxValue)]
public double Height { get; set; }
/// <summary>
/// Gets or sets the Width.
/// </summary>
[Parameter]
[ValidateRange(300, Int32.MaxValue)]
public double Width { get; set; }
/// <summary>
/// Gets or sets a value indicating Common Parameters should not be displayed
/// </summary>
[Parameter]
public SwitchParameter NoCommonParameter
{
get { return _noCommonParameter; }
set { _noCommonParameter = value; }
}
/// <summary>
/// Gets or sets a value indicating errors should not cause a message window to be displayed
/// </summary>
[Parameter]
public SwitchParameter ErrorPopup { get; set; }
/// <summary>
/// Gets or sets a value indicating the command should be sent to the pipeline as a string instead of run
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get { return _passThrough; }
set { _passThrough = value; }
} // PassThru
#endregion
#region Public and Protected Methods
/// <summary>
/// Executes a PowerShell script, writing the output objects to the pipeline.
/// </summary>
/// <param name="script">Script to execute</param>
public void RunScript(string script)
{
if (_showCommandProxy == null || string.IsNullOrEmpty(script))
{
return;
}
if (_passThrough)
{
this.WriteObject(script);
return;
}
if (ErrorPopup)
{
this.RunScriptSilentlyAndWithErrorHookup(script);
return;
}
if (_showCommandProxy.HasHostWindow)
{
if (!_showCommandProxy.SetPendingISECommand(script))
{
this.RunScriptSilentlyAndWithErrorHookup(script);
}
return;
}
if (!ConsoleInputWithNativeMethods.AddToConsoleInputBuffer(script, true))
{
this.WriteDebug(FormatAndOut_out_gridview.CannotWriteToConsoleInputBuffer);
this.RunScriptSilentlyAndWithErrorHookup(script);
}
}
/// <summary>
/// Dispose method in IDisposable
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Initialize a proxy instance for show-command.
/// </summary>
protected override void BeginProcessing()
{
_showCommandProxy = new ShowCommandProxy(this);
if (_showCommandProxy.ScreenHeight < this.Height)
{
ErrorRecord error = new ErrorRecord(
new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Height", _showCommandProxy.ScreenHeight)),
"PARAMETER_DATA_ERROR",
ErrorCategory.InvalidData,
null);
this.ThrowTerminatingError(error);
}
if (_showCommandProxy.ScreenWidth < this.Width)
{
ErrorRecord error = new ErrorRecord(
new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Width", _showCommandProxy.ScreenWidth)),
"PARAMETER_DATA_ERROR",
ErrorCategory.InvalidData,
null);
this.ThrowTerminatingError(error);
}
}
/// <summary>
/// ProcessRecord with or without CommandName.
/// </summary>
protected override void ProcessRecord()
{
if (Name == null)
{
_hasOpenedWindow = this.CanProcessRecordForAllCommands();
}
else
{
_hasOpenedWindow = this.CanProcessRecordForOneCommand();
}
}
/// <summary>
/// Optionally displays errors in a message
/// </summary>
protected override void EndProcessing()
{
if (!_hasOpenedWindow)
{
return;
}
// We wait untill the window is loaded and then activate it
// to work arround the console window gaining activation somewhere
// in the end of ProcessRecord, which causes the keyboard focus
// (and use oif tab key to focus controls) to go away from the window
_showCommandProxy.WindowLoaded.WaitOne();
_showCommandProxy.ActivateWindow();
this.WaitForWindowClosedOrHelpNeeded();
this.RunScript(_showCommandProxy.GetScript());
if (_errors.Count == 0 || !ErrorPopup)
{
return;
}
StringBuilder errorString = new StringBuilder();
for (int i = 0; i < _errors.Count; i++)
{
if (i != 0)
{
errorString.AppendLine();
}
ErrorRecord error = _errors[i];
errorString.Append(error.Exception.Message);
}
_showCommandProxy.ShowErrorString(errorString.ToString());
}
/// <summary>
/// StopProcessing is called close the window when user press Ctrl+C in the command prompt.
/// </summary>
protected override void StopProcessing()
{
_showCommandProxy.CloseWindow();
}
#endregion
#region Private Methods
/// <summary>
/// Runs the script in a new PowerShell instance and hooks up error stream to potentially display error popup.
/// This method has the inconvenience of not showing to the console user the script being executed.
/// </summary>
/// <param name="script">script to be run</param>
private void RunScriptSilentlyAndWithErrorHookup(string script)
{
// errors are not created here, because there is a field for it used in the final pop up
PSDataCollection<object> output = new PSDataCollection<object>();
output.DataAdded += new EventHandler<DataAddedEventArgs>(this.Output_DataAdded);
_errors.DataAdded += new EventHandler<DataAddedEventArgs>(this.Error_DataAdded);
PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
ps.Streams.Error = _errors;
ps.Commands.AddScript(script);
ps.Invoke(null, output, null);
}
/// <summary>
/// Issues an error when this.commandName was not found
/// </summary>
private void IssueErrorForNoCommand()
{
InvalidOperationException errorException = new InvalidOperationException(
String.Format(
CultureInfo.CurrentUICulture,
FormatAndOut_out_gridview.CommandNotFound,
Name));
this.ThrowTerminatingError(new ErrorRecord(errorException, "NoCommand", ErrorCategory.InvalidOperation, Name));
}
/// <summary>
/// Issues an error when there is more than one command matching this.commandName
/// </summary>
private void IssueErrorForMoreThanOneCommand()
{
InvalidOperationException errorException = new InvalidOperationException(
String.Format(
CultureInfo.CurrentUICulture,
FormatAndOut_out_gridview.MoreThanOneCommand,
Name,
"Show-Command"));
this.ThrowTerminatingError(new ErrorRecord(errorException, "MoreThanOneCommand", ErrorCategory.InvalidOperation, Name));
}
/// <summary>
/// Called from CommandProcessRecord to run the command that will get the CommandInfo and list of modules
/// </summary>
/// <param name="command">command to be retrieved</param>
/// <param name="modules">list of loaded modules</param>
private void GetCommandInfoAndModules(out CommandInfo command, out Dictionary<string, ShowCommandModuleInfo> modules)
{
command = null;
modules = null;
string commandText = _showCommandProxy.GetShowCommandCommand(Name, true);
Collection<PSObject> commandResults = this.InvokeCommand.InvokeScript(commandText);
object[] commandObjects = (object[])commandResults[0].BaseObject;
object[] moduleObjects = (object[])commandResults[1].BaseObject;
if (commandResults == null || moduleObjects == null || commandObjects.Length == 0)
{
this.IssueErrorForNoCommand();
return;
}
if (commandObjects.Length > 1)
{
this.IssueErrorForMoreThanOneCommand();
}
command = ((PSObject)commandObjects[0]).BaseObject as CommandInfo;
if (command == null)
{
this.IssueErrorForNoCommand();
return;
}
if (command.CommandType == CommandTypes.Alias)
{
commandText = _showCommandProxy.GetShowCommandCommand(command.Definition, false);
commandResults = this.InvokeCommand.InvokeScript(commandText);
if (commandResults == null || commandResults.Count != 1)
{
this.IssueErrorForNoCommand();
return;
}
command = (CommandInfo)commandResults[0].BaseObject;
}
modules = _showCommandProxy.GetImportedModulesDictionary(moduleObjects);
}
/// <summary>
/// ProcessRecord when a command name is specified.
/// </summary>
/// <returns>true if there was no exception processing this record</returns>
private bool CanProcessRecordForOneCommand()
{
CommandInfo commandInfo;
this.GetCommandInfoAndModules(out commandInfo, out _importedModules);
Diagnostics.Assert(commandInfo != null, "GetCommandInfoAndModules would throw a terminating error/exception");
try
{
_commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.IndexOf('\\') != -1);
_showCommandProxy.ShowCommandWindow(_commandViewModelObj, _passThrough);
}
catch (TargetInvocationException ti)
{
this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForOneCommand", ErrorCategory.InvalidOperation, Name));
return false;
}
return true;
}
/// <summary>
/// ProcessRecord when a command name is not specified.
/// </summary>
/// <returns>true if there was no exception processing this record</returns>
private bool CanProcessRecordForAllCommands()
{
Collection<PSObject> rawCommands = this.InvokeCommand.InvokeScript(_showCommandProxy.GetShowAllModulesCommand());
_commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject);
_importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject);
try
{
_showCommandProxy.ShowAllModulesWindow(_importedModules, _commands, _noCommonParameter.ToBool(), _passThrough);
}
catch (TargetInvocationException ti)
{
this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForAllCommands", ErrorCategory.InvalidOperation, Name));
return false;
}
return true;
}
/// <summary>
/// Waits untill the window has been closed answering HelpNeeded events
/// </summary>
private void WaitForWindowClosedOrHelpNeeded()
{
do
{
int which = WaitHandle.WaitAny(new WaitHandle[] { _showCommandProxy.WindowClosed, _showCommandProxy.HelpNeeded, _showCommandProxy.ImportModuleNeeded });
if (which == 0)
{
break;
}
if (which == 1)
{
Collection<PSObject> helpResults = this.InvokeCommand.InvokeScript(_showCommandProxy.GetHelpCommand(_showCommandProxy.CommandNeedingHelp));
_showCommandProxy.DisplayHelp(helpResults);
continue;
}
Diagnostics.Assert(which == 2, "which is 0,1 or 2 and 0 and 1 have been eliminated in the ifs above");
string commandToRun = _showCommandProxy.GetImportModuleCommand(_showCommandProxy.ParentModuleNeedingImportModule);
Collection<PSObject> rawCommands;
try
{
rawCommands = this.InvokeCommand.InvokeScript(commandToRun);
}
catch (RuntimeException e)
{
_showCommandProxy.ImportModuleFailed(e);
continue;
}
_commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject);
_importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject);
_showCommandProxy.ImportModuleDone(_importedModules, _commands);
continue;
}
while (true);
}
/// <summary>
/// Writes the output of a script being run into the pipeline
/// </summary>
/// <param name="sender">output collection</param>
/// <param name="e">output event</param>
private void Output_DataAdded(object sender, DataAddedEventArgs e)
{
this.WriteObject(((PSDataCollection<object>)sender)[e.Index]);
}
/// <summary>
/// Writes the errors of a script being run into the pipeline
/// </summary>
/// <param name="sender">error collection</param>
/// <param name="e">error event</param>
private void Error_DataAdded(object sender, DataAddedEventArgs e)
{
this.WriteError(((PSDataCollection<ErrorRecord>)sender)[e.Index]);
}
/// <summary>
/// Implements IDisposable logic
/// </summary>
/// <param name="isDisposing">true if being called from Dispose</param>
private void Dispose(bool isDisposing)
{
if (isDisposing)
{
if (_errors != null)
{
_errors.Dispose();
_errors = null;
}
}
}
#endregion
/// <summary>
/// Wraps interop code for console input buffer
/// </summary>
internal static class ConsoleInputWithNativeMethods
{
/// <summary>
/// Constant used in calls to GetStdHandle
/// </summary>
internal const int STD_INPUT_HANDLE = -10;
/// <summary>
/// Adds a string to the console input buffer
/// </summary>
/// <param name="str">string to add to console input buffer</param>
/// <param name="newLine">true to add Enter after the string</param>
/// <returns>true if it was successful in adding all characters to console input buffer</returns>
internal static bool AddToConsoleInputBuffer(string str, bool newLine)
{
IntPtr handle = ConsoleInputWithNativeMethods.GetStdHandle(ConsoleInputWithNativeMethods.STD_INPUT_HANDLE);
if (handle == IntPtr.Zero)
{
return false;
}
uint strLen = (uint)str.Length;
ConsoleInputWithNativeMethods.INPUT_RECORD[] records = new ConsoleInputWithNativeMethods.INPUT_RECORD[strLen + (newLine ? 1 : 0)];
for (int i = 0; i < strLen; i++)
{
ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref records[i], str[i]);
}
uint written;
if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, records, strLen, out written) || written != strLen)
{
// I do not know of a case where written is not going to be strlen. Maybe for some character that
// is not supported in the console. The API suggests this can happen,
// so we handle it by returning false
return false;
}
// Enter is written separately, because if this is a command, and one of the characters in the command was not written
// (written != strLen) it is desireable to fail (return false) before typing enter and running the command
if (newLine)
{
ConsoleInputWithNativeMethods.INPUT_RECORD[] enterArray = new ConsoleInputWithNativeMethods.INPUT_RECORD[1];
ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref enterArray[0], (char)13);
written = 0;
if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, enterArray, 1, out written))
{
// I don't think this will happen
return false;
}
Diagnostics.Assert(written == 1, "only Enter is being added and it is a supported character");
}
return true;
}
/// <summary>
/// Gets the console handle
/// </summary>
/// <param name="nStdHandle">which console handle to get</param>
/// <returns>the console handle</returns>
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetStdHandle(int nStdHandle);
/// <summary>
/// Writes to the console input buffer
/// </summary>
/// <param name="hConsoleInput">console handle</param>
/// <param name="lpBuffer">inputs to be written</param>
/// <param name="nLength">number of inputs to be written</param>
/// <param name="lpNumberOfEventsWritten">returned number of inputs actually written</param>
/// <returns>0 if the function fails</returns>
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WriteConsoleInput(
IntPtr hConsoleInput,
INPUT_RECORD[] lpBuffer,
uint nLength,
out uint lpNumberOfEventsWritten);
/// <summary>
/// A record to be added to the console buffer
/// </summary>
internal struct INPUT_RECORD
{
/// <summary>
/// The proper event type for a KeyEvent KEY_EVENT_RECORD
/// </summary>
internal const int KEY_EVENT = 0x0001;
/// <summary>
/// input buffer event type
/// </summary>
internal ushort EventType;
/// <summary>
/// The actual event. The original structure is a union of many others, but this is the largest of them
/// And we don't need other kinds of events
/// </summary>
internal KEY_EVENT_RECORD KeyEvent;
/// <summary>
/// Sets the necessary fields of <paramref name="inputRecord"/> for a KeyDown event for the <paramref name="character"/>
/// </summary>
/// <param name="inputRecord">input record to be set</param>
/// <param name="character">character to set the record with</param>
internal static void SetInputRecord(ref INPUT_RECORD inputRecord, char character)
{
inputRecord.EventType = INPUT_RECORD.KEY_EVENT;
inputRecord.KeyEvent.bKeyDown = true;
inputRecord.KeyEvent.UnicodeChar = character;
}
}
/// <summary>
/// Type of INPUT_RECORD which is a key
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct KEY_EVENT_RECORD
{
/// <summary>
/// true for key down and false for key up, but only needed if wVirtualKeyCode is used
/// </summary>
internal bool bKeyDown;
/// <summary>
/// repeat count
/// </summary>
internal ushort wRepeatCount;
/// <summary>
/// virtual key code
/// </summary>
internal ushort wVirtualKeyCode;
/// <summary>
/// virtual key scan code
/// </summary>
internal ushort wVirtualScanCode;
/// <summary>
/// character in input. If this is specified, wVirtualKeyCode, and others don't need to be
/// </summary>
internal char UnicodeChar;
/// <summary>
/// State of keys like Shift and control
/// </summary>
internal uint dwControlKeyState;
}
}
}
}
| KarolKaczmarek/PowerShell | src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs | C# | mit | 25,295 |
var name = "Wanderer";
var collection_type = 0;
var is_secret = 0;
var desc = "Visited 503 new locations.";
var status_text = "Gosh, where HAVEN'T you traveled? Your peregrinations have earned you this footworn-but-carefree Wanderer badge.";
var last_published = 1348803094;
var is_shareworthy = 1;
var url = "wanderer";
var category = "exploring";
var url_swf = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516.swf";
var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_180.png";
var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_60.png";
var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_40.png";
function on_apply(pc){
}
var conditions = {
8 : {
type : "group_count",
group : "locations_visited",
value : "503"
},
};
function onComplete(pc){ // generated from rewards
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_achievement_modifier();
if (/completist/i.exec(this.name)) {
var level = pc.stats_get_level();
if (level > 4) {
multiplier *= (pc.stats_get_level()/4);
}
}
pc.stats_add_xp(round_to_5(1000 * multiplier), true);
pc.stats_add_favor_points("lem", round_to_5(200 * multiplier));
if(pc.buffs_has('gift_of_gab')) {
pc.buffs_remove('gift_of_gab');
}
else if(pc.buffs_has('silvertongue')) {
pc.buffs_remove('silvertongue');
}
}
var rewards = {
"xp" : 1000,
"favor" : {
"giant" : "lem",
"points" : 200
}
};
// generated ok (NO DATE)
| yelworc/eleven-gsjs | achievements/wanderer.js | JavaScript | mit | 1,587 |
@charset "utf-8";
/* CSS Document */
#board_container{padding:20px 20px 0 ;
margin: 0 1%;
position:relative; background:#FFF;
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.15) inset, 0 1px 5px rgba(0, 0, 0, 0.075);
}
.board h2{color:#333; font-size:30px; padding:5px 0; margin:0; font-family:'Varela Round', sans-serif;}
.board h3{color:#666; font-size:24px; padding:0;}
.board p{color:#444; font-size:14px; line-height:24px;}
.board_right h2{color:#333; font-size:24px; margin:10px 0; padding:0;}
.board_right .follower{clear:both; font-size:14px; color:#333; padding:5px 0; margin:5px; font-weight:bold;}
.icon_board{margin:0 8px; font-size:13px !important;color:#FC6;}
.icon_board_text{font-size:13px; color:#333 !important;}
.board_small{font-size:20px; color:#333;}
.board_small_m{margin:0 10px;}
.row_min{position:fixed; z-index:100 !important; top:50px; left:0; background:linear-gradient(to bottom, rgb(255, 255, 255) 0%, rgb(248, 248, 248) 100%); width:120%; padding:10px 0;}
.row_lrg{z-index:1001;}
@media only screen and (min-width : 1200px) {
.board img{ height:auto; width:90%; margin:auto; }
.board_right img{width:72%; height:auto;}
.board_right h2{color:#333; font-size:24px; margin:10px 0; padding:0;}
}
@media only screen and (min-width : 768px) and (max-width : 1199px) {
.board img{ height:auto; width:100%;}
.board_right{width:25%; margin:0 auto; float:right;}
.board_right img{width:45%; height:auto; border:5px solid #333;}
}
@media only screen and (min-width : 481px) and (max-width : 767px) {
.board {width:80%; margin:50px auto;}
.board img{ height:auto; width:100%;}
.board_right{width:80%; margin:20px auto;}
.board_right img{width:30%; height:auto; border:5px solid #333;}
.row_min{top:100px !important;}
}
@media only screen and (max-width : 480px) {
.board img{ height:auto; width:100%;}
.board_right img{width:45%; height:auto; border:5px solid #333;}
.row_min{top:150px !important;}
#board_container{margin-top: 60px !important;}
}
/**********************************************/
/******* *******/
/******* User *******/
/******* *******/
/**********************************************/
.user_dis{display:none;}
.user_bg{background:#FFF; padding:0; box-shadow:0 1px 0 rgba(255, 255, 255, 0.15) inset, 0 1px 5px rgba(0, 0, 0, 0.075);}
.user_margin{margin-top:15px;}
.user_bg .img{float:left; height:140px; height:140px;}
.user_bg h2{float:left; width:60%; color:#666; font-size:28px;}
.user_pro_bg{background:#FFF; margin:0 20px;box-shadow:0 1px 0 rgba(255, 255, 255, 0.15) inset, 0 1px 5px rgba(0, 0, 0, 0.075);}
.user_pro_bg h2{color:#666; font-size:14px; font-weight:600; padding:0;}
.user_pro{list-style:none; margin:0; padding:0 0 10px; }
.user_pro li{padding-bottom:12px; color:#888; font-weight:600}
.user_pro li img{padding-right:5px; }
| peishenwu/pcboy_myyna | public/default/css/boaard.css | CSS | mit | 3,009 |
using System;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ContextMenuTests
{
private Mock<IPopupImpl> popupImpl;
private MouseTestHelper _mouse = new MouseTestHelper();
[Fact]
public void ContextRequested_Opens_ContextMenu()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
int openedCount = 0;
sut.MenuOpened += (sender, args) =>
{
openedCount++;
};
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
Assert.Equal(1, openedCount);
}
}
[Fact]
public void ContextMenu_Is_Opened_When_ContextFlyout_Is_Also_Set()
{
// We have this test for backwards compatability with the code that already sets custom ContextMenu.
using (Application())
{
var sut = new ContextMenu();
var flyout = new Flyout();
var target = new Panel
{
ContextMenu = sut,
ContextFlyout = flyout
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
Assert.False(flyout.IsOpen);
}
}
[Fact]
public void KeyUp_Raised_On_Target_Opens_ContextFlyout()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var contextRequestedCount = 0;
target.AddHandler(Control.ContextRequestedEvent, (s, a) => contextRequestedCount++, Interactivity.RoutingStrategies.Tunnel);
var window = PreparedWindow(target);
window.Show();
target.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = Key.Apps, Source = window });
Assert.True(sut.IsOpen);
Assert.Equal(1, contextRequestedCount);
}
}
[Fact]
public void KeyUp_Raised_On_Flyout_Closes_Opened_ContextMenu()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
target.RaiseEvent(new ContextRequestedEventArgs());
Assert.True(sut.IsOpen);
sut.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = Key.Apps, Source = window });
Assert.False(sut.IsOpen);
}
}
[Fact]
public void Opening_Raises_Single_Opened_Event()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
int openedCount = 0;
sut.MenuOpened += (sender, args) =>
{
openedCount++;
};
sut.Open(target);
Assert.Equal(1, openedCount);
}
}
[Fact]
public void Open_Should_Use_Default_Control()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
bool opened = false;
sut.MenuOpened += (sender, args) =>
{
opened = true;
};
sut.Open();
Assert.True(opened);
}
}
[Fact]
public void Open_Should_Raise_Exception_If_AlreadyDetached()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
target.ContextMenu = null;
Assert.ThrowsAny<Exception>(()=> sut.Open());
}
}
[Fact]
public void Closing_Raises_Single_Closed_Event()
{
using (Application())
{
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = new Window { Content = target };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
sut.Open(target);
int closedCount = 0;
sut.MenuClosed += (sender, args) =>
{
closedCount++;
};
sut.Close();
Assert.Equal(1, closedCount);
}
}
[Fact]
public void Cancel_Light_Dismiss_Closing_Keeps_Flyout_Open()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var window = PreparedWindow();
window.Width = 100;
window.Height = 100;
var button = new Button
{
Height = 10,
Width = 10,
HorizontalAlignment = Layout.HorizontalAlignment.Left,
VerticalAlignment = Layout.VerticalAlignment.Top
};
window.Content = button;
window.ApplyTemplate();
window.Show();
var tracker = 0;
var c = new ContextMenu();
c.ContextMenuClosing += (s, e) =>
{
tracker++;
e.Cancel = true;
};
button.ContextMenu = c;
c.Open(button);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Down(overlay, MouseButton.Left, new Point(90, 90));
_mouse.Up(button, MouseButton.Left, new Point(90, 90));
Assert.Equal(1, tracker);
Assert.True(c.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Never);
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(1));
}
}
[Fact]
public void Light_Dismiss_Closes_Flyout()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var window = PreparedWindow();
window.Width = 100;
window.Height = 100;
var button = new Button
{
Height = 10,
Width = 10,
HorizontalAlignment = Layout.HorizontalAlignment.Left,
VerticalAlignment = Layout.VerticalAlignment.Top
};
window.Content = button;
window.ApplyTemplate();
window.Show();
var c = new ContextMenu();
c.PlacementMode = PlacementMode.Bottom;
c.Open(button);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Down(overlay, MouseButton.Left, new Point(90, 90));
_mouse.Up(button, MouseButton.Left, new Point(90, 90));
Assert.False(c.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Exactly(1));
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(1));
}
}
[Fact]
public void Clicking_On_Control_Toggles_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay);
_mouse.Up(target);
Assert.False(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Once);
popupImpl.Verify(x => x.Hide(), Times.Once);
}
}
[Fact]
public void Right_Clicking_On_Control_Twice_Re_Opens_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
window.Show();
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay, MouseButton.Right);
_mouse.Up(target, MouseButton.Right);
Assert.True(sut.IsOpen);
popupImpl.Verify(x => x.Hide(), Times.Once);
popupImpl.Verify(x => x.Show(true, false), Times.Exactly(2));
}
}
[Fact]
public void Context_Menu_Can_Be_Shared_Between_Controls_Even_After_A_Control_Is_Removed_From_Visual_Tree()
{
using (Application())
{
var sut = new ContextMenu();
var target1 = new Panel
{
ContextMenu = sut
};
var target2 = new Panel
{
ContextMenu = sut
};
var sp = new StackPanel { Children = { target1, target2 } };
var window = new Window { Content = sp };
window.ApplyTemplate();
window.Presenter.ApplyTemplate();
_mouse.Click(target1, MouseButton.Right);
Assert.True(sut.IsOpen);
sp.Children.Remove(target1);
Assert.False(sut.IsOpen);
_mouse.Click(target2, MouseButton.Right);
Assert.True(sut.IsOpen);
}
}
[Fact]
public void Cancelling_Opening_Does_Not_Show_ContextMenu()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
bool eventCalled = false;
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
new Window { Content = target };
sut.ContextMenuOpening += (c, e) => { eventCalled = true; e.Cancel = true; };
_mouse.Click(target, MouseButton.Right);
Assert.True(eventCalled);
Assert.False(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Never);
}
}
[Fact]
public void Can_Set_Clear_ContextMenu_Property()
{
using (Application())
{
var target = new ContextMenu();
var control = new Panel();
control.ContextMenu = target;
control.ContextMenu = null;
}
}
[Fact]
public void Context_Menu_In_Resources_Can_Be_Shared()
{
using (Application())
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Resources>
<ContextMenu x:Key='contextMenu'>
<MenuItem>Foo</MenuItem>
</ContextMenu>
</Window.Resources>
<StackPanel>
<TextBlock Name='target1' ContextMenu='{StaticResource contextMenu}'/>
<TextBlock Name='target2' ContextMenu='{StaticResource contextMenu}'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var target1 = window.Find<TextBlock>("target1");
var target2 = window.Find<TextBlock>("target2");
var mouse = new MouseTestHelper();
Assert.NotNull(target1.ContextMenu);
Assert.NotNull(target2.ContextMenu);
Assert.Same(target1.ContextMenu, target2.ContextMenu);
window.Show();
var menu = target1.ContextMenu;
mouse.Click(target1, MouseButton.Right);
Assert.True(menu.IsOpen);
mouse.Click(target2, MouseButton.Right);
Assert.True(menu.IsOpen);
}
}
[Fact]
public void Context_Menu_Can_Be_Set_In_Style()
{
using (Application())
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='TextBlock'>
<Setter Property='ContextMenu'>
<ContextMenu>
<MenuItem>Foo</MenuItem>
</ContextMenu>
</Setter>
</Style>
</Window.Styles>
<StackPanel>
<TextBlock Name='target1'/>
<TextBlock Name='target2'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var target1 = window.Find<TextBlock>("target1");
var target2 = window.Find<TextBlock>("target2");
var mouse = new MouseTestHelper();
Assert.NotNull(target1.ContextMenu);
Assert.NotNull(target2.ContextMenu);
Assert.Same(target1.ContextMenu, target2.ContextMenu);
window.Show();
var menu = target1.ContextMenu;
mouse.Click(target1, MouseButton.Right);
Assert.True(menu.IsOpen);
mouse.Click(target2, MouseButton.Right);
Assert.True(menu.IsOpen);
}
}
[Fact]
public void Cancelling_Closing_Leaves_ContextMenuOpen()
{
using (Application())
{
popupImpl.Setup(x => x.Show(true, false)).Verifiable();
popupImpl.Setup(x => x.Hide()).Verifiable();
bool eventCalled = false;
var sut = new ContextMenu();
var target = new Panel
{
ContextMenu = sut
};
var window = PreparedWindow(target);
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
sut.ContextMenuClosing += (c, e) => { eventCalled = true; e.Cancel = true; };
window.Show();
_mouse.Click(target, MouseButton.Right);
Assert.True(sut.IsOpen);
_mouse.Down(overlay, MouseButton.Right);
_mouse.Up(target, MouseButton.Right);
Assert.True(eventCalled);
Assert.True(sut.IsOpen);
popupImpl.Verify(x => x.Show(true, false), Times.Once());
popupImpl.Verify(x => x.Hide(), Times.Never);
}
}
private Window PreparedWindow(object content = null)
{
var renderer = new Mock<IRenderer>();
var platform = AvaloniaLocator.Current.GetService<IWindowingPlatform>();
var windowImpl = Mock.Get(platform.CreateWindow());
windowImpl.Setup(x => x.CreateRenderer(It.IsAny<IRenderRoot>())).Returns(renderer.Object);
var w = new Window(windowImpl.Object) { Content = content };
w.ApplyTemplate();
w.Presenter.ApplyTemplate();
return w;
}
private IDisposable Application()
{
var screen = new PixelRect(new PixelPoint(), new PixelSize(100, 100));
var screenImpl = new Mock<IScreenImpl>();
screenImpl.Setup(x => x.ScreenCount).Returns(1);
screenImpl.Setup(X => X.AllScreens).Returns( new[] { new Screen(1, screen, screen, true) });
var windowImpl = MockWindowingPlatform.CreateWindowMock();
popupImpl = MockWindowingPlatform.CreatePopupMock(windowImpl.Object);
popupImpl.SetupGet(x => x.RenderScaling).Returns(1);
windowImpl.Setup(x => x.CreatePopup()).Returns(popupImpl.Object);
windowImpl.Setup(x => x.Screen).Returns(screenImpl.Object);
var services = TestServices.StyledWindow.With(
inputManager: new InputManager(),
windowImpl: windowImpl.Object,
windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object, x => popupImpl.Object));
return UnitTestApplication.Start(services);
}
}
}
| AvaloniaUI/Avalonia | tests/Avalonia.Controls.UnitTests/ContextMenuTests.cs | C# | mit | 19,072 |
// -*- C++ -*-
// Copyright (C) 2010-2017, Vaclav Haisman. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modifica-
// tion, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
// DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** @file */
#ifndef LOG4CPLUS_TCHAR_HEADER_
#define LOG4CPLUS_TCHAR_HEADER_
#include <log4cplus/config.hxx>
#if defined (LOG4CPLUS_HAVE_PRAGMA_ONCE)
#pragma once
#endif
#if defined (_WIN32)
#include <cstddef>
#endif
#ifdef UNICODE
# define LOG4CPLUS_TEXT2(STRING) L##STRING
#else
# define LOG4CPLUS_TEXT2(STRING) STRING
#endif // UNICODE
#define LOG4CPLUS_TEXT(STRING) LOG4CPLUS_TEXT2(STRING)
namespace log4cplus
{
#if defined (UNICODE)
typedef wchar_t tchar;
#else
typedef char tchar;
#endif
} // namespace log4cplus
#endif // LOG4CPLUS_TCHAR_HEADER_
| sunzhuoshi/VRDemoHelper | Common/log4cplus/include/log4cplus/tchar.h | C | mit | 1,989 |
#!/bin/bash -e
echo "================= Installing JRuby 1.7.19 ==================="
rvm requirements
rvm install jruby-1.7.19
rvm use jruby-1.7.19
# Install ruby gems
gem install bundler
| dry-dock/u12rubpls | version/jruby_1_7_19.sh | Shell | mit | 189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.