bool CheckExternalScripts::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) { try { sh::settings_registry settings(get_settings_proxy()); settings.set_alias(alias, "external scripts"); commands_.set_path(settings.alias().get_settings_path("scripts")); aliases_.set_path(settings.alias().get_settings_path("alias")); std::string wrappings_path = settings.alias().get_settings_path("wrappings"); settings.alias().add_path_to_settings() ("wrappings", sh::string_map_path(&wrappings_) , "EXTERNAL SCRIPT WRAPPINGS SECTION", "A list of templates for wrapped scripts.\n%SCRIPT% will be replaced by the actual script an %ARGS% will be replaced by any given arguments.", "WRAPPING", "An external script wrapping") ("alias", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_alias, this, _1, _2)), "ALIAS SECTION", "A list of aliases available.\n" "An alias is an internal command that has been predefined to provide a single command without arguments. Be careful so you don't create loops (ie check_loop=check_a, check_a=check_loop)", "ALIAS", "Query alias") ; settings.register_all(); settings.notify(); settings.clear(); if (wrappings_.find("ps1") == wrappings_.end()) { wrappings_["ps1"] = "cmd /c echo If (-Not (Test-Path \"scripts\\%SCRIPT%\") ) { Write-Host \"UNKNOWN: Script `\"%SCRIPT%`\" not found.\"; exit(3) }; scripts\\%SCRIPT% $ARGS$; exit($lastexitcode) | powershell.exe /noprofile -command -"; settings.register_key(wrappings_path, "ps1", NSCAPI::key_string, "POWERSHELL WRAPPING", "", "", false); settings.set_static_key(wrappings_path, "ps1", wrappings_["ps1"]); } if (wrappings_.find("vbs") == wrappings_.end()) { wrappings_["vbs"] = "cscript.exe //T:30 //NoLogo scripts\\\\lib\\\\wrapper.vbs %SCRIPT% %ARGS%"; settings.register_key(wrappings_path, "vbs", NSCAPI::key_string, "VISUAL BASIC WRAPPING", "", "", false); settings.set_static_key(wrappings_path, "vbs", wrappings_["vbs"]); } if (wrappings_.find("bat") == wrappings_.end()) { wrappings_["bat"] = "scripts\\\\%SCRIPT% %ARGS%"; settings.register_key(wrappings_path, "bat", NSCAPI::key_string, "BATCH FILE WRAPPING", "", "", false); settings.set_static_key(wrappings_path, "bat", wrappings_["bat"]); } if (aliases_.empty()) { NSC_DEBUG_MSG("No aliases found (adding default)"); add_alias("alias_cpu", "check_cpu"); add_alias("alias_cpu_ex", "check_cpu \"warn=load > $ARG1$\" \"crit=load > $ARG2$\" time=5m time=1m time=30s"); add_alias("alias_mem", "check_memory"); add_alias("alias_up", "check_uptime"); add_alias("alias_disk", "check_drivesize"); add_alias("alias_disk_loose", "check_drivesize"); add_alias("alias_volumes", "check_drivesize"); add_alias("alias_volumes_loose", "check_drivesize"); add_alias("alias_service", "check_service"); add_alias("alias_service_ex", "check_service \"exclude=Net Driver HPZ12\" \"exclude=Pml Driver HPZ12\" exclude=stisvc"); add_alias("alias_process", "check_process \"process=$ARG1$\" \"crit=state != 'started'\""); add_alias("alias_process_stopped", "check_process \"process=$ARG1$\" \"crit=state != 'stopped'\""); add_alias("alias_process_count", "check_process \"process=$ARG1$\" \"warn=count > $ARG2$\" \"crit=count > $ARG3$\""); add_alias("alias_process_hung", "check_process \"filter=is_hung\" \"crit=count>0\""); add_alias("alias_event_log", "check_eventlog"); add_alias("alias_file_size", "check_files \"path=$ARG1$\" \"crit=size > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${size}\" max-dir-depth=10"); add_alias("alias_file_age", "check_files \"path=$ARG1$\" \"crit=written > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${written}\" max-dir-depth=10"); add_alias("alias_sched_all", "check_tasksched show-all \"syntax=${title}: ${exit_code}\" \"crit=exit_code ne 0\""); add_alias("alias_sched_long", "check_tasksched \"filter=status = 'running'\" \"detail-syntax=${title} (${most_recent_run_time})\" \"crit=most_recent_run_time < -$ARG1$\""); add_alias("alias_sched_task", "check_tasksched show-all \"filter=title eq '$ARG1$'\" \"detail-syntax=${title} (${exit_code})\" \"crit=exit_code ne 0\""); // add_alias("alias_updates", "check_updates -warning 0 -critical 0"); } settings.alias().add_path_to_settings() ("EXTERNAL SCRIPT SECTION", "Section for external scripts configuration options (CheckExternalScripts).") ("scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_command, this, _1, _2)), "SCRIPT SECTION", "A list of scripts available to run from the CheckExternalScripts module. Syntax is: <command>=<script> <arguments>", "SCRIPT", "For more configuration options add a dedicated section (if you add a new section you can customize the user and various other advanced features)") ("wrapped scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)), "WRAPPED SCRIPTS SECTION", "A list of wrapped scripts (ie. scruts using a template mechanism). The template used will be defined by the extension of the script.", "WRAPPED SCRIPT", "A wrapped script defenitions") ; settings.alias().add_key_to_settings() ("timeout", sh::uint_key(&timeout, 60), "COMMAND TIMEOUT", "The maximum time in seconds that a command can execute. (if more then this execution will be aborted). NOTICE this only affects external commands not internal ones.") ("allow arguments", sh::bool_key(&allowArgs_, false), "COMMAND ARGUMENT PROCESSING", "This option determines whether or not the we will allow clients to specify arguments to commands that are executed.") ("allow nasty characters", sh::bool_key(&allowNasty_, false), "COMMAND ALLOW NASTY META CHARS", "This option determines whether or not the we will allow clients to specify nasty (as in |`&><'\"\\[]{}) characters in arguments.") ("script path", sh::string_key(&scriptDirectory_), "SCRIPT DIRECTORY", "Load all scripts in a directory and use them as commands. Probably dangerous but useful if you have loads of scripts :)") ; settings.alias().add_templates() ("scripts", "plus", "Add a simple script", "Add binding for a simple script", "{" "\"fields\": [ " " { \"id\": \"alias\", \"title\" : \"Alias\", \"type\" : \"input\", \"desc\" : \"This will identify the command\"} , " " { \"id\": \"script\", \"title\" : \"Script\", \"type\" : \"data-choice\", \"desc\" : \"The name of the script\",\"exec\" : \"CheckExternalScripts list --json\" } , " " { \"id\": \"args\", \"title\" : \"Arguments\", \"type\" : \"input\", \"desc\" : \"Command line arguments for the script use $ARG1$ to specify arguments\" } , " " { \"id\": \"cmd\", \"key\" : \"command\", \"title\" : \"A\", \"type\" : \"hidden\", \"desc\" : \"A\" } " " ], " "\"events\": { " "\"onSave\": \"(function (node) { node.save_path = self.path; var f = node.get_field('cmd'); f.key = node.get_field('alias').value(); var val = node.get_field('script').value(); if (node.get_field('args').value()) { val += ' ' + node.get_field('args').value(); }; f.value(val)})\"" "}" "}") ("alias", "plus", "Add an alias", "Add binding for an alias", "{" "\"fields\": [ " " { \"id\": \"alias\", \"title\" : \"Alias\", \"type\" : \"input\", \"desc\" : \"This will identify the command\"} , " " { \"id\": \"command\", \"title\" : \"Command\", \"type\" : \"data-choice\", \"desc\" : \"The name of the command to execute\",\"exec\" : \"CheckExternalScripts list --json --query\" } , " " { \"id\": \"args\", \"title\" : \"Arguments\", \"type\" : \"input\", \"desc\" : \"Command line arguments for the command. use $ARG1$ to specify arguments\" } , " " { \"id\": \"cmd\", \"key\" : \"command\", \"title\" : \"A\", \"type\" : \"hidden\", \"desc\" : \"A\" } " " ], " "\"events\": { " "\"onSave\": \"(function (node) { node.save_path = self.path; \nvar f = node.get_field('cmd'); \nf.key = node.get_field('alias').value(); \nvar val = node.get_field('command').value(); \nif (node.get_field('args').value()) { \nval += ' ' + node.get_field('args').value(); }; \nf.value(val)})\"" "}" "}") ; settings.register_all(); settings.notify(); std::string scripts_path = settings.alias().get_settings_path("scripts"); std::string alias_path = settings.alias().get_settings_path("alias"); commands_.add_samples(get_settings_proxy()); commands_.add_missing(get_settings_proxy(), "default", "", true); aliases_.add_samples(get_settings_proxy()); aliases_.add_missing(get_settings_proxy(), "default", "", true); if (!scriptDirectory_.empty()) { addAllScriptsFrom(scriptDirectory_); } root_ = get_base_path(); nscapi::core_helper core(get_core(), get_id()); BOOST_FOREACH(const boost::shared_ptr<commands::command_object> &o, commands_.get_object_list()) { core.register_alias(o->get_alias(), "External script: " + o->command); } BOOST_FOREACH(const boost::shared_ptr<alias::command_object> &o, aliases_.get_object_list()) { core.register_alias(o->get_alias(), "Alias for: " + o->command); } } catch (...) { NSC_LOG_ERROR_EX("loading"); return false; } return true; }
void FindController::updateFindUIAfterPageScroll(bool found, const String& string, FindOptions options, unsigned maxMatchCount) { Frame* selectedFrame = frameWithSelection(m_webPage->corePage()); PluginView* pluginView = pluginViewForFrame(m_webPage->mainFrame()); bool shouldShowOverlay = false; if (!found) { if (!pluginView) m_webPage->corePage()->unmarkAllTextMatches(); if (selectedFrame) selectedFrame->selection()->clear(); hideFindIndicator(); m_webPage->send(Messages::WebPageProxy::DidFailToFindString(string)); } else { shouldShowOverlay = options & FindOptionsShowOverlay; bool shouldShowHighlight = options & FindOptionsShowHighlight; unsigned matchCount = 1; if (shouldShowOverlay || shouldShowHighlight) { if (maxMatchCount == std::numeric_limits<unsigned>::max()) --maxMatchCount; if (pluginView) { matchCount = pluginView->countFindMatches(string, core(options), maxMatchCount + 1); shouldShowOverlay = false; } else { m_webPage->corePage()->unmarkAllTextMatches(); matchCount = m_webPage->corePage()->markAllMatchesForText(string, core(options), shouldShowHighlight, maxMatchCount + 1); } // If we have a large number of matches, we don't want to take the time to paint the overlay. if (matchCount > maxMatchCount) { shouldShowOverlay = false; matchCount = static_cast<unsigned>(kWKMoreThanMaximumMatchCount); } } m_webPage->send(Messages::WebPageProxy::DidFindString(string, matchCount)); if (!(options & FindOptionsShowFindIndicator) || !updateFindIndicator(selectedFrame, shouldShowOverlay)) hideFindIndicator(); } if (!shouldShowOverlay) { if (m_findPageOverlay) m_webPage->uninstallPageOverlay(m_findPageOverlay, true); } else { if (!m_findPageOverlay) { RefPtr<PageOverlay> findPageOverlay = PageOverlay::create(this); m_findPageOverlay = findPageOverlay.get(); m_webPage->installPageOverlay(findPageOverlay.release(), true); m_findPageOverlay->setNeedsDisplay(); } else m_findPageOverlay->setNeedsDisplay(); } }
void LayoutAlignmentCommand::undo() { LayoutAlignmentCommand::applyAlignment(core(), m_widget, m_oldAlignment); }
VOID WINAPI service_main(DWORD argc, LPTSTR* argv) { service_configuration configuration; parse_service_options(argc, argv, configuration); const fscp::logger logger = create_logger(configuration); logger(fscp::log_level::information) << "Log starts at " << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()); if (configuration.configuration_file.empty()) { logger(fscp::log_level::warning) << "No configuration specified."; } else { logger(fscp::log_level::information) << "Reading configuration at: " << configuration.configuration_file; } /* Initializations */ cryptoplus::crypto_initializer crypto_initializer; cryptoplus::algorithms_initializer algorithms_initializer; cryptoplus::error::error_strings_initializer error_strings_initializer; freelan::initializer freelan_initializer; service_context ctx; ctx.service_status.dwServiceType = SERVICE_WIN32; ctx.service_status.dwCurrentState = SERVICE_STOPPED; ctx.service_status.dwControlsAccepted = 0; ctx.service_status.dwWin32ExitCode = NO_ERROR; ctx.service_status.dwServiceSpecificExitCode = NO_ERROR; ctx.service_status.dwCheckPoint = 0; ctx.service_status.dwWaitHint = 0; ctx.service_status_handle = ::RegisterServiceCtrlHandlerEx(SERVICE_NAME, &handler_ex, &ctx); if (ctx.service_status_handle != 0) { ctx.service_status.dwCurrentState = SERVICE_START_PENDING; // Start pending ::SetServiceStatus(ctx.service_status_handle, &ctx.service_status); try { boost::asio::io_service io_service; fl::configuration fl_configuration = get_freelan_configuration(logger, configuration); fl::core core(io_service, fl_configuration); core.set_log_level(logger.level()); core.set_log_callback(logger.callback()); if (!fl_configuration.tap_adapter.up_script.empty()) { core.set_tap_adapter_up_callback(boost::bind(&execute_tap_adapter_up_script, fl_configuration.tap_adapter.up_script, logger, _1)); } if (!fl_configuration.tap_adapter.down_script.empty()) { core.set_tap_adapter_down_callback(boost::bind(&execute_tap_adapter_down_script, fl_configuration.tap_adapter.down_script, logger, _1)); } if (!fl_configuration.security.certificate_validation_script.empty()) { core.set_certificate_validation_callback(boost::bind(&execute_certificate_validation_script, fl_configuration.security.certificate_validation_script, logger, _1)); } if (!fl_configuration.server.authentication_script.empty()) { core.set_authentication_callback(boost::bind(&execute_authentication_script, fl_configuration.server.authentication_script, logger, _1, _2, _3, _4)); } if (!fl_configuration.router.dns_script.empty()) { core.set_dns_callback(boost::bind(&execute_dns_script, fl_configuration.router.dns_script, logger, _1, _2, _3)); } core.open(); boost::unique_lock<boost::mutex> lock(ctx.stop_function_mutex); ctx.stop_function = boost::bind(&fl::core::close, boost::ref(core)); lock.unlock(); // Running ctx.service_status.dwControlsAccepted |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); ctx.service_status.dwCurrentState = SERVICE_RUNNING; ::SetServiceStatus(ctx.service_status_handle, &ctx.service_status); boost::thread_group threads; unsigned int thread_count = configuration.thread_count; if (thread_count == 0) { thread_count = boost::thread::hardware_concurrency(); // Some implementation can return 0. if (thread_count == 0) { // We create 2 threads. thread_count = 2; } } logger(fscp::log_level::information) << "Using " << thread_count << " thread(s)."; logger(fscp::log_level::information) << "Execution started."; for (std::size_t i = 0; i < thread_count; ++i) { threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service)); } threads.join_all(); logger(fscp::log_level::information) << "Execution stopped."; lock.lock(); ctx.stop_function = NULL; lock.unlock(); } catch (boost::system::system_error& ex) { ctx.service_status.dwWin32ExitCode = ex.code().value(); ::SetServiceStatus(ctx.service_status_handle, &ctx.service_status); logger(fscp::log_level::error) << "Error: " << ex.code() << ":" << ex.code().message() << ":" << ex.what(); } catch (std::exception& ex) { ctx.service_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; ctx.service_status.dwServiceSpecificExitCode = 1; ::SetServiceStatus(ctx.service_status_handle, &ctx.service_status); logger(fscp::log_level::error) << "Error: " << ex.what(); } // Stop ctx.service_status.dwControlsAccepted &= ~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); ctx.service_status.dwCurrentState = SERVICE_STOPPED; ::SetServiceStatus(ctx.service_status_handle, &ctx.service_status); } logger(fscp::log_level::information) << "Log stops at " << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()); }
MSIDispatchConsumer* MSIDispatchConsumerClass::create(IDispatch* p) { VTable* ivtable = this->ivtable(); MSIDispatchConsumer *o = new (core()->GetGC(), ivtable->getExtraSize()) MSIDispatchConsumer(ivtable, prototype, p); return o; }
void FormWindowBase::resourceSetActivated(QtResourceSet *resource, bool resourceSetChanged) { if (resource == resourceSet() && resourceSetChanged) { reloadProperties(); emit pixmapCache()->reloaded(); emit iconCache()->reloaded(); if (QDesignerPropertyEditor *propertyEditor = qobject_cast<QDesignerPropertyEditor *>(core()->propertyEditor())) propertyEditor->reloadResourceProperties(); } }
ScriptObject* ObjectClass::construct() { return (ScriptObject*) core()->newObject(ivtable(), prototypePtr()); }
void EditorClient::handleKeyboardEvent(KeyboardEvent* event) { Frame* frame = core(m_webView)->focusController()->focusedOrMainFrame(); if (!frame || !frame->document()->focusedNode()) return; const PlatformKeyboardEvent* kevent = event->keyEvent(); if (!kevent || kevent->type() == PlatformKeyboardEvent::KeyUp) return; Node* start = frame->selection()->start().node(); if (!start) return; // FIXME: Use GtkBindingSet instead of this hard-coded switch // http://bugs.webkit.org/show_bug.cgi?id=15911 if (start->isContentEditable()) { switch (kevent->windowsVirtualKeyCode()) { case VK_BACK: frame->editor()->deleteWithDirection(SelectionController::BACKWARD, kevent->ctrlKey() ? WordGranularity : CharacterGranularity, false, true); break; case VK_DELETE: frame->editor()->deleteWithDirection(SelectionController::FORWARD, kevent->ctrlKey() ? WordGranularity : CharacterGranularity, false, true); break; case VK_LEFT: frame->selection()->modify(kevent->shiftKey() ? SelectionController::EXTEND : SelectionController::MOVE, SelectionController::LEFT, kevent->ctrlKey() ? WordGranularity : CharacterGranularity, true); break; case VK_RIGHT: frame->selection()->modify(kevent->shiftKey() ? SelectionController::EXTEND : SelectionController::MOVE, SelectionController::RIGHT, kevent->ctrlKey() ? WordGranularity : CharacterGranularity, true); break; case VK_UP: frame->selection()->modify(kevent->shiftKey() ? SelectionController::EXTEND : SelectionController::MOVE, SelectionController::BACKWARD, kevent->ctrlKey() ? ParagraphGranularity : LineGranularity, true); break; case VK_DOWN: frame->selection()->modify(kevent->shiftKey() ? SelectionController::EXTEND : SelectionController::MOVE, SelectionController::FORWARD, kevent->ctrlKey() ? ParagraphGranularity : LineGranularity, true); break; case VK_PRIOR: // PageUp frame->editor()->command(kevent->shiftKey() ? "MovePageUpAndModifySelection" : "MovePageUp").execute(); break; case VK_NEXT: // PageDown frame->editor()->command(kevent->shiftKey() ? "MovePageDownAndModifySelection" : "MovePageDown").execute(); break; case VK_HOME: if (kevent->ctrlKey() && kevent->shiftKey()) frame->editor()->command("MoveToBeginningOfDocumentAndModifySelection").execute(); else if (kevent->ctrlKey()) frame->editor()->command("MoveToBeginningOfDocument").execute(); else if (kevent->shiftKey()) frame->editor()->command("MoveToBeginningOfLineAndModifySelection").execute(); else frame->editor()->command("MoveToBeginningOfLine").execute(); break; case VK_END: if (kevent->ctrlKey() && kevent->shiftKey()) frame->editor()->command("MoveToEndOfDocumentAndModifySelection").execute(); else if (kevent->ctrlKey()) frame->editor()->command("MoveToEndOfDocument").execute(); else if (kevent->shiftKey()) frame->editor()->command("MoveToEndOfLineAndModifySelection").execute(); else frame->editor()->command("MoveToEndOfLine").execute(); break; case VK_RETURN: frame->editor()->command("InsertLineBreak").execute(); break; case VK_TAB: return; default: if (!kevent->ctrlKey() && !kevent->altKey() && !kevent->text().isEmpty()) { if (kevent->text().length() == 1) { UChar ch = kevent->text()[0]; // Don't insert null or control characters as they can result in unexpected behaviour if (ch < ' ') break; } frame->editor()->insertText(kevent->text(), event); } else if (kevent->ctrlKey()) { switch (kevent->windowsVirtualKeyCode()) { case VK_B: frame->editor()->command("ToggleBold").execute(); break; case VK_I: frame->editor()->command("ToggleItalic").execute(); break; case VK_Y: frame->editor()->command("Redo").execute(); break; case VK_Z: frame->editor()->command("Undo").execute(); break; default: return; } } else return; } } else { switch (kevent->windowsVirtualKeyCode()) { case VK_UP: frame->editor()->command("MoveUp").execute(); break; case VK_DOWN: frame->editor()->command("MoveDown").execute(); break; case VK_PRIOR: // PageUp frame->editor()->command("MovePageUp").execute(); break; case VK_NEXT: // PageDown frame->editor()->command("MovePageDown").execute(); break; case VK_HOME: if (kevent->ctrlKey()) frame->editor()->command("MoveToBeginningOfDocument").execute(); break; case VK_END: if (kevent->ctrlKey()) frame->editor()->command("MoveToEndOfDocument").execute(); break; default: return; } } event->setDefaultHandled(); }
CCPUInfo::CCPUInfo(void) { #ifdef TARGET_POSIX m_fProcStat = m_fProcTemperature = m_fCPUFreq = NULL; m_cpuInfoForFreq = false; #elif defined(TARGET_WINDOWS) m_cpuQueryFreq = nullptr; m_cpuQueryLoad = nullptr; #endif m_lastUsedPercentage = 0; m_cpuFeatures = 0; #if defined(TARGET_DARWIN) size_t len = 4; std::string cpuVendor; // The number of cores. if (sysctlbyname("hw.activecpu", &m_cpuCount, &len, NULL, 0) == -1) m_cpuCount = 1; // The model. #if defined(__ppc__) || defined (TARGET_DARWIN_IOS) const NXArchInfo *info = NXGetLocalArchInfo(); if (info != NULL) m_cpuModel = info->description; #else // NXGetLocalArchInfo is ugly for intel so keep using this method char buffer[512]; len = 512; if (sysctlbyname("machdep.cpu.brand_string", &buffer, &len, NULL, 0) == 0) m_cpuModel = buffer; // The CPU vendor len = 512; if (sysctlbyname("machdep.cpu.vendor", &buffer, &len, NULL, 0) == 0) cpuVendor = buffer; #endif // Go through each core. for (int i=0; i<m_cpuCount; i++) { CoreInfo core; core.m_id = i; core.m_strModel = m_cpuModel; core.m_strVendor = cpuVendor; m_cores[core.m_id] = core; } #elif defined(TARGET_WINDOWS) HKEY hKeyCpuRoot; if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor", 0, KEY_READ, &hKeyCpuRoot) == ERROR_SUCCESS) { DWORD num = 0; std::vector<CoreInfo> cpuCores; wchar_t subKeyName[200]; // more than enough DWORD subKeyNameLen = sizeof(subKeyName) / sizeof(wchar_t); while (RegEnumKeyExW(hKeyCpuRoot, num++, subKeyName, &subKeyNameLen, nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS) { HKEY hCpuKey; if (RegOpenKeyExW(hKeyCpuRoot, subKeyName, 0, KEY_QUERY_VALUE, &hCpuKey) == ERROR_SUCCESS) { CoreInfo cpuCore; if (swscanf_s(subKeyName, L"%i", &cpuCore.m_id) != 1) cpuCore.m_id = num - 1; wchar_t buf[300]; // more than enough DWORD bufSize = sizeof(buf); DWORD valType; if (RegQueryValueExW(hCpuKey, L"ProcessorNameString", nullptr, &valType, LPBYTE(buf), &bufSize) == ERROR_SUCCESS && valType == REG_SZ) { g_charsetConverter.wToUTF8(std::wstring(buf, bufSize / sizeof(wchar_t)), cpuCore.m_strModel); cpuCore.m_strModel = cpuCore.m_strModel.substr(0, cpuCore.m_strModel.find(char(0))); // remove extra null terminations StringUtils::RemoveDuplicatedSpacesAndTabs(cpuCore.m_strModel); StringUtils::Trim(cpuCore.m_strModel); } bufSize = sizeof(buf); if (RegQueryValueExW(hCpuKey, L"VendorIdentifier", nullptr, &valType, LPBYTE(buf), &bufSize) == ERROR_SUCCESS && valType == REG_SZ) { g_charsetConverter.wToUTF8(std::wstring(buf, bufSize / sizeof(wchar_t)), cpuCore.m_strVendor); cpuCore.m_strVendor = cpuCore.m_strVendor.substr(0, cpuCore.m_strVendor.find(char(0))); // remove extra null terminations } DWORD mhzVal; bufSize = sizeof(mhzVal); if (RegQueryValueExW(hCpuKey, L"~MHz", nullptr, &valType, LPBYTE(&mhzVal), &bufSize) == ERROR_SUCCESS && valType == REG_DWORD) cpuCore.m_fSpeed = double(mhzVal); RegCloseKey(hCpuKey); if (cpuCore.m_strModel.empty()) cpuCore.m_strModel = "Unknown"; cpuCores.push_back(cpuCore); } subKeyNameLen = sizeof(subKeyName) / sizeof(wchar_t); // restore length value } RegCloseKey(hKeyCpuRoot); std::sort(cpuCores.begin(), cpuCores.end()); // sort cores by id for (size_t i = 0; i < cpuCores.size(); i++) m_cores[i] = cpuCores[i]; // add in sorted order } if (!m_cores.empty()) m_cpuModel = m_cores.begin()->second.m_strModel; else m_cpuModel = "Unknown"; SYSTEM_INFO siSysInfo; GetNativeSystemInfo(&siSysInfo); m_cpuCount = siSysInfo.dwNumberOfProcessors; if (PdhOpenQueryW(nullptr, 0, &m_cpuQueryFreq) == ERROR_SUCCESS) { if (PdhAddEnglishCounterW(m_cpuQueryFreq, L"\\Processor Information(0,0)\\Processor Frequency", 0, &m_cpuFreqCounter) != ERROR_SUCCESS) m_cpuFreqCounter = nullptr; } else m_cpuQueryFreq = nullptr; if (PdhOpenQueryW(nullptr, 0, &m_cpuQueryLoad) == ERROR_SUCCESS) { for (size_t i = 0; i < m_cores.size(); i++) { if (PdhAddEnglishCounterW(m_cpuQueryLoad, StringUtils::Format(L"\\Processor(%d)\\%% Idle Time", int(i)).c_str(), 0, &m_cores[i].m_coreCounter) != ERROR_SUCCESS) m_cores[i].m_coreCounter = nullptr; } } else m_cpuQueryLoad = nullptr; #elif defined(TARGET_FREEBSD) size_t len; int i; char cpumodel[512]; len = sizeof(m_cpuCount); if (sysctlbyname("hw.ncpu", &m_cpuCount, &len, NULL, 0) != 0) m_cpuCount = 1; len = sizeof(cpumodel); if (sysctlbyname("hw.model", &cpumodel, &len, NULL, 0) != 0) (void)strncpy(cpumodel, "Unknown", 8); m_cpuModel = cpumodel; for (i = 0; i < m_cpuCount; i++) { CoreInfo core; core.m_id = i; core.m_strModel = m_cpuModel; m_cores[core.m_id] = core; } #else m_fProcStat = fopen("/proc/stat", "r"); m_fProcTemperature = fopen("/proc/acpi/thermal_zone/THM0/temperature", "r"); if (m_fProcTemperature == NULL) m_fProcTemperature = fopen("/proc/acpi/thermal_zone/THRM/temperature", "r"); if (m_fProcTemperature == NULL) m_fProcTemperature = fopen("/proc/acpi/thermal_zone/THR0/temperature", "r"); if (m_fProcTemperature == NULL) m_fProcTemperature = fopen("/proc/acpi/thermal_zone/TZ0/temperature", "r"); // read from the new location of the temperature data on new kernels, 2.6.39, 3.0 etc if (m_fProcTemperature == NULL) m_fProcTemperature = fopen("/sys/class/hwmon/hwmon0/temp1_input", "r"); if (m_fProcTemperature == NULL) m_fProcTemperature = fopen("/sys/class/thermal/thermal_zone0/temp", "r"); // On Raspberry PIs m_fCPUFreq = fopen ("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", "r"); if (!m_fCPUFreq) { m_cpuInfoForFreq = true; m_fCPUFreq = fopen("/proc/cpuinfo", "r"); } else m_cpuInfoForFreq = false; FILE* fCPUInfo = fopen("/proc/cpuinfo", "r"); m_cpuCount = 0; if (fCPUInfo) { char buffer[512]; int nCurrId = 0; while (fgets(buffer, sizeof(buffer), fCPUInfo)) { if (strncmp(buffer, "processor", strlen("processor"))==0) { char *needle = strstr(buffer, ":"); if (needle) { CoreInfo core; core.m_id = atoi(needle+2); nCurrId = core.m_id; m_cores[core.m_id] = core; } m_cpuCount++; } else if (strncmp(buffer, "vendor_id", strlen("vendor_id"))==0) { char *needle = strstr(buffer, ":"); if (needle && strlen(needle)>3) { needle+=2; m_cores[nCurrId].m_strVendor = needle; StringUtils::Trim(m_cores[nCurrId].m_strVendor); } } else if (strncmp(buffer, "Processor", strlen("Processor"))==0) { char *needle = strstr(buffer, ":"); if (needle && strlen(needle)>3) { needle+=2; m_cpuModel = needle; m_cores[nCurrId].m_strModel = m_cpuModel; StringUtils::Trim(m_cores[nCurrId].m_strModel); } } else if (strncmp(buffer, "BogoMIPS", strlen("BogoMIPS"))==0) { char *needle = strstr(buffer, ":"); if (needle && strlen(needle)>3) { needle+=2; m_cpuBogoMips = needle; m_cores[nCurrId].m_strBogoMips = m_cpuBogoMips; StringUtils::Trim(m_cores[nCurrId].m_strBogoMips); } } else if (strncmp(buffer, "Hardware", strlen("Hardware"))==0) { char *needle = strstr(buffer, ":"); if (needle && strlen(needle)>3) { needle+=2; m_cpuHardware = needle; m_cores[nCurrId].m_strHardware = m_cpuHardware; StringUtils::Trim(m_cores[nCurrId].m_strHardware); } } else if (strncmp(buffer, "Revision", strlen("Revision"))==0) { char *needle = strstr(buffer, ":"); if (needle && strlen(needle)>3) { needle+=2; m_cpuRevision = needle; m_cores[nCurrId].m_strRevision = m_cpuRevision; StringUtils::Trim(m_cores[nCurrId].m_strRevision); } } else if (strncmp(buffer, "Serial", strlen("Serial"))==0) { char *needle = strstr(buffer, ":"); if (needle && strlen(needle)>3) { needle+=2; m_cpuSerial = needle; m_cores[nCurrId].m_strSerial = m_cpuSerial; StringUtils::Trim(m_cores[nCurrId].m_strSerial); } } else if (strncmp(buffer, "model name", strlen("model name"))==0) { char *needle = strstr(buffer, ":"); if (needle && strlen(needle)>3) { needle+=2; m_cpuModel = needle; m_cores[nCurrId].m_strModel = m_cpuModel; StringUtils::Trim(m_cores[nCurrId].m_strModel); } } else if (strncmp(buffer, "flags", 5) == 0) { char* needle = strchr(buffer, ':'); if (needle) { char* tok = NULL, * save; needle++; tok = strtok_r(needle, " ", &save); while (tok) { if (0 == strcmp(tok, "mmx")) m_cpuFeatures |= CPU_FEATURE_MMX; else if (0 == strcmp(tok, "mmxext")) m_cpuFeatures |= CPU_FEATURE_MMX2; else if (0 == strcmp(tok, "sse")) m_cpuFeatures |= CPU_FEATURE_SSE; else if (0 == strcmp(tok, "sse2")) m_cpuFeatures |= CPU_FEATURE_SSE2; else if (0 == strcmp(tok, "sse3")) m_cpuFeatures |= CPU_FEATURE_SSE3; else if (0 == strcmp(tok, "ssse3")) m_cpuFeatures |= CPU_FEATURE_SSSE3; else if (0 == strcmp(tok, "sse4_1")) m_cpuFeatures |= CPU_FEATURE_SSE4; else if (0 == strcmp(tok, "sse4_2")) m_cpuFeatures |= CPU_FEATURE_SSE42; else if (0 == strcmp(tok, "3dnow")) m_cpuFeatures |= CPU_FEATURE_3DNOW; else if (0 == strcmp(tok, "3dnowext")) m_cpuFeatures |= CPU_FEATURE_3DNOWEXT; tok = strtok_r(NULL, " ", &save); } } } } fclose(fCPUInfo); // /proc/cpuinfo is not reliable on some Android platforms // At least we should get the correct cpu count for multithreaded decoding #if defined(TARGET_ANDROID) if (CAndroidFeatures::GetCPUCount() > m_cpuCount) { for (int i = m_cpuCount; i < CAndroidFeatures::GetCPUCount(); i++) { // Copy info from cpu 0 CoreInfo core(m_cores[0]); core.m_id = i; m_cores[core.m_id] = core; } m_cpuCount = CAndroidFeatures::GetCPUCount(); } #endif } else { m_cpuCount = 1; m_cpuModel = "Unknown"; } #endif StringUtils::Replace(m_cpuModel, '\r', ' '); StringUtils::Replace(m_cpuModel, '\n', ' '); StringUtils::RemoveDuplicatedSpacesAndTabs(m_cpuModel); StringUtils::Trim(m_cpuModel); /* Set some default for empty string variables */ if (m_cpuBogoMips.empty()) m_cpuBogoMips = "N/A"; if (m_cpuHardware.empty()) m_cpuHardware = "N/A"; if (m_cpuRevision.empty()) m_cpuRevision = "N/A"; if (m_cpuSerial.empty()) m_cpuSerial = "N/A"; readProcStat(m_userTicks, m_niceTicks, m_systemTicks, m_idleTicks, m_ioTicks); m_nextUsedReadTime.Set(MINIMUM_TIME_BETWEEN_READS); ReadCPUFeatures(); // Set MMX2 when SSE is present as SSE is a superset of MMX2 and Intel doesn't set the MMX2 cap if (m_cpuFeatures & CPU_FEATURE_SSE) m_cpuFeatures |= CPU_FEATURE_MMX2; if (HasNeon()) m_cpuFeatures |= CPU_FEATURE_NEON; }
ScriptObject* TouchscreenTypeClass::createInstance(VTable *ivtable, ScriptObject* prototype) { return new (core()->GetGC(), ivtable->getExtraSize()) TouchscreenTypeObject(ivtable, prototype, 0); //AS3 'new' opt...Add your init code here... }
QWidget *QMdiAreaPropertySheet::currentWindow() const { if (const QDesignerContainerExtension *c = qt_extension<QDesignerContainerExtension*>(core()->extensionManager(), object())) { const int ci = c->currentIndex(); if (ci < 0) return 0; return c->widget(ci); } return 0; }
ScriptObject* GraphicsPathWindingClass::createInstance(VTable *ivtable, ScriptObject* prototype) { return new (core()->GetGC(), ivtable->getExtraSize()) GraphicsPathWindingObject(ivtable, prototype, 0); //AS3 'new' opt...Add your init code here... }
KisColor::~KisColor() { core()->~Core(); }
/* * what return PeriphObject::open * */ bool CoreTest::execute_class_api_case(){ bool result = true; core_info_t core_info; Core core(0); //first get info //validate info SerialNumber serial; serial.get(); String serial_get_str; String serial_str; serial_get_str = serial.to_string(); if(core.open() >=0){ core.get_info(core_info); mcu_board_config_t mcu_board_config; core.get_mcu_board_config(mcu_board_config); if((mcu_board_config.core_osc_freq < MIN_OSC_FREQ) || \ (mcu_board_config.core_osc_freq > MAX_OSC_FREQ)){ print_case_message("core_osc_freq %lu",mcu_board_config.core_osc_freq); print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } if(mcu_board_config.core_cpu_freq <MIN_CPU_FREQ || \ mcu_board_config.core_cpu_freq >MAX_CPU_FREQ){ print_case_message("core_cpu_freq %lu",mcu_board_config.core_cpu_freq); print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } if(mcu_board_config.core_periph_freq < MIN_PERIPH_FREQ || \ mcu_board_config.core_periph_freq >MAX_PERIPH_FREQ){ print_case_message("core_periph_freq %lu",mcu_board_config.core_periph_freq); print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } if(mcu_board_config.usb_max_packet_zero ==0 ){ print_case_message("usb_max_packet_zero %lu",mcu_board_config.usb_max_packet_zero); print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } if(mcu_board_config.debug_uart_port > MCU_UART_PORTS){ print_case_message("debug_uart_port %d",mcu_board_config.debug_uart_port); print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } u32 osc_freq_temp = mcu_board_config.core_cpu_freq; core.set_clock_divide(2); core.get_mcu_board_config(mcu_board_config); if(osc_freq_temp != (2 * mcu_board_config.core_cpu_freq)){ print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } core.set_clock_divide(1); CoreInfo core_info_c(core_info); serial = core_info_c.serial_number(); serial_str = serial.to_string(); print_case_message("serial %s",serial_str.c_str()); if(memcmp(serial_str.c_str(),serial_get_str.c_str(),serial_str.size())){ print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } if(core_info_c.o_flags() != mcu_board_config.o_flags){ print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } /* print_case_message("events 0x%08x",core_info_c.o_events()); String api_version(core_info_c.api_version()); print_case_message("api version %s",api_version.c_str()); String delim; api_version.get_delimited_data(delim,3,'.'); print_case_message("api version %s",delim.c_str()); print_case_message("git hash %s",core_info_c.api_git_hash());*/ core.close(); }else{ print_case_message("Failed %s %d:", __FILE__, __LINE__); result = false; } return result; }
void cealtesthook_run_core() { core(arrtree_sum_core)(&arrtree_input, &scalar_output_core); }
void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge) { LOG(Network, "CFNet - didReceiveAuthenticationChallenge()"); ASSERT(d->m_currentWebChallenge.isNull()); // Since CFURLConnection networking relies on keeping a reference to the original CFURLAuthChallengeRef, // we make sure that is actually present ASSERT(challenge.cfURLAuthChallengeRef()); ASSERT(challenge.authenticationClient() == this); // Should be already set. #if !PLATFORM(WIN) // Proxy authentication is handled by CFNetwork internally. We can get here if the user cancels // CFNetwork authentication dialog, and we shouldn't ask the client to display another one in that case. if (challenge.protectionSpace().isProxy()) { // Cannot use receivedRequestToContinueWithoutCredential(), because current challenge is not yet set. CFURLConnectionUseCredential(d->m_connection.get(), 0, challenge.cfURLAuthChallengeRef()); return; } #endif if (!d->m_user.isNull() && !d->m_pass.isNull()) { RetainPtr<CFURLCredentialRef> credential = adoptCF(CFURLCredentialCreate(kCFAllocatorDefault, d->m_user.createCFString().get(), d->m_pass.createCFString().get(), 0, kCFURLCredentialPersistenceNone)); URL urlToStore; if (challenge.failureResponse().httpStatusCode() == 401) urlToStore = challenge.failureResponse().url(); CredentialStorage::set(core(credential.get()), challenge.protectionSpace(), urlToStore); CFURLConnectionUseCredential(d->m_connection.get(), credential.get(), challenge.cfURLAuthChallengeRef()); d->m_user = String(); d->m_pass = String(); // FIXME: Per the specification, the user shouldn't be asked for credentials if there were incorrect ones provided explicitly. return; } if (!client() || client()->shouldUseCredentialStorage(this)) { if (!d->m_initialCredential.isEmpty() || challenge.previousFailureCount()) { // The stored credential wasn't accepted, stop using it. // There is a race condition here, since a different credential might have already been stored by another ResourceHandle, // but the observable effect should be very minor, if any. CredentialStorage::remove(challenge.protectionSpace()); } if (!challenge.previousFailureCount()) { Credential credential = CredentialStorage::get(challenge.protectionSpace()); if (!credential.isEmpty() && credential != d->m_initialCredential) { ASSERT(credential.persistence() == CredentialPersistenceNone); if (challenge.failureResponse().httpStatusCode() == 401) { // Store the credential back, possibly adding it as a default for this directory. CredentialStorage::set(credential, challenge.protectionSpace(), challenge.failureResponse().url()); } RetainPtr<CFURLCredentialRef> cfCredential = adoptCF(createCF(credential)); CFURLConnectionUseCredential(d->m_connection.get(), cfCredential.get(), challenge.cfURLAuthChallengeRef()); return; } } } d->m_currentWebChallenge = challenge; if (client()) client()->didReceiveAuthenticationChallenge(this, d->m_currentWebChallenge); }
BOOL CParamsDlg::OnInitDialog() { CDialog::OnInitDialog(); SRParamsTable * pPT=core().rParamsTable(); /////PARAMS TABLE ///organize table m_pt.InsertColumn(0,"Звено",LVCFMT_LEFT,45); m_pt.InsertColumn(1,"Кин. пара",LVCFMT_LEFT,63); m_pt.InsertColumn(2,"Th, град",LVCFMT_LEFT,64); m_pt.InsertColumn(3,"S, мм",LVCFMT_LEFT,64); m_pt.InsertColumn(4,"A, мм",LVCFMT_LEFT,64); m_pt.InsertColumn(5,"Al, град",LVCFMT_LEFT,64); ////filling table LVITEM lvi; lvi.mask=LVIF_TEXT; CString s; for (Size i=1;i<pPT->pPLs.size();i++) { ///Num s.Format("%i",i); int ai=m_pt.InsertItem(i,s); lvi.iItem=ai; ///Pair lvi.iSubItem=1; s.Format("(%i, %i)",i-1,i); lvi.pszText=(char*)(LPCSTR)s; m_pt.SetItem(&lvi); ///Th lvi.iSubItem=2; s=pPT->pPLs[i].Th.GetAsStr().c_str(); lvi.pszText=(char*)(LPCSTR)s; m_pt.SetItem(&lvi); ///S lvi.iSubItem=3; s=pPT->pPLs[i].S.GetAsStr().c_str(); lvi.pszText=(char*)(LPCSTR)s; m_pt.SetItem(&lvi); ///A lvi.iSubItem=4; s=pPT->pPLs[i].A.GetAsStr().c_str(); lvi.pszText=(char*)(LPCSTR)s; m_pt.SetItem(&lvi); ///Al lvi.iSubItem=5; s=pPT->pPLs[i].Al.GetAsStr().c_str(); lvi.pszText=(char*)(LPCSTR)s; m_pt.SetItem(&lvi); } /////VALUES TABLE ///organize table m_val.InsertColumn(0,"Параметр",LVCFMT_LEFT,75); m_val.InsertColumn(1,"Минимум",LVCFMT_LEFT,70); m_val.InsertColumn(2,"Максимум",LVCFMT_LEFT,70); m_val.InsertColumn(3,"Исходное",LVCFMT_LEFT,66); ////filling table for (Size i=0;i<pPT->pVs.size();i++) { ///Name s=pPT->pVs[i].var.GetName().c_str(); int ai=m_val.InsertItem(i,s); lvi.iItem=ai; ///Min lvi.iSubItem=1; s.Format("%g",pPT->pVs[i].min); lvi.pszText=(char*)(LPCSTR)s; m_val.SetItem(&lvi); ///Max lvi.iSubItem=2; s.Format("%g",pPT->pVs[i].max); lvi.pszText=(char*)(LPCSTR)s; m_val.SetItem(&lvi); ///Def lvi.iSubItem=3; s.Format("%g",pPT->pVs[i].def); lvi.pszText=(char*)(LPCSTR)s; m_val.SetItem(&lvi); } return TRUE; }
bool GraphiteClient::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) { try { sh::settings_registry settings(get_settings_proxy()); settings.set_alias("graphite", alias, "client"); client_.set_path(settings.alias().get_settings_path("targets")); settings.alias().add_path_to_settings() ("GRAPHITE CLIENT SECTION", "Section for graphite passive check module.") ("handlers", sh::fun_values_path(boost::bind(&GraphiteClient::add_command, this, _1, _2)), "CLIENT HANDLER SECTION", "", "CLIENT HANDLER", "For more configuration options add a dedicated section") ("targets", sh::fun_values_path(boost::bind(&GraphiteClient::add_target, this, _1, _2)), "REMOTE TARGET DEFINITIONS", "", "TARGET", "For more configuration options add a dedicated section") ; settings.alias().add_key_to_settings() ("hostname", sh::string_key(&hostname_, "auto"), "HOSTNAME", "The host name of the monitored computer.\nSet this to auto (default) to use the windows name of the computer.\n\n" "auto\tHostname\n" "${host}\tHostname\n" "${host_lc}\nHostname in lowercase\n" "${host_uc}\tHostname in uppercase\n" "${domain}\tDomainname\n" "${domain_lc}\tDomainname in lowercase\n" "${domain_uc}\tDomainname in uppercase\n" ) ("channel", sh::string_key(&channel_, "GRAPHITE"), "CHANNEL", "The channel to listen to.") ; settings.register_all(); settings.notify(); client_.finalize(get_settings_proxy()); nscapi::core_helper core(get_core(), get_id()); core.register_channel(channel_); if (hostname_ == "auto") { hostname_ = boost::asio::ip::host_name(); } else if (hostname_ == "auto-lc") { hostname_ = boost::asio::ip::host_name(); std::transform(hostname_.begin(), hostname_.end(), hostname_.begin(), ::tolower); } else if (hostname_ == "auto-uc") { hostname_ = boost::asio::ip::host_name(); std::transform(hostname_.begin(), hostname_.end(), hostname_.begin(), ::toupper); } else { strEx::s::token dn = strEx::s::getToken(boost::asio::ip::host_name(), '.'); try { boost::asio::io_service svc; boost::asio::ip::tcp::resolver resolver(svc); boost::asio::ip::tcp::resolver::query query(boost::asio::ip::host_name(), ""); boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query), end; std::string s; while (iter != end) { s += iter->host_name(); s += " - "; s += iter->endpoint().address().to_string(); iter++; } } catch (const std::exception& e) { NSC_LOG_ERROR_EXR("Failed to resolve: ", e); } strEx::replace(hostname_, "${host}", dn.first); strEx::replace(hostname_, "${domain}", dn.second); std::transform(dn.first.begin(), dn.first.end(), dn.first.begin(), ::toupper); std::transform(dn.second.begin(), dn.second.end(), dn.second.begin(), ::toupper); strEx::replace(hostname_, "${host_uc}", dn.first); strEx::replace(hostname_, "${domain_uc}", dn.second); std::transform(dn.first.begin(), dn.first.end(), dn.first.begin(), ::tolower); std::transform(dn.second.begin(), dn.second.end(), dn.second.begin(), ::tolower); strEx::replace(hostname_, "${host_lc}", dn.first); strEx::replace(hostname_, "${domain_lc}", dn.second); } client_.set_sender(hostname_); } catch (nscapi::nscapi_exception &e) { NSC_LOG_ERROR_EXR("NSClient API exception: ", e); return false; } catch (std::exception &e) { NSC_LOG_ERROR_EXR("NSClient API exception: ", e); return false; } catch (...) { NSC_LOG_ERROR_EX("NSClient API exception: "); return false; } return true; }
ScriptObject* ProgressEventClass::createInstance(VTable *ivtable, ScriptObject* prototype) { return new (core()->GetGC(), ivtable->getExtraSize()) ProgressEventObject(ivtable, prototype, 0); //AS3 'new' opt...Add your init code here... }
void GeolocationClient::notifyErrorOccurred(const char* message) { RefPtr<WebCore::GeolocationError> error = WebCore::GeolocationError::create(WebCore::GeolocationError::PositionUnavailable, message); WebCore::GeolocationController::from(core(m_webView))->errorOccurred(error.get()); }
// fetch references to things defined in boot.jl void jl_get_builtin_hooks(void) { jl_nothing = core("nothing"); jl_root_task->tls = jl_nothing; jl_root_task->consumers = jl_nothing; jl_root_task->donenotify = jl_nothing; jl_root_task->exception = jl_nothing; jl_char_type = (jl_datatype_t*)core("Char"); jl_int8_type = (jl_datatype_t*)core("Int8"); jl_uint8_type = (jl_datatype_t*)core("Uint8"); jl_int16_type = (jl_datatype_t*)core("Int16"); jl_uint16_type = (jl_datatype_t*)core("Uint16"); jl_uint32_type = (jl_datatype_t*)core("Uint32"); jl_uint64_type = (jl_datatype_t*)core("Uint64"); jl_float32_type = (jl_datatype_t*)core("Float32"); jl_float64_type = (jl_datatype_t*)core("Float64"); jl_floatingpoint_type = (jl_datatype_t*)core("FloatingPoint"); jl_stackovf_exception = jl_apply((jl_function_t*)core("StackOverflowError"), NULL, 0); jl_diverror_exception = jl_apply((jl_function_t*)core("DivideError"), NULL, 0); jl_domain_exception = jl_apply((jl_function_t*)core("DomainError"), NULL, 0); jl_overflow_exception = jl_apply((jl_function_t*)core("OverflowError"), NULL, 0); jl_inexact_exception = jl_apply((jl_function_t*)core("InexactError"), NULL, 0); jl_undefref_exception = jl_apply((jl_function_t*)core("UndefRefError"),NULL,0); jl_interrupt_exception = jl_apply((jl_function_t*)core("InterruptException"),NULL,0); jl_bounds_exception = jl_apply((jl_function_t*)core("BoundsError"),NULL,0); jl_memory_exception = jl_apply((jl_function_t*)core("MemoryError"),NULL,0); jl_ascii_string_type = (jl_datatype_t*)core("ASCIIString"); jl_utf8_string_type = (jl_datatype_t*)core("UTF8String"); jl_symbolnode_type = (jl_datatype_t*)core("SymbolNode"); jl_getfieldnode_type = (jl_datatype_t*)core("GetfieldNode"); jl_array_uint8_type = jl_apply_type((jl_value_t*)jl_array_type, jl_tuple2(jl_uint8_type, jl_box_long(1))); }
void bfs(GlobalAddress<G> _g, int nbfs, TupleGraph tg) { bool verified = false; double t; auto _frontier = GlobalBag<VertexID>::create(_g->nv); auto _next = GlobalBag<VertexID>::create(_g->nv); call_on_all_cores([=]{ frontier = _frontier; next = _next; g = _g; }); // do BFS from multiple different roots and average their times for (int root_idx = 0; root_idx < nbfs; root_idx++) { // intialize parent to -1 forall(g, [](G::Vertex& v){ v->init(); v->level = -1; }); VertexID root; if (FLAGS_max_degree_source) { forall(g, [](VertexID i, G::Vertex& v){ max_degree << MaxDegree(i, v.nadj); }); root = static_cast<MaxDegree>(max_degree).idx(); } else { root = choose_root(g); } // setup 'root' as the parent of itself delegate::call(g->vs+root, [=](G::Vertex& v){ v->parent = root; v->level = 0; }); // reset frontier queues next->clear(); frontier->clear(); // start with root as only thing in frontier delegate::call((g->vs+root).core(), [=]{ frontier->add(root); }); t = walltime(); bool top_down = true; int64_t prev_nf = -1; int64_t frontier_edges = 0; int64_t remaining_edges = g->nadj; while (!frontier->empty()) { auto nf = frontier->size(); VLOG(1) << "remaining_edges = " << remaining_edges << ", nf = " << nf << ", prev_nf = " << prev_nf << ", frontier_edges: " ; if (top_down && frontier_edges > remaining_edges/FLAGS_beamer_alpha && nf > prev_nf) { VLOG(1) << "switching to bottom-up"; top_down = false; } else if (!top_down && frontier_edges < g->nv/FLAGS_beamer_beta && nf < prev_nf) { VLOG(1) << "switching to top-down"; top_down = true; } edge_count = 0; if (top_down) { // iterate over vertices in this level of the frontier forall(frontier, [](VertexID& i){ // visit all the adjacencies of the vertex // note: this has to be 'async' to prevent deadlock from // running out of available workers forall<async>(adj(g,i), [i](G::Edge& e) { auto j = e.id; // at the core where the vertex is... delegate::call<async>(e.ga, [i,j](G::Vertex& vj){ // note: no synchronization needed because 'call' is // guaranteed to be executed atomically because it // does no blocking operations if (vj->parent == -1) { // claim parenthood vj->parent = i; vj->level = current_depth; next->add(j); edge_count += vj.nadj; } }); }); }); } else { // bottom-up forall<&phaser>(g, [](G::Vertex& v){ if (v->level != -1) return; auto va = make_linear(&v); forall<async,&phaser>(adj(g,v), [=,&v](G::Edge& e){ if (v->level != -1) return; phaser.enroll(); auto eva = e.ga; send_heap_message(eva.core(), [=]{ auto& ev = *eva.pointer(); if (ev->level != -1 && ev->level < current_depth) { auto eid = g->id(ev); send_heap_message(va.core(), [=]{ auto& v = *va.pointer(); if (v->level == -1) { next->add(g->id(v)); v->level = current_depth; v->parent = eid; edge_count += v.nadj; } phaser.complete(); }); } else { phaser.send_completion(va.core()); } }); }); }); } call_on_all_cores([=]{ current_depth++; // switch to next frontier level std::swap(frontier, next); }); next->clear(); frontier_edges = edge_count; remaining_edges -= frontier_edges; prev_nf = nf; } // while (frontier not empty) double this_bfs_time = walltime() - t; LOG(INFO) << "(root=" << root << ", time=" << this_bfs_time << ")"; if (!verified) { // only verify the first one to save time t = walltime(); bfs_nedge = verify(tg, g, root); verify_time = (walltime()-t); LOG(INFO) << verify_time; verified = true; Metrics::reset_all_cores(); // don't count the first one } else { total_time += this_bfs_time; } bfs_mteps += bfs_nedge / this_bfs_time / 1.0e6; } }
// Function called as constructor ... not supported from user code MSIUnknownConsumer* MSIUnknownConsumerClass::create(IUnknown* p, const IID &iid) { VTable* ivtable = this->ivtable(); MSIUnknownConsumer *o = new (core()->GetGC(), ivtable->getExtraSize()) MSIUnknownConsumer(ivtable, prototype, p, iid); return o; }
Atom RegExpObject::replace(Stringp subject, Stringp replacement) { UsesUTF8String utf8Subject(subject); UsesUTF8String utf8Replacement(replacement); int ovector[OVECTOR_SIZE]; int subjectLength = utf8Subject->length(); int lastIndex=0; StringBuffer resultBuffer(core()); const char *src = utf8Subject->c_str(); // get start/end index of all matches int matchCount; while (lastIndex <= subjectLength && (matchCount = pcre_exec((pcre*)m_pcreInst, NULL, src, subjectLength, lastIndex, PCRE_NO_UTF8_CHECK, ovector, OVECTOR_SIZE)) > 0) { int captureCount = matchCount-1; int matchIndex = ovector[0]; int matchLen = ovector[1]-ovector[0]; // copy in stuff leading up to match resultBuffer.write(src+lastIndex, matchIndex-lastIndex); const char *ptr = utf8Replacement->c_str(); while (*ptr) { if (*ptr == '$') { switch (*(ptr+1)) { case '$': resultBuffer << '$'; ptr += 2; break; case '&': resultBuffer.write(src+matchIndex, matchLen); ptr += 2; break; case '`': resultBuffer.write(src, matchIndex); ptr += 2; break; case '\'': resultBuffer << src+ovector[1]; ptr += 2; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { int i; if (*(ptr+2) >= '0' && *(ptr+2) <= '9') { int j = 10*(ptr[1]-'0')+(ptr[2]-'0'); if (j > captureCount) { // Gobbling up two digits would overflow the // capture count, so just use the one digit. i = ptr[1]-'0'; } else { i = j; } } else { i = ptr[1]-'0'; } if (i >= 1 && i <= captureCount) { resultBuffer.write(src+ovector[i*2], ovector[i*2+1]-ovector[i*2]); ptr += (i >= 10) ? 3 : 2; } else { resultBuffer << *ptr++; } } break; default: resultBuffer << *ptr++; break; } } else { resultBuffer << *ptr++; } } int newLastIndex = ovector[0] + (ovector[1] - ovector[0]); // prevents infinite looping in certain cases fixReplaceLastIndex(src, subjectLength, lastIndex, newLastIndex, resultBuffer); lastIndex = newLastIndex; if (!get_global()) { break; } } // copy in stuff after last match if (lastIndex < subjectLength) { resultBuffer.write(src+lastIndex, subjectLength-lastIndex); } return stringFromUTF8(resultBuffer.c_str(), resultBuffer.length()); }
FILE * collect(struct header *hp, int printheaders) { FILE *fbuf; int lc, cc, escape, eofcount, fd, c, t; char linebuf[LINESIZE], tempname[PATHSIZE], *cp, getsub; sigset_t nset; int longline, lastlong, rc; /* So we don't make 2 or more lines out of a long input line. */ collf = NULL; /* * Start catching signals from here, but we're still die on interrupts * until we're in the main loop. */ sigemptyset(&nset); sigaddset(&nset, SIGINT); sigaddset(&nset, SIGHUP); sigprocmask(SIG_BLOCK, &nset, NULL); if ((saveint = signal(SIGINT, SIG_IGN)) != SIG_IGN) signal(SIGINT, collint); if ((savehup = signal(SIGHUP, SIG_IGN)) != SIG_IGN) signal(SIGHUP, collhup); savetstp = signal(SIGTSTP, collstop); savettou = signal(SIGTTOU, collstop); savettin = signal(SIGTTIN, collstop); if (setjmp(collabort) || setjmp(colljmp)) { rm(tempname); goto err; } sigprocmask(SIG_UNBLOCK, &nset, NULL); noreset++; snprintf(tempname, sizeof(tempname), "%s/mail.RsXXXXXXXXXX", tmpdir); if ((fd = mkstemp(tempname)) == -1 || (collf = Fdopen(fd, "w+")) == NULL) { warn("%s", tempname); goto err; } rm(tempname); /* * If we are going to prompt for a subject, * refrain from printing a newline after * the headers (since some people mind). */ t = GTO|GSUBJECT|GCC|GNL; getsub = 0; if (hp->h_subject == NULL && value("interactive") != NULL && (value("ask") != NULL || value("asksub") != NULL)) t &= ~GNL, getsub++; if (printheaders) { puthead(hp, stdout, t); fflush(stdout); } if ((cp = value("escape")) != NULL) escape = *cp; else escape = ESCAPE; eofcount = 0; hadintr = 0; lastlong = 0; longline = 0; if (!setjmp(colljmp)) { if (getsub) grabh(hp, GSUBJECT); } else { /* * Come here for printing the after-signal message. * Duplicate messages won't be printed because * the write is aborted if we get a SIGTTOU. */ cont: if (hadintr) { fflush(stdout); fprintf(stderr, "\n(Interrupt -- one more to kill letter)\n"); } else { printf("(continue)\n"); fflush(stdout); } } for (;;) { colljmp_p = 1; c = readline(stdin, linebuf, LINESIZE); colljmp_p = 0; if (c < 0) { if (value("interactive") != NULL && value("ignoreeof") != NULL && ++eofcount < 25) { printf("Use \".\" to terminate letter\n"); continue; } break; } lastlong = longline; longline = c == LINESIZE - 1; eofcount = 0; hadintr = 0; if (linebuf[0] == '.' && linebuf[1] == '\0' && value("interactive") != NULL && !lastlong && (value("dot") != NULL || value("ignoreeof") != NULL)) break; if (linebuf[0] != escape || value("interactive") == NULL || lastlong) { if (putline(collf, linebuf, !longline) < 0) goto err; continue; } c = linebuf[1]; switch (c) { default: /* * On double escape, just send the single one. * Otherwise, it's an error. */ if (c == escape) { if (putline(collf, &linebuf[1], !longline) < 0) goto err; else break; } printf("Unknown tilde escape.\n"); break; case 'C': /* * Dump core. */ core(); break; case '!': /* * Shell escape, send the balance of the * line to sh -c. */ shell(&linebuf[2]); break; case ':': case '_': /* * Escape to command mode, but be nice! */ execute(&linebuf[2], 1); goto cont; case '.': /* * Simulate end of file on input. */ goto out; case 'q': /* * Force a quit of sending mail. * Act like an interrupt happened. */ hadintr++; collint(SIGINT); exit(1); case 'x': /* * Exit, do not save in dead.letter. */ goto err; case 'h': /* * Grab a bunch of headers. */ grabh(hp, GTO|GSUBJECT|GCC|GBCC); goto cont; case 't': /* * Add to the To list. */ hp->h_to = cat(hp->h_to, extract(&linebuf[2], GTO)); break; case 's': /* * Set the Subject line. */ cp = &linebuf[2]; while (isspace((unsigned char)*cp)) cp++; hp->h_subject = savestr(cp); break; case 'R': /* * Set the Reply-To line. */ cp = &linebuf[2]; while (isspace((unsigned char)*cp)) cp++; hp->h_replyto = savestr(cp); break; case 'c': /* * Add to the CC list. */ hp->h_cc = cat(hp->h_cc, extract(&linebuf[2], GCC)); break; case 'b': /* * Add to the BCC list. */ hp->h_bcc = cat(hp->h_bcc, extract(&linebuf[2], GBCC)); break; case 'i': case 'A': case 'a': /* * Insert named variable in message. */ switch(c) { case 'i': cp = &linebuf[2]; while(isspace((unsigned char)*cp)) cp++; break; case 'a': cp = "sign"; break; case 'A': cp = "Sign"; break; default: goto err; } if(*cp != '\0' && (cp = value(cp)) != NULL) { printf("%s\n", cp); if(putline(collf, cp, 1) < 0) goto err; } break; case 'd': /* * Read in the dead letter file. */ if (strlcpy(linebuf + 2, getdeadletter(), sizeof(linebuf) - 2) >= sizeof(linebuf) - 2) { printf("Line buffer overflow\n"); break; } /* FALLTHROUGH */ case 'r': case '<': /* * Invoke a file: * Search for the file name, * then open it and copy the contents to collf. */ cp = &linebuf[2]; while (isspace((unsigned char)*cp)) cp++; if (*cp == '\0') { printf("Interpolate what file?\n"); break; } cp = expand(cp); if (cp == NULL) break; if (*cp == '!') { /* * Insert stdout of command. */ char *sh; int nullfd, tempfd, rc; char tempname2[PATHSIZE]; if ((nullfd = open("/dev/null", O_RDONLY, 0)) == -1) { warn("/dev/null"); break; } snprintf(tempname2, sizeof(tempname2), "%s/mail.ReXXXXXXXXXX", tmpdir); if ((tempfd = mkstemp(tempname2)) == -1 || (fbuf = Fdopen(tempfd, "w+")) == NULL) { warn("%s", tempname2); break; } unlink(tempname2); if ((sh = value("SHELL")) == NULL) sh = _PATH_CSHELL; rc = run_command(sh, 0, nullfd, fileno(fbuf), "-c", cp+1, NULL); close(nullfd); if (rc < 0) { Fclose(fbuf); break; } if (fsize(fbuf) == 0) { fprintf(stderr, "No bytes from command \"%s\"\n", cp+1); Fclose(fbuf); break; } rewind(fbuf); } else if (isdir(cp)) { printf("%s: Directory\n", cp); break; } else if ((fbuf = Fopen(cp, "r")) == NULL) { warn("%s", cp); break; } printf("\"%s\" ", cp); fflush(stdout); lc = 0; cc = 0; while ((rc = readline(fbuf, linebuf, LINESIZE)) >= 0) { if (rc != LINESIZE - 1) lc++; if ((t = putline(collf, linebuf, rc != LINESIZE - 1)) < 0) { Fclose(fbuf); goto err; } cc += t; } Fclose(fbuf); printf("%d/%d\n", lc, cc); break; case 'w': /* * Write the message on a file. */ cp = &linebuf[2]; while (*cp == ' ' || *cp == '\t') cp++; if (*cp == '\0') { fprintf(stderr, "Write what file!?\n"); break; } if ((cp = expand(cp)) == NULL) break; rewind(collf); exwrite(cp, collf, 1); break; case 'm': case 'M': case 'f': case 'F': /* * Interpolate the named messages, if we * are in receiving mail mode. Does the * standard list processing garbage. * If ~f is given, we don't shift over. */ if (forward(linebuf + 2, collf, tempname, c) < 0) goto err; goto cont; case '?': if ((fbuf = Fopen(_PATH_TILDE, "r")) == NULL) { warn("%s", _PATH_TILDE); break; } while ((t = getc(fbuf)) != EOF) putchar(t); Fclose(fbuf); break; case 'p': /* * Print out the current state of the * message without altering anything. */ rewind(collf); printf("-------\nMessage contains:\n"); puthead(hp, stdout, GTO|GSUBJECT|GCC|GBCC|GNL); while ((t = getc(collf)) != EOF) putchar(t); goto cont; case '|': /* * Pipe message through command. * Collect output as new message. */ rewind(collf); mespipe(collf, &linebuf[2]); goto cont; case 'v': case 'e': /* * Edit the current message. * 'e' means to use EDITOR * 'v' means to use VISUAL */ rewind(collf); mesedit(collf, c); goto cont; } } goto out; err: if (collf != NULL) { Fclose(collf); collf = NULL; } out: if (collf != NULL) rewind(collf); noreset--; sigprocmask(SIG_BLOCK, &nset, NULL); signal(SIGINT, saveint); signal(SIGHUP, savehup); signal(SIGTSTP, savetstp); signal(SIGTTOU, savettou); signal(SIGTTIN, savettin); sigprocmask(SIG_UNBLOCK, &nset, NULL); return (collf); }
Atom RegExpObject::replace(Stringp subject, ScriptObject* replaceFunction) { UsesUTF8String utf8Subject(subject); int ovector[OVECTOR_SIZE]; int subjectLength = utf8Subject->length(); int lastIndex=0; StringBuffer resultBuffer(core()); const char *src = utf8Subject->c_str(); // get start/end index of all matches int matchCount; while (lastIndex < subjectLength && (matchCount = pcre_exec((pcre*)m_pcreInst, NULL, src, subjectLength, lastIndex, PCRE_NO_UTF8_CHECK, ovector, OVECTOR_SIZE)) > 0) { int captureCount = matchCount-1; int matchIndex = ovector[0]; int matchLen = ovector[1]-ovector[0]; // copy in stuff leading up to match resultBuffer.write(src+lastIndex, matchIndex-lastIndex); // call the replace function Atom argv[NUM_MATCHES+4]; int argc = captureCount+3; argv[0] = undefinedAtom; // ECMA 15.5.4.11: Argument 1 is the substring that matched. argv[1] = core()->newString(src+matchIndex, matchLen)->atom(); // ECMA 15.5.4.11: The next m arguments are all of the captures in the // MatchResult for (int i=1; i<=captureCount; i++) { argv[i+1] = core()->newString(src+ovector[i*2], ovector[i*2+1]-ovector[i*2])->atom(); } // ECMA 15.5.4.11: Argument m+2 is the offset within string // where the match occurred argv[captureCount+2] = core()->uintToAtom(matchIndex); // ECMA 15.5.4.11: Argument m+3 is string argv[captureCount+3] = subject->atom(); resultBuffer << core()->string(toplevel()->op_call(replaceFunction->atom(), argc, argv)); int newLastIndex = ovector[0] + (ovector[1] - ovector[0]); // prevents infinite looping in certain cases fixReplaceLastIndex(src, subjectLength, lastIndex, newLastIndex, resultBuffer); lastIndex = newLastIndex; if (!get_global()) break; } // copy in stuff after last match if (lastIndex < subjectLength) { resultBuffer.write(src+lastIndex, subjectLength-lastIndex); } return stringFromUTF8(resultBuffer.c_str(), resultBuffer.length()); }
void LayoutAlignmentCommand::redo() { LayoutAlignmentCommand::applyAlignment(core(), m_widget, m_newAlignment); }
void FrameLoaderClient::forceLayout() { FrameView* view = core(m_frame)->view(); if (view) view->forceLayout(true); }
ScriptObject* SystemTrayIconClass::createInstance(VTable *ivtable, ScriptObject* prototype) { return new (core()->GetGC(), ivtable->getExtraSize()) SystemTrayIconObject(ivtable, prototype, 0); //AS3 'new' opt...Add your init code here... }
int main(void) { CURLM *cm; CURLMsg *msg; long L; unsigned int C = 0; int M, Q, U = -1; fd_set R, W, E; struct timeval T; CURL_data *resp=NULL; core(); curl_global_init(CURL_GLOBAL_ALL); resp = (CURL_data *)malloc(sizeof(CURL_data)); memset(resp,0,sizeof(CURL_data)); curl_global_init(CURL_GLOBAL_ALL); cm = curl_multi_init(); /* we can optionally limit the total amount of connections this multi handle uses */ curl_multi_setopt(cm, CURLMOPT_MAXCONNECTS, (long)MAX); for(C = 0; C < MAX; ++C) { init(cm, C,resp); } while(U) { curl_multi_perform(cm, &U); if(U) { FD_ZERO(&R); FD_ZERO(&W); FD_ZERO(&E); if(curl_multi_fdset(cm, &R, &W, &E, &M)) { fprintf(stderr, "E: curl_multi_fdset\n"); return EXIT_FAILURE; } if(curl_multi_timeout(cm, &L)) { fprintf(stderr, "E: curl_multi_timeout\n"); return EXIT_FAILURE; } if(L == -1) L = 100; if(M == -1) { #ifdef WIN32 Sleep(L); #else sleep((unsigned int)L / 1000); #endif } else { T.tv_sec = L/1000; T.tv_usec = (L%1000)*1000; if(0 > select(M + 1, &R, &W, &E, &T)) { fprintf(stderr, "E: select(%i,,,,%li): %i: %s\n", M + 1, L, errno, strerror(errno)); return EXIT_FAILURE; }else{ fprintf(stderr,"Start!!! [%d]\n",U); } } } while((msg = curl_multi_info_read(cm, &Q))) { if(msg->msg == CURLMSG_DONE) { char *url; CURL *e = msg->easy_handle; curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &url); fprintf(stderr, "R: %d - %s <%s>\n", msg->data.result, curl_easy_strerror(msg->data.result), url); //fprintf(stderr,"%s\n",resp->body.memory); curl_multi_remove_handle(cm, e); curl_easy_cleanup(e); } else { fprintf(stderr, "E: CURLMsg (%d)\n", msg->msg); } #if 0 if(C < CNT) { init(cm, C++,resp); U++; /* just to prevent it from remaining at 0 if there are more URLs to get */ } #endif } } curl_multi_cleanup(cm); curl_global_cleanup(); return EXIT_SUCCESS; }