jvalue _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_arg, bool force_jobject = false) { jvalue v; switch(p_type) { case Variant::BOOL: { if (force_jobject) { jclass bclass = env->FindClass("java/lang/Boolean"); jmethodID ctor = env->GetMethodID(bclass, "<init>", "(Z)V"); jvalue val; val.z = (bool)(*p_arg); jobject obj = env->NewObjectA(bclass, ctor, &val); v.l = obj; } else { v.z=*p_arg; }; } break; case Variant::INT: { if (force_jobject) { jclass bclass = env->FindClass("java/lang/Integer"); jmethodID ctor = env->GetMethodID(bclass, "<init>", "(I)V"); jvalue val; val.i = (int)(*p_arg); jobject obj = env->NewObjectA(bclass, ctor, &val); v.l = obj; } else { v.i=*p_arg; }; } break; case Variant::REAL: { if (force_jobject) { jclass bclass = env->FindClass("java/lang/Double"); jmethodID ctor = env->GetMethodID(bclass, "<init>", "(D)V"); jvalue val; val.d = (double)(*p_arg); jobject obj = env->NewObjectA(bclass, ctor, &val); v.l = obj; } else { v.f=*p_arg; }; } break; case Variant::STRING: { String s = *p_arg; jstring jStr = env->NewStringUTF(s.utf8().get_data()); v.l=jStr; } break; case Variant::STRING_ARRAY: { DVector<String> sarray = *p_arg; jobjectArray arr = env->NewObjectArray(sarray.size(),env->FindClass("java/lang/String"),env->NewStringUTF("")); for(int j=0;j<sarray.size();j++) { env->SetObjectArrayElement(arr,j,env->NewStringUTF( sarray[j].utf8().get_data() )); } v.l=arr; } break; case Variant::DICTIONARY: { Dictionary dict = *p_arg; jclass dclass = env->FindClass("com/android/godot/Dictionary"); jmethodID ctor = env->GetMethodID(dclass, "<init>", "()V"); jobject jdict = env->NewObject(dclass, ctor); Array keys = dict.keys(); jobjectArray jkeys = env->NewObjectArray(keys.size(), env->FindClass("java/lang/String"), env->NewStringUTF("")); for (int j=0; j<keys.size(); j++) { env->SetObjectArrayElement(jkeys, j, env->NewStringUTF(String(keys[j]).utf8().get_data())); }; jmethodID set_keys = env->GetMethodID(dclass, "set_keys", "([Ljava/lang/String;)V"); jvalue val; val.l = jkeys; env->CallVoidMethodA(jdict, set_keys, &val); jobjectArray jvalues = env->NewObjectArray(keys.size(), env->FindClass("java/lang/Object"), NULL); for (int j=0; j<keys.size(); j++) { Variant var = dict[keys[j]]; val = _variant_to_jvalue(env, var.get_type(), &var, true); env->SetObjectArrayElement(jvalues, j, val.l); }; jmethodID set_values = env->GetMethodID(dclass, "set_values", "([Ljava/lang/Object;)V"); val.l = jvalues; env->CallVoidMethodA(jdict, set_values, &val); v.l = jdict; } break; case Variant::INT_ARRAY: { DVector<int> array = *p_arg; jintArray arr = env->NewIntArray(array.size()); DVector<int>::Read r = array.read(); env->SetIntArrayRegion(arr,0,array.size(),r.ptr()); v.l=arr; } break; case Variant::RAW_ARRAY: { DVector<uint8_t> array = *p_arg; jbyteArray arr = env->NewByteArray(array.size()); DVector<uint8_t>::Read r = array.read(); env->SetByteArrayRegion(arr,0,array.size(),reinterpret_cast<const signed char*>(r.ptr())); v.l=arr; } break; case Variant::REAL_ARRAY: { DVector<float> array = *p_arg; jfloatArray arr = env->NewFloatArray(array.size()); DVector<float>::Read r = array.read(); env->SetFloatArrayRegion(arr,0,array.size(),r.ptr()); v.l=arr; } break; default: { v.i = 0; } break; } return v; };
void TForm1::WriteClassifications(Variant &vSheet, std::vector<exlClass> &classes) { lblStatus->Caption = "Приступаю к сортировке классификаций..."; Log->Lines->Add("Приступаю к сортировке классификаций..."); int nReplaced = 1; while(nReplaced > 0) { nReplaced = 0; for (unsigned int i = 0; i < classes.size()-1; i++) { if (classes[i].Name.UpperCase() > classes[i+1].Name.UpperCase()) { exlClass cl = classes[i]; classes[i] = classes[i+1]; classes[i+1] = cl; nReplaced++; } } } Log->Lines->Add("Отсортировано!"); int nRowsCount = vSheet.OlePropertyGet("Cells").OlePropertyGet("Rows").OlePropertyGet("Count"); int nLastRow1 = vSheet.OlePropertyGet("Cells", nRowsCount, 1).OlePropertyGet("End", xlUp).OlePropertyGet("Row"); int nLastRow2 = vSheet.OlePropertyGet("Cells", nRowsCount, 2).OlePropertyGet("End", xlUp).OlePropertyGet("Row"); int nLastRow3 = vSheet.OlePropertyGet("Cells", nRowsCount, 3).OlePropertyGet("End", xlUp).OlePropertyGet("Row"); int nLastRow4 = vSheet.OlePropertyGet("Cells", nRowsCount, 4).OlePropertyGet("End", xlUp).OlePropertyGet("Row"); int nLastRow = 0; nLastRow = std::max(nLastRow, nLastRow1); nLastRow = std::max(nLastRow, nLastRow2); nLastRow = std::max(nLastRow, nLastRow3); nLastRow = std::max(nLastRow, nLastRow4); lblStatus->Caption = "Произвожу очистку классификаций в файле..."; Log->Lines->Add("Произвожу очистку классификаций в файле"); ProgressBar1->Max = nLastRow; ProgressBar1->Min = 0; for (int i = 1; i < nLastRow; i++) { ProgressBar1->Position = i; Application->ProcessMessages(); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",i+1,1).OlePropertySet("Value", WideString("")); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",i+1,2).OlePropertySet("Value", WideString("")); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",i+1,3).OlePropertySet("Value", WideString("")); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",i+1,4).OlePropertySet("Value", WideString("")); } lblStatus->Caption = "Приступаю к записи классификаций в файл..."; Log->Lines->Add("Приступаю к записи в файл " + IntToStr((int)classes.size())); ProgressBar1->Max = classes.size(); ProgressBar1->Min = 0; vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",1,1).OlePropertySet("Value", WideString("Наименование")); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",1,2).OlePropertySet("Value", WideString("Класс")); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",1,3).OlePropertySet("Value", WideString("Комментарий")); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",1,4).OlePropertySet("Value", WideString("Месяца")); for (unsigned int i = 0; i < classes.size(); i++) { exlClass cl = classes[i]; ProgressBar1->Position = i; vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",i+2,1).OlePropertySet("Value", WideString(cl.Name)); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",i+2,2).OlePropertySet("Value", WideString(cl.Class)); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",i+2,3).OlePropertySet("Value", WideString(cl.Comment)); vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",i+2,4).OlePropertySet("Value", WideString(cl.Monthes)); } lblStatus->Caption = ""; }
void TForm1::setBorders(Variant &vSheet, int nRow, int nCol) { vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,nCol).OlePropertyGet("Borders").OlePropertySet("LineStyle", xlContinuous); }
bool TestExtOpenssl::test_openssl_x509_read() { Variant fcert = f_file_get_contents("test/ext/test_x509.crt"); Variant cert = f_openssl_x509_read(fcert); VERIFY(!cert.toObject().isNull()); return Count(true); }
bool UrlFile::open(const String& input_url, const String& mode) { String url = input_url; const char* modestr = mode.c_str(); if (strchr(modestr, '+') || strchr(modestr, 'a') || strchr(modestr, 'w')) { std::string msg = "cannot open a url stream for write/append operation: "; msg += url.c_str(); m_error = msg; return false; } HttpClient http(m_timeout, m_maxRedirect); auto ctx = this->getStreamContext(); if (ctx) { http.setStreamContextOptions(ctx->getOptions()); } m_response.clear(); if (!m_proxyHost.empty()) { http.proxy(m_proxyHost, m_proxyPort, m_proxyUsername, m_proxyPassword); } HeaderMap *pHeaders = nullptr; HeaderMap requestHeaders; if (!m_headers.empty()) { pHeaders = &requestHeaders; for (ArrayIter iter(m_headers); iter; ++iter) { requestHeaders[std::string(iter.first().toString().data())]. push_back(iter.second().toString().data()); } } Variant user = f_parse_url(url, k_PHP_URL_USER); if (user.isString()) { Variant pass = f_parse_url(url, k_PHP_URL_PASS); http.auth(user.toString().c_str(), pass.toString().c_str()); url = HHVM_FN(preg_replace)( s_remove_user_pass_pattern, s_remove_user_pass_replace, url, 1 ).toString(); } int code; req::vector<String> responseHeaders; if (m_get) { code = http.get(url.c_str(), m_response, pHeaders, &responseHeaders); } else { code = http.request(m_method, url.c_str(), m_postData.data(), m_postData.size(), m_response, pHeaders, &responseHeaders); } m_responseHeaders.reset(); for (unsigned int i = 0; i < responseHeaders.size(); i++) { m_responseHeaders.append(responseHeaders[i]); } VMRegAnchor vra; ActRec* fp = vmfp(); if (fp->skipFrame()) fp = g_context->getPrevVMStateSkipFrame(fp); auto id = fp->func()->lookupVarId(s_http_response_header.get()); if (id != kInvalidId) { auto tvTo = frame_local(fp, id); Variant varFrom(m_responseHeaders); const auto tvFrom(varFrom.asTypedValue()); if (tvTo->m_type == KindOfRef) { tvTo = tvTo->m_data.pref->tv(); } tvDup(*tvFrom, *tvTo); } else if ((fp->func()->attrs() & AttrMayUseVV) && fp->hasVarEnv()) { fp->getVarEnv()->set(s_http_response_header.get(), Variant(m_responseHeaders).asTypedValue()); } /* * If code == 0, Curl failed to connect; per PHP5, ignore_errors just means * to not worry if we get an http resonse code that isn't between 200 and 400, * but we shouldn't ignore other errors. * all status codes in the 2xx range are defined by the specification as * successful; * all status codes in the 3xx range are for redirection, and so also should * never fail. */ if ((code >= 200 && code < 400) || (m_ignoreErrors && code != 0)) { setName(url.toCppString()); m_data = const_cast<char*>(m_response.data()); m_len = m_response.size(); return true; } else { m_error = http.getLastError().c_str(); return false; } }
int apc_rfc1867_progress(apc_rfc1867_data *rfc1867ApcData, unsigned int event, void *event_data, void **extra) { switch (event) { case MULTIPART_EVENT_START: { multipart_event_start *data = (multipart_event_start *) event_data; rfc1867ApcData->content_length = data->content_length; rfc1867ApcData->tracking_key.clear(); rfc1867ApcData->name.clear(); rfc1867ApcData->cancel_upload = 0; rfc1867ApcData->temp_filename = NULL; rfc1867ApcData->start_time = my_time(); rfc1867ApcData->bytes_processed = 0; rfc1867ApcData->prev_bytes_processed = 0; rfc1867ApcData->rate = 0; rfc1867ApcData->update_freq = RuntimeOption::Rfc1867Freq; if (rfc1867ApcData->update_freq < 0) { assert(false); // TODO: support percentage // frequency is a percentage, not bytes rfc1867ApcData->update_freq = rfc1867ApcData->content_length * RuntimeOption::Rfc1867Freq / 100; } break; } case MULTIPART_EVENT_FORMDATA: { multipart_event_formdata *data = (multipart_event_formdata *)event_data; if (data->name && !strncasecmp(data->name, RuntimeOption::Rfc1867Name.c_str(), RuntimeOption::Rfc1867Name.size()) && data->value && data->length && data->length < RFC1867_TRACKING_KEY_MAXLEN - RuntimeOption::Rfc1867Prefix.size()) { int len = RuntimeOption::Rfc1867Prefix.size(); if (len > RFC1867_TRACKING_KEY_MAXLEN) { len = RFC1867_TRACKING_KEY_MAXLEN; } rfc1867ApcData->tracking_key = string(RuntimeOption::Rfc1867Prefix.c_str(), len); len = strlen(*data->value); int rem = RFC1867_TRACKING_KEY_MAXLEN - rfc1867ApcData->tracking_key.size(); if (len > rem) len = rem; rfc1867ApcData->tracking_key += string(*data->value, len); rfc1867ApcData->bytes_processed = data->post_bytes_processed; } /* Facebook: Temporary fix for a bug in PHP's rfc1867 code, fixed here for convenience: http://cvs.php.net/viewvc.cgi/php-src/main/ rfc1867.c?r1=1.173.2.1.2.11&r2=1.173.2.1.2.12 */ (*data->newlength) = data->length; break; } case MULTIPART_EVENT_FILE_START: if (!rfc1867ApcData->tracking_key.empty()) { multipart_event_file_start *data = (multipart_event_file_start *)event_data; rfc1867ApcData->bytes_processed = data->post_bytes_processed; int len = strlen(*data->filename); if (len > RFC1867_FILENAME_MAXLEN) len = RFC1867_FILENAME_MAXLEN; rfc1867ApcData->filename = string(*data->filename, len); rfc1867ApcData->temp_filename = NULL; len = strlen(data->name); if (len > RFC1867_NAME_MAXLEN) len = RFC1867_NAME_MAXLEN; rfc1867ApcData->name = string(data->name, len); ArrayInit track(6); track.set(s_total, rfc1867ApcData->content_length); track.set(s_current, rfc1867ApcData->bytes_processed); track.set(s_filename, rfc1867ApcData->filename); track.set(s_name, rfc1867ApcData->name); track.set(s_done, 0); track.set(s_start_time, rfc1867ApcData->start_time); f_apc_store(rfc1867ApcData->tracking_key, track.create(), 3600); } break; case MULTIPART_EVENT_FILE_DATA: if (!rfc1867ApcData->tracking_key.empty()) { multipart_event_file_data *data = (multipart_event_file_data *) event_data; rfc1867ApcData->bytes_processed = data->post_bytes_processed; if (rfc1867ApcData->bytes_processed - rfc1867ApcData->prev_bytes_processed > rfc1867ApcData->update_freq) { Variant v; if (s_apc_store[0].get(rfc1867ApcData->tracking_key, v)) { if (v.is(KindOfArray)) { ArrayInit track(6); track.set(s_total, rfc1867ApcData->content_length); track.set(s_current, rfc1867ApcData->bytes_processed); track.set(s_filename, rfc1867ApcData->filename); track.set(s_name, rfc1867ApcData->name); track.set(s_done, 0); track.set(s_start_time, rfc1867ApcData->start_time); f_apc_store(rfc1867ApcData->tracking_key, track.create(), 3600); } rfc1867ApcData->prev_bytes_processed = rfc1867ApcData->bytes_processed; } } } break; case MULTIPART_EVENT_FILE_END: if (!rfc1867ApcData->tracking_key.empty()) { multipart_event_file_end *data = (multipart_event_file_end *)event_data; rfc1867ApcData->bytes_processed = data->post_bytes_processed; rfc1867ApcData->cancel_upload = data->cancel_upload; rfc1867ApcData->temp_filename = data->temp_filename; ArrayInit track(8); track.set(s_total, rfc1867ApcData->content_length); track.set(s_current, rfc1867ApcData->bytes_processed); track.set(s_filename, rfc1867ApcData->filename); track.set(s_name, rfc1867ApcData->name); track.set(s_temp_filename, rfc1867ApcData->temp_filename, CopyString); track.set(s_cancel_upload, rfc1867ApcData->cancel_upload); track.set(s_done, 0); track.set(s_start_time, rfc1867ApcData->start_time); f_apc_store(rfc1867ApcData->tracking_key, track.create(), 3600); } break; case MULTIPART_EVENT_END: if (!rfc1867ApcData->tracking_key.empty()) { double now = my_time(); multipart_event_end *data = (multipart_event_end *)event_data; rfc1867ApcData->bytes_processed = data->post_bytes_processed; if(now>rfc1867ApcData->start_time) { rfc1867ApcData->rate = 8.0*rfc1867ApcData->bytes_processed/(now-rfc1867ApcData->start_time); } else { rfc1867ApcData->rate = 8.0*rfc1867ApcData->bytes_processed; /* Too quick */ ArrayInit track(8); track.set(s_total, rfc1867ApcData->content_length); track.set(s_current, rfc1867ApcData->bytes_processed); track.set(s_rate, rfc1867ApcData->rate); track.set(s_filename, rfc1867ApcData->filename); track.set(s_name, rfc1867ApcData->name); track.set(s_cancel_upload, rfc1867ApcData->cancel_upload); track.set(s_done, 1); track.set(s_start_time, rfc1867ApcData->start_time); f_apc_store(rfc1867ApcData->tracking_key, track.create(), 3600); } } break; } return 0; }
/** * New sprintf implementation for PHP. * * Modifiers: * * " " pad integers with spaces * "-" left adjusted field * n field size * "."n precision (floats only) * "+" Always place a sign (+ or -) in front of a number * * Type specifiers: * * "%" literal "%", modifiers are ignored. * "b" integer argument is printed as binary * "c" integer argument is printed as a single character * "d" argument is an integer * "f" the argument is a float * "o" integer argument is printed as octal * "s" argument is a string * "x" integer argument is printed as lowercase hexadecimal * "X" integer argument is printed as uppercase hexadecimal */ char *string_printf(const char *format, int len, CArrRef args, int *outlen) { Array vargs = args; if (!vargs.isNull() && !vargs->isVectorData()) { vargs = Array::Create(); for (ArrayIter iter(args); iter; ++iter) { vargs.append(iter.second()); } } if (len == 0) { return strdup(""); } int size = 240; char *result = (char *)malloc(size); int outpos = 0; int argnum = 0, currarg = 1; for (int inpos = 0; inpos < len; ++inpos) { char ch = format[inpos]; int expprec = 0; if (ch != '%') { appendchar(&result, &outpos, &size, ch); continue; } if (format[inpos + 1] == '%') { appendchar(&result, &outpos, &size, '%'); inpos++; continue; } /* starting a new format specifier, reset variables */ int alignment = ALIGN_RIGHT; int adjusting = 0; char padding = ' '; int always_sign = 0; int width, precision; inpos++; /* skip the '%' */ ch = format[inpos]; if (isascii(ch) && !isalpha(ch)) { /* first look for argnum */ int temppos = inpos; while (isdigit((int)format[temppos])) temppos++; if (format[temppos] == '$') { argnum = getnumber(format, &inpos); if (argnum <= 0) { free(result); throw_invalid_argument("argnum: must be greater than zero"); return NULL; } inpos++; /* skip the '$' */ } else { argnum = currarg++; } /* after argnum comes modifiers */ for (;; inpos++) { ch = format[inpos]; if (ch == ' ' || ch == '0') { padding = ch; } else if (ch == '-') { alignment = ALIGN_LEFT; /* space padding, the default */ } else if (ch == '+') { always_sign = 1; } else if (ch == '\'') { padding = format[++inpos]; } else { break; } } ch = format[inpos]; /* after modifiers comes width */ if (isdigit(ch)) { if ((width = getnumber(format, &inpos)) < 0) { free(result); throw_invalid_argument("width: must be greater than zero " "and less than %d", INT_MAX); return NULL; } adjusting |= ADJ_WIDTH; } else { width = 0; } ch = format[inpos]; /* after width and argnum comes precision */ if (ch == '.') { ch = format[++inpos]; if (isdigit((int)ch)) { if ((precision = getnumber(format, &inpos)) < 0) { free(result); throw_invalid_argument("precision: must be greater than zero " "and less than %d", INT_MAX); return NULL; } ch = format[inpos]; adjusting |= ADJ_PRECISION; expprec = 1; } else { precision = 0; } } else { precision = 0; } } else { width = precision = 0; argnum = currarg++; } if (argnum > vargs.size()) { free(result); throw_invalid_argument("arguments: (too few)"); return NULL; } if (ch == 'l') { ch = format[++inpos]; } /* now we expect to find a type specifier */ Variant tmp = vargs[argnum-1]; switch (ch) { case 's': { String s = tmp.toString(); appendstring(&result, &outpos, &size, s, width, precision, padding, alignment, s.size(), 0, expprec, 0); break; } case 'd': appendint(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, always_sign); break; case 'u': appenduint(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment); break; case 'g': case 'G': case 'e': case 'E': case 'f': case 'F': appenddouble(&result, &outpos, &size, tmp.toDouble(), width, padding, alignment, precision, adjusting, ch, always_sign); break; case 'c': appendchar(&result, &outpos, &size, tmp.toByte()); break; case 'o': append2n(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, 3, hexchars, expprec); break; case 'x': append2n(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, 4, hexchars, expprec); break; case 'X': append2n(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, 4, HEXCHARS, expprec); break; case 'b': append2n(&result, &outpos, &size, tmp.toInt64(), width, padding, alignment, 1, hexchars, expprec); break; case '%': appendchar(&result, &outpos, &size, '%'); break; default: break; } } /* possibly, we have to make sure we have room for the terminating null? */ result[outpos]=0; if (outlen) *outlen = outpos; return result; }
bool ArrayData::IsValidKey(const Variant& k) { return k.isInteger() || (k.isString() && IsValidKey(k.getStringData())); }
static Variant HHVM_METHOD(Memcache, get, const Variant& key, VRefParam flags /*= null*/) { auto data = Native::data<MemcacheData>(this_); if (key.is(KindOfArray)) { std::vector<const char *> real_keys; std::vector<size_t> key_len; Array keyArr = key.toArray(); real_keys.reserve(keyArr.size()); key_len.reserve(keyArr.size()); for (ArrayIter iter(keyArr); iter; ++iter) { auto key = iter.second().toString(); String serializedKey = memcache_prepare_key(key); real_keys.push_back(const_cast<char *>(serializedKey.c_str())); key_len.push_back(iter.second().toString().length()); } if (!real_keys.empty()) { const char *payload = NULL; size_t payload_len = 0; uint32_t flags = 0; const char *res_key = NULL; size_t res_key_len = 0; memcached_result_st result; memcached_return_t ret = memcached_mget(&data->m_memcache, &real_keys[0], &key_len[0], real_keys.size()); memcached_result_create(&data->m_memcache, &result); Array return_val; while ((memcached_fetch_result(&data->m_memcache, &result, &ret)) != nullptr) { if (ret != MEMCACHED_SUCCESS) { // should probably notify about errors continue; } payload = memcached_result_value(&result); payload_len = memcached_result_length(&result); flags = memcached_result_flags(&result); res_key = memcached_result_key_value(&result); res_key_len = memcached_result_key_length(&result); return_val.set(String(res_key, res_key_len, CopyString), memcache_fetch_from_storage(payload, payload_len, flags)); } memcached_result_free(&result); return return_val; } } else { char *payload = NULL; size_t payload_len = 0; uint32_t flags = 0; memcached_return_t ret; String serializedKey = memcache_prepare_key(key.toString()); if (serializedKey.length() == 0) { return false; } payload = memcached_get(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), &payload_len, &flags, &ret); /* This is for historical reasons from libmemcached*/ if (ret == MEMCACHED_END) { ret = MEMCACHED_NOTFOUND; } if (ret == MEMCACHED_NOTFOUND) { return false; } Variant retval = memcache_fetch_from_storage(payload, payload_len, flags); free(payload); return retval; } return false; }
void LuaScriptInstance::OnSetAttribute(const AttributeInfo& attr, const Variant& src) { if (attr.ptr_ != (void*)0xffffffff) { Serializable::OnSetAttribute(attr, src); return; } if (scriptObjectRef_ == LUA_REFNIL) return; String name = attr.name_; unsigned length = name.Length(); if (name.Back() == '_') length -= 1; int top = lua_gettop(luaState_); String functionName = String("Set") + name.Substring(0, 1).ToUpper() + name.Substring(1, length - 1); WeakPtr<LuaFunction> function = GetScriptObjectFunction(functionName); // If set function exist if (function) { if (function->BeginCall(this)) { function->PushVariant(src); function->EndCall(); } } else { lua_rawgeti(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_); lua_pushstring(luaState_, name.CString()); switch (attr.type_) { case VAR_BOOL: lua_pushboolean(luaState_, src.GetBool()); break; case VAR_FLOAT: lua_pushnumber(luaState_, src.GetFloat()); break; case VAR_STRING: tolua_pushurho3dstring(luaState_, src.GetString()); break; case VAR_VECTOR2: tolua_pushusertype(luaState_, (void*)&(src.GetVector2()), "Vector2"); break; case VAR_VECTOR3: tolua_pushusertype(luaState_, (void*)&(src.GetVector3()), "Vector3"); break; case VAR_VECTOR4: tolua_pushusertype(luaState_, (void*)&(src.GetVector4()), "Vector4"); break; case VAR_QUATERNION: tolua_pushusertype(luaState_, (void*)&(src.GetQuaternion()), "Quaternion"); break; case VAR_COLOR: tolua_pushusertype(luaState_, (void*)&(src.GetColor()), "Color"); break; case VAR_INTRECT: tolua_pushusertype(luaState_, (void*)&(src.GetIntRect()), "IntRect"); break; case VAR_INTVECTOR2: tolua_pushusertype(luaState_, (void*)&(src.GetIntVector2()), "IntVector2"); break; default: LOGERROR("Unsupported data type"); lua_settop(luaState_, top); return; } lua_settable(luaState_, -3); } lua_settop(luaState_, top); }
Variant HHVM_FUNCTION(json_decode, const String& json, bool assoc /* = false */, int64_t depth /* = 512 */, int64_t options /* = 0 */) { json_set_last_error_code(json_error_codes::JSON_ERROR_NONE); if (json.empty()) { return init_null(); } const int64_t supported_options = k_JSON_FB_LOOSE | k_JSON_FB_COLLECTIONS | k_JSON_FB_STABLE_MAPS | k_JSON_BIGINT_AS_STRING; int64_t parser_options = options & supported_options; Variant z; if (JSON_parser(z, json.data(), json.size(), assoc, depth, parser_options)) { return z; } String trimmed = HHVM_FN(trim)(json, "\t\n\r "); if (trimmed.size() == 4) { if (!strcasecmp(trimmed.data(), "null")) { json_set_last_error_code(json_error_codes::JSON_ERROR_NONE); return init_null(); } if (!strcasecmp(trimmed.data(), "true")) { json_set_last_error_code(json_error_codes::JSON_ERROR_NONE); return true; } } else if (trimmed.size() == 5 && !strcasecmp(trimmed.data(), "false")) { json_set_last_error_code(json_error_codes::JSON_ERROR_NONE); return false; } int64_t p; double d; DataType type = json.get()->isNumericWithVal(p, d, 0); if (type == KindOfInt64) { json_set_last_error_code(json_error_codes::JSON_ERROR_NONE); return p; } else if (type == KindOfDouble) { json_set_last_error_code(json_error_codes::JSON_ERROR_NONE); if ((options & k_JSON_BIGINT_AS_STRING) && (json.toInt64() == LLONG_MAX || json.toInt64() == LLONG_MIN) && errno == ERANGE) { // Overflow bool is_float = false; for (int i = (trimmed[0] == '-' ? 1 : 0); i < trimmed.size(); ++i) { if (trimmed[i] < '0' || trimmed[i] > '9') { is_float = true; break; } } if (!is_float) { return trimmed; } } return d; } char ch0 = json.charAt(0); if (json.size() > 1 && ch0 == '"' && json.charAt(json.size() - 1) == '"') { json_set_last_error_code(json_error_codes::JSON_ERROR_NONE); // Wrap the string in an array to allow the JSON_parser to handle // things like unicode escape sequences, then unwrap to get result String wrapped("["); wrapped += json + "]"; // Stick to a normal hhvm array for the wrapper const int64_t mask = ~(k_JSON_FB_COLLECTIONS | k_JSON_FB_STABLE_MAPS); if (JSON_parser(z, wrapped.data(), wrapped.size(), false, depth, parser_options & mask) && z.isArray()) { Array arr = z.toArray(); if ((arr.size() == 1) && arr.exists(0)) { return arr[0]; } // The input string could be something like: "foo","bar" // Which will parse inside the [] wrapper, but be invalid json_set_last_error_code(json_error_codes::JSON_ERROR_SYNTAX); } } if ((options & k_JSON_FB_LOOSE) && json.size() > 1 && ch0 == '\'' && json.charAt(json.size() - 1) == '\'') { json_set_last_error_code(json_error_codes::JSON_ERROR_NONE); return json.substr(1, json.size() - 2); } assert(json_get_last_error_code() != json_error_codes::JSON_ERROR_NONE); return init_null(); }
bool_t BtcChinaBtcCny::process(Callback& callback) { if(!callback.receivedTime(Time::time())) return false; HttpRequest httpRequest; Buffer data; String dataStr; for(;; Thread::sleep(14000)) { String url("https://data.btcchina.com/data/historydata"); if(lastTradeId != 0) url.printf("https://data.btcchina.com/data/historydata?since=%llu", lastTradeId); if(!httpRequest.get(url, data)) { error = httpRequest.getErrorString(); open = false; return false; } timestamp_t localTime = Time::time(); dataStr.attach((const char_t*)(byte_t*)data, data.size()); Variant dataVar; if(!Json::parse(dataStr, dataVar)) { error = "Could not parse trade data."; open = false; return false; } const List<Variant>& tradesList = dataVar.toList(); if(!tradesList.isEmpty()) { const HashMap<String, Variant>& tradeData = tradesList.back().toMap(); timestamp_t serverTime = tradeData.find("date")->toInt64() * 1000LL; timestamp_t offset = serverTime - localTime; if(offset < timeOffset || !timeOffsetSet) { timeOffset = offset; timeOffsetSet = true; if(!callback.receivedTime(serverTime)) return false; } } Trade trade; for(List<Variant>::Iterator i = tradesList.begin(), end = tradesList.end(); i != end; ++i) { const HashMap<String, Variant>& tradeData = i->toMap(); trade.id = tradeData.find("tid")->toInt64(); trade.time = tradeData.find("date")->toInt64() * 1000LL; trade.price = tradeData.find("price")->toDouble(); trade.amount = tradeData.find("amount")->toDouble(); trade.flags = 0; if(trade.id > lastTradeId) { if(!callback.receivedTrade(trade)) return false; lastTradeId = trade.id; } } } return false; // unreachable }
void ScriptEditorDebugger::_property_changed(Object*p_base,const StringName& p_property,const Variant& p_value){ if (!p_base || !live_debug || !connection.is_valid() || !editor->get_edited_scene()) return; Node *node = p_base->cast_to<Node>(); if (node) { NodePath path = editor->get_edited_scene()->get_path_to(node); int pathid = _get_node_path_cache(path); if (p_value.is_ref()) { Ref<Resource> res = p_value; if (res.is_valid() && res->get_path()!=String()) { Array msg; msg.push_back("live_node_prop_res"); msg.push_back(pathid); msg.push_back(p_property); msg.push_back(res->get_path()); ppeer->put_var(msg); } } else { Array msg; msg.push_back("live_node_prop"); msg.push_back(pathid); msg.push_back(p_property); msg.push_back(p_value); ppeer->put_var(msg); } return; } Resource *res = p_base->cast_to<Resource>(); if (res && res->get_path()!=String()) { String respath = res->get_path(); int pathid = _get_res_path_cache(respath); if (p_value.is_ref()) { Ref<Resource> res = p_value; if (res.is_valid() && res->get_path()!=String()) { Array msg; msg.push_back("live_res_prop_res"); msg.push_back(pathid); msg.push_back(p_property); msg.push_back(res->get_path()); ppeer->put_var(msg); } } else { Array msg; msg.push_back("live_res_prop"); msg.push_back(pathid); msg.push_back(p_property); msg.push_back(p_value); ppeer->put_var(msg); } return; } //print_line("prop"); }
void ScriptEditorDebugger::_notification(int p_what) { switch(p_what) { case NOTIFICATION_ENTER_TREE: { step->set_icon( get_icon("DebugStep","EditorIcons")); next->set_icon( get_icon("DebugNext","EditorIcons")); back->set_icon( get_icon("Back","EditorIcons")); forward->set_icon( get_icon("Forward","EditorIcons")); dobreak->set_icon( get_icon("Pause","EditorIcons")); docontinue->set_icon( get_icon("DebugContinue","EditorIcons")); tb->set_normal_texture( get_icon("Close","EditorIcons")); tb->set_hover_texture( get_icon("CloseHover","EditorIcons")); tb->set_pressed_texture( get_icon("Close","EditorIcons")); scene_tree_refresh->set_icon( get_icon("Reload","EditorIcons")); le_set->connect("pressed",this,"_live_edit_set"); le_clear->connect("pressed",this,"_live_edit_clear"); error_list->connect("item_selected",this,"_error_selected"); error_stack->connect("item_selected",this,"_error_stack_selected"); vmem_refresh->set_icon( get_icon("Reload","EditorIcons")); } break; case NOTIFICATION_PROCESS: { if (error_count!=last_error_count) { if (error_count==0) { error_split->set_name("Errors"); } else { error_split->set_name("Errors ("+itos(error_count)+")"); } last_error_count=error_count; } if (connection.is_null()) { if (server->is_connection_available()) { connection = server->take_connection(); if (connection.is_null()) break; EditorNode::get_log()->add_message("** Debug Process Started **"); log_forced_visible=false; ppeer->set_stream_peer(connection); show(); dobreak->set_disabled(false); tabs->set_current_tab(0); emit_signal("show_debugger",true); reason->set_text("Child Process Connected"); reason->set_tooltip("Child Process Connected"); scene_tree->clear(); le_set->set_disabled(true); le_clear->set_disabled(false); error_list->clear(); error_stack->clear(); error_count=0; //live_edit_root->set_text("/root"); update_live_edit_root(); } else { break; } }; if (!connection->is_connected()) { stop(); editor->notify_child_process_exited(); //somehow, exited break; }; if (ppeer->get_available_packet_count() <= 0) { break; }; while(ppeer->get_available_packet_count() > 0) { if (pending_in_queue) { int todo = MIN( ppeer->get_available_packet_count(), pending_in_queue ); for(int i=0;i<todo;i++) { Variant cmd; Error ret = ppeer->get_var(cmd); if (ret!=OK) { stop(); ERR_FAIL_COND(ret!=OK); } message.push_back(cmd); pending_in_queue--; } if (pending_in_queue==0) { _parse_message(message_type,message); message.clear(); } } else { if (ppeer->get_available_packet_count()>=2) { Variant cmd; Error ret = ppeer->get_var(cmd); if (ret!=OK) { stop(); ERR_FAIL_COND(ret!=OK); } if (cmd.get_type()!=Variant::STRING) { stop(); ERR_FAIL_COND(cmd.get_type()!=Variant::STRING); } message_type=cmd; ret = ppeer->get_var(cmd); if (ret!=OK) { stop(); ERR_FAIL_COND(ret!=OK); } if (cmd.get_type()!=Variant::INT) { stop(); ERR_FAIL_COND(cmd.get_type()!=Variant::INT); } pending_in_queue=cmd; if (pending_in_queue==0) { _parse_message(message_type,Array()); message.clear(); } } else { break; } } } } break; } }
bool TestServer::VerifyServerResponse(const char *input, const char *output, const char *url, const char *method, const char *header, const char *postdata, bool responseHeader, const char *file /* = "" */, int line /* = 0 */) { ASSERT(input); if (!CleanUp()) return false; if (Option::EnableEval < Option::FullEval) { if (!GenerateFiles(input, "TestServer") || !CompileFiles()) { return false; } } else { string fullPath = "/unittest/rootdoc/string"; ofstream f(fullPath.c_str()); if (!f) { printf("Unable to open %s for write. Run this test from src/.\n", fullPath.c_str()); return false; } f << input; f.close(); } AsyncFunc<TestServer> func(this, &TestServer::RunServer); func.start(); String server = "http://"; server += f_php_uname("n"); server += ":8080/"; server += url; string actual, err; for (int i = 0; i < 10; i++) { Variant c = f_curl_init(); f_curl_setopt(c, k_CURLOPT_URL, server); f_curl_setopt(c, k_CURLOPT_RETURNTRANSFER, true); if (postdata) { f_curl_setopt(c, k_CURLOPT_POSTFIELDS, postdata); f_curl_setopt(c, k_CURLOPT_POST, true); } if (header) { f_curl_setopt(c, k_CURLOPT_HTTPHEADER, CREATE_VECTOR1(header)); } if (responseHeader) { f_curl_setopt(c, k_CURLOPT_HEADER, 1); } Variant res = f_curl_exec(c); if (!same(res, false)) { actual = res.toString(); break; } sleep(1); // wait until HTTP server is up and running } AsyncFunc<TestServer>(this, &TestServer::StopServer).run(); func.waitForEnd(); bool passed = (actual == output); if (responseHeader) { passed = (actual.find(output) != string::npos); } if (!passed) { printf("%s:%d\nParsing: [%s]\nBet %d:\n" "--------------------------------------\n" "%s" "--------------------------------------\n" "Got %d:\n" "--------------------------------------\n" "%s" "--------------------------------------\n", file, line, input, (int)strlen(output), output, (int)actual.length(), actual.c_str()); return false; } return true; }
//--------------------------------------------------------------------------- void __fastcall TXFTJALLExportThread::Execute() { //---- Place thread code here ---- ValidEXBTN->Enabled = false; ValidPreBTN->Enabled = false; ValidEBTN->Enabled = false; ValidQBTN->Enabled = false; Variant ExcelApp; try { ExcelApp = CreateOleObject("Excel.Application"); } catch(...) { MessageBox(XFTJQFrm->Handle, "错误:您的系统中可能没有安装Excel!", "Error in launch Excel!", MB_OK|MB_ICONERROR); ValidEXBTN->Enabled = true; ValidPreBTN->Enabled = true; ValidEBTN->Enabled = true; return; } ValidQuery->Open(); String DTX = ""; String path = GlobalPath; String Templatepath; ValidQuery->First(); int allrecord = ValidQuery->RecordCount; for(int i = 0; i <65531; i++) { DTX += ValidQuery->FieldByName("qdate")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("ZSFZE")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("ZSFCS")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("BFSFZE")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("BFCS")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("LHSFZE")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("LHCS")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("SUSFZE")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("SUCS")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("NTSFZE")->AsAnsiString.Trim(); DTX += "\t"; DTX += ValidQuery->FieldByName("NTCS")->AsAnsiString.Trim(); DTX += "\n"; Validprogress->Position = i*100/allrecord; ValidQuery->Next(); if(ValidQuery->Eof) break; } Templatepath = path + "\\ExportXLSTemplate\\XFTJALLMXTemplate.xlt"; ExcelApp.OlePropertyGet("workbooks").OleFunction("Open", Templatepath.t_str()); Variant WB = ExcelApp.OlePropertyGet("ActiveWorkBook"); Variant ST = WB.OlePropertyGet("Sheets", 1); ST.OlePropertyGet("Cells",2,2).OlePropertySet("Value", ValidBHStr.t_str()); ST.OlePropertyGet("Cells",2,5).OlePropertySet("Value", ValidBMStr.t_str()); ST.OlePropertyGet("Cells",2,9).OlePropertySet("Value", ValidBeginDatestr.t_str()); ST.OlePropertyGet("Cells",3,2).OlePropertySet("Value", ValidCZYStr.t_str()); ST.OlePropertyGet("Cells",3,5).OlePropertySet("Value", DateTimeToStr(Now()).t_str()); ST.OlePropertyGet("Cells",3,9).OlePropertySet("Value", ValidEndDatestr.t_str()); ST.OlePropertyGet("Cells",5,2).OlePropertySet("Value", ValidZZE.t_str()); ST.OlePropertyGet("Cells",6,2).OlePropertySet("Value", ValidZZCS.t_str()); ST.OlePropertyGet("Cells",5,4).OlePropertySet("Value", ValidBZE.t_str()); ST.OlePropertyGet("Cells",6,4).OlePropertySet("Value", ValidBZCS.t_str()); ST.OlePropertyGet("Cells",5,6).OlePropertySet("Value", ValidLZE.t_str()); ST.OlePropertyGet("Cells",6,6).OlePropertySet("Value", ValidLZCS.t_str()); ST.OlePropertyGet("Cells",5,8).OlePropertySet("Value", ValidSZE.t_str()); ST.OlePropertyGet("Cells",6,8).OlePropertySet("Value", ValidSZCS.t_str()); ST.OlePropertyGet("Cells",5,10).OlePropertySet("Value", ValidNZE.t_str()); ST.OlePropertyGet("Cells",6,10).OlePropertySet("Value", ValidNZCS.t_str()); Variant RE = ST.OlePropertyGet("Range", "A9").OleFunction("Select"); Clipboard()->Clear(); Clipboard()->SetTextBuf(DTX.c_str()); ST.OleFunction("Paste"); Clipboard()->Clear(); ExcelApp.OlePropertyGet("Columns").OleFunction("AutoFit"); WB.OleFunction("SaveAs", Validsavepath.t_str()); ExcelApp.OleFunction("Quit"); ExcelApp = Unassigned; Validprogress->Position = 100; MessageBox(XFTJQFrm->Handle, "数据已完成导出!", "Successfully!", MB_OK|MB_ICONINFORMATION); ValidEXBTN->Enabled = true; ValidPreBTN->Enabled = true; ValidEBTN->Enabled = true; ValidQBTN->Enabled = true; }
StatementPtr IfStatement::preOptimize(AnalysisResultConstPtr ar) { if (ar->getPhase() < AnalysisResult::FirstPreOptimize) { return StatementPtr(); } // we cannot optimize away the code inside if statement, because // there may be a goto that goes into if statement. if (hasReachableLabel()) { return StatementPtr(); } bool changed = false; int i; int j; Variant value; bool hoist = false; for (i = 0; i < m_stmts->getCount(); i++) { IfBranchStatementPtr branch = dynamic_pointer_cast<IfBranchStatement>((*m_stmts)[i]); ExpressionPtr condition = branch->getCondition(); if (!condition) { StatementPtr stmt = branch->getStmt(); if (stmt) { if (!i && ((getFunctionScope() && !getFunctionScope()->inPseudoMain()) || !stmt->hasDecl())) { hoist = true; break; } if (stmt->is(KindOfIfStatement)) { StatementListPtr sub_stmts = dynamic_pointer_cast<IfStatement>(stmt)->m_stmts; m_stmts->removeElement(i); changed = true; for (j = 0; j < sub_stmts->getCount(); j++) { m_stmts->insertElement((*sub_stmts)[j], i++); } } } break; } else if (condition->getEffectiveScalar(value)) { if (value.toBoolean()) { hoist = !i && ((getFunctionScope() && !getFunctionScope()->inPseudoMain()) || !branch->hasDecl()); break; } else if (!condition->hasEffect()) { m_stmts->removeElement(i--); changed = true; } else if (branch->getStmt()) { branch->clearStmt(); changed = true; } } } if (!changed && i && i == m_stmts->getCount()) return StatementPtr(); // either else branch or if (true) branch without further declarations i++; while (i < m_stmts->getCount()) { m_stmts->removeElement(i); changed = true; } // if there is only one branch left, return stmt. if (hoist) { IfBranchStatementPtr branch = dynamic_pointer_cast<IfBranchStatement>((*m_stmts)[0]); return branch->getStmt() ? branch->getStmt() : NULL_STATEMENT(); } else if (m_stmts->getCount() == 0) { return NULL_STATEMENT(); } else { return changed ? static_pointer_cast<Statement>(shared_from_this()) : StatementPtr(); } }
void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) { if (!tcp_client->is_connected()) { ERR_EXPLAIN("Script Debugger failed to connect, but being used anyway."); ERR_FAIL(); } packet_peer_stream->put_var("debug_enter"); packet_peer_stream->put_var(2); packet_peer_stream->put_var(p_can_continue); packet_peer_stream->put_var(p_script->debug_get_error()); while(true) { _get_output(); if (packet_peer_stream->get_available_packet_count()>0) { Variant var; Error err = packet_peer_stream->get_var(var); ERR_CONTINUE( err != OK); ERR_CONTINUE( var.get_type()!=Variant::ARRAY ); Array cmd = var; ERR_CONTINUE( cmd.size()==0); ERR_CONTINUE( cmd[0].get_type()!=Variant::STRING ); String command = cmd[0]; if (command=="get_stack_dump") { packet_peer_stream->put_var("stack_dump"); int slc = p_script->debug_get_stack_level_count(); packet_peer_stream->put_var( slc ); for(int i=0;i<slc;i++) { Dictionary d; d["file"]=p_script->debug_get_stack_level_source(i); d["line"]=p_script->debug_get_stack_level_line(i); d["function"]=p_script->debug_get_stack_level_function(i); //d["id"]=p_script->debug_get_stack_level_ d["id"]=0; packet_peer_stream->put_var( d ); } } else if (command=="get_stack_frame_vars") { cmd.remove(0); ERR_CONTINUE( cmd.size()!=1 ); int lv = cmd[0]; List<String> members; List<Variant> member_vals; p_script->debug_get_stack_level_members(lv,&members,&member_vals); ERR_CONTINUE( members.size() !=member_vals.size() ); List<String> locals; List<Variant> local_vals; p_script->debug_get_stack_level_locals(lv,&locals,&local_vals); ERR_CONTINUE( locals.size() !=local_vals.size() ); packet_peer_stream->put_var("stack_frame_vars"); packet_peer_stream->put_var(2+locals.size()*2+members.size()*2); { //members packet_peer_stream->put_var(members.size()); List<String>::Element *E=members.front(); List<Variant>::Element *F=member_vals.front(); while(E) { if (F->get().get_type()==Variant::OBJECT) { packet_peer_stream->put_var("*"+E->get()); packet_peer_stream->put_var(safe_get_instance_id(F->get())); } else { packet_peer_stream->put_var(E->get()); packet_peer_stream->put_var(F->get()); } E=E->next(); F=F->next(); } } { //locals packet_peer_stream->put_var(locals.size()); List<String>::Element *E=locals.front(); List<Variant>::Element *F=local_vals.front(); while(E) { if (F->get().get_type()==Variant::OBJECT) { packet_peer_stream->put_var("*"+E->get()); packet_peer_stream->put_var(safe_get_instance_id(F->get())); } else { packet_peer_stream->put_var(E->get()); packet_peer_stream->put_var(F->get()); } E=E->next(); F=F->next(); } } } else if (command=="step") { set_depth(-1); set_lines_left(1); break; } else if (command=="next") { set_depth(0); set_lines_left(1); break; } else if (command=="continue") { set_depth(-1); set_lines_left(-1); break; } else if (command=="break") { ERR_PRINT("Got break when already broke!"); break; } else if (command=="request_scene_tree") { if (request_scene_tree) request_scene_tree(request_scene_tree_ud); } else if (command=="request_video_mem") { _send_video_memory(); } else if (command=="breakpoint") { bool set = cmd[3]; if (set) insert_breakpoint(cmd[2],cmd[1]); else remove_breakpoint(cmd[2],cmd[1]); } else { _parse_live_edit(cmd); } } else { OS::get_singleton()->delay_usec(10000); } } packet_peer_stream->put_var("debug_exit"); packet_peer_stream->put_var(0); }
bool VirtualHost::rewriteURL(CStrRef host, String &url, bool &qsa, int &redirect) const { String normalized = url; if (normalized.empty() || normalized.charAt(0) != '/') { normalized = String("/") + normalized; } for (unsigned int i = 0; i < m_rewriteRules.size(); i++) { const RewriteRule &rule = m_rewriteRules[i]; bool passed = true; for (vector<RewriteCond>::const_iterator it = rule.rewriteConds.begin(); it != rule.rewriteConds.end(); ++it) { String subject; if (it->type == RewriteCond::Request) { subject = normalized; } else { subject = host; } Variant ret = preg_match(String(it->pattern.c_str(), it->pattern.size(), AttachLiteral), subject); if (!ret.same(it->negate ? 0 : 1)) { passed = false; break; } } if (!passed) continue; Variant matches; int count = preg_match(rule.pattern.c_str(), normalized, matches); if (count > 0) { const char *s = rule.to.c_str(); StringBuffer ret; while (*s) { int backref = -1; if (*s == '\\') { if ('0' <= s[1] && s[1] <= '9') { s++; backref = get_backref(&s); } else if (s[1] == '\\') { s++; } } else if (*s == '$') { if (s[1] == '{') { const char *t = s+2; if ('0' <= *t && *t <= '9') { backref = get_backref(&t); if (*t != '}') { backref = -1; } else { s = t+1; } } } else if ('0' <= s[1] && s[1] <= '9') { s++; backref = get_backref(&s); } } if (backref >= 0) { String br = matches[backref].toString(); if (rule.encode_backrefs) { br = StringUtil::UrlEncode(br); } ret.append(br); } else { ret.append(s, 1); s++; } } url = ret.detach(); qsa = rule.qsa; redirect = rule.redirect; return true; } } return false; }
// foldConst() is callable from the parse phase as well as the analysis phase. // We take advantage of this during the parse phase to reduce very simple // expressions down to a single scalar and keep the parse tree smaller, // especially in cases of long chains of binary operators. However, we limit // the effectivness of this during parse to ensure that we eliminate only // very simple scalars that don't require analysis in later phases. For now, // that's just simply scalar values. ExpressionPtr BinaryOpExpression::foldConst(AnalysisResultConstPtr ar) { ExpressionPtr optExp; Variant v1; Variant v2; if (!m_exp2->getScalarValue(v2)) { if ((ar->getPhase() != AnalysisResult::ParseAllFiles) && m_exp1->isScalar() && m_exp1->getScalarValue(v1)) { switch (m_op) { case T_IS_IDENTICAL: case T_IS_NOT_IDENTICAL: if (v1.isNull()) { return makeIsNull(ar, getRange(), m_exp2, m_op == T_IS_NOT_IDENTICAL); } break; case T_LOGICAL_AND: case T_BOOLEAN_AND: case T_LOGICAL_OR: case T_BOOLEAN_OR: { ExpressionPtr rep = v1.toBoolean() == (m_op == T_LOGICAL_AND || m_op == T_BOOLEAN_AND) ? m_exp2 : m_exp1; rep = ExpressionPtr( new UnaryOpExpression( getScope(), getRange(), rep, T_BOOL_CAST, true)); return replaceValue(rep); } case '+': case '.': case '*': case '&': case '|': case '^': if (m_exp2->is(KindOfBinaryOpExpression)) { auto binOpExp = dynamic_pointer_cast<BinaryOpExpression>(m_exp2); if (binOpExp->m_op == m_op && binOpExp->m_exp1->isScalar()) { auto aExp = m_exp1; auto bExp = binOpExp->m_exp1; auto cExp = binOpExp->m_exp2; if (aExp->isArray() || bExp->isArray() || cExp->isArray()) { break; } m_exp1 = binOpExp = Clone(binOpExp); m_exp2 = cExp; binOpExp->m_exp1 = aExp; binOpExp->m_exp2 = bExp; if (auto optExp = binOpExp->foldConst(ar)) { m_exp1 = optExp; } return static_pointer_cast<Expression>(shared_from_this()); } } break; default: break; } } return ExpressionPtr(); } if (m_exp1->isScalar()) { if (!m_exp1->getScalarValue(v1)) return ExpressionPtr(); try { auto scalar1 = dynamic_pointer_cast<ScalarExpression>(m_exp1); auto scalar2 = dynamic_pointer_cast<ScalarExpression>(m_exp2); // Some data, like the values of __CLASS__ and friends, are not available // while we're still in the initial parse phase. if (ar->getPhase() == AnalysisResult::ParseAllFiles) { if ((scalar1 && scalar1->needsTranslation()) || (scalar2 && scalar2->needsTranslation())) { return ExpressionPtr(); } } if ((!Option::WholeProgram || !Option::ParseTimeOpts) && getScope()) { // In the VM, don't optimize __CLASS__ if within a trait, since // __CLASS__ is not resolved yet. auto cs = getClassScope(); if (cs && cs->isTrait()) { if ((scalar1 && scalar1->getType() == T_CLASS_C) || (scalar2 && scalar2->getType() == T_CLASS_C)) { return ExpressionPtr(); } } } Variant result; auto add = RuntimeOption::IntsOverflowToInts ? cellAdd : cellAddO; auto sub = RuntimeOption::IntsOverflowToInts ? cellSub : cellSubO; auto mul = RuntimeOption::IntsOverflowToInts ? cellMul : cellMulO; switch (m_op) { case T_LOGICAL_XOR: result = static_cast<bool>(v1.toBoolean() ^ v2.toBoolean()); break; case '|': *result.asCell() = cellBitOr(*v1.asCell(), *v2.asCell()); break; case '&': *result.asCell() = cellBitAnd(*v1.asCell(), *v2.asCell()); break; case '^': *result.asCell() = cellBitXor(*v1.asCell(), *v2.asCell()); break; case '.': if (v1.isArray() || v2.isArray()) { return ExpressionPtr(); } result = concat(v1.toString(), v2.toString()); break; case T_IS_IDENTICAL: result = same(v1, v2); break; case T_IS_NOT_IDENTICAL: result = !same(v1, v2); break; case T_IS_EQUAL: result = equal(v1, v2); break; case T_IS_NOT_EQUAL: result = !equal(v1, v2); break; case '<': result = less(v1, v2); break; case T_IS_SMALLER_OR_EQUAL: result = cellLessOrEqual(*v1.asCell(), *v2.asCell()); break; case '>': result = more(v1, v2); break; case T_IS_GREATER_OR_EQUAL: result = cellGreaterOrEqual(*v1.asCell(), *v2.asCell()); break; case T_SPACESHIP: result = cellCompare(*v1.asCell(), *v2.asCell()); break; case '+': *result.asCell() = add(*v1.asCell(), *v2.asCell()); break; case '-': *result.asCell() = sub(*v1.asCell(), *v2.asCell()); break; case '*': *result.asCell() = mul(*v1.asCell(), *v2.asCell()); break; case '/': if ((v2.isIntVal() && v2.toInt64() == 0) || v2.toDouble() == 0.0) { return ExpressionPtr(); } *result.asCell() = cellDiv(*v1.asCell(), *v2.asCell()); break; case '%': if ((v2.isIntVal() && v2.toInt64() == 0) || v2.toDouble() == 0.0) { return ExpressionPtr(); } *result.asCell() = cellMod(*v1.asCell(), *v2.asCell()); break; case T_SL: { int64_t shift = v2.toInt64(); if (!RuntimeOption::PHP7_IntSemantics) { result = v1.toInt64() << (shift & 63); } else if (shift >= 64) { result = 0; } else if (shift < 0) { // This raises an error, and so can't be folded. return ExpressionPtr(); } else { result = v1.toInt64() << (shift & 63); } break; } case T_SR: { int64_t shift = v2.toInt64(); if (!RuntimeOption::PHP7_IntSemantics) { result = v1.toInt64() >> (shift & 63); } else if (shift >= 64) { result = v1.toInt64() >= 0 ? 0 : -1; } else if (shift < 0) { // This raises an error, and so can't be folded. return ExpressionPtr(); } else { result = v1.toInt64() >> (shift & 63); } break; } case T_BOOLEAN_OR: result = v1.toBoolean() || v2.toBoolean(); break; case T_BOOLEAN_AND: result = v1.toBoolean() && v2.toBoolean(); break; case T_LOGICAL_OR: result = v1.toBoolean() || v2.toBoolean(); break; case T_LOGICAL_AND: result = v1.toBoolean() && v2.toBoolean(); break; case T_INSTANCEOF: { if (v2.isString()) { if (v1.isArray() && interface_supports_array(v2.getStringData())) { result = true; break; } if (v1.isString() && interface_supports_string(v2.getStringData())) { result = true; break; } if (v1.isInteger() && interface_supports_int(v2.getStringData())) { result = true; break; } if (v1.isDouble() && interface_supports_double(v2.getStringData())) { result = true; break; } } result = false; break; } default: return ExpressionPtr(); } return makeScalarExpression(ar, result); } catch (...) {
bool AccessorDirectProperty<ObjectType, MemberType>::ReadData( const void *object, Variant &value) const { return value.SetValue((translucent_cast<const ObjectType *>(object)->*mGetter)()); }
Variant Spline::LinearInterpolation(const Variant& lhs, const Variant& rhs, float t) const { switch (lhs.GetType()) { case VAR_FLOAT: return Lerp(lhs.GetFloat(), rhs.GetFloat(), t); case VAR_VECTOR2: return lhs.GetVector2().Lerp(rhs.GetVector2(), t); case VAR_VECTOR3: return lhs.GetVector3().Lerp(rhs.GetVector3(), t); case VAR_VECTOR4: return lhs.GetVector4().Lerp(rhs.GetVector4(), t); case VAR_COLOR: return lhs.GetColor().Lerp(rhs.GetColor(), t); default: return Variant::EMPTY; } }
ExpressionPtr UnaryOpExpression::preOptimize(AnalysisResultConstPtr ar) { Variant value; Variant result; if (m_exp && ar->getPhase() >= AnalysisResult::FirstPreOptimize) { if (m_op == T_UNSET) { if (m_exp->isScalar() || (m_exp->is(KindOfExpressionList) && static_pointer_cast<ExpressionList>(m_exp)->getCount() == 0)) { recomputeEffects(); return CONSTANT("null"); } return ExpressionPtr(); } } if (m_op == T_ISSET && m_exp->is(KindOfExpressionList) && static_pointer_cast<ExpressionList>(m_exp)->getListKind() == ExpressionList::ListKindParam) { auto el = static_pointer_cast<ExpressionList>(m_exp); result = true; int i = 0, n = el->getCount(); for (; i < n; i++) { ExpressionPtr e((*el)[i]); if (!e || !e->isScalar() || !e->getScalarValue(value)) break; if (value.isNull()) { result = false; } } if (i == n) { return replaceValue(makeScalarExpression(ar, result)); } } else if (m_op != T_ARRAY && m_op != T_VEC && m_op != T_DICT && m_op != T_KEYSET && m_exp && m_exp->isScalar() && m_exp->getScalarValue(value) && preCompute(value, result)) { return replaceValue(makeScalarExpression(ar, result)); } else if (m_op == T_BOOL_CAST) { switch (m_exp->getKindOf()) { default: break; case KindOfBinaryOpExpression: { int op = static_pointer_cast<BinaryOpExpression>(m_exp)->getOp(); switch (op) { case T_LOGICAL_OR: case T_BOOLEAN_OR: case T_LOGICAL_AND: case T_BOOLEAN_AND: case T_LOGICAL_XOR: case T_INSTANCEOF: case '<': case T_IS_SMALLER_OR_EQUAL: case '>': case T_IS_GREATER_OR_EQUAL: case T_SPACESHIP: case T_IS_IDENTICAL: case T_IS_NOT_IDENTICAL: case T_IS_EQUAL: case T_IS_NOT_EQUAL: return m_exp; } break; } case KindOfUnaryOpExpression: { int op = static_pointer_cast<UnaryOpExpression>(m_exp)->getOp(); switch (op) { case T_BOOL_CAST: case '!': case T_ISSET: case T_EMPTY: case T_PRINT: return m_exp; } break; } } } return ExpressionPtr(); }
Object c_Closure::t_bindto(const Variant& newthis, const Variant& scope) { if (RuntimeOption::RepoAuthoritative && RuntimeOption::EvalAllowScopeBinding) { raise_warning("Closure binding is not supported in RepoAuthoritative mode"); return nullptr; } auto const cls = getVMClass(); auto const invoke = cls->getCachedInvoke(); ObjectData* od = nullptr; if (newthis.isObject()) { if (invoke->isStatic()) { raise_warning("Cannot bind an instance to a static closure"); } else { od = newthis.getObjectData(); } } else if (!newthis.isNull()) { raise_warning("Closure::bindto() expects parameter 1 to be object"); return nullptr; } auto const curscope = invoke->cls(); auto newscope = curscope; if (scope.isObject()) { newscope = scope.getObjectData()->getVMClass(); } else if (scope.isString()) { auto const className = scope.getStringData(); if (!className->equal(s_static.get())) { newscope = Unit::loadClass(className); if (!newscope) { raise_warning("Class '%s' not found", className->data()); return nullptr; } } } else if (scope.isNull()) { newscope = nullptr; } else { raise_warning("Closure::bindto() expects parameter 2 " "to be string or object"); return nullptr; } if (od && !newscope) { // Bound closures should be scoped. If no scope is specified, scope it to // the Closure class. newscope = static_cast<Class*>(c_Closure::classof()); } bool thisNotOfCtx = od && !od->getVMClass()->classof(newscope); if (!RuntimeOption::EvalAllowScopeBinding) { if (newscope != curscope) { raise_warning("Re-binding closure scopes is disabled"); return nullptr; } if (thisNotOfCtx) { raise_warning("Binding to objects not subclassed from closure " "context is disabled"); return nullptr; } } c_Closure* clone = Clone(this); clone->setClass(nullptr); Attr curattrs = invoke->attrs(); Attr newattrs = static_cast<Attr>(curattrs & ~AttrHasForeignThis); if (od) { od->incRefCount(); clone->setThis(od); if (thisNotOfCtx) { // If the bound $this is not a subclass of the context class, then we // have to pessimize translation. newattrs |= AttrHasForeignThis; } } else if (newscope) { // If we attach a scope to a function with no bound $this we need to make // the function static. newattrs |= AttrStatic; clone->setClass(newscope); } // If we are changing either the scope or the attributes of the closure, we // need to re-scope its Closure subclass. if (newscope != curscope || newattrs != curattrs) { assert(newattrs != AttrNone); auto newcls = cls->rescope(newscope, newattrs); clone->setVMClass(newcls); } return Object(clone); }
MainLoop *test(TestType p_type) { List<String> cmdlargs = OS::get_singleton()->get_cmdline_args(); if (cmdlargs.empty()) { return NULL; } String test = cmdlargs.back()->get(); if (!test.ends_with(".gd") && !test.ends_with(".gdc")) { print_line("This test expects a path to a GDScript file as its last parameter. Got: " + test); return NULL; } FileAccess *fa = FileAccess::open(test, FileAccess::READ); if (!fa) { ERR_EXPLAIN("Could not open file: " + test); ERR_FAIL_V(NULL); } Vector<uint8_t> buf; int flen = fa->get_len(); buf.resize(fa->get_len() + 1); fa->get_buffer(buf.ptrw(), flen); buf.write[flen] = 0; String code; code.parse_utf8((const char *)&buf[0]); Vector<String> lines; int last = 0; for (int i = 0; i <= code.length(); i++) { if (code[i] == '\n' || code[i] == 0) { lines.push_back(code.substr(last, i - last)); last = i + 1; } } if (p_type == TEST_TOKENIZER) { GDScriptTokenizerText tk; tk.set_code(code); int line = -1; while (tk.get_token() != GDScriptTokenizer::TK_EOF) { String text; if (tk.get_token() == GDScriptTokenizer::TK_IDENTIFIER) text = "'" + tk.get_token_identifier() + "' (identifier)"; else if (tk.get_token() == GDScriptTokenizer::TK_CONSTANT) { Variant c = tk.get_token_constant(); if (c.get_type() == Variant::STRING) text = "\"" + String(c) + "\""; else text = c; text = text + " (" + Variant::get_type_name(c.get_type()) + " constant)"; } else if (tk.get_token() == GDScriptTokenizer::TK_ERROR) text = "ERROR: " + tk.get_token_error(); else if (tk.get_token() == GDScriptTokenizer::TK_NEWLINE) text = "newline (" + itos(tk.get_token_line()) + ") + indent: " + itos(tk.get_token_line_indent()); else if (tk.get_token() == GDScriptTokenizer::TK_BUILT_IN_FUNC) text = "'" + String(GDScriptFunctions::get_func_name(tk.get_token_built_in_func())) + "' (built-in function)"; else text = tk.get_token_name(tk.get_token()); if (tk.get_token_line() != line) { int from = line + 1; line = tk.get_token_line(); for (int i = from; i <= line; i++) { int l = i - 1; if (l >= 0 && l < lines.size()) { print_line("\n" + itos(i) + ": " + lines[l] + "\n"); } } } print_line("\t(" + itos(tk.get_token_column()) + "): " + text); tk.advance(); } } if (p_type == TEST_PARSER) { GDScriptParser parser; Error err = parser.parse(code); if (err) { print_line("Parse Error:\n" + itos(parser.get_error_line()) + ":" + itos(parser.get_error_column()) + ":" + parser.get_error()); memdelete(fa); return NULL; } const GDScriptParser::Node *root = parser.get_parse_tree(); ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, NULL); const GDScriptParser::ClassNode *cnode = static_cast<const GDScriptParser::ClassNode *>(root); _parser_show_class(cnode, 0, lines); } if (p_type == TEST_COMPILER) { GDScriptParser parser; Error err = parser.parse(code); if (err) { print_line("Parse Error:\n" + itos(parser.get_error_line()) + ":" + itos(parser.get_error_column()) + ":" + parser.get_error()); memdelete(fa); return NULL; } GDScript *script = memnew(GDScript); GDScriptCompiler gdc; err = gdc.compile(&parser, script); if (err) { print_line("Compile Error:\n" + itos(gdc.get_error_line()) + ":" + itos(gdc.get_error_column()) + ":" + gdc.get_error()); memdelete(script); return NULL; } Ref<GDScript> gds = Ref<GDScript>(script); Ref<GDScript> current = gds; while (current.is_valid()) { print_line("** CLASS **"); _disassemble_class(current, lines); current = current->get_base(); } } else if (p_type == TEST_BYTECODE) { Vector<uint8_t> buf2 = GDScriptTokenizerBuffer::parse_code_string(code); String dst = test.get_basename() + ".gdc"; FileAccess *fw = FileAccess::open(dst, FileAccess::WRITE); fw->store_buffer(buf2.ptr(), buf2.size()); memdelete(fw); } memdelete(fa); return NULL; }
static String HHVM_FUNCTION(set_include_path, const Variant& new_include_path) { String s = f_get_include_path(); IniSetting::SetUser("include_path", new_include_path.toString()); return s; }
//--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { edtFile->Text = ""; m_strFileName = ""; if (OpenDialog1->Execute()) { m_bBackup = false; UnicodeString strFileName = OpenDialog1->FileName; if (! FileExists (strFileName)) { MessageBox (Handle, UnicodeString(L"Файл '" + strFileName + L"' не существует").c_str(), L"prompt", MB_OK); edtFile->Text = ""; return; } edtFile->Text = strFileName; // TODO: create backup now or later? // TODO: INIT OPERATIONS // TODO: scan month Variant var_Book,var_Sheet,var_Cell; Variant app = Variant::CreateObject("Excel.Application"); // app.OlePropertySet("Visible",false); Variant excel; try { excel = app.OlePropertyGet("Workbooks").OleFunction("Open", WideString(strFileName.c_str())); } catch (...) { MessageBox (Handle, UnicodeString(L"Не получается открыть файл '" + strFileName + L"' как excel").c_str(), L"prompt", MB_OK); app.OleProcedure("Quit"); edtFile->Text = ""; return; } Log->Lines->Add("Файл загружен производиться анализ"); Variant vSheets = excel.OlePropertyGet("Worksheets"); m_nPageClassification = 0; m_vMonth.clear(); cmbMonth->Items->Clear(); cmbMonth->Items->Add(""); int nSheets = vSheets.OlePropertyGet("Count"); Log->Lines->Add("Всего листов: " + IntToStr(nSheets)); for (int i = 0; i < nSheets; i++) { Variant vSheet = vSheets.OlePropertyGet("Item",i+1); UnicodeString str = vSheet.OlePropertyGet("Name"); if (str.UpperCase() == UnicodeString("классификации").UpperCase()) { m_nPageClassification = i+1; }; if (str.UpperCase().Pos("МЕСЯЦ ") > 0) { cmbMonth->Items->Add(str); exlSheet s; s.Number = i+1; s.Name = str; m_vMonth.push_back(s); } Log->Lines->Add("Лист " + IntToStr(i+1) + ": " + str); } if (m_nPageClassification == 0) { MessageBox (Handle, UnicodeString(L"Не найден лист 'классификации'").c_str(), L"prompt", MB_OK); app.OleProcedure("Quit"); edtFile->Text = ""; return; } if (m_vMonth.size() == 0) { MessageBox (Handle, UnicodeString(L"Не найден ни один лист с 'месяц xx'").c_str(), L"prompt", MB_OK); app.OleProcedure("Quit"); edtFile->Text = ""; return; } app.OleProcedure("Quit"); m_strFileName = strFileName; } }
static Array HHVM_FUNCTION(getopt, const String& options, const Variant& longopts /*=null */) { opt_struct *opts, *orig_opts; int len = parse_opts(options.data(), options.size(), &opts); if (!longopts.isNull()) { Array arropts = longopts.toArray(); int count = arropts.size(); /* the first <len> slots are filled by the one short ops * we now extend our array and jump to the new added structs */ opts = (opt_struct *)realloc(opts, sizeof(opt_struct) * (len + count + 1)); orig_opts = opts; opts += len; memset(opts, 0, count * sizeof(opt_struct)); for (ArrayIter iter(arropts); iter; ++iter) { String entry = iter.second().toString(); opts->need_param = 0; opts->opt_name = strdup(entry.data()); len = strlen(opts->opt_name); if ((len > 0) && (opts->opt_name[len - 1] == ':')) { opts->need_param++; opts->opt_name[len - 1] = '\0'; if ((len > 1) && (opts->opt_name[len - 2] == ':')) { opts->need_param++; opts->opt_name[len - 2] = '\0'; } } opts->opt_char = 0; opts++; } } else { opts = (opt_struct*) realloc(opts, sizeof(opt_struct) * (len + 1)); orig_opts = opts; opts += len; } /* php_getopt want to identify the last param */ opts->opt_char = '-'; opts->need_param = 0; opts->opt_name = NULL; static const StaticString s_argv("argv"); Array vargv = php_global(s_argv).toArray(); int argc = vargv.size(); char **argv = (char **)malloc((argc+1) * sizeof(char*)); std::vector<String> holders; int index = 0; for (ArrayIter iter(vargv); iter; ++iter) { String arg = iter.second().toString(); holders.push_back(arg); argv[index++] = (char*)arg.data(); } argv[index] = NULL; /* after our pointer arithmetic jump back to the first element */ opts = orig_opts; int o; char *php_optarg = NULL; int php_optind = 1; SCOPE_EXIT { free_longopts(orig_opts); free(orig_opts); free(argv); }; Array ret = Array::Create(); Variant val; int optchr = 0; int dash = 0; /* have already seen the - */ char opt[2] = { '\0' }; char *optname; int optname_len = 0; int php_optidx; while ((o = php_getopt(argc, argv, opts, &php_optarg, &php_optind, 0, 1, optchr, dash, php_optidx)) != -1) { /* Skip unknown arguments. */ if (o == '?') { continue; } /* Prepare the option character and the argument string. */ if (o == 0) { optname = opts[php_optidx].opt_name; } else { if (o == 1) { o = '-'; } opt[0] = o; optname = opt; } if (php_optarg != NULL) { /* keep the arg as binary, since the encoding is not known */ val = String(php_optarg, CopyString); } else { val = false; } /* Add this option / argument pair to the result hash. */ optname_len = strlen(optname); if (!(optname_len > 1 && optname[0] == '0') && is_numeric_string(optname, optname_len, NULL, NULL, 0) == KindOfInt64) { /* numeric string */ int optname_int = atoi(optname); if (ret.exists(optname_int)) { Variant &e = ret.lvalAt(optname_int); if (!e.isArray()) { ret.set(optname_int, make_packed_array(e, val)); } else { e.toArrRef().append(val); } } else { ret.set(optname_int, val); } } else { /* other strings */ String key(optname, strlen(optname), CopyString); if (ret.exists(key)) { Variant &e = ret.lvalAt(key); if (!e.isArray()) { ret.set(key, make_packed_array(e, val)); } else { e.toArrRef().append(val); } } else { ret.set(key, val); } } php_optarg = NULL; } return ret; }
void TForm1::clearCell(Variant &vSheet, int nRow, int nCol) { vSheet.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,nCol).OlePropertySet("Value", WideString("")); }
result_t JsonRpcHandler::invoke(object_base *v, obj_ptr<Handler_base> &retVal, AsyncEvent *ac) { if (ac) return CHECK_ERROR(CALL_E_NOASYNC); obj_ptr<Message_base> msg = Message_base::getInstance(v); if (msg == NULL) return CHECK_ERROR(CALL_E_BADVARTYPE); Isolate* isolate = holder(); obj_ptr<HttpRequest_base> htreq = HttpRequest_base::getInstance(v); obj_ptr<SeekableStream_base> body; obj_ptr<Buffer_base> buf; v8::Local<v8::Value> jsval; v8::Local<v8::Object> o; Variant result; exlib::string str; int64_t len; int32_t sz, i; result_t hr; obj_ptr<List_base> params; if (htreq != NULL) { if (htreq->firstHeader("Content-Type", result) == CALL_RETURN_NULL) return CHECK_ERROR(Runtime::setError("jsonrpc: Content-Type is missing.")); str = result.string(); if (qstricmp(str.c_str(), "application/json", 16)) return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid Content-Type.")); } msg->get_body(body); body->size(len); sz = (int32_t) len; body->rewind(); hr = body->ac_read(sz, buf); if (hr < 0) return hr; if (hr == CALL_RETURN_NULL) return CHECK_ERROR(Runtime::setError("jsonrpc: request body is empty.")); body.Release(); buf->toString(str); buf.Release(); hr = json_base::decode(str, jsval); if (hr < 0) return hr; if (!jsval->IsObject()) return CHECK_ERROR(Runtime::setError("jsonrpc: Invalid rpc request.")); o = v8::Local<v8::Object>::Cast(jsval); jsval = o->Get(isolate->NewFromUtf8("method", 6)); if (IsEmpty(jsval)) return CHECK_ERROR(Runtime::setError("jsonrpc: method is missing.")); msg->get_value(str); str += '/'; str.append(*v8::String::Utf8Value(jsval)); msg->set_value(str); jsval = o->Get(isolate->NewFromUtf8("params", 6)); if (!jsval.IsEmpty() && jsval->IsArray()) { v8::Local<v8::Array> jsparams = v8::Local<v8::Array>::Cast(jsval); sz = jsparams->Length(); msg->get_params(params); params->resize(sz); for (i = 0; i < sz; i++) params->_indexed_setter(i, jsparams->Get(i)); } obj_ptr<Handler_base> hdlr1; hr = JSHandler::js_invoke(m_handler, v, hdlr1, NULL); if (hr >= 0 && hr != CALL_RETURN_NULL) hr = mq_base::ac_invoke(hdlr1, v); v8::Local<v8::String> strId = isolate->NewFromUtf8("id", 2); jsval = o->Get(strId); o = v8::Object::New(isolate->m_isolate); o->Set(strId, jsval); if (hr < 0) { errorLog("JsonRpcHandler: " + getResultMessage(hr)); result_t hr1 = json_base::encode(o, str); if (hr1 < 0) return hr1; if (str.length() <= 2) str.assign("{", 1); else { str.resize(str.length() - 1); str += ','; } if (hr == CALL_E_INVALID_CALL) str.append( "\"error\": {\"code\": -32601, \"message\": \"Method not found.\"}}"); else str.append( "\"error\": {\"code\": -32603, \"message\": \"Internal error.\"}}"); } else { msg->get_result(result); o->Set(isolate->NewFromUtf8("result", 6), result); hr = json_base::encode(o, str); if (hr < 0) return hr; } body = new MemoryStream(); buf = new Buffer(str); hr = body->ac_write(buf); if (hr < 0) return hr; obj_ptr<Message_base> rep; hr = msg->get_response(rep); if (hr < 0) return hr; rep->set_body(body); if (htreq) ((HttpMessage_base *)(Message_base *)rep)->setHeader( "Content-Type", "application/json"); return CALL_RETURN_NULL; }