repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
landolsi1/tunisiehologram | vendor/composer/autoload_psr4.php | 1473 | <?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Zend\\Json\\' => array($vendorDir . '/zendframework/zend-json/src'),
'Symfony\\Bundle\\SwiftmailerBundle\\' => array($vendorDir . '/symfony/swiftmailer-bundle'),
'Symfony\\Bundle\\MonologBundle\\' => array($vendorDir . '/symfony/monolog-bundle'),
'Symfony\\Bundle\\AsseticBundle\\' => array($vendorDir . '/symfony/assetic-bundle'),
'Sensio\\Bundle\\FrameworkExtraBundle\\' => array($vendorDir . '/sensio/framework-extra-bundle'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Ob\\HighchartsBundle\\' => array($vendorDir . '/ob/highcharts-bundle'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'Incenteev\\ParameterHandler\\' => array($vendorDir . '/incenteev/composer-parameter-handler'),
'FOS\\UserBundle\\' => array($vendorDir . '/friendsofsymfony/user-bundle'),
'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
'Doctrine\\Common\\Cache\\' => array($vendorDir . '/doctrine/cache/lib/Doctrine/Common/Cache'),
'Doctrine\\Common\\' => array($vendorDir . '/doctrine/common/lib/Doctrine/Common'),
'Doctrine\\Bundle\\DoctrineCacheBundle\\' => array($vendorDir . '/doctrine/doctrine-cache-bundle'),
'Doctrine\\Bundle\\DoctrineBundle\\' => array($vendorDir . '/doctrine/doctrine-bundle'),
);
| mit |
sodash/open-code | winterwell.nlp/src/com/winterwell/nlp/io/ListTokenStream.java | 3946 | package com.winterwell.nlp.io;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.winterwell.utils.Printer;
import com.winterwell.utils.TodoException;
import com.winterwell.utils.containers.AbstractIterator;
import com.winterwell.utils.containers.Containers;
import com.winterwell.utils.log.Log;
/**
* A Token stream backed by a list.
*
* This class does allow you to add more Token, but this is not threadsafe. To
* iterate through again, use {@link #copyWithReset()}.
*
* @author Daniel
*/
public final class ListTokenStream extends ATokenStream implements
Collection<Tkn> {
private final List<Tkn> data;
public ListTokenStream(int capacity) {
data = new ArrayList<Tkn>(capacity);
}
/**
* Read from the input stream into this one.
*/
public ListTokenStream(ITokenStream stream) {
this(Containers.getList(stream));
}
/**
*
* @param Token
* This will be copied. If it empty, the stream will have zero
* dimensions and be pretty much unusable.
*/
public ListTokenStream(List<Tkn> Token) {
// copy the list to our backing store
Token = new ArrayList<Tkn>(Token);
if (Token.isEmpty()) {
Log.report("Empty Token-list: created 0D Tokenstream");
}
this.data = Token;
}
/**
* Create a ListTokenStream which directly reuses the backing list, but
* maintains its own position. This is a faster alternative to
* {@link #copyWithReset()}: you get the rewind but not the copy.
*
* @param data
* This will NOT be copied
* @param share
* must be true. Used to separate from the other constructor.
*/
public ListTokenStream(ListTokenStream data, boolean share) {
assert share == true;
this.data = data.data;
}
/**
* Convenience constructor
*
* @param splitByWhitespace
*/
public ListTokenStream(String splitByWhitespace) {
this(12);
String[] words = splitByWhitespace.split("\\s+");
for (String word : words) {
add(new Tkn(word));
}
}
/**
* Add a new piece of Token to the end of the stream. This method is not
* threadsafe.
*
* @param d
*/
@Override
public boolean add(Tkn d) {
return data.add(d);
}
@Override
public boolean addAll(Collection<? extends Tkn> c) {
return data.addAll(c);
}
@Override
public void clear() {
data.clear();
}
@Override
public boolean contains(Object o) {
if (o instanceof Tkn)
return data.contains(o);
throw new IllegalArgumentException("Not a Token: " + o.getClass());
}
@Override
public boolean containsAll(Collection<?> c) {
return data.containsAll(c);
}
@Override
public ITokenStream factory(String input) {
throw new TodoException();
}
public List<Tkn> getList() {
return data;
}
@Override
public boolean isEmpty() {
return data.isEmpty();
}
@Override
public boolean isFactory() {
throw new TodoException();
}
@Override
public AbstractIterator<Tkn> iterator() {
final Iterator<Tkn> bit = data.iterator();
return new AbstractIterator<Tkn>() {
@Override
protected Tkn next2() throws Exception {
if ( ! bit.hasNext()) return null;
return bit.next();
}
};
}
@Override
public boolean remove(Object o) {
if (o instanceof Tkn)
return data.remove(o);
throw new IllegalArgumentException("Not a Token: " + o.getClass());
}
@Override
public boolean removeAll(Collection<?> c) {
return data.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return data.retainAll(c);
}
@Override
public int size() {
return data.size();
}
@Override
public Object[] toArray() {
return data.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return data.toArray(a);
}
@Override
public String toString() {
return ListTokenStream.class.getSimpleName()
+ ": "
+ Printer.toString(Containers.subList(data, 0,
Math.min(4, size()))) + " (first 4 items)";
}
}
| mit |
binghuo365/BaseLab | 3rd/ACE-5.7.0/ACE_wrappers/examples/Reactor/Proactor/test_aiosig.cpp | 7858 | // $Id: test_aiosig.cpp 84565 2009-02-23 08:20:39Z johnnyw $
// ============================================================================
//
// = FILENAME
// test_aiosig.cpp
//
// = DESCRITPTION
// Check out test_aiosig_ace.cpp, the ACE'ified version of this
// program. This program may not be uptodate.
//
// = COMPILATION
// CC -g -o test_aiosig -lrt test_aiosig.cpp
//
// = RUN
// ./test_aiosig
//
// = AUTHOR
// Programming for the Real World. Bill O. GallMeister.
// Modified by Alexander Babu Arulanthu <[email protected]>
//
// =====================================================================
//FUZZ: disable check_for_lack_ACE_OS
//FUZZ: disable check_for_improper_main_declaration
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <limits.h>
#include <pthread.h>
#include <aio.h>
int file_handle = -1;
char mb1 [BUFSIZ + 1];
char mb2 [BUFSIZ + 1];
aiocb aiocb1, aiocb2;
sigset_t completion_signal;
// Function prototypes.
int setup_signal_delivery (void);
int issue_aio_calls (void);
int query_aio_completions (void);
int test_aio_calls (void);
int setup_signal_handler (void);
int setup_signal_handler (int signal_number);
int
setup_signal_delivery (void)
{
// Make the sigset_t consisting of the completion signal.
if (sigemptyset (&completion_signal) == -1)
{
perror ("Error:Couldnt init the RT completion signal set\n");
return -1;
}
if (sigaddset (&completion_signal, SIGRTMIN) == -1)
{
perror ("Error:Couldnt init the RT completion signal set\n");
return -1;
}
// Mask them.
if (pthread_sigmask (SIG_BLOCK, &completion_signal, 0) == -1)
{
perror ("Error:Couldnt maks the RT completion signals\n");
return -1;
}
return setup_signal_handler (SIGRTMIN);
}
int
issue_aio_calls (void)
{
// Setup AIOCB.
aiocb1.aio_fildes = file_handle;
aiocb1.aio_offset = 0;
aiocb1.aio_buf = mb1;
aiocb1.aio_nbytes = BUFSIZ;
aiocb1.aio_reqprio = 0;
aiocb1.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
aiocb1.aio_sigevent.sigev_signo = SIGRTMIN;
aiocb1.aio_sigevent.sigev_value.sival_ptr = (void *) &aiocb1;
// Fire off the aio write.
if (aio_read (&aiocb1) == -1)
{
// Queueing failed.
perror ("Error:Asynch_Read_Stream: aio_read queueing failed\n");
return -1;
}
// Setup AIOCB.
aiocb2.aio_fildes = file_handle;
aiocb2.aio_offset = BUFSIZ + 1;
aiocb2.aio_buf = mb2;
aiocb2.aio_nbytes = BUFSIZ;
aiocb2.aio_reqprio = 0;
aiocb2.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
aiocb2.aio_sigevent.sigev_signo = SIGRTMIN;
aiocb2.aio_sigevent.sigev_value.sival_ptr = (void *) &aiocb2;
// Fire off the aio write.
if (aio_read (&aiocb2) == -1)
{
// Queueing failed.
perror ("Error:Asynch_Read_Stream: aio_read queueing failed\n");
return -1;
}
return 0;
}
int
query_aio_completions (void)
{
size_t number_of_compleions = 0;
for (number_of_compleions = 0;
number_of_compleions < 2;
number_of_compleions ++)
{
// Wait for <milli_seconds> amount of time.
// @@ Assigning <milli_seconds> to tv_sec.
timespec timeout;
timeout.tv_sec = INT_MAX;
timeout.tv_nsec = 0;
// To get back the signal info.
siginfo_t sig_info;
// Await the RT completion signal.
int sig_return = sigtimedwait (&completion_signal,
&sig_info,
&timeout);
// Error case.
// If failure is coz of timeout, then return *0* but set
// errno appropriately. This is what the WinNT proactor
// does.
if (sig_return == -1)
{
perror ("Error:Error waiting for RT completion signals\n");
return -1;
}
// RT completion signals returned.
if (sig_return != SIGRTMIN)
{
printf ("Unexpected signal (%d) has been received while waiting for RT Completion Signals\n",
sig_return);
return -1;
}
// @@ Debugging.
printf ("Sig number found in the sig_info block : %d\n",
sig_info.si_signo);
// Is the signo returned consistent?
if (sig_info.si_signo != sig_return)
{
printf ("Inconsistent signal number (%d) in the signal info block\n",
sig_info.si_signo);
return -1;
}
// @@ Debugging.
printf ("Signal code for this signal delivery : %d\n",
sig_info.si_code);
// Is the signal code an aio completion one?
if ((sig_info.si_code != SI_ASYNCIO) &&
(sig_info.si_code != SI_QUEUE))
{
printf ("Unexpected signal code (%d) returned on completion querying\n",
sig_info.si_code);
return -1;
}
// Retrive the aiocb.
aiocb* aiocb_ptr = (aiocb *) sig_info.si_value.sival_ptr;
// Analyze error and return values. Return values are
// actually <errno>'s associated with the <aio_> call
// corresponding to aiocb_ptr.
int error_code = aio_error (aiocb_ptr);
if (error_code == -1)
{
perror ("Error:Invalid control block was sent to <aio_error> for compleion querying\n");
return -1;
}
if (error_code != 0)
{
// Error occurred in the <aio_>call. Return the errno
// corresponding to that <aio_> call.
printf ("Error:An AIO call has failed:Error code = %d\n",
error_code);
return -1;
}
// No error occured in the AIO operation.
int nbytes = aio_return (aiocb_ptr);
if (nbytes == -1)
{
perror ("Error:Invalid control block was send to <aio_return>\n");
return -1;
}
if (number_of_compleions == 0)
// Print the buffer.
printf ("Number of bytes transferred : %d\n The buffer : %s\n",
nbytes,
mb1);
else
// Print the buffer.
printf ("Number of bytes transferred : %d\n The buffer : %s\n",
nbytes,
mb2);
}
return 0;
}
int
test_aio_calls (void)
{
// Set up the input file.
// Open file (in SEQUENTIAL_SCAN mode)
file_handle = open ("test_aiosig.cpp", O_RDONLY);
if (file_handle == -1)
{
perror ("Error:Opening the inputfile");
return -1;
}
if (setup_signal_delivery () < 0)
return -1;
if (issue_aio_calls () < 0)
return -1;
if (query_aio_completions () < 0)
return -1;
return 0;
}
void
null_handler (int /* signal_number */,
siginfo_t * /* info */,
void * /* context */)
{
}
int
setup_signal_handler (int signal_number)
{
// Setting up the handler(!) for these signals.
struct sigaction reaction;
sigemptyset (&reaction.sa_mask); // Nothing else to mask.
reaction.sa_flags = SA_SIGINFO; // Realtime flag.
#if defined (SA_SIGACTION)
// Lynx says, it is better to set this bit to be portable.
reaction.sa_flags &= SA_SIGACTION;
#endif /* SA_SIGACTION */
reaction.sa_sigaction = null_handler; // Null handler.
int sigaction_return = sigaction (SIGRTMIN,
&reaction,
0);
if (sigaction_return == -1)
{
perror ("Error:Proactor couldnt do sigaction for the RT SIGNAL");
return -1;
}
return 0;
}
int
main (int, char *[])
{
if (test_aio_calls () == 0)
printf ("RT SIG test successful:\n"
"ACE_POSIX_SIG_PROACTOR should work in this platform\n");
else
printf ("RT SIG test failed:\n"
"ACE_POSIX_SIG_PROACTOR may not work in this platform\n");
return 0;
}
| mit |
yinjimmy/cocos2d-x-mini | platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp | 10591 | #include <stdlib.h>
#include <jni.h>
#include <android/log.h>
#include <string>
#include "JniHelper.h"
#include "Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#define LOG_TAG "Java_org_cocos2dx_lib_Cocos2dxHelper.cpp"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
static EditTextCallback s_pfEditTextCallback = NULL;
static void* s_ctx = NULL;
using namespace cocos2d;
using namespace std;
string g_apkPath;
extern "C" {
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetApkPath(JNIEnv* env, jobject thiz, jstring apkPath) {
g_apkPath = JniHelper::jstring2string(apkPath);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) {
jsize size = env->GetArrayLength(text);
if (size > 0) {
jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0);
char* pBuf = (char*)malloc(size+1);
if (pBuf != NULL) {
memcpy(pBuf, data, size);
pBuf[size] = '\0';
// pass data to edittext's delegate
if (s_pfEditTextCallback) s_pfEditTextCallback(pBuf, s_ctx);
free(pBuf);
}
env->ReleaseByteArrayElements(text, data, 0);
} else {
if (s_pfEditTextCallback) s_pfEditTextCallback("", s_ctx);
}
}
}
const char * getApkPath() {
return g_apkPath.c_str();
}
void showDialogJNI(const char * pszMsg, const char * pszTitle) {
if (!pszMsg) {
return;
}
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "showDialog", "(Ljava/lang/String;Ljava/lang/String;)V")) {
jstring stringArg1;
if (!pszTitle) {
stringArg1 = t.env->NewStringUTF("");
} else {
stringArg1 = t.env->NewStringUTF(pszTitle);
}
jstring stringArg2 = t.env->NewStringUTF(pszMsg);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
t.env->DeleteLocalRef(t.classID);
}
}
void showEditTextDialogJNI(const char* pszTitle, const char* pszMessage, int nInputMode, int nInputFlag, int nReturnType, int nMaxLength, EditTextCallback pfEditTextCallback, void* ctx) {
if (pszMessage == NULL) {
return;
}
s_pfEditTextCallback = pfEditTextCallback;
s_ctx = ctx;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "showEditTextDialog", "(Ljava/lang/String;Ljava/lang/String;IIII)V")) {
jstring stringArg1;
if (!pszTitle) {
stringArg1 = t.env->NewStringUTF("");
} else {
stringArg1 = t.env->NewStringUTF(pszTitle);
}
jstring stringArg2 = t.env->NewStringUTF(pszMessage);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2, nInputMode, nInputFlag, nReturnType, nMaxLength);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
t.env->DeleteLocalRef(t.classID);
}
}
void terminateProcessJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "terminateProcess", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
std::string getPackageNameJNI() {
JniMethodInfo t;
std::string ret("");
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getCocos2dxPackageName", "()Ljava/lang/String;")) {
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
ret = JniHelper::jstring2string(str);
t.env->DeleteLocalRef(str);
}
return ret;
}
std::string getFileDirectoryJNI() {
JniMethodInfo t;
std::string ret("");
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getCocos2dxWritablePath", "()Ljava/lang/String;")) {
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
ret = JniHelper::jstring2string(str);
t.env->DeleteLocalRef(str);
}
return ret;
}
std::string getCurrentLanguageJNI() {
JniMethodInfo t;
std::string ret("");
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getCurrentLanguage", "()Ljava/lang/String;")) {
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
ret = JniHelper::jstring2string(str);
t.env->DeleteLocalRef(str);
}
return ret;
}
void enableAccelerometerJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "enableAccelerometer", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
void setAccelerometerIntervalJNI(float interval) {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setAccelerometerInterval", "(F)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, interval);
t.env->DeleteLocalRef(t.classID);
}
}
void disableAccelerometerJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "disableAccelerometer", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
// functions for CCUserDefault
bool getBoolForKeyJNI(const char* pKey, bool defaultValue)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getBoolForKey", "(Ljava/lang/String;Z)Z")) {
jstring stringArg = t.env->NewStringUTF(pKey);
jboolean ret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, stringArg, defaultValue);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
return ret;
}
return defaultValue;
}
int getIntegerForKeyJNI(const char* pKey, int defaultValue)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getIntegerForKey", "(Ljava/lang/String;I)I")) {
jstring stringArg = t.env->NewStringUTF(pKey);
jint ret = t.env->CallStaticIntMethod(t.classID, t.methodID, stringArg, defaultValue);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
return ret;
}
return defaultValue;
}
float getFloatForKeyJNI(const char* pKey, float defaultValue)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getFloatForKey", "(Ljava/lang/String;F)F")) {
jstring stringArg = t.env->NewStringUTF(pKey);
jfloat ret = t.env->CallStaticFloatMethod(t.classID, t.methodID, stringArg, defaultValue);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
return ret;
}
return defaultValue;
}
double getDoubleForKeyJNI(const char* pKey, double defaultValue)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getDoubleForKey", "(Ljava/lang/String;D)D")) {
jstring stringArg = t.env->NewStringUTF(pKey);
jdouble ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, stringArg);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
return ret;
}
return defaultValue;
}
std::string getStringForKeyJNI(const char* pKey, const char* defaultValue)
{
JniMethodInfo t;
std::string ret("");
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getStringForKey", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;")) {
jstring stringArg1 = t.env->NewStringUTF(pKey);
jstring stringArg2 = t.env->NewStringUTF(defaultValue);
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, stringArg1, stringArg2);
ret = JniHelper::jstring2string(str);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
t.env->DeleteLocalRef(str);
return ret;
}
return defaultValue;
}
void setBoolForKeyJNI(const char* pKey, bool value)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setBoolForKey", "(Ljava/lang/String;Z)V")) {
jstring stringArg = t.env->NewStringUTF(pKey);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg, value);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
}
}
void setIntegerForKeyJNI(const char* pKey, int value)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setIntegerForKey", "(Ljava/lang/String;I)V")) {
jstring stringArg = t.env->NewStringUTF(pKey);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg, value);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
}
}
void setFloatForKeyJNI(const char* pKey, float value)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setFloatForKey", "(Ljava/lang/String;F)V")) {
jstring stringArg = t.env->NewStringUTF(pKey);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg, value);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
}
}
void setDoubleForKeyJNI(const char* pKey, double value)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setDoubleForKey", "(Ljava/lang/String;D)V")) {
jstring stringArg = t.env->NewStringUTF(pKey);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg, value);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
}
}
void setStringForKeyJNI(const char* pKey, const char* value)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setStringForKey", "(Ljava/lang/String;Ljava/lang/String;)V")) {
jstring stringArg1 = t.env->NewStringUTF(pKey);
jstring stringArg2 = t.env->NewStringUTF(value);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
}
}
| mit |
Jason3S/cspell-trie | src/lib/suggest.test.ts | 9363 | import {expect} from 'chai';
import * as Sug from './suggest';
import {Trie} from './trie';
describe('Validate Suggest', () => {
it('Tests suggestions', () => {
const trie = Trie.create(sampleWords);
const results = Sug.suggest(trie.root, 'talks');
// console.log(JSON.stringify(results));
const suggestions = results.map(s => s.word);
expect(suggestions).to.contain('talks');
expect(suggestions).to.contain('talk');
expect(suggestions[0]).to.be.equal('talks');
expect(suggestions[1]).to.be.equal('talk');
expect(suggestions).to.deep.equal(['talks', 'talk', 'walks', 'talked', 'talker', 'walk']);
});
it('Tests suggestions', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore tallk
const results = Sug.suggest(trie.root, 'tallk');
// console.log(JSON.stringify(results));
const suggestions = results.map(s => s.word);
expect(suggestions).to.contain('talks');
expect(suggestions).to.contain('talk');
expect(suggestions[1]).to.be.equal('talks');
expect(suggestions[0]).to.be.equal('talk');
expect(suggestions).to.deep.equal(['talk', 'talks', 'walk']);
});
it('Tests suggestions', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore jernals
const results = Sug.suggest(trie.root, 'jernals');
// console.log(JSON.stringify(results));
const suggestions = results.map(s => s.word);
expect(suggestions).to.deep.equal(['journals', 'journal']);
});
it('Tests suggestions for `juornals` (reduced cost for swap)', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore juornals
const results = Sug.suggest(trie.root, 'juornals');
// console.log(JSON.stringify(results));
const suggestions = results.map(s => s.word);
expect(suggestions).to.deep.equal([
'journals',
'journal',
'journalism',
'journalist',
'journey',
'jovial',
]);
});
it('Tests suggestions', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore joyfull
const results = Sug.suggest(trie.root, 'joyfull');
// console.log(JSON.stringify(results));
const suggestions = results.map(s => s.word);
expect(suggestions).to.deep.equal(['joyfully', 'joyful', 'joyfuller', 'joyfullest', 'joyous']);
});
it('Tests compound suggestions', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore walkingtalkingjoy
const results = Sug.suggest(trie.root, 'walkingtalkingjoy', 1, Sug.CompoundWordsMethod.SEPARATE_WORDS);
// console.log(JSON.stringify(results));
const suggestions = results.map(s => s.word);
expect(suggestions).to.deep.equal(['walking talking joy', ]);
});
it('Tests suggestions', () => {
const trie = Trie.create(sampleWords);
const results = Sug.suggest(trie.root, '');
// console.log(JSON.stringify(results));
const suggestions = results.map(s => s.word);
expect(suggestions).to.deep.equal([]);
});
it('Tests suggestions with low max num', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore joyfull
const results = Sug.suggest(trie.root, 'joyfull', 3);
// console.log(JSON.stringify(results));
const suggestions = results.map(s => s.word);
expect(suggestions).to.deep.equal(['joyfully', 'joyful', 'joyfuller']);
});
it('Tests genSuggestions', () => {
const trie = Trie.create(sampleWords);
const collector = Sug.suggestionCollector('joyfull', 3, (word) => word !== 'joyfully');
collector.collect(
Sug.genSuggestions(trie.root, collector.word)
);
const suggestions = collector.suggestions.map(s => s.word);
expect(suggestions).to.not.contain('joyfully');
expect(suggestions).to.deep.equal(['joyful', 'joyfuller', 'joyfullest']);
expect(collector.maxCost).to.be.lessThan(300);
});
it('Tests genSuggestions wanting 0', () => {
const trie = Trie.create(sampleWords);
const collector = Sug.suggestionCollector('joyfull', 0);
collector.collect(
Sug.genSuggestions(trie.root, collector.word)
);
const suggestions = collector.suggestions.map(s => s.word);
expect(suggestions).to.be.length(0);
});
it('Tests genSuggestions wanting -10', () => {
const trie = Trie.create(sampleWords);
const collector = Sug.suggestionCollector('joyfull', -10);
collector.collect(
Sug.genSuggestions(trie.root, collector.word)
);
const suggestions = collector.suggestions.map(s => s.word);
expect(suggestions).to.be.length(0);
});
it('Tests genSuggestions as array', () => {
const trie = Trie.create(sampleWords);
const sugs = [...Sug.genSuggestions(trie.root, 'joyfull')];
const sr = sugs.sort(Sug.compSuggestionResults);
const suggestions = sr.map(s => s && s.word);
expect(suggestions).to.deep.equal(['joyfully', 'joyful', 'joyfuller', 'joyfullest', 'joyous']);
});
it('Tests genSuggestions with compounds', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore joyfullwalk
const collector = Sug.suggestionCollector('joyfullwalk', 3);
collector.collect(
Sug.genCompoundableSuggestions(trie.root, collector.word, Sug.CompoundWordsMethod.SEPARATE_WORDS)
);
const suggestions = collector.suggestions.map(s => s.word);
expect(suggestions).to.deep.equal(['joyful walk', 'joyful walks', 'joyfully walk']);
expect(collector.maxCost).to.be.lessThan(300);
});
it('Tests genSuggestions with compounds', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore joyfullwalk joyfulwalk joyfulwalks joyfullywalk, joyfullywalks
const collector = Sug.suggestionCollector('joyfullwalk', 3);
collector.collect(
Sug.genCompoundableSuggestions(trie.root, collector.word, Sug.CompoundWordsMethod.JOIN_WORDS)
);
const suggestions = collector.suggestions.map(s => s.word);
expect(suggestions).to.deep.equal(['joyful+walk', 'joyful+walks', 'joyfully+walk', ]);
expect(collector.maxCost).to.be.lessThan(300);
});
it('Tests the collector with filter', () => {
const collector = Sug.suggestionCollector('joyfull', 3, (word) => word !== 'joyfully');
collector.add({ word: 'joyfully', cost: 100 })
.add({ word: 'joyful', cost: 100 });
expect(collector.suggestions).to.be.length(1);
});
it('Tests the collector with duplicate words of different costs', () => {
const collector = Sug.suggestionCollector('joyfull', 3, (word) => word !== 'joyfully');
collector.add({ word: 'joyful', cost: 100 });
expect(collector.suggestions.length).to.be.equal(1);
collector.add({ word: 'joyful', cost: 75 });
expect(collector.suggestions.length).to.be.equal(1);
expect(collector.suggestions[0].cost).to.be.equal(75);
collector.add({ word: 'joyfuller', cost: 200 })
.add({ word: 'joyfullest', cost: 300 })
.add({ word: 'joyfulness', cost: 340 })
.add({ word: 'joyful', cost: 85 });
expect(collector.suggestions.length).to.be.equal(3);
expect(collector.suggestions[0].cost).to.be.equal(75);
});
it('Test that accents are closer', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore wålk
const collector = Sug.suggestionCollector('wålk', 3);
collector.collect(
Sug.genCompoundableSuggestions(trie.root, collector.word, Sug.CompoundWordsMethod.JOIN_WORDS)
);
const suggestions = collector.suggestions.map(s => s.word);
expect(suggestions).to.deep.equal(['walk', 'walks', 'talk']);
});
it('Test that accents are closer', () => {
const trie = Trie.create(sampleWords);
// cspell:ignore wâlkéd
const collector = Sug.suggestionCollector('wâlkéd', 3);
collector.collect(
Sug.genCompoundableSuggestions(trie.root, collector.word, Sug.CompoundWordsMethod.JOIN_WORDS)
);
const suggestions = collector.suggestions.map(s => s.word);
expect(suggestions).to.deep.equal(['walked', 'walker', 'talked']);
});
});
const sampleWords = [
'walk',
'walked',
'walker',
'walking',
'walks',
'talk',
'talks',
'talked',
'talker',
'talking',
'lift',
'lifts',
'lifted',
'lifter',
'lifting',
'journal',
'journals',
'journalism',
'journalist',
'journalistic',
'journey',
'journeyer',
'journeyman',
'journeymen',
'joust',
'jouster',
'jousting',
'jovial',
'joviality',
'jowl',
'jowly',
'joy',
'joyful',
'joyfuller',
'joyfullest',
'joyfully',
'joyfulness',
'joyless',
'joylessness',
'joyous',
'joyousness',
'joyridden',
'joyride',
'joyrider',
'joyriding',
'joyrode',
'joystick',
];
| mit |
FacticiusVir/SharpVk | src/SharpVk/PhysicalDeviceDepthStencilResolveProperties.gen.cs | 2941 | // The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct PhysicalDeviceDepthStencilResolveProperties
{
/// <summary>
///
/// </summary>
public SharpVk.ResolveModeFlags SupportedDepthResolveModes
{
get;
set;
}
/// <summary>
///
/// </summary>
public SharpVk.ResolveModeFlags SupportedStencilResolveModes
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool IndependentResolveNone
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool IndependentResolve
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="pointer">
/// </param>
internal static unsafe PhysicalDeviceDepthStencilResolveProperties MarshalFrom(SharpVk.Interop.PhysicalDeviceDepthStencilResolveProperties* pointer)
{
PhysicalDeviceDepthStencilResolveProperties result = default(PhysicalDeviceDepthStencilResolveProperties);
result.SupportedDepthResolveModes = pointer->SupportedDepthResolveModes;
result.SupportedStencilResolveModes = pointer->SupportedStencilResolveModes;
result.IndependentResolveNone = pointer->IndependentResolveNone;
result.IndependentResolve = pointer->IndependentResolve;
return result;
}
}
}
| mit |
orchestral/orchestra | controllers/resources.php | 2106 | <?php
use Orchestra\Presenter\Resource as ResourcePresenter,
Orchestra\Resources,
Orchestra\Site,
Orchestra\View;
class Orchestra_Resources_Controller extends Orchestra\Controller {
/**
* Construct Resources Controller, only authenticated user should be able
* to access this controller.
*
* @access public
* @return void
*/
public function __construct()
{
parent::__construct();
$this->filter('before', 'orchestra::auth');
}
/**
* Route to Resources List
*
* @access private
* @param array $resources
* @return Response
*/
private function index_page($resources)
{
$model = array();
foreach ($resources as $name => $resource)
{
if (false === value($resource->visible)) continue;
$model[$name] = $resource;
}
Site::set('title', __('orchestra::title.resources.list'));
Site::set('description', __('orchestra::title.resources.list-detail'));
return View::make('orchestra::resources.index', array(
'table' => ResourcePresenter::table($model),
));
}
/**
* Add a drop-in resource anywhere on Orchestra
*
* @access public
* @param string $request
* @param array $arguments
* @return Response
*/
public function __call($request, $arguments = array())
{
list($method, $name) = explode('_', $request, 2);
unset($method);
$action = array_shift($arguments) ?: 'index';
$content = null;
$resources = Resources::all();
switch (true)
{
case ($name === 'index' and $name === $action) :
return $this->index_page($resources);
break;
default :
$content = Resources::call($name, $action, $arguments);
break;
}
return Resources::response($content, function ($content)
use ($resources, $name, $action)
{
( ! str_contains($name, '.')) ?
$namespace = $name : list($namespace,) = explode('.', $name, 2);
return View::make('orchestra::resources.resources', array(
'content' => $content,
'resources' => array(
'list' => $resources,
'namespace' => $namespace,
'name' => $name,
'action' => $action,
),
));
});
}
}
| mit |
genavarov/lamacoin | src/rpcprotocol.cpp | 8865 | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcprotocol.h"
#include "clientversion.h"
#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include "version.h"
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
//! Number of bytes to allocate and read at most at once in post data
const size_t POST_READ_SIZE = 256 * 1024;
/**
* HTTP protocol
*
* This ain't Apache. We're just using HTTP header for the length field
* and to be compatible with other JSON-RPC implementations.
*/
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: lamacoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
static string rfc1123Time()
{
return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime());
}
static const char *httpStatusDescription(int nStatus)
{
switch (nStatus) {
case HTTP_OK: return "OK";
case HTTP_BAD_REQUEST: return "Bad Request";
case HTTP_FORBIDDEN: return "Forbidden";
case HTTP_NOT_FOUND: return "Not Found";
case HTTP_INTERNAL_SERVER_ERROR: return "Internal Server Error";
default: return "";
}
}
string HTTPError(int nStatus, bool keepalive, bool headersOnly)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: lamacoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time(), FormatFullVersion());
return HTTPReply(nStatus, httpStatusDescription(nStatus), keepalive,
headersOnly, "text/plain");
}
string HTTPReplyHeader(int nStatus, bool keepalive, size_t contentLength, const char *contentType)
{
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %u\r\n"
"Content-Type: %s\r\n"
"Server: lamacoin-json-rpc/%s\r\n"
"\r\n",
nStatus,
httpStatusDescription(nStatus),
rfc1123Time(),
keepalive ? "keep-alive" : "close",
contentLength,
contentType,
FormatFullVersion());
}
string HTTPReply(int nStatus, const string& strMsg, bool keepalive,
bool headersOnly, const char *contentType)
{
if (headersOnly)
{
return HTTPReplyHeader(nStatus, keepalive, 0, contentType);
} else {
return HTTPReplyHeader(nStatus, keepalive, strMsg.size(), contentType) + strMsg;
}
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
while (true)
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto, size_t max_size)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || (size_t)nLen > max_size)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch;
size_t ptr = 0;
while (ptr < (size_t)nLen)
{
size_t bytes_to_read = std::min((size_t)nLen - ptr, POST_READ_SIZE);
vch.resize(ptr + bytes_to_read);
stream.read(&vch[ptr], bytes_to_read);
if (!stream) // Connection lost while reading
return HTTP_INTERNAL_SERVER_ERROR;
ptr += bytes_to_read;
}
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
/**
* JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
* but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
* unspecified (HTTP errors and contents of 'error').
*
* 1.0 spec: http://json-rpc.org/wiki/specification
* 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html
* http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
*/
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
| mit |
MadMartians/alcohol | public/js/sockets/stream.js | 18 | var socket = io()
| mit |
progre/sx13 | Scarlex13/UserInterfaces/Commons/ValueObjects/Color.cs | 340 | namespace Progressive.Scarlex13.UserInterfaces.Commons.ValueObjects
{
internal struct Color
{
public byte Blue;
public byte Green;
public byte Red;
public Color(byte red, byte green, byte blue)
{
Red = red;
Green = green;
Blue = blue;
}
}
} | mit |
ramunasd/platform | src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/grid.js | 28486 | define(function(require) {
'use strict';
var Grid;
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var Backgrid = require('backgrid');
var __ = require('orotranslation/js/translator');
var mediator = require('oroui/js/mediator');
var LoadingMaskView = require('oroui/js/app/views/loading-mask-view');
var GridHeader = require('./header');
var GridBody = require('./body');
var GridFooter = require('./footer');
var GridColumns = require('./columns');
var Toolbar = require('./toolbar');
var ActionColumn = require('./column/action-column');
var SelectRowCell = require('oro/datagrid/cell/select-row-cell');
var SelectAllHeaderCell = require('./header-cell/select-all-header-cell');
var RefreshCollectionAction = require('oro/datagrid/action/refresh-collection-action');
var ResetCollectionAction = require('oro/datagrid/action/reset-collection-action');
var ExportAction = require('oro/datagrid/action/export-action');
var PluginManager = require('oroui/js/app/plugins/plugin-manager');
var scrollHelper = require('oroui/js/tools/scroll-helper');
/**
* Basic grid class.
*
* Triggers events:
* - "rowClicked" when row of grid body is clicked
*
* @export orodatagrid/js/datagrid/grid
* @class orodatagrid.datagrid.Grid
* @extends Backgrid.Grid
*/
Grid = Backgrid.Grid.extend({
/** @property {String} */
name: 'datagrid',
/** @property {String} */
tagName: 'div',
/** @property {int} */
requestsCount: 0,
/** @property {String} */
className: 'oro-datagrid',
/** @property */
template: _.template(
'<div class="toolbar"></div>' +
'<div class="other-scroll-container">' +
'<div class="other-scroll"><div></div></div>' +
'<div class="container-fluid grid-scrollable-container">' +
'<div class="grid-container">' +
'<table class="grid table-hover table table-bordered table-condensed"></table>' +
'</div>' +
'</div>' +
'<div class="no-data"></div>' +
'</div>'
),
/** @property */
noDataTemplate: _.template('<span><%= hint %><span>'),
/** @property {Object} */
selectors: {
grid: '.grid',
toolbar: '.toolbar',
noDataBlock: '.no-data',
filterBox: '.filter-box',
loadingMaskContainer: '.other-scroll-container',
floatTheadContainer: '.floatThead-container'
},
/** @property {orodatagrid.datagrid.Header} */
header: GridHeader,
/** @property {orodatagrid.datagrid.Body} */
body: GridBody,
/** @property {orodatagrid.datagrid.Footer} */
footer: GridFooter,
/** @property {orodatagrid.datagrid.Toolbar} */
toolbar: Toolbar,
/** @property {orodatagrid.datagrid.MetadataModel} */
metadataModel: null,
/** @property {LoadingMaskView|null} */
loadingMask: null,
/** @property {orodatagrid.datagrid.column.ActionColumn} */
actionsColumn: ActionColumn,
/** @property true when no one column configured to be shown in th grid */
noColumnsFlag: false,
/**
* @property {Object} Default properties values
*/
defaults: {
rowClickActionClass: 'row-click-action',
rowClassName: '',
toolbarOptions: {
addResetAction: true,
addRefreshAction: true,
addColumnManager: true,
columnManager: {}
},
rowClickAction: undefined,
multipleSorting: true,
rowActions: [],
massActions: new Backbone.Collection(),
enableFullScreenLayout: false
},
/**
* Column indexing starts from this valus in case when 'order' is not specified in column config.
* This start index required to display new columns at end of already sorted columns set
*/
DEFAULT_COLUMN_START_INDEX: 1000,
/**
* Initialize grid
*
* @param {Object} options
* @param {Backbone.Collection} options.collection
* @param {(Backbone.Collection|Array)} options.columns
* @param {String} [options.rowClickActionClass] CSS class for row with click action
* @param {String} [options.rowClassName] CSS class for row
* @param {Object} [options.toolbarOptions] Options for toolbar
* @param {Object} [options.exportOptions] Options for export
* @param {Array<oro.datagrid.action.AbstractAction>} [options.rowActions] Array of row actions prototypes
* @param {Backbone.Collection<oro.datagrid.action.AbstractAction>} [options.massActions] Collection of mass actions prototypes
* @param {Boolean} [options.multiSelectRowEnabled] Option for enabling multi select row
* @param {oro.datagrid.action.AbstractAction} [options.rowClickAction] Prototype for
* action that handles row click
* @throws {TypeError} If mandatory options are undefined
*/
initialize: function(options) {
var opts = options || {};
this.subviews = [];
this.pluginManager = new PluginManager(this);
if (options.plugins) {
this.pluginManager.enable(options.plugins);
}
this.trigger('beforeParseOptions', options);
if (this.className) {
this.$el.addClass(_.result(this, 'className'));
}
// Check required options
if (!opts.collection) {
throw new TypeError('"collection" is required');
}
this.collection = opts.collection;
if (!opts.columns) {
throw new TypeError('"columns" is required');
}
if (opts.columns.length === 0) {
this.noColumnsFlag = true;
}
if (!opts.metadataModel) {
throw new TypeError('"metadataModel" is required');
}
// Init properties values based on options and defaults
_.extend(this, this.defaults, opts);
this.toolbarOptions = {};
_.extend(this.toolbarOptions, this.defaults.toolbarOptions, opts.toolbarOptions);
this.exportOptions = {};
_.extend(this.exportOptions, opts.exportOptions);
this.collection.multipleSorting = this.multipleSorting;
this._initRowActions();
if (this.rowClickAction) {
// This option property is used in orodatagrid.datagrid.Body
opts.rowClassName = this.rowClickActionClass + ' ' + this.rowClassName;
}
this._initColumns(opts);
this.toolbar = this._createToolbar(this.toolbarOptions);
// use columns collection as event bus since there is no alternatives
this.listenTo(this.columns, 'afterMakeCell', function(row, cell) {
this.trigger('afterMakeCell', row, cell);
});
this.trigger('beforeBackgridInitialize');
Grid.__super__.initialize.apply(this, arguments);
this.trigger('afterBackgridInitialize');
// Listen and proxy events
this._listenToCollectionEvents();
this._listenToContentEvents();
this._listenToCommands();
},
/**
* @inheritDoc
*/
dispose: function() {
var subviews;
if (this.disposed) {
return;
}
this.pluginManager.dispose();
_.each(this.columns.models, function(column) {
column.dispose();
});
this.columns.dispose();
delete this.columns;
delete this.refreshAction;
delete this.resetAction;
delete this.exportAction;
subviews = ['header', 'body', 'footer', 'toolbar', 'loadingMask'];
_.each(subviews, function(viewName) {
this[viewName].dispose();
delete this[viewName];
}, this);
Grid.__super__.dispose.call(this);
},
/**
* Initializes columns collection required to draw grid
*
* @param {Object} options
* @private
*/
_initColumns: function(options) {
if (Object.keys(this.rowActions).length > 0) {
options.columns.push(this._createActionsColumn());
}
if (options.multiSelectRowEnabled) {
options.columns.unshift(this._createSelectRowColumn());
}
for (var i = 0; i < options.columns.length; i++) {
var column = options.columns[i];
if (column.order === void 0 && !(column instanceof Backgrid.Column)) {
column.order = i + this.DEFAULT_COLUMN_START_INDEX;
}
column.metadata = _.findWhere(options.metadata.columns, {name: column.name});
}
this.columns = options.columns = new GridColumns(options.columns);
this.columns.sort();
},
/**
* Init this.rowActions and this.rowClickAction
*
* @private
*/
_initRowActions: function() {
if (!this.rowClickAction) {
this.rowClickAction = _.find(this.rowActions, function(action) {
return Boolean(action.prototype.rowAction);
});
}
},
/**
* Creates actions column
*
* @return {Backgrid.Column}
* @private
*/
_createActionsColumn: function() {
var column;
column = new this.actionsColumn({
datagrid: this,
actions: this.rowActions,
massActions: this.massActions,
manageable: false,
order: Infinity
});
return column;
},
/**
* Creates mass actions column
*
* @return {Backgrid.Column}
* @private
*/
_createSelectRowColumn: function() {
var column;
column = new Backgrid.Column({
name: 'massAction',
label: __('Selected Rows'),
renderable: true,
sortable: false,
editable: false,
manageable: false,
cell: SelectRowCell,
headerCell: SelectAllHeaderCell,
order: -Infinity
});
return column;
},
/**
* Gets selection state
*
* @returns {{selectedModels: *, inset: boolean}}
*/
getSelectionState: function() {
var selectAllHeader = this.header.row.cells[0];
return selectAllHeader.getSelectionState();
},
/**
* Resets selection state
*/
resetSelectionState: function() {
this.collection.trigger('backgrid:selectNone');
},
/**
* Creates instance of toolbar
*
* @return {orodatagrid.datagrid.Toolbar}
* @private
*/
_createToolbar: function(options) {
var toolbar;
var toolbarOptions = {
collection: this.collection,
actions: this._getToolbarActions(),
extraActions: this._getToolbarExtraActions()
};
_.defaults(toolbarOptions, options);
this.trigger('beforeToolbarInit', toolbarOptions);
toolbar = new this.toolbar(toolbarOptions);
this.trigger('afterToolbarInit', toolbar);
return toolbar;
},
/**
* Get actions of toolbar
*
* @return {Array}
* @private
*/
_getToolbarActions: function() {
var actions = [];
if (this.toolbarOptions.addRefreshAction) {
actions.push(this.getRefreshAction());
}
if (this.toolbarOptions.addResetAction) {
actions.push(this.getResetAction());
}
return actions;
},
/**
* Get actions of toolbar
*
* @return {Array}
* @private
*/
_getToolbarExtraActions: function() {
var actions = [];
if (!_.isEmpty(this.exportOptions)) {
actions.push(this.getExportAction());
}
return actions;
},
/**
* Get action that refreshes grid's collection
*
* @return {oro.datagrid.action.RefreshCollectionAction}
*/
getRefreshAction: function() {
if (!this.refreshAction) {
this.refreshAction = new RefreshCollectionAction({
datagrid: this,
launcherOptions: {
label: __('oro_datagrid.action.refresh'),
className: 'btn',
iconClassName: 'icon-repeat'
}
});
this.listenTo(mediator, 'datagrid:doRefresh:' + this.name, _.debounce(function() {
if (this.$el.is(':visible')) {
this.refreshAction.execute();
}
}, 100));
this.listenTo(this.refreshAction, 'preExecute', function(action, options) {
this.$el.trigger('preExecute:refresh:' + this.name, [action, options]);
});
}
return this.refreshAction;
},
/**
* Get action that resets grid's collection
*
* @return {oro.datagrid.action.ResetCollectionAction}
*/
getResetAction: function() {
if (!this.resetAction) {
this.resetAction = new ResetCollectionAction({
datagrid: this,
launcherOptions: {
label: __('oro_datagrid.action.reset'),
className: 'btn',
iconClassName: 'icon-refresh'
}
});
this.listenTo(mediator, 'datagrid:doReset:' + this.name, _.debounce(function() {
if (this.$el.is(':visible')) {
this.resetAction.execute();
}
}, 100));
this.listenTo(this.resetAction, 'preExecute', function(action, options) {
this.$el.trigger('preExecute:reset:' + this.name, [action, options]);
});
}
return this.resetAction;
},
/**
* Get action that exports grid's data
*
* @return {oro.datagrid.action.ExportAction}
*/
getExportAction: function() {
if (!this.exportAction) {
var links = [];
_.each(this.exportOptions, function(val, key) {
links.push({
key: key,
label: val.label,
attributes: {
'class': 'no-hash',
'download': null
}
});
});
this.exportAction = new ExportAction({
datagrid: this,
launcherOptions: {
label: __('oro.datagrid.extension.export.label'),
title: __('oro.datagrid.extension.export.tooltip'),
className: 'btn',
iconClassName: 'icon-upload-alt',
links: links
}
});
this.listenTo(this.exportAction, 'preExecute', function(action, options) {
this.$el.trigger('preExecute:export:' + this.name, [action, options]);
});
}
return this.exportAction;
},
/**
* Listen to events of collection
*
* @private
*/
_listenToCollectionEvents: function() {
this.listenTo(this.collection, 'request', function(model, xhr) {
this._beforeRequest();
var self = this;
var always = xhr.always;
xhr.always = function() {
always.apply(this, arguments);
if (!self.disposed) {
self._afterRequest(this);
}
};
});
this.listenTo(this.collection, 'remove', this._onRemove);
this.listenTo(this.collection, 'change', function(model) {
this.$el.trigger('datagrid:change:' + this.name, model);
});
},
/**
* Listen to events of body, proxies events "rowClicked", handle run of rowClickAction if required
*
* @private
*/
_listenToContentEvents: function() {
this.listenTo(this.body, 'rowClicked', function(row) {
this.trigger('rowClicked', this, row);
this._runRowClickAction(row);
});
this.listenTo(this.columns, 'change:renderable', function() {
this.trigger('content:update');
});
this.listenTo(this.header.row, 'columns:reorder', function() {
// triggers content:update event in separate process
// to give time body's rows to finish reordering
_.defer(_.bind(this.trigger, this, 'content:update'));
});
},
/**
* Create row click action
*
* @param {orodatagrid.datagrid.Row} row
* @private
*/
_runRowClickAction: function(row) {
var config;
if (!this.rowClickAction) {
return;
}
var action = new this.rowClickAction({
datagrid: this,
model: row.model
});
if (typeof action.dispose === 'function') {
this.subviews.push(action);
}
config = row.model.get('action_configuration');
if (!config || config[action.name] !== false) {
action.run();
}
},
/**
* Listen to commands on mediator
*/
_listenToCommands: function() {
this.listenTo(mediator, 'datagrid:setParam:' + this.name, function(param, value) {
this.setAdditionalParameter(param, value);
});
this.listenTo(mediator, 'datagrid:removeParam:' + this.name, function(param) {
this.removeAdditionalParameter(param);
});
this.listenTo(mediator, 'datagrid:restoreState:' + this.name,
function(columnName, dataField, included, excluded) {
this.collection.each(function(model) {
if (_.indexOf(included, model.get(dataField)) !== -1) {
model.set(columnName, true);
}
if (_.indexOf(excluded, model.get(dataField)) !== -1) {
model.set(columnName, false);
}
});
});
this.listenTo(mediator, 'datagrid:restoreChangeset:' + this.name, function(dataField, changeset) {
this.collection.each(function(model) {
if (changeset[model.get(dataField)]) {
_.each(changeset[model.get(dataField)], function(value, columnName) {
model.set(columnName, value);
});
}
});
});
},
/**
* Renders the grid, no data block and loading mask
*
* @return {*}
*/
render: function() {
this.$el.html(this.template());
this.$grid = this.$(this.selectors.grid);
this.renderToolbar();
this.renderGrid();
this.renderNoDataBlock();
this.renderLoadingMask();
this.listenTo(this.collection, 'reset', this.renderNoDataBlock);
this._deferredRender();
this.initLayout().always(_.bind(function() {
this.rendered = true;
/**
* Backbone event. Fired when the grid has been successfully rendered.
* @event rendered
*/
this.trigger('rendered');
/**
* Backbone event. Fired when data for grid has been successfully rendered.
* @event grid_render:complete
*/
mediator.trigger('grid_render:complete', this.$el);
this._resolveDeferredRender();
}, this));
return this;
},
/**
* Renders the grid's header, then footer, then finally the body.
*/
renderGrid: function() {
this.$grid.append(this.header.render().$el);
if (this.footer) {
this.$grid.append(this.footer.render().$el);
}
this.$grid.append(this.body.render().$el);
mediator.trigger('grid_load:complete', this.collection, this.$grid);
},
/**
* Renders grid toolbar.
*/
renderToolbar: function() {
this.$(this.selectors.toolbar).append(this.toolbar.render().$el);
},
/**
* Renders loading mask.
*/
renderLoadingMask: function() {
if (this.loadingMask) {
this.loadingMask.dispose();
}
this.loadingMask = new LoadingMaskView({
container: this.$(this.selectors.loadingMaskContainer)
});
},
/**
* Define no data block.
*/
_defineNoDataBlock: function() {
var placeholders = {
entityHint: (this.entityHint || __('oro.datagrid.entityHint')).toLowerCase()
};
var message = _.isEmpty(this.collection.state.filters) ?
'oro.datagrid.no.entities' : 'oro.datagrid.no.results';
message = this.noColumnsFlag ? 'oro.datagrid.no.columns' : message;
this.$(this.selectors.noDataBlock).html($(this.noDataTemplate({
hint: __(message, placeholders).replace('\n', '<br />')
})));
},
/**
* Triggers when collection "request" event fired
*
* @private
*/
_beforeRequest: function() {
this.requestsCount += 1;
this.showLoading();
},
/**
* Triggers when collection request is done
*
* @private
*/
_afterRequest: function(jqXHR) {
var json = jqXHR.responseJSON || {};
if (json.metadata) {
this._processLoadedMetadata(json.metadata);
}
this.requestsCount -= 1;
if (this.requestsCount === 0) {
this.hideLoading();
/**
* Backbone event. Fired when data for grid has been successfully rendered.
* @event grid_load:complete
*/
mediator.trigger('grid_load:complete', this.collection, this.$el);
this.initLayout();
this.trigger('content:update');
}
},
/**
* @param {Object} metadata
* @private
*/
_processLoadedMetadata: function(metadata) {
_.extend(this.metadata, metadata);
this.metadataModel.set(metadata);
},
/**
* Show loading mask and disable toolbar
*/
showLoading: function() {
this.loadingMask.show();
this.toolbar.disable();
this.trigger('disable');
},
/**
* Hide loading mask and enable toolbar
*/
hideLoading: function() {
this.loadingMask.hide();
this.toolbar.enable();
this.trigger('enable');
},
/**
* Update no data block status
*
* @private
*/
renderNoDataBlock: function() {
this._defineNoDataBlock();
this.$el.toggleClass('no-data-visible', this.collection.models.length <= 0 || this.noColumnsFlag);
},
/**
* Triggers when collection "remove" event fired
*
* @private
*/
_onRemove: function(model) {
mediator.trigger('datagrid:beforeRemoveRow:' + this.name, model);
this.collection.fetch({reset: true});
mediator.trigger('datagrid:afterRemoveRow:' + this.name);
},
/**
* Set additional parameter to send on server
*
* @param {String} name
* @param value
*/
setAdditionalParameter: function(name, value) {
var state = this.collection.state;
if (!_.has(state, 'parameters')) {
state.parameters = {};
}
state.parameters[name] = value;
},
/**
* Remove additional parameter
*
* @param {String} name
*/
removeAdditionalParameter: function(name) {
var state = this.collection.state;
if (_.has(state, 'parameters')) {
delete state.parameters[name];
}
},
/**
* Ensure that cell is visible. Works like cell.el.scrollIntoView, but in more appropriate way
*
* @param cell
*/
ensureCellIsVisible: function(cell) {
var e = $.Event('ensureCellIsVisible');
this.trigger('ensureCellIsVisible', e, cell);
if (e.isDefaultPrevented()) {
return;
}
scrollHelper.scrollIntoView(cell.el);
},
/**
* Finds cell by corresponding model and column
*
* @param model
* @param column
* @return {Backgrid.Cell}
*/
findCell: function(model, column) {
var rows = this.body.rows;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.model === model) {
var cells = row.cells;
for (var j = 0; j < cells.length; j++) {
var cell = cells[j];
if (cell.column === column) {
return cell;
}
}
}
}
return null;
},
/**
* Finds cell by model and column indexes
*
* @param {number} modelI
* @param {number} columnI
* @return {Backgrid.Cell}
*/
findCellByIndex: function(modelI, columnI) {
try {
return _.findWhere(this.body.rows[modelI].cells, {
column: this.columns.at(columnI)
});
} catch (e) {
return null;
}
},
/**
* Finds header cell by column index
*
* @param {number} columnI
* @return {Backgrid.Cell}
*/
findHeaderCellByIndex: function(columnI) {
try {
return _.findWhere(this.header.row.cells, {
column: this.columns.at(columnI)
});
} catch (e) {
return null;
}
}
});
return Grid;
});
| mit |
robertecurtin/plutos-envy | PlutosEnvy/urls.py | 839 | """PlutosEnvy URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^game/', include('game.urls')),
url(r'^admin/', admin.site.urls),
]
| mit |
kazinduzi/kasoko | vendor/Solarium/QueryType/Analysis/ResponseParser/Field.php | 5174 | <?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.
*
* @copyright Copyright 2011 Bas de Nooijer <[email protected]>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*/
/**
* @namespace
*/
namespace Solarium\QueryType\Analysis\ResponseParser;
use Solarium\Core\Query\Result\Result;
use Solarium\QueryType\Analysis\Result as AnalysisResult;
use Solarium\QueryType\Analysis\Result\ResultList;
use Solarium\QueryType\Analysis\Result\Item;
use Solarium\QueryType\Analysis\Result\Types;
use Solarium\Core\Query\ResponseParser as ResponseParserAbstract;
use Solarium\Core\Query\ResponseParserInterface as ResponseParserInterface;
/**
* Parse document analysis response data
*/
class Field extends ResponseParserAbstract implements ResponseParserInterface
{
/**
* Parse response data
*
* @param Result $result
* @return array
*/
public function parse($result)
{
$data = $result->getData();
if (isset($data['analysis'])) {
$items = $this->parseAnalysis($result, $data['analysis']);
} else {
$items = array();
}
return $this->addHeaderInfo($data, array('items' => $items));
}
/**
* Parser
*
* @param Result $result
* @param array $data
* @return Types[]
*/
protected function parseAnalysis($result, $data)
{
$types = array();
foreach ($data as $documentKey => $documentData) {
$fields = $this->parseTypes($result, $documentData);
$types[] = new AnalysisResult\ResultList($documentKey, $fields);
}
return $types;
}
/**
* Parse analysis types and items
*
* @param Result $result
* @param array $typeData
* @return Types[]
*/
protected function parseTypes($result, $typeData)
{
$query = $result->getQuery();
$results = array();
foreach ($typeData as $fieldKey => $fieldData) {
$types = array();
foreach ($fieldData as $typeKey => $typeData) {
if ($query->getResponseWriter() == $query::WT_JSON) {
// fix for extra level for key fields
if (count($typeData) == 1) {
$typeData = current($typeData);
}
$typeData = $this->convertToKeyValueArray($typeData);
}
$classes = array();
foreach ($typeData as $class => $analysis) {
if (is_string($analysis)) {
$item = new Item(
array(
'text' => $analysis,
'start' => null,
'end' => null,
'position' => null,
'positionHistory' => null,
'type' => null,
)
);
$classes[] = new ResultList($class, array($item));
} else {
$items = array();
foreach ($analysis as $itemData) {
$items[] = new Item($itemData);
}
$classes[] = new ResultList($class, $items);
}
}
$types[] = new ResultList($typeKey, $classes);
}
$results[] = new Types($fieldKey, $types);
}
return $results;
}
}
| mit |
diddledan/diddledan.github.io | @polymer/polymer/lib/utils/array-splice.d.ts | 1507 | /**
* DO NOT EDIT
*
* This file was automatically generated by
* https://github.com/Polymer/gen-typescript-declarations
*
* To modify these typings, edit the source file(s):
* lib/utils/array-splice.js
*/
export {calculateSplices};
/**
* Returns an array of splice records indicating the minimum edits required
* to transform the `previous` array into the `current` array.
*
* Splice records are ordered by index and contain the following fields:
* - `index`: index where edit started
* - `removed`: array of removed items from this index
* - `addedCount`: number of items added at this index
*
* This function is based on the Levenshtein "minimum edit distance"
* algorithm. Note that updates are treated as removal followed by addition.
*
* The worst-case time complexity of this algorithm is `O(l * p)`
* l: The length of the current array
* p: The length of the previous array
*
* However, the worst-case complexity is reduced by an `O(n)` optimization
* to detect any shared prefix & suffix between the two arrays and only
* perform the more expensive minimum edit distance calculation over the
* non-shared portions of the arrays.
*
* @returns Returns an array of splice record objects. Each of these
* contains: `index` the location where the splice occurred; `removed`
* the array of removed items from this location; `addedCount` the number
* of items added at this location.
*/
declare function calculateSplices(current: any[], previous: any[]): any[];
| mit |
DanWahlin/CustomerManagerStandard | CustomerManager/test/lib/angular-mocks.js | 94155 | /**
* @license AngularJS v1.3.0
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function (window, angular, undefined) {
'use strict';
/**
* @ngdoc object
* @name angular.mock
* @description
*
* Namespace from 'angular-mocks.js' which contains testing related code.
*/
angular.mock = {};
/**
* ! This is a private undocumented service !
*
* @name $browser
*
* @description
* This service is a mock implementation of {@link ng.$browser}. It provides fake
* implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
* cookies, etc...
*
* The api of this service is the same as that of the real {@link ng.$browser $browser}, except
* that there are several helper methods available which can be used in tests.
*/
angular.mock.$BrowserProvider = function () {
this.$get = function () {
return new angular.mock.$Browser();
};
};
angular.mock.$Browser = function () {
var self = this;
this.isMock = true;
self.$$url = "http://server/";
self.$$lastUrl = self.$$url; // used by url polling fn
self.pollFns = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = angular.noop;
self.$$incOutstandingRequestCount = angular.noop;
// register url polling fn
self.onUrlChange = function (listener) {
self.pollFns.push(
function () {
if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) {
self.$$lastUrl = self.$$url;
self.$$lastState = self.$$state;
listener(self.$$url, self.$$state);
}
}
);
return listener;
};
self.$$checkUrlChange = angular.noop;
self.cookieHash = {};
self.lastCookieHash = {};
self.deferredFns = [];
self.deferredNextId = 0;
self.defer = function (fn, delay) {
delay = delay || 0;
self.deferredFns.push({ time: (self.defer.now + delay), fn: fn, id: self.deferredNextId });
self.deferredFns.sort(function (a, b) { return a.time - b.time; });
return self.deferredNextId++;
};
/**
* @name $browser#defer.now
*
* @description
* Current milliseconds mock time.
*/
self.defer.now = 0;
self.defer.cancel = function (deferId) {
var fnIndex;
angular.forEach(self.deferredFns, function (fn, index) {
if (fn.id === deferId) fnIndex = index;
});
if (fnIndex !== undefined) {
self.deferredFns.splice(fnIndex, 1);
return true;
}
return false;
};
/**
* @name $browser#defer.flush
*
* @description
* Flushes all pending requests and executes the defer callbacks.
*
* @param {number=} number of milliseconds to flush. See {@link #defer.now}
*/
self.defer.flush = function (delay) {
if (angular.isDefined(delay)) {
self.defer.now += delay;
} else {
if (self.deferredFns.length) {
self.defer.now = self.deferredFns[self.deferredFns.length - 1].time;
} else {
throw new Error('No deferred tasks to be flushed');
}
}
while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
self.deferredFns.shift().fn();
}
};
self.$$baseHref = '/';
self.baseHref = function () {
return this.$$baseHref;
};
};
angular.mock.$Browser.prototype = {
/**
* @name $browser#poll
*
* @description
* run all fns in pollFns
*/
poll: function poll() {
angular.forEach(this.pollFns, function (pollFn) {
pollFn();
});
},
addPollFn: function (pollFn) {
this.pollFns.push(pollFn);
return pollFn;
},
url: function (url, replace, state) {
if (angular.isUndefined(state)) {
state = null;
}
if (url) {
this.$$url = url;
// Native pushState serializes & copies the object; simulate it.
this.$$state = angular.copy(state);
return this;
}
return this.$$url;
},
state: function () {
return this.$$state;
},
cookies: function (name, value) {
if (name) {
if (angular.isUndefined(value)) {
delete this.cookieHash[name];
} else {
if (angular.isString(value) && //strings only
value.length <= 4096) { //strict cookie storage limits
this.cookieHash[name] = value;
}
}
} else {
if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
this.lastCookieHash = angular.copy(this.cookieHash);
this.cookieHash = angular.copy(this.cookieHash);
}
return this.cookieHash;
}
},
notifyWhenNoOutstandingRequests: function (fn) {
fn();
}
};
/**
* @ngdoc provider
* @name $exceptionHandlerProvider
*
* @description
* Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
* passed to the `$exceptionHandler`.
*/
/**
* @ngdoc service
* @name $exceptionHandler
*
* @description
* Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
* to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
* information.
*
*
* ```js
* describe('$exceptionHandlerProvider', function() {
*
* it('should capture log messages and exceptions', function() {
*
* module(function($exceptionHandlerProvider) {
* $exceptionHandlerProvider.mode('log');
* });
*
* inject(function($log, $exceptionHandler, $timeout) {
* $timeout(function() { $log.log(1); });
* $timeout(function() { $log.log(2); throw 'banana peel'; });
* $timeout(function() { $log.log(3); });
* expect($exceptionHandler.errors).toEqual([]);
* expect($log.assertEmpty());
* $timeout.flush();
* expect($exceptionHandler.errors).toEqual(['banana peel']);
* expect($log.log.logs).toEqual([[1], [2], [3]]);
* });
* });
* });
* ```
*/
angular.mock.$ExceptionHandlerProvider = function () {
var handler;
/**
* @ngdoc method
* @name $exceptionHandlerProvider#mode
*
* @description
* Sets the logging mode.
*
* @param {string} mode Mode of operation, defaults to `rethrow`.
*
* - `rethrow`: If any errors are passed to the handler in tests, it typically means that there
* is a bug in the application or test, so this mock will make these tests fail.
* - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`
* mode stores an array of errors in `$exceptionHandler.errors`, to allow later
* assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and
* {@link ngMock.$log#reset reset()}
*/
this.mode = function (mode) {
switch (mode) {
case 'rethrow':
handler = function (e) {
throw e;
};
break;
case 'log':
var errors = [];
handler = function (e) {
if (arguments.length == 1) {
errors.push(e);
} else {
errors.push([].slice.call(arguments, 0));
}
};
handler.errors = errors;
break;
default:
throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
}
};
this.$get = function () {
return handler;
};
this.mode('rethrow');
};
/**
* @ngdoc service
* @name $log
*
* @description
* Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
* (one array per logging level). These arrays are exposed as `logs` property of each of the
* level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
*
*/
angular.mock.$LogProvider = function () {
var debug = true;
function concat(array1, array2, index) {
return array1.concat(Array.prototype.slice.call(array2, index));
}
this.debugEnabled = function (flag) {
if (angular.isDefined(flag)) {
debug = flag;
return this;
} else {
return debug;
}
};
this.$get = function () {
var $log = {
log: function () { $log.log.logs.push(concat([], arguments, 0)); },
warn: function () { $log.warn.logs.push(concat([], arguments, 0)); },
info: function () { $log.info.logs.push(concat([], arguments, 0)); },
error: function () { $log.error.logs.push(concat([], arguments, 0)); },
debug: function () {
if (debug) {
$log.debug.logs.push(concat([], arguments, 0));
}
}
};
/**
* @ngdoc method
* @name $log#reset
*
* @description
* Reset all of the logging arrays to empty.
*/
$log.reset = function () {
/**
* @ngdoc property
* @name $log#log.logs
*
* @description
* Array of messages logged using {@link ng.$log#log `log()`}.
*
* @example
* ```js
* $log.log('Some Log');
* var first = $log.log.logs.unshift();
* ```
*/
$log.log.logs = [];
/**
* @ngdoc property
* @name $log#info.logs
*
* @description
* Array of messages logged using {@link ng.$log#info `info()`}.
*
* @example
* ```js
* $log.info('Some Info');
* var first = $log.info.logs.unshift();
* ```
*/
$log.info.logs = [];
/**
* @ngdoc property
* @name $log#warn.logs
*
* @description
* Array of messages logged using {@link ng.$log#warn `warn()`}.
*
* @example
* ```js
* $log.warn('Some Warning');
* var first = $log.warn.logs.unshift();
* ```
*/
$log.warn.logs = [];
/**
* @ngdoc property
* @name $log#error.logs
*
* @description
* Array of messages logged using {@link ng.$log#error `error()`}.
*
* @example
* ```js
* $log.error('Some Error');
* var first = $log.error.logs.unshift();
* ```
*/
$log.error.logs = [];
/**
* @ngdoc property
* @name $log#debug.logs
*
* @description
* Array of messages logged using {@link ng.$log#debug `debug()`}.
*
* @example
* ```js
* $log.debug('Some Error');
* var first = $log.debug.logs.unshift();
* ```
*/
$log.debug.logs = [];
};
/**
* @ngdoc method
* @name $log#assertEmpty
*
* @description
* Assert that all of the logging methods have no logged messages. If any messages are present,
* an exception is thrown.
*/
$log.assertEmpty = function () {
var errors = [];
angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function (logLevel) {
angular.forEach($log[logLevel].logs, function (log) {
angular.forEach(log, function (logItem) {
errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' +
(logItem.stack || ''));
});
});
});
if (errors.length) {
errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " +
"an expected log message was not checked and removed:");
errors.push('');
throw new Error(errors.join('\n---------\n'));
}
};
$log.reset();
return $log;
};
};
/**
* @ngdoc service
* @name $interval
*
* @description
* Mock implementation of the $interval service.
*
* Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
* move forward by `millis` milliseconds and trigger any functions scheduled to run in that
* time.
*
* @param {function()} fn A function that should be called repeatedly.
* @param {number} delay Number of milliseconds between each function call.
* @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
* indefinitely.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {promise} A promise which will be notified on each iteration.
*/
angular.mock.$IntervalProvider = function () {
this.$get = ['$rootScope', '$q',
function ($rootScope, $q) {
var repeatFns = [],
nextRepeatId = 0,
now = 0;
var $interval = function (fn, delay, count, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
iteration = 0,
skipApply = (angular.isDefined(invokeApply) && !invokeApply);
count = (angular.isDefined(count)) ? count : 0;
promise.then(null, null, fn);
promise.$$intervalId = nextRepeatId;
function tick() {
deferred.notify(iteration++);
if (count > 0 && iteration >= count) {
var fnIndex;
deferred.resolve(iteration);
angular.forEach(repeatFns, function (fn, index) {
if (fn.id === promise.$$intervalId) fnIndex = index;
});
if (fnIndex !== undefined) {
repeatFns.splice(fnIndex, 1);
}
}
if (!skipApply) $rootScope.$apply();
}
repeatFns.push({
nextTime: (now + delay),
delay: delay,
fn: tick,
id: nextRepeatId,
deferred: deferred
});
repeatFns.sort(function (a, b) { return a.nextTime - b.nextTime; });
nextRepeatId++;
return promise;
};
/**
* @ngdoc method
* @name $interval#cancel
*
* @description
* Cancels a task associated with the `promise`.
*
* @param {promise} promise A promise from calling the `$interval` function.
* @returns {boolean} Returns `true` if the task was successfully cancelled.
*/
$interval.cancel = function (promise) {
if (!promise) return false;
var fnIndex;
angular.forEach(repeatFns, function (fn, index) {
if (fn.id === promise.$$intervalId) fnIndex = index;
});
if (fnIndex !== undefined) {
repeatFns[fnIndex].deferred.reject('canceled');
repeatFns.splice(fnIndex, 1);
return true;
}
return false;
};
/**
* @ngdoc method
* @name $interval#flush
* @description
*
* Runs interval tasks scheduled to be run in the next `millis` milliseconds.
*
* @param {number=} millis maximum timeout amount to flush up until.
*
* @return {number} The amount of time moved forward.
*/
$interval.flush = function (millis) {
now += millis;
while (repeatFns.length && repeatFns[0].nextTime <= now) {
var task = repeatFns[0];
task.fn();
task.nextTime += task.delay;
repeatFns.sort(function (a, b) { return a.nextTime - b.nextTime; });
}
return millis;
};
return $interval;
}];
};
/* jshint -W101 */
/* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
* This directive should go inside the anonymous function but a bug in JSHint means that it would
* not be enacted early enough to prevent the warning.
*/
var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8061_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4] || 0) - tzHour,
int(match[5] || 0) - tzMin,
int(match[6] || 0),
int(match[7] || 0));
return date;
}
return string;
}
function int(str) {
return parseInt(str, 10);
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while (num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
/**
* @ngdoc type
* @name angular.mock.TzDate
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
*
* Mock of the Date type which has its timezone specified via constructor arg.
*
* The main purpose is to create Date-like instances with timezone fixed to the specified timezone
* offset, so that we can test code that depends on local timezone settings without dependency on
* the time zone settings of the machine where the code is running.
*
* @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
* @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
*
* @example
* !!!! WARNING !!!!!
* This is not a complete Date object so only methods that were implemented can be called safely.
* To make matters worse, TzDate instances inherit stuff from Date via a prototype.
*
* We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
* incomplete we might be missing some non-standard methods. This can result in errors like:
* "Date.prototype.foo called on incompatible Object".
*
* ```js
* var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
* newYearInBratislava.getTimezoneOffset() => -60;
* newYearInBratislava.getFullYear() => 2010;
* newYearInBratislava.getMonth() => 0;
* newYearInBratislava.getDate() => 1;
* newYearInBratislava.getHours() => 0;
* newYearInBratislava.getMinutes() => 0;
* newYearInBratislava.getSeconds() => 0;
* ```
*
*/
angular.mock.TzDate = function (offset, timestamp) {
var self = new Date(0);
if (angular.isString(timestamp)) {
var tsStr = timestamp;
self.origDate = jsonStringToDate(timestamp);
timestamp = self.origDate.getTime();
if (isNaN(timestamp))
throw {
name: "Illegal Argument",
message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
};
} else {
self.origDate = new Date(timestamp);
}
var localOffset = new Date(timestamp).getTimezoneOffset();
self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60;
self.date = new Date(timestamp + self.offsetDiff);
self.getTime = function () {
return self.date.getTime() - self.offsetDiff;
};
self.toLocaleDateString = function () {
return self.date.toLocaleDateString();
};
self.getFullYear = function () {
return self.date.getFullYear();
};
self.getMonth = function () {
return self.date.getMonth();
};
self.getDate = function () {
return self.date.getDate();
};
self.getHours = function () {
return self.date.getHours();
};
self.getMinutes = function () {
return self.date.getMinutes();
};
self.getSeconds = function () {
return self.date.getSeconds();
};
self.getMilliseconds = function () {
return self.date.getMilliseconds();
};
self.getTimezoneOffset = function () {
return offset * 60;
};
self.getUTCFullYear = function () {
return self.origDate.getUTCFullYear();
};
self.getUTCMonth = function () {
return self.origDate.getUTCMonth();
};
self.getUTCDate = function () {
return self.origDate.getUTCDate();
};
self.getUTCHours = function () {
return self.origDate.getUTCHours();
};
self.getUTCMinutes = function () {
return self.origDate.getUTCMinutes();
};
self.getUTCSeconds = function () {
return self.origDate.getUTCSeconds();
};
self.getUTCMilliseconds = function () {
return self.origDate.getUTCMilliseconds();
};
self.getDay = function () {
return self.date.getDay();
};
// provide this method only on browsers that already have it
if (self.toISOString) {
self.toISOString = function () {
return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
padNumber(self.origDate.getUTCDate(), 2) + 'T' +
padNumber(self.origDate.getUTCHours(), 2) + ':' +
padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';
};
}
//hide all methods not implemented in this mock that the Date prototype exposes
var unimplementedMethods = ['getUTCDay',
'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
angular.forEach(unimplementedMethods, function (methodName) {
self[methodName] = function () {
throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock");
};
});
return self;
};
//make "tzDateInstance instanceof Date" return true
angular.mock.TzDate.prototype = Date.prototype;
/* jshint +W101 */
angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
.config(['$provide', function ($provide) {
var reflowQueue = [];
$provide.value('$$animateReflow', function (fn) {
var index = reflowQueue.length;
reflowQueue.push(fn);
return function cancel() {
reflowQueue.splice(index, 1);
};
});
$provide.decorator('$animate', ['$delegate', '$$asyncCallback', '$timeout', '$browser',
function ($delegate, $$asyncCallback, $timeout, $browser) {
var animate = {
queue: [],
cancel: $delegate.cancel,
enabled: $delegate.enabled,
triggerCallbackEvents: function () {
$$asyncCallback.flush();
},
triggerCallbackPromise: function () {
$timeout.flush(0);
},
triggerCallbacks: function () {
this.triggerCallbackEvents();
this.triggerCallbackPromise();
},
triggerReflow: function () {
angular.forEach(reflowQueue, function (fn) {
fn();
});
reflowQueue = [];
}
};
angular.forEach(
['animate', 'enter', 'leave', 'move', 'addClass', 'removeClass', 'setClass'], function (method) {
animate[method] = function () {
animate.queue.push({
event: method,
element: arguments[0],
options: arguments[arguments.length - 1],
args: arguments
});
return $delegate[method].apply($delegate, arguments);
};
});
return animate;
}]);
}]);
/**
* @ngdoc function
* @name angular.mock.dump
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available function.
*
* Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
* debugging.
*
* This method is also available on window, where it can be used to display objects on debug
* console.
*
* @param {*} object - any object to turn into string.
* @return {string} a serialized string of the argument
*/
angular.mock.dump = function (object) {
return serialize(object);
function serialize(object) {
var out;
if (angular.isElement(object)) {
object = angular.element(object);
out = angular.element('<div></div>');
angular.forEach(object, function (element) {
out.append(angular.element(element).clone());
});
out = out.html();
} else if (angular.isArray(object)) {
out = [];
angular.forEach(object, function (o) {
out.push(serialize(o));
});
out = '[ ' + out.join(', ') + ' ]';
} else if (angular.isObject(object)) {
if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
out = serializeScope(object);
} else if (object instanceof Error) {
out = object.stack || ('' + object.name + ': ' + object.message);
} else {
// TODO(i): this prevents methods being logged,
// we should have a better way to serialize objects
out = angular.toJson(object, true);
}
} else {
out = String(object);
}
return out;
}
function serializeScope(scope, offset) {
offset = offset || ' ';
var log = [offset + 'Scope(' + scope.$id + '): {'];
for (var key in scope) {
if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) {
log.push(' ' + key + ': ' + angular.toJson(scope[key]));
}
}
var child = scope.$$childHead;
while (child) {
log.push(serializeScope(child, offset + ' '));
child = child.$$nextSibling;
}
log.push('}');
return log.join('\n' + offset);
}
};
/**
* @ngdoc service
* @name $httpBackend
* @description
* Fake HTTP backend implementation suitable for unit testing applications that use the
* {@link ng.$http $http service}.
*
* *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
* development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
*
* During unit testing, we want our unit tests to run quickly and have no external dependencies so
* we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or
* [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is
* to verify whether a certain request has been sent or not, or alternatively just let the
* application make requests, respond with pre-trained responses and assert that the end result is
* what we expect it to be.
*
* This mock implementation can be used to respond with static or dynamic responses via the
* `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
*
* When an Angular application needs some data from a server, it calls the $http service, which
* sends the request to a real server using $httpBackend service. With dependency injection, it is
* easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
* the requests and respond with some testing data without sending a request to a real server.
*
* There are two ways to specify what test data should be returned as http responses by the mock
* backend when the code under test makes http requests:
*
* - `$httpBackend.expect` - specifies a request expectation
* - `$httpBackend.when` - specifies a backend definition
*
*
* # Request Expectations vs Backend Definitions
*
* Request expectations provide a way to make assertions about requests made by the application and
* to define responses for those requests. The test will fail if the expected requests are not made
* or they are made in the wrong order.
*
* Backend definitions allow you to define a fake backend for your application which doesn't assert
* if a particular request was made or not, it just returns a trained response if a request is made.
* The test will pass whether or not the request gets made during testing.
*
*
* <table class="table">
* <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
* <tr>
* <th>Syntax</th>
* <td>.expect(...).respond(...)</td>
* <td>.when(...).respond(...)</td>
* </tr>
* <tr>
* <th>Typical usage</th>
* <td>strict unit tests</td>
* <td>loose (black-box) unit testing</td>
* </tr>
* <tr>
* <th>Fulfills multiple requests</th>
* <td>NO</td>
* <td>YES</td>
* </tr>
* <tr>
* <th>Order of requests matters</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Request required</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Response required</th>
* <td>optional (see below)</td>
* <td>YES</td>
* </tr>
* </table>
*
* In cases where both backend definitions and request expectations are specified during unit
* testing, the request expectations are evaluated first.
*
* If a request expectation has no response specified, the algorithm will search your backend
* definitions for an appropriate response.
*
* If a request didn't match any expectation or if the expectation doesn't have the response
* defined, the backend definitions are evaluated in sequential order to see if any of them match
* the request. The response from the first matched definition is returned.
*
*
* # Flushing HTTP requests
*
* The $httpBackend used in production always responds to requests asynchronously. If we preserved
* this behavior in unit testing, we'd have to create async unit tests, which are hard to write,
* to follow and to maintain. But neither can the testing mock respond synchronously; that would
* change the execution of the code under test. For this reason, the mock $httpBackend has a
* `flush()` method, which allows the test to explicitly flush pending requests. This preserves
* the async api of the backend, while allowing the test to execute synchronously.
*
*
* # Unit testing with mock $httpBackend
* The following code shows how to setup and use the mock backend when unit testing a controller.
* First we create the controller under test:
*
```js
// The module code
angular
.module('MyApp', [])
.controller('MyController', MyController);
// The controller code
function MyController($scope, $http) {
var authToken;
$http.get('/auth.py').success(function(data, status, headers) {
authToken = headers('A-Token');
$scope.user = data;
});
$scope.saveMessage = function(message) {
var headers = { 'Authorization': authToken };
$scope.status = 'Saving...';
$http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
$scope.status = '';
}).error(function() {
$scope.status = 'ERROR!';
});
};
}
```
*
* Now we setup the mock backend and create the test specs:
*
```js
// testing controller
describe('MyController', function() {
var $httpBackend, $rootScope, createController, authRequestHandler;
// Set up the module
beforeEach(module('MyApp'));
beforeEach(inject(function($injector) {
// Set up the mock http service responses
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
authRequestHandler = $httpBackend.when('GET', '/auth.py')
.respond({userId: 'userX'}, {'A-Token': 'xxx'});
// Get hold of a scope (i.e. the root scope)
$rootScope = $injector.get('$rootScope');
// The $controller service is used to create instances of controllers
var $controller = $injector.get('$controller');
createController = function() {
return $controller('MyController', {'$scope' : $rootScope });
};
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch authentication token', function() {
$httpBackend.expectGET('/auth.py');
var controller = createController();
$httpBackend.flush();
});
it('should fail authentication', function() {
// Notice how you can change the response even after it was set
authRequestHandler.respond(401, '');
$httpBackend.expectGET('/auth.py');
var controller = createController();
$httpBackend.flush();
expect($rootScope.status).toBe('Failed...');
});
it('should send msg to server', function() {
var controller = createController();
$httpBackend.flush();
// now you don’t care about the authentication, but
// the controller will still send the request and
// $httpBackend will respond without you having to
// specify the expectation and response for this request
$httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
$rootScope.saveMessage('message content');
expect($rootScope.status).toBe('Saving...');
$httpBackend.flush();
expect($rootScope.status).toBe('');
});
it('should send auth header', function() {
var controller = createController();
$httpBackend.flush();
$httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
// check if the header was send, if it wasn't the expectation won't
// match the request and the test will fail
return headers['Authorization'] == 'xxx';
}).respond(201, '');
$rootScope.saveMessage('whatever');
$httpBackend.flush();
});
});
```
*/
angular.mock.$HttpBackendProvider = function () {
this.$get = ['$rootScope', createHttpBackendMock];
};
/**
* General factory function for $httpBackend mock.
* Returns instance for unit testing (when no arguments specified):
* - passing through is disabled
* - auto flushing is disabled
*
* Returns instance for e2e testing (when `$delegate` and `$browser` specified):
* - passing through (delegating request to real backend) is enabled
* - auto flushing is enabled
*
* @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
* @param {Object=} $browser Auto-flushing enabled if specified
* @return {Object} Instance of $httpBackend mock
*/
function createHttpBackendMock($rootScope, $delegate, $browser) {
var definitions = [],
expectations = [],
responses = [],
responsesPush = angular.bind(responses, responses.push),
copy = angular.copy;
function createResponse(status, data, headers, statusText) {
if (angular.isFunction(status)) return status;
return function () {
return angular.isNumber(status)
? [status, data, headers, statusText]
: [200, status, data];
};
}
// TODO(vojta): change params to: method, url, data, headers, callback
function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {
var xhr = new MockXhr(),
expectation = expectations[0],
wasExpected = false;
function prettyPrint(data) {
return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
? data
: angular.toJson(data);
}
function wrapResponse(wrapped) {
if (!$browser && timeout && timeout.then) timeout.then(handleTimeout);
return handleResponse;
function handleResponse() {
var response = wrapped.response(method, url, data, headers);
xhr.$$respHeaders = response[2];
callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
copy(response[3] || ''));
}
function handleTimeout() {
for (var i = 0, ii = responses.length; i < ii; i++) {
if (responses[i] === handleResponse) {
responses.splice(i, 1);
callback(-1, undefined, '');
break;
}
}
}
}
if (expectation && expectation.match(method, url)) {
if (!expectation.matchData(data))
throw new Error('Expected ' + expectation + ' with different data\n' +
'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
if (!expectation.matchHeaders(headers))
throw new Error('Expected ' + expectation + ' with different headers\n' +
'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
prettyPrint(headers));
expectations.shift();
if (expectation.response) {
responses.push(wrapResponse(expectation));
return;
}
wasExpected = true;
}
var i = -1, definition;
while ((definition = definitions[++i])) {
if (definition.match(method, url, data, headers || {})) {
if (definition.response) {
// if $browser specified, we do auto flush all requests
($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
} else if (definition.passThrough) {
$delegate(method, url, data, callback, headers, timeout, withCredentials);
} else throw new Error('No response defined !');
return;
}
}
throw wasExpected ?
new Error('No response defined !') :
new Error('Unexpected request: ' + method + ' ' + url + '\n' +
(expectation ? 'Expected ' + expectation : 'No more request expected'));
}
/**
* @ngdoc method
* @name $httpBackend#when
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
* data string and returns true if the data is as expected.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*
* - respond –
* `{function([status,] data[, headers, statusText])
* | function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can
* return an array containing response status (number), response data (string), response
* headers (Object), and the text for the status (string). The respond method returns the
* `requestHandler` object for possible overrides.
*/
$httpBackend.when = function (method, url, data, headers) {
var definition = new MockHttpExpectation(method, url, data, headers),
chain = {
respond: function (status, data, headers, statusText) {
definition.passThrough = undefined;
definition.response = createResponse(status, data, headers, statusText);
return chain;
}
};
if ($browser) {
chain.passThrough = function () {
definition.response = undefined;
definition.passThrough = true;
return chain;
};
}
definitions.push(definition);
return chain;
};
/**
* @ngdoc method
* @name $httpBackend#whenGET
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenHEAD
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenDELETE
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPOST
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
* data string and returns true if the data is as expected.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPUT
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
* data string and returns true if the data is as expected.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenJSONP
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
createShortMethods('when');
/**
* @ngdoc method
* @name $httpBackend#expect
* @description
* Creates a new request expectation.
*
* @param {string} method HTTP method.
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
* receives data string and returns true if the data is as expected, or Object if request body
* is in JSON format.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current expectation.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*
* - respond –
* `{function([status,] data[, headers, statusText])
* | function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can
* return an array containing response status (number), response data (string), response
* headers (Object), and the text for the status (string). The respond method returns the
* `requestHandler` object for possible overrides.
*/
$httpBackend.expect = function (method, url, data, headers) {
var expectation = new MockHttpExpectation(method, url, data, headers),
chain = {
respond: function (status, data, headers, statusText) {
expectation.response = createResponse(status, data, headers, statusText);
return chain;
}
};
expectations.push(expectation);
return chain;
};
/**
* @ngdoc method
* @name $httpBackend#expectGET
* @description
* Creates a new request expectation for GET requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled. See #expect for more info.
*/
/**
* @ngdoc method
* @name $httpBackend#expectHEAD
* @description
* Creates a new request expectation for HEAD requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectDELETE
* @description
* Creates a new request expectation for DELETE requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectPOST
* @description
* Creates a new request expectation for POST requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
* receives data string and returns true if the data is as expected, or Object if request body
* is in JSON format.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectPUT
* @description
* Creates a new request expectation for PUT requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
* receives data string and returns true if the data is as expected, or Object if request body
* is in JSON format.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectPATCH
* @description
* Creates a new request expectation for PATCH requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
* receives data string and returns true if the data is as expected, or Object if request body
* is in JSON format.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectJSONP
* @description
* Creates a new request expectation for JSONP requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
createShortMethods('expect');
/**
* @ngdoc method
* @name $httpBackend#flush
* @description
* Flushes all pending requests using the trained responses.
*
* @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
* all pending requests will be flushed. If there are no pending requests when the flush method
* is called an exception is thrown (as this typically a sign of programming error).
*/
$httpBackend.flush = function (count, digest) {
if (digest !== false) $rootScope.$digest();
if (!responses.length) throw new Error('No pending request to flush !');
if (angular.isDefined(count) && count !== null) {
while (count--) {
if (!responses.length) throw new Error('No more pending request to flush !');
responses.shift()();
}
} else {
while (responses.length) {
responses.shift()();
}
}
$httpBackend.verifyNoOutstandingExpectation(digest);
};
/**
* @ngdoc method
* @name $httpBackend#verifyNoOutstandingExpectation
* @description
* Verifies that all of the requests defined via the `expect` api were made. If any of the
* requests were not made, verifyNoOutstandingExpectation throws an exception.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* ```js
* afterEach($httpBackend.verifyNoOutstandingExpectation);
* ```
*/
$httpBackend.verifyNoOutstandingExpectation = function (digest) {
if (digest !== false) $rootScope.$digest();
if (expectations.length) {
throw new Error('Unsatisfied requests: ' + expectations.join(', '));
}
};
/**
* @ngdoc method
* @name $httpBackend#verifyNoOutstandingRequest
* @description
* Verifies that there are no outstanding requests that need to be flushed.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* ```js
* afterEach($httpBackend.verifyNoOutstandingRequest);
* ```
*/
$httpBackend.verifyNoOutstandingRequest = function () {
if (responses.length) {
throw new Error('Unflushed requests: ' + responses.length);
}
};
/**
* @ngdoc method
* @name $httpBackend#resetExpectations
* @description
* Resets all request expectations, but preserves all backend definitions. Typically, you would
* call resetExpectations during a multiple-phase test when you want to reuse the same instance of
* $httpBackend mock.
*/
$httpBackend.resetExpectations = function () {
expectations.length = 0;
responses.length = 0;
};
return $httpBackend;
function createShortMethods(prefix) {
angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function (method) {
$httpBackend[prefix + method] = function (url, headers) {
return $httpBackend[prefix](method, url, undefined, headers);
};
});
angular.forEach(['PUT', 'POST', 'PATCH'], function (method) {
$httpBackend[prefix + method] = function (url, data, headers) {
return $httpBackend[prefix](method, url, data, headers);
};
});
}
}
function MockHttpExpectation(method, url, data, headers) {
this.data = data;
this.headers = headers;
this.match = function (m, u, d, h) {
if (method != m) return false;
if (!this.matchUrl(u)) return false;
if (angular.isDefined(d) && !this.matchData(d)) return false;
if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
return true;
};
this.matchUrl = function (u) {
if (!url) return true;
if (angular.isFunction(url.test)) return url.test(u);
if (angular.isFunction(url)) return url(u);
return url == u;
};
this.matchHeaders = function (h) {
if (angular.isUndefined(headers)) return true;
if (angular.isFunction(headers)) return headers(h);
return angular.equals(headers, h);
};
this.matchData = function (d) {
if (angular.isUndefined(data)) return true;
if (data && angular.isFunction(data.test)) return data.test(d);
if (data && angular.isFunction(data)) return data(d);
if (data && !angular.isString(data)) return angular.equals(data, angular.fromJson(d));
return data == d;
};
this.toString = function () {
return method + ' ' + url;
};
}
function createMockXhr() {
return new MockXhr();
}
function MockXhr() {
// hack for testing $http, $httpBackend
MockXhr.$$lastInstance = this;
this.open = function (method, url, async) {
this.$$method = method;
this.$$url = url;
this.$$async = async;
this.$$reqHeaders = {};
this.$$respHeaders = {};
};
this.send = function (data) {
this.$$data = data;
};
this.setRequestHeader = function (key, value) {
this.$$reqHeaders[key] = value;
};
this.getResponseHeader = function (name) {
// the lookup must be case insensitive,
// that's why we try two quick lookups first and full scan last
var header = this.$$respHeaders[name];
if (header) return header;
name = angular.lowercase(name);
header = this.$$respHeaders[name];
if (header) return header;
header = undefined;
angular.forEach(this.$$respHeaders, function (headerVal, headerName) {
if (!header && angular.lowercase(headerName) == name) header = headerVal;
});
return header;
};
this.getAllResponseHeaders = function () {
var lines = [];
angular.forEach(this.$$respHeaders, function (value, key) {
lines.push(key + ': ' + value);
});
return lines.join('\n');
};
this.abort = angular.noop;
}
/**
* @ngdoc service
* @name $timeout
* @description
*
* This service is just a simple decorator for {@link ng.$timeout $timeout} service
* that adds a "flush" and "verifyNoPendingTasks" methods.
*/
angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function ($delegate, $browser) {
/**
* @ngdoc method
* @name $timeout#flush
* @description
*
* Flushes the queue of pending tasks.
*
* @param {number=} delay maximum timeout amount to flush up until
*/
$delegate.flush = function (delay) {
$browser.defer.flush(delay);
};
/**
* @ngdoc method
* @name $timeout#verifyNoPendingTasks
* @description
*
* Verifies that there are no pending tasks that need to be flushed.
*/
$delegate.verifyNoPendingTasks = function () {
if ($browser.deferredFns.length) {
throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
formatPendingTasksAsString($browser.deferredFns));
}
};
function formatPendingTasksAsString(tasks) {
var result = [];
angular.forEach(tasks, function (task) {
result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
});
return result.join(', ');
}
return $delegate;
}];
angular.mock.$RAFDecorator = ['$delegate', function ($delegate) {
var queue = [];
var rafFn = function (fn) {
var index = queue.length;
queue.push(fn);
return function () {
queue.splice(index, 1);
};
};
rafFn.supported = $delegate.supported;
rafFn.flush = function () {
if (queue.length === 0) {
throw new Error('No rAF callbacks present');
}
var length = queue.length;
for (var i = 0; i < length; i++) {
queue[i]();
}
queue = [];
};
return rafFn;
}];
angular.mock.$AsyncCallbackDecorator = ['$delegate', function ($delegate) {
var callbacks = [];
var addFn = function (fn) {
callbacks.push(fn);
};
addFn.flush = function () {
angular.forEach(callbacks, function (fn) {
fn();
});
callbacks = [];
};
return addFn;
}];
/**
*
*/
angular.mock.$RootElementProvider = function () {
this.$get = function () {
return angular.element('<div ng-app></div>');
};
};
/**
* @ngdoc module
* @name ngMock
* @packageName angular-mocks
* @description
*
* # ngMock
*
* The `ngMock` module provides support to inject and mock Angular services into unit tests.
* In addition, ngMock also extends various core ng services such that they can be
* inspected and controlled in a synchronous manner within test code.
*
*
* <div doc-module-components="ngMock"></div>
*
*/
angular.module('ngMock', ['ng']).provider({
$browser: angular.mock.$BrowserProvider,
$exceptionHandler: angular.mock.$ExceptionHandlerProvider,
$log: angular.mock.$LogProvider,
$interval: angular.mock.$IntervalProvider,
$httpBackend: angular.mock.$HttpBackendProvider,
$rootElement: angular.mock.$RootElementProvider
}).config(['$provide', function ($provide) {
$provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
$provide.decorator('$$rAF', angular.mock.$RAFDecorator);
$provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator);
}]);
/**
* @ngdoc module
* @name ngMockE2E
* @module ngMockE2E
* @packageName angular-mocks
* @description
*
* The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
* Currently there is only one mock present in this module -
* the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
*/
angular.module('ngMockE2E', ['ng']).config(['$provide', function ($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
}]);
/**
* @ngdoc service
* @name $httpBackend
* @module ngMockE2E
* @description
* Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
* applications that use the {@link ng.$http $http service}.
*
* *Note*: For fake http backend implementation suitable for unit testing please see
* {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
*
* This implementation can be used to respond with static or dynamic responses via the `when` api
* and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
* real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
* templates from a webserver).
*
* As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
* is being developed with the real backend api replaced with a mock, it is often desirable for
* certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
* templates or static files from the webserver). To configure the backend with this behavior
* use the `passThrough` request handler of `when` instead of `respond`.
*
* Additionally, we don't want to manually have to flush mocked out requests like we do during unit
* testing. For this reason the e2e $httpBackend flushes mocked out requests
* automatically, closely simulating the behavior of the XMLHttpRequest object.
*
* To setup the application to run with this http backend, you have to create a module that depends
* on the `ngMockE2E` and your application modules and defines the fake backend:
*
* ```js
* myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
* myAppDev.run(function($httpBackend) {
* phones = [{name: 'phone1'}, {name: 'phone2'}];
*
* // returns the current list of phones
* $httpBackend.whenGET('/phones').respond(phones);
*
* // adds a new phone to the phones array
* $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
* var phone = angular.fromJson(data);
* phones.push(phone);
* return [200, phone, {}];
* });
* $httpBackend.whenGET(/^\/templates\//).passThrough();
* //...
* });
* ```
*
* Afterwards, bootstrap your app with this new module.
*/
/**
* @ngdoc method
* @name $httpBackend#when
* @module ngMockE2E
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*
* - respond –
* `{function([status,] data[, headers, statusText])
* | function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string), response headers
* (Object), and the text for the status (string).
* - passThrough – `{function()}` – Any request matching a backend definition with
* `passThrough` handler will be passed through to the real backend (an XHR request will be made
* to the server.)
* - Both methods return the `requestHandler` object for possible overrides.
*/
/**
* @ngdoc method
* @name $httpBackend#whenGET
* @module ngMockE2E
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenHEAD
* @module ngMockE2E
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenDELETE
* @module ngMockE2E
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPOST
* @module ngMockE2E
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPUT
* @module ngMockE2E
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPATCH
* @module ngMockE2E
* @description
* Creates a new backend definition for PATCH requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenJSONP
* @module ngMockE2E
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
angular.mock.e2e = {};
angular.mock.e2e.$httpBackendDecorator =
['$rootScope', '$delegate', '$browser', createHttpBackendMock];
if (window.jasmine || window.mocha) {
var currentSpec = null,
isSpecRunning = function () {
return !!currentSpec;
};
(window.beforeEach || window.setup)(function () {
currentSpec = this;
});
(window.afterEach || window.teardown)(function () {
var injector = currentSpec.$injector;
angular.forEach(currentSpec.$modules, function (module) {
if (module && module.$$hashKey) {
module.$$hashKey = undefined;
}
});
currentSpec.$injector = null;
currentSpec.$modules = null;
currentSpec = null;
if (injector) {
injector.get('$rootElement').off();
injector.get('$browser').pollFns.length = 0;
}
// clean up jquery's fragment cache
angular.forEach(angular.element.fragments, function (val, key) {
delete angular.element.fragments[key];
});
MockXhr.$$lastInstance = null;
angular.forEach(angular.callbacks, function (val, key) {
delete angular.callbacks[key];
});
angular.callbacks.counter = 0;
});
/**
* @ngdoc function
* @name angular.mock.module
* @description
*
* *NOTE*: This function is also published on window for easy access.<br>
* *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
*
* This function registers a module configuration code. It collects the configuration information
* which will be used when the injector is created by {@link angular.mock.inject inject}.
*
* See {@link angular.mock.inject inject} for usage example
*
* @param {...(string|Function|Object)} fns any number of modules which are represented as string
* aliases or as anonymous module initialization functions. The modules are used to
* configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
* object literal is passed they will be registered as values in the module, the key being
* the module name and the value being what is returned.
*/
window.module = angular.mock.module = function () {
var moduleFns = Array.prototype.slice.call(arguments, 0);
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
if (currentSpec.$injector) {
throw new Error('Injector already created, can not register a module!');
} else {
var modules = currentSpec.$modules || (currentSpec.$modules = []);
angular.forEach(moduleFns, function (module) {
if (angular.isObject(module) && !angular.isArray(module)) {
modules.push(function ($provide) {
angular.forEach(module, function (value, key) {
$provide.value(key, value);
});
});
} else {
modules.push(module);
}
});
}
}
};
/**
* @ngdoc function
* @name angular.mock.inject
* @description
*
* *NOTE*: This function is also published on window for easy access.<br>
* *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
*
* The inject function wraps a function into an injectable function. The inject() creates new
* instance of {@link auto.$injector $injector} per test, which is then used for
* resolving references.
*
*
* ## Resolving References (Underscore Wrapping)
* Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
* in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
* that is declared in the scope of the `describe()` block. Since we would, most likely, want
* the variable to have the same name of the reference we have a problem, since the parameter
* to the `inject()` function would hide the outer variable.
*
* To help with this, the injected parameters can, optionally, be enclosed with underscores.
* These are ignored by the injector when the reference name is resolved.
*
* For example, the parameter `_myService_` would be resolved as the reference `myService`.
* Since it is available in the function body as _myService_, we can then assign it to a variable
* defined in an outer scope.
*
* ```
* // Defined out reference variable outside
* var myService;
*
* // Wrap the parameter in underscores
* beforeEach( inject( function(_myService_){
* myService = _myService_;
* }));
*
* // Use myService in a series of tests.
* it('makes use of myService', function() {
* myService.doStuff();
* });
*
* ```
*
* See also {@link angular.mock.module angular.mock.module}
*
* ## Example
* Example of what a typical jasmine tests looks like with the inject method.
* ```js
*
* angular.module('myApplicationModule', [])
* .value('mode', 'app')
* .value('version', 'v1.0.1');
*
*
* describe('MyApp', function() {
*
* // You need to load modules that you want to test,
* // it loads only the "ng" module by default.
* beforeEach(module('myApplicationModule'));
*
*
* // inject() is used to inject arguments of all given functions
* it('should provide a version', inject(function(mode, version) {
* expect(version).toEqual('v1.0.1');
* expect(mode).toEqual('app');
* }));
*
*
* // The inject and module method can also be used inside of the it or beforeEach
* it('should override a version and test the new version is injected', function() {
* // module() takes functions or strings (module aliases)
* module(function($provide) {
* $provide.value('version', 'overridden'); // override version here
* });
*
* inject(function(version) {
* expect(version).toEqual('overridden');
* });
* });
* });
*
* ```
*
* @param {...Function} fns any number of functions which will be injected using the injector.
*/
var ErrorAddingDeclarationLocationStack = function (e, errorForStack) {
this.message = e.message;
this.name = e.name;
if (e.line) this.line = e.line;
if (e.sourceId) this.sourceId = e.sourceId;
if (e.stack && errorForStack)
this.stack = e.stack + '\n' + errorForStack.stack;
if (e.stackArray) this.stackArray = e.stackArray;
};
ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
window.inject = angular.mock.inject = function () {
var blockFns = Array.prototype.slice.call(arguments, 0);
var errorForStack = new Error('Declaration Location');
return isSpecRunning() ? workFn.call(currentSpec) : workFn;
/////////////////////
function workFn() {
var modules = currentSpec.$modules || [];
var strictDi = !!currentSpec.$injectorStrict;
modules.unshift('ngMock');
modules.unshift('ng');
var injector = currentSpec.$injector;
if (!injector) {
if (strictDi) {
// If strictDi is enabled, annotate the providerInjector blocks
angular.forEach(modules, function (moduleFn) {
if (typeof moduleFn === "function") {
angular.injector.$$annotate(moduleFn);
}
});
}
injector = currentSpec.$injector = angular.injector(modules, strictDi);
currentSpec.$injectorStrict = strictDi;
}
for (var i = 0, ii = blockFns.length; i < ii; i++) {
if (currentSpec.$injectorStrict) {
// If the injector is strict / strictDi, and the spec wants to inject using automatic
// annotation, then annotate the function here.
injector.annotate(blockFns[i]);
}
try {
/* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
injector.invoke(blockFns[i] || angular.noop, this);
/* jshint +W040 */
} catch (e) {
if (e.stack && errorForStack) {
throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
}
throw e;
} finally {
errorForStack = null;
}
}
}
};
angular.mock.inject.strictDi = function (value) {
value = arguments.length ? !!value : true;
return isSpecRunning() ? workFn() : workFn;
function workFn() {
if (value !== currentSpec.$injectorStrict) {
if (currentSpec.$injector) {
throw new Error('Injector already created, can not modify strict annotations');
} else {
currentSpec.$injectorStrict = value;
}
}
}
};
}
})(window, window.angular); | mit |
capesean/codegenerator | codegenerator/Models/Settings.cs | 2143 | using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Configuration;
using System.Linq;
namespace WEB.Models
{
public class Settings
{
[Key]
public int SettingsId { get; set; }
[NotMapped]
public string SiteName { get; set; }
[NotMapped]
public string RootUrl { get; set; }
[NotMapped]
public string EmailFromAddress { get; set; }
[NotMapped]
public string EmailFromName { get; set; }
[NotMapped]
public string EmailToErrors { get; set; }
[NotMapped]
public string EmailPassword { get; set; }
[NotMapped]
public int EmailPort { get; set; }
[NotMapped]
public string EmailSMTP { get; set; }
[NotMapped]
public bool EmailSSL { get; set; }
[NotMapped]
public string EmailUserName { get; set; }
[NotMapped]
public string SubstitutionAddress { get; set; }
public Settings() { }
public Settings(ApplicationDbContext dbContext)
{
var settings = dbContext.Settings.Single();
SettingsId = settings.SettingsId;
SiteName = ConfigurationManager.AppSettings["SiteName"];
RootUrl = ConfigurationManager.AppSettings["RootUrl"];
EmailFromAddress = ConfigurationManager.AppSettings["Email:FromAddress"];
EmailFromName = ConfigurationManager.AppSettings["Email:FromName"];
EmailToErrors = ConfigurationManager.AppSettings["Email:ToErrors"];
EmailSMTP = ConfigurationManager.AppSettings["Email:SMTP"];
EmailPort = Convert.ToInt32(ConfigurationManager.AppSettings["Email:Port"]);
EmailPassword = ConfigurationManager.AppSettings["Email:Password"];
EmailUserName = ConfigurationManager.AppSettings["Email:UserName"];
EmailSSL = Convert.ToBoolean(ConfigurationManager.AppSettings["Email:SSL"]);
SubstitutionAddress = ConfigurationManager.AppSettings["Email:SubstitutionAddress"];
}
}
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/vis/0.7.4/vis.min.js | 131 | version https://git-lfs.github.com/spec/v1
oid sha256:c7a5c0cb2d2bb3e59e7454df3561b8720a1f48230afed426fb4a996838227f02
size 270184
| mit |
yltsrc/warder | spec/fixtures/valid_rails_app/config/environment.rb | 151 | # Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Valid::Application.initialize!
| mit |
Roberto95/NURCON | NURCON/WebApp/formulario/Usuarios.aspx.cs | 1557 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApp
{
public partial class Usuarios : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (BusinessLogicLayer.AdministradorBLL.siHayDatos())
{
if (BusinessLogicLayer.AdministradorBLL.iniciarSesionUs(txtUser.Text) && BusinessLogicLayer.AdministradorBLL.iniciarSesionPass(txtPassword.Text))
{
Response.Redirect("inicio.aspx");
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Usuario o contraseña incorrectos');</script>");
//MessageBox.Show("Usuario o contraseña incorrectos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
if (txtUser.Text == "admin" && txtPassword.Text == "admin")
{
Response.Redirect("cambiarDatos.aspx");
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Usuario o contraseña incorrectos');</script>");
}
}
}
}
}
| mit |
ninianne98/CarrotCakeCMS | PluginEventCalendarModule/CalendarAdminCategoryList.ascx.cs | 667 | using System;
using System.Collections.Generic;
using System.Linq;
using Carrotware.CMS.Interface;
/*
* CarrotCake CMS - Event Calendar
* http://www.carrotware.com/
*
* Copyright 2013, Samantha Copeland
* Dual licensed under the MIT or GPL Version 3 licenses.
*
* Date: June 2013
*/
namespace Carrotware.CMS.UI.Plugins.EventCalendarModule {
public partial class CalendarAdminCategoryList : AdminModule {
protected void Page_Load(object sender, EventArgs e) {
LoadData();
}
protected void LoadData() {
var lst = CalendarHelper.GetCalendarCategories(SiteID);
CalendarHelper.BindDataBoundControl(dgMenu, lst);
}
}
} | mit |
Azure/azure-sdk-for-net | sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/Models/GremlinGraphData.Serialization.cs | 5110 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.CosmosDB.Models;
using Azure.ResourceManager.Models;
namespace Azure.ResourceManager.CosmosDB
{
public partial class GremlinGraphData : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("tags");
writer.WriteStartObject();
foreach (var item in Tags)
{
writer.WritePropertyName(item.Key);
writer.WriteStringValue(item.Value);
}
writer.WriteEndObject();
writer.WritePropertyName("location");
writer.WriteStringValue(Location);
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(Resource))
{
writer.WritePropertyName("resource");
writer.WriteObjectValue(Resource);
}
if (Optional.IsDefined(Options))
{
writer.WritePropertyName("options");
writer.WriteObjectValue(Options);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static GremlinGraphData DeserializeGremlinGraphData(JsonElement element)
{
IDictionary<string, string> tags = default;
AzureLocation location = default;
ResourceIdentifier id = default;
string name = default;
ResourceType type = default;
SystemData systemData = default;
Optional<GremlinGraphPropertiesResource> resource = default;
Optional<GremlinGraphPropertiesOptions> options = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("tags"))
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (var property0 in property.Value.EnumerateObject())
{
dictionary.Add(property0.Name, property0.Value.GetString());
}
tags = dictionary;
continue;
}
if (property.NameEquals("location"))
{
location = property.Value.GetString();
continue;
}
if (property.NameEquals("id"))
{
id = new ResourceIdentifier(property.Value.GetString());
continue;
}
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("systemData"))
{
systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("resource"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
resource = GremlinGraphPropertiesResource.DeserializeGremlinGraphPropertiesResource(property0.Value);
continue;
}
if (property0.NameEquals("options"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
options = GremlinGraphPropertiesOptions.DeserializeGremlinGraphPropertiesOptions(property0.Value);
continue;
}
}
continue;
}
}
return new GremlinGraphData(id, name, type, systemData, tags, location, resource.Value, options.Value);
}
}
}
| mit |
peidachang/jforth-sf | src/main/java/org/xforth/sf/netty/Initializer/BaseInitializer.java | 732 | package org.xforth.sf.netty.Initializer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
/**
* Base initializer
* impl of ApplicationContextAware or lookup
*
* 可以统计流量和日志
*/
public abstract class BaseInitializer extends ChannelInitializer {
@Override
public void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//这里可以统计流量和日志
addCodecHandler(pipeline);
addBusinessHandler(pipeline);
}
protected abstract void addCodecHandler(ChannelPipeline pipeline);
protected abstract void addBusinessHandler(ChannelPipeline pipeline);
}
| mit |
trianglman/sqrl | examples/server/web/index.php | 2726 | <?php
/*
* The MIT License
*
* Copyright 2014 johnj.
*
* 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.
*/
namespace sqrlexample;
require_once(__DIR__.'/../vendor/autoload.php');
require_once(__DIR__.'/../includes/ExampleStatefulStorage.php');
session_start();
//configuration stuff
$config = new \Trianglman\Sqrl\SqrlConfiguration();
$config->load(__DIR__.'/../config/sqrlconfig.json');
$store = new ExampleStatefulStorage(new \PDO('mysql:host=localhost;dbname=sqrl', 'example', 'bar'),$_SERVER['REMOTE_ADDR'],$_SESSION);
$generator = new \Trianglman\Sqrl\SqrlGenerate($config,$store);
$nonce = $generator->getNonce();
$sqrlUrl = $generator->getUrl();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SQRL Example Server</title>
</head>
<body>
<h1>Welcome to the SQRL PHP Example Server</h1>
<p>
This server should enable you to walk through a number of test scenarios using the SQRL protocol.
</p>
<p>
Please use the below link/QR code to sign in and either create a new account or view your already entered account information.
</p>
<p style="text-align: center;">
<a href="<?php echo $sqrlUrl;?>">
<img src="sqrlImg.php" title="Click or scan to log in" alt="SQRL QR Code" />
</a><br />
<a href="<?php echo $sqrlUrl;?>"><?php echo $sqrlUrl;?></a><br />
<a href="/login/isNonceValidated.php">Verify Login</a><!-- This should also be automated with JavaScript for a smoother UX-->
</p>
</body>
</html>
| mit |
shellchine/fepack | server/public/goconf.js | 327 | var goConf = {
groups: [
{
type: "common",
name: "常规项目",
label: "请选择后端团队",
list: {
'0' : '内部测试(不同步到后端)',
'1' : '192.168.171.4',
'2' : '192.168.171.7'
}
}]
}
| mit |
GridProtectionAlliance/openHistorian | Source/Applications/openHistorian/openHistorian/Grafana/public/app/types/plugins.ts | 914 | import { PluginError, PluginMeta } from '@grafana/data';
import { PanelPlugin } from '@grafana/data';
import { TemplateSrv } from '@grafana/runtime';
export interface PluginDashboard {
dashboardId: number;
description: string;
folderId: number;
imported: boolean;
importedRevision: number;
importedUri: string;
importedUrl: string;
path: string;
pluginId: string;
removed: boolean;
revision: number;
slug: string;
title: string;
}
export interface PanelPluginsIndex {
[id: string]: PanelPlugin;
}
export interface PluginsState {
plugins: PluginMeta[];
errors: PluginError[];
searchQuery: string;
hasFetched: boolean;
dashboards: PluginDashboard[];
isLoadingPluginDashboards: boolean;
panels: PanelPluginsIndex;
}
export interface VariableQueryProps {
query: any;
onChange: (query: any, definition: string) => void;
datasource: any;
templateSrv: TemplateSrv;
}
| mit |
SpongePowered/Sponge | src/main/java/org/spongepowered/common/data/provider/block/state/StainedGlassBlockData.java | 2059 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) 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.
*/
package org.spongepowered.common.data.provider.block.state;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.StainedGlassBlock;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.data.type.DyeColor;
import org.spongepowered.common.data.provider.DataProviderRegistrator;
public final class StainedGlassBlockData {
private StainedGlassBlockData() {
}
// @formatter:off
public static void register(final DataProviderRegistrator registrator) {
registrator
.asImmutable(Block.class)
.create(Keys.DYE_COLOR)
.get(h -> (DyeColor) (Object) ((StainedGlassBlock) h).getColor())
.supports(h -> h instanceof StainedGlassBlock);
}
// @formatter:on
}
| mit |
RabbitStewDio/Steropes.UI | build-automation/build/Build.cs | 13188 | using JetBrains.Annotations;
using Nuke.Common;
using Nuke.Common.CI;
using Nuke.Common.Execution;
using Nuke.Common.Git;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.Git;
using Nuke.Common.Tools.GitVersion;
using Nuke.Common.Utilities;
using Nuke.Common.Utilities.Collections;
using Nuke.GitHub;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using static Nuke.Common.IO.CompressionTasks;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.GitHub.GitHubTasks;
using static Nuke.Common.ChangeLog.ChangelogTasks;
[CheckBuildProjectConfigurations]
[ShutdownDotNetAfterServerBuild]
[SuppressMessage("ReSharper", "InconsistentNaming")]
class Build : NukeBuild
{
/// Support plugins are available for:
/// - JetBrains ReSharper https://nuke.build/resharper
/// - JetBrains Rider https://nuke.build/rider
/// - Microsoft VisualStudio https://nuke.build/visualstudio
/// - Microsoft VSCode https://nuke.build/vscode
public static int Main() => Execute<Build>(x => x.Default);
static readonly string[] DefaultPublishTargets =
{
"win-x64",
// "linux-x64"
};
const string NuGetDefaultUrl = "https://api.nuget.org/v3/index.json";
[Parameter("NuGet Source - Defaults to the value of the environment variable 'NUGET_SOURCE' or '" + NuGetDefaultUrl + "'")]
string NuGetSource;
[Parameter("NuGet API Key - Defaults to the value of the environment variable 'NUGET_API_KEY'")]
string NuGetApiKey;
[Parameter("Publish Target Runtime Identifiers for building self-contained applications - Default is ['win-x64', 'linux-x64']")]
string[] PublishTargets = DefaultPublishTargets;
[Parameter("Skip Tests - Default is 'false'")]
readonly bool SkipTests;
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Parameter("(Optional) GitHub Authentication Token for uploading releases - Defaults to the value of the GITHUB_API_TOKEN environment variable")]
string GitHubAuthenticationToken;
[Parameter("(Optional) Git remote id override")]
string GitRepositoryRemoteId;
[Parameter("(Optional) Path to the release notes for NuGet packages and GitHub releases.")]
AbsolutePath PackageReleaseNotesFile;
[Solution]
readonly Solution Solution;
GitRepository GitRepository;
[GitVersion(NoFetch = true, Framework = "net5.0")]
readonly GitVersion GitVersion;
string ChangeLogFile => RootDirectory / "CHANGELOG.md";
AbsolutePath SourceDirectory => RootDirectory / "src";
AbsolutePath SamplesDirectory => RootDirectory / "samples";
AbsolutePath ArtifactsDirectory => RootDirectory / "output";
AbsolutePath ArtifactsArchiveDirectory => RootDirectory / "build-artefacts";
AbsolutePath NuGetTargetDirectory => ArtifactsArchiveDirectory / GitVersion.SemVer / "nuget";
public Build()
{ }
protected override void OnBuildInitialized()
{
base.OnBuildInitialized();
if (string.IsNullOrEmpty(GitRepositoryRemoteId))
{
GitRepositoryRemoteId = "origin";
}
GitRepository = GitRepository.FromLocalDirectory(RootDirectory, null, GitRepositoryRemoteId);
PublishTargets ??= DefaultPublishTargets;
NuGetApiKey ??= Environment.GetEnvironmentVariable("NUGET_API_KEY");
NuGetSource ??= Environment.GetEnvironmentVariable("NUGET_SOURCE") ?? NuGetDefaultUrl;
GitHubAuthenticationToken ??= Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
}
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
EnsureCleanDirectory(ArtifactsDirectory);
DotNetClean(s => s.SetProject(Solution)
.SetConfiguration(Configuration)
.SetAssemblyVersion(GitVersion.AssemblySemVer)
.SetFileVersion(GitVersion.AssemblySemFileVer)
.SetInformationalVersion(GitVersion.InformationalVersion));
});
Target Restore => _ => _
.Executes(() =>
{
DotNetRestore(s => s.SetProjectFile(Solution));
});
Target Compile => _ =>
_
.DependsOn(Restore)
.Executes(() =>
{
Logger.Info($"Building with version {GitVersion.AssemblySemFileVer}");
DotNetBuild(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.SetAssemblyVersion(GitVersion.AssemblySemVer)
.SetFileVersion(GitVersion.AssemblySemFileVer)
.SetInformationalVersion(GitVersion.InformationalVersion)
.EnableNoRestore());
});
Target Test => _ =>
_
.DependsOn(Compile)
.Executes(() =>
{
if (SkipTests)
{
return;
}
DotNetTest(s => s.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.EnableNoRestore());
});
Target Pack => _ =>
_.DependsOn(Test)
.Executes(() =>
{
string releaseNotes = null;
if (!string.IsNullOrEmpty(PackageReleaseNotesFile) && File.Exists(PackageReleaseNotesFile))
{
releaseNotes = TextTasks.ReadAllText(PackageReleaseNotesFile);
}
DotNetPack(s => s.SetProject(Solution)
.SetConfiguration(Configuration)
.SetVersion(GitVersion.NuGetVersionV2)
.SetSymbolPackageFormat(DotNetSymbolPackageFormat.snupkg)
.EnableIncludeSymbols()
.EnableIncludeSource()
.EnableNoRestore()
.When(!string.IsNullOrEmpty(releaseNotes), x => x.SetPackageReleaseNotes(releaseNotes)));
GlobFiles(ArtifactsDirectory, "**/*.nupkg")
.NotEmpty()
.ForEach(absPath =>
{
Logger.Info(absPath);
var fileName = Path.GetFileName(absPath);
CopyFile(absPath, NuGetTargetDirectory / fileName, FileExistsPolicy.OverwriteIfNewer);
});
GlobFiles(ArtifactsDirectory, "**/*.snupkg")
.NotEmpty()
.ForEach(absPath =>
{
Logger.Info(absPath);
var fileName = Path.GetFileName(absPath);
CopyFile(absPath, NuGetTargetDirectory / fileName, FileExistsPolicy.OverwriteIfNewer);
});
});
Target Publish => _ =>
_.DependsOn(Test)
.Executes(() =>
{
var projects = GlobFiles(SourceDirectory, "**/*.csproj")
.Concat(GlobFiles(SamplesDirectory, "**/*.csproj"));
foreach (var target in PublishTargets)
{
var runtimeValue = target;
foreach (var projectFile in projects)
{
Logger.Info("Processing " + projectFile);
// parsing MSBuild projects is pretty much broken thanks to some
// buggy behaviour with MSBuild itself. For some reason MSBuild
// cannot load its own runtime and then simply crashes wildly
//
// https://github.com/dotnet/msbuild/issues/5706#issuecomment-687625355
// https://github.com/microsoft/MSBuildLocator/pull/79
//
// That issue is still active.
var project = new ProjectParser().Parse(projectFile, Configuration, runtimeValue);
if (project.OutputType != "WinExe" &&
project.OutputType != "Exe")
{
continue;
}
if (!project.IsValidPlatformFor(runtimeValue))
{
continue;
}
foreach (var framework in project.TargetFrameworks)
{
Logger.Info($"Processing {project.Name} with runtime {runtimeValue}");
DotNetPublish(s => s.SetProject(projectFile)
.SetAssemblyVersion(GitVersion.AssemblySemVer)
.SetFileVersion(GitVersion.AssemblySemFileVer)
.SetInformationalVersion(GitVersion.InformationalVersion)
.SetRuntime(runtimeValue)
.EnableSelfContained());
var buildTargetDir = ArtifactsDirectory / project.Name / "bin" / Configuration / framework;
var archiveTargetDir = ArtifactsArchiveDirectory / GitVersion.SemVer / "builds" / runtimeValue / framework;
var archiveFile = archiveTargetDir / $"{project.Name}-{GitVersion.SemVer}.zip";
DeleteFile(archiveFile);
CompressZip(buildTargetDir, archiveFile);
}
}
}
});
Target PushNuGet => _ =>
_.Description("Uploads all generated NuGet files to the configured NuGet server")
.OnlyWhenDynamic(() => !string.IsNullOrEmpty(NuGetSource))
.OnlyWhenDynamic(() => !string.IsNullOrEmpty(NuGetApiKey))
.Executes(() =>
{
GlobFiles(NuGetTargetDirectory, "*.nupkg")
.Where(x => !x.EndsWith(".symbols.nupkg"))
.ForEach(x =>
{
DotNetNuGetPush(s => s.SetTargetPath(x)
.EnableSkipDuplicate()
.EnableNoServiceEndpoint()
.SetSource(NuGetSource)
.SetApiKey(NuGetApiKey));
});
});
Target PublishGitHubRelease => _ =>
_.Description("Uploads all generated package files to GitHub")
.OnlyWhenDynamic(() => !string.IsNullOrEmpty(GitHubAuthenticationToken))
.OnlyWhenDynamic(() => IsGitHubRepository())
.Executes<Task>(async () =>
{
var releaseTag = $"v{GitVersion.MajorMinorPatch}";
string releaseNotes = null;
if (!string.IsNullOrEmpty(PackageReleaseNotesFile) && File.Exists(PackageReleaseNotesFile))
{
releaseNotes = TextTasks.ReadAllText(PackageReleaseNotesFile);
}
var repositoryInfo = GetGitHubRepositoryInfo(GitRepository);
var releaseArtefacts = GlobFiles(NuGetTargetDirectory, "*.nupkg")
.Concat(GlobFiles(NuGetTargetDirectory, "*.snupkg"))
.Concat(GlobFiles(ArtifactsArchiveDirectory / GitVersion.SemVer / "builds", "**/*.zip"))
.ToArray();
if (releaseArtefacts.Length > 0)
{
await PublishRelease(x => x.SetArtifactPaths(releaseArtefacts)
.SetCommitSha(GitVersion.Sha)
.SetReleaseNotes(releaseNotes)
.SetRepositoryName(repositoryInfo.repositoryName)
.SetRepositoryOwner(repositoryInfo.gitHubOwner)
.SetTag(releaseTag)
.SetToken(GitHubAuthenticationToken));
}
});
bool IsGitHubRepository()
{
return string.Equals(GitRepository?.Endpoint, "github.com");
}
Target Default => _ =>
_.Description("Builds the project and produces all release artefacts")
.DependsOn(Clean)
.DependsOn(Publish)
.DependsOn(Pack);
Target Upload => _ =>
_.Description("Uploads all generated release artefacts to the NuGet repository and GitHub")
.DependsOn(PushNuGet)
.DependsOn(PublishGitHubRelease);
}
| mit |
wmira/react-icons-kit | src/md/ic_computer_twotone.js | 387 | export const ic_computer_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M4 6h16v10H4z","opacity":".3"},"children":[]},{"name":"path","attribs":{"d":"M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"},"children":[]}]}; | mit |
p2made/yii2-p2y2-things | assets/locale/ArLyAsset.php | 1121 | <?php
/**
* ArLyAsset.php
*
* Yii2 asset for moment
* https://momentjs.com
*
* @author Pedro Plowman
* @copyright Copyright © Pedro Plowman, 2019
* @link https://github.com/p2made
* @license MIT
*
* @package p2made/yii2-p2y2-moment
* @class \p2m\assets\locale\ArLyAsset
*/
/**
* Load this asset with...
* p2m\assets\locale\ArLyAsset::register($this);
*
* or specify as a dependency with...
* 'p2m\assets\locale\ArLyAsset',
*/
namespace p2m\assets\locale;
class ArLyAsset extends \p2m\assets\base\P2AssetBundle
{
protected $packageName = 'moment';
protected $packageVersion = '2.24.0';
protected $packageData = [
'baseUrl' => 'https://cdn.jsdelivr.net/npm/moment@##-version-##/locale',
'sourcePath' => '@npm/moment/locale',
'static' => [
'jsOptions' => [
'integrity' => 'sha384-U0af6ngdzkIN5uiRSoLQuEbz6VfECnXQdoXb/KuYgB5ArWL318nINLEWl7yMPUGj',
'crossorigin' => 'anonymous',
],
],
'js' => [
'ar-ly.js',
],
'depends' => [
'p2m\assets\MomentAsset',
],
];
public function init()
{
$this->configureAsset($this->packageData);
parent::init();
}
}
| mit |
bg1bgst333/Sample | winapi/CreateWindow/WC_COMBOBOX/src/WC_COMBOBOX/WC_COMBOBOX/WC_COMBOBOX.cpp | 19338 | // wb_t@CÌCN[h
// ùèÌwb_t@C
#include <windows.h> // WWindowsAPI
#include <tchar.h> // TCHAR^
#include <commctrl.h> // RRg[
// Æ©Ìwb_t@C
#include "resource.h" // \[XID
// ÖÌvg^Cvé¾
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); // EBhEbZ[WÉÎµÄÆ©Ìð·éæ¤Éè`µ½R[obNÖWindowProc.
INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); // _CAOÌð·éR[obNÖDialogProc.
// _tWinMainÖÌè`
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd){
// ÏEzñÌé¾Eú»
HWND hWnd; // CreateWindowÅ쬵½EBhEÌEBhEnhði[·éHWND^ÏhWnd.
MSG msg; // EBhEbZ[Wîñði[·éMSG\¢Ì^Ïmsg.
WNDCLASS wc; // EBhENXîñðàÂWNDCLASS\¢Ì^Ïwc.
TCHAR tszWindowName[256]; // EBhE¼ði[·éTCHAR^zñtszWindowName.(·³256)
HDC hDC = NULL; // ±ÌEBhEÌfoCXReLXgnhhDCðNULLÉú».
HACCEL hAccel = NULL; // ANZ[^e[uÌnhði[·éHAACEL^ÏhAccelðNULLÉú».
// EBhENXÌÝè
wc.lpszClassName = _T("WC_COMBOBOX"); // EBhENX¼Í"WC_COMBOBOX".
wc.style = CS_HREDRAW | CS_VREDRAW; // X^CÍCS_HREDRAW | CS_VREDRAW.
wc.lpfnWndProc = WindowProc; // EBhEvV[WÍÆ©Ìðè`µ½WindowProc.
wc.hInstance = hInstance; // CX^XnhÍ_tWinMainÌø.
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // ACRÉÍ쬵½ACR"icon1.ico"(MAKEINTRESOURCE(IDI_ICON1))ðLoadIconÅ[hµÄg¤.
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // J[\Íîó.
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // wiÍuV.
wc.lpszMenuName = MAKEINTRESOURCE(IDR_MAINMENU); // j
[ÉÍIDR_MAINMENUðMAKEINTRESOURCE}NÅwè.
wc.cbClsExtra = 0; // 0Å¢¢.
wc.cbWndExtra = 0; // 0Å¢¢.
// EBhENXÌo^
if (!RegisterClass(&wc)){ // RegisterClassÅEBhENXðo^µ, 0ªÔÁ½çG[.
// G[
MessageBox(NULL, _T("RegisterClass failed!"), _T("WC_COMBOBOX"), MB_OK | MB_ICONHAND); // MessageBoxÅ"RegisterClass failed!"ÆG[bZ[Wð\¦.
return -1; // ÙíI¹(1)
}
// ¶ñ\[XÌ[h
LoadString(hInstance, IDS_WINDOW_NAME, tszWindowName, 256); // LoadStringÅSTRINGTABLE©çIDS_WINDOW_NAMEÉ ½é¶ñð[hµ, tszWindowNameÉi[.
// EBhEÌì¬
hWnd = CreateWindow(_T("WC_COMBOBOX"), tszWindowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); // CreateWindowÅ, ãÅo^µ½"WC_COMBOBOX"EBhENXÌEBhEðì¬.
if (hWnd == NULL){ // EBhEÌì¬É¸sµ½Æ«.
// G[
MessageBox(NULL, _T("CreateWindow failed!"), _T("WC_COMBOBOX"), MB_OK | MB_ICONHAND); // MessageBoxÅ"CreateWindow failed!"ÆG[bZ[Wð\¦.
return -2; // ÙíI¹(2)
}
// ANZ[^e[uÌ[h
hAccel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_MAINMENU)); // LoadAcceleratorsÅANZ[^e[uð[h.(ANZ[^e[uÌ\[XIDÍj
[Ư¶IDR_MAINMENU.)
// EBhEÌ\¦
ShowWindow(hWnd, SW_SHOW); // ShowWindowÅSW_SHOWðwèµÄEBhEÌ\¦.
// foCXReLXgÌæ¾.
hDC = GetDC(hWnd); // GetDCÅfoCXReLXgnhhDCðæ¾.
// PeekMessageÉæéC[v.
while (TRUE){ // íÉ^(TRUE)ÈÌųÀ[v.
// EBhEbZ[WªÄ¢é©ðmF·é.
if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)){ // PeekMessageÅEBhEbZ[WªÄ¢é©ðmFµ, ^ÈçÄ¢é.(PM_NOREMOVEÈÌÅbZ[WL
[©ç±ÌbZ[WðíµÈ¢.ÌGetMessageª»ÌbZ[Wð·é.)
// Ä¢½ç»ÌbZ[Wðæ¾.
if (GetMessage(&msg, NULL, 0, 0) > 0){ // GetMessageÅPeekMessageÅmFµ½bZ[Wðæ¾.
// ANZ[^L[Ì.
if (!TranslateAccelerator(hWnd, hAccel, &msg)){ // TranslateAcceleratorÅANZ[^L[ðWM_COMMANDÉÏ·Å«½êÍ, ȺÌbZ[W͵Ȣ.
// EBhEbZ[WÌo
TranslateMessage(&msg); // TranslateMessageżzL[bZ[Wð¶bZ[WÖÏ·.
DispatchMessage(&msg); // DispatchMessageÅó¯æÁ½bZ[WðEBhEvV[W(±ÌêÍÆ©Éè`µ½WindowProc)Éo.
}
}
else{ // ³íI¹(0), ܽÍG[ÉæéÙíI¹(-1).
// C[vð²¯é.
break; // breakÅC[vð²¯é.
}
}
else{ // UÈçEBhEbZ[WªÄ¢È¢Æ«.
// ½àµÈ¢.
}
}
// foCXReLXgÌðú.
if (hDC != NULL){ // hDCªðú³êĢȯêÎ.
// foCXReLXgððú·é.
ReleaseDC(hWnd, hDC); // ReleaseDCÅhDCððú.
hDC = NULL; // NULLðZbg.
}
// vOÌI¹
return (int)msg.wParam; // I¹R[h(msg.wParam)ðßèlƵÄÔ·.
}
// WindowProcÖÌè`
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ // EBhEbZ[WÉÎµÄÆ©Ìð·éæ¤Éè`µ½EBhEvV[W.
// EBhEbZ[WÉηé.
switch (uMsg){ // switch-casa¶ÅuMsgÌl²ÆÉðU誯é.
// EBhEÌ쬪Jn³ê½.
case WM_CREATE: // EBhEÌ쬪Jn³ê½.(uMsgªWM_CREATEÌ.)
// WM_CREATEubN
{
// ÏÌé¾
HWND hButton; // {^ÌEBhEnhhButton.
HWND hStatic; // X^eBbNRg[ÌEBhEnhhStatic.
HWND hEdit; // GfBbgRg[ÌEBhEnhhEdit.
HWND hCheck; // `FbN{bNXRg[ÌEBhEnhhCheck.
HWND hRadio1; // WI{^Rg[ÌEBhEnhhRadio1.
HWND hRadio2; // WI{^Rg[ÌEBhEnhhRadio2.
HWND hRadio3; // WI{^Rg[ÌEBhEnhhRadio3.
HWND hGroup; // O[v{bNXRg[ÌEBhEnhhGroup.
HWND hList; // Xg{bNXRg[ÌEBhEnhhList.
HWND hCombo; // R{{bNXRg[ÌEBhEnhhCombo.
LPCREATESTRUCT lpCS; // CreateStruct\¢ÌÌ|C^lpCS.
// AvP[VCX^XnhÌæ¾.
lpCS = (LPCREATESTRUCT)lParam; // lParamðLPCREATESTRUCTÉLXgµÄ, lpCSÉi[.
// {^Ìì¬.
hButton = CreateWindow(WC_BUTTON, _T("Button1"), WS_CHILD | WS_VISIBLE, 50, 00, 100, 30, hwnd, (HMENU)ID_BUTTON1, lpCS->hInstance, NULL); // CreateWindowÌWC_BUTTONÅ{^"Button1"ðì¬.
if (hButton == NULL){ // hButtonªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// X^eBbNRg[(eLXg)Ìì¬.
hStatic = CreateWindow(WC_STATIC, _T("StaticText1"), WS_CHILD | WS_VISIBLE, 50, 30, 100, 30, hwnd, (HMENU)ID_STATIC1, lpCS->hInstance, NULL); // CreateWindowÌWC_STATICÅX^eBbNRg[(eLXg)"StaticText1"ðì¬.
if (hStatic == NULL){ // hStaticªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// GfBbgRg[Ìì¬.
hEdit = CreateWindow(WC_EDIT, _T("Edit1"), WS_CHILD | WS_BORDER | WS_VISIBLE, 50, 60, 150, 30, hwnd, (HMENU)ID_EDIT1, lpCS->hInstance, NULL); // CreateWindowÌWC_EDITÅGfBbgRg["Edit1"ðì¬.
if (hEdit == NULL){ // hEditªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// `FbN{bNXÌì¬.
hCheck = CreateWindow(WC_BUTTON, _T("CheckBox1"), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 50, 90, 100, 30, hwnd, (HMENU)ID_CHECK1, lpCS->hInstance, NULL); // CreateWindowÌWC_BUTTONÆBS_CHECKBOXÅ`FbN{bNX"CheckBox1"ðì¬.
if (hCheck == NULL){ // hCheckªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// O[v{bNX1Ìì¬.
hGroup = CreateWindow(WC_BUTTON, _T("GroupBox1"), WS_CHILD | WS_VISIBLE | BS_GROUPBOX, 50, 120, 410, 150, hwnd, (HMENU)ID_GROUP1, lpCS->hInstance, NULL); // CreateWindowÌWC_BUTTONÆBS_GROUPBOXÅO[v{bNX"GroupBox1"ðì¬.
if (hGroup == NULL){ // hGroupªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// WI{^1Ìì¬.
hRadio1 = CreateWindow(WC_BUTTON, _T("RadioButton1"), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON | WS_GROUP, 20, 20, 120, 30, hGroup, (HMENU)ID_RADIO1, lpCS->hInstance, NULL); // CreateWindowÌWC_BUTTONÆBS_RADIOBUTTONÅWI{^"RadioButton1"ðì¬.(hGroupÌqEBhEƵÄì¬. O[vÌÅÌRg[ÉÍWS_GROUPð¯é.)
if (hRadio1 == NULL){ // hRadio1ªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// WI{^2Ìì¬.
hRadio2 = CreateWindow(WC_BUTTON, _T("RadioButton2"), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON, 140, 20, 120, 30, hGroup, (HMENU)ID_RADIO2, lpCS->hInstance, NULL); // CreateWindowÌWC_BUTTONÆBS_RADIOBUTTONÅWI{^"RadioButton2"ðì¬.(hGroupÌqEBhEƵÄì¬.)
if (hRadio2 == NULL){ // hRadio2ªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// WI{^3Ìì¬.
hRadio3 = CreateWindow(WC_BUTTON, _T("RadioButton3"), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON, 260, 20, 120, 30, hGroup, (HMENU)ID_RADIO3, lpCS->hInstance, NULL); // CreateWindowÌWC_BUTTONÆBS_RADIOBUTTONÅWI{^"RadioButton3"ðì¬.(hGroupÌqEBhEƵÄì¬.)
if (hRadio3 == NULL){ // hRadio3ªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// Xg{bNXÌì¬.
hList = CreateWindow(WC_LISTBOX, _T("ListBox1"), WS_CHILD | WS_VISIBLE | WS_BORDER | WS_VSCROLL, 50, 280, 150, 80, hwnd, (HMENU)ID_LIST1, lpCS->hInstance, NULL); // CreateWindowÌWC_LISTBOXÅXg{bNX"ListBox1"ðì¬.
if (hList == NULL){ // hListªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// R{{bNXÌì¬.
hCombo = CreateWindow(WC_COMBOBOX, _T("ComboBox1"), WS_CHILD | WS_VISIBLE | CBS_SIMPLE | WS_VSCROLL, 210, 280, 150, 80, hwnd, (HMENU)ID_COMBO1, lpCS->hInstance, NULL); // CreateWindowÌWC_COMBOBOXÅR{{bNX"ComboBox1"ðì¬.
if (hCombo == NULL){ // hComboªNULLÈç.
// G[.
return -1; // -1ðÔ·.
}
// EBhE쬬÷
return 0; // return¶Å0ðÔµÄ, EBhE쬬÷Æ·é.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// EBhEªjü³ê½.
case WM_DESTROY: // EBhEªjü³ê½.(uMsgªWM_DESTROYÌ.)
// WM_DESTROYubN
{
// I¹bZ[WÌM.
PostQuitMessage(0); // PostQuitMessageÅI¹R[hð0ƵÄWM_QUITbZ[WðM.(·éÆbZ[W[vÌGetMessageÌßèlª0ÉÈéÌÅ, bZ[W[v©ç²¯é.)
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// j
[ÚªIð³ê½è, {^ÈÇÌRg[ª³ê½èµÄ, R}hª¶µ½.
case WM_COMMAND: // j
[ÚªIð³ê½è, {^ÈÇÌRg[ª³ê½èµÄ, R}hª¶µ½.(uMsgªWM_COMMANDÌ.)
// WM_COMMANDubN
{
// ÇÌj
[Ú, ܽÍRg[ªIð³ê½©ð»è·é.
switch (LOWORD(wParam)){ // LOWORD(wParam)ÅIð³ê½j
[Ú, ܽÍRg[ÌIDªæ¾Å«éÌÅ, »ÌlÅ»è·é.
// æ¾µ½ID²ÆÉðªò.
// Item1-1ªIð³ê½.
case ID_ITEM_1_1:
// ID_ITEM_1_1ubN
{
// ÏÌé¾
HINSTANCE hInstance; // AvP[VCX^Xnh
// hInstanceðæ¾
hInstance = (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE); // GetWindowLongÅAvP[VCX^Xnhðæ¾µ, hInstanceÉi[.
// _CAO{bNXÌ\¦
DialogBox(hInstance, MAKEINTRESOURCEW(IDD_DIALOG), hwnd, DialogProc); // DialogBoxÅ_CAO{bNXð\¦.(_CAOÌÍDialogProcÉ¢Ä é.)
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Item1-2ªIð³ê½.
case ID_ITEM_1_2:
// ID_ITEM_1_2ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("Item1-2"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"Item1-2"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Item1-3ªIð³ê½.
case ID_ITEM_1_3:
// ID_ITEM_1_3ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("Item1-3"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"Item1-3"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Item2-1ªIð³ê½.
case ID_ITEM_2_1:
// ID_ITEM_2_1ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("Item2-1"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"Item2-1"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Item2-2ªIð³ê½.
case ID_ITEM_2_2:
// ID_ITEM_2_2ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("Item2-2"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"Item2-2"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Item2-3ªIð³ê½.
case ID_ITEM_2_3:
// ID_ITEM_2_3ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("Item2-3"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"Item2-3"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Item3-1ªIð³ê½.
case ID_ITEM_3_1:
// ID_ITEM_3_1ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("Item3-1"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"Item3-1"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Item3-2ªIð³ê½.
case ID_ITEM_3_2:
// ID_ITEM_3_2ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("Item3-2"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"Item3-2"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Item3-3ªIð³ê½.
case ID_ITEM_3_3:
// ID_ITEM_3_3ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("Item3-3"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"Item3-3"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// Button1ª³ê½.
case ID_BUTTON1:
// ID_BUTTON1ubN
{
// ÏÌé¾.
HWND hGroup; // GroupBox1ÌEBhEnh.
// GroupBox1ÌEBhEnhðæ¾.
hGroup = GetDlgItem(hwnd, ID_GROUP1); // GetDlgItemÅID_GROUP1Ìnhæ¾.
// RadioButton1É`FbNðüêé.
CheckRadioButton(hGroup, ID_RADIO1, ID_RADIO3, ID_RADIO1); // CheckRadioButtonÅID_RADIO1ÌÝÉ`FbNð¯é.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// CheckBox1ª³ê½.
case ID_CHECK1:
// ID_CHECK1ubN
{
// bZ[W{bNXð\¦.
MessageBox(NULL, _T("CheckBox1 Cliked!"), _T("WC_COMBOBOX"), MB_OK | MB_ICONASTERISK); // MessageBoxÅ"CheckBox1 Cliked!"Æ\¦.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// RadioButton1ª³ê½Æ«.
case ID_RADIO1:
// ID_RADIO1ubN
{
// ID_RADIO1É`FbNð¯é.(ÀÛÉÍID_RADIO1Í, ID_GROUP1ÌqEBhEÉÈÁÄ¢é½ß, ±±ÉÍÈ¢.)
CheckRadioButton(hwnd, ID_RADIO1, ID_RADIO3, ID_RADIO1); // CheckRadioButtonÅID_RADIO1ÌÝÉ`FbNð¯é.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// RadioButton2ª³ê½Æ«.
case ID_RADIO2:
// ID_RADIO2ubN
{
// ID_RADIO2É`FbNð¯é.(ÀÛÉÍID_RADIO2Í, ID_GROUP1ÌqEBhEÉÈÁÄ¢é½ß, ±±ÉÍÈ¢.)
CheckRadioButton(hwnd, ID_RADIO1, ID_RADIO3, ID_RADIO2); // CheckRadioButtonÅID_RADIO2ÌÝÉ`FbNð¯é.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// RadioButton3ª³ê½Æ«.
case ID_RADIO3:
// ID_RADIO3ubN
{
// ID_RADIO3É`FbNð¯é.(ÀÛÉÍID_RADIO3Í, ID_GROUP1ÌqEBhEÉÈÁÄ¢é½ß, ±±ÉÍÈ¢.)
CheckRadioButton(hwnd, ID_RADIO1, ID_RADIO3, ID_RADIO3); // CheckRadioButtonÅID_RADIO3ÌÝÉ`FbNð¯é.
// 0ðÔ·.
return 0; // µ½ÌÅßèlƵÄ0ðÔ·.
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// ãLÈOÌ.
default:
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
}
}
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
// ãLÈOÌ.
default: // ãLÈOÌlÌÌùè.
// ùèÌÖü©¤.
break; // breakŲ¯Ä, ùèÌ(DefWindowProc)Öü©¤.
}
// ÆÍùèÌÉC¹é.
return DefWindowProc(hwnd, uMsg, wParam, lParam); // ßèlàÜßDefWindowProcÉùèÌðC¹é.
}
// DialogProcÖÌè`
INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam){ // _CAOÌð·éR[obNÖ.
// _CAOÌbZ[W
switch (uMsg){ // uMsgÌàeÅ»f.
// _CAOªÂ¶çê½.
case WM_CLOSE: // _CAOªÂ¶çê½.(uMsgªWM_CLOSEÌ.)
// WM_CLOSEubN
{
// _CAOðI¹·é.
EndDialog(hwndDlg, IDOK); // EndDialogÅ_CAOðI¹·é.
// TRUEðÔ·.
return TRUE; // Å«½ÌÅTRUE.
}
// ²¯é.
break; // breakŲ¯é.
default:
// ²¯é.
break; // breakŲ¯é.
}
// ±±É鯫ÍūĢȢ.
return FALSE; // ūĢȢÌÅFALSE.
} | mit |
moble/spherical_functions | tests/time_LM_ranges.py | 1706 | #! /usr/bin/env ipython
# Copyright (c) 2019, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
from __future__ import print_function, division, absolute_import
try:
from IPython import get_ipython
ipython = get_ipython()
except AttributeError:
print("This script must be run with `ipython`")
raise
import sys
import numpy as np
import random
import quaternion
import numbapro as nb
from numbapro import *
import spherical_functions as sf
ru = lambda: random.uniform(-1, 1)
ells = range(16 + 1) + [24, 32]
evals = np.empty_like(ells, dtype=int)
picoseconds = np.empty_like(ells, dtype=float)
ell_min = 0
for i, ell_max in enumerate(ells):
evals[i] = (ell_max * (11 + ell_max * (12 + 4 * ell_max)) + ell_min * (1 - 4 * ell_min ** 2) + 3) // 3
LMpM = np.empty((evals[i], 3), dtype=int)
result = ipython.magic("timeit -o global LMpM; LMpM = sf.LMpM_range(ell_min, ell_max)")
picoseconds[i] = 1e12 * result.best / evals[i]
print("With ell_max={0}, and {1} evaluations, each LMpM averages {2:.0f} ps".format(ell_max, evals[i],
picoseconds[i]))
result = ipython.magic(
"timeit -o global LMpM; LMpM = np.array([[ell,mp,m] for ell in range(ell_min,ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)])")
picoseconds[i] = 1e12 * result.best / evals[i]
print("\tWith ell_max={0}, and {1} evaluations, each LMpM averages {2:.0f} ps".format(ell_max, evals[i],
picoseconds[i]))
sys.stdout.flush()
| mit |
ideato/phpcollab3 | plugins/idProjectManagementPlugin/lib/form/doctrine/PluginIssueForm.class.php | 597 | <?php
/**
* This file is part of the phpCollab3 package.
* (c) 2009 Ideato s.r.l. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* PluginIssueForm.class.php
*
* @package phpCollab3
* @subpackage idProjectManagementPlugin Forms
*/
/**
* PluginIssue form.
*
* @package phpCollab3
* @subpackage idProjectManagementPlugin Forms
* @version SVN: $Id: sfDoctrineFormTemplate.php 6174 2007-11-27 06:22:40Z fabien $
*/
abstract class PluginIssueForm extends BaseIssueForm
{
} | mit |
sleepyyyybear/restaurant | client/src/app/tai-khoan/tai-khoan-routing.module.ts | 358 | import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TaiKhoanComponent } from './tai-khoan.component';
const routes: Routes = [
{ path: '', component: TaiKhoanComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TaiKhoanRoutingModule { }
| mit |
AntonChankin/otus_java_2017_10_chankin | homework06/src/main/java/com/antonchankin/otus/hw06/impl/CashDispenserImpl.java | 5048 | package com.antonchankin.otus.hw06.impl;
import com.antonchankin.otus.hw06.api.CartredgeChangeSubject;
import com.antonchankin.otus.hw06.api.CartridgeChangeObserver;
import com.antonchankin.otus.hw06.api.CashDispenser;
import com.antonchankin.otus.hw06.model.Cartridge;
import com.antonchankin.otus.hw06.model.CashUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CashDispenserImpl implements CashDispenser, CartredgeChangeSubject {
private Logger log = LoggerFactory.getLogger(CashDispenserImpl.class);
private List<Cartridge> cartridges;
private CartridgeChangeObserver listener;
public CashDispenserImpl() {
this.cartridges = new ArrayList<>(0);
}
public CashDispenserImpl(List<Cartridge> cartridges) {
this.cartridges = cartridges;
}
public void load(Cartridge cartridge){
if (cartridge != null) {
cartridges.add(cartridge);
listener.onCartridgeChanged();
}
}
public void replace(Cartridge empty, Cartridge full){
if (cartridges.remove(empty)) {
cartridges.add(full);
listener.onCartridgeChanged();
}
}
public void remove(Cartridge cartridge){
if (cartridge != null) {
cartridges.remove(cartridge);
listener.onCartridgeChanged();
}
}
@Override
public boolean dispense(CashUnit unit) {
Cartridge cartridge = null;
boolean isDispensed = false;
for (Cartridge element : cartridges) {
if(element.getId() == unit.getDenominationId()){
cartridge = element;
break;
}
}
if (cartridge != null && cartridge.getAmount() > unit.getAmount()) {
cartridge.setAmount(cartridge.getAmount() - unit.getAmount());
log.info("Dispensed " + unit.getAmount() + " of " + cartridge.getDenominationName());
isDispensed = true;
}
return isDispensed;
}
@Override
public boolean dispense(List<CashUnit> units) {
boolean isDispensed = false;
boolean isValid = true;
try {
for (CashUnit unit : units) {
Cartridge cartridge = null;
for (Cartridge element : cartridges) {
if(element.getId() == unit.getDenominationId()){
cartridge = element;
break;
}
}
if (cartridge != null && cartridge.getAmount() > unit.getAmount()) {
isValid = isValid && cartridge.getAmount() > unit.getAmount();
}
}
for (CashUnit unit : units) {
isDispensed = true;
Cartridge cartridge = null;
for (Cartridge element : cartridges) {
if(element.getId() == unit.getDenominationId()){
cartridge = element;
break;
}
}
log.info("Dispensed " + unit.getAmount() + " of " + cartridge.getDenominationName());
cartridge.setAmount(cartridge.getAmount() - unit.getAmount());
}
} catch (Exception e) {
log.error("Cannot dispense", e);
isDispensed = false;
}
return isDispensed;
}
@Override
public Map<Integer, String> getDenominationsNames() {
Map<Integer, String> denominations = new HashMap<>(cartridges.size());
for (Cartridge cartridge : cartridges) {
denominations.put(cartridge.getId(), cartridge.getDenominationName());
}
return denominations;
}
@Override
public List<CashUnit> getAvailable() {
List<CashUnit> units = new ArrayList<>(cartridges.size());
for (Cartridge cartridge : cartridges) {
units.add(new CashUnit(cartridge.getId(), cartridge.getAmount()));
}
return units;
}
@Override
public Map<Integer, Integer> getDenominations() {
Map<Integer, Integer> denominations = new HashMap<>(cartridges.size());
for (Cartridge cartridge : cartridges) {
denominations.put(cartridge.getDenomination(), cartridge.getId());
}
return denominations;
}
@Override
public int getMaxDenomination() {
int max = 0;
for (Cartridge cartridge : cartridges) {
max = cartridge.getDenomination() > max ? cartridge.getDenomination() : max;
}
return max;
}
@Override
public int getMinDenomination() {
int min = 0;
for (Cartridge cartridge : cartridges) {
min = cartridge.getDenomination() < min ? cartridge.getDenomination() : min;
}
return min;
}
@Override
public void attach(CartridgeChangeObserver observer) {
listener = observer;
}
}
| mit |
despawnerer/theatrics | web/src/js/models/price.js | 848 | import {formatPriceRange} from '../utils/formatting';
export default class Price {
constructor(event, data) {
this.event = event;
this.data = data;
}
hasRange() {
return this.data.lower != null || this.data.upper != null;
}
toString() {
if (this.hasRange()) {
const currency = this.event.getLocation().currency;
return formatPriceRange(this.data.lower, this.data.upper, currency);
} else {
return this.data.text;
}
}
toJSONLD(app) {
if (this.hasRange()) {
const currency = this.event.getLocation().currency;
const offer = {
'@type': 'AggregateOffer',
priceCurrency: currency,
}
if (this.data.lower != null) offer.lowPrice = this.data.lower;
if (this.data.upper != null) offer.highPrice = this.data.upper;
return offer;
}
}
}
| mit |
kristianmandrup/ruby_traverser_dsl | test/manipulate/update/update_assignment_test.rb | 1880 | require File.dirname(__FILE__) + '/../test_helper'
require 'yaml'
class TraversalTest < Test::Unit::TestCase
include TestHelper
define_method :"setup" do
src = %q{
a = 3
b = c
x = 'abc'
}
code = Ripper::RubyBuilder.build(src)
@node = code[0]
end
define_method :"test find assignment in method definition and replace value of right side String value '3'" do
src = %q{
def hello_world(a)
my_var = 2
end
}
code = Ripper::RubyBuilder.build(src)
node = code.find(:def, 'hello_world', :params => ['a']) do |b|
assign_node = b.find(:assignment, 'my_var')
assign_node.update(:value => '3')
end
assert_equal '3', node[0].value
end
define_method :"test find assignment in method definition and replace value of right side with Integer value 3" do
src = %q{
def hello_world(a)
my_var = 2
end
}
code = Ripper::RubyBuilder.build(src)
node = code.find(:def, 'hello_world', :params => ['a']) do |b|
assign_node = b.find(:assignment, 'my_var')
assign_node.update(3)
end
assert_equal 3, node[0].value
end
define_method :"test find assignment in method definition and replace value variable name with 'my_other' " do
src = %q{
def hello_world(a)
my_var = 2
end
}
code = Ripper::RubyBuilder.build(src)
node = code.find(:def, 'hello_world', :params => ['a']) do |b|
assign_node = b.find(:assignment, 'my_var')
assign_node.update(:name => 'my_other')
end
assert_equal 'my_other', node[0].name
end
end
| mit |
ne1ro/capistrano_pm2 | lib/capistrano_pm2/version.rb | 59 | # Gem version
module CapistranoPm2
VERSION = '0.0.5'
end
| mit |
lijinchao2007/leftorright | sumeru/src/pilot.js | 1038 | /*
* message pilot, 自动生成pilot
*/
var runnable = function(sumeru){
var pilot = {};
var counter = 0;
var createPilotId = function(){
return "pilot"+counter++;
};
var setPilot = function(obj,type){
// 解决server端collection占用内存不释放的问题.
if(fw.IS_SUMERU_SERVER){
return;
}
var type = type || 'model';
if(!obj._getPilotId()){
var pilotid = createPilotId();
pilot[pilotid] = {
type:type,
stub:obj
};
obj._setPilotId(pilotid);
}
}
var getPilot = function(pilotid){
return pilot[pilotid];
}
if(sumeru.msgpilot){
return;
}
var api = sumeru.addSubPackage('msgpilot');
api.__reg('setPilot', setPilot, 'private');
api.__reg('getPilot', getPilot, 'private');
};
if(typeof module !='undefined' && module.exports){
module.exports = runnable;
}else{
runnable(sumeru);
} | mit |
darkrasid/gitlabhq | lib/gitlab/repo_path.rb | 548 | module Gitlab
module RepoPath
NotFoundError = Class.new(StandardError)
def self.strip_storage_path(repo_path)
result = nil
Gitlab.config.repositories.storages.values.each do |params|
storage_path = params['path']
if repo_path.start_with?(storage_path)
result = repo_path.sub(storage_path, '')
break
end
end
if result.nil?
raise NotFoundError.new("No known storage path matches #{repo_path.inspect}")
end
result.sub(/\A\/*/, '')
end
end
end
| mit |
ecbypi/besko | app/helpers/deliveries_helper.rb | 730 | module DeliveriesHelper
def delivery_search_results_css_class(query)
css_class = "deliveries-listing"
if query.filter == DeliveryQuery::FILTER_OPTIONS[:all]
css_class << " all-deliveries-listing"
end
css_class
end
def delivery_search_filter_options
@delivery_search_filter_options ||=
DeliveryQuery::FILTER_OPTIONS.map do |key, value|
[t(".delivery_search.filter_labels.#{key}"), value]
end
end
def delivery_search_sort_options
@delivery_search_sort_options ||=
DeliveryQuery::SORT_OPTIONS.map do |key, value|
[t(".delivery_search.sort_labels.#{key}"), value]
end
end
def delivery_search_deliverer_options
Delivery::Deliverers
end
end
| mit |
NeonSpectrum/KanadeBot | NadekoBot.Core/Modules/Games/NunchiCommands.cs | 5031 | using Discord;
using Discord.Commands;
using Discord.WebSocket;
using NadekoBot.Common.Attributes;
using NadekoBot.Modules.Games.Common.Nunchi;
using NadekoBot.Modules.Games.Services;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Games
{
public partial class Games
{
[Group]
public class NunchiCommands : NadekoSubmodule<GamesService>
{
private readonly DiscordSocketClient _client;
public NunchiCommands(DiscordSocketClient client)
{
_client = client;
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Nunchi()
{
var newNunchi = new Nunchi(Context.User.Id, Context.User.ToString());
Nunchi nunchi;
//if a game was already active
if ((nunchi = _service.NunchiGames.GetOrAdd(Context.Guild.Id, newNunchi)) != newNunchi)
{
// join it
if (!await nunchi.Join(Context.User.Id, Context.User.ToString()))
{
// if you failed joining, that means game is running or just ended
// await ReplyErrorLocalized("nunchi_already_started").ConfigureAwait(false);
return;
}
await ReplyConfirmLocalized("nunchi_joined", nunchi.ParticipantCount).ConfigureAwait(false);
return;
}
try { await ConfirmLocalized("nunchi_created").ConfigureAwait(false); } catch { }
nunchi.OnGameEnded += Nunchi_OnGameEnded;
//nunchi.OnGameStarted += Nunchi_OnGameStarted;
nunchi.OnRoundEnded += Nunchi_OnRoundEnded;
nunchi.OnUserGuessed += Nunchi_OnUserGuessed;
nunchi.OnRoundStarted += Nunchi_OnRoundStarted;
_client.MessageReceived += _client_MessageReceived;
var success = await nunchi.Initialize().ConfigureAwait(false);
if (!success)
{
if (_service.NunchiGames.TryRemove(Context.Guild.Id, out var game))
game.Dispose();
await ConfirmLocalized("nunchi_failed_to_start").ConfigureAwait(false);
}
Task _client_MessageReceived(SocketMessage arg)
{
var _ = Task.Run(async () =>
{
if (arg.Channel.Id != Context.Channel.Id)
return;
if (!int.TryParse(arg.Content, out var number))
return;
try
{
await nunchi.Input(arg.Author.Id, arg.Author.ToString(), number).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
});
return Task.CompletedTask;
}
Task Nunchi_OnGameEnded(Nunchi arg1, string arg2)
{
if (_service.NunchiGames.TryRemove(Context.Guild.Id, out var game))
{
_client.MessageReceived -= _client_MessageReceived;
game.Dispose();
}
if (arg2 == null)
return ConfirmLocalized("nunchi_ended_no_winner", Format.Bold(arg2));
else
return ConfirmLocalized("nunchi_ended", Format.Bold(arg2));
}
}
private Task Nunchi_OnRoundStarted(Nunchi arg, int cur)
{
return ConfirmLocalized("nunchi_round_started",
Format.Bold(arg.ParticipantCount.ToString()),
Format.Bold(cur.ToString()));
}
private Task Nunchi_OnUserGuessed(Nunchi arg)
{
return ConfirmLocalized("nunchi_next_number", Format.Bold(arg.CurrentNumber.ToString()));
}
private Task Nunchi_OnRoundEnded(Nunchi arg1, (ulong Id, string Name)? arg2)
{
if(arg2.HasValue)
return ConfirmLocalized("nunchi_round_ended", Format.Bold(arg2.Value.Name));
else
return ConfirmLocalized("nunchi_round_ended_boot",
Format.Bold("\n" + string.Join("\n, ", arg1.Participants.Select(x => x.Name)))); // this won't work if there are too many users
}
private Task Nunchi_OnGameStarted(Nunchi arg)
{
return ConfirmLocalized("nunchi_started", Format.Bold(arg.ParticipantCount.ToString()));
}
}
}
} | mit |
DXCanas/content-curation | contentcuration/contentcuration/tests/test_asynctask.py | 7976 | from __future__ import absolute_import
from builtins import range
from builtins import str
from .base import BaseAPITestCase
from contentcuration.models import ContentNode
from contentcuration.models import Task
from contentcuration.tasks import create_async_task
from contentcuration.tasks_test import non_async_test_task
class AsyncTaskTestCase(BaseAPITestCase):
"""
These tests check that creating and updating Celery tasks using the create_async_task function result in
an up-to-date Task object with the latest status and information about the task.
"""
task_url = '/api/task'
def test_asynctask_reports_success(self):
"""
Tests that when an async task is created and completed, the Task object has a status of 'SUCCESS' and
contains the return value of the task.
"""
metadata = {'test': True}
task_options = {
'user_id': self.user.pk,
'metadata': metadata
}
task, task_info = create_async_task('test', task_options)
self.assertTrue(Task.objects.filter(metadata__test=True).count() == 1)
self.assertEqual(task_info.user, self.user)
self.assertEqual(task_info.task_type, 'test')
self.assertEqual(task_info.is_progress_tracking, False)
result = task.get()
self.assertEqual(result, 42)
self.assertEqual(Task.objects.get(task_id=task.id).metadata['result'], 42)
self.assertEqual(Task.objects.get(task_id=task.id).status, 'SUCCESS')
def test_asynctask_reports_progress(self):
"""
Test that we can retrieve task progress via the Task API.
"""
metadata = {'test': True}
task_options = {
'user_id': self.user.pk,
'metadata': metadata
}
task, task_info = create_async_task('progress-test', task_options)
self.assertTrue(Task.objects.filter(metadata__test=True).count() == 1)
result = task.get()
self.assertEqual(result, 42)
self.assertEqual(Task.objects.get(task_id=task.id).status, 'SUCCESS')
# progress is retrieved dynamically upon calls to get the task info, so
# use an API call rather than checking the db directly for progress.
url = '{}/{}'.format(self.task_url, task_info.id)
response = self.get(url)
self.assertEqual(response.data['status'], 'SUCCESS')
self.assertEqual(response.data['task_type'], 'progress-test')
self.assertEqual(response.data['metadata']['progress'], 100)
self.assertEqual(response.data['metadata']['result'], 42)
def test_asynctask_filters_by_channel(self):
"""
Test that we can filter tasks by channel ID.
"""
self.channel.editors.add(self.user)
self.channel.save()
metadata = {'affects': {'channels': [self.channel.id]}}
task_options = {
'user_id': self.user.pk,
'metadata': metadata
}
task, task_info = create_async_task('progress-test', task_options)
self.assertTrue(Task.objects.filter(metadata__affects__channels__contains=[self.channel.id]).count() == 1)
result = task.get()
self.assertEqual(result, 42)
self.assertEqual(Task.objects.get(task_id=task.id).status, 'SUCCESS')
# since tasks run sync in tests, we can't test it in an actual running state
# so simulate the running state in the task object.
db_task = Task.objects.get(task_id=task.id)
db_task.status = 'STARTED'
db_task.save()
url = '{}?channel_id={}'.format(self.task_url, self.channel.id)
response = self.get(url)
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['status'], 'STARTED')
self.assertEqual(response.data[0]['task_type'], 'progress-test')
self.assertEqual(response.data[0]['metadata']['progress'], 100)
self.assertEqual(response.data[0]['metadata']['result'], 42)
# once the task is completed, it should be removed from the list of channel tasks.
db_task.status = 'SUCCESS'
db_task.save()
response = self.get(url)
self.assertEqual(len(response.data), 0)
url = '{}?channel_id={}'.format(self.task_url, task_info.id, "nope")
response = self.get(url)
self.assertEqual(len(response.data), 0)
def test_asynctask_reports_error(self):
"""
Tests that if a task fails with an error, that the error information is stored in the Task object for later
retrieval and analysis.
"""
metadata = {'test': True}
task_options = {
'user_id': self.user.pk,
'metadata': metadata
}
task, task_info = create_async_task('error-test', task_options)
task = Task.objects.get(task_id=task.id)
self.assertEqual(task.status, 'FAILURE')
self.assertTrue('error' in task.metadata)
error = task.metadata['error']
# Python 3 has assertCountEqual, so add an alias for compatibility
try:
self.assertItemsEqual
except:
self.assertItemsEqual = self.assertCountEqual
self.assertItemsEqual(list(error.keys()), ['message', 'task_args', 'task_kwargs', 'traceback'])
self.assertEqual(len(error['task_args']), 0)
self.assertEqual(len(error['task_kwargs']), 0)
traceback_string = '\n'.join(error['traceback'])
self.assertTrue("Exception" in traceback_string)
self.assertTrue("I'm sorry Dave, I'm afraid I can't do that." in traceback_string)
def test_only_create_async_task_creates_task_entry(self):
"""
Test that we don't add a Task entry when we create a new Celery task outside of the create_async_task API.
"""
task = non_async_test_task.apply_async()
result = task.get()
self.assertEquals(result, 42)
self.assertEquals(Task.objects.filter(task_id=task.id).count(), 0)
def test_duplicate_nodes_task(self):
metadata = {'test': True}
task_options = {
'user_id': self.user.pk,
'metadata': metadata
}
ids = []
node_ids = []
for i in range(3, 6):
node_id = '0000000000000000000000000000000' + str(i)
node_ids.append(node_id)
node = ContentNode.objects.get(node_id=node_id)
ids.append(node.pk)
parent_node = ContentNode.objects.get(node_id='00000000000000000000000000000002')
task_args = {
'user_id': self.user.pk,
'channel_id': self.channel.pk,
'node_ids': ids,
'target_parent': parent_node.pk
}
task, task_info = create_async_task('duplicate-nodes', task_options, task_args)
# progress is retrieved dynamically upon calls to get the task info, so
# use an API call rather than checking the db directly for progress.
url = '{}/{}'.format(self.task_url, task_info.id)
response = self.get(url)
assert response.data['status'] == 'SUCCESS', "Task failed, exception: {}".format(response.data['metadata']['error']['traceback'])
self.assertEqual(response.data['status'], 'SUCCESS')
self.assertEqual(response.data['task_type'], 'duplicate-nodes')
self.assertEqual(response.data['metadata']['progress'], 100)
result = response.data['metadata']['result']
self.assertTrue(isinstance(result, list))
parent_node.refresh_from_db()
children = parent_node.get_children()
child_ids = []
for child in children:
child_ids.append(child.source_node_id)
# make sure the changes were actually made to the DB
for node_id in node_ids:
assert node_id in child_ids
# make sure the copies are in the results
for item in result:
assert item['original_source_node_id'] in node_ids
| mit |
botman/botman | tests/Messages/AttachmentTest.php | 593 | <?php
namespace BotMan\BotMan\tests\Messages;
use BotMan\BotMan\Messages\Attachments\Image;
use PHPUnit\Framework\TestCase;
class AttachmentTest extends TestCase
{
/** @test */
public function it_can_set_and_get_extras()
{
//Create an Image
$attachment = new Image('foo');
// Test adding an extra then getting it
$attachment->addExtras('foo', [1, 2, 3]);
$this->assertSame([1, 2, 3], $attachment->getExtras('foo'));
// Test getting a non-existent extra
$this->assertNull($attachment->getExtras('DoesNotExist'));
}
}
| mit |
PaulMcMillan/kismetclient | runclient.py | 702 | #!/usr/bin/env python
"""
This is a trivial example of how to use kismetclient in an application.
"""
from kismetclient import Client as KismetClient
from kismetclient import handlers
from pprint import pprint
import logging
log = logging.getLogger('kismetclient')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
address = ('127.0.0.1', 2501)
k = KismetClient(address)
k.register_handler('TRACKINFO', handlers.print_fields)
def handle_ssid(client, ssid, mac):
print 'ssid spotted: "%s" with mac %s' % (ssid, mac)
k.register_handler('SSID', handle_ssid)
try:
while True:
k.listen()
except KeyboardInterrupt:
pprint(k.protocols)
log.info('Exiting...')
| mit |
next-l/enju_biblio | app/helpers/owns_helper.rb | 53 | module OwnsHelper
include ManifestationsHelper
end
| mit |
juzefwt/cieplo-wlasciwie | src/Kraken/RankingBundle/Entity/NoticePrototype.php | 1086 | <?php
namespace Kraken\RankingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="notice_prototypes")
*/
class NoticePrototype
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Notice", mappedBy="noticePrototype", cascade={"all"})
*/
protected $notices;
/**
* @ORM\Column(type="string")
*/
protected $type;
/**
* @ORM\Column(type="string")
*/
protected $label;
public function __toString()
{
return '['.$this->type.'] '.$this->label;
}
public function getId()
{
return $this->id;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
public function getType()
{
return $this->type;
}
public function setLabel($label)
{
$this->label = $label;
return $this;
}
public function getLabel()
{
return $this->label;
}
}
| mit |
zx648383079/ZoDream.UI | src/js/core/event.ts | 515 | abstract class Eve {
public options: any;
public on(event: string, callback: Function): this {
this.options['on' + event] = callback;
return this;
}
public hasEvent(event: string): boolean {
return this.options.hasOwnProperty('on' + event);
}
public trigger(event: string, ... args: any[]) {
let realEvent = 'on' + event;
if (!this.hasEvent(event)) {
return;
}
return this.options[realEvent].call(this, ...args);
}
} | mit |
drugdev/attribute_extras | test/nullify_attributes_test.rb | 1811 | require 'test_helper'
class NullifyAttributesTest < ActiveSupport::TestCase
def test_nullify_attributes
person = Person.new
person.set_blank_attributes
assert person.nullify_attributes
person_attributes.each do |attribute|
assert_nil person.send(attribute)
end
end
def test_nullify_attributes!
person = Person.new
person.set_blank_attributes
assert person.nullify_attributes!
person_attributes.each do |attribute|
assert_nil person.send(attribute)
end
end
def test_nullified_attributes_inheritance
architect = Architect.new
architect.set_blank_attributes
assert architect.nullify_attributes
architect_attributes.each do |attribute|
assert_nil architect.send(attribute)
end
end
def test_nullified_attributes
assert_equal person_attributes, Person.nullified_attributes.map(&:attribute)
assert_empty Developer.nullified_attributes.map(&:attribute)
assert_equal [:architect_nullified], Architect.nullified_attributes.map(&:attribute)
end
def test_inherited_nullified_attributes
assert_equal person_attributes, Person.inherited_nullified_attributes.map(&:attribute)
assert_equal person_attributes, Developer.inherited_nullified_attributes.map(&:attribute)
assert_equal architect_attributes, Architect.inherited_nullified_attributes.map(&:attribute)
end
private
# a list of the attributes that are nullified on the architect class
def architect_attributes
@architect_attributes ||= ([:architect_nullified] + person_attributes)
end
# a list of the attributes that are nullified on the person class
def person_attributes
@person_attributes ||= [:person_nullified_one, :person_nullified_two, :person_nullified_three, :person_nullified_four]
end
end
| mit |
memorycoin/memorycoin | src/qt/votecoinsdialog.cpp | 11044 | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Copyright (c) 2013-2014 Memorycoin Dev Team
#include "votecoinsdialog.h"
#include "ui_votecoinsdialog.h"
#include "walletmodel.h"
#include "memorycoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "votecoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include <QMessageBox>
#include <QTextDocument>
#include <QScrollBar>
VoteCoinsDialog::VoteCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::VoteCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void VoteCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
VoteCoinsEntry *entry = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
//setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance());
//connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64)));
//connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
VoteCoinsDialog::~VoteCoinsDialog()
{
delete ui;
}
void VoteCoinsDialog::checkSweep(){
if(model->NeedsSweep()){
ui->sendButton->setEnabled(false);
ui->sweepLabel->setVisible(true);
ui->sweepButton->setVisible(true);
}else{
ui->sendButton->setEnabled(true);
ui->sweepLabel->setVisible(false);
ui->sweepButton->setVisible(false);
}
}
void VoteCoinsDialog::sendToRecipients(bool sweep, qint64 sweepFee){
QList<SendCoinsRecipient> recipients;
if(sweep){
//Sweep
SendCoinsRecipient rv;
rv.address =QString::fromStdString(model->getDefaultWalletAddress());
rv.amount = model->getBalance()+model->getUnconfirmedBalance()-sweepFee;
rv.label = "Main Wallet Address";
recipients.append(rv);
//sendToRecipients(recipients);
//Change button states
ui->sendButton->setEnabled(true);
ui->sweepLabel->setVisible(false);
ui->sweepButton->setVisible(false);
}else{
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
VoteCoinsEntry *entry = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
#if QT_VERSION >= 0x050000
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(MemorycoinUnits::formatWithUnit(MemorycoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address));
#else
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(MemorycoinUnits::formatWithUnit(MemorycoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
#endif
}
fNewRecipientAllowed = false;
/*QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}*/
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
if(sweep){
fNewRecipientAllowed = true;
sendToRecipients(true,sendstatus.fee);
break;
}
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(MemorycoinUnits::formatWithUnit(MemorycoinUnits::BTC, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed!"),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void VoteCoinsDialog::on_sweepButton_clicked(){
sendToRecipients(true,0);
}
void VoteCoinsDialog::on_sendButton_clicked()
{
sendToRecipients(false,0);
}
void VoteCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void VoteCoinsDialog::reject()
{
clear();
}
void VoteCoinsDialog::accept()
{
clear();
}
VoteCoinsEntry *VoteCoinsDialog::addEntry()
{
VoteCoinsEntry *entry = new VoteCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(VoteCoinsEntry*)), this, SLOT(removeEntry(VoteCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
//ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
//QScrollBar* bar = ui->scrollArea->verticalScrollBar();
//if(bar)
// bar->setSliderPosition(bar->maximum());
return entry;
}
void VoteCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
VoteCoinsEntry *entry = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
//setupTabChain(0);
}
void VoteCoinsDialog::removeEntry(VoteCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
/*QWidget *VoteCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
VoteCoinsEntry *entry = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}*/
void VoteCoinsDialog::setAddress(const QString &address)
{
VoteCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
VoteCoinsEntry *first = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void VoteCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
VoteCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
VoteCoinsEntry *first = qobject_cast<VoteCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
/*bool VoteCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseMemorycoinURI(uri, &rv))
{
CMemorycoinAddress address(rv.address.toStdString());
if (!address.IsValid())
return false;
pasteEntry(rv);
return true;
}
return false;
}*/
/*void VoteCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(MemorycoinUnits::formatWithUnit(unit, balance));
}
void VoteCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(MemorycoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));
}
}*/
| mit |
erdanieee/imagePicker | node_modules/dmg-builder/out/dmgLicense.d.ts | 260 | /// <reference types="debug" />
import { PackageBuilder } from "builder-util/out/api";
import _debug from "debug";
export declare const debug: _debug.IDebugger;
export declare function addLicenseToDmg(packager: PackageBuilder, dmgPath: string): Promise<void>;
| mit |
asimihsan/masspinger | src/icmp_header.hpp | 3921 | // ---------------------------------------------------------------------------
// Copyright (c) 2011 Asim Ihsan (asim dot ihsan at gmail dot com)
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Based on the ICMP example from the Boost ASIO library, with the following
// copyright header:
//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// ---------------------------------------------------------------------------
#ifndef ICMP_HEADER_HPP
#define ICMP_HEADER_HPP
#include <istream>
#include <ostream>
#include <algorithm>
// ICMP header for both IPv4 and IPv6.
//
// The wire format of an ICMP header is:
//
// 0 8 16 31
// +---------------+---------------+------------------------------+ ---
// | | | | ^
// | type | code | checksum | |
// | | | | |
// +---------------+---------------+------------------------------+ 8 bytes
// | | | |
// | identifier | sequence number | |
// | | | v
// +-------------------------------+------------------------------+ ---
class icmp_header
{
public:
enum { echo_reply = 0, destination_unreachable = 3, source_quench = 4,
redirect = 5, echo_request = 8, time_exceeded = 11, parameter_problem = 12,
timestamp_request = 13, timestamp_reply = 14, info_request = 15,
info_reply = 16, address_request = 17, address_reply = 18 };
icmp_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); }
unsigned char type() const { return rep_[0]; }
unsigned char code() const { return rep_[1]; }
unsigned short checksum() const { return decode(2, 3); }
unsigned short identifier() const { return decode(4, 5); }
unsigned short sequence_number() const { return decode(6, 7); }
void type(unsigned char n) { rep_[0] = n; }
void code(unsigned char n) { rep_[1] = n; }
void checksum(unsigned short n) { encode(2, 3, n); }
void identifier(unsigned short n) { encode(4, 5, n); }
void sequence_number(unsigned short n) { encode(6, 7, n); }
friend std::istream& operator>>(std::istream& is, icmp_header& header)
{ return is.read(reinterpret_cast<char*>(header.rep_), 8); }
friend std::ostream& operator<<(std::ostream& os, const icmp_header& header)
{ return os.write(reinterpret_cast<const char*>(header.rep_), 8); }
private:
unsigned short decode(int a, int b) const
{ return (rep_[a] << 8) + rep_[b]; }
void encode(int a, int b, unsigned short n)
{
rep_[a] = static_cast<unsigned char>(n >> 8);
rep_[b] = static_cast<unsigned char>(n & 0xFF);
}
unsigned char rep_[8];
};
template <typename Iterator>
void compute_checksum(icmp_header& header,
Iterator body_begin, Iterator body_end)
{
unsigned int sum = (header.type() << 8) + header.code()
+ header.identifier() + header.sequence_number();
Iterator body_iter = body_begin;
while (body_iter != body_end)
{
sum += (static_cast<unsigned char>(*body_iter++) << 8);
if (body_iter != body_end)
sum += static_cast<unsigned char>(*body_iter++);
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
header.checksum(static_cast<unsigned short>(~sum));
}
#endif // ICMP_HEADER_HPP
| mit |
oozcitak/XCOM | XCOM/XCOM/ActionForms/PurgeAllForm.Designer.cs | 24016 | namespace XCOM.Commands.XCommand
{
partial class PurgeAllForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdOK = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.cbSectionViewStyles = new System.Windows.Forms.CheckBox();
this.cbDetailViewStyles = new System.Windows.Forms.CheckBox();
this.cbVisualStyles = new System.Windows.Forms.CheckBox();
this.cbViews = new System.Windows.Forms.CheckBox();
this.cbViewports = new System.Windows.Forms.CheckBox();
this.cbUCSSettings = new System.Windows.Forms.CheckBox();
this.cbTextStyles = new System.Windows.Forms.CheckBox();
this.cbTableStyles = new System.Windows.Forms.CheckBox();
this.cbShapes = new System.Windows.Forms.CheckBox();
this.cbPlotStyles = new System.Windows.Forms.CheckBox();
this.cbMultileaderStyles = new System.Windows.Forms.CheckBox();
this.cbMlineStyles = new System.Windows.Forms.CheckBox();
this.cbMaterials = new System.Windows.Forms.CheckBox();
this.cbLinetypes = new System.Windows.Forms.CheckBox();
this.cbLayers = new System.Windows.Forms.CheckBox();
this.cbGroups = new System.Windows.Forms.CheckBox();
this.cbDimensionStyles = new System.Windows.Forms.CheckBox();
this.cbBlocks = new System.Windows.Forms.CheckBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.cbZeroLengthGeometry = new System.Windows.Forms.CheckBox();
this.cbEmptyTexts = new System.Windows.Forms.CheckBox();
this.cbRegApps = new System.Windows.Forms.CheckBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.btnCheckAll = new System.Windows.Forms.Button();
this.btnUncheckAll = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// cmdCancel
//
this.cmdCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cmdCancel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.cmdCancel.Location = new System.Drawing.Point(279, 392);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.Size = new System.Drawing.Size(75, 23);
this.cmdCancel.TabIndex = 6;
this.cmdCancel.Text = "İptal";
this.cmdCancel.UseVisualStyleBackColor = true;
this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
//
// cmdOK
//
this.cmdOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOK.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.cmdOK.Location = new System.Drawing.Point(198, 392);
this.cmdOK.Name = "cmdOK";
this.cmdOK.Size = new System.Drawing.Size(75, 23);
this.cmdOK.TabIndex = 5;
this.cmdOK.Text = "Tamam";
this.cmdOK.UseVisualStyleBackColor = true;
this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.cbSectionViewStyles);
this.groupBox1.Controls.Add(this.cbDetailViewStyles);
this.groupBox1.Controls.Add(this.cbVisualStyles);
this.groupBox1.Controls.Add(this.cbViews);
this.groupBox1.Controls.Add(this.cbViewports);
this.groupBox1.Controls.Add(this.cbUCSSettings);
this.groupBox1.Controls.Add(this.cbTextStyles);
this.groupBox1.Controls.Add(this.cbTableStyles);
this.groupBox1.Controls.Add(this.cbShapes);
this.groupBox1.Controls.Add(this.cbPlotStyles);
this.groupBox1.Controls.Add(this.cbMultileaderStyles);
this.groupBox1.Controls.Add(this.cbMlineStyles);
this.groupBox1.Controls.Add(this.cbMaterials);
this.groupBox1.Controls.Add(this.cbLinetypes);
this.groupBox1.Controls.Add(this.cbLayers);
this.groupBox1.Controls.Add(this.cbGroups);
this.groupBox1.Controls.Add(this.cbDimensionStyles);
this.groupBox1.Controls.Add(this.cbBlocks);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(340, 273);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Çizim Veritabanı";
//
// cbSectionViewStyles
//
this.cbSectionViewStyles.AutoSize = true;
this.cbSectionViewStyles.Checked = true;
this.cbSectionViewStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbSectionViewStyles.Location = new System.Drawing.Point(193, 240);
this.cbSectionViewStyles.Name = "cbSectionViewStyles";
this.cbSectionViewStyles.Size = new System.Drawing.Size(116, 17);
this.cbSectionViewStyles.TabIndex = 17;
this.cbSectionViewStyles.Text = "Section view styles";
this.cbSectionViewStyles.UseVisualStyleBackColor = true;
//
// cbDetailViewStyles
//
this.cbDetailViewStyles.AutoSize = true;
this.cbDetailViewStyles.Checked = true;
this.cbDetailViewStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbDetailViewStyles.Location = new System.Drawing.Point(193, 217);
this.cbDetailViewStyles.Name = "cbDetailViewStyles";
this.cbDetailViewStyles.Size = new System.Drawing.Size(107, 17);
this.cbDetailViewStyles.TabIndex = 16;
this.cbDetailViewStyles.Text = "Detail view styles";
this.cbDetailViewStyles.UseVisualStyleBackColor = true;
//
// cbVisualStyles
//
this.cbVisualStyles.AutoSize = true;
this.cbVisualStyles.Checked = true;
this.cbVisualStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbVisualStyles.Location = new System.Drawing.Point(193, 171);
this.cbVisualStyles.Name = "cbVisualStyles";
this.cbVisualStyles.Size = new System.Drawing.Size(83, 17);
this.cbVisualStyles.TabIndex = 15;
this.cbVisualStyles.Text = "Visual styles";
this.cbVisualStyles.UseVisualStyleBackColor = true;
//
// cbViews
//
this.cbViews.AutoSize = true;
this.cbViews.Checked = true;
this.cbViews.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbViews.Location = new System.Drawing.Point(193, 148);
this.cbViews.Name = "cbViews";
this.cbViews.Size = new System.Drawing.Size(54, 17);
this.cbViews.TabIndex = 14;
this.cbViews.Text = "Views";
this.cbViews.UseVisualStyleBackColor = true;
//
// cbViewports
//
this.cbViewports.AutoSize = true;
this.cbViewports.Checked = true;
this.cbViewports.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbViewports.Location = new System.Drawing.Point(193, 125);
this.cbViewports.Name = "cbViewports";
this.cbViewports.Size = new System.Drawing.Size(72, 17);
this.cbViewports.TabIndex = 13;
this.cbViewports.Text = "Viewports";
this.cbViewports.UseVisualStyleBackColor = true;
//
// cbUCSSettings
//
this.cbUCSSettings.AutoSize = true;
this.cbUCSSettings.Checked = true;
this.cbUCSSettings.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbUCSSettings.Location = new System.Drawing.Point(193, 102);
this.cbUCSSettings.Name = "cbUCSSettings";
this.cbUCSSettings.Size = new System.Drawing.Size(87, 17);
this.cbUCSSettings.TabIndex = 12;
this.cbUCSSettings.Text = "UCS settings";
this.cbUCSSettings.UseVisualStyleBackColor = true;
//
// cbTextStyles
//
this.cbTextStyles.AutoSize = true;
this.cbTextStyles.Checked = true;
this.cbTextStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbTextStyles.Location = new System.Drawing.Point(19, 240);
this.cbTextStyles.Name = "cbTextStyles";
this.cbTextStyles.Size = new System.Drawing.Size(76, 17);
this.cbTextStyles.TabIndex = 9;
this.cbTextStyles.Text = "Text styles";
this.cbTextStyles.UseVisualStyleBackColor = true;
//
// cbTableStyles
//
this.cbTableStyles.AutoSize = true;
this.cbTableStyles.Checked = true;
this.cbTableStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbTableStyles.Location = new System.Drawing.Point(19, 217);
this.cbTableStyles.Name = "cbTableStyles";
this.cbTableStyles.Size = new System.Drawing.Size(82, 17);
this.cbTableStyles.TabIndex = 8;
this.cbTableStyles.Text = "Table styles";
this.cbTableStyles.UseVisualStyleBackColor = true;
//
// cbShapes
//
this.cbShapes.AutoSize = true;
this.cbShapes.Checked = true;
this.cbShapes.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbShapes.Location = new System.Drawing.Point(193, 56);
this.cbShapes.Name = "cbShapes";
this.cbShapes.Size = new System.Drawing.Size(62, 17);
this.cbShapes.TabIndex = 11;
this.cbShapes.Text = "Shapes";
this.cbShapes.UseVisualStyleBackColor = true;
//
// cbPlotStyles
//
this.cbPlotStyles.AutoSize = true;
this.cbPlotStyles.Checked = true;
this.cbPlotStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbPlotStyles.Location = new System.Drawing.Point(193, 33);
this.cbPlotStyles.Name = "cbPlotStyles";
this.cbPlotStyles.Size = new System.Drawing.Size(73, 17);
this.cbPlotStyles.TabIndex = 10;
this.cbPlotStyles.Text = "Plot styles";
this.cbPlotStyles.UseVisualStyleBackColor = true;
//
// cbMultileaderStyles
//
this.cbMultileaderStyles.AutoSize = true;
this.cbMultileaderStyles.Checked = true;
this.cbMultileaderStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbMultileaderStyles.Location = new System.Drawing.Point(19, 194);
this.cbMultileaderStyles.Name = "cbMultileaderStyles";
this.cbMultileaderStyles.Size = new System.Drawing.Size(106, 17);
this.cbMultileaderStyles.TabIndex = 7;
this.cbMultileaderStyles.Text = "Multileader styles";
this.cbMultileaderStyles.UseVisualStyleBackColor = true;
//
// cbMlineStyles
//
this.cbMlineStyles.AutoSize = true;
this.cbMlineStyles.Checked = true;
this.cbMlineStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbMlineStyles.Location = new System.Drawing.Point(19, 171);
this.cbMlineStyles.Name = "cbMlineStyles";
this.cbMlineStyles.Size = new System.Drawing.Size(80, 17);
this.cbMlineStyles.TabIndex = 6;
this.cbMlineStyles.Text = "Mline styles";
this.cbMlineStyles.UseVisualStyleBackColor = true;
//
// cbMaterials
//
this.cbMaterials.AutoSize = true;
this.cbMaterials.Checked = true;
this.cbMaterials.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbMaterials.Location = new System.Drawing.Point(19, 148);
this.cbMaterials.Name = "cbMaterials";
this.cbMaterials.Size = new System.Drawing.Size(68, 17);
this.cbMaterials.TabIndex = 5;
this.cbMaterials.Text = "Materials";
this.cbMaterials.UseVisualStyleBackColor = true;
//
// cbLinetypes
//
this.cbLinetypes.AutoSize = true;
this.cbLinetypes.Checked = true;
this.cbLinetypes.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbLinetypes.Location = new System.Drawing.Point(19, 125);
this.cbLinetypes.Name = "cbLinetypes";
this.cbLinetypes.Size = new System.Drawing.Size(71, 17);
this.cbLinetypes.TabIndex = 4;
this.cbLinetypes.Text = "Linetypes";
this.cbLinetypes.UseVisualStyleBackColor = true;
//
// cbLayers
//
this.cbLayers.AutoSize = true;
this.cbLayers.Checked = true;
this.cbLayers.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbLayers.Location = new System.Drawing.Point(19, 102);
this.cbLayers.Name = "cbLayers";
this.cbLayers.Size = new System.Drawing.Size(57, 17);
this.cbLayers.TabIndex = 3;
this.cbLayers.Text = "Layers";
this.cbLayers.UseVisualStyleBackColor = true;
//
// cbGroups
//
this.cbGroups.AutoSize = true;
this.cbGroups.Checked = true;
this.cbGroups.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbGroups.Location = new System.Drawing.Point(19, 79);
this.cbGroups.Name = "cbGroups";
this.cbGroups.Size = new System.Drawing.Size(60, 17);
this.cbGroups.TabIndex = 2;
this.cbGroups.Text = "Groups";
this.cbGroups.UseVisualStyleBackColor = true;
//
// cbDimensionStyles
//
this.cbDimensionStyles.AutoSize = true;
this.cbDimensionStyles.Checked = true;
this.cbDimensionStyles.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbDimensionStyles.Location = new System.Drawing.Point(19, 56);
this.cbDimensionStyles.Name = "cbDimensionStyles";
this.cbDimensionStyles.Size = new System.Drawing.Size(104, 17);
this.cbDimensionStyles.TabIndex = 1;
this.cbDimensionStyles.Text = "Dimension styles";
this.cbDimensionStyles.UseVisualStyleBackColor = true;
//
// cbBlocks
//
this.cbBlocks.AutoSize = true;
this.cbBlocks.Checked = true;
this.cbBlocks.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbBlocks.Location = new System.Drawing.Point(19, 33);
this.cbBlocks.Name = "cbBlocks";
this.cbBlocks.Size = new System.Drawing.Size(58, 17);
this.cbBlocks.TabIndex = 0;
this.cbBlocks.Text = "Blocks";
this.cbBlocks.UseVisualStyleBackColor = true;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.cbZeroLengthGeometry);
this.groupBox2.Controls.Add(this.cbEmptyTexts);
this.groupBox2.Location = new System.Drawing.Point(12, 291);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(167, 85);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Çizim Nesneleri";
//
// cbZeroLengthGeometry
//
this.cbZeroLengthGeometry.AutoSize = true;
this.cbZeroLengthGeometry.Checked = true;
this.cbZeroLengthGeometry.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbZeroLengthGeometry.Location = new System.Drawing.Point(19, 29);
this.cbZeroLengthGeometry.Name = "cbZeroLengthGeometry";
this.cbZeroLengthGeometry.Size = new System.Drawing.Size(126, 17);
this.cbZeroLengthGeometry.TabIndex = 0;
this.cbZeroLengthGeometry.Text = "Sıfır uzunluklu çizgiler";
this.cbZeroLengthGeometry.UseVisualStyleBackColor = true;
//
// cbEmptyTexts
//
this.cbEmptyTexts.AutoSize = true;
this.cbEmptyTexts.Checked = true;
this.cbEmptyTexts.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbEmptyTexts.Location = new System.Drawing.Point(19, 52);
this.cbEmptyTexts.Name = "cbEmptyTexts";
this.cbEmptyTexts.Size = new System.Drawing.Size(139, 17);
this.cbEmptyTexts.TabIndex = 1;
this.cbEmptyTexts.Text = "İçeriği boş text nesneleri";
this.cbEmptyTexts.UseVisualStyleBackColor = true;
//
// cbRegApps
//
this.cbRegApps.AutoSize = true;
this.cbRegApps.Checked = true;
this.cbRegApps.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbRegApps.Location = new System.Drawing.Point(20, 29);
this.cbRegApps.Name = "cbRegApps";
this.cbRegApps.Size = new System.Drawing.Size(70, 17);
this.cbRegApps.TabIndex = 0;
this.cbRegApps.Text = "RegApps";
this.cbRegApps.UseVisualStyleBackColor = true;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.cbRegApps);
this.groupBox3.Location = new System.Drawing.Point(185, 291);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(167, 85);
this.groupBox3.TabIndex = 2;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Diğer Seçenekler";
//
// btnCheckAll
//
this.btnCheckAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnCheckAll.Image = global::XCOM.Properties.Resources.lightbulb;
this.btnCheckAll.Location = new System.Drawing.Point(12, 392);
this.btnCheckAll.Name = "btnCheckAll";
this.btnCheckAll.Size = new System.Drawing.Size(23, 23);
this.btnCheckAll.TabIndex = 3;
this.btnCheckAll.UseVisualStyleBackColor = true;
this.btnCheckAll.Click += new System.EventHandler(this.btnCheckAll_Click);
//
// btnUncheckAll
//
this.btnUncheckAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnUncheckAll.Image = global::XCOM.Properties.Resources.lightbulb_off;
this.btnUncheckAll.Location = new System.Drawing.Point(34, 392);
this.btnUncheckAll.Name = "btnUncheckAll";
this.btnUncheckAll.Size = new System.Drawing.Size(23, 23);
this.btnUncheckAll.TabIndex = 4;
this.btnUncheckAll.UseVisualStyleBackColor = true;
this.btnUncheckAll.Click += new System.EventHandler(this.btnUncheckAll_Click);
//
// PurgeAllForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.cmdCancel;
this.ClientSize = new System.Drawing.Size(366, 427);
this.Controls.Add(this.btnUncheckAll);
this.Controls.Add(this.btnCheckAll);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.cmdCancel);
this.Controls.Add(this.cmdOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PurgeAllForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Purge All";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button cmdCancel;
private System.Windows.Forms.Button cmdOK;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox cbBlocks;
private System.Windows.Forms.CheckBox cbTextStyles;
private System.Windows.Forms.CheckBox cbTableStyles;
private System.Windows.Forms.CheckBox cbShapes;
private System.Windows.Forms.CheckBox cbPlotStyles;
private System.Windows.Forms.CheckBox cbMultileaderStyles;
private System.Windows.Forms.CheckBox cbMlineStyles;
private System.Windows.Forms.CheckBox cbMaterials;
private System.Windows.Forms.CheckBox cbLinetypes;
private System.Windows.Forms.CheckBox cbLayers;
private System.Windows.Forms.CheckBox cbGroups;
private System.Windows.Forms.CheckBox cbDimensionStyles;
private System.Windows.Forms.CheckBox cbUCSSettings;
private System.Windows.Forms.CheckBox cbViews;
private System.Windows.Forms.CheckBox cbViewports;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.CheckBox cbZeroLengthGeometry;
private System.Windows.Forms.CheckBox cbEmptyTexts;
private System.Windows.Forms.CheckBox cbRegApps;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Button btnCheckAll;
private System.Windows.Forms.Button btnUncheckAll;
private System.Windows.Forms.CheckBox cbVisualStyles;
private System.Windows.Forms.CheckBox cbDetailViewStyles;
private System.Windows.Forms.CheckBox cbSectionViewStyles;
}
} | mit |
dhenson02/fan2c | src/js/Components/Player/PlayerInfo.js | 322 | 'use strict';
import React from 'react';
class PlayerInfo extends React.Component {
constructor ( props ) {
super(props);
this.state = {};
}
render () {
return (
<div>
<h2>PLAYER INFO</h2>
</div>
);
}
}
export default PlayerInfo;
| mit |
callant/CharacterLCD | CharacterLCD/CharacterLCD.AllJoynServer/ViewModel/MainViewModel.cs | 3687 | using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Windows.Input;
using Windows.Devices.AllJoyn;
using Callant;
using Windows.ApplicationModel.Core;
using System;
namespace CharacterLCD.AllJoynServer.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
////if (IsInDesignMode)
////{
//// // Code runs in Blend --> create design time data.
////}
////else
////{
//// // Code runs "for real"
////}
}
private string _status = "Not running";
public string Status
{
get { return _status; }
set { Set("Status", ref _status, value); }
}
private CharacterLCDProducer _producer;
public CharacterLCDProducer Producer
{
get { return _producer; }
set { Set("Producer", ref _producer, value); }
}
public ICommand StartServer { get { return new RelayCommand(Start); } }
public ICommand StopServer { get { return new RelayCommand(Stop); } }
public void Start()
{
CharacterLCDProducer p = new CharacterLCDProducer(new AllJoynBusAttachment());
p.Service = new CharacterLCDService();
Producer = p;
Producer.Start();
Producer.SessionLost += Producer_SessionLost;
Producer.SessionMemberAdded += Producer_SessionMemberAdded;
Producer.SessionMemberRemoved += Producer_SessionMemberRemoved;
Producer.Stopped += Producer_Stopped;
Status = "Running";
}
public void Stop()
{
Producer.Stop();
Status = "Not running";
}
private async void Producer_Stopped(CharacterLCDProducer sender, AllJoynProducerStoppedEventArgs args)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Status = "Stoped!";
});
}
private async void Producer_SessionMemberRemoved(CharacterLCDProducer sender, AllJoynSessionMemberRemovedEventArgs args)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Status = "Session member removed!";
});
}
private async void Producer_SessionMemberAdded(CharacterLCDProducer sender, AllJoynSessionMemberAddedEventArgs args)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Status = "Session member added!";
});
}
private async void Producer_SessionLost(CharacterLCDProducer sender, AllJoynSessionLostEventArgs args)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Status = "Session lost!";
});
}
}
} | mit |
stackdump/txbitwrap | txbitwrap/api/headers.py | 1108 | """ share headers accross resources """
import os
_ALLOW = os.environ.get('ALLOW_ORIGIN', '*')
class Mixin(object):
""" set default api headers """
def options(self, *args, **kwargs):
""" allow cors """
pass
def set_default_headers(self):
""" allow cors """
self.set_header('Content-Type', 'application/json')
self.set_header('Access-Control-Allow-Origin', _ALLOW)
self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
self.set_header('Access-Control-Allow-Methods', 'GET')
class PostMixin(object):
""" set headers for handlers that support post """
def options(self, *args, **kwargs):
""" allow cors """
pass
def set_default_headers(self):
""" allow cors """
self.set_header('Content-Type', 'application/json')
self.set_header('Access-Control-Allow-Origin', _ALLOW)
self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
self.set_header('Access-Control-Allow-Methods', 'POST')
| mit |
CS2103JAN2017-W13-B2/main | src/test/java/guitests/UndoCommandTest.java | 3024 | //@@author A0143504R
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.address.commons.core.Messages;
import seedu.address.logic.commands.ClearCommand;
import seedu.address.logic.commands.DeleteCommand;
import seedu.address.logic.commands.EditCommand;
import seedu.address.logic.commands.MarkCommand;
import seedu.address.logic.commands.UndoCommand;
import seedu.address.testutil.TestTask;
public class UndoCommandTest extends TaskManagerGuiTest {
private TestTask[] expectedList = td.getTypicalTasks();
/**
* Tries to undo an add command
*/
@Test
public void undo_addCommand() {
TestTask taskToAdd = td.alice;
commandBox.runCommand(taskToAdd.getAddCommand());
assertUndoSuccess(expectedList);
}
/**
* Tries to undo a delete command
*/
@Test
public void undo_deleteCommand() {
int targetIndex = 1;
commandBox.runCommand(DeleteCommand.COMMAND_WORD + " " + targetIndex);
assertUndoSuccess(expectedList);
}
/**
* Tries to undo a clear command
*/
@Test
public void undo_clearCommand() {
commandBox.runCommand("mark 1");
commandBox.runCommand("mark 2");
commandBox.runCommand(ClearCommand.COMMAND_WORD + " done");
expectedList[0].setStatus("done");
expectedList[0].setStatus("done");
assertUndoSuccess(expectedList);
}
/**
* Tries to undo a mark command
*/
@Test
public void undo_markCommand() {
int targetIndex = 1;
commandBox.runCommand(MarkCommand.COMMAND_WORD + " " + 1);
expectedList[targetIndex - 1].setStatus("Done");
assertUndoSuccess(expectedList);
}
/**
* Tries to undo an edit command
*/
@Test
public void undo_editCommand() {
int targetIndex = 1;
String detailsToEdit = "Bobby";
commandBox.runCommand(EditCommand.COMMAND_WORD + " " + targetIndex + " " + detailsToEdit);
assertUndoSuccess(expectedList);
}
/**
* Tries to undo a command with an invalid command word
*/
@Test
public void undo_invalidCommand_fail() {
commandBox.runCommand("undoo");
assertResultMessage(String.format(Messages.MESSAGE_UNKNOWN_COMMAND));
}
/**
* Tries to undo a command without any previous commands
*/
@Test
public void undo_noChange_fail() {
commandBox.runCommand(UndoCommand.COMMAND_WORD);
assertResultMessage(String.format(UndoCommand.MESSAGE_NO_CHANGE));
}
/**
* Runs undo command and checks whether the current list matches the expected list
* @param expectedList list after undo command is carried out
*/
private void assertUndoSuccess(TestTask[] expectedList) {
commandBox.runCommand(UndoCommand.COMMAND_WORD);
assertTrue(taskListPanel.isListMatching(expectedList));
assertResultMessage(String.format(UndoCommand.MESSAGE_SUCCESS));
}
}
| mit |
psionin/smartcoin | src/qt/locale/bitcoin_af.ts | 32125 | <TS language="af" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Regs-kliek om die adres of etiket te verander</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Skep 'n nuwe adres</translation>
</message>
<message>
<source>&New</source>
<translation>&Nuut</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Dupliseer die geselekteerde adres na die sisteem se geheuebord</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Dupliseer</translation>
</message>
<message>
<source>C&lose</source>
<translation>S&luit</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Verwyder die adres wat u gekies het van die lys</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Voer die inligting op hierdie bladsy uit na 'n leer</translation>
</message>
<message>
<source>&Export</source>
<translation>&Voer uit</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Vee uit</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Kies die adres waarheen u munte wil stuur</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Kies die adres wat die munte moet ontvang</translation>
</message>
<message>
<source>C&hoose</source>
<translation>K&ies</translation>
</message>
<message>
<source>Such sending addresses</source>
<translation>Stuurders adresse</translation>
</message>
<message>
<source>Much receiving addresses</source>
<translation>Ontvanger adresse</translation>
</message>
<message>
<source>These are your Smartcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Hierdie is die adresse vanwaar u Smartcoin betalings stuur. U moet altyd die bedrag en die adres van die ontvanger nagaan voordat u enige munte stuur.</translation>
</message>
<message>
<source>These are your Smartcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Hierdie is die adresse waar u Smartcoins sal ontvang. Ons beveel aan dat u 'n nuwe adres kies vir elke transaksie</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Dupliseer Adres</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Kopieer &Etiket</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Verander</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Voer adreslys uit</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Uitvoer was onsuksesvol</translation>
</message>
<message>
<source>There was an error trying to save the address list to %1. Please try again.</source>
<translation>Die adreslys kon nie in %1 gestoor word nie. Probeer asseblief weer.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Merk</translation>
</message>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Wagwoord Dialoog</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Tik u wagwoord in</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Nuwe wagwoord</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Herhaal nuwe wagwoord</translation>
</message>
<message>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Tik die nuwe wagwoord vir u beursie.<br/>Gerbuik asseblief 'n wagwoord met <b>tien of meer lukrake karakters</b>, of <b>agt of meer woorde</b>.</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Kodifiseer beursie</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>U het u beursie se wagwoord nodig om toegang tot u beursie te verkry.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Sluit beursie oop</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>U het u beursie se wagwoord nodig om u beursie se kode te ontsyfer.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Ontsleutel beursie</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Verander wagwoord</translation>
</message>
<message>
<source>Enter the old passphrase and new passphrase to the wallet.</source>
<translation>Tik die ou en die nuwe wagwoorde vir die beursie.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Bevestig dat die beursie gekodifiseer is</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SMARTCOINS</b>!</source>
<translation>Waarskuwing: Indien u die beursie kodifiseer en u vergeet u wagwoord <b>VERLOOR U AL U SMARTCOINS</b>!</translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Is u seker dat u die beursie wil kodifiseer?</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Beursie gekodifiseer</translation>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>BELANGRIK: Alle vorige kopieë en rugsteun-weergawes wat u tevore van die gemaak het, moet vervang word met die jongste weergawe van u nuutste gekodifiseerde beursie. Alle vorige weergawes en rugsteun-kopieë van u beursie sal nutteloos raak die oomblik wat u die nuut-gekodifiseerde beursie begin gebruik.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Kodifikasie was onsuksesvol</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Weens 'n interne fout het kodifikasie het nie geslaag nie. U beursie is nie gekodifiseer nie</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Die wagwoorde stem nie ooreen nie.</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Die beursie is nie oopgesluit nie</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>U het die verkeerde wagwoord ingetik.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Beursie-dekripsie het misluk</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Beursie wagwoordfrase is suksesvol verander.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>WAARSKUWING: Outomatiese Kapitalisering is aktief op u sleutelbord!</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
<message>
<source>IP/Netmask</source>
<translation>IP/Netmasker</translation>
</message>
<message>
<source>Banned Until</source>
<translation>Verban tot</translation>
</message>
</context>
<context>
<name>SmartcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Teken &boodskap...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Netwerk-sinkronisasie...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Oorsig</translation>
</message>
<message>
<source>Node</source>
<translation>Node</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Vertoon 'n algemene oorsig van die beursie</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Transaksies</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Blaai deur transaksiegeskiedenis</translation>
</message>
<message>
<source>E&xit</source>
<translation>&Sluit</translation>
</message>
<message>
<source>Quit application</source>
<translation>Stop en verlaat die applikasie</translation>
</message>
<message>
<source>&About %1</source>
<translation>&Oor %1</translation>
</message>
<message>
<source>Show information about %1</source>
<translation>Wys inligting oor %1</translation>
</message>
<message>
<source>About &Qt</source>
<translation>Oor &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Wys inligting oor Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Opsies</translation>
</message>
<message>
<source>Modify configuration options for %1</source>
<translation>Verander konfigurasie-opsies vir %1</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Kodifiseer Beursie</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Rugsteun-kopie van Beursie</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&Verander Wagwoord</translation>
</message>
<message>
<source>&Such sending addresses...</source>
<translation>&Versending adresse...</translation>
</message>
<message>
<source>&Much receiving addresses...</source>
<translation>&Ontvanger adresse</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Oop & URI...</translation>
</message>
<message>
<source>Click to disable network activity.</source>
<translation>Kliek om netwerkaktiwiteit af te skakel.</translation>
</message>
<message>
<source>Network activity disabled.</source>
<translation>Netwerkaktiwiteit gedeaktiveer.</translation>
</message>
<message>
<source>Click to enable network activity again.</source>
<translation>Kliek om netwerkaktiwiteit weer aan te skakel.</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Besig met herindeksering van blokke op hardeskyf...</translation>
</message>
<message>
<source>Send coins to a Smartcoin address</source>
<translation>Stuur munte na 'n Smartcoin adres</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Maak 'n rugsteun-kopié van beursie na 'n ander stoorplek</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Verander die wagwoord wat ek vir kodifikasie van my beursie gebruik</translation>
</message>
<message>
<source>&Debug window</source>
<translation>&Ontfout venster</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Maak ontfouting en diagnostiese konsole oop</translation>
</message>
<message>
<source>Smartcoin</source>
<translation>Smartcoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Beursie</translation>
</message>
<message>
<source>&Send</source>
<translation>&Stuur</translation>
</message>
<message>
<source>&Receive</source>
<translation>&Ontvang</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Wys / Versteek</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Wys of versteek die hoofbladsy</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Kodifiseer die private sleutes wat aan jou beursie gekoppel is.</translation>
</message>
<message>
<source>Sign messages with your Smartcoin addresses to prove you own them</source>
<translation>Onderteken boodskappe met u Smartcoin adresse om u eienaarskap te bewys</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Smartcoin addresses</source>
<translation>Verifieër boodskappe om seker te maak dat dit met die gespesifiseerde Smartcoin adresse</translation>
</message>
<message>
<source>&File</source>
<translation>&Leër</translation>
</message>
<message>
<source>&Help</source>
<translation>&Help</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Orebalk</translation>
</message>
<message>
<source>Request payments (generates QR codes and smartcoin: URIs)</source>
<translation>Versoek betalings (genereer QR-kodes en smartcoin: URI's)</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>Vertoon die lys van gebruikte versendingsadresse en etikette</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>Vertoon die lys van gebruikte ontvangers-adresse en etikette</translation>
</message>
<message>
<source>Open a smartcoin: URI or payment request</source>
<translation>Skep 'n smartcoin: URI of betalingsversoek</translation>
</message>
<message>
<source>Indexing blocks on disk...</source>
<translation>Blokke op skyf word geïndekseer...</translation>
</message>
<message>
<source>Processing blocks on disk...</source>
<translation>Blokke op skyf word geprosesseer...</translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 agter</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Laaste ontvange blok is %1 gelede gegenereer.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Transaksies hierna sal nog nie sigbaar wees nie.</translation>
</message>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
<message>
<source>Warning</source>
<translation>Waarskuwing</translation>
</message>
<message>
<source>Information</source>
<translation>Inligting</translation>
</message>
<message>
<source>Up to date</source>
<translation>Op datum</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Word op datum gebring...</translation>
</message>
<message>
<source>Date: %1
</source>
<translation>Datum: %1
</translation>
</message>
<message>
<source>Address: %1
</source>
<translation>Adres: %1
</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Gestuurde transaksie</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Inkomende transaksie</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Bytes:</source>
<translation>Grepe:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Fooi:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Stof:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Na Fooi:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>(de)selekteer alle</translation>
</message>
<message>
<source>List mode</source>
<translation>Lysmodus</translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Bevestigings</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Bevestig</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Wysig Adres</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>name</source>
<translation>naam</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>weergawe</translation>
</message>
<message>
<source>About %1</source>
<translation>Ongeveer %1</translation>
</message>
<message>
<source>UI Options:</source>
<translation>Gebruikerkoppelvlakopsies:</translation>
</message>
<message>
<source>Start minimized</source>
<translation>Begin geminimeer</translation>
</message>
<message>
<source>Reset all settings changed in the GUI</source>
<translation>Alle instellings wat in die grafiese gebruikerkoppelvlak gewysig is, terugstel</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Welkom</translation>
</message>
<message>
<source>Welcome to %1.</source>
<translation>Welkom by %1.</translation>
</message>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
<message>
<source>Hide</source>
<translation>Versteek</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Opsies</translation>
</message>
<message>
<source>MB</source>
<translation>MG</translation>
</message>
<message>
<source>Accept connections from outside</source>
<translation>Verbindings van buite toelaat</translation>
</message>
<message>
<source>Allow incoming connections</source>
<translation>Inkomende verbindings toelaat</translation>
</message>
<message>
<source>Reset all client options to default.</source>
<translation>Alle kliëntopsies na verstek terugstel.</translation>
</message>
<message>
<source>Expert</source>
<translation>Kenner</translation>
</message>
<message>
<source>IPv6</source>
<translation>IPv6</translation>
</message>
<message>
<source>Tor</source>
<translation>Tor</translation>
</message>
<message>
<source>default</source>
<translation>verstek</translation>
</message>
<message>
<source>none</source>
<translation>geen</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Bevestig terugstel van opsies</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>Kliënt moet herbegin word om veranderinge te aktiveer.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Available:</source>
<translation>Beskikbaar:</translation>
</message>
<message>
<source>Pending:</source>
<translation>Hangend:</translation>
</message>
<message>
<source>Immature:</source>
<translation>Onvolwasse:</translation>
</message>
<message>
<source>Balances</source>
<translation>Balanse</translation>
</message>
<message>
<source>Total:</source>
<translation>Totaal:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>U huidige totale balans</translation>
</message>
<message>
<source>Spendable:</source>
<translation>Besteebaar:</translation>
</message>
<message>
<source>Recent transactions</source>
<translation>Onlangse transaksies</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>User Agent</source>
<translation>Gebruikeragent</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>%1 d</source>
<translation>%1 d</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 u</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 m</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 s</translation>
</message>
<message>
<source>None</source>
<translation>Geen</translation>
</message>
<message>
<source>N/A</source>
<translation>n.v.t.</translation>
</message>
<message>
<source>%1 ms</source>
<translation>%1 ms</translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 en %2</translation>
</message>
</context>
<context>
<name>QObject::QObject</name>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>n.v.t.</translation>
</message>
<message>
<source>Client version</source>
<translation>Kliëntweergawe</translation>
</message>
<message>
<source>General</source>
<translation>Algemeen</translation>
</message>
<message>
<source>Network</source>
<translation>Netwerk</translation>
</message>
<message>
<source>Name</source>
<translation>Naam</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Aantal verbindings</translation>
</message>
<message>
<source>Block chain</source>
<translation>Blokketting</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Huidige aantal blokke</translation>
</message>
<message>
<source>Received</source>
<translation>Ontvang</translation>
</message>
<message>
<source>Sent</source>
<translation>Gestuur</translation>
</message>
<message>
<source>Banned peers</source>
<translation>Verbanne porture</translation>
</message>
<message>
<source>Whitelisted</source>
<translation>Gewitlys</translation>
</message>
<message>
<source>Direction</source>
<translation>Rigting</translation>
</message>
<message>
<source>Version</source>
<translation>Weergawe</translation>
</message>
<message>
<source>User Agent</source>
<translation>Gebruikeragent</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>Label</source>
<translation>Merk</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Label</source>
<translation>Merk</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Bytes:</source>
<translation>Grepe:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Fooi:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Na Fooi:</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Transaksiefooi:</translation>
</message>
<message>
<source>Choose...</source>
<translation>Kies...</translation>
</message>
<message>
<source>per kilobyte</source>
<translation>per kilogreep</translation>
</message>
<message>
<source>Hide</source>
<translation>Versteek</translation>
</message>
<message>
<source>total at least</source>
<translation>totaal ten minste</translation>
</message>
<message>
<source>Dust:</source>
<translation>Stof:</translation>
</message>
<message>
<source>Balance:</source>
<translation>Balans:</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
</context>
<context>
<name>SendConfirmationDialog</name>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
</context>
<context>
<name>SplashScreen</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Label</source>
<translation>Merk</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Bevestig</translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Label</source>
<translation>Merk</translation>
</message>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Uitvoer was onsuksesvol</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>&Voer uit</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Voer die inligting op hierdie bladsy uit na 'n leer</translation>
</message>
</context>
<context>
<name>smartcoin-core</name>
<message>
<source>Smartcoin Core</source>
<translation>Smartcoin Kern</translation>
</message>
<message>
<source>Information</source>
<translation>Inligting</translation>
</message>
<message>
<source>Warning</source>
<translation>Waarskuwing</translation>
</message>
<message>
<source>Do not keep transactions in the mempool longer than <n> hours (default: %u)</source>
<translation>Moenie transaksies vir langer as <n> ure in die geheuepoel hou nie (verstek: %u)</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Onvoldoende fondse</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Blokindeks word gelaai...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Beursie word gelaai...</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Word herskandeer...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Klaar met laai</translation>
</message>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
</context>
</TS>
| mit |
martijnhoogendoorn/inkingbehavior | Dev.MartijnHoogendoorn.Inking.Behavior/Converters/SizeToDoubleConverter.cs | 951 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml.Data;
namespace Dev.MartijnHoogendoorn.Inking.Behavior.Converters
{
public class SizeToDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value != null && value is Size)
{
return ((Size)value).Height;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value != null)
{
double val;
if (double.TryParse(value.ToString(), out val))
{
return new Size(val, val);
}
}
return null;
}
}
}
| mit |
stuartcoin/stuartcoin | src/test/getarg_tests.cpp | 4762 | #include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include "util.h"
BOOST_AUTO_TEST_SUITE(getarg_tests)
static void
ResetArgs(const std::string& strArg)
{
std::vector<std::string> vecArg;
boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on);
// Insert dummy executable name:
vecArg.insert(vecArg.begin(), "testbitcoin");
// Convert to char*:
std::vector<const char*> vecChar;
BOOST_FOREACH(std::string& s, vecArg)
vecChar.push_back(s.c_str());
ParseParameters(vecChar.size(), &vecChar[0]);
}
BOOST_AUTO_TEST_CASE(boolarg)
{
ResetArgs("-STC");
BOOST_CHECK(GetBoolArg("-STC"));
BOOST_CHECK(GetBoolArg("-STC", false));
BOOST_CHECK(GetBoolArg("-STC", true));
BOOST_CHECK(!GetBoolArg("-fo"));
BOOST_CHECK(!GetBoolArg("-fo", false));
BOOST_CHECK(GetBoolArg("-fo", true));
BOOST_CHECK(!GetBoolArg("-STCo"));
BOOST_CHECK(!GetBoolArg("-STCo", false));
BOOST_CHECK(GetBoolArg("-STCo", true));
ResetArgs("-STC=0");
BOOST_CHECK(!GetBoolArg("-STC"));
BOOST_CHECK(!GetBoolArg("-STC", false));
BOOST_CHECK(!GetBoolArg("-STC", true));
ResetArgs("-STC=1");
BOOST_CHECK(GetBoolArg("-STC"));
BOOST_CHECK(GetBoolArg("-STC", false));
BOOST_CHECK(GetBoolArg("-STC", true));
// New 0.6 feature: auto-map -nosomething to !-something:
ResetArgs("-noSTC");
BOOST_CHECK(!GetBoolArg("-STC"));
BOOST_CHECK(!GetBoolArg("-STC", false));
BOOST_CHECK(!GetBoolArg("-STC", true));
ResetArgs("-noSTC=1");
BOOST_CHECK(!GetBoolArg("-STC"));
BOOST_CHECK(!GetBoolArg("-STC", false));
BOOST_CHECK(!GetBoolArg("-STC", true));
ResetArgs("-STC -noSTC"); // -STC should win
BOOST_CHECK(GetBoolArg("-STC"));
BOOST_CHECK(GetBoolArg("-STC", false));
BOOST_CHECK(GetBoolArg("-STC", true));
ResetArgs("-STC=1 -noSTC=1"); // -STC should win
BOOST_CHECK(GetBoolArg("-STC"));
BOOST_CHECK(GetBoolArg("-STC", false));
BOOST_CHECK(GetBoolArg("-STC", true));
ResetArgs("-STC=0 -noSTC=0"); // -STC should win
BOOST_CHECK(!GetBoolArg("-STC"));
BOOST_CHECK(!GetBoolArg("-STC", false));
BOOST_CHECK(!GetBoolArg("-STC", true));
// New 0.6 feature: treat -- same as -:
ResetArgs("--STC=1");
BOOST_CHECK(GetBoolArg("-STC"));
BOOST_CHECK(GetBoolArg("-STC", false));
BOOST_CHECK(GetBoolArg("-STC", true));
ResetArgs("--noSTC=1");
BOOST_CHECK(!GetBoolArg("-STC"));
BOOST_CHECK(!GetBoolArg("-STC", false));
BOOST_CHECK(!GetBoolArg("-STC", true));
}
BOOST_AUTO_TEST_CASE(stringarg)
{
ResetArgs("");
BOOST_CHECK_EQUAL(GetArg("-STC", ""), "");
BOOST_CHECK_EQUAL(GetArg("-STC", "eleven"), "eleven");
ResetArgs("-STC -bar");
BOOST_CHECK_EQUAL(GetArg("-STC", ""), "");
BOOST_CHECK_EQUAL(GetArg("-STC", "eleven"), "");
ResetArgs("-STC=");
BOOST_CHECK_EQUAL(GetArg("-STC", ""), "");
BOOST_CHECK_EQUAL(GetArg("-STC", "eleven"), "");
ResetArgs("-STC=11");
BOOST_CHECK_EQUAL(GetArg("-STC", ""), "11");
BOOST_CHECK_EQUAL(GetArg("-STC", "eleven"), "11");
ResetArgs("-STC=eleven");
BOOST_CHECK_EQUAL(GetArg("-STC", ""), "eleven");
BOOST_CHECK_EQUAL(GetArg("-STC", "eleven"), "eleven");
}
BOOST_AUTO_TEST_CASE(intarg)
{
ResetArgs("");
BOOST_CHECK_EQUAL(GetArg("-STC", 11), 11);
BOOST_CHECK_EQUAL(GetArg("-STC", 0), 0);
ResetArgs("-STC -bar");
BOOST_CHECK_EQUAL(GetArg("-STC", 11), 0);
BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
ResetArgs("-STC=11 -bar=12");
BOOST_CHECK_EQUAL(GetArg("-STC", 0), 11);
BOOST_CHECK_EQUAL(GetArg("-bar", 11), 12);
ResetArgs("-STC=NaN -bar=NotANumber");
BOOST_CHECK_EQUAL(GetArg("-STC", 1), 0);
BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
}
BOOST_AUTO_TEST_CASE(doubledash)
{
ResetArgs("--STC");
BOOST_CHECK_EQUAL(GetBoolArg("-STC"), true);
ResetArgs("--STC=verbose --bar=1");
BOOST_CHECK_EQUAL(GetArg("-STC", ""), "verbose");
BOOST_CHECK_EQUAL(GetArg("-bar", 0), 1);
}
BOOST_AUTO_TEST_CASE(boolargno)
{
ResetArgs("-noSTC");
BOOST_CHECK(!GetBoolArg("-STC"));
BOOST_CHECK(!GetBoolArg("-STC", true));
BOOST_CHECK(!GetBoolArg("-STC", false));
ResetArgs("-noSTC=1");
BOOST_CHECK(!GetBoolArg("-STC"));
BOOST_CHECK(!GetBoolArg("-STC", true));
BOOST_CHECK(!GetBoolArg("-STC", false));
ResetArgs("-noSTC=0");
BOOST_CHECK(GetBoolArg("-STC"));
BOOST_CHECK(GetBoolArg("-STC", true));
BOOST_CHECK(GetBoolArg("-STC", false));
ResetArgs("-STC --noSTC");
BOOST_CHECK(GetBoolArg("-STC"));
ResetArgs("-noSTC -STC"); // STC always wins:
BOOST_CHECK(GetBoolArg("-STC"));
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
meoguru/node-oauth2orize-facebook | lib/util.js | 456 | 'use strict';
var request = require('request');
exports.getFacebookProfile = function (accessToken, cb) {
request({
url: 'https://graph.facebook.com/me?access_token=' + accessToken,
json: true
},
function (err, res, body) {
if (err) {
return cb(err);
}
if (body && body.error) {
var msg = body.error.message || 'Could not get Facebook profile.';
return cb(new Error(msg));
}
cb(null, body);
});
};
| mit |
foxostro/CheeseTesseract | external/windows/boost/include/boost/asio/detail/win_thread.hpp | 2864 | //
// win_thread.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_WIN_THREAD_HPP
#define BOOST_ASIO_DETAIL_WIN_THREAD_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/push_options.hpp>
#include <boost/asio/detail/push_options.hpp>
#include <boost/config.hpp>
#include <boost/system/system_error.hpp>
#include <boost/asio/detail/pop_options.hpp>
#if defined(BOOST_WINDOWS) && !defined(UNDER_CE)
#include <boost/asio/error.hpp>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/socket_types.hpp>
#include <boost/asio/detail/push_options.hpp>
#include <boost/throw_exception.hpp>
#include <memory>
#include <process.h>
#include <boost/asio/detail/pop_options.hpp>
namespace boost {
namespace asio {
namespace detail {
unsigned int __stdcall win_thread_function(void* arg);
class win_thread
: private noncopyable
{
public:
// Constructor.
template <typename Function>
win_thread(Function f)
{
std::auto_ptr<func_base> arg(new func<Function>(f));
unsigned int thread_id = 0;
thread_ = reinterpret_cast<HANDLE>(::_beginthreadex(0, 0,
win_thread_function, arg.get(), 0, &thread_id));
if (!thread_)
{
DWORD last_error = ::GetLastError();
boost::system::system_error e(
boost::system::error_code(last_error,
boost::asio::error::get_system_category()),
"thread");
boost::throw_exception(e);
}
arg.release();
}
// Destructor.
~win_thread()
{
::CloseHandle(thread_);
}
// Wait for the thread to exit.
void join()
{
::WaitForSingleObject(thread_, INFINITE);
}
private:
friend unsigned int __stdcall win_thread_function(void* arg);
class func_base
{
public:
virtual ~func_base() {}
virtual void run() = 0;
};
template <typename Function>
class func
: public func_base
{
public:
func(Function f)
: f_(f)
{
}
virtual void run()
{
f_();
}
private:
Function f_;
};
::HANDLE thread_;
};
inline unsigned int __stdcall win_thread_function(void* arg)
{
std::auto_ptr<win_thread::func_base> func(
static_cast<win_thread::func_base*>(arg));
func->run();
return 0;
}
} // namespace detail
} // namespace asio
} // namespace boost
#endif // defined(BOOST_WINDOWS) && !defined(UNDER_CE)
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_DETAIL_WIN_THREAD_HPP
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/twitter-bootstrap/3.0.0-rc2/js/tooltip.min.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:31d71321f51d8e72755aee1cda6dfef47eae0acc69b84b0387aa715fb6664162
size 6505
| mit |
iogav/Partner-Center-Java-SDK | PartnerSdk/src/main/java/com/microsoft/store/partnercenter/models/licenses/LicenseAssignment.java | 1174 | // -----------------------------------------------------------------------
// <copyright file="LicenseAssignment.java" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
package com.microsoft.store.partnercenter.models.licenses;
import com.fasterxml.jackson.annotation.JsonProperty;
/***
* Model for licenses and service plans to be assigned to a user.
*/
public class LicenseAssignment {
/***
* Gets or sets service plan ids which will not be assigned to the user.
*/
@JsonProperty( "ExcludedPlans" )
private Iterable<String> __ExcludedPlans;
public Iterable<String> getExcludedPlans()
{
return __ExcludedPlans;
}
public void setExcludedPlans( Iterable<String> value )
{
__ExcludedPlans = value;
}
/***
* Gets or sets product id to be assigned to the user.
*/
@JsonProperty( "SkuId" )
private String __SkuId;
public String getSkuId()
{
return __SkuId;
}
public void setSkuId( String value )
{
__SkuId = value;
}
}
| mit |
cuhtis/pocket-aces | player.py | 586 | from enum import Enum
class Player():
def __init__(self, name, stack):
self.name = name
self.stack = stack
self.cards = None
self.state = self.State.FOLDED
def __str__(self):
pass
def fold(self):
pass
def check(self):
pass
def call(self):
pass
def raisebet(self, amount):
pass
def stack_gain(self, amount):
pass
def stack_loss(self, amount):
pass
class State(Enum):
OBSERVING = "observing"
PLAYING = "playing"
FOLDED = "folded"
| mit |
smarr/SOMns-vscode | server/org.eclipse.lsp4j-gen/org/eclipse/lsp4j/FileRename.java | 3106 | /**
* Copyright (c) 2016-2018 TypeFox and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0,
* or the Eclipse Distribution License v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.lsp4j;
import org.eclipse.lsp4j.jsonrpc.validation.NonNull;
import org.eclipse.lsp4j.util.Preconditions;
import org.eclipse.xtext.xbase.lib.Pure;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;
/**
* Represents information on a file/folder rename.
* <p>
* Since 3.16.0
*/
@SuppressWarnings("all")
public class FileRename {
/**
* A file:// URI for the original location of the file/folder being renamed.
*/
@NonNull
private String oldUri;
/**
* A file:// URI for the new location of the file/folder being renamed.
*/
@NonNull
private String newUri;
public FileRename() {
}
public FileRename(@NonNull final String oldUri, @NonNull final String newUri) {
this.oldUri = Preconditions.<String>checkNotNull(oldUri, "oldUri");
this.newUri = Preconditions.<String>checkNotNull(newUri, "newUri");
}
/**
* A file:// URI for the original location of the file/folder being renamed.
*/
@Pure
@NonNull
public String getOldUri() {
return this.oldUri;
}
/**
* A file:// URI for the original location of the file/folder being renamed.
*/
public void setOldUri(@NonNull final String oldUri) {
this.oldUri = Preconditions.checkNotNull(oldUri, "oldUri");
}
/**
* A file:// URI for the new location of the file/folder being renamed.
*/
@Pure
@NonNull
public String getNewUri() {
return this.newUri;
}
/**
* A file:// URI for the new location of the file/folder being renamed.
*/
public void setNewUri(@NonNull final String newUri) {
this.newUri = Preconditions.checkNotNull(newUri, "newUri");
}
@Override
@Pure
public String toString() {
ToStringBuilder b = new ToStringBuilder(this);
b.add("oldUri", this.oldUri);
b.add("newUri", this.newUri);
return b.toString();
}
@Override
@Pure
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FileRename other = (FileRename) obj;
if (this.oldUri == null) {
if (other.oldUri != null)
return false;
} else if (!this.oldUri.equals(other.oldUri))
return false;
if (this.newUri == null) {
if (other.newUri != null)
return false;
} else if (!this.newUri.equals(other.newUri))
return false;
return true;
}
@Override
@Pure
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.oldUri== null) ? 0 : this.oldUri.hashCode());
return prime * result + ((this.newUri== null) ? 0 : this.newUri.hashCode());
}
}
| mit |
crowi/crowi | client/components/Backlink.tsx | 3139 | import React from 'react'
import UserPicture from './User/UserPicture'
import Crowi from 'client/util/Crowi'
import { Backlink as BacklinkType, User } from 'client/types/crowi'
interface Props {
crowi: Crowi
pageId: string | null
limit: number
offset: number
}
interface State {
currentOffset: number
hasNext: boolean
backLinks: BacklinkType[]
}
class Backlink extends React.Component<Props, State> {
static defaultProps = {
pageId: null,
limit: 5,
offset: 0,
}
constructor(props: Props) {
super(props)
this.state = {
currentOffset: 0,
hasNext: false,
backLinks: [],
}
}
componentDidMount() {
this.fetchBacklinks()
}
fetchBacklinks() {
this.props.crowi
.apiGet('/backlink.list', {
page_id: this.props.pageId,
limit: this.props.limit + 1,
offset: this.state.currentOffset,
})
.then((response) => {
if (response.ok !== true) {
console.log('Sorry, something went wrong.')
} else {
let hasNext = false
if (response.data.length > this.props.limit) {
hasNext = true
}
const appendBacklinks: BacklinkType[] = response.data.slice(0, this.props.limit)
const backLinks = this.state.backLinks
let i = 0
appendBacklinks.forEach((backLink) => {
const index = this.state.currentOffset + i
backLinks[index] = backLink
i++
})
const currentOffset = this.state.currentOffset + this.props.limit
this.setState({
currentOffset: currentOffset,
hasNext: hasNext,
backLinks: backLinks,
})
}
})
.catch((err) => {
console.log('Failed to fetch data of Backlinks')
// console.log(err);
})
}
handleReadMore(e: React.MouseEvent<HTMLAnchorElement>) {
e.preventDefault()
this.fetchBacklinks()
}
createList(backlink: BacklinkType) {
const path = backlink.fromPage.path
const user = backlink.fromRevision.author
return (
<li className="backlink-item" key={'crowi:page:backlink:' + backlink._id}>
<a className="backlink-link" href={path}>
<span className="backlink-picture">
<UserPicture user={user} />
</span>
<span className="backlink-path">{path}</span>
</a>
</li>
)
}
createReadMore() {
if (this.state.hasNext === true) {
return (
<p className="backlink-readmore">
<a href="#" onClick={(e) => this.handleReadMore(e)}>
Read More Backlinks
</a>
</p>
)
}
return <p />
}
render() {
const lists = this.state.backLinks.map((backLink) => this.createList(backLink))
if (lists.length === 0) {
return null
}
const readMore = this.createReadMore()
return (
<div className="page-meta-contents">
<p className="page-meta-title">Backlinks</p>
<ul className="backlink-list">{lists}</ul>
{readMore}
</div>
)
}
}
export default Backlink
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/yui/3.18.0/uploader-queue/index.js | 127 | version https://git-lfs.github.com/spec/v1
oid sha256:6b1917d1110f34f57204edd1d679fee994fa8c2e8f62497c0d3aa3985b4f5c9b
size 91
| mit |
chester0516/htc-prototype-bak | wip/buy-improvement/Gruntfile.js | 6096 | /*global module:false*/
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-postcss');
grunt.loadNpmTasks('grunt-devtools');
grunt.loadNpmTasks('grunt-targethtml');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-imagemin');
var imageminJpegRecompress = require('imagemin-jpeg-recompress');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
defaultJsPath: '<%= pkg.rootAssetPath %><%= pkg.directories.jsFolder %>',
defaultLessPath: '<%= pkg.rootAssetPath %><%= pkg.directories.lessFolder %>',
defaultCssPath: '<%= pkg.rootAssetPath %><%= pkg.directories.cssFolder %>',
defaultImgPath: '<%= pkg.rootAssetPath %><%= pkg.directories.imageFolder %>',
less: {
fileList: ['buy-improvement.less','fake-header-footer.less'],
development: {
options: {
compress: '<%= compressLess %>',
plugins: [
new(require('less-plugin-rtl'))({
dir: 'LTR'
}),
new(require('less-plugin-autoprefix'))({
browsers: ['> 1%', 'ie 9', 'last 2 versions']
})
]
},
files: [{
expand: true,
src: ['<%= less.fileList %>'],
dest: '<%= defaultCssPath %>',
cwd: '<%= defaultLessPath %>',
ext: '.css',
extDot: 'last'
}]
},
developmentRTL: {
options: {
compress: '<%= compressLess %>',
plugins: [
new(require('less-plugin-rtl'))({
dir: 'RTL'
}),
new(require('less-plugin-autoprefix'))({
browsers: ['> 1%', 'ie 9', 'last 2 versions']
})
]
},
files: [{
expand: true,
src: ['<%= less.fileList %>'],
dest: '<%= defaultCssPath %>',
cwd: '<%= defaultLessPath %>',
ext: '.rtl.css',
extDot: 'last'
}]
},
production: {
options: {
compress: '<%= compressLess %>',
plugins: [
new(require('less-plugin-rtl'))({
dir: 'LTR'
}),
new(require('less-plugin-autoprefix'))({
browsers: ['> 1%', 'ie 9', 'last 2 versions']
})
]
},
files: [{
expand: true,
src: ['<%= less.fileList %>'],
dest: '<%= defaultCssPath %>',
cwd: '<%= defaultLessPath %>',
ext: '.min.css',
extDot: 'last'
}]
},
productionRTL: {
options: {
compress: '<%= compressLess %>',
plugins: [
new(require('less-plugin-rtl'))({
dir: 'RTL'
}),
new(require('less-plugin-autoprefix'))({
browsers: ['> 1%', 'ie 9', 'last 2 versions']
})
]
},
files: [{
expand: true,
src: ['<%= less.fileList %>'],
dest: '<%= defaultCssPath %>',
cwd: '<%= defaultLessPath %>',
ext: '.rtl.min.css',
extDot: 'last'
}]
}
},
uglify: {
production: {
files: {
'<%= defaultJsPath %>buy-improvement.min.js': ['<%= defaultJsPath %>/buy-improvement.js']
}
}
},
targethtml: {
options: {
curlyTags: {
rlsdate: '<%= grunt.template.today("yyyymmdd") %>'
}
},
production: {
files: {
'<%= pkg.destPath %>default.htm': 'default.htm'
}
}
},
imagemin: {
production: {
options: {
use: [imageminJpegRecompress()]
},
files: [{
expand: true,
src: ['<%= defaultImgPath %>*.{png,jpg,gif}'], // Actual patterns to match
dest: '<%= pkg.destPath %>' // Destination path prefix
}]
}
},
copy: {
production: {
expand: true,
src: ['<%= defaultJsPath %>plugins/**', '<%= defaultJsPath %>vendor/**'],
dest: '<%= pkg.destPath %>',
},
},
watch: {
files: ['*.htm', '<%= defaultJsPath %>*', '<%= defaultLessPath %>*', '<%= defaultLessPath %>lib/*'],
tasks: ['less:development', 'less:developmentRTL'],
options: {
livereload: true,
}
}
});
grunt.registerTask('prod', 'production build', function() {
grunt.config.set('compressLess', true);
grunt.task.run(['copy:production', 'uglify:production', 'less:production', 'targethtml:production', 'imagemin:production']);
});
grunt.registerTask('default', 'watch files updated and develop build', function() {
grunt.config.set('compressLess', false);
grunt.task.run(['watch']);
});
} | mit |
gbrammer/pabeta | code/align.py | 15558 | #!/usr/bin/env python
"""
Align to Subaru and/or HST astrometric catalogs.
GBB
"""
import os
import shutil
import numpy as np
import pyfits
import pywcs
#import astropy.wcs as pywcs
#import astropy.io.fits as pyfits
import threedhst
from threedhst import catIO
import pyraf
from pyraf import iraf
def get_align_to_subaru(sci='M0416_Ks_c1_mp_avg.fits', wht='M0416_Ks_c1_mp_exp.fits', field='', clean=True, toler=3, verbose=False, fitgeometry='shift', shift_max=20, rms_max=1.1, rot_max=2, rot_only=True, THRESH=2, align_data=None):
"""
Align HAWK-I images to the FF Subaru astrometric reference catalogs
"""
#sci='M0416_Ks_c1_mp_avg.fits'; wht='M0416_Ks_c1_mp_exp.fits'
### Make object catalog
se = threedhst.sex.SExtractor()
se.aXeParams()
se.copyConvFile()
se.overwrite = True
se.options['CHECKIMAGE_TYPE'] = 'NONE'
if wht is None:
se.options['WEIGHT_TYPE'] = 'NONE'
else:
se.options['WEIGHT_TYPE'] = 'MAP_WEIGHT'
se.options['WEIGHT_IMAGE'] = wht
se.options['FILTER'] = 'Y'
se.options['DETECT_THRESH'] = '%d' %(THRESH)
se.options['ANALYSIS_THRESH'] = '%d' %(THRESH)
se.options['MAG_ZEROPOINT'] = '26.0'
#### Run SExtractor on direct and alignment images
## direct image
se.options['CATALOG_NAME'] = 'direct.cat'
status = se.sextractImage(sci)
threedhst.sex.sexcatRegions('direct.cat', 'direct.reg', format=2)
directCat = threedhst.sex.mySexCat('direct.cat')
#### Get the X/Y coords of the reference catalog
#head = pyfits.getheader(sci, 0)
#wcs = pywcs.WCS(head)
if 'M0416' in sci:
ra_list, dec_list, mag = np.loadtxt(os.getenv('HAWKI')+'/FrontierFields/HST/hlsp_frontier_subaru_suprimecam_macs0416-astrom_R_v1_cat.txt', unpack=True)
if ('c4' in sci):
ra_list, dec_list, mag = np.loadtxt(os.getenv('HAWKI')+'/FrontierFields/HST/M0416/macs0416_f814w_radec.cat', unpack=True)
#
if 'M0717' in sci:
ra_list, dec_list, mag = np.loadtxt('subaru.radec', unpack=True)
if ('M1149' in sci) | (field == 'M1149'):
ra_list, dec_list, mag = np.loadtxt('/Users/brammer/Research/VLT/HAWKI/MACS1149/hlsp_frontier_subaru_suprimecam_macs1149-astrom_R_v1_cat.txt', unpack=True)
if 'A2744' in sci:
ra_list, dec_list, mag = np.loadtxt(os.getenv('HAWKI')+'/FrontierFields/HST/hlsp_frontier_subaru_suprimecam_abell2744-astrom_i_v1_cat.txt', unpack=True)
if ('c1' in sci) | ('c4' in sci):
ra_list, dec_list, mag = np.loadtxt(os.getenv('HAWKI')+'/FrontierFields/HST/abell2744_f814w_radec.cat', unpack=True)
if align_data is not None:
ra_list, dec_list, mag = align_data
im = pyfits.open(sci)
print sci
sh = im[0].shape
head = im[0].header
head['CUNIT1'] = 'deg'; head['CUNIT2'] = 'deg'
wcs = pywcs.WCS(head)
x_image, y_image = wcs.wcs_sky2pix(ra_list, dec_list, 1)
try:
x_image, y_image = wcs.wcs_sky2pix(ra_list, dec_list, 1)
except:
x_image, y_image = wcs.wcs_world2pix(ra_list, dec_list, 1)
ok = (x_image > 0) & (y_image > 0) & (x_image < sh[1]) & (y_image < sh[1])
x_image, y_image = x_image[ok], y_image[ok]
fpr = open('align.reg','w')
fpr.write('image\n')
for i in range(ok.sum()): fpr.write('circle(%.6f, %.6f,0.3") # color=magenta\n' %(x_image[i], y_image[i]))
fpr.close()
# x_image, y_image = [], []
#
# for ra, dec in zip(ra_list, dec_list):
# x, y = wcs.wcs_sky2pix([[ra, dec]], 1)[0]
# if (x > 0) & (y > 0) & (x < sh[1]) & (y < sh[1]):
# x_image.append(x)
# y_image.append(y)
alignCat = catIO.EmptyCat()
alignCat['X_IMAGE'] = np.array(x_image)
alignCat['Y_IMAGE'] = np.array(y_image)
xshift = 0
yshift = 0
rot = 0
scale = 1.
xrms = 2
yrms = 2
NITER = 5
IT = 0
while (IT < NITER):
IT = IT+1
#### Get x,y coordinates of detected objects
## direct image
fp = open('direct.xy','w')
for i in range(len(directCat.X_IMAGE)):
fp.write('%s %s\n' %(directCat.X_IMAGE[i],directCat.Y_IMAGE[i]))
fp.close()
## alignment image
fp = open('align.xy','w')
for i in range(len(alignCat.X_IMAGE)):
fp.write('%s %s\n' %(np.float(alignCat.X_IMAGE[i])+xshift,
np.float(alignCat.Y_IMAGE[i])+yshift))
fp.close()
iraf.flpr()
iraf.flpr()
iraf.flpr()
#### iraf.xyxymatch to find matches between the two catalogs
pow = toler*1.
try:
os.remove('align.match')
except:
pass
status1 = iraf.xyxymatch(input="direct.xy", reference="align.xy",
output="align.match",
tolerance=2**pow, separation=0, verbose=iraf.yes, Stdout=1)
nmatch = 0
while status1[-1].startswith('0') | (nmatch < 10) | (float(status1[-3].split()[1]) > 40):
pow+=1
os.remove('align.match')
status1 = iraf.xyxymatch(input="direct.xy", reference="align.xy",
output="align.match",
tolerance=2**pow, separation=0, verbose=iraf.yes, Stdout=1)
#
nmatch = 0
for line in open('align.match').xreadlines( ): nmatch += 1
if verbose:
for line in status1:
print line
#### Compute shifts with iraf.geomap
iraf.flpr()
iraf.flpr()
iraf.flpr()
try:
os.remove("align.map")
except:
pass
status2 = iraf.geomap(input="align.match", database="align.map",
fitgeometry=fitgeometry, interactive=iraf.no,
xmin=iraf.INDEF, xmax=iraf.INDEF, ymin=iraf.INDEF, ymax=iraf.INDEF,
maxiter = 10, reject = 2.0, Stdout=1)
if verbose:
for line in status2:
print line
#fp = open(root+'.iraf.log','a')
#fp.writelines(status1)
#fp.writelines(status2)
#fp.close()
#### Parse geomap.output
fp = open("align.map","r")
for line in fp.readlines():
spl = line.split()
if spl[0].startswith('xshift'):
xshift += float(spl[1])
if spl[0].startswith('yshift'):
yshift += float(spl[1])
if spl[0].startswith('xrotation'):
rot = float(spl[1])
if spl[0].startswith('xmag'):
scale = float(spl[1])
if spl[0].startswith('xrms'):
xrms = float(spl[1])
if spl[0].startswith('yrms'):
yrms = float(spl[1])
fp.close()
#os.system('wc align.match')
print 'Shift iteration #%d, xshift=%f, yshift=%f, rot=%f, scl=%f (rms: %5.2f,%5.2f)' %(IT, xshift, yshift, rot, scale, xrms, yrms)
os.system('cat align.match | grep -v "\#" | grep [0-9] | awk \'{print "circle(", $1, ",", $2, ",4) # color=green"}\' > d.reg')
os.system('cat align.match | grep -v "\#" | grep [0-9] | awk \'{print "circle(", $3, ",", $4, ",4) # color=magenta"}\' > a.reg')
shutil.copy('align.map', sci.replace('.fits', '.align.map'))
shutil.copy('align.match', sci.replace('.fits', '.align.match'))
#### Cleanup
if clean:
rmfiles = ['align.cat', 'align.map','align.match','align.reg','align.xy', 'direct.cat','direct.reg','direct.xy']
for file in rmfiles:
try:
os.remove(file)
except:
pass
fp = open(sci.replace('.fits', '.align.info'), 'w')
fp.write('# image xshift yshift rot scale xrms yrms\n')
fp.write('%s %.3f %.3f %.4f %.4f %.3f %.3f\n' %(sci, xshift, yshift, rot, scale, xrms, yrms))
if (np.abs(xshift) > shift_max) | (np.abs(yshift) > shift_max) | (xrms > rms_max) | (yrms > rms_max):
print 'Shifts out of allowed range. Run again with increased shift_max to accept.'
#return xshift, yshift, rot, scale, xrms, yrms
## Add a small shift that should come out easily with another
## shift iteration
xshift, yshift, rot, scale, xrms, yrms = 2,2,0,1.0,-99,-99
for file in [sci, wht]:
if ('r' in fitgeometry) & rot_only:
xshift, yshift = 0, 0
#apply_offsets(file, [[xshift, yshift, rot, scale]])
from drizzlepac import updatehdr
updatehdr.updatewcs_with_shift(file, sci, wcsname='DRZWCS',
rot=rot,scale=scale,
xsh=xshift, ysh=yshift,
fit=None,
xrms=xrms, yrms = yrms,
verbose=False, force=True, sciext=0)
if '_dr' in sci:
im = pyfits.open(sci)
h = im[0].header
for i in range(h['NDRIZIM']):
flt_str = h['D%03dDATA' %(i+1)]
if 'sci,2' in flt_str:
continue
#
flt_im = flt_str.split('[')[0]
ext = int(flt_str.split('[')[1][:-1].split(',')[1])
updatehdr.updatewcs_with_shift(flt_im, sci, wcsname='GTWEAK', rot=rot, scale=scale, xsh=xshift, ysh=yshift,
fit=None, xrms=xrms, yrms = yrms, verbose=False, force=True, sciext='SCI')
# im = pyfits.open(file, mode='update')
# wcs = pywcs.WCS(im[0].header)
# wcs.rotateCD(-rot)
# wcs.wcs.cd /= scale
# #
# im[0].header['CRPIX1'] += xshift
# im[0].header['CRPIX2'] += yshift
# #
# for i in [0,1]:
# for j in [0,1]:
# im[0].header['CD%d_%d' %(i+1, j+1)] = wcs.wcs.cd[i,j]
# #
# im.flush()
return xshift, yshift, rot, scale, xrms, yrms
def apply_offsets(file, params):
import astropy.wcs as pywcs
import astropy.io.fits as pyfits
im = pyfits.open(file, mode='update')
for p in params:
xshift, yshift, rot, scale = p
#print p
wcs = pywcs.WCS(im[0].header)
wcs.rotateCD(-rot)
wcs.wcs.cd /= scale
im[0].header['CRPIX1'] += xshift
im[0].header['CRPIX2'] += yshift
#
for i in [0,1]:
for j in [0,1]:
im[0].header['CD%d_%d' %(i+1, j+1)] = wcs.wcs.cd[i,j]
#
im.flush()
def go_coarse():
align.coarse_align(image='M1149_test_sci.fits', ref='/Users/brammer/Research/HST/FrontierFields/Subaru/hlsp_clash_subaru_suprimecam_macs1149_rc_2010-v20120820_sw.fits')
files = glob.glob('20150224*sci.fits')
files = glob.glob('*c4*sci.fits')
for file in files:
params = []
for iter in range(4):
out = align.get_align_to_subaru(sci=file, wht=file.replace('sci', 'wht'), clean=True, toler=4, verbose=False, fitgeometry='rxyscale', shift_max=40, rot_max=2, rot_only=False, THRESH=3, field='M1149')
params.append(out[:-2])
np.savetxt(file+'.align', params, fmt='%7.4f')
def coarse_align(image='M0416_Ks/M0416_Ks_c1_mp_avg.fits', ref='../20131103_60.01/M0416_Ks/M0416_Ks_c1_mp_avg.fits'):
"""
Do rough alignment of two images with DS9. The script will display both images
and prompt you to center the frame on a common object (just click to pan the frames).
"""
import threedhst.dq
ds9 = threedhst.dq.myDS9()
im = pyfits.open(image)
im_ref = pyfits.open(ref)
ds9.frame(1)
ds9.set('file %s' %(image))
ds9.scale(-0.1,10)
ds9.set('scale log')
ds9.frame(2)
ds9.set('file %s' %(ref))
ds9.scale(-0.1,10)
ds9.set('scale log')
ds9.set('tile yes')
ds9.set('mode pan')
x = raw_input('Center both frames on an object and type <ENTER>.')
ds9.frame(1)
im_rd = np.cast[float](ds9.get('pan fk5').split())
im_xy = np.cast[float](ds9.get('pan image').split())
ds9.frame(2)
ref_rd = np.cast[float](ds9.get('pan fk5').split())
ref_xy = np.cast[float](ds9.get('pan image').split())
delta = ref_rd-im_rd
im = pyfits.open(image, mode='update')
im[0].header['CRVAL1'] += delta[0]
im[0].header['CRVAL2'] += delta[1]
im[0].header['DELTARA'] = delta[0]
im[0].header['DELTADE'] = delta[1]
print 'Delta (pix)', im_xy-ref_xy
print 'Delta: %.4f, %.4f "' %(delta[0]*3600, delta[1]*3600)
im.flush()
def check_alignment(match='A2744_Ks_c1_mp_avg.align.match'):
x_ref, y_ref, x_in, y_in, i_ref, i_in = np.loadtxt(match, unpack=True)
dx = x_in - x_ref
dy = y_in - y_ref
pix_scale = 0.1
pix_scale = 0.06
scl = 0.5
plt.scatter(dx, dy, alpha=0.1)
plt.xlim(-scl/pix_scale, scl/pix_scale); plt.ylim(-scl/pix_scale, scl/pix_scale)
plt.xlabel(r'$\Delta x$ [%.02f" pix]' %(pix_scale)); plt.ylabel(r'$\Delta y$ [%.02f" pix]' %(pix_scale))
dr = np.sqrt(threedhst.utils.biweight(dx)**2+threedhst.utils.biweight(dy)**2)
ok = (np.abs(dx) < 2*dr) & (np.abs(dy) < 2*dr)
s = 200
plt.quiver(x_in[ok], y_in[ok], dx[ok]*s, dy[ok]*s, scale=1, units='xy', alpha=0.5)
plt.quiver(0.05*x_in.max(), 0.05*y_in.max(), s, 0, scale=1, units='xy', alpha=0.8, label='1 pix', color='red')
#plt.legend()
if __name__ == '__main__':
import sys
cwd = os.getcwd()
if 'A2744' in cwd:
field = 'A2744'
if 'M0416' in cwd:
field = 'M0416'
#print sys.argv
chips = [1,2,3,4]
if len(sys.argv) > 1:
chips = []
for c in sys.argv[1:]:
chips.append(int(c))
#print chips
#### Run in three steps to refine the shifts: shift, rxyscale, shift
#### The first gets you close, the second takes out any rotation, and the last
#### is needed because I don't know the shift reference of "rxyscale"....
for chip in chips:
get_align_to_subaru(sci='%s_Ks_c%d_mp_avg.fits' %(field, chip), wht='%s_Ks_c%d_mp_exp.fits' %(field, chip), clean=False, toler=3, verbose=False, fitgeometry='shift')
get_align_to_subaru(sci='%s_Ks_c%d_mp_avg.fits' %(field, chip), wht='%s_Ks_c%d_mp_exp.fits' %(field, chip), clean=False, toler=3, verbose=False, fitgeometry='rxyscale', rot_only=True)
xshift, yshift, rot, scale, xrms, yrms = get_align_to_subaru(sci='%s_Ks_c%d_mp_avg.fits' %(field, chip), wht='%s_Ks_c%d_mp_exp.fits' %(field, chip), clean=False, toler=3, verbose=False, fitgeometry='shift')
if xrms < -90:
xshift, yshift, rot, scale, xrms, yrms = get_align_to_subaru(sci='%s_Ks_c%d_mp_avg.fits' %(field, chip), wht='%s_Ks_c%d_mp_exp.fits' %(field, chip), clean=False, toler=3, verbose=False, fitgeometry='shift')
# get_align_to_subaru(sci='M0416_Ks_c2_mp_avg.fits', wht='M0416_Ks_c2_mp_exp.fits', clean=False, toler=3, verbose=False, fitgeometry='shift')
# get_align_to_subaru(sci='M0416_Ks_c3_mp_avg.fits', wht='M0416_Ks_c3_mp_exp.fits', clean=False, toler=3, verbose=False, fitgeometry='shift')
# get_align_to_subaru(sci='M0416_Ks_c4_mp_avg.fits', wht='M0416_Ks_c4_mp_exp.fits', clean=False, toler=3, verbose=False, fitgeometry='shift')
| mit |
LeonardoBraga/ng2-helpers | test/module.spec.js | 987 | describe('Module', function() {
'use strict';
beforeEach(function() {
angular.module('ng2', []);
spyOn(angular, 'module').and.callThrough();
});
it('should set the module name through Module\'s `name` property', function() {
Module({
name: 'ng2'
})
.Component()
.Class(function test() {});
expect(angular.module).toHaveBeenCalledWith('ng2', undefined);
});
it('should pass the module\'s dependencies through Module\'s `imports` property', function() {
Module({
name: 'ng2',
imports: ['module1', 'module2']
})
.Component()
.Class(function test() {});
expect(angular.module).toHaveBeenCalledWith('ng2', ['module1', 'module2']);
});
it('should allow the module\'s creation through Module\'s `imports` property', function() {
Module({
name: 'ng2',
imports: []
})
.Component()
.Class(function test() {});
expect(angular.module).toHaveBeenCalledWith('ng2', []);
});
}); | mit |
ccheng312/chordsheets | modules/songs/server/models/song.server.model.js | 781 | 'use strict';
/**
* Module dependencies
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Song Schema
*/
var SongSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
trim: true,
unique: true,
required: 'Title cannot be blank'
},
artist: {
type: String,
default: '',
trim: true
},
defaultKey: {
type: String,
trim: true,
match: /^[A-G][b#]?m?$/,
required: 'Default key cannot be blank'
},
bpm: Number,
tags: {
type: [String],
lowercase: true
},
content: {
type: String,
trim: true,
required: 'Content cannot be blank'
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Song', SongSchema);
| mit |
smolyakoff/conreign | src/Orleans.MongoStorageProvider/Driver/GrainReferenceSerializer.cs | 4446 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using Orleans.Runtime;
namespace Orleans.MongoStorageProvider.Driver
{
public class GrainReferenceSerializer : SerializerBase<GrainReference>
{
private readonly IGrainReferenceConverter _grainReferenceConverter;
private const string InterfaceNameField = "grain_interface";
private const string KeyField = "grain_key";
private static readonly MethodInfo DeserializationMethod = typeof(GrainExtensions).GetMethod(
"Cast",
BindingFlags.Static | BindingFlags.Public);
public GrainReferenceSerializer(IGrainReferenceConverter grainReferenceConverter)
{
_grainReferenceConverter = grainReferenceConverter ?? throw new ArgumentNullException(nameof(grainReferenceConverter));
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args,
GrainReference value)
{
if (value == null)
{
context.Writer.WriteNull();
return;
}
var grainReference = value;
var grainKey = grainReference.ToKeyString();
var grainInterfaceType = grainReference
.GetType()
.GetInterfaces()
.FirstOrDefault(t => typeof(IGrain).IsAssignableFrom(t));
if (grainInterfaceType == null)
{
throw new InvalidOperationException("Expected grain reference to implement IGrain.");
}
context.Writer.WriteStartDocument();
context.Writer.WriteString(InterfaceNameField, grainInterfaceType.AssemblyQualifiedName);
context.Writer.WriteString(KeyField, grainKey);
context.Writer.WriteEndDocument();
}
public override GrainReference Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
if (context.Reader.CurrentBsonType == BsonType.Null)
{
context.Reader.ReadNull();
return null;
}
EnsureBsonTypeEquals(context.Reader, BsonType.Document);
// The MongoDB document will look like
// { "_t": "CodeGenGrainName", _v: { grain_interface: "Fully qualified type name", grain_key: "GrainReference=..."} }
context.Reader.ReadStartDocument();
context.Reader.FindElement("_v");
context.Reader.ReadStartDocument();
var interfaceName = context.Reader.ReadString(InterfaceNameField);
var grainKey = context.Reader.ReadString(KeyField);
context.Reader.ReadEndDocument();
context.Reader.ReadEndDocument();
if (string.IsNullOrEmpty(interfaceName) || string.IsNullOrEmpty(grainKey))
{
throw new InvalidOperationException(
$"Expected ${InterfaceNameField} and ${KeyField} fields in the document. " +
$"Got ${InterfaceNameField}={interfaceName}, {KeyField}={grainKey}.");
}
var grainReference = _grainReferenceConverter.GetGrainFromKeyString(grainKey);
var grainInterfaceType = LookupGrainInterfaces(interfaceName, args.NominalType)
.FirstOrDefault(x => x != null);
if (grainInterfaceType == null)
{
throw new InvalidOperationException(
$"Failed to resolve grain interface type. Serialized type was: {interfaceName}.");
}
var deserialize = DeserializationMethod.MakeGenericMethod(grainInterfaceType);
var grainInterface = deserialize.Invoke(null, new object[] {grainReference});
return (GrainReference) grainInterface;
}
private static IEnumerable<Type> LookupGrainInterfaces(string serializedName, Type nominalType)
{
var choices = new List<Type> {nominalType};
choices.AddRange(nominalType.GetInterfaces());
choices.RemoveAll(x => !typeof(IGrain).GetTypeInfo().IsAssignableFrom(x));
foreach (var choice in choices)
yield return choice;
yield return Type.GetType(serializedName, false);
}
}
} | mit |
jklemmack/DailyReports | DailyReports/app/DailyReport/Manpower/ManpowerController.js | 825 | 'use strict';
angular.module('myApp.DailyReports.Manpower', [])
.controller('ManpowerListController', ['$scope', '$http', '$location', function ($scope, $http, $location) {
$scope.goToDailyReport = function(){
var view = "/Report/123/20130911";
$location.path(view);
}
$scope.goToAddManpower = function() {
var view = '/Report/123/20130911/Manpower/1234';
$location.path(view);
}
}])
.controller('ManpowerDetailController', ['$scope', '$location', function ($scope, $location) {
$scope.goToList = function() {
var view = '/Report/123/20130911';
$location.path(view);
}
$scope.saveManpowerEntry = function(){
$scope.goToList();
}
}]); | mit |
10leej/BobHUD | modules/units/pet.lua | 3502 | --pet
local _, cfg = ... --export config
local addon, ns = ... --get addon namespace
local f = CreateFrame("Button","BobPetHUD",UIParent,"SecureUnitButtonTemplate")
local UnitPowerType = UnitPowerType
f.unit = "pet" --change to unit you want to track
--Make the Health Bar
--background texture
f.back = f:CreateTexture(nil,"BACKGROUND")
f.back:SetSize(unpack(cfg.pet.barsize))
f.back:SetPoint("CENTER",UIParent,cfg.pet.healthx,cfg.pet.healthy)
f.back:SetTexture("Interface\\Addons\\BobHUD\\media\\healthbar")
f.back:SetVertexColor(0,0,0,cfg.pet.alpha)
if cfg.transparency.OOCfade then
f.back:Hide()
end
--health bar
f.hp = CreateFrame("StatusBar",nil,f,"TextStatusBar")
f.hp:SetSize(unpack(cfg.pet.barsize))
f.hp:SetPoint("CENTER",UIParent,cfg.pet.healthx,cfg.pet.healthy)
f.hp:SetStatusBarTexture("Interface\\Addons\\BobHUD\\media\\healthbar")
f.hp:SetStatusBarColor(0,.8,0)
f.hp:SetMinMaxValues(0,1)
f.hp:SetOrientation("VERTICAL")
f.hp:EnableMouse(false)
f.hp:SetAlpha(cfg.pet.alpha)
if cfg.transparency.OOCfade then
f.hp:Hide()
end
--Make the Mana Bar
f:SetAttribute("unit",f.unit)
--background texture
f.back = f:CreateTexture(nil,"BACKGROUND")
f.back:SetSize(unpack(cfg.pet.barsize))
f.back:SetPoint("CENTER",UIParent,cfg.pet.powerx,cfg.pet.powery)
f.back:SetTexture("Interface\\Addons\\BobHUD\\media\\healthbar")
f.back:SetVertexColor(0,0,0,cfg.pet.alpha)
if cfg.transparency.OOCfade then
f.back:Hide()
end
--mana bar
f.mp = CreateFrame("StatusBar",nil,f,"TextStatusBar")
f.mp:SetSize(unpack(cfg.pet.barsize))
f.mp:SetPoint("CENTER",UIParent,cfg.pet.powerx,cfg.pet.powery)
f.mp:SetStatusBarTexture("Interface\\Addons\\BobHUD\\media\\healthbar")
local powercolor = PowerBarColor[select(2, UnitPowerType(f.unit))] or PowerBarColor['MANA']
f.mp:SetStatusBarColor(powercolor.r, powercolor.g, powercolor.b)
f.mp:SetMinMaxValues(0,1)
f.mp:SetOrientation("VERTICAL")
f.mp:EnableMouse(false)
f.mp:SetAlpha(cfg.pet.alpha)
if cfg.transparency.OOCfade then
f.mp:Hide()
end
--Updates the status bar to new health
f:SetScript("OnEvent", function(self, event, unit)
if event == "UNIT_HEALTH_FREQUENT" or event == "PLAYER_ENTERING_WORLD" or event == "UNIT_PET" then
--update health
self.hp:SetValue(UnitHealth(f.unit)/UnitHealthMax(f.unit))
local currentHealth, maxHealth = UnitHealth(f.unit), UnitHealthMax(f.unit)
local percentHealth = currentHealth / maxHealth * 100
end
if event == "UNIT_POWER_FREQUENT" or event == "PLAYER_ENTERING_WORLD" or event == "UNIT_PET" then
--update powa
self.mp:SetValue(UnitPower(f.unit)/UnitPowerMax(f.unit))
local currentPower, maxPower = UnitPower(f.unit), UnitPowerMax(f.unit)
local percentPower = currentPower / maxPower * 100
local powercolor = PowerBarColor[select(2, UnitPowerType(f.unit))] or PowerBarColor['MANA']
f.mp:SetStatusBarColor(powercolor.r, powercolor.g, powercolor.b)
end
if cfg.transparency.OOCfade then
if event == "PLAYER_REGEN_ENABLED" or event == "PLAYER_ENTERING_WORLD" or event == "UNIT_PET" then
f.back:Hide()
f.hp:Hide()
f.mp:Hide()
end
if event == "PLAYER_REGEN_DISABLED" then
f.back:Show()
f.hp:Show()
f.mp:Show()
end
end
end)
f:RegisterEvent("UNIT_PET")
f:RegisterEvent("PLAYER_ENTERING_WORLD")
f:RegisterEvent("PLAYER_REGEN_DISABLED")
f:RegisterEvent("PLAYER_REGEN_ENABLED")
f:RegisterUnitEvent("UNIT_HEALTH_FREQUENT", f.unit)
f:RegisterUnitEvent("UNIT_POWER_FREQUENT", f.unit)
RegisterUnitWatch(f) --Check to see if unit exists
| mit |
tamlok/vnote | src/core/sessionconfig.cpp | 12596 | #include "sessionconfig.h"
#include <QDir>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <utils/fileutils.h>
#include "configmgr.h"
#include "mainconfig.h"
#include "historymgr.h"
using namespace vnotex;
bool SessionConfig::NotebookItem::operator==(const NotebookItem &p_other) const
{
return m_type == p_other.m_type
&& m_rootFolderPath == p_other.m_rootFolderPath
&& m_backend == p_other.m_backend;
}
void SessionConfig::NotebookItem::fromJson(const QJsonObject &p_jobj)
{
m_type = p_jobj[QStringLiteral("type")].toString();
m_rootFolderPath = p_jobj[QStringLiteral("root_folder")].toString();
m_backend = p_jobj[QStringLiteral("backend")].toString();
}
QJsonObject SessionConfig::NotebookItem::toJson() const
{
QJsonObject jobj;
jobj[QStringLiteral("type")] = m_type;
jobj[QStringLiteral("root_folder")] = m_rootFolderPath;
jobj[QStringLiteral("backend")] = m_backend;
return jobj;
}
void SessionConfig::ExternalProgram::fromJson(const QJsonObject &p_jobj)
{
m_name = p_jobj[QStringLiteral("name")].toString();
m_command = p_jobj[QStringLiteral("command")].toString();
m_shortcut = p_jobj[QStringLiteral("shortcut")].toString();
}
QJsonObject SessionConfig::ExternalProgram::toJson() const
{
QJsonObject jobj;
jobj[QStringLiteral("name")] = m_name;
jobj[QStringLiteral("command")] = m_command;
jobj[QStringLiteral("shortcut")] = m_shortcut;
return jobj;
}
SessionConfig::SessionConfig(ConfigMgr *p_mgr)
: IConfig(p_mgr, nullptr)
{
}
SessionConfig::~SessionConfig()
{
}
void SessionConfig::init()
{
auto mgr = getMgr();
auto sessionSettings = mgr->getSettings(ConfigMgr::Source::Session);
const auto &sessionJobj = sessionSettings->getJson();
loadCore(sessionJobj);
loadStateAndGeometry(sessionJobj);
m_exportOption.fromJson(sessionJobj[QStringLiteral("export_option")].toObject());
m_searchOption.fromJson(sessionJobj[QStringLiteral("search_option")].toObject());
m_viewAreaSession = readByteArray(sessionJobj, QStringLiteral("viewarea_session"));
m_notebookExplorerSession = readByteArray(sessionJobj, QStringLiteral("notebook_explorer_session"));
loadExternalPrograms(sessionJobj);
loadNotebooks(sessionJobj);
loadHistory(sessionJobj);
if (MainConfig::isVersionChanged()) {
doVersionSpecificOverride();
}
}
void SessionConfig::loadCore(const QJsonObject &p_session)
{
const auto coreObj = p_session.value(QStringLiteral("core")).toObject();
m_newNotebookDefaultRootFolderPath = readString(coreObj,
QStringLiteral("new_notebook_default_root_folder_path"));
if (m_newNotebookDefaultRootFolderPath.isEmpty()) {
m_newNotebookDefaultRootFolderPath = QDir::homePath();
}
m_currentNotebookRootFolderPath = readString(coreObj, QStringLiteral("current_notebook_root_folder_path"));
{
auto option = readString(coreObj, QStringLiteral("opengl"));
m_openGL = stringToOpenGL(option);
}
if (!isUndefinedKey(coreObj, QStringLiteral("system_title_bar"))) {
m_systemTitleBarEnabled = readBool(coreObj, QStringLiteral("system_title_bar"));
} else {
m_systemTitleBarEnabled = true;
}
if (!isUndefinedKey(coreObj, QStringLiteral("minimize_to_system_tray"))) {
m_minimizeToSystemTray = readBool(coreObj, QStringLiteral("minimize_to_system_tray")) ? 1 : 0;
}
m_flashPage = readString(coreObj, QStringLiteral("flash_page"));
m_quickAccessFiles = readStringList(coreObj, QStringLiteral("quick_access"));
}
QJsonObject SessionConfig::saveCore() const
{
QJsonObject coreObj;
coreObj[QStringLiteral("new_notebook_default_root_folder_path")] = m_newNotebookDefaultRootFolderPath;
coreObj[QStringLiteral("current_notebook_root_folder_path")] = m_currentNotebookRootFolderPath;
coreObj[QStringLiteral("opengl")] = openGLToString(m_openGL);
coreObj[QStringLiteral("system_title_bar")] = m_systemTitleBarEnabled;
if (m_minimizeToSystemTray != -1) {
coreObj[QStringLiteral("minimize_to_system_tray")] = m_minimizeToSystemTray > 0;
}
coreObj[QStringLiteral("flash_page")] = m_flashPage;
writeStringList(coreObj, QStringLiteral("quick_access"), m_quickAccessFiles);
return coreObj;
}
const QString &SessionConfig::getNewNotebookDefaultRootFolderPath() const
{
return m_newNotebookDefaultRootFolderPath;
}
void SessionConfig::setNewNotebookDefaultRootFolderPath(const QString &p_path)
{
updateConfig(m_newNotebookDefaultRootFolderPath,
p_path,
this);
}
const QVector<SessionConfig::NotebookItem> &SessionConfig::getNotebooks() const
{
return m_notebooks;
}
void SessionConfig::setNotebooks(const QVector<SessionConfig::NotebookItem> &p_notebooks)
{
updateConfig(m_notebooks,
p_notebooks,
this);
}
void SessionConfig::loadNotebooks(const QJsonObject &p_session)
{
const auto notebooksJson = p_session.value(QStringLiteral("notebooks")).toArray();
m_notebooks.resize(notebooksJson.size());
for (int i = 0; i < notebooksJson.size(); ++i) {
m_notebooks[i].fromJson(notebooksJson[i].toObject());
}
}
QJsonArray SessionConfig::saveNotebooks() const
{
QJsonArray nbArray;
for (const auto &nb : m_notebooks) {
nbArray.append(nb.toJson());
}
return nbArray;
}
const QString &SessionConfig::getCurrentNotebookRootFolderPath() const
{
return m_currentNotebookRootFolderPath;
}
void SessionConfig::setCurrentNotebookRootFolderPath(const QString &p_path)
{
updateConfig(m_currentNotebookRootFolderPath,
p_path,
this);
}
void SessionConfig::writeToSettings() const
{
getMgr()->writeSessionSettings(toJson());
}
QJsonObject SessionConfig::toJson() const
{
QJsonObject obj;
obj[QStringLiteral("core")] = saveCore();
obj[QStringLiteral("notebooks")] = saveNotebooks();
obj[QStringLiteral("state_geometry")] = saveStateAndGeometry();
obj[QStringLiteral("export_option")] = m_exportOption.toJson();
obj[QStringLiteral("search_option")] = m_searchOption.toJson();
writeByteArray(obj, QStringLiteral("viewarea_session"), m_viewAreaSession);
writeByteArray(obj, QStringLiteral("notebook_explorer_session"), m_notebookExplorerSession);
obj[QStringLiteral("external_programs")] = saveExternalPrograms();
obj[QStringLiteral("history")] = saveHistory();
return obj;
}
QJsonObject SessionConfig::saveStateAndGeometry() const
{
QJsonObject obj;
writeByteArray(obj, QStringLiteral("main_window_state"), m_mainWindowStateGeometry.m_mainState);
writeByteArray(obj, QStringLiteral("main_window_geometry"), m_mainWindowStateGeometry.m_mainGeometry);
writeStringList(obj, QStringLiteral("visible_docks_before_expand"), m_mainWindowStateGeometry.m_visibleDocksBeforeExpand);
return obj;
}
SessionConfig::MainWindowStateGeometry SessionConfig::getMainWindowStateGeometry() const
{
return m_mainWindowStateGeometry;
}
void SessionConfig::setMainWindowStateGeometry(const SessionConfig::MainWindowStateGeometry &p_state)
{
updateConfig(m_mainWindowStateGeometry, p_state, this);
}
SessionConfig::OpenGL SessionConfig::getOpenGLAtBootstrap()
{
auto userConfigFile = ConfigMgr::locateSessionConfigFilePathAtBootstrap();
if (!userConfigFile.isEmpty()) {
auto bytes = FileUtils::readFile(userConfigFile);
auto obj = QJsonDocument::fromJson(bytes).object();
auto coreObj = obj.value(QStringLiteral("core")).toObject();
auto str = coreObj.value(QStringLiteral("opengl")).toString();
return stringToOpenGL(str);
}
return OpenGL::None;
}
SessionConfig::OpenGL SessionConfig::getOpenGL() const
{
return m_openGL;
}
void SessionConfig::setOpenGL(OpenGL p_option)
{
updateConfig(m_openGL, p_option, this);
}
QString SessionConfig::openGLToString(OpenGL p_option)
{
switch (p_option) {
case OpenGL::Desktop:
return QStringLiteral("desktop");
case OpenGL::Angle:
return QStringLiteral("angle");
case OpenGL::Software:
return QStringLiteral("software");
default:
return QStringLiteral("none");
}
}
SessionConfig::OpenGL SessionConfig::stringToOpenGL(const QString &p_str)
{
auto option = p_str.toLower();
if (option == QStringLiteral("software")) {
return OpenGL::Software;
} else if (option == QStringLiteral("desktop")) {
return OpenGL::Desktop;
} else if (option == QStringLiteral("angle")) {
return OpenGL::Angle;
} else {
return OpenGL::None;
}
}
bool SessionConfig::getSystemTitleBarEnabled() const
{
return m_systemTitleBarEnabled;
}
void SessionConfig::setSystemTitleBarEnabled(bool p_enabled)
{
updateConfig(m_systemTitleBarEnabled, p_enabled, this);
}
int SessionConfig::getMinimizeToSystemTray() const
{
return m_minimizeToSystemTray;
}
void SessionConfig::setMinimizeToSystemTray(bool p_enabled)
{
updateConfig(m_minimizeToSystemTray, p_enabled ? 1 : 0, this);
}
void SessionConfig::doVersionSpecificOverride()
{
// In a new version, we may want to change one value by force.
// SHOULD set the in memory variable only, or will override the notebook list.
}
const ExportOption &SessionConfig::getExportOption() const
{
return m_exportOption;
}
void SessionConfig::setExportOption(const ExportOption &p_option)
{
updateConfig(m_exportOption, p_option, this);
}
const SearchOption &SessionConfig::getSearchOption() const
{
return m_searchOption;
}
void SessionConfig::setSearchOption(const SearchOption &p_option)
{
updateConfig(m_searchOption, p_option, this);
}
void SessionConfig::loadStateAndGeometry(const QJsonObject &p_session)
{
const auto obj = p_session.value(QStringLiteral("state_geometry")).toObject();
m_mainWindowStateGeometry.m_mainState = readByteArray(obj, QStringLiteral("main_window_state"));
m_mainWindowStateGeometry.m_mainGeometry = readByteArray(obj, QStringLiteral("main_window_geometry"));
m_mainWindowStateGeometry.m_visibleDocksBeforeExpand = readStringList(obj, QStringLiteral("visible_docks_before_expand"));
}
QByteArray SessionConfig::getViewAreaSessionAndClear()
{
QByteArray bytes;
m_viewAreaSession.swap(bytes);
return bytes;
}
void SessionConfig::setViewAreaSession(const QByteArray &p_bytes)
{
updateConfigWithoutCheck(m_viewAreaSession, p_bytes, this);
}
QByteArray SessionConfig::getNotebookExplorerSessionAndClear()
{
QByteArray bytes;
m_notebookExplorerSession.swap(bytes);
return bytes;
}
void SessionConfig::setNotebookExplorerSession(const QByteArray &p_bytes)
{
updateConfigWithoutCheck(m_notebookExplorerSession, p_bytes, this);
}
const QString &SessionConfig::getFlashPage() const
{
return m_flashPage;
}
void SessionConfig::setFlashPage(const QString &p_file)
{
updateConfig(m_flashPage, p_file, this);
}
const QStringList &SessionConfig::getQuickAccessFiles() const
{
return m_quickAccessFiles;
}
void SessionConfig::setQuickAccessFiles(const QStringList &p_files)
{
updateConfig(m_quickAccessFiles, p_files, this);
}
void SessionConfig::loadExternalPrograms(const QJsonObject &p_session)
{
const auto arr = p_session.value(QStringLiteral("external_programs")).toArray();
m_externalPrograms.resize(arr.size());
for (int i = 0; i < arr.size(); ++i) {
m_externalPrograms[i].fromJson(arr[i].toObject());
}
}
QJsonArray SessionConfig::saveExternalPrograms() const
{
QJsonArray arr;
for (const auto &pro : m_externalPrograms) {
arr.append(pro.toJson());
}
return arr;
}
const QVector<SessionConfig::ExternalProgram> &SessionConfig::getExternalPrograms() const
{
return m_externalPrograms;
}
const QVector<HistoryItem> &SessionConfig::getHistory() const
{
return m_history;
}
void SessionConfig::addHistory(const HistoryItem &p_item)
{
HistoryMgr::insertHistoryItem(m_history, p_item);
update();
}
void SessionConfig::clearHistory()
{
m_history.clear();
update();
}
void SessionConfig::loadHistory(const QJsonObject &p_session)
{
auto arr = p_session[QStringLiteral("history")].toArray();
m_history.resize(arr.size());
for (int i = 0; i < arr.size(); ++i) {
m_history[i].fromJson(arr[i].toObject());
}
}
QJsonArray SessionConfig::saveHistory() const
{
QJsonArray arr;
for (const auto &item : m_history) {
arr.append(item.toJson());
}
return arr;
}
| mit |
Arch-vile/bouncer | client/app/defer/defer.js | 197 | 'use strict';
angular.module('bouncerApp')
.config(function($stateProvider) {
$stateProvider
.state('defer', {
url: '/defer/:token?amount&units',
controller: 'DeferCtrl'
});
}); | mit |
zero1n/artgallery | app/scripts/controllers/navbar.js | 353 | 'use strict';
/**
* @ngdoc function
* @name artgalleryApp.controller:NavbarCtrl
* @description
* # NavbarCtrl
* Controller of the artgalleryApp
*/
angular.module('artgalleryApp')
.controller('NavbarCtrl',['$scope','$auth', function ($scope, $auth) {
$scope.isAuthenticated = function() {
return $auth.isAuthenticated();
};
}]);
| mit |
mokhan/scale | lib/scale/shapes/line.rb | 310 | module Scale
class Line
include Node
attribute :x1, Integer # the x position of point 1
attribute :y1, Integer # the y position of point 1
attribute :x2, Integer # the x position of point 2
attribute :y2, Integer # the y position of point 2
def xml_tag
:line
end
end
end
| mit |
iwangx/createjs | src/easeljs/display/BitmapText.js | 10310 | /*
* BitmapText
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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.
*/
//this.createjs = this.createjs || {};
(function () {
"use strict";
// constructor:
/**
* Displays text using bitmap glyphs defined in a sprite sheet. Multi-line text is supported
* using new line characters, but automatic wrapping is not supported. See the
* {{#crossLink "BitmapText/spriteSheet:property"}}{{/crossLink}}
* property for more information on defining glyphs.
*
* <strong>Important:</strong> BitmapText extends Container, but is not designed to be used as one.
* As such, methods like addChild and removeChild are disabled.
* @class BitmapText
* @extends DisplayObject
* @param {String} [text=""] The text to display.
* @param {SpriteSheet} [spriteSheet=null] The spritesheet that defines the character glyphs.
* @constructor
**/
function BitmapText(text, spriteSheet) {
this.Container_constructor();
// public properties:
/**
* The text to display.
* @property text
* @type String
* @default ""
**/
this.text = text||"";
/**
* A SpriteSheet instance that defines the glyphs for this bitmap text. Each glyph/character
* should have a single frame animation defined in the sprite sheet named the same as
* corresponding character. For example, the following animation definition:
*
* "A": {frames: [0]}
*
* would indicate that the frame at index 0 of the spritesheet should be drawn for the "A" character. The short form
* is also acceptable:
*
* "A": 0
*
* Note that if a character in the text is not found in the sprite sheet, it will also
* try to use the alternate case (upper or lower).
*
* See SpriteSheet for more information on defining sprite sheet data.
* @property spriteSheet
* @type SpriteSheet
* @default null
**/
this.spriteSheet = spriteSheet;
/**
* The height of each line of text. If 0, then it will use a line height calculated
* by checking for the height of the "1", "T", or "L" character (in that order). If
* those characters are not defined, it will use the height of the first frame of the
* sprite sheet.
* @property lineHeight
* @type Number
* @default 0
**/
this.lineHeight = 0;
/**
* This spacing (in pixels) will be added after each character in the output.
* @property letterSpacing
* @type Number
* @default 0
**/
this.letterSpacing = 0;
/**
* If a space character is not defined in the sprite sheet, then empty pixels equal to
* spaceWidth will be inserted instead. If 0, then it will use a value calculated
* by checking for the width of the "1", "l", "E", or "A" character (in that order). If
* those characters are not defined, it will use the width of the first frame of the
* sprite sheet.
* @property spaceWidth
* @type Number
* @default 0
**/
this.spaceWidth = 0;
// private properties:
/**
* @property _oldProps
* @type Object
* @protected
**/
this._oldProps = {text:0,spriteSheet:0,lineHeight:0,letterSpacing:0,spaceWidth:0};
}
var p = createjs.extend(BitmapText, createjs.Container);
/**
* <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// static properties:
/**
* BitmapText uses Sprite instances to draw text. To reduce the creation and destruction of instances (and thus garbage collection), it maintains
* an internal object pool of sprite instances to reuse. Increasing this value can cause more sprites to be
* retained, slightly increasing memory use, but reducing instantiation.
* @property maxPoolSize
* @type Number
* @static
* @default 100
**/
BitmapText.maxPoolSize = 100;
/**
* Sprite object pool.
* @type {Array}
* @static
* @private
*/
BitmapText._spritePool = [];
// public methods:
/**
* Docced in superclass.
**/
p.draw = function(ctx, ignoreCache) {
if (this.DisplayObject_draw(ctx, ignoreCache)) { return; }
this._updateText();
this.Container_draw(ctx, ignoreCache);
};
/**
* Docced in superclass.
**/
p.getBounds = function() {
this._updateText();
return this.Container_getBounds();
};
/**
* Returns true or false indicating whether the display object would be visible if drawn to a canvas.
* This does not account for whether it would be visible within the boundaries of the stage.
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method isVisible
* @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas
**/
p.isVisible = function() {
var hasContent = this.cacheCanvas || (this.spriteSheet && this.spriteSheet.complete && this.text);
return !!(this.visible && this.alpha > 0 && this.scaleX !== 0 && this.scaleY !== 0 && hasContent);
};
p.clone = function() {
return this._cloneProps(new BitmapText(this.text, this.spriteSheet));
};
/**
* <strong>Disabled in BitmapText.</strong>
* @method addChild
**/
/**
* <strong>Disabled in BitmapText.</strong>
* @method addChildAt
**/
/**
* <strong>Disabled in BitmapText.</strong>
* @method removeChild
**/
/**
* <strong>Disabled in BitmapText.</strong>
* @method removeChildAt
**/
/**
* <strong>Disabled in BitmapText.</strong>
* @method removeAllChildren
**/
p.addChild = p.addChildAt = p.removeChild = p.removeChildAt = p.removeAllChildren = function() {};
// private methods:
/**
* @method _cloneProps
* @param {BitmapText} o
* @return {BitmapText} o
* @protected
**/
p._cloneProps = function(o) {
this.Container__cloneProps(o);
o.lineHeight = this.lineHeight;
o.letterSpacing = this.letterSpacing;
o.spaceWidth = this.spaceWidth;
return o;
};
/**
* @method _getFrameIndex
* @param {String} character
* @param {SpriteSheet} spriteSheet
* @return {Number}
* @protected
**/
p._getFrameIndex = function(character, spriteSheet) {
var c, o = spriteSheet.getAnimation(character);
if (!o) {
(character != (c = character.toUpperCase())) || (character != (c = character.toLowerCase())) || (c=null);
if (c) { o = spriteSheet.getAnimation(c); }
}
return o && o.frames[0];
};
/**
* @method _getFrame
* @param {String} character
* @param {SpriteSheet} spriteSheet
* @return {Object}
* @protected
**/
p._getFrame = function(character, spriteSheet) {
var index = this._getFrameIndex(character, spriteSheet);
return index == null ? index : spriteSheet.getFrame(index);
};
/**
* @method _getLineHeight
* @param {SpriteSheet} ss
* @return {Number}
* @protected
**/
p._getLineHeight = function(ss) {
var frame = this._getFrame("1",ss) || this._getFrame("T",ss) || this._getFrame("L",ss) || ss.getFrame(0);
return frame ? frame.rect.height : 1;
};
/**
* @method _getSpaceWidth
* @param {SpriteSheet} ss
* @return {Number}
* @protected
**/
p._getSpaceWidth = function(ss) {
var frame = this._getFrame("1",ss) || this._getFrame("l",ss) || this._getFrame("e",ss) || this._getFrame("a",ss) || ss.getFrame(0);
return frame ? frame.rect.width : 1;
};
/**
* @method _drawText
* @protected
**/
p._updateText = function() {
var x=0, y=0, o=this._oldProps, change=false, spaceW=this.spaceWidth, lineH=this.lineHeight, ss=this.spriteSheet;
var pool=BitmapText._spritePool, kids=this.children, childIndex=0, numKids=kids.length, sprite;
for (var n in o) {
if (o[n] != this[n]) {
o[n] = this[n];
change = true;
}
}
if (!change) { return; }
var hasSpace = !!this._getFrame(" ", ss);
if (!hasSpace && !spaceW) { spaceW = this._getSpaceWidth(ss); }
if (!lineH) { lineH = this._getLineHeight(ss); }
for(var i=0, l=this.text.length; i<l; i++) {
var character = this.text.charAt(i);
if (character == " " && !hasSpace) {
x += spaceW;
continue;
} else if (character=="\n" || character=="\r") {
if (character=="\r" && this.text.charAt(i+1) == "\n") { i++; } // crlf
x = 0;
y += lineH;
continue;
}
var index = this._getFrameIndex(character, ss);
if (index == null) { continue; }
if (childIndex < numKids) {
sprite = kids[childIndex];
} else {
kids.push(sprite = pool.length ? pool.pop() : new createjs.Sprite());
sprite.parent = this;
numKids++;
}
sprite.spriteSheet = ss;
sprite.gotoAndStop(index);
sprite.x = x;
sprite.y = y;
childIndex++;
x += sprite.getBounds().width + this.letterSpacing;
}
while (numKids > childIndex) {
// faster than removeChild.
pool.push(sprite = kids.pop());
sprite.parent = null;
numKids--;
}
if (pool.length > BitmapText.maxPoolSize) { pool.length = BitmapText.maxPoolSize; }
};
createjs.BitmapText = createjs.promote(BitmapText, "Container");
}()); | mit |
kaizer04/SoftUni | HTML&CSS/CSS-Overview-Homework/02-ColorKitchen/Properties/AssemblyInfo.cs | 1386 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("_02_ColorKitchen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("_02_ColorKitchen")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fac3b43d-eac4-40e2-8ecc-f9b1e33c4d9f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
SENATICS/template-concrete5 | packages/dsOpenData/single_pages/dashboard/open_data/datasets.php | 10276 | <?php defined('C5_EXECUTE') or die('Access denied.');
$form = Loader::helper('form');
?>
<style>
div#ccm-dashboard-content>header{
background-color:#42ca90 !important;
box-shadow: 0px 10px 10px #ECECEC;
}
div#ccm-dashboard-content>header h1{
color:#FFF !important;
}
div#ccm-dashboard-content .btn-link{
color:#FFF !important;
}
</style>
<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper(t('Conjunto de Datos')); ?>
<?php //SE CARGA EL MENU SUPERIOR PARA EL DASHBOARD
$packagePath = Package::getByID($this->c->pkgID)->getPackagePath();
include($packagePath.'/single_pages/dashboard/open_data/menu.php');
?>
<?php if (empty($catalogos) && ( !isset( $datasetsID ) || $datasetsID === null)): ?>
<div class="alert alert-info">
<?php echo t('No hay Catálogo para añadir un nuevo Conjunto de Datos. Ir al Añadir Catálogo para añadir un nuevo Catálogo') ?>
</div>
<?php else: ?>
<div class="btn_add_resource"></div>
<div class="sub_cabecera">
<h3 class="titulo_seccion" style="display:inline-block !important; margin:4px; margin-left:1px;">
<a class="btn_volver" href="<?php echo View::url('dashboard/open_data/list_datasets/show/'.$titulo_datasets[0]['opendataID']) ?>">
<i class='fa fa-arrow-left' aria-hidden='true'></i>
</a>
<?php echo "Agregar / Editar un Conjunto de Dato";?>
</h3>
</div>
<div class="row">
<div class="col-sm-6 col-xs-12">
<form class="form-horizontal" method="post" id="ccm-multilingual-page-report-form">
<fieldset class="control-group">
<label class="control-label"><?php echo t('Catálogo') ?><span class="formulario_requerido">*</span></label>
<div class="controls">
<?php $datasets_catalogID = isset( $datasets_catalogID ) ? $datasets_catalogID : null; ?>
<select class="form-control" name="datasets_catalogID" id="datasets_catalogID" value="<?php echo $datasets_catalogID; ?>">
<option value="0"> Seleccione una opción </option>
<?php foreach ($catalogos as $cata): ?>
<option value="<?php echo $cata['opendataID'] ?>" <?php $selected = $cata['opendataID']==$datasets_catalogID ? "selected" : ""; echo $selected; ?> ><?php echo $cata['title'] ?></option>
<?php endforeach; ?>
</select>
</div>
</fieldset>
<fieldset class="control-group">
<label class="control-label"><?php echo t('Título del Conjunto de Datos') ?><span class="formulario_requerido">*</span></label>
<div class="controls">
<input maxlength="150" placeholder="Ej. Elementos Culturales" class="form-control" type="text" name="datasets_title" id="datasets_title" value="<?php echo ( isset( $datasets_title ) ) ? $datasets_title : ''; ?>">
</div>
</fieldset>
<fieldset class="control-group datasets_description">
<label class="control-label"><?php echo t('Descripción') ?></label>
<div class="controls">
<textarea placeholder="Descripción detallada del Conjunto de Datos" class="form-control" rows="5" name="datasets_description"
id="datasets_description"><?php echo (isset($datasets_description)) ? $datasets_description : ''; ?></textarea>
</div>
</fieldset>
<fieldset class="control-group datasets_url">
<label class="control-label"><?php echo t('URL Página de Descarga') ?><span class="formulario_requerido">*</span></label>
<div class="controls">
<input maxlength="255" style="width:100%;" placeholder="Ej: http://www.midominio.gov.py/datos/conjunto-de-datos" type="url" name="datasets_url" id="datasets_url"
value="<?php echo (isset($datasets_url)) ? $datasets_url : ''; ?>">
</div>
</fieldset>
<fieldset class="control-group datasets_author">
<label class="control-label"><?php echo t('Autor') ?> </label>
<div class="controls">
<input maxlength="255" placeholder="Ej: Juan Gonzalez" type="text" name="datasets_author" id="datasets_author"
value="<?php echo (isset($datasets_author)) ? $datasets_author : ''; ?>">
</div>
</fieldset>
<fieldset class="control-group datasets_email_author">
<label class="control-label"><?php echo t('E-mail Autor') ?> </label>
<div class="controls">
<input style="width:100%;" maxlength="255" placeholder="Ej: [email protected]" type="email" name="datasets_email_author" id="datasets_email_author"
value="<?php echo (isset($datasets_email_author)) ? $datasets_email_author : ''; ?>">
</div>
</fieldset>
<fieldset class="control-group datasets_licenseID">
<label class="control-label"><?php echo t('Licencia') ?><span class="formulario_requerido">*</span></label>
<div class="controls"> <!-- FOREACH PARA LISTAR LICENCIAS -->
<?php $datasets_licenseID = isset( $datasets_licenseID ) ? $datasets_licenseID : null; ?>
<select class="form-control" name="datasets_licenseID" id="datasets_licenseID" value="<?php echo $datasets_licenseID; ?>">
<option value="0"> Seleccione una opción </option>
<?php foreach ($licenses as $lic): ?>
<option value="<?php echo $lic['licenseID'] ?>" <?php $selected = $lic['licenseID']==$datasets_licenseID ? "selected" : ""; echo $selected; ?> ><?php echo $lic['license_name'] ?></option>
<?php endforeach; ?>
</select>
</div>
</fieldset>
<fieldset class="control-group datasets_tags">
<label class="control-label"><?php echo t('Etiquetas') ?> </label>
<!-- separado por comas -->
<div class="controls">
<input style="width:100%;" placeholder="Cultura,Transparencia,Elemento Cultural (Separados por comas)" maxlength="255" type="text" name="datasets_tags" id="datasets_tags"
value="<?php echo (isset($datasets_tags)) ? $datasets_tags : ''; ?>">
</div>
</fieldset>
<fieldset class="control-group datasets_version">
<label class="control-label"><?php echo t('Versión') ?> </label>
<div class="controls">
<input placeholder="1.0" maxlength="255" type="text" name="datasets_version" id="datasets_version"
value="<?php echo (isset($datasets_version)) ? $datasets_version : ''; ?>">
</div>
</fieldset>
<fieldset class="control-group offset2">
<div class="clearfix">
<div style="margin-top: 10px;">
<button class="<?php echo $button['class'] ?>" type="submit"><i class='fa fa-check' aria-hidden='true'></i> <?php echo $button['label'] ?></button>
<a class="btn btn-default" href="<?php echo View::url('dashboard/open_data/list_datasets/show/'.$titulo_datasets[0]['opendataID']) ?>">
<i class='fa fa-arrow-left' aria-hidden='true'></i> <?php echo t('Volver a la lista de Conjunto de Datos'); ?>
</a>
</div>
</div>
</fieldset>
</form>
</div>
<div class="col-sm-6 col-xs-12">
<div class="card">
<h2>¿Datos Abiertos?</h2>
<blockquote class="detalle_descripcion">El concepto <b>datos abiertos</b> (open data, en inglés) es una filosofía y práctica que persigue que determinados tipos de datos estén disponibles de forma libre para todo el mundo, sin restricciones de derechos de autor, de patentes o de otros mecanismos de control. La reutilización de la información es el objetivo fundamental de las políticas de Open Data. La información del sector público constituye una materia prima importante para diversos productos y servicios de contenidos digitales.</blockquote>
<h2>¿Que son los Conjunto de Datos?</h2>
<blockquote class="detalle_descripcion">Es un <b>conjunto de información estructurada que describe algún tema(s) de interés</b>. Un conjunto de datos (conocido también por el anglicismo: dataset, comúnmente utilizado en algunos países hispanohablantes) es una colección de datos habitualmente tabulada.
En general y en su versión más simple, un conjunto de datos corresponde a los contenidos de una única tabla de base de datos o una única matriz de datos estadística, donde cada columna de la tabla representa una variable en particular, y cada fila representa a un miembro determinado del conjunto de datos en cuestión.
Un conjunto de datos contiene los valores para cada una de las variables, como por ejemplo la altura y el peso de un objeto, que corresponden a cada miembro del conjunto de datos. Cada uno de estos valores se conoce con el nombre de dato. El conjunto de datos puede incluir datos para uno o más miembros en función de su número de filas.</blockquote>
</div>
</div>
</div>
<?php endif; ?>
<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper(); ?>
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_data_factory/lib/2018-06-01/generated/azure_mgmt_data_factory/models/greenplum_table_dataset.rb | 5418 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataFactory::Mgmt::V2018_06_01
module Models
#
# Greenplum Database dataset.
#
class GreenplumTableDataset < Dataset
include MsRestAzure
def initialize
@type = "GreenplumTable"
end
attr_accessor :type
# @return This property will be retired. Please consider using schema +
# table properties instead.
attr_accessor :table_name
# @return The table name of Greenplum. Type: string (or Expression with
# resultType string).
attr_accessor :table
# @return The schema name of Greenplum. Type: string (or Expression with
# resultType string).
attr_accessor :greenplum_table_dataset_schema
#
# Mapper for GreenplumTableDataset class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'GreenplumTable',
type: {
name: 'Composite',
class_name: 'GreenplumTableDataset',
model_properties: {
additional_properties: {
client_side_validation: true,
required: false,
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'ObjectElementType',
type: {
name: 'Object'
}
}
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
},
structure: {
client_side_validation: true,
required: false,
serialized_name: 'structure',
type: {
name: 'Object'
}
},
schema: {
client_side_validation: true,
required: false,
serialized_name: 'schema',
type: {
name: 'Object'
}
},
linked_service_name: {
client_side_validation: true,
required: true,
serialized_name: 'linkedServiceName',
default_value: {},
type: {
name: 'Composite',
class_name: 'LinkedServiceReference'
}
},
parameters: {
client_side_validation: true,
required: false,
serialized_name: 'parameters',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'ParameterSpecificationElementType',
type: {
name: 'Composite',
class_name: 'ParameterSpecification'
}
}
}
},
annotations: {
client_side_validation: true,
required: false,
serialized_name: 'annotations',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ObjectElementType',
type: {
name: 'Object'
}
}
}
},
folder: {
client_side_validation: true,
required: false,
serialized_name: 'folder',
type: {
name: 'Composite',
class_name: 'DatasetFolder'
}
},
type: {
client_side_validation: true,
required: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
table_name: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.tableName',
type: {
name: 'Object'
}
},
table: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.table',
type: {
name: 'Object'
}
},
greenplum_table_dataset_schema: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.schema',
type: {
name: 'Object'
}
}
}
}
}
end
end
end
end
| mit |
mg6maciej/parcelable-test-support | src/androidTest/java/pl/mg6/testsupport/data/Complex.java | 1718 | package pl.mg6.testsupport.data;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public final class Complex implements Parcelable {
private final Simple simple;
private final Hrisey hrisey;
public final List<String> list;
public Complex(Simple simple, Hrisey hrisey, List<String> list) {
this.simple = simple;
this.hrisey = hrisey;
this.list = list;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.simple, flags);
dest.writeParcelable(this.hrisey, flags);
if (this.list == null) {
dest.writeInt(-1);
} else {
dest.writeInt(this.list.size());
for (String value : this.list) {
dest.writeString(value);
}
}
}
private Complex(Parcel in) {
this.simple = in.readParcelable(Simple.class.getClassLoader());
this.hrisey = in.readParcelable(Hrisey.class.getClassLoader());
int size = in.readInt();
if (size == -1) {
this.list = null;
} else {
this.list = new ArrayList<>();
while (size > 0) {
this.list.add(in.readString());
size--;
}
}
}
public static final Parcelable.Creator<Complex> CREATOR = new Parcelable.Creator<Complex>() {
public Complex createFromParcel(Parcel source) {
return new Complex(source);
}
public Complex[] newArray(int size) {
return new Complex[size];
}
};
}
| mit |
abhacid/cAlgoBot | Sources/Indicators/Round Numbers/Round Numbers/Round Numbers.cs | 861 | using System;
using cAlgo.API;
namespace cAlgo.Indicators
{
[Indicator(IsOverlay = true, AccessRights = AccessRights.None)]
public class RoundNumbers : Indicator
{
[Parameter(DefaultValue = 100)]
public int StepPips { get; set; }
protected override void Initialize()
{
double max = MarketSeries.High.Maximum(MarketSeries.High.Count);
double min = MarketSeries.Low.Minimum(MarketSeries.Low.Count);
double step = Symbol.PipSize * StepPips;
double start = Math.Floor(min / step) * step;
for (double level = start; level <= max + step; level += step)
{
ChartObjects.DrawHorizontalLine("line_" + level, level, Colors.Gray);
}
}
public override void Calculate(int index)
{
}
}
}
| mit |
CraveFood/farmblocks | packages/dropdown/src/components/Dropdown.js | 2025 | import React from "react";
import PropTypes from "prop-types";
import {
Button as AriaButtonWrapper,
Wrapper as AriaWrapper,
Menu,
} from "react-aria-menubutton";
import Button from "@crave/farmblocks-button";
import { SmChevronDown } from "@crave/farmblocks-icon";
import DropdownWrapper from "../styledComponents/DropdownWrapper";
import DropdownMenuWrapper from "../styledComponents/DropdownMenuWrapper";
const Dropdown = (props) => {
const [isMenuOpen, setIsMenuOpen] = React.useState(false);
return (
<DropdownWrapper className={props.className}>
<AriaWrapper
onSelection={props.handleSelection}
onMenuToggle={({ isOpen }) => {
setIsMenuOpen(isOpen);
props.onMenuToggle?.({ isOpen });
}}
>
<AriaButtonWrapper>
{props.trigger || (
<Button
rightIcon={<SmChevronDown />}
text={props.text}
ref={props.innerRef}
active={isMenuOpen}
{...props.buttonProps}
className="menuButton"
/>
)}
</AriaButtonWrapper>
<Menu>
<DropdownMenuWrapper
align={props.align}
zIndex={props.zIndex}
width={props.width}
maxHeight={props.maxHeight}
>
<ul>{props.children}</ul>
</DropdownMenuWrapper>
</Menu>
</AriaWrapper>
</DropdownWrapper>
);
};
Dropdown.defaultProps = {
handleSelection: () => false,
text: "",
align: "left",
};
Dropdown.propTypes = {
handleSelection: PropTypes.func,
onMenuToggle: PropTypes.func,
children: PropTypes.node.isRequired,
text: PropTypes.string,
align: PropTypes.oneOf(["left", "right"]),
zIndex: PropTypes.number,
width: PropTypes.string,
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
maxHeight: PropTypes.string,
className: PropTypes.string,
buttonProps: PropTypes.object,
trigger: PropTypes.node,
};
export default Dropdown;
| mit |
Akkowicz/webdev-assignments | node_modules/@material/textfield/label/constants.js | 805 | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @enum {string} */
const cssClasses = {
LABEL_FLOAT_ABOVE: 'mdc-text-field__label--float-above',
LABEL_SHAKE: 'mdc-text-field__label--shake',
};
export {cssClasses};
| mit |
FedericoGuidi/FoodLocker | test/controllers/users_controller_test.rb | 2595 | require 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
@other_user = users(:archer)
end
test "should redirect index when not logged in" do
get users_path
assert_redirected_to login_url
end
test "should get new" do
get signup_path
assert_response :success
end
test "should redirect edit when not logged in" do
get edit_user_path(@user)
assert_not flash.empty?
assert_redirected_to login_url
end
test "should redirect update when not logged in" do
patch user_path(@user), params: { user: { name: @user.name,
email: @user.email } }
assert_not flash.empty?
assert_redirected_to login_url
end
test "should not allow the admin attribute to be edited via the web" do
log_in_as(@other_user)
assert_not @other_user.admin?
patch user_path(@other_user), params: {
user: { password: '',
password_confirmation: '',
admin: true } }
assert_not @other_user.reload.admin?
end
test "should redirect edit when logged in as wrong user" do
log_in_as(@other_user)
get edit_user_path(@user)
assert flash.empty?
assert_redirected_to root_url
end
test "should redirect update when logged in as wrong user" do
log_in_as(@other_user)
patch user_path(@user), params: { user: { name: @user.name,
email: @user.email } }
assert flash.empty?
assert_redirected_to root_url
end
test "should redirect destroy when not logged in" do
assert_no_difference 'User.count' do
delete user_path(@user)
end
assert_redirected_to login_url
end
test "should redirect destroy when logged in as a non-admin" do
log_in_as(@other_user)
assert_no_difference 'User.count' do
delete user_path(@user)
end
assert_redirected_to root_url
end
test "should redirect following when not logged in" do
get following_user_path(@user)
assert_redirected_to login_url
end
test "should redirect followers when not logged in" do
get followers_user_path(@user)
assert_redirected_to login_url
end
end
| mit |
TwineTree/XmlNotepad | src/XmlNotepad/XmlCache.cs | 22176 | using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using System.Text;
using System.Net;
using System.Net.Cache;
namespace XmlNotepad
{
/// <summary>
/// XmlCache wraps an XmlDocument and provides the stuff necessary for an "editor" in terms
/// of watching for changes on disk, notification when the file has been reloaded, and keeping
/// track of the current file name and dirty state.
/// </summary>
public class XmlCache : IDisposable
{
string filename;
string xsltFilename;
bool dirty;
DomLoader loader;
XmlDocument doc;
FileSystemWatcher watcher;
int retries;
Timer timer = new Timer();
ISynchronizeInvoke sync;
//string namespaceUri = string.Empty;
SchemaCache schemaCache;
Dictionary<XmlNode, XmlSchemaInfo> typeInfo;
int batch;
DateTime lastModified;
Checker checker;
IServiceProvider site;
public event EventHandler FileChanged;
public event EventHandler<ModelChangedEventArgs> ModelChanged;
public XmlCache(IServiceProvider site, ISynchronizeInvoke sync)
{
this.loader = new DomLoader(site);
this.schemaCache = new SchemaCache(site);
this.site = site;
this.sync = sync;
this.Document = new XmlDocument();
this.timer.Tick += new EventHandler(Reload);
this.timer.Interval = 1000;
this.timer.Enabled = false;
}
~XmlCache() {
Dispose(false);
}
public Uri Location {
get { return new Uri(this.filename); }
}
public string FileName {
get { return this.filename; }
}
public bool IsFile {
get {
if (!string.IsNullOrEmpty(this.filename)) {
return this.Location.IsFile;
}
return false;
}
}
/// <summary>
/// File path to (optionally user-specified) xslt file.
/// </summary>
public string XsltFileName
{
get {
return this.xsltFilename;
}
set { this.xsltFilename = value; }
}
public bool Dirty
{
get { return this.dirty; }
}
public XmlResolver SchemaResolver {
get {
return this.schemaCache.Resolver;
}
}
public XPathNavigator Navigator
{
get
{
XPathDocument xdoc = new XPathDocument(this.filename);
XPathNavigator nav = xdoc.CreateNavigator();
return nav;
}
}
public void ValidateModel(TaskHandler handler) {
this.checker = new Checker(handler);
checker.Validate(this);
}
public XmlDocument Document
{
get { return this.doc; }
set
{
if (this.doc != null)
{
this.doc.NodeChanged -= new XmlNodeChangedEventHandler(OnDocumentChanged);
this.doc.NodeInserted -= new XmlNodeChangedEventHandler(OnDocumentChanged);
this.doc.NodeRemoved -= new XmlNodeChangedEventHandler(OnDocumentChanged);
}
this.doc = value;
if (this.doc != null)
{
this.doc.NodeChanged += new XmlNodeChangedEventHandler(OnDocumentChanged);
this.doc.NodeInserted += new XmlNodeChangedEventHandler(OnDocumentChanged);
this.doc.NodeRemoved += new XmlNodeChangedEventHandler(OnDocumentChanged);
}
}
}
public Dictionary<XmlNode, XmlSchemaInfo> TypeInfoMap {
get { return this.typeInfo; }
set { this.typeInfo = value; }
}
public XmlSchemaInfo GetTypeInfo(XmlNode node) {
if (this.typeInfo == null) return null;
if (this.typeInfo.ContainsKey(node)) {
return this.typeInfo[node];
}
return null;
}
public XmlSchemaElement GetElementType(XmlQualifiedName xmlQualifiedName)
{
if (this.schemaCache != null)
{
return this.schemaCache.GetElementType(xmlQualifiedName);
}
return null;
}
public XmlSchemaAttribute GetAttributeType(XmlQualifiedName xmlQualifiedName)
{
if (this.schemaCache != null)
{
return this.schemaCache.GetAttributeType(xmlQualifiedName);
}
return null;
}
/// <summary>
/// Provides schemas used for validation.
/// </summary>
public SchemaCache SchemaCache
{
get { return this.schemaCache; }
set { this.schemaCache = value; }
}
/// <summary>
/// Loads an instance of xml.
/// Load updated to handle validation when instance doc refers to schema.
/// </summary>
/// <param name="file">Xml instance document</param>
/// <returns></returns>
public void Load(string file)
{
this.Clear();
loader = new DomLoader(this.site);
StopFileWatch();
Uri uri = new Uri(file, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri) {
Uri resolved = new Uri(new Uri(Directory.GetCurrentDirectory() + "\\"), uri);
file = resolved.LocalPath;
uri = resolved;
}
this.filename = file;
this.lastModified = this.LastModTime;
this.dirty = false;
StartFileWatch();
XmlReaderSettings settings = GetReaderSettings();
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationEvent);
using (XmlReader reader = XmlReader.Create(file, settings)) {
this.Document = loader.Load(reader);
}
this.xsltFilename = this.loader.XsltFileName;
// calling this event will cause the XmlTreeView to populate
FireModelChanged(ModelChangeType.Reloaded, this.doc);
}
public void Load(XmlReader reader, string fileName)
{
this.Clear();
loader = new DomLoader(this.site);
StopFileWatch();
Uri uri = new Uri(fileName, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri)
{
Uri resolved = new Uri(new Uri(Directory.GetCurrentDirectory() + "\\"), uri);
fileName = resolved.LocalPath;
uri = resolved;
}
this.filename = fileName;
this.lastModified = this.LastModTime;
this.dirty = false;
StartFileWatch();
this.Document = loader.Load(reader);
this.xsltFilename = this.loader.XsltFileName;
// calling this event will cause the XmlTreeView to populate
FireModelChanged(ModelChangeType.Reloaded, this.doc);
}
internal XmlReaderSettings GetReaderSettings() {
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
settings.CheckCharacters = false;
settings.XmlResolver = new XmlProxyResolver(this.site);
return settings;
}
public void ExpandIncludes() {
if (this.Document != null) {
this.dirty = true;
XmlReaderSettings s = new XmlReaderSettings();
s.ProhibitDtd = false;
s.XmlResolver = new XmlProxyResolver(this.site);
using (XmlReader r = XmlIncludeReader.CreateIncludeReader(this.Document, s, this.FileName)) {
this.Document = loader.Load(r);
}
// calling this event will cause the XmlTreeView to populate
FireModelChanged(ModelChangeType.Reloaded, this.doc);
}
}
public void BeginUpdate() {
if (batch == 0)
FireModelChanged(ModelChangeType.BeginBatchUpdate, this.doc);
batch++;
}
public void EndUpdate() {
batch--;
if (batch == 0)
FireModelChanged(ModelChangeType.EndBatchUpdate, this.doc);
}
public LineInfo GetLineInfo(XmlNode node) {
return loader.GetLineInfo(node);
}
void OnValidationEvent(object sender, ValidationEventArgs e)
{
// todo: log errors in error list window.
}
public void Reload()
{
string filename = this.filename;
Clear();
Load(filename);
}
public void Clear()
{
this.Document = new XmlDocument();
StopFileWatch();
this.filename = null;
FireModelChanged(ModelChangeType.Reloaded, this.doc);
}
public void Save()
{
Save(this.filename);
}
public Encoding GetEncoding() {
XmlDeclaration xmldecl = doc.FirstChild as XmlDeclaration;
Encoding result = null;
if (xmldecl != null)
{
try
{
string e = xmldecl.Encoding;
if (!string.IsNullOrEmpty(e))
{
result = Encoding.GetEncoding(e);
}
}
catch (Exception)
{
}
}
if (result == null)
{
// default is UTF-8.
result = Encoding.UTF8;
}
return result;
}
internal static Encoding SniffByteOrderMark(byte[] bytes, int len)
{
if (len >= 3 && bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf )
{
return Encoding.UTF8;
}
else if (len >= 4 && ((bytes[0] == 0x00 && bytes[1] == 0x00 && bytes[2] == 0xfe && bytes[3] == 0xff) || (bytes[0] == 0xfe && bytes[1] == 0xff && bytes[2] == 0xfe && bytes[3] == 0xff)))
{
return Encoding.GetEncoding(12001); // big endian UTF-32.
}
else if (len >= 4 && ((bytes[0] == 0xff && bytes[1] == 0xfe && bytes[2] == 0x00 && bytes[3] == 0x00) || (bytes[0] == 0xff && bytes[1] == 0xfe && bytes[2] == 0xff && bytes[3] == 0xfe) ))
{
return Encoding.UTF32; // skip UTF-32 little endian BOM
}
else if (len >= 2 && bytes[0] == 0xff && bytes[1] == 0xfe )
{
return Encoding.Unicode; // skip UTF-16 little endian BOM
}
else if (len >= 2 && bytes[0] == 0xf2 && bytes[1] == 0xff )
{
return Encoding.BigEndianUnicode; // skip UTF-16 big endian BOM
}
return null;
}
public void AddXmlDeclarationWithEncoding()
{
XmlDeclaration xmldecl = doc.FirstChild as XmlDeclaration;
if (xmldecl == null)
{
doc.InsertBefore(doc.CreateXmlDeclaration("1.0", "utf-8", null), doc.FirstChild);
}
else
{
string e = xmldecl.Encoding;
if (string.IsNullOrEmpty(e))
{
xmldecl.Encoding = "utf-8";
}
}
}
public void Save(string name)
{
try
{
StopFileWatch();
XmlWriterSettings s = new XmlWriterSettings();
Utilities.InitializeWriterSettings(s, this.site);
var encoding = GetEncoding();
s.Encoding = encoding;
bool noBom = false;
if (this.site != null)
{
Settings settings = (Settings)this.site.GetService(typeof(Settings));
if (settings != null)
{
noBom = (bool)settings["NoByteOrderMark"];
if (noBom)
{
// then we must have an XML declaration with an encoding attribute.
AddXmlDeclarationWithEncoding();
}
}
}
if (noBom)
{
MemoryStream ms = new MemoryStream();
using (XmlWriter w = XmlWriter.Create(ms, s))
{
doc.Save(w);
}
ms.Seek(0, SeekOrigin.Begin);
using (FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write, FileShare.None))
{
byte[] bytes = new byte[16000];
int len = ms.Read(bytes, 0, bytes.Length);
int start = 0;
Encoding sniff = SniffByteOrderMark(bytes, len);
if (sniff != null)
{
if (sniff == Encoding.UTF8)
{
start = 3;
}
else if (sniff == Encoding.GetEncoding(12001) || sniff == Encoding.UTF32) // UTF-32.
{
start = 4;
}
else if (sniff == Encoding.Unicode || sniff == Encoding.BigEndianUnicode) // UTF-16.
{
start = 2;
}
}
while (len > 0)
{
fs.Write(bytes, start, len - start);
len = ms.Read(bytes, 0, bytes.Length);
start = 0;
}
}
}
else
{
using (XmlWriter w = XmlWriter.Create(name, s))
{
doc.Save(w);
}
}
this.dirty = false;
this.filename = name;
this.lastModified = this.LastModTime;
FireModelChanged(ModelChangeType.Saved, this.doc);
}
finally
{
StartFileWatch();
}
}
public bool IsReadOnly(string filename) {
return File.Exists(filename) &&
(File.GetAttributes(filename) & FileAttributes.ReadOnly) != 0;
}
public void MakeReadWrite(string filename) {
if (!File.Exists(filename))
return;
StopFileWatch();
try {
FileAttributes attrsMinusReadOnly = File.GetAttributes(this.filename) & ~FileAttributes.ReadOnly;
File.SetAttributes(filename, attrsMinusReadOnly);
} finally {
StartFileWatch();
}
}
void StopFileWatch()
{
if (this.watcher != null)
{
this.watcher.Dispose();
this.watcher = null;
}
}
private void StartFileWatch()
{
if (this.filename != null && Location.IsFile && File.Exists(this.filename))
{
string dir = Path.GetDirectoryName(this.filename) + "\\";
this.watcher = new FileSystemWatcher(dir, "*.*");
this.watcher.Changed += new FileSystemEventHandler(watcher_Changed);
this.watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
this.watcher.EnableRaisingEvents = true;
}
else
{
StopFileWatch();
}
}
void StartReload(object sender, EventArgs e)
{
// Apart from retrying, the timer has the nice side effect of also
// collapsing multiple file system events into one timer event.
retries = 3;
timer.Enabled = true;
timer.Start();
}
DateTime LastModTime {
get {
if (Location.IsFile) return File.GetLastWriteTime(this.filename);
return DateTime.Now;
}
}
void Reload(object sender, EventArgs e)
{
try
{
// Only do the reload if the file on disk really is different from
// what we last loaded.
if (this.lastModified < LastModTime) {
// Test if we can open the file (it might still be locked).
using (FileStream fs = new FileStream(this.filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
fs.Close();
}
timer.Enabled = false;
FireFileChanged();
}
}
finally
{
retries--;
if (retries == 0)
{
timer.Enabled = false;
}
}
}
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Changed &&
IsSamePath(this.filename, e.FullPath))
{
sync.BeginInvoke(new EventHandler(StartReload), new object[] { this, EventArgs.Empty });
}
}
private void watcher_Renamed(object sender, RenamedEventArgs e)
{
if (IsSamePath(this.filename, e.OldFullPath))
{
StopFileWatch();
this.filename = e.FullPath;
StartFileWatch();
sync.BeginInvoke(new EventHandler(StartReload), new object[] { this, EventArgs.Empty });
}
}
static bool IsSamePath(string a, string b)
{
return string.Compare(a, b, true) == 0;
}
void FireFileChanged()
{
if (this.FileChanged != null)
{
FileChanged(this, EventArgs.Empty);
}
}
void FireModelChanged(ModelChangeType t, XmlNode node)
{
if (this.ModelChanged != null)
this.ModelChanged(this, new ModelChangedEventArgs(t, node));
}
void OnPIChange(XmlNodeChangedEventArgs e) {
XmlProcessingInstruction pi = (XmlProcessingInstruction)e.Node;
if (pi.Name == "xml-stylesheet") {
if (e.Action == XmlNodeChangedAction.Remove) {
// see if there's another!
pi = (XmlProcessingInstruction)this.doc.SelectSingleNode("processing-instruction('xml-stylesheet')");
}
if (pi != null) {
this.xsltFilename = DomLoader.ParseXsltArgs(pi.Data);
}
}
}
private void OnDocumentChanged(object sender, XmlNodeChangedEventArgs e)
{
// initialize t
ModelChangeType t = ModelChangeType.NodeChanged;
if (e.Node is XmlProcessingInstruction) {
OnPIChange(e);
}
if (XmlHelpers.IsXmlnsNode(e.NewParent) || XmlHelpers.IsXmlnsNode(e.Node)) {
// we flag a namespace change whenever an xmlns attribute changes.
t = ModelChangeType.NamespaceChanged;
XmlNode node = e.Node;
if (e.Action == XmlNodeChangedAction.Remove) {
node = e.OldParent; // since node.OwnerElement link has been severed!
}
this.dirty = true;
FireModelChanged(t, node);
} else {
switch (e.Action) {
case XmlNodeChangedAction.Change:
t = ModelChangeType.NodeChanged;
break;
case XmlNodeChangedAction.Insert:
t = ModelChangeType.NodeInserted;
break;
case XmlNodeChangedAction.Remove:
t = ModelChangeType.NodeRemoved;
break;
}
this.dirty = true;
FireModelChanged(t, e.Node);
}
}
public void Dispose() {
Dispose(true);
}
protected virtual void Dispose(bool disposing) {
if (timer != null) {
timer.Dispose();
timer = null;
}
StopFileWatch();
GC.SuppressFinalize(this);
}
}
public enum ModelChangeType
{
Reloaded,
Saved,
NodeChanged,
NodeInserted,
NodeRemoved,
NamespaceChanged,
BeginBatchUpdate,
EndBatchUpdate,
}
public class ModelChangedEventArgs : EventArgs
{
ModelChangeType type;
XmlNode node;
public ModelChangedEventArgs(ModelChangeType t, XmlNode node)
{
this.type = t;
this.node = node;
}
public XmlNode Node {
get { return node; }
set { node = value; }
}
public ModelChangeType ModelChangeType
{
get { return this.type; }
set { this.type = value; }
}
}
public enum IndentChar {
Space,
Tab
}
} | mit |
sushihangover/Xamarin.Forms.Renderer.Tests | FormsLifeCycle/FormsLifeCycle/Properties/AssemblyInfo.cs | 1037 | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("FormsLifeCycle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SushiHangover")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("SushiHangover/RobertN - 2015")]
[assembly: AssemblyTrademark("SushiHangover")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit |
coltonj96/UsefulCombinators | UsefulCombinators_0.1.8/prototypes/technology/technology.lua | 1893 | data:extend({
{
type = "technology",
name = "useful-combinators",
icon = "__UsefulCombinators__/graphics/technology/clock.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "timer-combinator"
},
{
type = "unlock-recipe",
recipe = "counting-combinator"
},
{
type = "unlock-recipe",
recipe = "random-combinator"
},
{
type = "unlock-recipe",
recipe = "comparator-combinator"
},
{
type = "unlock-recipe",
recipe = "converter-combinator"
},
{
type = "unlock-recipe",
recipe = "min-combinator"
},
{
type = "unlock-recipe",
recipe = "max-combinator"
},
{
type = "unlock-recipe",
recipe = "and-gate-combinator"
},
{
type = "unlock-recipe",
recipe = "nand-gate-combinator"
},
{
type = "unlock-recipe",
recipe = "nor-gate-combinator"
},
{
type = "unlock-recipe",
recipe = "not-gate-combinator"
},
{
type = "unlock-recipe",
recipe = "or-gate-combinator"
},
{
type = "unlock-recipe",
recipe = "xnor-gate-combinator"
},
{
type = "unlock-recipe",
recipe = "xor-gate-combinator"
},
{
type = "unlock-recipe",
recipe = "detector-combinator"
},
{
type = "unlock-recipe",
recipe = "sensor-combinator"
}
},
prerequisites = {"circuit-network"},
unit =
{
count = 100,
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1}
},
time = 15
},
order = "a-d-d"
}
}) | mit |
oknoorap/wpcs | scripts/wordpress-coding-standards/WordPress/Tests/CodeAnalysis/AssignmentInConditionUnitTest.php | 1587 | <?php
/**
* Unit test class for WordPress Coding Standard.
*
* @package WPCS\WordPressCodingStandards
* @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards
* @license https://opensource.org/licenses/MIT MIT
*/
namespace WordPress\Tests\CodeAnalysis;
use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;
/**
* Unit test class for the AssignmentInCondition sniff.
*
* @package WPCS\WordPressCodingStandards
*
* @since 0.14.0
*/
class AssignmentInConditionUnitTest extends AbstractSniffUnitTest {
/**
* Returns the lines where errors should occur.
*
* @return array <int line number> => <int number of errors>
*/
public function getErrorList() {
return array();
}
/**
* Returns the lines where warnings should occur.
*
* @return array <int line number> => <int number of warnings>
*/
public function getWarningList() {
return array(
29 => 1,
30 => 1,
31 => 1,
32 => 1,
33 => 1,
34 => 1,
35 => 1,
36 => 1,
37 => 1,
38 => 1,
39 => 1,
40 => 1,
41 => 1,
42 => 1,
43 => 1,
44 => 2,
46 => 1,
47 => 1,
50 => 1,
51 => 1,
52 => 1,
53 => 1,
54 => 1,
55 => 1,
56 => 1,
58 => 1,
60 => 1,
63 => 2,
67 => 1,
68 => 2,
71 => 1,
73 => 1,
75 => 1,
79 => 1,
80 => 1,
81 => 1,
83 => 1,
84 => 1,
86 => 1,
87 => 1,
88 => 1,
91 => 1,
95 => 1,
106 => 1,
107 => 1,
108 => 2,
109 => 1,
110 => 1,
111 => 2,
112 => 3,
);
}
} // End class.
| mit |
stefanw/froide | frontend/javascript/alpha/InfoBox.ts | 2585 | // interface IHTMLToolTipElement extends HTMLInputElement { Tooltip: any | null; }
export default class InfoBox {
element: HTMLElement
editButton: HTMLElement | undefined
copyUrlTrigger: HTMLElement | undefined
editPanel: HTMLElement | undefined
infoList: HTMLElement | undefined
editPanelIsVisible: boolean | undefined
constructor () {
this.element = document.getElementById('infobox') as HTMLElement
// edit button listener
this.editButton = this.element.querySelector('.info-box__edit-button') as HTMLElement
if (this.editButton) {
this.editPanel = this.element.querySelector('.info-box__edit-panel') as HTMLElement
this.editPanelIsVisible = false
this.infoList = this.element.querySelector('.info-box__list') as HTMLElement
// event listeners
this.editButton.addEventListener('click', this.editButtonClickCallback.bind(this))
}
// copy short url listener
this.copyUrlTrigger = this.element.querySelector('.copy-short-url-trigger') as HTMLElement
if (this.copyUrlTrigger) {
this.copyUrlTrigger.addEventListener('click', this.copyShortUrlTriggerClickCallback.bind(this))
}
}
editButtonClickCallback (e: MouseEvent) {
e.preventDefault()
if (this.editButton && this.editPanel && this.infoList) {
this.editPanel.classList.toggle('d-none')
this.infoList.classList.toggle('d-none')
this.editButton.children[0].classList.toggle('d-none')
this.editButton.children[1].classList.toggle('d-none')
this.editPanelIsVisible = !this.editPanelIsVisible
}
}
copyShortUrlTriggerClickCallback (e: MouseEvent) {
e.preventDefault()
const el = e.target as IHTMLToolTipElement
const url = el.getAttribute('href')
if (url) {
this.copyToClipboard(url)
}
if (el.Tooltip) {
const originalTitle = el.title;
el.title = el.dataset.copied || ""
el.Tooltip.hide()
const switchTooltip = () => {
el.Tooltip.show()
el.removeEventListener("hidden.bs.tooltip", switchTooltip)
window.setTimeout(() => {
el.Tooltip.hide()
el.title = originalTitle
}, 2500)
}
el.addEventListener("hidden.bs.tooltip", switchTooltip);
}
}
copyToClipboard (text: string) {
const el = document.createElement('textarea')
el.value = text
el.setAttribute('readonly', '')
el.style.position = 'absolute'
el.style.left = '-9999px'
document.body.appendChild(el)
el.select()
document.execCommand('copy')
document.body.removeChild(el)
}
} | mit |
davepacheco/matty | lib/matty.js | 6178 | #!/usr/bin/env node
// vim: ft=javascript
var mod_assert = require('assert');
var mod_events = require('events');
var mod_fs = require('fs');
var mod_http = require('http');
var mod_path = require('path');
var mod_util = require('util');
var mod_extsprintf = require('extsprintf');
var mod_jsprim = require('jsprim');
var mod_mkdirp = require('mkdirp');
var mod_restify = require('restify');
var mod_vasync = require('vasync');
var mod_verror = require('verror');
var sprintf = mod_extsprintf.sprintf;
var EventEmitter = mod_events.EventEmitter;
var VError = mod_verror.VError;
/* Public interface */
exports.createCrawler = createCrawler;
function createCrawler(conf, log)
{
var c = new Crawler(conf, log);
c.init();
return (c);
}
function parseDate(str)
{
var d = Date.parse(str);
if (isNaN(d))
return (null);
return (new Date(d));
}
function Crawler(conf, log)
{
EventEmitter.call(this);
var s, e;
mod_assert.equal(typeof (conf), 'object');
mod_assert.ok(conf !== null);
if ((s = parseDate(conf['start'])) === null)
throw (new VError('invalid start date: "%s"', conf['start']));
if ((e = parseDate(conf['end'])) === null)
throw (new VError('invalid end date: "%s"', conf['end']));
this.c_conf = mod_jsprim.deepCopy(conf);
this.c_start = s;
this.c_end = e;
this.c_log = log;
this.c_queue = null;
this.c_dfl = null;
this.c_go = false;
this.c_client = null;
this.c_nrequests = 0;
this.c_startts = Date.now();
this.c_donets = null;
}
mod_util.inherits(Crawler, EventEmitter);
Crawler.prototype.init = function ()
{
var c = this;
var dflpath = mod_path.join(__dirname, '../etc/defaults.json');
mod_fs.readFile(dflpath, function (err, contents) {
if (err) {
c.emit('error',
new VError(err, 'failed to read defaults'));
return;
}
try {
c.c_dfl = JSON.parse(contents);
c.c_conf.__proto__ = c.c_dfl;
} catch (ex) {
c.emit('error',
new VError(ex, 'failed to parse defaults'));
return;
}
c.initFini();
});
};
Crawler.prototype.initFini = function ()
{
var c = this;
this.c_queue = mod_vasync.queue(this.fetchOne.bind(this),
this.c_conf['concurrency']);
this.c_queue.drain = function () {
c.c_donets = Date.now();
c.emit('end');
};
this.c_client = mod_restify.createHttpClient({
'log': this.c_log,
'url': this.c_conf['server']
});
mod_http.globalAgent.maxSockets = this.c_conf['concurrency'];
this.initStorage();
this.emit('ready');
if (this.c_go)
this.start();
this.on('end', function () { c.c_client.close(); });
};
Crawler.prototype.initStorage = function ()
{
var c = this;
this.on('file', function (path, instream) {
/*
* XXX This will generate an enormous number more syscalls than
* necessary. Since we're limited by server-side throughput,
* it's not clear that's a problem for us at the moment.
*/
instream.pause();
var filepath = mod_path.join(c.c_conf['output'], path);
mod_mkdirp(mod_path.dirname(filepath), function (err) {
if (err) {
instream.destroy();
c.emit('error', err);
return;
}
var outstream = mod_fs.createWriteStream(
mod_path.join(c.c_conf['output'], path));
instream.pipe(outstream);
instream.resume();
});
});
};
Crawler.prototype.start = function ()
{
var c = this;
if (this.c_dfl === null) {
this.c_go = true;
return;
}
var start = this.c_start.getTime();
var end = this.c_end.getTime();
var when, url;
for (when = start; when <= end; when += 86400000) {
url = this.urlDate(new Date(when));
this.c_queue.push(url);
}
if (this.c_queue.queued.length + this.c_queue.npending === 0)
process.nextTick(function () { c.emit('end'); });
};
Crawler.prototype.urlDate = function (when)
{
return (sprintf('year_%s/month_%02d/day_%02d/', when.getUTCFullYear(),
when.getUTCMonth() + 1, when.getUTCDate()));
};
Crawler.prototype.fetchOne = function (url, callback)
{
var c = this;
var path = mod_path.join(this.c_conf['root'], url);
/*
* Users can configure a regex that must match everything we fetch, but
* top-level game directories must be explicitly allowed.
*/
if (url.length > 'year_yyyy/month_yy/day_yy/'.length &&
!this.shouldFetch(url)) {
callback();
return;
}
this.c_log.debug('fetch', path);
this.c_nrequests++;
this.c_client.get(path, function (err, request) {
if (err) {
c.emit('error', err);
return;
}
request.on('result', function (err2, response) {
if (err2) {
c.emit('error', err2);
return;
}
if (mod_jsprim.startsWith(
response.headers['content-type'], 'text/html'))
c.gotDirectory(url, response, callback);
else
c.gotFile(url, response, callback);
});
});
};
Crawler.prototype.gotDirectory = function (url, response, callback)
{
this.emit('directory', url);
var c = this;
var data = '';
response.on('data', function (chunk) {
data += chunk.toString('utf8');
});
response.on('end', function () {
/*
* This is not especially robust.
*/
data.split(/\n/).forEach(function (line) {
/* JSSTYLED */
var match = /<li><a href="([^"]+)">.*<\/a><\/li>/.
exec(line);
if (!match || match.length < 2 || match[1][0] == '/')
return;
c.c_queue.push(mod_path.join(url, match[1]));
});
callback();
});
};
Crawler.prototype.shouldFetch = function (uri)
{
var i, pattern;
var isdir = uri[uri.length - 1] == '/';
for (i = 0; i < this.c_conf['match_all'].length; i++) {
pattern = new RegExp(this.c_conf['match_all'][i]);
if (!pattern.test(uri))
return (false);
}
if (isdir)
return (true);
for (i = 0; i < this.c_conf['file_match'].length; i++) {
pattern = new RegExp(this.c_conf['file_match'][i]);
if (pattern.test(uri))
return (true);
}
return (false);
};
Crawler.prototype.gotFile = function (url, response, callback)
{
if (this.listeners('file').length > 0)
this.emit('file', url, response);
else
response.on('data', function () {});
response.on('end', function () { callback(); });
};
Crawler.prototype.stats = function ()
{
return ({
'nrequests': this.c_nrequests,
'time': this.c_donets !== null ?
this.c_donets - this.c_startts : '<still running>'
});
};
| mit |
chemila/symfony | app/cache/dev/assetic/config/2/2144651f778c429e6d150dfe52f086c8.php | 152 | <?php
// /home/ethan/www/dev.symfony.com/vendor/symfony/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/base.html.twig
return array (
);
| mit |
OlegRy/Aukolnine | js/change_password.js | 570 | function change_password(login)
{
var current = $('#cur_password').val();
var new_password = $('#new_password').val();
var login = $('#my_login').val();
$.ajax({
type: "POST",
url: "/personal/change_password",
data: {
'current': current,
'new_password': new_password
},
success: function(msg){
if(msg == 'error')
{
$('#error_password').css('display', 'block');
}
else if(msg == 'success')
{
$('#error_password').css('display', 'none');
$('#success_password').css('display', 'block');
}
}
});
} | mit |
jchip/gulp-clap | test/flags-require.js | 3082 | 'use strict';
var expect = require('expect');
var runner = require('gulp-test-tools').gulpRunner;
var skipLines = require('gulp-test-tools').skipLines;
var headLines = require('gulp-test-tools').headLines;
var eraseTime = require('gulp-test-tools').eraseTime;
var eraseLapse = require('gulp-test-tools').eraseLapse;
var path = require('path');
describe('flag: --require', function() {
it('requires module before running gulpfile', function(done) {
runner({ verbose: false })
.gulp('--require ../test-module.js', '--cwd ./test/fixtures/gulpfiles')
.run(cb);
function cb(err, stdout) {
var insideLog = headLines(stdout, 1);
expect(insideLog).toEqual('inside test module');
var requireLog = eraseTime(headLines(stdout, 1, 1));
expect(requireLog).toEqual(
'Requiring external module ../test-module.js');
var chgWorkdirLog = headLines(stdout, 1, 2);
var workdir = 'test/fixtures/gulpfiles'.replace(/\//g, path.sep);
expect(chgWorkdirLog).toMatch('Working directory changed to ');
expect(chgWorkdirLog).toMatch(workdir);
stdout = eraseLapse(eraseTime(skipLines(stdout, 4)));
expect(stdout).toEqual(
'Starting \'default\'...\n' +
'Starting \'test1\'...\n' +
'Starting \'noop\'...\n' +
'Finished \'noop\' after ?\n' +
'Finished \'test1\' after ?\n' +
'Starting \'test3\'...\n' +
'Starting \'described\'...\n' +
'Finished \'described\' after ?\n' +
'Finished \'test3\' after ?\n' +
'Starting \'noop\'...\n' +
'Finished \'noop\' after ?\n' +
'Finished \'default\' after ?\n' +
''
);
done(err);
}
});
it('errors if module doesn\'t exist', function(done) {
runner({ verbose: false })
.gulp('--require ./null-module.js', '--cwd ./test/fixtures/gulpfiles')
.run(cb);
function cb(err, stdout, stderr) {
expect(stdout).toNotMatch('inside test module');
expect(stdout).toNotMatch(
'Requiring external module ../test-module.js');
var chgWorkdirLog = headLines(stdout, 1);
var workdir = 'test/fixtures/gulpfiles'.replace(/\//g, path.sep);
expect(chgWorkdirLog).toMatch('Working directory changed to ');
expect(chgWorkdirLog).toMatch(workdir);
stdout = eraseLapse(eraseTime(skipLines(stdout, 2)));
expect(stdout).toEqual(
'Starting \'default\'...\n' +
'Starting \'test1\'...\n' +
'Starting \'noop\'...\n' +
'Finished \'noop\' after ?\n' +
'Finished \'test1\' after ?\n' +
'Starting \'test3\'...\n' +
'Starting \'described\'...\n' +
'Finished \'described\' after ?\n' +
'Finished \'test3\' after ?\n' +
'Starting \'noop\'...\n' +
'Finished \'noop\' after ?\n' +
'Finished \'default\' after ?\n' +
''
);
stderr = eraseTime(stderr);
expect(stderr).toEqual(
'Failed to load external module ./null-module.js\n');
done(err);
}
});
});
| mit |
hiperz/ConvNetSharp | src/ConvNetSharp.Core/Layers/TanhLayer.cs | 1135 | using System;
using System.Collections.Generic;
using ConvNetSharp.Volume;
namespace ConvNetSharp.Core.Layers
{
public class TanhLayer<T> : LayerBase<T> where T : struct, IEquatable<T>, IFormattable
{
public TanhLayer(Dictionary<string, object> data) : base(data)
{
}
public TanhLayer()
{
}
public override void Backward(Volume<T> outputGradient)
{
this.OutputActivationGradients = outputGradient;
this.OutputActivation.DoTanhGradient(this.InputActivation, this.OutputActivationGradients, this.InputActivationGradients);
}
protected override Volume<T> Forward(Volume<T> input, bool isTraining = false)
{
input.DoTanh(this.OutputActivation);
return this.OutputActivation;
}
public override void Init(int inputWidth, int inputHeight, int inputDepth)
{
base.Init(inputWidth, inputHeight, inputDepth);
this.OutputDepth = inputDepth;
this.OutputWidth = inputWidth;
this.OutputHeight = inputHeight;
}
}
} | mit |
mmnaseri/spring-data-mock | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcher.java | 613 | package com.mmnaseri.utils.spring.data.domain.impl.matchers;
/**
* This matcher will return {@literal true} if the argument passed is not equal to the value on the
* object, even when their case differences are ignored.
*
* @author Milad Naseri ([email protected])
* @since 1.0 (9/29/15)
*/
public class IsNotLikeMatcher extends AbstractSimpleStringMatcher {
@Override
protected boolean matches(String actual, String argument) {
return (actual == null && argument != null)
|| (actual != null && argument == null)
|| (actual != null && !actual.equalsIgnoreCase(argument));
}
}
| mit |
oviedomonica123/conest-encuesta-backend | db/migrate/20140817003903_create_bloques_instrumentos.rb | 126 | class CreateBloquesInstrumentos < ActiveRecord::Migration
def change
create_join_table :bloques, :instrumentos
end
end
| mit |
GoZOo/Drupaloscopy | hashs-database/hashs/core___assets___vendor___ckeditor___plugins___specialchar___dialogs___lang___cy.js | 5216 | 8.0-alpha3:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha4:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha5:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha6:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha7:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha8:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha9:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha10:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha11:6d3df8721f24bd2cbf7ff76dfeac51c5dee24cd9db3ce42490b553866728a8a4
8.0-alpha12:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0-alpha13:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0.0-alpha14:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0.0-alpha15:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0.0-beta1:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0.0-beta2:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0.0-beta3:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0.0-beta4:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0.0-beta6:2ef43ecac8ff8ebfc334634615abf35a1e5f3444102eac02d137c533d6857bca
8.0.0-beta7:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-beta9:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-beta10:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-beta11:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-beta12:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-beta13:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-beta14:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-beta15:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-beta16:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-rc1:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-rc2:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-rc3:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.0-rc4:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.1:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.2:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.3:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.4:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.5:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.0.6:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.1.0-beta1:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.1.0-beta2:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.0-rc1:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.1:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.2:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.3:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.4:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.5:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.6:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.7:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.8:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.9:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.1.10:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.0-beta1:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.0-beta2:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.0-beta3:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.0-rc1:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.0-rc2:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.1:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.2:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.3:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.4:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.5:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.6:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.3.0-alpha1:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.3.0-beta1:1a81765b63f667371c6243bad2b5ff71de966a9c8aab0541f7c235d2c4422c4a
8.3.0-rc1:1a81765b63f667371c6243bad2b5ff71de966a9c8aab0541f7c235d2c4422c4a
8.2.7:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.3.0-rc2:1a81765b63f667371c6243bad2b5ff71de966a9c8aab0541f7c235d2c4422c4a
8.0.0:0ec002983473a0cbd84117863659699c54cbd29c8335f1ef720e1ab4ad7a2bd0
8.1.0:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.2.0:e4d09af9c1b44036be7ea0ad2ad882c29e87c45bfee23ccc988b7926da740eed
8.3.0:1a81765b63f667371c6243bad2b5ff71de966a9c8aab0541f7c235d2c4422c4a
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.