repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
sergiusens/snapcraft
setup.py
5212
#!/usr/bin/env python3 # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2015-2018 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import codecs import os import re import sys # Common distribution data name = "snapcraft" version = "devel" description = "Easily craft snaps from multiple sources" author_email = "snapcraft@lists.snapcraft.io" url = "https://github.com/snapcore/snapcraft" packages = [ "snapcraft", "snapcraft.cli", "snapcraft.cli.snapcraftctl", "snapcraft.extractors", "snapcraft.integrations", "snapcraft.internal", "snapcraft.internal.cache", "snapcraft.internal.build_providers", "snapcraft.internal.build_providers._multipass", "snapcraft.internal.deltas", "snapcraft.internal.lifecycle", "snapcraft.internal.lxd", "snapcraft.internal.meta", "snapcraft.internal.pluginhandler", "snapcraft.internal.project_loader", "snapcraft.internal.project_loader.grammar", "snapcraft.internal.project_loader.grammar_processing", "snapcraft.internal.project_loader.inspection", "snapcraft.internal.project_loader._extensions", "snapcraft.internal.repo", "snapcraft.internal.sources", "snapcraft.internal.states", "snapcraft.project", "snapcraft.plugins", "snapcraft.plugins._ros", "snapcraft.plugins._python", "snapcraft.storeapi", ] package_data = {"snapcraft.internal.repo": ["manifest.txt"]} license = "GPL v3" classifiers = ( "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Natural Language :: English", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Topic :: Software Development :: Build Tools", "Topic :: System :: Software Distribution", ) # look/set what version we have changelog = "debian/changelog" if os.path.exists(changelog): head = codecs.open(changelog, encoding="utf-8").readline() match = re.compile(".*\((.*)\).*").match(head) if match: version = match.group(1) # If on Windows, construct an exe distribution if sys.platform == "win32": from cx_Freeze import setup, Executable # cx_Freeze relevant options build_exe_options = { # Explicitly add any missed packages that are not found at runtime "packages": [ "pkg_resources", "pymacaroons", "click", "responses", "configparser", "docopt", "cffi", ], # Explicit inclusion data, which is then clobbered. "include_files": [ ("libraries", os.path.join("share", "snapcraft", "libraries")), ("schema", os.path.join("share", "snapcraft", "schema")), ("extensions", os.path.join("share", "snapcraft", "extensions")), ], } exe = Executable(script="bin/snapcraft", base=None) # console subsystem setup( name=name, version=version, description=description, author_email=author_email, url=url, packages=packages, package_data=package_data, license=license, classifiers=classifiers, # cx_Freeze-specific arguments options={"build_exe": build_exe_options}, executables=[exe], ) # On other platforms, continue as normal else: from setuptools import setup setup( name=name, version=version, description=description, author_email=author_email, url=url, packages=packages, package_data=package_data, license=license, classifiers=classifiers, # non-cx_Freeze arguments entry_points={ "console_scripts": [ "snapcraft = snapcraft.cli.__main__:run", "snapcraft-parser = snapcraft.internal.parser:main", ] }, # This is not in console_scripts because we need a clean environment scripts=["bin/snapcraftctl"], data_files=[ ("share/snapcraft/schema", ["schema/" + x for x in os.listdir("schema")]), ( "share/snapcraft/libraries", ["libraries/" + x for x in os.listdir("libraries")], ), ( "share/snapcraft/extensions", ["extensions/" + x for x in os.listdir("extensions")], ), ], install_requires=["pysha3", "pyxdg", "requests"], test_suite="tests.unit", )
gpl-3.0
AndreasAnemyrLNU/phploggerlib
view/html/HTMLPage.php
2471
<?php /** * Created by PhpStorm. * User: AndreasAnemyr * Date: 2015-11-03 * Time: 22:47 */ namespace view; class HTMLPage { private $nav; /** * HTMLPage constructor. */ public function __construct(\view\Navigation $nav) { $this->nav = $nav; } public function getHTMLPage($main) { return "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"/> <title>phpLoggerLig assignment4 Re-exam</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\"> </head> <body> <div class=\"col-xs-10 col-sm-10 col-md-10 col-lg-10 col-xs-push-1 col-sm-push-1 col-md-push-1 col-lg-push-1\"> <nav class=\"navbar navbar-default\"> <div class=\"container-fluid\"> <!-- Brand and toggle get grouped for better mobile display --> <div class=\"navbar-header\"> <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\"> <span class=\"sr-only\">Toggle navigation</span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> </button> <a class=\"navbar-brand\" href=\"?#\"><h5 class=\"h5\">phpLoggerLib</h5></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\"> <ul class=\"nav navbar-nav\"> <li>{$this->nav->RenderGenericDoButtonWithAction('Interface', 'logmanager', 'interface', 'primary')}</li> <li>{$this->nav->RenderGenericDoButtonWithAction('IP List', 'logmanager', 'iplist', 'primary')}</li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <main class=\"container-fluid well\"> $main </main> </div> </body> </html> "; } }
gpl-3.0
brgl/EmbeddedLinuxSuite
include/els/System.hpp
1356
/* * Copyright (C) 2013 Bartosz Golaszewski * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file System.hpp * @brief C++ wrappers for various system calls and libc library calls. * * These throw LibcError exceptions in case of errors. */ #pragma once #include "Macros.hpp" #include "Types.hpp" #include <string> ELS_BEGIN_NAMESPACE_2(els, sys) ELS_EXPORT_SYMBOL pid_t getPid(void) throw(); ELS_EXPORT_SYMBOL pid_t getTid(void) throw(); ELS_EXPORT_SYMBOL char** getEnvp(void) throw(); ELS_EXPORT_SYMBOL void makeDir(const std::string& path, ElsMode mode); ELS_EXPORT_SYMBOL void* libcMalloc(ElsSize size); ELS_EXPORT_SYMBOL void libcFree(void* ptr); ELS_END_NAMESPACE_2
gpl-3.0
tutao/tutanota
app-android/app/src/main/java/de/tutao/tutanota/credentials/CredentialsEncryptionBeforeAPI30.java
5435
package de.tutao.tutanota.credentials; import android.security.keystore.KeyPermanentlyInvalidatedException; import android.security.keystore.UserNotAuthenticatedException; import android.util.Log; import androidx.annotation.RequiresApi; import androidx.biometric.BiometricManager; import androidx.biometric.BiometricPrompt; import androidx.fragment.app.FragmentActivity; import java.security.KeyStoreException; import java.util.ArrayList; import java.util.List; import javax.crypto.Cipher; import de.tutao.tutanota.AndroidKeyStoreFacade; import de.tutao.tutanota.CredentialAuthenticationException; import de.tutao.tutanota.CryptoError; import de.tutao.tutanota.R; import de.tutao.tutanota.Utils; @RequiresApi(23) public final class CredentialsEncryptionBeforeAPI30 implements ICredentialsEncryption { private final AndroidKeyStoreFacade keyStoreFacade; private final FragmentActivity activity; private final AuthenticationPrompt authenticationPrompt; public CredentialsEncryptionBeforeAPI30(AndroidKeyStoreFacade keyStoreFacade, FragmentActivity activity, AuthenticationPrompt authenticationPrompt) { this.keyStoreFacade = keyStoreFacade; this.activity = activity; this.authenticationPrompt = authenticationPrompt; } @Override public String encryptUsingKeychain(String base64EncodedData, CredentialEncryptionMode encryptionMode) throws KeyStoreException, CryptoError, CredentialAuthenticationException, KeyPermanentlyInvalidatedException { byte[] dataToEncrypt = Utils.base64ToBytes(base64EncodedData); Cipher cipher; try { cipher = keyStoreFacade.getCipherForEncryptionMode(encryptionMode); if (encryptionMode == CredentialEncryptionMode.ENCRYPTION_MODE_BIOMETRICS) { BiometricPrompt.CryptoObject cryptoObject = new BiometricPrompt.CryptoObject(cipher); this.authenticationPrompt.authenticateCryptoObject(activity, createPromptInfo(encryptionMode), cryptoObject); } } catch (KeyStoreException e) { if (e.getCause() instanceof UserNotAuthenticatedException) { this.authenticationPrompt.authenticate(activity, createPromptInfo(encryptionMode)); cipher = keyStoreFacade.getCipherForEncryptionMode(encryptionMode); } else { throw e; } } byte[] encryptedBytes = keyStoreFacade.encryptData(dataToEncrypt, cipher); return Utils.bytesToBase64(encryptedBytes); } @Override public String decryptUsingKeychain(String base64EncodedEncryptedData, CredentialEncryptionMode encryptionMode) throws KeyStoreException, CryptoError, CredentialAuthenticationException, KeyPermanentlyInvalidatedException { byte[] dataToDecrypt = Utils.base64ToBytes(base64EncodedEncryptedData); Cipher cipher; try { cipher = keyStoreFacade.getCipherForDecryptionMode(encryptionMode, dataToDecrypt); if (encryptionMode == CredentialEncryptionMode.ENCRYPTION_MODE_BIOMETRICS) { BiometricPrompt.CryptoObject cryptoObject = new BiometricPrompt.CryptoObject(cipher); this.authenticationPrompt.authenticateCryptoObject(activity, createPromptInfo(encryptionMode), cryptoObject); } } catch (KeyStoreException e) { if (e.getCause() instanceof UserNotAuthenticatedException) { this.authenticationPrompt.authenticate(activity, createPromptInfo(encryptionMode)); cipher = keyStoreFacade.getCipherForDecryptionMode(encryptionMode, dataToDecrypt); } else { throw e; } } byte[] decryptedBytes = keyStoreFacade.decryptData(dataToDecrypt, cipher); return Utils.bytesToBase64(decryptedBytes); } @Override public List<CredentialEncryptionMode> getSupportedEncryptionModes() { List<CredentialEncryptionMode> supportedModes = new ArrayList<>(); supportedModes.add(CredentialEncryptionMode.ENCRYPTION_MODE_DEVICE_LOCK); BiometricManager biometricManager = BiometricManager.from(activity); if (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS) { supportedModes.add(CredentialEncryptionMode.ENCRYPTION_MODE_BIOMETRICS); } if (biometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL | BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS) { supportedModes.add(CredentialEncryptionMode.ENCRYPTION_MODE_SYSTEM_PASSWORD); } return supportedModes; } private BiometricPrompt.PromptInfo createPromptInfo(CredentialEncryptionMode mode) { if (mode == CredentialEncryptionMode.ENCRYPTION_MODE_BIOMETRICS) { BiometricPrompt.PromptInfo.Builder promptInfoBuilder = new BiometricPrompt.PromptInfo.Builder() .setTitle(activity.getString(R.string.unlockCredentials_action)) // see AuthentorUtils#isSupportedCombination from androidx.biometrics .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG) .setNegativeButtonText(activity.getString(android.R.string.cancel)); return promptInfoBuilder.build(); } else if (mode == CredentialEncryptionMode.ENCRYPTION_MODE_SYSTEM_PASSWORD) { BiometricPrompt.PromptInfo.Builder promptInfoBuilder = new BiometricPrompt.PromptInfo.Builder() .setTitle(activity.getString(R.string.unlockCredentials_action)) // see AuthentorUtils#isSupportedCombination from androidx.biometrics .setAllowedAuthenticators(BiometricManager.Authenticators.DEVICE_CREDENTIAL | BiometricManager.Authenticators.BIOMETRIC_WEAK); return promptInfoBuilder.build(); } else { throw new AssertionError(""); } } }
gpl-3.0
andreabrambilla/libres
lib/include/ert/job_queue/workflow_joblist.hpp
1870
/* Copyright (C) 2012 Equinor ASA, Norway. The file 'workflow_joblist.h' is part of ERT - Ensemble based Reservoir Tool. ERT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ERT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html> for more details. */ #ifndef ERT_WORKFLOW_JOBLIST_H #define ERT_WORKFLOW_JOBLIST_H #ifdef __cplusplus extern "C" { #endif #include <ert/job_queue/workflow_job.hpp> typedef struct workflow_joblist_struct workflow_joblist_type; workflow_joblist_type * workflow_joblist_alloc(); void workflow_joblist_free( workflow_joblist_type * joblist); const workflow_job_type * workflow_joblist_get_job( const workflow_joblist_type * joblist , const char * job_name); void workflow_joblist_add_job( workflow_joblist_type * joblist , const workflow_job_type * job); bool workflow_joblist_add_job_from_file( workflow_joblist_type * joblist , const char * job_name , const char * config_file ); config_parser_type * workflow_joblist_get_compiler( const workflow_joblist_type * joblist ); config_parser_type * workflow_joblist_get_job_config( const workflow_joblist_type * joblist ); bool workflow_joblist_has_job( const workflow_joblist_type * joblist , const char * job_name); stringlist_type * workflow_joblist_get_job_names(const workflow_joblist_type * joblist); #ifdef __cplusplus } #endif #endif
gpl-3.0
bcgov/sbc-qsystem
QSystem/src/ru/apertum/qsystem/common/QConfig.java
22371
/* * Copyright (C) 2016 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ru.apertum.qsystem.common; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.configuration2.FileBasedConfiguration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.FileBasedBuilderParametersImpl; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.ex.ConfigurationException; import ru.apertum.qsystem.common.exceptions.ServerException; /** * Manager of configure. It Holds all mechanisms for using properties and providing it for other * consumers. * * @author evgeniy.egorov */ public final class QConfig { // ключ, отвечающий за возможность работы регистрации в кнопочном исполнении. // ключ, отвечающий за возможность работы регистрации при наличии только некой клавиатуры. Список услуг в виде картинки с указанием что нажать на клаве для той или иной услуги //touch,info,med,btn,kbd public static final String KEY_WELCOME_MODE = "welcome-mode"; public static final String KEY_WELCOME_TOUCH = "touch"; public static final String KEY_WELCOME_INFO = "info"; public static final String KEY_WELCOME_MED = "med"; public static final String KEY_WELCOME_BTN = "btn"; public static final String KEY_WELCOME_KBD = "kbd"; private static final String KEY_DEBUG = "debug"; // ключ, отвечающий за режим демонстрации. При нем не надо прятать мышку и убирать шапку формы // Режим демонстрации. При нем не надо прятать мышку и убирать шапку формы. private static final String KEY_DEMO = "demo"; private static final String KEY_IDE = "ide"; private static final String KEY_START = "ubtn-start"; // ключ, отвечающий за возможность загрузки плагинов. private static final String KEY_NOPLUGINS = "noplugins"; // ключ, отвечающий за паузу на старте. private static final String KEY_DELAY = "delay"; // ключ, отвечающий за возможность работы клиента на терминальном сервере. private static final String KEY_TERMINAL = "terminal"; //Всегда грузим temp.json и никогда не чистим состояние. private static final String KEY_RETAIN = "retain"; private static final String KEY_CLANGS = "change-langs"; // ключ, отвечающий за паузу при вызове только что вставшего с очередь. Чтоб в зал успел вбежать. private static final String KEY_DELAY_INVITE_FIRST = "delay-first-invite"; private static final String KEY_HTTP = "http-server"; private static final String KEY_HTTP_PROTOCOL_POST = "http-protocol-post"; private static final String KEY_HTTP_PROTOCOL_GET = "http-protocol-get"; private static final String KEY_POINT = "point"; private static final String KEY_BOARD_CFG = "board-config"; private static final String KEY_BOARD_FX_CFG = "board-fx-config"; private static final String KEY_S = "server-address"; private static final String KEY_WEB_SERVICE_URL = "web-service-url"; private static final String KEY_S_PORT = "server-port"; private static final String KEY_C_PORT = "client-port"; private static final String KEY_USER = "user"; private static final String KEY_LOG_INFO = "loginfo"; private static final String KEY_USE_EXT_PRIORITY = "use-ext-prority"; private static final String KEY_NUM_DIVIDER = "number-divider"; private static final String ZKEY_BOARD_CFG = "zboard-config"; private static final String TKEY_BOARD_CFG = "tboard-config"; private static final String KEY_NO_HIDE_CURSOR = "no-hide-cursor"; /** * type 0-сервер,1-клиент,2-приемная,3-админка,4-киоск,5-сервер хардварных кнопок */ private static int type = -1; private final FileBasedConfiguration config; private final Options options = new Options(); private final CommandLineParser parser = new DefaultParser(); private final InetAddress tcpServerAddress; private CommandLine line; private QConfig() { try { if (new File(Uses.PROPERTIES_FILE).exists()) { final FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>( PropertiesConfiguration.class) .configure( new FileBasedBuilderParametersImpl().setFileName(Uses.PROPERTIES_FILE) .setEncoding("utf8")); builder.setAutoSave(true); config = builder.getConfiguration(); // config contains all properties read from the file } else { this.config = new PropertiesConfiguration(); } } catch (ConfigurationException ex) { throw new RuntimeException("Properties file wasn't read.", ex); } options.addOption("?", "hey", false, "Show information about command line arguments"); options.addOption("h", "help", false, "Show information about command line arguments"); options.addOption("wsu", KEY_WEB_SERVICE_URL, false, "Full URL to Web Service for HTTP RPC calls - eg HTTP://test.com"); /* CLIENT: ide -s 127.0.0.1 -cport 3129 -sport 3128 -cfg config/clientboard.xml -cfgfx1 config/clientboardfx.properties -point1 234 debug -terminal1 RECEPTION: ide -s 127.0.0.1 -cport 3129 -sport 3128 debug WELCOME: ide -s 127.0.0.1 -sport 3128 -cport 3129 debug med info1 -buttons1 demo1 -clangs1 -keyboard1 Option o = new Option("log", "loglavel", true, "Level for logger log4j. It have higher priority than properties file."); o.setArgName("ebat'"); options.addOption(o); */ // 0-сервер,1-клиент,2-приемная,3-админка,4-киоск,5-сервер хардварных кнопок, 26 - зональник, 17 - редактор табло //type = -1; options.addOption("ndiv", KEY_NUM_DIVIDER, true, "Divider for client ticket number between prefix and number. For ex: A-800. Default is empty."); options.addOption("d", KEY_DEBUG, false, "Debug mode. Show all messages in console and do not make forms fulscreen."); options.addOption("li", KEY_LOG_INFO, false, "Logging mode. Info level only."); if (type == -1 || type == 0 || type == 1 || type == 4 || type == 26) { options.addOption(KEY_DEMO, false, "Demo mode. You can use mouse and you can see header of forms."); options.addOption("nhc", KEY_NO_HIDE_CURSOR, false, "No-hide-cursor mode. In some linux GUI could be problen with hide cursor."); } options.addOption(KEY_IDE, false, "Do not touch it!"); if (type == -1 || type == 5) { options.addOption("ubs", KEY_START, false, "Auto start for hardware user buttons."); } options.addOption("np", KEY_NOPLUGINS, false, "Do not load plugins."); Option o = new Option("p", KEY_DELAY, true, "Do delay before starting. It can be useful for waiting for prepared other components of QSystem."); o.setArgName("in seconds"); options.addOption(o); if (type == -1 || type == 0 || type == 1) { options.addOption("t", KEY_TERMINAL, false, "If QSystem working in terminal environment. Not on dedicated computers."); } if (type == -1 || type == 4) { o = new Option("wm", KEY_WELCOME_MODE, true, "If welcome app is not a touch kiosk.\ninfo - just show and print an information.\nmed - Input some number and stand for advance.\nbtn - if it is special hardware buttons device.\nkbd- Ability to work for registration point if there is only a keyboard ar mouse. A list of services in the form of a picture which indicate that to press on keyboard or mouse for a particular service."); o.setArgName("touch,info,med,btn,kbd"); options.addOption(o); options.addOption("cl", KEY_CLANGS, false, "Manage multi language mode before start welcome point."); } if (type == -1 || type == 0) { options.addOption("r", KEY_RETAIN, false, "Always to keep the state after restart the server QSystem."); o = new Option("dfi", KEY_DELAY_INVITE_FIRST, true, "Pause before calling a client by user after getting line. To have time to run into the room."); o.setArgName("in seconds"); options.addOption(o); o = new Option("http", KEY_HTTP, true, "To start built-in http server which support servlets and web-socket. Specify a port."); o.setArgName("port"); options.addOption(o); } if (type == -1 || type == 1) { o = new Option("pt", KEY_POINT, true, "Alternative label for user's workplace.."); o.setOptionalArg(true); o.setArgName("label"); options.addOption(o); o = new Option("cfg", KEY_BOARD_CFG, true, "Config xml file for main board."); o.setArgName("xml-file"); options.addOption(o); o = new Option("cfgfx", KEY_BOARD_FX_CFG, true, "Config properties file for main board as FX form."); o.setArgName("file"); options.addOption(o); o = new Option("u", KEY_USER, true, "User ID for fast login into client app. From DB."); o.setArgName("user ID"); options.addOption(o); } if (type == -1 || type == 1 || type == 2 || type == 4) { //-s 127.0.0.1 -sport 3128 -cport 3129 o = new Option("s", KEY_S, true, "Address of QMS QSystem server."); o.setArgName("label"); options.addOption(o); o = new Option("sport", KEY_S_PORT, true, "TCP port of QMS QSystem server."); o.setArgName("port"); options.addOption(o); o = new Option("cport", KEY_C_PORT, true, "UDP port of user's computer for receiving message from server."); o.setArgName("port"); options.addOption(o); } if (type == -1 || type == 1 || type == 2 || type == 3 || type == 4 || type == 5) { o = new Option("httpp", KEY_HTTP_PROTOCOL_POST, true, "Use HTTP as protocol for transpotring POST commands from clients to server."); o.setArgName("port"); options.addOption(o); o = new Option("httpg", KEY_HTTP_PROTOCOL_GET, true, "Use HTTP as protocol for transpotring GET commands from clients to server."); o.setArgName("port"); options.addOption(o); } if (type == -1 || type == 3) { options.addOption("uep", KEY_USE_EXT_PRIORITY, false, "Bad. Forget about it. This is amount of additional priorities for services."); } if (type == -1 || type == 26) { o = new Option("zcfg", ZKEY_BOARD_CFG, true, "Config xml file for zone board."); o.setArgName("xml-file"); options.addOption(o); } if (type == -1 || type == 17) { o = new Option("tcfg", TKEY_BOARD_CFG, true, "Config xml file for board."); o.setArgName("xml-file"); options.addOption(o); } try { // create the parser line = parser.parse(options, new String[0]); } catch (ParseException ex) { } try { tcpServerAddress = InetAddress.getByName(getServerAddress()); } catch (UnknownHostException exception) { throw new ServerException("Address TCP server is not correct.", exception); } } public static QConfig cfg() { return ConfigHolder.INSTANCE; } // CM: Temporary, to try and get config info. public FileBasedConfiguration getQsysProperties() { return config; } /** * @param tp 0-сервер,1-клиент,2-приемная,3-админка,4-киоск,5-сервер хардварных кнопок */ public static QConfig cfg(int tp) { type = tp; return ConfigHolder.INSTANCE; } public boolean isServer() { return type == 0; } public boolean isClient() { return type == 1; } public boolean isReception() { return type == 2; } public boolean isAdminApp() { return type == 3; } public boolean isWelcome() { return type == 4; } public boolean isUB() { return type == 5; } public int getStoppingPort() { return line.hasOption("stoppingport") ? Integer.parseInt(line.getOptionValue("stoppingport", "27001")) : 27001; } /** * @param args cmd params */ public QConfig prepareCLI(String[] args) { try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong throw new RuntimeException("Parsing failed. Reason: ", exp); } new HelpFormatter().printHelp("command line parameters for QMS QSystem...", options); // automatically generate the help statement if (line.hasOption("help") || line.hasOption("h") || line.hasOption("?")) { System.exit(0); } QLog.l().logger().info("Properties are ready."); return this; } public boolean isDebug() { return line.hasOption(KEY_DEBUG) ? true : config.getBoolean(KEY_DEBUG, false); } public boolean isLogInfo() { return line.hasOption(KEY_LOG_INFO) ? true : config.getBoolean(KEY_LOG_INFO, false); } public boolean isDemo() { return line.hasOption(KEY_DEMO) ? true : config.getBoolean(KEY_DEMO, false); } public boolean isHideCursor() { return line.hasOption(KEY_NO_HIDE_CURSOR) ? false : !config.getBoolean(KEY_NO_HIDE_CURSOR, false); } public boolean isIDE() { return line.hasOption(KEY_IDE) ? true : config.getBoolean(KEY_IDE, false); } public boolean isUbtnStart() { return line.hasOption(KEY_START) ? true : config.getBoolean(KEY_START, false); } public boolean isNoPlugins() { return line.hasOption(KEY_NOPLUGINS) ? true : config.getBoolean(KEY_NOPLUGINS, false); } public boolean isPlaginable() { return !isNoPlugins(); } public int getDelay() { try { return line.hasOption(KEY_DELAY) ? Integer.parseInt(line.getOptionValue(KEY_DELAY, "0")) : config.getInt(KEY_DELAY, 0); } catch (Exception ex) { System.err.println(ex); return 15; } } public boolean isTerminal() { return line.hasOption(KEY_TERMINAL) ? true : config.getBoolean(KEY_TERMINAL, false); } /** * touch,info,med,btn,kbd * * @return mode */ public String getWelcomeMode() { return line.hasOption(KEY_WELCOME_MODE) ? line.getOptionValue(KEY_WELCOME_MODE, "touch") : config.getString(KEY_WELCOME_MODE, "touch"); } /** * WebServiceURL is used when doing HTTP RPC calls. Previously QSystem could only do such calls * to IP addresses. * * @return The WebServiceURL */ public String getWebServiceURL() { return line.hasOption(KEY_WEB_SERVICE_URL) ? line.getOptionValue(KEY_WEB_SERVICE_URL, "") : config.getString(KEY_WEB_SERVICE_URL, ""); } public boolean isChangeLangs() { return line.hasOption(KEY_CLANGS) ? true : config.getBoolean(KEY_CLANGS, false); } public boolean isRetain() { return line.hasOption(KEY_RETAIN) ? true : config.getBoolean(KEY_RETAIN, false); } public int getDelayFirstInvite() { try { return line.hasOption(KEY_DELAY_INVITE_FIRST) ? Integer.parseInt(line.getOptionValue(KEY_DELAY_INVITE_FIRST, "15")) : config.getInt(KEY_DELAY_INVITE_FIRST, 15); } catch (Exception ex) { System.err.println(ex); return 15; } } public int getHttp() { try { return line.hasOption(KEY_HTTP) ? Integer.parseInt(line.getOptionValue(KEY_HTTP, "0")) : config.getInt(KEY_HTTP, 0); } catch (Exception ex) { System.err.println(ex); return 0; } } /** * @return Порт на который надо отправлять HTTP запросы. 0 - отключено */ public int getHttpProtocol() { try { return line.hasOption(KEY_HTTP_PROTOCOL_GET) || line.hasOption(KEY_HTTP_PROTOCOL_POST) ? Integer.parseInt(line.getOptionValue(KEY_HTTP_PROTOCOL_GET, line.getOptionValue(KEY_HTTP_PROTOCOL_POST, "0"))) : config.getInt(KEY_HTTP_PROTOCOL_GET, config.getInt(KEY_HTTP_PROTOCOL_POST, 0)); } catch (Exception ex) { System.err.println(ex); return 0; } } /** * Проверка на протокол общения с сервером и тип запросов. * * @return null - не использовать http, true - POST, false - GET */ public Boolean getHttpRequestType() { return getHttpProtocol() > 0 ? (line.hasOption(KEY_HTTP_PROTOCOL_POST) || config.getInt(KEY_HTTP_PROTOCOL_POST, 0) > 0) : null; } public boolean useExtPriorities() { return line.hasOption(KEY_USE_EXT_PRIORITY) ? true : config.getBoolean(KEY_USE_EXT_PRIORITY, false); } public String getPoint() { return line.hasOption(KEY_POINT) ? line.getOptionValue(KEY_POINT, "") : config.getString(KEY_POINT, ""); } public String getPointN() { return getPoint() == null || getPoint().isEmpty() ? null : getPoint(); } public String getUserID() { return line.getOptionValue(KEY_USER, ""); } public String getBoardCfgFile() { return line.hasOption(KEY_BOARD_CFG) ? line.getOptionValue(KEY_BOARD_CFG, "") : config.getString(KEY_BOARD_CFG, ""); } public String getBoardCfgFXfile() { return line.hasOption(KEY_BOARD_FX_CFG) ? line.getOptionValue(KEY_BOARD_FX_CFG, "") : config.getString(KEY_BOARD_FX_CFG, ""); } public String getServerAddress() { return line.hasOption(KEY_S) ? line.getOptionValue(KEY_S, "127.0.0.1") : config.getString(KEY_S, "127.0.0.1"); } public InetAddress getInetServerAddress() { return tcpServerAddress; } public int getServerPort() { try { return line.hasOption(KEY_S_PORT) ? Integer.parseInt(line.getOptionValue(KEY_S_PORT, "3128")) : config.getInt(KEY_S_PORT, 3128); } catch (Exception ex) { System.err.println(ex); return 3128; } } public int getClientPort() { try { return line.hasOption(KEY_C_PORT) ? Integer.parseInt(line.getOptionValue(KEY_C_PORT, "3129")) : config.getInt(KEY_C_PORT, 3129); } catch (Exception ex) { System.err.println(ex); return 3129; } } public String getNumDivider(String prefix) { return (prefix == null || prefix.isEmpty()) ? "" : (line.hasOption(KEY_NUM_DIVIDER) ? line.getOptionValue(KEY_NUM_DIVIDER, "").replaceAll("_", " ") : ""); } public String getZoneBoardCfgFile() { return line.hasOption(ZKEY_BOARD_CFG) ? line.getOptionValue(ZKEY_BOARD_CFG, "") : config.getString(ZKEY_BOARD_CFG, ""); } public String getTabloBoardCfgFile() { return line.hasOption(TKEY_BOARD_CFG) ? line.getOptionValue(TKEY_BOARD_CFG, "") : config.getString(TKEY_BOARD_CFG, ""); } private static class ConfigHolder { private static final QConfig INSTANCE = new QConfig(); } }
gpl-3.0
fesch/Moenagade
src/lu/fisch/moenagade/gui/ImageFile.java
511
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lu.fisch.moenagade.gui; import java.io.File; /** * * @author robert.fisch */ public class ImageFile extends File { public ImageFile(String string) { super(string); } @Override public String toString() { return getName(); } }
gpl-3.0
raisercostin/mucommander-2
src/main/com/mucommander/VersionChecker.java
11115
/* * This file is part of muCommander, http://www.mucommander.com * Copyright (C) 2002-2012 Maxence Bernard * * muCommander is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * muCommander is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mucommander; import java.io.InputStream; import javax.xml.parsers.SAXParserFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.mucommander.commons.file.FileFactory; /** * Retrieves information about the latest release of muCommander. * <p> * The {@link com.mucommander.RuntimeConstants#VERSION_URL} URL contains information * about the latest release of muCommander:<br> * - date of latest release.<br> * - latest official version.<br> * - where to download the latest version from.<br> * This class is used to access those informations and compare them with what is known * of the current one, making it possible to notify users of new releases. * </p> * <p> * Checking for new releases is a fairly straightforward process, and can be done * with a few lines of code: * <pre> * VersionChecker version; * * try { * version = VersionChecker.getInstance(); * if(version.isNewVersionAvailable()) * System.out.println("A new version of muCommander is available"); * else * System.out.println("You've got the latest muCommander version"); * } * catch(Exception e) {System.err.println("An error occured.");} * </pre> * </p> * <p> * muCommander is considered up to date if:<br> * - the {@link com.mucommander.RuntimeConstants#VERSION local version} is * not smaller than the remote one.<br> * - the {@link com.mucommander.RuntimeConstants#BUILD_DATE local release date} is * not smaller than the remote one.<br> * While comparing release dates seems a bit odd - after all, if a new version is release, * a new version number should be created. However, it's possible to download development * versions of the current release, and those might be updated almost daily. Comparing dates * makes it possible to automate the whole process without having to worry about out version * numbers growing silly. * </p> * @author Maxence Bernard, Nicolas Rinaudo */ public class VersionChecker extends DefaultHandler { private static final Logger LOGGER = LoggerFactory.getLogger(VersionChecker.class); // - XML structure ---------------------------------------------------------- // -------------------------------------------------------------------------- /** Root XML element. */ public static final String ROOT_ELEMENT = "trolcommander"; /** Version XML element. */ public static final String VERSION_ELEMENT = "latest_version"; /** Download URL XML element. */ public static final String DOWNLOAD_URL_ELEMENT = "download_url"; /** JAR URL XML element. */ public static final String JAR_URL_ELEMENT = "jar_url"; /** Date XML element. */ public static final String DATE_ELEMENT = "release_date"; // - XML parsing states ----------------------------------------------------- // -------------------------------------------------------------------------- /** Currently parsing the version tag. */ public static final int STATE_VERSION = 1; /** Currently parsing the download URL tag. */ public static final int STATE_DOWNLOAD_URL = 2; /** Currently parsing the download URL tag. */ public static final int STATE_JAR_URL = 3; /** Currently parsing the date tag. */ public static final int STATE_DATE = 4; /** We're not quite sure what we're parsing. */ public static final int STATE_UNKNOWN = 5; // - Instance fields -------------------------------------------------------- // -------------------------------------------------------------------------- /** Remote version number. */ private String latestVersion; /** Where to download the latest version. */ private String downloadURL; /** URL to the latest JAR file. */ private String jarURL; /** Remote release date. */ private String releaseDate; /** Current state the parser is in. */ private int state; // - Initialisation --------------------------------------------------------- // -------------------------------------------------------------------------- /** * Creates a new version checker instance. */ private VersionChecker() {} /** * Retrieves a description of the latest released version of muCommander. * @return a description of the latest released version of muCommander. * @exception Exception thrown if any error happens while retrieving the remote version. */ public static VersionChecker getInstance() throws Exception { VersionChecker instance; InputStream in; // Input stream on the remote XML file. LOGGER.debug("Opening connection to " + RuntimeConstants.VERSION_URL); // Parses the remote XML file using UTF-8 encoding. in = FileFactory.getFile(RuntimeConstants.VERSION_URL).getInputStream(); try { SAXParserFactory.newInstance().newSAXParser().parse(in, instance = new VersionChecker()); } catch(Exception e) { LOGGER.debug("Failed to read version XML file at "+RuntimeConstants.VERSION_URL, e); throw e; } finally { in.close(); } // Makes sure we retrieved the information we were looking for. // We're not checking the release date as older version of muCommander // didn't use it. if(instance.latestVersion == null || instance.latestVersion.equals("") || instance.downloadURL == null || instance.downloadURL.equals("")) throw new Exception(); return instance; } // - Remote version information --------------------------------------------- // -------------------------------------------------------------------------- /** * Checks whether the remote version is newer than the current one. * @return <code>true</code> if the remote version is newer than the current one, * <code>false</code> otherwise. */ public boolean isNewVersionAvailable() { // If the local and remote versions are the same, compares release dates. if (latestVersion.equals(RuntimeConstants.VERSION.trim().toLowerCase())) { // This ensures backward compatibility - if the remote version file does not contain // release date information, ignore it. if (releaseDate.isEmpty()) return true; // Checks whether the remote release date is later than the current release date. return releaseDate.compareTo(RuntimeConstants.BUILD_DATE) > 0; } return true; } /** * Returns the version number of the latest muCommander release. * @return the version number of the latest muCommander release. */ public String getLatestVersion() {return latestVersion;} /** * Returns the URL at which the latest version of muCommander can be downloaded. * @return the URL at which the latest version of muCommander can be downloaded. */ public String getDownloadURL() {return downloadURL;} /** * Returns the URL to the latest JAR file, <code>null</code> if not available. * @return the URL to the latest JAR file. */ public String getJarURL() {return jarURL;} /** * Returns the date at which the latest version of muCommander has been released. * <p> * The date format is YYYYMMDD. * </p> * @return the date at which the latest version of muCommander has been released. */ public String getReleaseDate() {return releaseDate;} // - XML parsing ------------------------------------------------------------ // -------------------------------------------------------------------------- /** * Called when the XML document parsing has started. */ @Override public void startDocument() { latestVersion = ""; downloadURL = ""; jarURL = ""; releaseDate = ""; } /** * Notifies the parser of CDATA. */ @Override public void characters(char[] ch, int offset, int length) { if(state == STATE_VERSION) latestVersion += new String(ch, offset, length); else if(state == STATE_DOWNLOAD_URL) downloadURL += new String(ch, offset, length); else if(state == STATE_JAR_URL) jarURL += new String(ch, offset, length); else if(state == STATE_DATE) releaseDate += new String(ch, offset, length); } /** * Notifies the parser that a new tag is starting. */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // Checks whether we know the tag and updates the current state. switch (qName) { case VERSION_ELEMENT: state = STATE_VERSION; break; case DOWNLOAD_URL_ELEMENT: state = STATE_DOWNLOAD_URL; break; case JAR_URL_ELEMENT: state = STATE_JAR_URL; break; case DATE_ELEMENT: state = STATE_DATE; break; default: state = STATE_UNKNOWN; break; } } /** * Notifies the parser that the current element is finished. */ @Override public void endElement(String uri, String localName, String qName) throws SAXException {state = STATE_UNKNOWN;} /** * Notifies the parser that XML parsing is finished. */ @Override public void endDocument() { // Make sure we're not keep meaningless whitecase characters in the data. latestVersion = latestVersion.toLowerCase().trim(); downloadURL = downloadURL.trim(); jarURL = jarURL.trim(); if (jarURL.length() == 0) { jarURL = null; } releaseDate = releaseDate.trim(); // Logs the data if in debug mode. LOGGER.debug("download URL: " + downloadURL); LOGGER.debug("jar URL: " + jarURL); LOGGER.debug("latestVersion: " + latestVersion); LOGGER.debug("releaseDate: " + releaseDate); } }
gpl-3.0
eae/opendental
OpenDentBusiness/Crud/JobCrud.cs
22043
//This file is automatically generated. //Do not attempt to make changes to this file because the changes will be erased and overwritten. using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Drawing; namespace OpenDentBusiness.Crud{ public class JobCrud { ///<summary>Gets one Job object from the database using the primary key. Returns null if not found.</summary> public static Job SelectOne(long jobNum){ string command="SELECT * FROM job " +"WHERE JobNum = "+POut.Long(jobNum); List<Job> list=TableToList(Db.GetTable(command)); if(list.Count==0) { return null; } return list[0]; } ///<summary>Gets one Job object from the database using a query.</summary> public static Job SelectOne(string command){ if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) { throw new ApplicationException("Not allowed to send sql directly. Rewrite the calling class to not use this query:\r\n"+command); } List<Job> list=TableToList(Db.GetTable(command)); if(list.Count==0) { return null; } return list[0]; } ///<summary>Gets a list of Job objects from the database using a query.</summary> public static List<Job> SelectMany(string command){ if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) { throw new ApplicationException("Not allowed to send sql directly. Rewrite the calling class to not use this query:\r\n"+command); } List<Job> list=TableToList(Db.GetTable(command)); return list; } ///<summary>Converts a DataTable to a list of objects.</summary> public static List<Job> TableToList(DataTable table){ List<Job> retVal=new List<Job>(); Job job; foreach(DataRow row in table.Rows) { job=new Job(); job.JobNum = PIn.Long (row["JobNum"].ToString()); job.UserNumConcept = PIn.Long (row["UserNumConcept"].ToString()); job.UserNumExpert = PIn.Long (row["UserNumExpert"].ToString()); job.UserNumEngineer = PIn.Long (row["UserNumEngineer"].ToString()); job.UserNumApproverConcept= PIn.Long (row["UserNumApproverConcept"].ToString()); job.UserNumApproverJob = PIn.Long (row["UserNumApproverJob"].ToString()); job.UserNumApproverChange = PIn.Long (row["UserNumApproverChange"].ToString()); job.UserNumDocumenter = PIn.Long (row["UserNumDocumenter"].ToString()); job.UserNumCustContact = PIn.Long (row["UserNumCustContact"].ToString()); job.UserNumCheckout = PIn.Long (row["UserNumCheckout"].ToString()); job.UserNumInfo = PIn.Long (row["UserNumInfo"].ToString()); job.ParentNum = PIn.Long (row["ParentNum"].ToString()); job.DateTimeCustContact = PIn.DateT (row["DateTimeCustContact"].ToString()); string priority=row["Priority"].ToString(); if(priority==""){ job.Priority =(JobPriority)0; } else try{ job.Priority =(JobPriority)Enum.Parse(typeof(JobPriority),priority); } catch{ job.Priority =(JobPriority)0; } string category=row["Category"].ToString(); if(category==""){ job.Category =(JobCategory)0; } else try{ job.Category =(JobCategory)Enum.Parse(typeof(JobCategory),category); } catch{ job.Category =(JobCategory)0; } job.JobVersion = PIn.String(row["JobVersion"].ToString()); job.HoursEstimate = PIn.Int (row["HoursEstimate"].ToString()); job.HoursActual = PIn.Int (row["HoursActual"].ToString()); job.DateTimeEntry = PIn.DateT (row["DateTimeEntry"].ToString()); job.Description = PIn.String(row["Description"].ToString()); job.Documentation = PIn.String(row["Documentation"].ToString()); job.Title = PIn.String(row["Title"].ToString()); string phaseCur=row["PhaseCur"].ToString(); if(phaseCur==""){ job.PhaseCur =(JobPhase)0; } else try{ job.PhaseCur =(JobPhase)Enum.Parse(typeof(JobPhase),phaseCur); } catch{ job.PhaseCur =(JobPhase)0; } job.IsApprovalNeeded = PIn.Bool (row["IsApprovalNeeded"].ToString()); job.AckDateTime = PIn.DateT (row["AckDateTime"].ToString()); retVal.Add(job); } return retVal; } ///<summary>Converts a list of Job into a DataTable.</summary> public static DataTable ListToTable(List<Job> listJobs,string tableName="") { if(string.IsNullOrEmpty(tableName)) { tableName="Job"; } DataTable table=new DataTable(tableName); table.Columns.Add("JobNum"); table.Columns.Add("UserNumConcept"); table.Columns.Add("UserNumExpert"); table.Columns.Add("UserNumEngineer"); table.Columns.Add("UserNumApproverConcept"); table.Columns.Add("UserNumApproverJob"); table.Columns.Add("UserNumApproverChange"); table.Columns.Add("UserNumDocumenter"); table.Columns.Add("UserNumCustContact"); table.Columns.Add("UserNumCheckout"); table.Columns.Add("UserNumInfo"); table.Columns.Add("ParentNum"); table.Columns.Add("DateTimeCustContact"); table.Columns.Add("Priority"); table.Columns.Add("Category"); table.Columns.Add("JobVersion"); table.Columns.Add("HoursEstimate"); table.Columns.Add("HoursActual"); table.Columns.Add("DateTimeEntry"); table.Columns.Add("Description"); table.Columns.Add("Documentation"); table.Columns.Add("Title"); table.Columns.Add("PhaseCur"); table.Columns.Add("IsApprovalNeeded"); table.Columns.Add("AckDateTime"); foreach(Job job in listJobs) { table.Rows.Add(new object[] { POut.Long (job.JobNum), POut.Long (job.UserNumConcept), POut.Long (job.UserNumExpert), POut.Long (job.UserNumEngineer), POut.Long (job.UserNumApproverConcept), POut.Long (job.UserNumApproverJob), POut.Long (job.UserNumApproverChange), POut.Long (job.UserNumDocumenter), POut.Long (job.UserNumCustContact), POut.Long (job.UserNumCheckout), POut.Long (job.UserNumInfo), POut.Long (job.ParentNum), POut.DateT (job.DateTimeCustContact,false), POut.Int ((int)job.Priority), POut.Int ((int)job.Category), job.JobVersion, POut.Int (job.HoursEstimate), POut.Int (job.HoursActual), POut.DateT (job.DateTimeEntry,false), job.Description, job.Documentation, job.Title, POut.Int ((int)job.PhaseCur), POut.Bool (job.IsApprovalNeeded), POut.DateT (job.AckDateTime,false), }); } return table; } ///<summary>Inserts one Job into the database. Returns the new priKey.</summary> public static long Insert(Job job){ if(DataConnection.DBtype==DatabaseType.Oracle) { job.JobNum=DbHelper.GetNextOracleKey("job","JobNum"); int loopcount=0; while(loopcount<100){ try { return Insert(job,true); } catch(Oracle.DataAccess.Client.OracleException ex){ if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){ job.JobNum++; loopcount++; } else{ throw ex; } } } throw new ApplicationException("Insert failed. Could not generate primary key."); } else { return Insert(job,false); } } ///<summary>Inserts one Job into the database. Provides option to use the existing priKey.</summary> public static long Insert(Job job,bool useExistingPK){ if(!useExistingPK && PrefC.RandomKeys) { job.JobNum=ReplicationServers.GetKey("job","JobNum"); } string command="INSERT INTO job ("; if(useExistingPK || PrefC.RandomKeys) { command+="JobNum,"; } command+="UserNumConcept,UserNumExpert,UserNumEngineer,UserNumApproverConcept,UserNumApproverJob,UserNumApproverChange,UserNumDocumenter,UserNumCustContact,UserNumCheckout,UserNumInfo,ParentNum,DateTimeCustContact,Priority,Category,JobVersion,HoursEstimate,HoursActual,DateTimeEntry,Description,Documentation,Title,PhaseCur,IsApprovalNeeded,AckDateTime) VALUES("; if(useExistingPK || PrefC.RandomKeys) { command+=POut.Long(job.JobNum)+","; } command+= POut.Long (job.UserNumConcept)+"," + POut.Long (job.UserNumExpert)+"," + POut.Long (job.UserNumEngineer)+"," + POut.Long (job.UserNumApproverConcept)+"," + POut.Long (job.UserNumApproverJob)+"," + POut.Long (job.UserNumApproverChange)+"," + POut.Long (job.UserNumDocumenter)+"," + POut.Long (job.UserNumCustContact)+"," + POut.Long (job.UserNumCheckout)+"," + POut.Long (job.UserNumInfo)+"," + POut.Long (job.ParentNum)+"," + POut.DateT (job.DateTimeCustContact)+"," +"'"+POut.String(job.Priority.ToString())+"'," +"'"+POut.String(job.Category.ToString())+"'," +"'"+POut.String(job.JobVersion)+"'," + POut.Int (job.HoursEstimate)+"," + POut.Int (job.HoursActual)+"," + DbHelper.Now()+"," + DbHelper.ParamChar+"paramDescription," + DbHelper.ParamChar+"paramDocumentation," +"'"+POut.String(job.Title)+"'," +"'"+POut.String(job.PhaseCur.ToString())+"'," + POut.Bool (job.IsApprovalNeeded)+"," + POut.DateT (job.AckDateTime)+")"; if(job.Description==null) { job.Description=""; } OdSqlParameter paramDescription=new OdSqlParameter("paramDescription",OdDbType.Text,job.Description); if(job.Documentation==null) { job.Documentation=""; } OdSqlParameter paramDocumentation=new OdSqlParameter("paramDocumentation",OdDbType.Text,job.Documentation); if(useExistingPK || PrefC.RandomKeys) { Db.NonQ(command,paramDescription,paramDocumentation); } else { job.JobNum=Db.NonQ(command,true,paramDescription,paramDocumentation); } return job.JobNum; } ///<summary>Inserts one Job into the database. Returns the new priKey. Doesn't use the cache.</summary> public static long InsertNoCache(Job job){ if(DataConnection.DBtype==DatabaseType.MySql) { return InsertNoCache(job,false); } else { if(DataConnection.DBtype==DatabaseType.Oracle) { job.JobNum=DbHelper.GetNextOracleKey("job","JobNum"); //Cacheless method } return InsertNoCache(job,true); } } ///<summary>Inserts one Job into the database. Provides option to use the existing priKey. Doesn't use the cache.</summary> public static long InsertNoCache(Job job,bool useExistingPK){ bool isRandomKeys=Prefs.GetBoolNoCache(PrefName.RandomPrimaryKeys); string command="INSERT INTO job ("; if(!useExistingPK && isRandomKeys) { job.JobNum=ReplicationServers.GetKeyNoCache("job","JobNum"); } if(isRandomKeys || useExistingPK) { command+="JobNum,"; } command+="UserNumConcept,UserNumExpert,UserNumEngineer,UserNumApproverConcept,UserNumApproverJob,UserNumApproverChange,UserNumDocumenter,UserNumCustContact,UserNumCheckout,UserNumInfo,ParentNum,DateTimeCustContact,Priority,Category,JobVersion,HoursEstimate,HoursActual,DateTimeEntry,Description,Documentation,Title,PhaseCur,IsApprovalNeeded,AckDateTime) VALUES("; if(isRandomKeys || useExistingPK) { command+=POut.Long(job.JobNum)+","; } command+= POut.Long (job.UserNumConcept)+"," + POut.Long (job.UserNumExpert)+"," + POut.Long (job.UserNumEngineer)+"," + POut.Long (job.UserNumApproverConcept)+"," + POut.Long (job.UserNumApproverJob)+"," + POut.Long (job.UserNumApproverChange)+"," + POut.Long (job.UserNumDocumenter)+"," + POut.Long (job.UserNumCustContact)+"," + POut.Long (job.UserNumCheckout)+"," + POut.Long (job.UserNumInfo)+"," + POut.Long (job.ParentNum)+"," + POut.DateT (job.DateTimeCustContact)+"," +"'"+POut.String(job.Priority.ToString())+"'," +"'"+POut.String(job.Category.ToString())+"'," +"'"+POut.String(job.JobVersion)+"'," + POut.Int (job.HoursEstimate)+"," + POut.Int (job.HoursActual)+"," + DbHelper.Now()+"," + DbHelper.ParamChar+"paramDescription," + DbHelper.ParamChar+"paramDocumentation," +"'"+POut.String(job.Title)+"'," +"'"+POut.String(job.PhaseCur.ToString())+"'," + POut.Bool (job.IsApprovalNeeded)+"," + POut.DateT (job.AckDateTime)+")"; if(job.Description==null) { job.Description=""; } OdSqlParameter paramDescription=new OdSqlParameter("paramDescription",OdDbType.Text,job.Description); if(job.Documentation==null) { job.Documentation=""; } OdSqlParameter paramDocumentation=new OdSqlParameter("paramDocumentation",OdDbType.Text,job.Documentation); if(useExistingPK || isRandomKeys) { Db.NonQ(command,paramDescription,paramDocumentation); } else { job.JobNum=Db.NonQ(command,true,paramDescription,paramDocumentation); } return job.JobNum; } ///<summary>Updates one Job in the database.</summary> public static void Update(Job job){ string command="UPDATE job SET " +"UserNumConcept = "+POut.Long (job.UserNumConcept)+", " +"UserNumExpert = "+POut.Long (job.UserNumExpert)+", " +"UserNumEngineer = "+POut.Long (job.UserNumEngineer)+", " +"UserNumApproverConcept= "+POut.Long (job.UserNumApproverConcept)+", " +"UserNumApproverJob = "+POut.Long (job.UserNumApproverJob)+", " +"UserNumApproverChange = "+POut.Long (job.UserNumApproverChange)+", " +"UserNumDocumenter = "+POut.Long (job.UserNumDocumenter)+", " +"UserNumCustContact = "+POut.Long (job.UserNumCustContact)+", " +"UserNumCheckout = "+POut.Long (job.UserNumCheckout)+", " +"UserNumInfo = "+POut.Long (job.UserNumInfo)+", " +"ParentNum = "+POut.Long (job.ParentNum)+", " +"DateTimeCustContact = "+POut.DateT (job.DateTimeCustContact)+", " +"Priority = '"+POut.String(job.Priority.ToString())+"', " +"Category = '"+POut.String(job.Category.ToString())+"', " +"JobVersion = '"+POut.String(job.JobVersion)+"', " +"HoursEstimate = "+POut.Int (job.HoursEstimate)+", " +"HoursActual = "+POut.Int (job.HoursActual)+", " //DateTimeEntry not allowed to change +"Description = "+DbHelper.ParamChar+"paramDescription, " +"Documentation = "+DbHelper.ParamChar+"paramDocumentation, " +"Title = '"+POut.String(job.Title)+"', " +"PhaseCur = '"+POut.String(job.PhaseCur.ToString())+"', " +"IsApprovalNeeded = "+POut.Bool (job.IsApprovalNeeded)+", " +"AckDateTime = "+POut.DateT (job.AckDateTime)+" " +"WHERE JobNum = "+POut.Long(job.JobNum); if(job.Description==null) { job.Description=""; } OdSqlParameter paramDescription=new OdSqlParameter("paramDescription",OdDbType.Text,job.Description); if(job.Documentation==null) { job.Documentation=""; } OdSqlParameter paramDocumentation=new OdSqlParameter("paramDocumentation",OdDbType.Text,job.Documentation); Db.NonQ(command,paramDescription,paramDocumentation); } ///<summary>Updates one Job in the database. Uses an old object to compare to, and only alters changed fields. This prevents collisions and concurrency problems in heavily used tables. Returns true if an update occurred.</summary> public static bool Update(Job job,Job oldJob){ string command=""; if(job.UserNumConcept != oldJob.UserNumConcept) { if(command!=""){ command+=",";} command+="UserNumConcept = "+POut.Long(job.UserNumConcept)+""; } if(job.UserNumExpert != oldJob.UserNumExpert) { if(command!=""){ command+=",";} command+="UserNumExpert = "+POut.Long(job.UserNumExpert)+""; } if(job.UserNumEngineer != oldJob.UserNumEngineer) { if(command!=""){ command+=",";} command+="UserNumEngineer = "+POut.Long(job.UserNumEngineer)+""; } if(job.UserNumApproverConcept != oldJob.UserNumApproverConcept) { if(command!=""){ command+=",";} command+="UserNumApproverConcept = "+POut.Long(job.UserNumApproverConcept)+""; } if(job.UserNumApproverJob != oldJob.UserNumApproverJob) { if(command!=""){ command+=",";} command+="UserNumApproverJob = "+POut.Long(job.UserNumApproverJob)+""; } if(job.UserNumApproverChange != oldJob.UserNumApproverChange) { if(command!=""){ command+=",";} command+="UserNumApproverChange = "+POut.Long(job.UserNumApproverChange)+""; } if(job.UserNumDocumenter != oldJob.UserNumDocumenter) { if(command!=""){ command+=",";} command+="UserNumDocumenter = "+POut.Long(job.UserNumDocumenter)+""; } if(job.UserNumCustContact != oldJob.UserNumCustContact) { if(command!=""){ command+=",";} command+="UserNumCustContact = "+POut.Long(job.UserNumCustContact)+""; } if(job.UserNumCheckout != oldJob.UserNumCheckout) { if(command!=""){ command+=",";} command+="UserNumCheckout = "+POut.Long(job.UserNumCheckout)+""; } if(job.UserNumInfo != oldJob.UserNumInfo) { if(command!=""){ command+=",";} command+="UserNumInfo = "+POut.Long(job.UserNumInfo)+""; } if(job.ParentNum != oldJob.ParentNum) { if(command!=""){ command+=",";} command+="ParentNum = "+POut.Long(job.ParentNum)+""; } if(job.DateTimeCustContact != oldJob.DateTimeCustContact) { if(command!=""){ command+=",";} command+="DateTimeCustContact = "+POut.DateT(job.DateTimeCustContact)+""; } if(job.Priority != oldJob.Priority) { if(command!=""){ command+=",";} command+="Priority = '"+POut.String(job.Priority.ToString())+"'"; } if(job.Category != oldJob.Category) { if(command!=""){ command+=",";} command+="Category = '"+POut.String(job.Category.ToString())+"'"; } if(job.JobVersion != oldJob.JobVersion) { if(command!=""){ command+=",";} command+="JobVersion = '"+POut.String(job.JobVersion)+"'"; } if(job.HoursEstimate != oldJob.HoursEstimate) { if(command!=""){ command+=",";} command+="HoursEstimate = "+POut.Int(job.HoursEstimate)+""; } if(job.HoursActual != oldJob.HoursActual) { if(command!=""){ command+=",";} command+="HoursActual = "+POut.Int(job.HoursActual)+""; } //DateTimeEntry not allowed to change if(job.Description != oldJob.Description) { if(command!=""){ command+=",";} command+="Description = "+DbHelper.ParamChar+"paramDescription"; } if(job.Documentation != oldJob.Documentation) { if(command!=""){ command+=",";} command+="Documentation = "+DbHelper.ParamChar+"paramDocumentation"; } if(job.Title != oldJob.Title) { if(command!=""){ command+=",";} command+="Title = '"+POut.String(job.Title)+"'"; } if(job.PhaseCur != oldJob.PhaseCur) { if(command!=""){ command+=",";} command+="PhaseCur = '"+POut.String(job.PhaseCur.ToString())+"'"; } if(job.IsApprovalNeeded != oldJob.IsApprovalNeeded) { if(command!=""){ command+=",";} command+="IsApprovalNeeded = "+POut.Bool(job.IsApprovalNeeded)+""; } if(job.AckDateTime != oldJob.AckDateTime) { if(command!=""){ command+=",";} command+="AckDateTime = "+POut.DateT(job.AckDateTime)+""; } if(command==""){ return false; } if(job.Description==null) { job.Description=""; } OdSqlParameter paramDescription=new OdSqlParameter("paramDescription",OdDbType.Text,job.Description); if(job.Documentation==null) { job.Documentation=""; } OdSqlParameter paramDocumentation=new OdSqlParameter("paramDocumentation",OdDbType.Text,job.Documentation); command="UPDATE job SET "+command +" WHERE JobNum = "+POut.Long(job.JobNum); Db.NonQ(command,paramDescription,paramDocumentation); return true; } ///<summary>Returns true if Update(Job,Job) would make changes to the database. ///Does not make any changes to the database and can be called before remoting role is checked.</summary> public static bool UpdateComparison(Job job,Job oldJob) { if(job.UserNumConcept != oldJob.UserNumConcept) { return true; } if(job.UserNumExpert != oldJob.UserNumExpert) { return true; } if(job.UserNumEngineer != oldJob.UserNumEngineer) { return true; } if(job.UserNumApproverConcept != oldJob.UserNumApproverConcept) { return true; } if(job.UserNumApproverJob != oldJob.UserNumApproverJob) { return true; } if(job.UserNumApproverChange != oldJob.UserNumApproverChange) { return true; } if(job.UserNumDocumenter != oldJob.UserNumDocumenter) { return true; } if(job.UserNumCustContact != oldJob.UserNumCustContact) { return true; } if(job.UserNumCheckout != oldJob.UserNumCheckout) { return true; } if(job.UserNumInfo != oldJob.UserNumInfo) { return true; } if(job.ParentNum != oldJob.ParentNum) { return true; } if(job.DateTimeCustContact != oldJob.DateTimeCustContact) { return true; } if(job.Priority != oldJob.Priority) { return true; } if(job.Category != oldJob.Category) { return true; } if(job.JobVersion != oldJob.JobVersion) { return true; } if(job.HoursEstimate != oldJob.HoursEstimate) { return true; } if(job.HoursActual != oldJob.HoursActual) { return true; } //DateTimeEntry not allowed to change if(job.Description != oldJob.Description) { return true; } if(job.Documentation != oldJob.Documentation) { return true; } if(job.Title != oldJob.Title) { return true; } if(job.PhaseCur != oldJob.PhaseCur) { return true; } if(job.IsApprovalNeeded != oldJob.IsApprovalNeeded) { return true; } if(job.AckDateTime != oldJob.AckDateTime) { return true; } return false; } ///<summary>Deletes one Job from the database.</summary> public static void Delete(long jobNum){ string command="DELETE FROM job " +"WHERE JobNum = "+POut.Long(jobNum); Db.NonQ(command); } } }
gpl-3.0
openstates/openstates
openstates/hi/__init__.py
3122
from openstates.utils import url_xpath, State from .people import HIPersonScraper from .events import HIEventScraper from .bills import HIBillScraper # from .committees import HICommitteeScraper settings = dict(SCRAPELIB_TIMEOUT=300) class Hawaii(State): scrapers = { "people": HIPersonScraper, "bills": HIBillScraper, # 'committees': HICommitteeScraper, "events": HIEventScraper, } legislative_sessions = [ { "_scraped_name": "2012", "identifier": "2011 Regular Session", "name": "2011-2012 Regular Session", "start_date": "2011-01-19", "end_date": "2012-05-03", }, { "_scraped_name": "2013", "identifier": "2013 Regular Session", "name": "2013 Regular Session", "start_date": "2013-01-16", "end_date": "2013-05-03", }, { "_scraped_name": "2014", "identifier": "2014 Regular Session", "name": "2014 Regular Session", "start_date": "2014-01-15", "end_date": "2014-05-02", }, { "_scraped_name": "2015", "identifier": "2015 Regular Session", "name": "2015 Regular Session", "start_date": "2015-01-21", "end_date": "2015-05-07", }, { "_scraped_name": "2016", "identifier": "2016 Regular Session", "name": "2016 Regular Session", "start_date": "2016-01-20", "end_date": "2016-05-05", }, { "_scraped_name": "2017", "identifier": "2017 Regular Session", "name": "2017 Regular Session", "start_date": "2017-01-18", "end_date": "2017-05-04", }, { "_scraped_name": "2018", "identifier": "2018 Regular Session", "name": "2018 Regular Session", "start_date": "2018-01-18", "end_date": "2018-05-03", }, { "_scraped_name": "2019", "identifier": "2019 Regular Session", "name": "2019 Regular Session", "start_date": "2019-01-15", "end_date": "2019-04-12", }, { "_scraped_name": "2020", "identifier": "2020 Regular Session", "name": "2020 Regular Session", "start_date": "2020-01-15", "end_date": "2020-05-07", }, ] ignored_scraped_sessions = [ "2011", "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003", "2002", "2001", "2000", "1999", ] def get_session_list(self): # doesn't include current session, we need to change it sessions = url_xpath( "http://www.capitol.hawaii.gov/archives/main.aspx", "//div[@class='roundedrect gradientgray shadow']/a/text()", ) sessions.remove("Archives Main") return sessions
gpl-3.0
pootzko/auto-wol
src/net/cmikavac/autowol/utils/TimeUtil.java
4438
package net.cmikavac.autowol.utils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import android.content.Context; public class TimeUtil { /** * Gets a timestamp in milliseconds from hour and minute of day. * @param hour Hour of day. * @param minute Minute of day. * @return Timestamp in milliseconds. */ public static Long getTimeInMilliseconds(int hour, int minute) { Calendar time = Calendar.getInstance(); time.set(Calendar.HOUR_OF_DAY, hour); time.set(Calendar.MINUTE, minute); return time.getTimeInMillis(); } /** * Formats time in milliseconds based on users AndroidOS preferences (AM/PM vs 24-hour). * @param milliSeconds Timestamp in milliseconds. * @param context Context entity. * @return Human-readable formatted time string. */ public static String getFormatedTime(Long milliSeconds, Context context) { DateFormat formatter = getFormatter(context); Calendar time = Calendar.getInstance(); time.setTimeInMillis(milliSeconds); return formatter.format(time.getTime()); } /** * Gets android formatter based on current Context and users AndroidOS preferences (AM/PM vs 24-hour). * @param context Context entity. * @return DateFormat entity with formatting set. */ private static DateFormat getFormatter(Context context) { String format = android.text.format.DateFormat.is24HourFormat(context) ? "HH:mm" : "hh:mmaa"; return new SimpleDateFormat(format, Locale.getDefault()); } /** * Gets hour of day from milliseconds. * @param milliSeconds Timestamp in milliseconds. * @return Hour of day. */ public static int getHourFromMilliseconds(Long milliSeconds) { Calendar time = Calendar.getInstance(); time.setTimeInMillis(milliSeconds); return time.get(Calendar.HOUR_OF_DAY); } /** * Gets minutes value from milliseconds. * @param milliSeconds Timestamp in milliseconds. * @return Minutes. */ public static int getMinuteFromMilliseconds(Long milliSeconds) { Calendar time = Calendar.getInstance(); time.setTimeInMillis(milliSeconds); return time.get(Calendar.MINUTE); } /** * Checks if time now is between quiet hours "from" and "to" values. Creates 3 new * new timestamps and sets hours and minutes for quiet hours "from" and "to" * and then compares the timestamps in milliseconds. * @param quietFrom Quiet hours from timestamp in milliseconds. * @param quietTo Quiet hours to timestamp in milliseconds. * @return Is time now between quiet hours "from" and "to" values? */ public static Boolean isNowBetweenQuietHours(Long quietFrom, Long quietTo) { Calendar timeNow = Calendar.getInstance(); Calendar timeFrom = Calendar.getInstance(); timeFrom.set(Calendar.HOUR_OF_DAY, getHourFromMilliseconds(quietFrom)); timeFrom.set(Calendar.MINUTE, getMinuteFromMilliseconds(quietFrom)); Calendar timeTo = Calendar.getInstance(); timeTo.set(Calendar.HOUR_OF_DAY, getHourFromMilliseconds(quietTo)); timeTo.set(Calendar.MINUTE, getMinuteFromMilliseconds(quietTo)); if (timeTo.before(timeFrom)) { timeTo.add(Calendar.DATE, 1); } return timeNow.after(timeFrom) && timeNow.before(timeTo) ? true : false; } /** * Checks if idleTime amount of minutes has passed since last network disconnection. * @param idleTime Number of minutes to check if they passed since last DC. * @param lastDisconnected Last time disconnected timestamp in milliseconds. * @return Has idle time passed? */ public static Boolean hasIdleTimePassed(Integer idleTime, Long lastDisconnected) { if (lastDisconnected.equals(null)) return true; Calendar timeIdle = Calendar.getInstance(); timeIdle.add(Calendar.MINUTE, -1 * idleTime); Calendar timeDisconnected = Calendar.getInstance(); timeDisconnected.setTimeInMillis(lastDisconnected); return timeDisconnected.before(timeIdle); } }
gpl-3.0
Interfacelab/ilab-media-tools
lib/mcloud-aws/aws-sdk-php/src/GuardDuty/GuardDutyClient.php
10449
<?php namespace MediaCloud\Vendor\Aws\GuardDuty; use MediaCloud\Vendor\Aws\AwsClient; /** * This client is used to interact with the **Amazon GuardDuty** service. * @method \MediaCloud\Vendor\Aws\Result acceptInvitation(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise acceptInvitationAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result archiveFindings(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise archiveFindingsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result createDetector(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise createDetectorAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result createFilter(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise createFilterAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result createIPSet(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise createIPSetAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result createMembers(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise createMembersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result createPublishingDestination(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise createPublishingDestinationAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result createSampleFindings(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise createSampleFindingsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result createThreatIntelSet(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise createThreatIntelSetAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result declineInvitations(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise declineInvitationsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result deleteDetector(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise deleteDetectorAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result deleteFilter(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise deleteFilterAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result deleteIPSet(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise deleteIPSetAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result deleteInvitations(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise deleteInvitationsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result deleteMembers(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise deleteMembersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result deletePublishingDestination(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise deletePublishingDestinationAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result deleteThreatIntelSet(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise deleteThreatIntelSetAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result describeOrganizationConfiguration(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise describeOrganizationConfigurationAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result describePublishingDestination(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise describePublishingDestinationAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result disableOrganizationAdminAccount(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise disableOrganizationAdminAccountAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result disassociateFromMasterAccount(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise disassociateFromMasterAccountAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result disassociateMembers(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise disassociateMembersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result enableOrganizationAdminAccount(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise enableOrganizationAdminAccountAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getDetector(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getDetectorAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getFilter(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getFilterAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getFindings(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getFindingsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getFindingsStatistics(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getFindingsStatisticsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getIPSet(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getIPSetAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getInvitationsCount(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getInvitationsCountAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getMasterAccount(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getMasterAccountAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getMemberDetectors(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getMemberDetectorsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getMembers(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getMembersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getThreatIntelSet(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getThreatIntelSetAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result getUsageStatistics(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getUsageStatisticsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result inviteMembers(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise inviteMembersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listDetectors(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listDetectorsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listFilters(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listFiltersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listFindings(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listFindingsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listIPSets(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listIPSetsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listInvitations(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listInvitationsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listMembers(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listMembersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listOrganizationAdminAccounts(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listOrganizationAdminAccountsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listPublishingDestinations(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listPublishingDestinationsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listTagsForResource(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listTagsForResourceAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result listThreatIntelSets(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listThreatIntelSetsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result startMonitoringMembers(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise startMonitoringMembersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result stopMonitoringMembers(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise stopMonitoringMembersAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result tagResource(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise tagResourceAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result unarchiveFindings(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise unarchiveFindingsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result untagResource(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise untagResourceAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result updateDetector(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updateDetectorAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result updateFilter(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updateFilterAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result updateFindingsFeedback(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updateFindingsFeedbackAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result updateIPSet(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updateIPSetAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result updateMemberDetectors(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updateMemberDetectorsAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result updateOrganizationConfiguration(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updateOrganizationConfigurationAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result updatePublishingDestination(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updatePublishingDestinationAsync(array $args = []) * @method \MediaCloud\Vendor\Aws\Result updateThreatIntelSet(array $args = []) * @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updateThreatIntelSetAsync(array $args = []) */ class GuardDutyClient extends AwsClient {}
gpl-3.0
heartvalve/OpenFlipper
Plugin-MeanCurvature/MeanCurvature.hh
4867
/*===========================================================================*\ * * * OpenFlipper * * Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen * * www.openflipper.org * * * *--------------------------------------------------------------------------- * * This file is part of OpenFlipper. * * * * OpenFlipper is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenFlipper is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU LesserGeneral Public * * License along with OpenFlipper. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $LastChangedBy$ * * $Date$ * * * \*===========================================================================*/ #ifndef MEANCURVATUREPLUGIN_HH #define MEANCURVATUREPLUGIN_HH #include <QObject> #include <QMenuBar> #include <OpenFlipper/BasePlugin/BaseInterface.hh> #include <OpenFlipper/BasePlugin/TextureInterface.hh> #include <OpenFlipper/common/Types.hh> class MeanCurvaturePlugin : public QObject, BaseInterface, TextureInterface { Q_OBJECT Q_INTERFACES(BaseInterface) Q_INTERFACES(TextureInterface) #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "org.OpenFlipper.Plugins.Plugin-MeanCurvature") #endif signals: // Texture Interface void addTexture( QString _textureName , QString _filename , uint dimension ); void updatedTextures( QString , int ); void setTextureMode(QString _textureName ,QString _mode); // Base Interface void setSlotDescription(QString _slotName, QString _slotDescription, QStringList _parameters, QStringList _descriptions); private slots: void slotUpdateTexture( QString _textureName , int _identifier ); void pluginsInitialized(); // Tell system that this plugin runs without ui void noguiSupported( ) {} ; public slots: /** \brief Scripting slot to trigger computation of mean curvature * * The curvature will be stored on the mesh on the vertex property called "Mean Curvature" */ bool computeMeanCurvature(int _objectId); QString version() { return QString("1.0"); }; public : MeanCurvaturePlugin(); ~MeanCurvaturePlugin(); QString name() { return (QString("MeanCurvature")); }; QString description( ) { return (QString("Generates Mean Curvature information")); }; private: template< typename MeshT > void computeMeanCurvature(MeshT* _mesh); }; #endif //MEANCURVATUREPLUGIN_HH
gpl-3.0
gythialy/openmuc
projects/driver/modbus/src/test/java/org/openmuc/framework/driver/modbus/test/DriverTest.java
1855
/* * Copyright 2011-2021 Fraunhofer ISE * * This file is part of OpenMUC. * For more information visit http://www.openmuc.org * * OpenMUC is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenMUC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenMUC. If not, see <http://www.gnu.org/licenses/>. * */ package org.openmuc.framework.driver.modbus.test; import org.junit.jupiter.api.Test; import org.openmuc.framework.config.DriverInfo; import org.openmuc.framework.driver.modbus.ModbusDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DriverTest { private static final Logger logger = LoggerFactory.getLogger(DriverTest.class); @Test public void printDriverInfo() { ModbusDriver driver = new ModbusDriver(); DriverInfo info = driver.getInfo(); StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("Driver Id = " + info.getId() + "\n"); sb.append("Description = " + info.getDescription() + "\n"); sb.append("DeviceAddressSyntax = " + info.getDeviceAddressSyntax() + "\n"); sb.append("SettingsSyntax = " + info.getSettingsSyntax() + "\n"); sb.append("ChannelAddressSyntax = " + info.getChannelAddressSyntax() + "\n"); sb.append("DeviceScanSettingsSyntax = " + info.getDeviceScanSettingsSyntax() + "\n"); logger.info(sb.toString()); } }
gpl-3.0
hairymunky/golg
golg/editor/dialogs/scroll_picker.cc
5830
/********************************************************************** Golgotha Forever - A portable, free 3D strategy and FPS game. Copyright (C) 1999 Golgotha Forever Developers Sources contained in this distribution were derived from Crack Dot Com's public release of Golgotha which can be found here: http://www.crack.com All changes and new works are licensed under the GPL: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA For the full license, see COPYING. ***********************************************************************/ #include "editor/e_state.hh" #include "gui/scroll_bar.hh" #include "editor/dialogs/scroll_picker.hh" #include "window/style.hh" #include "gui/button.hh" #include "tmanage.hh" #include "r1_api.hh" #include "tile.hh" #include "g1_render.hh" void g1_scroll_picker_class::create_windows() { for (int i=0; i<windows.size(); i++) delete render_windows[i]; windows.clear(); render_windows.clear(); int y=start_y; int obj_size=info->object_size; int on=info->scroll_offset; int tb=0; int objs_per_line=info->max_object_size/obj_size; int done=0; while (y+obj_size<=height() && !done) { int x=0; while (x+obj_size<=info->max_object_size && !done) { i4_window_class *w=create_window(obj_size, obj_size, on); if (!w) done=1; else { r1_render_window_class *rwin; rwin=g1_render.r_api->create_render_window(obj_size, obj_size, R1_COPY_1x1); windows.add(w); render_windows.add(rwin); rwin->add_child(0,0, w); add_child(x, y, rwin); on++; tb++; x+=obj_size; } } y+=obj_size; } if (scroll_bar) scroll_bar->set_new_total((total_objects()+objs_per_line-1)/objs_per_line); } g1_scroll_picker_class::g1_scroll_picker_class(i4_graphical_style_class *style, w32 option_flags, g1_scroll_picker_info *info, int total_objects) : i4_color_window_class(0,0, style->color_hint->neutral(), style), windows(16,16), render_windows(16,16), info(info) { if (option_flags & (1<<ROTATE)) add_child(0,0, g1_edit_state.create_button("tp_rotate", ROTATE, i4_T, this)); if (option_flags & (1<<MIRROR)) add_child(0,0, g1_edit_state.create_button("tp_mirror", MIRROR, i4_T, this)); if (option_flags & (1<<GROW)) add_child(0,0, g1_edit_state.create_button("tp_grow", GROW, i4_T, this)); if (option_flags & (1<<SHRINK)) add_child(0,0, g1_edit_state.create_button("tp_shrink", SHRINK, i4_T, this)); arrange_down_right(); resize_to_fit_children(); int scroll_area_height=info->max_object_size * info->max_objects_down, scroll_area_width=info->max_object_size; start_y=height(); if (option_flags & (1<<SCROLL)) { scroll_bar = new i4_scroll_bar(i4_T, scroll_area_height, scroll_area_height/info->object_size, total_objects, SCROLL, this, style); scroll_area_width += scroll_bar->width(); } else scroll_bar = 0; resize(scroll_area_width > width() ? scroll_area_width : width(), scroll_area_height + height()); if (scroll_bar) add_child(width()-scroll_bar->width(), start_y, scroll_bar); } void g1_scroll_picker_class::parent_draw(i4_draw_context_class &context) { i4_color_window_class::parent_draw(context); r1_texture_manager_class *tman=g1_render.r_api->get_tmanager(); tman->next_frame(); } void g1_scroll_picker_class::receive_event(i4_event *ev) { if (ev->type()==i4_event::USER_MESSAGE) { CAST_PTR(sm, i4_scroll_message, ev); if (sm->sub_type==SCROLL) { int obj_size=info->object_size; int objs_per_line=info->max_object_size/obj_size; int off=sm->amount * objs_per_line; if (off>=total_objects()) off-=objs_per_line; info->scroll_offset=off; for (int i=0; i<windows.size(); i++) change_window_object_num(windows[i], off+i); } } else if (ev->type()==i4_event::OBJECT_MESSAGE) { CAST_PTR(om, i4_object_message_event_class, ev); switch (om->sub_type) { case GROW : { if (info->object_size*2<=info->max_object_size) { info->scroll_offset=0; info->object_size*=2; create_windows(); } } break; case SHRINK : { if (info->object_size/2>=info->min_object_size) { info->scroll_offset=0; info->object_size/=2; create_windows(); } } break; case MIRROR : { mirror(); refresh(); } break; case ROTATE : { rotate(); refresh(); } break; } } else i4_parent_window_class::receive_event(ev); } void g1_scroll_picker_class::refresh() { for (int i=0; i<windows.size(); i++) windows[i]->request_redraw(i4_F); }
gpl-3.0
darlinghq/darling
src/frameworks/CoreServices/src/CarbonCore/Multiprocessing.cpp
2383
/* This file is part of Darling. Copyright (C) 2012-2013 Lubos Dolezel Darling is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Darling is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Darling. If not, see <http://www.gnu.org/licenses/>. */ #include <CoreServices/Multiprocessing.h> #include <unistd.h> #include <ctime> #include <pthread.h> #include <CoreServices/MacErrors.h> Boolean _MPIsFullyInitialized() { return true; } OSStatus MPDelayUntil(AbsoluteTime* time) { struct timespec ts = { time_t(*reinterpret_cast<uint64_t*>(time) / 1000000000ll), long(*reinterpret_cast<uint64_t*>(time) % 1000000000ll) }; nanosleep(&ts, nullptr); return noErr; } unsigned long MPProcessors() { return sysconf(_SC_NPROCESSORS_ONLN); } OSStatus MPCreateCriticalRegion(MPCriticalRegionID* criticalRegion) { pthread_mutex_t* pp = new pthread_mutex_t; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); *criticalRegion = pp; pthread_mutex_init(pp, &attr); return noErr; } OSStatus MPDeleteCriticalRegion(MPCriticalRegionID criticalRegion) { pthread_mutex_t* pp = (pthread_mutex_t*) criticalRegion; if (pp != nullptr) { pthread_mutex_destroy(pp); delete pp; } return noErr; } OSStatus MPEnterCriticalRegion(MPCriticalRegionID criticalRegion, Duration timeout) { pthread_mutex_t* pp = (pthread_mutex_t*) criticalRegion; if (!pp) return paramErr; if (timeout == kDurationForever) { pthread_mutex_lock(pp); return noErr; } else { do { if (pthread_mutex_trylock(pp) == 0) return noErr; if (timeout > 0) { usleep(10*1000); timeout -= 10; } } while (timeout > 0); return kMPTimeoutErr; } } OSStatus MPExitCriticalRegion(MPCriticalRegionID criticalRegion) { pthread_mutex_t* pp = (pthread_mutex_t*) criticalRegion; if (pp != nullptr) { pthread_mutex_unlock(pp); return noErr; } else return paramErr; }
gpl-3.0
Pisti03/Snake
src/test/java/hu/unideb/inf/snake/PositionTest.java
2263
package hu.unideb.inf.snake; /* * #%L * Snake * %% * Copyright (C) 2016 University of Debrecen, Faculty of Informatics * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import hu.unideb.inf.snake.model.Position; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Kokas István */ public class PositionTest { private static Position pos; @BeforeClass public static void setUpClass() { pos = new Position(1, 2); } @AfterClass public static void tearDownClass() { pos = null; } @Test public void testToString() { assertEquals(pos.toString(), "Position{x=1, y=2}"); } @Test public void testRandomize() { Position pos2 = new Position(pos); pos2.randomize(0, 30); assertNotEquals(pos, pos2); } @Test public void testEquals() { Position teszt = null; Position teszt2 = new Position(); String position = "ez nem egy pozicio"; assertFalse(teszt2.equals(teszt)); assertFalse(teszt2.equals(position)); Position teszt3 = new Position(); assertEquals(teszt3, teszt2); } @Test public void testSetValue() { Position teszt = new Position(5, 6); Position teszt2 = new Position(7, 8); assertEquals(5, teszt.getX()); assertEquals(6, teszt.getY()); teszt.setValue(teszt2); assertEquals(7, teszt.getX()); assertEquals(8, teszt.getY()); } }
gpl-3.0
nadoo/glider
rule/check.go
2909
package rule import ( "crypto/tls" "errors" "fmt" "io" "net" "os" "os/exec" "regexp" "strings" "time" "github.com/nadoo/glider/pkg/pool" "github.com/nadoo/glider/proxy" ) // Checker is a forwarder health checker. type Checker interface { Check(dialer proxy.Dialer) (elap time.Duration, err error) } type tcpChecker struct { addr string timeout time.Duration } func newTcpChecker(addr string, timeout time.Duration) *tcpChecker { if _, port, _ := net.SplitHostPort(addr); port == "" { addr = net.JoinHostPort(addr, "80") } return &tcpChecker{addr, timeout} } // Check implements the Checker interface. func (c *tcpChecker) Check(dialer proxy.Dialer) (time.Duration, error) { startTime := time.Now() rc, err := dialer.Dial("tcp", c.addr) if err != nil { return 0, err } rc.Close() return time.Since(startTime), nil } type httpChecker struct { addr string uri string expect string timeout time.Duration tlsConfig *tls.Config serverName string regex *regexp.Regexp } func newHttpChecker(addr, uri, expect string, timeout time.Duration, withTLS bool) *httpChecker { c := &httpChecker{ addr: addr, uri: uri, expect: expect, timeout: timeout, regex: regexp.MustCompile(expect), } if _, p, _ := net.SplitHostPort(addr); p == "" { if withTLS { c.addr = net.JoinHostPort(addr, "443") } else { c.addr = net.JoinHostPort(addr, "80") } } c.serverName = c.addr[:strings.LastIndex(c.addr, ":")] if withTLS { c.tlsConfig = &tls.Config{ServerName: c.serverName} } return c } // Check implements the Checker interface. func (c *httpChecker) Check(dialer proxy.Dialer) (time.Duration, error) { startTime := time.Now() rc, err := dialer.Dial("tcp", c.addr) if err != nil { return 0, err } if c.tlsConfig != nil { tlsConn := tls.Client(rc, c.tlsConfig) if err := tlsConn.Handshake(); err != nil { tlsConn.Close() return 0, err } rc = tlsConn } defer rc.Close() if c.timeout > 0 { rc.SetDeadline(time.Now().Add(c.timeout)) } if _, err = io.WriteString(rc, "GET "+c.uri+" HTTP/1.1\r\nHost:"+c.serverName+"\r\n\r\n"); err != nil { return 0, err } r := pool.GetBufReader(rc) defer pool.PutBufReader(r) line, err := r.ReadString('\n') if err != nil { return 0, err } if !c.regex.MatchString(line) { return 0, fmt.Errorf("expect: %s, got: %s", c.expect, line) } elapsed := time.Since(startTime) if elapsed > c.timeout { return elapsed, errors.New("timeout") } return elapsed, nil } type fileChecker struct{ path string } func newFileChecker(path string) *fileChecker { return &fileChecker{path} } // Check implements the Checker interface. func (c *fileChecker) Check(dialer proxy.Dialer) (time.Duration, error) { cmd := exec.Command(c.path) cmd.Stdout = os.Stdout cmd.Env = os.Environ() cmd.Env = append(cmd.Env, "FORWARDER_ADDR="+dialer.Addr()) return 0, cmd.Run() }
gpl-3.0
ramsodev/DitaManagement
dita/dita.map/src/net/ramso/dita/map/ItemgroupClass.java
16653
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.08.02 at 08:10:00 PM CEST // package net.ramso.dita.map; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for itemgroup.class complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="itemgroup.class"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}itemgroup.content"/> * &lt;/sequence> * &lt;attGroup ref="{}itemgroup.attributes"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "itemgroup.class", propOrder = { "content" }) @XmlSeeAlso({ Itemgroup.class }) public class ItemgroupClass { @XmlElementRefs({ @XmlElementRef(name = "ul", type = Ul.class, required = false), @XmlElementRef(name = "pre", type = Pre.class, required = false), @XmlElementRef(name = "q", type = Q.class, required = false), @XmlElementRef(name = "ph", type = Ph.class, required = false), @XmlElementRef(name = "simpletable", type = Simpletable.class, required = false), @XmlElementRef(name = "boolean", type = Boolean.class, required = false), @XmlElementRef(name = "fn", type = Fn.class, required = false), @XmlElementRef(name = "xref", type = Xref.class, required = false), @XmlElementRef(name = "term", type = Term.class, required = false), @XmlElementRef(name = "sl", type = Sl.class, required = false), @XmlElementRef(name = "unknown", type = Unknown.class, required = false), @XmlElementRef(name = "p", type = P.class, required = false), @XmlElementRef(name = "draft-comment", type = DraftComment.class, required = false), @XmlElementRef(name = "lines", type = Lines.class, required = false), @XmlElementRef(name = "required-cleanup", type = RequiredCleanup.class, required = false), @XmlElementRef(name = "keyword", type = Keyword.class, required = false), @XmlElementRef(name = "data", type = Data.class, required = false), @XmlElementRef(name = "fig", type = Fig.class, required = false), @XmlElementRef(name = "tm", type = Tm.class, required = false), @XmlElementRef(name = "table", type = Table.class, required = false), @XmlElementRef(name = "indexterm", type = Indexterm.class, required = false), @XmlElementRef(name = "image", type = Image.class, required = false), @XmlElementRef(name = "note", type = Note.class, required = false), @XmlElementRef(name = "lq", type = Lq.class, required = false), @XmlElementRef(name = "ol", type = Ol.class, required = false), @XmlElementRef(name = "object", type = net.ramso.dita.map.Object.class, required = false), @XmlElementRef(name = "indextermref", type = Indextermref.class, required = false), @XmlElementRef(name = "data-about", type = DataAbout.class, required = false), @XmlElementRef(name = "cite", type = Cite.class, required = false), @XmlElementRef(name = "state", type = State.class, required = false), @XmlElementRef(name = "foreign", type = Foreign.class, required = false), @XmlElementRef(name = "dl", type = Dl.class, required = false) }) @XmlMixed protected List<java.lang.Object> content; @XmlAttribute(name = "outputclass") protected String outputclass; @XmlAttribute(name = "xtrc") protected String xtrc; @XmlAttribute(name = "xtrf") protected String xtrf; @XmlAttribute(name = "translate") protected YesnoAttClass translate; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "dir") protected DirAttsClass dir; @XmlAttribute(name = "base") protected String base; @XmlAttribute(name = "rev") protected String rev; @XmlAttribute(name = "importance") protected ImportanceAttsClass importance; @XmlAttribute(name = "status") protected StatusAttsClass status; @XmlAttribute(name = "props") protected String props; @XmlAttribute(name = "platform") protected String platform; @XmlAttribute(name = "product") protected String product; @XmlAttribute(name = "audience") protected String audienceMod; @XmlAttribute(name = "otherprops") protected String otherprops; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String id; @XmlAttribute(name = "conref") protected String conref; @XmlAttribute(name = "conrefend") protected String conrefend; @XmlAttribute(name = "conaction") protected ConactionAttClass conaction; @XmlAttribute(name = "conkeyref") protected String conkeyref; /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Ul } * {@link Pre } * {@link Q } * {@link Ph } * {@link Simpletable } * {@link Boolean } * {@link Fn } * {@link Xref } * {@link Term } * {@link Sl } * {@link Unknown } * {@link P } * {@link DraftComment } * {@link Lines } * {@link RequiredCleanup } * {@link Keyword } * {@link Data } * {@link Fig } * {@link Tm } * {@link Table } * {@link Indexterm } * {@link Image } * {@link Note } * {@link Ol } * {@link Lq } * {@link net.ramso.dita.map.Object } * {@link Indextermref } * {@link DataAbout } * {@link Cite } * {@link String } * {@link State } * {@link Foreign } * {@link Dl } * * */ public List<java.lang.Object> getContent() { if (content == null) { content = new ArrayList<java.lang.Object>(); } return this.content; } /** * Gets the value of the outputclass property. * * @return * possible object is * {@link String } * */ public String getOutputclass() { return outputclass; } /** * Sets the value of the outputclass property. * * @param value * allowed object is * {@link String } * */ public void setOutputclass(String value) { this.outputclass = value; } /** * Gets the value of the xtrc property. * * @return * possible object is * {@link String } * */ public String getXtrc() { return xtrc; } /** * Sets the value of the xtrc property. * * @param value * allowed object is * {@link String } * */ public void setXtrc(String value) { this.xtrc = value; } /** * Gets the value of the xtrf property. * * @return * possible object is * {@link String } * */ public String getXtrf() { return xtrf; } /** * Sets the value of the xtrf property. * * @param value * allowed object is * {@link String } * */ public void setXtrf(String value) { this.xtrf = value; } /** * Gets the value of the translate property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getTranslate() { return translate; } /** * Sets the value of the translate property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setTranslate(YesnoAttClass value) { this.translate = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link DirAttsClass } * */ public DirAttsClass getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link DirAttsClass } * */ public void setDir(DirAttsClass value) { this.dir = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the rev property. * * @return * possible object is * {@link String } * */ public String getRev() { return rev; } /** * Sets the value of the rev property. * * @param value * allowed object is * {@link String } * */ public void setRev(String value) { this.rev = value; } /** * Gets the value of the importance property. * * @return * possible object is * {@link ImportanceAttsClass } * */ public ImportanceAttsClass getImportance() { return importance; } /** * Sets the value of the importance property. * * @param value * allowed object is * {@link ImportanceAttsClass } * */ public void setImportance(ImportanceAttsClass value) { this.importance = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusAttsClass } * */ public StatusAttsClass getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusAttsClass } * */ public void setStatus(StatusAttsClass value) { this.status = value; } /** * Gets the value of the props property. * * @return * possible object is * {@link String } * */ public String getProps() { return props; } /** * Sets the value of the props property. * * @param value * allowed object is * {@link String } * */ public void setProps(String value) { this.props = value; } /** * Gets the value of the platform property. * * @return * possible object is * {@link String } * */ public String getPlatform() { return platform; } /** * Sets the value of the platform property. * * @param value * allowed object is * {@link String } * */ public void setPlatform(String value) { this.platform = value; } /** * Gets the value of the product property. * * @return * possible object is * {@link String } * */ public String getProduct() { return product; } /** * Sets the value of the product property. * * @param value * allowed object is * {@link String } * */ public void setProduct(String value) { this.product = value; } /** * Gets the value of the audienceMod property. * * @return * possible object is * {@link String } * */ public String getAudienceMod() { return audienceMod; } /** * Sets the value of the audienceMod property. * * @param value * allowed object is * {@link String } * */ public void setAudienceMod(String value) { this.audienceMod = value; } /** * Gets the value of the otherprops property. * * @return * possible object is * {@link String } * */ public String getOtherprops() { return otherprops; } /** * Sets the value of the otherprops property. * * @param value * allowed object is * {@link String } * */ public void setOtherprops(String value) { this.otherprops = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the conref property. * * @return * possible object is * {@link String } * */ public String getConref() { return conref; } /** * Sets the value of the conref property. * * @param value * allowed object is * {@link String } * */ public void setConref(String value) { this.conref = value; } /** * Gets the value of the conrefend property. * * @return * possible object is * {@link String } * */ public String getConrefend() { return conrefend; } /** * Sets the value of the conrefend property. * * @param value * allowed object is * {@link String } * */ public void setConrefend(String value) { this.conrefend = value; } /** * Gets the value of the conaction property. * * @return * possible object is * {@link ConactionAttClass } * */ public ConactionAttClass getConaction() { return conaction; } /** * Sets the value of the conaction property. * * @param value * allowed object is * {@link ConactionAttClass } * */ public void setConaction(ConactionAttClass value) { this.conaction = value; } /** * Gets the value of the conkeyref property. * * @return * possible object is * {@link String } * */ public String getConkeyref() { return conkeyref; } /** * Sets the value of the conkeyref property. * * @param value * allowed object is * {@link String } * */ public void setConkeyref(String value) { this.conkeyref = value; } }
gpl-3.0
gohdan/DFC
known_files/hashes/bitrix/modules/sale/payment/qiwi/en/qiwi.php
61
Bitrix 16.5 Business Demo = 42aec6751144ef758a2bd513af19dfbf
gpl-3.0
mon2au/invoicebinder
invoicebinderhome/src/main/java/com/invoicebinderhome/server/service/DownloadServiceImpl.java
1242
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.invoicebinderhome.server.service; import com.invoicebinderhome.client.service.download.DownloadService; import com.invoicebinderhome.server.serversettings.ServerSettingsManager; import com.invoicebinderhome.shared.model.DownloadInfo; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * * @author mon2 */ @SuppressWarnings("serial") @Transactional(rollbackFor = RuntimeException.class) @Service("download") public class DownloadServiceImpl extends RemoteServiceServlet implements DownloadService { @Override public DownloadInfo getDownloadInfo() { DownloadInfo info = new DownloadInfo(); info.setBuildDate(ServerSettingsManager.BuildInformation.getBuildDate()); info.setDownloadVersion(ServerSettingsManager.BuildInformation.getBuildVersion()); info.setDownloadCount(ServerSettingsManager.AppConfiguration.getDownloadCount()); return info; } }
gpl-3.0
JavidTeam/TeleJavid
plugins/fun.lua
16878
--Begin Fun.lua By @Javid_Team --Special Thx To @Ali_K_1999 -------------------------------- local function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') return result end -------------------------------- local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" -------------------------------- local function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -------------------------------- local function get_staticmap(area) local api = base_api .. "/staticmap?" local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale == "locality" then zoom=8 elseif scale == "country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~= nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end -------------------------------- local function get_weather(location) print("Finding weather in ", location) local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local url = BASE_URL url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b' url = url..'&units=metric' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'دمای شهر '..city..' هم اکنون '..weather.main.temp..' درجه سانتی گراد می باشد\n____________________' local conditions = 'شرایط فعلی آب و هوا : ' if weather.weather[1].main == 'Clear' then conditions = conditions .. 'آفتابی☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. 'ابری ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. 'بارانی ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. 'طوفانی ☔☔☔☔' elseif weather.weather[1].main == 'Mist' then conditions = conditions .. 'مه 💨' end return temp .. '\n' .. conditions end -------------------------------- local function calc(exp) url = 'http://api.mathjs.org/v1/' url = url..'?expr='..URL.escape(exp) b,c = http.request(url) text = nil if c == 200 then text = 'Result = '..b..'\n____________________'..msg_caption elseif c == 400 then text = b else text = 'Unexpected error\n' ..'Is api.mathjs.org up?' end return text end -------------------------------- function exi_file(path, suffix) local files = {} local pth = tostring(path) local psv = tostring(suffix) for k, v in pairs(scandir(pth)) do if (v:match('.'..psv..'$')) then table.insert(files, v) end end return files end -------------------------------- function file_exi(name, path, suffix) local fname = tostring(name) local pth = tostring(path) local psv = tostring(suffix) for k,v in pairs(exi_file(pth, psv)) do if fname == v then return true end end return false end -------------------------------- function run(msg, matches) local Chash = "cmd_lang:"..msg.to.id local Clang = redis:get(Chash) if (matches[1]:lower() == 'calc' and not Clang) or (matches[1]:lower() == 'ماشین حساب' and Clang) and matches[2] then if msg.to.type == "pv" then return end return calc(matches[2]) end -------------------------------- if (matches[1]:lower() == 'praytime' and not Clang) or (matches[1]:lower() == 'ساعات شرعی' and Clang) then if matches[2] then city = matches[2] elseif not matches[2] then city = 'Tehran' end local lat,lng,url = get_staticmap(city) local dumptime = run_bash('date +%s') local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7') local jdat = json:decode(code) local data = jdat.data.timings local text = 'شهر: '..city text = text..'\nاذان صبح: '..data.Fajr text = text..'\nطلوع آفتاب: '..data.Sunrise text = text..'\nاذان ظهر: '..data.Dhuhr text = text..'\nغروب آفتاب: '..data.Sunset text = text..'\nاذان مغرب: '..data.Maghrib text = text..'\nعشاء : '..data.Isha text = text..msg_caption return tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html') end -------------------------------- if (matches[1]:lower() == 'tophoto' and not Clang) or (matches[1]:lower() == 'تبدیل به عکس' and Clang) and msg.reply_id then function tophoto(arg, data) function tophoto_cb(arg,data) if data.content_.sticker_ then local file = data.content_.sticker_.sticker_.path_ local secp = tostring(tcpath)..'/data/sticker/' local ffile = string.gsub(file, '-', '') local fsecp = string.gsub(secp, '-', '') local name = string.gsub(ffile, fsecp, '') local sname = string.gsub(name, 'webp', 'jpg') local pfile = 'data/photos/'..sname local pasvand = 'webp' local apath = tostring(tcpath)..'/data/sticker' if file_exi(tostring(name), tostring(apath), tostring(pasvand)) then os.rename(file, pfile) tdcli.sendPhoto(msg.to.id, 0, 0, 1, nil, pfile, msg_caption, dl_cb, nil) else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This sticker does not exist. Send sticker again._'..msg_caption, 1, 'md') end else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This is not a sticker._', 1, 'md') end end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, tophoto_cb, nil) end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_id }, tophoto, nil) end -------------------------------- if (matches[1]:lower() == 'tosticker' and not Clang) or (matches[1]:lower() == 'تبدیل به استیکر' and Clang) and msg.reply_id then function tosticker(arg, data) function tosticker_cb(arg,data) if data.content_.ID == 'MessagePhoto' then file = data.content_.photo_.id_ local pathf = tcpath..'/data/photo/'..file..'_(1).jpg' local pfile = 'data/photos/'..file..'.webp' if file_exi(file..'_(1).jpg', tcpath..'/data/photo', 'jpg') then os.rename(pathf, pfile) tdcli.sendDocument(msg.chat_id_, 0, 0, 1, nil, pfile, msg_caption, dl_cb, nil) else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This photo does not exist. Send photo again._', 1, 'md') end else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This is not a photo._', 1, 'md') end end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, tosticker_cb, nil) end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_id }, tosticker, nil) end -------------------------------- if (matches[1]:lower() == 'weather' and not Clang) or (matches[1]:lower() == 'اب و هوا' and Clang) then city = matches[2] local wtext = get_weather(city) if not wtext then wtext = 'مکان وارد شده صحیح نیست' end return wtext end -------------------------------- if (matches[1]:lower() == 'time' and not Clang) or (matches[1]:lower() == 'ساعت' and Clang) then local url , res = http.request('http://irapi.ir/time/') if res ~= 200 then return "No connection" end local colors = {'blue','green','yellow','magenta','Orange','DarkOrange','red'} local fonts = {'mathbf','mathit','mathfrak','mathrm'} local jdat = json:decode(url) local url = 'http://latex.codecogs.com/png.download?'..'\\dpi{600}%20\\huge%20\\'..fonts[math.random(#fonts)]..'{{\\color{'..colors[math.random(#colors)]..'}'..jdat.ENtime..'}}' local file = download_to_file(url,'time.webp') tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil) end -------------------------------- if (matches[1]:lower() == 'voice' and not Clang) or (matches[1]:lower() == 'تبدیل به صدا' and Clang) then local text = matches[2] textc = text:gsub(' ','.') if msg.to.type == 'pv' then return nil else local url = "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&text="..textc local file = download_to_file(url,'TeleJavid.mp3') tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil) end end -------------------------------- if (matches[1]:lower() == 'tr' and not Clang) or (matches[1]:lower() == 'ترجمه' and Clang) then url = https.request('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20160119T111342Z.fd6bf13b3590838f.6ce9d8cca4672f0ed24f649c1b502789c9f4687a&format=plain&lang='..URL.escape(matches[2])..'&text='..URL.escape(matches[3])) data = json:decode(url) return 'زبان : '..data.lang..'\nترجمه : '..data.text[1]..'\n____________________'..msg_caption end -------------------------------- if (matches[1]:lower() == 'short' and not Clang) or (matches[1]:lower() == 'لینک کوتاه' and Clang) then if matches[2]:match("[Hh][Tt][Tt][Pp][Ss]://") then shortlink = matches[2] elseif not matches[2]:match("[Hh][Tt][Tt][Pp][Ss]://") then shortlink = "https://"..matches[2] end local yon = http.request('http://api.yon.ir/?url='..URL.escape(shortlink)) local jdat = json:decode(yon) local bitly = https.request('https://api-ssl.bitly.com/v3/shorten?access_token=f2d0b4eabb524aaaf22fbc51ca620ae0fa16753d&longUrl='..URL.escape(shortlink)) local data = json:decode(bitly) local u2s = http.request('http://u2s.ir/?api=1&return_text=1&url='..URL.escape(shortlink)) local llink = http.request('http://llink.ir/yourls-api.php?signature=a13360d6d8&action=shorturl&url='..URL.escape(shortlink)..'&format=simple') local text = ' 🌐لینک اصلی :\n'..check_markdown(data.data.long_url)..'\n\nلینکهای کوتاه شده با 6 سایت کوتاه ساز لینک : \n》کوتاه شده با bitly :\n___________________________\n'..(check_markdown(data.data.url) or '---')..'\n___________________________\n》کوتاه شده با u2s :\n'..(check_markdown(u2s) or '---')..'\n___________________________\n》کوتاه شده با llink : \n'..(check_markdown(llink) or '---')..'\n___________________________\n》لینک کوتاه شده با yon : \nyon.ir/'..(check_markdown(jdat.output) or '---')..'\n____________________'..msg_caption return tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html') end -------------------------------- if (matches[1]:lower() == 'sticker' and not Clang) or (matches[1]:lower() == 'استیکر' and Clang) then local eq = URL.escape(matches[2]) local w = "500" local h = "500" local txtsize = "100" local txtclr = "ff2e4357" if matches[3] then txtclr = matches[3] end if matches[4] then txtsize = matches[4] end if matches[5] and matches[6] then w = matches[5] h = matches[6] end local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc" local receiver = msg.to.id local file = download_to_file(url,'text.webp') tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil) end -------------------------------- if (matches[1]:lower() == 'عکس' and not Clang) or (matches[1]:lower() == 'عکس' and Clang) then local eq = URL.escape(matches[2]) local w = "500" local h = "500" local txtsize = "100" local txtclr = "ff2e4357" if matches[3] then txtclr = matches[3] end if matches[4] then txtsize = matches[4] end if matches[5] and matches[6] then w = matches[5] h = matches[6] end local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc" local receiver = msg.to.id local file = download_to_file(url,'text.jpg') tdcli.sendPhoto(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil) end -------------------------------- if matches[1] == "helpfun" and not Clang then local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not lang then helpfun_en = [[ _TeleJavid Fun Help Commands:_ *!time* _Get time in a sticker_ *!short* `[link]` _Make short url_ *!voice* `[text]` _Convert text to voice_ *!tr* `[lang] [word]` _Translates FA to EN and EN to FA_ _Example:_ *!tr fa hi* *!sticker* `[word]` _Convert text to sticker_ *!photo* `[word]` _Convert text to photo_ *!calc* `[number]` Calculator *!praytime* `[city]` _Get Patent (Pray Time)_ *!tosticker* `[reply]` _Convert photo to sticker_ *!tophoto* `[reply]` _Convert text to photo_ *!weather* `[city]` _Get weather_ *Good luck ;)*]] else helpfun_en = [[ _راهنمای فان ربات جاوید:_ *!time* _دریافت ساعت به صورت استیکر_ *!short* `[link]` _کوتاه کننده لینک_ *!voice* `[text]` _تبدیل متن به صدا_ *!tr* `[lang]` `[word]` _ترجمه متن فارسی به انگلیسی وبرعکس_ _مثال:_ _!tr en سلام_ *!sticker* `[word]` _تبدیل متن به استیکر_ *!photo* `[word]` _تبدیل متن به عکس_ *!calc* `[number]` _ماشین حساب_ *!praytime* `[city]` _اعلام ساعات شرعی_ *!tosticker* `[reply]` _تبدیل عکس به استیکر_ *!tophoto* `[reply]` _تبدیل استیکر‌به عکس_ *!weather* `[city]` _دریافت اب وهوا_ موفق باشید ;)]] end return helpfun_en..msg_caption end if matches[1] == "راهنمای سرگرمی" and Clang then local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not lang then helpfun_fa = [[ _TeleJavid Fun Help Commands:_ *ساعت* _Get time in a sticker_ *لینک کوتاه* `[لینک]` _Make short url_ *تبدیل به صدا* `[متن]` _Convert text to voice_ *ترجمه* `[زبان] [کلمه]` _Translates FA to EN and EN to FA_ _Example:_ *ترجمه hi fa* *استیکر* `[متن]` _Convert text to sticker_ *عکس* `[متن]` _Convert text to photo_ *ماشین حساب* `[معادله]` Calculator *ساعات شرعی* `[شهر]` _Get Patent (Pray Time)_ *تبدیل به استیکر* `[ریپلی]` _Convert photo to sticker_ *تبدیل به عکس* `[ریپلی]` _Convert text to photo_ *اب و هوا* `[شهر]` _Get weather_ *Good luck ;)*]] else helpfun_fa = [[ _راهنمای فان ربات جاوید:_ *ساعت* _دریافت ساعت به صورت استیکر_ *لینک کوتاه* `[لینک]` _کوتاه کننده لینک_ *تبدیل به صدا* `[متن]` _تبدیل متن به صدا_ *ترجمه* `[زبان]` `[متن]` _ترجمه متن فارسی به انگلیسی وبرعکس_ _مثال:_ _ترجمه en سلام_ *استیکر* `[متن]` _تبدیل متن به استیکر_ *استیکر* `[متن]` _تبدیل متن به عکس_ *ماشین حساب* `[معادله]` _ماشین حساب_ *ساعات شرعی* `[شهر]` _اعلام ساعات شرعی_ *تبدیل به استیکر* `[ریپلی]` _تبدیل عکس به استیکر_ *تبدیل به عکس* `[ریپلی]` _تبدیل استیکر‌به عکس_ *اب و هوا* `[شهر]` _دریافت اب وهوا_ موفق باشید ;)]] end return helpfun_fa..msg_caption end end -------------------------------- return { patterns = { "^(helpfun)$", "^(weather) (.*)$", "^(calc) (.*)$", "^(time)$", "^(tophoto)$", "^(tosticker)$", "^(voice) +(.*)$", "^([Pp]raytime) (.*)$", "^(praytime)$", "^([Tt]r) ([^%s]+) (.*)$", "^([Ss]hort) (.*)$", "^(photo) (.+)$", "^(sticker) (.+)$", "^(راهنمای سرگرمی)$", "^(اب و هوا) (.*)$", "^(ماشین حساب) (.*)$", "^(ساعت)$", "^(تبدیل به عکس)$", "^(تبدیل به استیکر)$", "^(تبدیل به صدا) +(.*)$", "^(ساعات شرعی) (.*)$", "^(ساعات شرعی)$", "^(ترجمه) ([^%s]+) (.*)$", "^(لینک کوتاه) (.*)$", "^(عکس) (.+)$", "^(استیکر) (.+)$" }, run = run, } --#by @Javid_Team :)
gpl-3.0
cryogenic-dreams/StarCraft-GPBot
GPBot/src/nonTerminal/TechTree.java
751
package nonTerminal; import ec.EvolutionState; import ec.Problem; import ec.gp.ADFStack; import ec.gp.GPData; import ec.gp.GPIndividual; import ec.gp.GPNode; public class TechTree extends GPNode { /** * */ private static final long serialVersionUID = 1; public String toString() { return "techtree";// This is for the visual representation } @Override public String name() { return "techtree";// this is for the magic } public int expectedChildren() { return 1;// this } public void eval(final EvolutionState state, final int thread, final GPData input, final ADFStack stack, final GPIndividual individual, final Problem problem) { children[0].eval(state, thread, input, stack, individual, problem); } }
gpl-3.0
VulpesCorsac/ANGEL
V 0.5.0 (Shaman)/Equipment/Generator/DS345/DS345.cpp
11643
#include "DS345.h" DS345::DS345() { this->serial = nullptr; } DS345::DS345(const QString &portName, const int &new_baudrate) { this->serial = nullptr; setConnection(portName, new_baudrate); } DS345::~DS345() { if (this->serial->isOpen()) this->serial->close(); this->serial->~QSerialPort(); } QSerialPort* DS345::getSerial() const { return this->serial; } void DS345::setSerial(QSerialPort *new_serial) { this->serial = new_serial; } bool DS345::setConnection(const QString &portName, const int &new_baudrate) { if (this->isActive()) return true; if (this->serial == nullptr) this->serial = new QSerialPort(this); this->serial->setPortName(portName); if (isValidBaudrate(new_baudrate)) this->serial->setBaudRate((qint32) new_baudrate); else return false; this->serial->setParity(QSerialPort::NoParity); this->serial->setDataBits(QSerialPort::Data8); this->serial->setStopBits(QSerialPort::TwoStop); if (!this->serial->open(QIODevice::ReadWrite)) { QSerialPort::SerialPortError error; this->serial->error(error); emit this->errorSignal(tr("Can't open %1, error code %2").arg(portName).arg(serial->error())); return false; } else { QString idn; return getIDN(idn); } } void DS345::disconnect() const { if (this->serial->isOpen()) this->serial->close(); } bool DS345::isValidBaudrate(const int &new_baudrate) const { if (new_baudrate == 1200 || new_baudrate == 2400 || new_baudrate == 4800 || new_baudrate == 9600) return true; return false; } bool DS345::changeBaudrate(const int &new_baudrate) { if (!isValidBaudrate(new_baudrate)) return false; if (!this->serial->isOpen()) { this->serial->setBaudRate((qint32) new_baudrate); return true; } else { this->serial->close(); return setConnection(this->serial->portName(), new_baudrate); } } bool DS345::isActive() const { QString idn; if (getIDN(idn)) return true; return false; } bool DS345::send(const QString &command, QString &response, const bool &wait_for_response) const { emit this->commandSignal(command); response = ""; if (this->serial == nullptr || !this->serial->isOpen()) return false; QString modyfiedCommand = command.trimmed() + "\n"; serial->write(modyfiedCommand.toLocal8Bit()); if (serial->waitForBytesWritten(defaultWriteTimeout)) { if (wait_for_response) { if (this->serial->waitForReadyRead(defaultReadTimeout)) { QByteArray responseData = serial->readAll(); while (this->serial->waitForReadyRead(defaultReadWaitTimeout)) responseData += serial->readAll(); response = QString(responseData); emit this->responseSignal(response); return true; } else { emit this->timeoutSignal(tr("Wait write request timeout %1").arg(QTime::currentTime().toString())); return false; } } else return true; } else { emit this->timeoutSignal(tr("Wait write request timeout %1").arg(QTime::currentTime().toString())); return false; } } bool DS345::sendCommand(const QString &command) const { QString response; return send(command, response, false); } bool DS345::sendQuery(const QString &command, QString &response) const { return send(command, response, true); } bool DS345::getIDN(QString &idn) const { return sendQuery("*IDN?", idn); } bool DS345::correctAmplitudeType(const QString &type) const { if (type.trimmed() == "VR" || type.trimmed() == "VP" || type.trimmed() == "DB") return true; return false; } bool DS345::setAmplitude(const double &new_amplitude, const QString &type) const { QString command = "AMLP " + QString::number(new_amplitude) + " "; if (correctAmplitudeType(type)) command += type.trimmed(); else return false; return sendCommand(command); } double DS345::getAmplitude(QString &type) const { QString response; QString command = "AMPL? "; if (correctAmplitudeType(type)) command += type.trimmed(); if (!sendQuery(command, response)) return -1; if (correctAmplitudeType(type)) type = response.right(2); return response.trimmed().left(response.length() - 2).toDouble(); } bool DS345::setFrequency(const double &new_frequency) const { QString command = "FREQ " + QString::number(new_frequency); return sendCommand(command); } double DS345::getFrequency() const { QString response; QString command = "FREQ?"; if (!sendQuery(command, response)) return -1; else return response.trimmed().toDouble(); } int DS345::functionToNumber(const QString &function_string) const { QString function = function_string.trimmed(); if (function.trimmed() == "SINE") return 0; if (function.trimmed() == "SQUARE") return 1; if (function.trimmed() == "TRIANGLE") return 2; if (function.trimmed() == "RAMP") return 3; if (function.trimmed() == "NOISE") return 4; if (function.trimmed() == "ARBITRARY") return 5; return -1; } QString DS345::numberToFunction(const int &function_number) const { if (function_number == 0) return "SINE"; if (function_number == 1) return "SQUARE"; if (function_number == 2) return "TRIANGLE"; if (function_number == 3) return "RAMP"; if (function_number == 4) return "NOISE"; if (function_number == 5) return "ARBITRARY"; return ""; } bool DS345::setFunction(const int &function_number) const { QString command = "FUNC " + QString::number(function_number); return sendCommand(command); } bool DS345::setFunction(const QString &function) const { return setFunction(functionToNumber(function)); } QString DS345::getFunction() const { QString command = "FUNC?"; QString response; if (sendQuery(command, response)) return numberToFunction(response.trimmed().toInt()); else return ""; } bool DS345::setInverse(const bool &new_inverse) const { QString command = "INVT "; if (new_inverse) command = "1"; else command = "0"; return sendCommand(command); } bool DS345::getInverse() const { QString command = "INVT?"; QString response; sendQuery(command, response); return (response.trimmed().toInt() == 1); } bool DS345::setSynchronization(const bool &new_synchronization) const { QString command = "SYNC "; if (new_synchronization) command = "1"; else command = "0"; return sendCommand(command); } bool DS345::getSynchronization() const { QString command = "SYNC?"; QString response; sendQuery(command, response); return (response.trimmed().toInt() == 1); } bool DS345::setAMdepth(const int &new_persentage) const { QString command = "DPTH " + QString::number(new_persentage); return sendCommand(command); } int DS345::getAMdepth() const { QString command = "DPTH?"; QString response; sendQuery(command, response); return response.trimmed().toInt(); } bool DS345::setFMspan(const double &new_span) const { QString command = "FDEV " + QString::number(new_span); return sendCommand(command); } double DS345::getFMspan() const { QString command = "FDEV?"; QString response; sendQuery(command, response); return response.trimmed().toDouble(); } int DS345::modulateFunctionToNumber(const QString &function_string) const { if (function_string.trimmed() == "SINGLE SWEEP") return 0; if (function_string.trimmed() == "RAMP") return 1; if (function_string.trimmed() == "TRIANGLE") return 2; if (function_string.trimmed() == "SINE") return 3; if (function_string.trimmed() == "SQUARE") return 4; if (function_string.trimmed() == "ARB") return 5; if (function_string.trimmed() == "NONE") return 6; return -1; } QString DS345::numberToModulateFunction(const int &function_number) const { if (function_number == 0) return "SINGLE SWEEP"; if (function_number == 1) return "RAMP"; if (function_number == 2) return "TRIANGLE"; if (function_number == 3) return "SINE"; if (function_number == 4) return "SQUARE"; if (function_number == 5) return "ARB"; if (function_number == 6) return "NONE"; return ""; } bool DS345::setModulationFunction(const int &function_number) const { QString command = "MDWF " + QString::number(function_number); return sendCommand(command); } bool DS345::setModulationFunction(const QString &function_string) const { return setModulationFunction(modulateFunctionToNumber(function_string)); } QString DS345::getModulationFunction() const { QString command = "MDWF?"; QString response; sendQuery(command, response); return numberToModulateFunction(response.trimmed().toInt()); } bool DS345::setModulationEnabled(const bool &enable) const { QString command = "MENA "; if (enable) command += "1"; else command += "0"; return sendCommand(command); } bool DS345::getModulationEnabled() const { QString command = "MENA?"; QString response; sendQuery(command, response); return (response.trimmed() == "1"); } QString DS345::numberToModulateType(const int &type_number) const { if (type_number == 0) return "LIN SWEEP"; if (type_number == 1) return "LOG SWEEP"; if (type_number == 2) return "INTERNAL AM"; if (type_number == 3) return "FM"; if (type_number == 4) return "fm"; if (type_number == 5) return "BURST"; return ""; } int DS345::modulateTypeToNumber(const QString &function_string) const { if (function_string.trimmed() == "LIN SWEEP") return 0; if (function_string.trimmed() == "LOG SWEEP") return 1; if (function_string.trimmed() == "INTERNAL AM") return 2; if (function_string.trimmed() == "FM") return 3; if (function_string.trimmed() == "fm") return 4; if (function_string.trimmed() == "BURST") return 5; return -1; } bool DS345::setModulationType(const int &function_number) const { QString command = "MTYP " + QString::number(function_number); return sendCommand(command); } bool DS345::setModulationType(const QString &function_string) const { return setModulationType(modulateTypeToNumber(function_string)); } QString DS345::getModulationType() const { QString command = "MTYP?"; QString response; sendQuery(command, response); return numberToModulateType(response.trimmed().toInt()); } bool DS345::setModulationRate(const double &new_rate) const { QString command = "RATE " + QString::number(new_rate); return sendCommand(command); } double DS345::getModulationRate() const { QString command = "RATE?"; QString response; sendQuery(command, response); return response.trimmed().toDouble(); } bool DS345::setModulationSpan(const double &new_span) const { QString command = "SPAN " + QString::number(new_span); return sendCommand(command); } double DS345::getModulationSpan() const { QString command = "SPAN?"; QString response; sendQuery(command, response); return response.trimmed().toDouble(); }
gpl-3.0
manusis/dblite
test/testers/lib/FwUnitTestCase.php
818
<?php class FwUnitTestCase extends UnitTestCase { public function __construct() { parent::__construct(); } private $browser; public function getBrowser() { if($this->browser && $this->browser->sessionId) { return $this->browser; } else { include_once "Testing/Selenium.php"; $browser = new Testing_Selenium("*safari", MAIN_URL); $browser->start(); $this->browser = $browser; return $browser; } } public function assertEquals($first, $second, $message = '%s') { $this->assertEqual($first, $second, $message); } public function assertsTrue($result, $message = false) { $this->assertTrue($result, $message = false); } } ?>
gpl-3.0
perf2k2/direct
src/api/entities/bidmodifiers/BidModifierToggleItem.php
832
<?php namespace perf2k2\direct\api\entities\bidmodifiers; use perf2k2\direct\api\enums\bidmodifiers\BidModifierTypeEnum; use perf2k2\direct\api\FilteredEntity; final class BidModifierToggleItem extends FilteredEntity { protected $CampaignId; protected $AdGroupId; protected $Type; protected $Enabled; public function setCampaignId(int $CampaignId): self { $this->CampaignId = $CampaignId; return $this; } public function setAdGroupId(int $AdGroupId): self { $this->AdGroupId = $AdGroupId; return $this; } public function setType(BidModifierTypeEnum $Type): self { $this->Type = $Type; return $this; } public function setEnabled(string $Enabled): self { $this->Enabled = $Enabled; return $this; } }
gpl-3.0
OWASP/WebSpa
src/main/java/net/seleucus/wsp/daemon/WSDaemonStart.java
225
package net.seleucus.wsp.daemon; import net.seleucus.wsp.main.WSGestalt; import net.seleucus.wsp.main.WebSpa; public class WSDaemonStart extends WSGestalt { public WSDaemonStart(WebSpa myWebSpa) { super(myWebSpa); } }
gpl-3.0
erseco/ugr_ddsi
controller/chart_users_data.php
1153
<?php /******************************************* * * 2014 - DDSI (Diseño y desarrollo de sistemas de información) * Grado en Ingeniería Informática * * Ernesto Serrano <erseco@correo.ugr.es> * Garoé Expósito Luis <garoluis@correo.ugr.es * Daniel Pérez Gázquez <Plenidag@correo.ugr.es> * Jose Fco Alcalde <jfap0003@correo.ugr.es> * * ******************************************* * * Devuelve los datos para rellenar la gráfica en formato JSON * ******************************************************************************/ ?> <?php // Set the JSON header //header("Content-type: text/json"); // Incluimos el fichero de configuracíon (por el __autoload) require_once "../config.php"; // Creamos un objeto de la clase $entity = new Users(); // Obtenemos los datos $rows = $entity->getAll(); $array = Array(); // Recorremos las filas (hacemos un cast de $rows a (array) para evitar comprobar si viene vacio) foreach ((array)$rows as $row): array_push($array, "['".$row["name"]."', ".$row["total_questions"]."]"); endforeach; // Unimos todos los valores usando "," como separador echo "[".implode(", ", $array)."]"; ?>
gpl-3.0
YuanLiou/phenom
mobile/src/main/java/liou/rayyuan/phenom/model/CurrentUserManager.java
2106
package liou.rayyuan.phenom.model; import android.text.TextUtils; import liou.rayyuan.phenom.model.domain.Token; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by louis383 on 16/5/8. */ public class CurrentUserManager { private APIManager apiManager; private PreferenceManager preferenceManager; private Token userToken; public CurrentUserManager(PreferenceManager preferenceManager) { this.preferenceManager = preferenceManager; } public CurrentUserManager(APIManager apiManager, PreferenceManager preferenceManager) { this.apiManager = apiManager; this.preferenceManager = preferenceManager; } public void setApiManager(APIManager apiManager) { this.apiManager = apiManager; } public void login(Token userToken) { this.userToken = userToken; String tokenString = Token.JSONSerialization(userToken); preferenceManager.setCurrentUser(tokenString); } public void logout() { this.userToken = new Token(); preferenceManager.removeCurrentUser(); apiManager.expireToken().enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { } @Override public void onFailure(Call<Void> call, Throwable t) { } }); } public void restoreLoginState() { if (isLogin()) { String userTokenString = preferenceManager.getUserTokenString(); Token token = Token.JSONDeserialization(userTokenString); this.userToken = token; } } public boolean isLogin() { return !TextUtils.isEmpty(preferenceManager.getUserTokenString()); } public String getAccessKey() { if (userToken == null) { return ""; } return userToken.getOauthToken(); } public String getAccessSecret() { if (userToken == null) { return ""; } return userToken.getOauthTokenSecret(); } }
gpl-3.0
daemonraco/toobasic
includes/configs/ConfigLoaderSimple.php
658
<?php /** * @file ConfigLoaderSimple.php * @author Alejandro Dario Simi */ namespace TooBasic\Configs; // // Class aliases. use TooBasic\Paths; /** * @class ConfigLoaderSimple * This class holds the logic to load multiple config files in a simple way. */ class ConfigLoaderSimple extends ConfigLoader { // // Protected methods. /** * This method returns the list of config file paths to load. * * @return string[] Returns a list of absolute paths. */ protected function paths() { $out = []; $aux = Paths::Instance()->configPath($this->_config->name(), Paths::ExtensionJSON); if($aux) { $out[] = $aux; } return $out; } }
gpl-3.0
dmitry-vlasov/russell
src/all.cpp
1431
#include "com/actions.cpp" #include "com/log.cpp" #include "com/common.cpp" #include "com/memusage.cpp" #include "com/timer.cpp" #include "com/xml.cpp" #include "daem.cpp" #include "mm/mm_sys.cpp" #include "rus/rus_sys.cpp" #include "mm/mm_cut.cpp" #include "mm/mm_inclusions.cpp" #include "mm/mm_merge.cpp" #include "mm/mm_parser.cpp" #include "mm/mm_read.cpp" #include "mm/mm_translate.cpp" #include "mm/mm_tree.cpp" #include "mm/mm_verify.cpp" #include "rus/expr/rus_expr_parse.cpp" #include "rus/expr/rus_expr_unify.cpp" #include "rus/parser/rus_parser.cpp" #include "rus/prover/rus_prover_cartesian.cpp" #include "rus/prover/rus_prover_down.cpp" #include "rus/prover/rus_prover_expr.cpp" #include "rus/prover/rus_prover_index.cpp" #include "rus/prover/rus_prover_node.cpp" #include "rus/prover/rus_prover_proof.cpp" #include "rus/prover/rus_prover_show.cpp" #include "rus/prover/rus_prover_space.cpp" #include "rus/prover/rus_prover_tactics.cpp" #include "rus/prover/rus_prover_test_prover.cpp" #include "rus/prover/rus_prover_unify.cpp" #include "rus/prover/tree_index/rus_prover_matrix_index.cpp" #include "rus/prover/tree_index/rus_prover_vector_index.cpp" #include "rus/rus_ast.cpp" #include "rus/rus_expr.cpp" #include "rus/rus_memvol.cpp" #include "rus/rus_show.cpp" #include "rus/rus_parser.cpp" #include "rus/rus_read.cpp" #include "rus/rus_translate.cpp" #include "rus/rus_verify.cpp" #include "rus/rus_xml.cpp"
gpl-3.0
esbtools/event-handler
lightblue/src/main/java/org/esbtools/eventhandler/lightblue/client/FindRequests.java
4834
/* * Copyright 2016 esbtools Contributors and/or its affiliates. * * This file is part of esbtools. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.esbtools.eventhandler.lightblue.client; import org.esbtools.eventhandler.lightblue.DocumentEventEntity; import org.esbtools.eventhandler.lightblue.config.EventHandlerConfigEntity; import org.esbtools.lightbluenotificationhook.NotificationEntity; import com.redhat.lightblue.client.Literal; import com.redhat.lightblue.client.Projection; import com.redhat.lightblue.client.Query; import com.redhat.lightblue.client.Sort; import com.redhat.lightblue.client.request.data.DataFindRequest; import java.time.Instant; import java.util.Date; public abstract class FindRequests { /** * Constructs a find request which retrieves up to {@code maxNotifications} notifications of the * given {@code entityNames} which are either currently * {@link NotificationEntity.Status#unprocessed} or expired. * * <p>Notifications are expired when their {@link NotificationEntity#getProcessingDate()} is at * or older than the provided {@code expiredProcessingDate}. */ public static DataFindRequest oldestNotificationsForEntitiesUpTo(String[] entityNames, int maxNotifications, Instant expiredProcessingDate) { DataFindRequest findEntities = new DataFindRequest( NotificationEntity.ENTITY_NAME, NotificationEntity.ENTITY_VERSION); findEntities.where(Query.and( Query.withValue("clientRequestDate", Query.neq, Literal.value(null)), Query.withValues("entityName", Query.NaryOp.in, Literal.values(entityNames)), Query.or( Query.withValue("status", Query.BinOp.eq, DocumentEventEntity.Status.unprocessed), Query.and( Query.withValue("status", Query.BinOp.eq, DocumentEventEntity.Status.processing), Query.withValue("processingDate", Query.BinOp.lte, Date.from(expiredProcessingDate))) ))); findEntities.select(Projection.includeFieldRecursively("*")); findEntities.sort(Sort.asc("clientRequestDate")); findEntities.range(0, maxNotifications - 1); return findEntities; } /** * Constructs a find request which retrieves up to {@code maxEvents} events of the given * {@code types} which are either currently {@link DocumentEventEntity.Status#unprocessed} or * expired. * * <p>Events are expired when their {@link DocumentEventEntity#getProcessingDate()} is at or * older than the provided {@code expiredProcessingDate}. */ public static DataFindRequest priorityDocumentEventsForTypesUpTo(String[] types, int maxEvents, Instant expiredProcessingDate) { DataFindRequest findEntities = new DataFindRequest(DocumentEventEntity.ENTITY_NAME, DocumentEventEntity.VERSION); findEntities.where(Query.and( Query.withValues("canonicalType", Query.NaryOp.in, Literal.values(types)), Query.or( Query.withValue("status", Query.BinOp.eq, DocumentEventEntity.Status.unprocessed), Query.and( Query.withValue("status", Query.BinOp.eq, DocumentEventEntity.Status.processing), Query.withValue("processingDate", Query.BinOp.lte, Date.from(expiredProcessingDate))) ))); findEntities.select(Projection.includeFieldRecursively("*")); findEntities.sort(Sort.desc("priority"), Sort.asc("creationDate")); findEntities.range(0, maxEvents - 1); return findEntities; } public static DataFindRequest eventHandlerConfigForDomain(String configDomain) { DataFindRequest findConfig = new DataFindRequest( EventHandlerConfigEntity.ENTITY_NAME, EventHandlerConfigEntity.ENTITY_VERSION); findConfig.where(Query.withValue("domain", Query.BinOp.eq, configDomain)); findConfig.select(Projection.includeFieldRecursively("*")); return findConfig; } }
gpl-3.0
Tynael/Dummy-Website
includes/functions.php
4446
<?php function redirect_to($new_location) { header("Location: " . $new_location); exit; } function mysql_prep($string) { global $connection; $escaped_string = mysqli_real_escape_string($connection, $string); return $escaped_string; } function confirm_query($result_set) { if (!$result_set) { die("Database query failed."); } } function form_errors($errors = array()) { $output = ""; if (!empty($errors)) { $output .= "<div class=\"error\">"; $output .= "Please fix the following errors:"; $output .= "<ul>"; foreach ($errors as $key => $error) { $output .= "<li>"; $output .= htmlentities($error); $output .= "</li>"; } $output .= "</ul>"; $output .= "</div>"; } return $output; } function find_all_subjects() { global $connection; $query = "SELECT * "; $query .= "FROM subjects "; // $query .= "WHERE visible = 1 "; $query .= "ORDER BY position ASC"; $subject_set = mysqli_query($connection, $query); confirm_query($subject_set); return $subject_set; } function find_pages_for_subject($subject_id) { global $connection; $safe_subject_id = mysqli_real_escape_string($connection, $subject_id); $query = "SELECT * "; $query .= "FROM pages "; $query .= "WHERE visible = 1 "; $query .= "AND subject_id = {$safe_subject_id} "; $query .= "ORDER BY position ASC"; $page_set = mysqli_query($connection, $query); confirm_query($page_set); return $page_set; } function find_subject_by_id($subject_id) { global $connection; $safe_subject_id = mysqli_real_escape_string($connection, $subject_id); $query = "SELECT * "; $query .= "FROM subjects "; $query .= "WHERE id = {$safe_subject_id} "; $query .= "LIMIT 1"; $subject_set = mysqli_query($connection, $query); confirm_query($subject_set); if ($subject = mysqli_fetch_assoc($subject_set)) { return $subject; } else { return null; } } function find_default_page_for_subject($subject_id) { $page_set = find_pages_for_subject($subject_id); if ($first_page = mysqli_fetch_assoc($page_set)) { return $first_page; } else { return null; } } function find_page_by_id($page_id) { global $connection; $safe_page_id = mysqli_real_escape_string($connection, $page_id); $query = "SELECT * "; $query .= "FROM pages "; $query .= "WHERE id = {$safe_page_id} "; $query .= "LIMIT 1"; $page_set = mysqli_query($connection, $query); confirm_query($page_set); if ($page = mysqli_fetch_assoc($page_set)) { return $page; } else { return null; } } function find_selected_page() { global $current_subject; global $current_page; if (isset($_GET["subject"])) { $current_subject = find_subject_by_id($_GET["subject"]); $current_page = find_default_page_for_subject($current_subject["id"]); } elseif (isset($_GET["page"])) { $current_subject = null; $current_page = find_page_by_id($_GET["page"]); } else { $current_subject = null; $current_page = null; } } // navigation take 2 arguments // - the current subject array or null // - the current page array or null function navigation($subject_array, $page_array) { $output = "<ul class=\"subjects\">"; $subject_set = find_all_subjects(); while($subject = mysqli_fetch_assoc($subject_set)) { $output .= "<li"; if ($subject_array && $subject["id"] == $subject_array["id"]) { $output .= " class=\"selected\""; } $output .= ">"; $output .= "<a href=\"manage_content.php?subject="; $output .= urlencode($subject["id"]); $output .= "\">"; $output .= htmlentities($subject["menu_name"]); $output .= "</a>"; // Pages start $page_set = find_pages_for_subject($subject["id"]); $output .= "<ul class=\"pages\">"; while($page = mysqli_fetch_assoc($page_set)) { $output .= "<li"; if ($page_array && $page["id"] == $page_array["id"]) { $output .= " class=\"selected\""; } $output .= ">"; $output .= "<a href=\"manage_content.php?page="; $output .= urlencode($page["id"]); $output .= "\">"; $output .= htmlentities($page["menu_name"]); $output .= "</a></li>"; } mysqli_free_result($page_set); $output .= "</ul></li>"; } mysqli_free_result($subject_set); $output .= "</ul>"; return $output; } ?>
gpl-3.0
leaot/LaJoy-Meteor-Starter-Theme-with-User-System
app/.meteor/local/build/programs/web.browser/app/client/lib/semantic-ui/definitions/behaviors/visit.js
34209
(function(){ ///////////////////////////////////////////////////////////////////////// // // // client/lib/semantic-ui/definitions/behaviors/visit.js // // // ///////////////////////////////////////////////////////////////////////// // /* // DO NOT MODIFY - This file has been generated and will be regenerated Semantic UI v2.1.7 // */ // /*! // * # Semantic UI - Visit // * http://github.com/semantic-org/semantic-ui/ // * // * // * Copyright 2015 Contributors // * Released under the MIT license // * http://opensource.org/licenses/MIT // * // */ // // ;(function ($, window, document, undefined) { // 16 // "use strict"; // 18 // $.visit = $.fn.visit = function (parameters) { // 20 var $allModules = $.isFunction(this) ? $(window) : $(this), // 21 moduleSelector = $allModules.selector || '', // time = new Date().getTime(), // performance = [], // query = arguments[0], // methodInvoked = typeof query == 'string', // queryArguments = [].slice.call(arguments, 1), // returnedValue; // $allModules.each(function () { // 35 var settings = $.isPlainObject(parameters) ? $.extend(true, {}, $.fn.visit.settings, parameters) : $.extend({}, $.fn.visit.settings), error = settings.error, // namespace = settings.namespace, // eventNamespace = '.' + namespace, // moduleNamespace = namespace + '-module', // $module = $(this), // $displays = $(), // element = this, // instance = $module.data(moduleNamespace), // module; // module = { // 55 // initialize: function () { // 57 if (settings.count) { // 58 module.store(settings.key.count, settings.count); // 59 } else if (settings.id) { // module.add.id(settings.id); // 62 } else if (settings.increment && methodInvoked !== 'increment') { module.increment(); // 65 } // module.add.display($module); // 67 module.instantiate(); // 68 }, // // instantiate: function () { // 71 module.verbose('Storing instance of visit module', module); // 72 instance = module; // 73 $module.data(moduleNamespace, module); // 74 }, // // destroy: function () { // 79 module.verbose('Destroying instance'); // 80 $module.removeData(moduleNamespace); // 81 }, // // increment: function (id) { // 86 var currentValue = module.get.count(), // 87 newValue = +currentValue + 1; // if (id) { // 91 module.add.id(id); // 92 } else { // if (newValue > settings.limit && !settings.surpass) { // 95 newValue = settings.limit; // 96 } // module.debug('Incrementing visits', newValue); // 98 module.store(settings.key.count, newValue); // 99 } // }, // // decrement: function (id) { // 103 var currentValue = module.get.count(), // 104 newValue = +currentValue - 1; // if (id) { // 108 module.remove.id(id); // 109 } else { // module.debug('Removing visit'); // 112 module.store(settings.key.count, newValue); // 113 } // }, // // get: { // 117 count: function () { // 118 return +module.retrieve(settings.key.count) || 0; // 119 }, // idCount: function (ids) { // 121 ids = ids || module.get.ids(); // 122 return ids.length; // 123 }, // ids: function (delimitedIDs) { // 125 var idArray = []; // 126 delimitedIDs = delimitedIDs || module.retrieve(settings.key.ids); if (typeof delimitedIDs === 'string') { // 130 idArray = delimitedIDs.split(settings.delimiter); // 131 } // module.verbose('Found visited ID list', idArray); // 133 return idArray; // 134 }, // storageOptions: function (data) { // 136 var options = {}; // 137 if (settings.expires) { // 140 options.expires = settings.expires; // 141 } // if (settings.domain) { // 143 options.domain = settings.domain; // 144 } // if (settings.path) { // 146 options.path = settings.path; // 147 } // return options; // 149 } // }, // // has: { // 153 visited: function (id, ids) { // 154 var visited = false; // 155 ids = ids || module.get.ids(); // 158 if (id !== undefined && ids) { // 159 $.each(ids, function (index, value) { // 160 if (value == id) { // 161 visited = true; // 162 } // }); // } // return visited; // 166 } // }, // // set: { // 170 count: function (value) { // 171 module.store(settings.key.count, value); // 172 }, // ids: function (value) { // 174 module.store(settings.key.ids, value); // 175 } // }, // // reset: function () { // 179 module.store(settings.key.count, 0); // 180 module.store(settings.key.ids, null); // 181 }, // // add: { // 184 id: function (id) { // 185 var currentIDs = module.retrieve(settings.key.ids), // 186 newIDs = currentIDs === undefined || currentIDs === '' ? id : currentIDs + settings.delimiter + id; if (module.has.visited(id)) { // 192 module.debug('Unique content already visited, not adding visit', id, currentIDs); } else if (id === undefined) { // module.debug('ID is not defined'); // 196 } else { // module.debug('Adding visit to unique content', id); // 199 module.store(settings.key.ids, newIDs); // 200 } // module.set.count(module.get.idCount()); // 202 }, // display: function (selector) { // 204 var $element = $(selector); // 205 if ($element.length > 0 && !$.isWindow($element[0])) { // 208 module.debug('Updating visit count for element', $element); $displays = $displays.length > 0 ? $displays.add($element) : $element; } // } // }, // // remove: { // 218 id: function (id) { // 219 var currentIDs = module.get.ids(), // 220 newIDs = []; // if (id !== undefined && currentIDs !== undefined) { // 224 module.debug('Removing visit to unique content', id, currentIDs); $.each(currentIDs, function (index, value) { // 226 if (value !== id) { // 227 newIDs.push(value); // 228 } // }); // newIDs = newIDs.join(settings.delimiter); // 231 module.store(settings.key.ids, newIDs); // 232 } // module.set.count(module.get.idCount()); // 234 } // }, // // check: { // 238 limit: function (value) { // 239 value = value || module.get.count(); // 240 if (settings.limit) { // 241 if (value >= settings.limit) { // 242 module.debug('Pages viewed exceeded limit, firing callback', value, settings.limit); settings.onLimit.call(element, value); // 244 } // module.debug('Limit not reached', value, settings.limit); settings.onChange.call(element, value); // 247 } // module.update.display(value); // 249 } // }, // // update: { // 253 display: function (value) { // 254 value = value || module.get.count(); // 255 if ($displays.length > 0) { // 256 module.debug('Updating displayed view count', $displays); $displays.html(value); // 258 } // } // }, // // store: function (key, value) { // 263 var options = module.get.storageOptions(value); // 264 if (settings.storageMethod == 'localstorage' && window.localStorage !== undefined) { window.localStorage.setItem(key, value); // 268 module.debug('Value stored using local storage', key, value); } else if ($.cookie !== undefined) { // $.cookie(key, value, options); // 272 module.debug('Value stored using cookie', key, value, options); } else { // module.error(error.noCookieStorage); // 276 return; // 277 } // if (key == settings.key.count) { // 279 module.check.limit(value); // 280 } // }, // retrieve: function (key, value) { // 283 var storedValue; // 284 if (settings.storageMethod == 'localstorage' && window.localStorage !== undefined) { storedValue = window.localStorage.getItem(key); // 288 } // // get by cookie // else if ($.cookie !== undefined) { // storedValue = $.cookie(key); // 292 } else { // module.error(error.noCookieStorage); // 295 } // if (storedValue == 'undefined' || storedValue == 'null' || storedValue === undefined || storedValue === null) { storedValue = undefined; // 298 } // return storedValue; // 300 }, // // setting: function (name, value) { // 303 if ($.isPlainObject(name)) { // 304 $.extend(true, settings, name); // 305 } else if (value !== undefined) { // settings[name] = value; // 308 } else { // return settings[name]; // 311 } // }, // internal: function (name, value) { // 314 module.debug('Changing internal', name, value); // 315 if (value !== undefined) { // 316 if ($.isPlainObject(name)) { // 317 $.extend(true, module, name); // 318 } else { // module[name] = value; // 321 } // } else { // return module[name]; // 325 } // }, // debug: function () { // 328 if (settings.debug) { // 329 if (settings.performance) { // 330 module.performance.log(arguments); // 331 } else { // module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); // 335 } // } // }, // verbose: function () { // 339 if (settings.verbose && settings.debug) { // 340 if (settings.performance) { // 341 module.performance.log(arguments); // 342 } else { // module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); // 346 } // } // }, // error: function () { // 350 module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); // 352 }, // performance: { // 354 log: function (message) { // 355 var currentTime, executionTime, previousTime; // 356 if (settings.performance) { // 361 currentTime = new Date().getTime(); // 362 previousTime = time || currentTime; // 363 executionTime = currentTime - previousTime; // 364 time = currentTime; // 365 performance.push({ // 366 'Name': message[0], // 367 'Arguments': [].slice.call(message, 1) || '', // 368 'Element': element, // 369 'Execution Time': executionTime // 370 }); // } // clearTimeout(module.performance.timer); // 373 module.performance.timer = setTimeout(module.performance.display, 500); }, // display: function () { // 376 var title = settings.name + ':', // 377 totalTime = 0; // time = false; // 381 clearTimeout(module.performance.timer); // 382 $.each(performance, function (index, data) { // 383 totalTime += data['Execution Time']; // 384 }); // title += ' ' + totalTime + 'ms'; // 386 if (moduleSelector) { // 387 title += ' \'' + moduleSelector + '\''; // 388 } // if ($allModules.length > 1) { // 390 title += ' ' + '(' + $allModules.length + ')'; // 391 } // if ((console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); // 394 if (console.table) { // 395 console.table(performance); // 396 } else { // $.each(performance, function (index, data) { // 399 console.log(data['Name'] + ': ' + data['Execution Time'] + 'ms'); }); // } // console.groupEnd(); // 403 } // performance = []; // 405 } // }, // invoke: function (query, passedArguments, context) { // 408 var object = instance, // 409 maxDepth, // found, // response; // passedArguments = passedArguments || queryArguments; // 415 context = element || context; // 416 if (typeof query == 'string' && object !== undefined) { // 417 query = query.split(/[\. ]/); // 418 maxDepth = query.length - 1; // 419 $.each(query, function (depth, value) { // 420 var camelCaseValue = depth != maxDepth ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query; if ($.isPlainObject(object[camelCaseValue]) && depth != maxDepth) { object = object[camelCaseValue]; // 426 } else if (object[camelCaseValue] !== undefined) { // found = object[camelCaseValue]; // 429 return false; // 430 } else if ($.isPlainObject(object[value]) && depth != maxDepth) { object = object[value]; // 433 } else if (object[value] !== undefined) { // found = object[value]; // 436 return false; // 437 } else { // return false; // 440 } // }); // } // if ($.isFunction(found)) { // 444 response = found.apply(context, passedArguments); // 445 } else if (found !== undefined) { // response = found; // 448 } // if ($.isArray(returnedValue)) { // 450 returnedValue.push(response); // 451 } else if (returnedValue !== undefined) { // returnedValue = [returnedValue, response]; // 454 } else if (response !== undefined) { // returnedValue = response; // 457 } // return found; // 459 } // }; // if (methodInvoked) { // 462 if (instance === undefined) { // 463 module.initialize(); // 464 } // module.invoke(query); // 466 } else { // if (instance !== undefined) { // 469 instance.invoke('destroy'); // 470 } // module.initialize(); // 472 } // }); // return returnedValue !== undefined ? returnedValue : this; // 477 }; // // $.fn.visit.settings = { // 483 // name: 'Visit', // 485 // debug: false, // 487 verbose: false, // 488 performance: true, // 489 // namespace: 'visit', // 491 // increment: false, // 493 surpass: false, // 494 count: false, // 495 limit: false, // 496 // delimiter: '&', // 498 storageMethod: 'localstorage', // 499 // key: { // 501 count: 'visit-count', // 502 ids: 'visit-ids' // 503 }, // // expires: 30, // 506 domain: false, // 507 path: '/', // 508 // onLimit: function () {}, // 510 onChange: function () {}, // 511 // error: { // 513 method: 'The method you called is not defined', // 514 missingPersist: 'Using the persist setting requires the inclusion of PersistJS', noCookieStorage: 'The default storage cookie requires $.cookie to be included.' } // // }; // })(jQuery, window, document); // ///////////////////////////////////////////////////////////////////////// }).call(this);
gpl-3.0
janhf/PartmanCalculator
src/de/upb/phys/partmancalc/PartmanAlgorithm.java
2157
/* * PartmanCalculator - Calculates partition sizes with the algorithm * of debian installers partitioner * Copyright (C) 2015 Jan-Philipp Hülshoff <github@bklosr.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package de.upb.phys.partmancalc; import java.util.List; public class PartmanAlgorithm extends Algorithm { public PartmanAlgorithm(Harddisk hdd) { super(hdd); } private long sum(long[] a) { long sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } @Override protected void calculate() { List<Partition> partitions = hdd.getPartitions(); long[] factor = new long[partitions.size()]; long[] min = new long[partitions.size()]; long[] max = new long[partitions.size()]; long[] priority = new long[partitions.size()]; long freespace = hdd.getSize(); for (int i = 0; i < partitions.size(); i++) { min[i] = partitions.get(i).getMinSize(); max[i] = partitions.get(i).getMaxSize(); priority[i] = partitions.get(i).getPriority(); factor[i] = priority[i] - min[i]; } boolean ready = false; while (!ready) { long minsum = sum(min); long factsum = sum(factor); ready = true; for (int i = 0; i < partitions.size(); i++) { long x = min[i] + (freespace - minsum) * factor[i] / factsum; if (x > max[i]) x = max[i]; if (x != min[i]) { ready = false; min[i] = x; } } } for (int i = 0; i < partitions.size(); i++) { partitions.get(i).setCalculatedSize((int)min[i]); } } }
gpl-3.0
goodspb/elcon
app/common/Model/MetaData/InCache.php
964
<?php namespace Common\Model\MetaData; use Common\Cache; use Phalcon\Mvc\Model\MetaData; use Phalcon\Mvc\Model\Exception; /** * Common\Model\MetaData\InCache * * Stores model meta-data in cache. * *<code> * $metaData = new \Common\Model\Metadata\InCache(); *</code> */ class InCache extends MetaData { protected $_metaData = array(); protected function prepareVirtualPath($key, $separator = '_') { return strtr($key, ['/' => $separator, '\\' => $separator, ':' => $separator]); } /** * Reads meta-data from files * * @param string $key * @return mixed */ public function read($key) { return Cache::get($this->prepareVirtualPath($key)); } /** * Writes the meta-data to files * * @param string $key * @param array $data */ public function write($key, $data) { Cache::set($this->prepareVirtualPath($key), $data, Cache::TTL_ONE_MONTH); } }
gpl-3.0
techdude101/code
JS/HelloWorld.js
31
document.write("Hello World");
gpl-3.0
CDrummond/madrigal
core/monoicon.cpp
7273
/* * Cantata * * Copyright (c) 2011-2016 Craig Drummond <craig.p.drummond@gmail.com> * * ---- * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "core/monoicon.h" #include "core/utils.h" #ifdef Q_OS_MAC #include "mac/osxstyle.h" #endif #include <QFile> #include <QIconEngine> #include <QSvgRenderer> #include <QPainter> #include <QPixmapCache> #include <QRect> #include <QFontDatabase> #include <QApplication> #include <QPalette> namespace Core { class MonoIconEngine : public QIconEngine { public: MonoIconEngine(const QString &file, MonoIcon::Type t, const QColor &col, const QColor &sel) : fileName(file) , type(t) , color(col) , selectedColor(sel) { switch (type) { case MonoIcon::ex_cd: fileName=":cd"; break; case MonoIcon::ex_mediaplay: fileName=QApplication::isLeftToRight() ? ":media-play" : ":media-play-rtl"; break; case MonoIcon::ex_mediapause: fileName=":media-pause"; break; case MonoIcon::ex_mediaprevious: fileName=":media-prev"; break; case MonoIcon::ex_medianext: fileName=":media-next"; break; case MonoIcon::ex_mediastop: fileName=":media-stop"; break; case MonoIcon::ex_radio: fileName=":radio"; break; case MonoIcon::ex_genre: fileName=":genre"; break; case MonoIcon::ex_conductor: fileName=":conductor"; break; default: break; } } virtual ~MonoIconEngine() {} MonoIconEngine * clone() const { return new MonoIconEngine(fileName, type, color, selectedColor); } virtual void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) { Q_UNUSED(state) QColor col=QIcon::Selected==mode ? selectedColor : color; if (QIcon::Selected==mode && !col.isValid()) { #ifdef Q_OS_MAC col=Mac::OSXStyle::self()->viewPalette().highlightedText().color(); #else col=QApplication::palette().highlightedText().color(); #endif } QString key=(fileName.isEmpty() ? QString::number(type) : fileName)+ QLatin1Char('-')+QString::number(rect.width())+QLatin1Char('-')+QString::number(rect.height())+QLatin1Char('-')+col.name(); QPixmap pix; if (!QPixmapCache::find(key, &pix)) { pix=QPixmap(rect.width(), rect.height()); pix.fill(Qt::transparent); QPainter p(&pix); if (fileName.isEmpty()) { QString fontName; if (MonoIcon::ex_one==type) { fontName="serif"; } else { // Load fontawesome, if it is not already loaded if (fontAwesomeFontName.isEmpty()) { QFile fa(":fa.ttf"); fa.open(QIODevice::ReadOnly); QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies(QFontDatabase::addApplicationFontFromData(fa.readAll())); if (!loadedFontFamilies.empty()) { fontAwesomeFontName= loadedFontFamilies.at(0); } fa.close(); } fontName=fontAwesomeFontName; } QFont font(fontName); int pixelSize=rect.height(); if (MonoIcon::ex_one==type) { font.setBold(true); } else if (pixelSize>10) { static const int constScale=14; static const int constHalfScale=constScale/2; pixelSize=((pixelSize/constScale)*constScale)+((pixelSize%constScale)>=constHalfScale ? constScale : 0); pixelSize=qMin(pixelSize, rect.height()); if (MonoIcon::bars==type && pixelSize%constHalfScale) { pixelSize-=1; } } font.setPixelSize(pixelSize); font.setStyleStrategy(QFont::PreferAntialias); font.setHintingPreference(QFont::PreferFullHinting); p.setFont(font); p.setPen(col); p.setRenderHint(QPainter::Antialiasing, true); if (MonoIcon::ex_one==type) { QString str=QString::number(type); p.drawText(QRect(0, 0, rect.width(), rect.height()), str, QTextOption(Qt::AlignHCenter|Qt::AlignVCenter)); p.drawText(QRect(1, 0, rect.width(), rect.height()), str, QTextOption(Qt::AlignHCenter|Qt::AlignVCenter)); } else { p.drawText(QRect(0, 0, rect.width(), rect.height()), QString(QChar(static_cast<int>(type))), QTextOption(Qt::AlignCenter|Qt::AlignVCenter)); } } else { QSvgRenderer renderer; QFile f(rect.width()<=32 && QFile::exists(fileName+"32") ? fileName+"32" : fileName); QByteArray bytes; if (f.open(QIODevice::ReadOnly)) { bytes=f.readAll(); } if (!bytes.isEmpty()) { bytes.replace("#000", col.name().toLatin1()); } renderer.load(bytes); renderer.render(&p, QRect(0, 0, rect.width(), rect.height())); } QPixmapCache::insert(key, pix); } if (QIcon::Disabled==mode) { painter->save(); painter->setOpacity(painter->opacity()*0.35); } painter->drawPixmap(rect.topLeft(), pix); if (QIcon::Disabled==mode) { painter->restore(); } } virtual QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) { QPixmap pix(size); pix.fill(Qt::transparent); QPainter painter(&pix); paint(&painter, QRect(QPoint(0, 0), size), mode, state); return pix; } private: QString fileName; MonoIcon::Type type; QColor color; QColor selectedColor; static QString fontAwesomeFontName; }; QString MonoIconEngine::fontAwesomeFontName; const QColor MonoIcon::constRed(220, 0, 0); QIcon MonoIcon::icon(const QString &fileName, const QColor &col, const QColor &sel) { return QIcon(new MonoIconEngine(fileName, (MonoIcon::Type)0, col, sel)); } QIcon MonoIcon::icon(Type icon, const QColor &col, const QColor &sel) { return QIcon(new MonoIconEngine(QString(), icon, col, sel)); } }
gpl-3.0
Emd4600/SporeModder
src/sporemodder/files/formats/renderWare4/Rw4ToDDS.java
5611
package sporemodder.files.formats.renderWare4; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.HashMap; import java.util.List; import javax.swing.JPanel; import sporemodder.files.ActionCommand; import sporemodder.files.FileStreamAccessor; import sporemodder.files.InputStreamAccessor; import sporemodder.files.OutputStreamAccessor; import sporemodder.files.formats.ConvertAction; import sporemodder.files.formats.FileFormatStructure; import sporemodder.files.formats.ResourceKey; import sporemodder.files.formats.dds.DDSTexture; import sporemodder.userinterface.dialogs.UIErrorsDialog; import sporemodder.utilities.InputOutputPaths.InputOutputPair; public class Rw4ToDDS implements ConvertAction { private static RW4Main getRW4(InputStreamAccessor in) throws InstantiationException, IllegalAccessException, IOException { RW4Main rw4 = new RW4Main(); rw4.readHeader(in); if (!rw4.isTexture()) { return null; } // only read necessary sections rw4.readSections(in, RW4Texture.class, RW4Buffer.class); return rw4; } private void writeRW4(InputStreamAccessor in, OutputStreamAccessor out) throws IOException { out.seek(0); out.write(in.toByteArray()); } private void writeRW4(InputStreamAccessor in, String outPath) throws IOException { // remove .dds extension if present String path = outPath; int indexOf = path.indexOf(".dds"); if (indexOf != -1) { path = path.substring(0, indexOf); } Files.write(new File(path).toPath(), in.toByteArray(), StandardOpenOption.WRITE, StandardOpenOption.CREATE); } @Override public FileFormatStructure convert(File input, File output) throws Exception { FileStreamAccessor in = null; FileStreamAccessor out = null; try { in = new FileStreamAccessor(input, "r"); RW4Main main = getRW4(in); DDSTexture texture; if (main == null || (texture = main.toTexture()) == null) { // writeRW4(in, output.getAbsolutePath()); // return new FileFormatStructure.DefaulFormatStructure(); // the unpacker will write the original file return null; } else { out = new FileStreamAccessor(output, "rw", true); texture.write(out); return main; } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } @Override public FileFormatStructure convert(InputStreamAccessor input, OutputStreamAccessor output) throws Exception { RW4Main main = getRW4(input); DDSTexture texture; if (main == null || (texture = main.toTexture()) == null) { // writeRW4(in, output.getAbsolutePath()); // return new FileFormatStructure.DefaulFormatStructure(); // the unpacker will write the original file return null; } else { texture.write(output); return main; } } @Override public FileFormatStructure convert(InputStreamAccessor input, String outputPath) throws Exception { FileStreamAccessor out = null; try { RW4Main main = getRW4(input); DDSTexture texture; if (main == null || (texture = main.toTexture()) == null) { // writeRW4(in, output.getAbsolutePath()); // return new FileFormatStructure.DefaulFormatStructure(); // the unpacker will write the original file return null; } else { out = new FileStreamAccessor(outputPath, "rw", true); texture.write(out); return main; } } finally { if (out != null) { out.close(); } } } @Override public FileFormatStructure convert(String inputPath, OutputStreamAccessor output) throws Exception { try (FileStreamAccessor in = new FileStreamAccessor(inputPath, "r")) { RW4Main main = getRW4(in); DDSTexture texture; if (main == null || (texture = main.toTexture()) == null) { // writeRW4(in, output.getAbsolutePath()); // return new FileFormatStructure.DefaulFormatStructure(); // the unpacker will write the original file return null; } else { texture.write(output); return main; } } } @Override public boolean isValid(ResourceKey key) { return key.getTypeID() == 0x2F4E681B; } @Override public boolean isValid(String extension) { return extension.equals("rw4"); } @Override public String getOutputExtension(String extension) { return "dds"; } @Override public boolean isValid(File file) { return file.isFile() && file.getName().endsWith(".rw4"); } @Override public File getOutputFile(File file) { return ActionCommand.replaceFileExtension(file, ".rw4.dds"); } @Override public int getOutputExtensionID(String extension) { return 0x2F4E681B; } @Override public DDSTexture process(File input) throws Exception { try (InputStreamAccessor in = new FileStreamAccessor(input, "r")) { RW4Main main = getRW4(in); DDSTexture texture; if (main == null || (texture = main.toTexture()) == null) { return null; } else { return texture; } } } @Override public JPanel createOptionsPanel() { return null; } public static boolean processCommand(String[] args) { List<InputOutputPair> pairs = ActionCommand.parseDefaultArguments(args, "rw4", "dds", false); if (pairs == null) { return false; } Rw4ToDDS converter = new Rw4ToDDS(); HashMap<File, Exception> exceptions = new HashMap<File, Exception>(); for (InputOutputPair pair : pairs) { try { converter.convert(pair.input, pair.output); } catch (Exception e) { exceptions.put(pair.input, e); } } if (exceptions.size() > 0) { new UIErrorsDialog(exceptions); return false; } return true; } }
gpl-3.0
nickebbutt/od-suffixtree
src/main/java/com/od/radixtree/sequence/CharSequenceWithAssignableTerminalChar.java
1205
package com.od.radixtree.sequence; /** * User: nick * Date: 23/05/13 * Time: 09:41 * * A CharSequenceWithIntTerminator in which an int is specified as the terminator value. * * This should be used when adding sequences to a generalized suffix tree structure, since in this case each * sequence added (and its suffixes) must have a distinct terminator */ public class CharSequenceWithAssignableTerminalChar implements CharSequenceWithIntTerminator { private CharSequence s; private int terminalInt; public CharSequenceWithAssignableTerminalChar(CharSequence s, int terminalInt) { this.s = s; this.terminalInt = terminalInt; } @Override public int length() { return s.length() + 1; } @Override public char charAt(int index) { return index == s.length() ? TERMINATOR_CHAR_REPRESENTATION : s.charAt(index); } public int intAt(int index) { return index == s.length() ? terminalInt : s.charAt(index); } @Override public CharSequence subSequence(int start, int end) { throw new UnsupportedOperationException(); } }
gpl-3.0
RotaruDan/cytopathologyeditor
app/models/application.server.model.js
792
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Application Schema */ var ApplicationSchema = new Schema({ name: { type: String, required: 'Please add an apk file!' }, apkFile: { type: String, trim: true, required: 'Please add an apk file!' }, htmlFile: { type: String, trim: true, required: 'Please add an html file!' }, updated: { type: Date, default: Date.now }, created: { type: Date, default: Date.now }, status: { type: String, enum: ['FAIL', 'SUCCESS', 'BUILDING'], default: 'BUILDING' } }); mongoose.model('Application', ApplicationSchema);
gpl-3.0
ManuRodriguezSebastian/DAM
Procesos/EjerciciosNoe/src/Mesa.java
972
public class Mesa { boolean[] platos; public Mesa(int nPlatos) { platos = new boolean[nPlatos]; } public synchronized int entrarFilosofo() { int i; for (i = 0; i < platos.length; i++) { int anterior = (i + platos.length - 1) % platos.length; int siguiente = (i + 1) % platos.length; if (!platos[anterior] && !platos[i] && !platos[siguiente]) { platos[i] = true; break; } } if (i == platos.length) i = -1; return i; } public void salirFilosofo(int i) { platos[i] = false; } } /* * Aritmética modular: Nunca se sale del array. El resultado nunca va a ser <= que la longitud del array. * Ejemplo: 23 dividido 4 los resultados son: 0,1,2,3. * * El siguiente siempre es: * (posicion + 1) % longitudArray. * * Por ejemplo: Siguiente a 0: (0 + 1) % 23 = 1 * * El anterior siempre es: * (posicion + (longitudArray - 1) % longitudArray. * * Por ejemplo: Anterior a 1: (1 + (23-1) % 23 = 22 */
gpl-3.0
OlyNet/olydorfapp
app/src/main/java/eu/olynet/olydorfapp/model/AbstractMetaItemMixIn.java
2672
/* * This file is part of OlydorfApp. * * OlydorfApp is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OlydorfApp is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OlydorfApp. If not, see <http://www.gnu.org/licenses/>. */ package eu.olynet.olydorfapp.model; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * MixIn so that the type information of AbstractMetaItems can be stored when writing them to the * cache. All subclasses of AbstractMetaItem <b>must</b> be listed here! * * @author Martin Herrmann <a href="mailto:martin.herrmann@olynet.eu">martin.herrmann@olynet.eu<a> */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "abstractType") @JsonSubTypes( {@JsonSubTypes.Type(value = OrganizationMetaItem.class, name = "OrganizationMetaItem"), @JsonSubTypes.Type(value = OrganizationItem.class, name = "OrganizationItem"), @JsonSubTypes.Type(value = NewsMetaItem.class, name = "NewsMetaItem"), @JsonSubTypes.Type(value = NewsItem.class, name = "NewsItem"), @JsonSubTypes.Type(value = FoodMetaItem.class, name = "FoodMetaItem"), @JsonSubTypes.Type(value = FoodItem.class, name = "FoodItem"), @JsonSubTypes.Type(value = CategoryMetaItem.class, name = "CategoryMetaItem"), @JsonSubTypes.Type(value = CategoryItem.class, name = "CategoryItem"), @JsonSubTypes.Type(value = DrinkMetaItem.class, name = "DrinkMetaItem"), @JsonSubTypes.Type(value = DrinkItem.class, name = "DrinkItem"), @JsonSubTypes.Type(value = DrinkSizeMetaItem.class, name = "DrinkSizeMetaItem"), @JsonSubTypes.Type(value = DrinkSizeItem.class, name = "DrinkSizeItem"), @JsonSubTypes.Type(value = MealOfTheDayMetaItem.class, name = "MealOfTheDayMetaItem"), @JsonSubTypes.Type(value = MealOfTheDayItem.class, name = "MealOfTheDayItem"), @JsonSubTypes.Type(value = DailyMealMetaItem.class, name = "DailyMealMetaItem"), @JsonSubTypes.Type(value = DailyMealItem.class, name = "DailyMealItem")}) abstract public class AbstractMetaItemMixIn { /* leave empty */ }
gpl-3.0
nicolas17/boincgit-test
client/cs_scheduler.cpp
38474
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. // High-level logic for communicating with scheduling servers, // and for merging the result of a scheduler RPC into the client state // The scheduler RPC mechanism is in scheduler_op.C #include "cpp.h" #ifdef _WIN32 #include "boinc_win.h" #else #include "config.h" #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <map> #include <set> #endif #include "crypt.h" #include "error_numbers.h" #include "file_names.h" #include "filesys.h" #include "parse.h" #include "str_util.h" #include "str_replace.h" #include "url.h" #include "util.h" #include "client_msgs.h" #include "cs_notice.h" #include "cs_trickle.h" #include "project.h" #include "result.h" #include "scheduler_op.h" #include "sandbox.h" #include "client_state.h" using std::max; using std::vector; using std::string; // quantities like avg CPU time decay by a factor of e every week // #define EXP_DECAY_RATE (1./(SECONDS_PER_DAY*7)) // try to report results this much before their deadline // #define REPORT_DEADLINE_CUSHION ((double)SECONDS_PER_DAY) #ifndef SIM // Write a scheduler request to a disk file, // to be sent to a scheduling server // int CLIENT_STATE::make_scheduler_request(PROJECT* p) { char buf[1024]; MIOFILE mf; unsigned int i; RESULT* rp; get_sched_request_filename(*p, buf, sizeof(buf)); FILE* f = boinc_fopen(buf, "wb"); if (!f) return ERR_FOPEN; double trs = total_resource_share(); double rrs = runnable_resource_share(RSC_TYPE_ANY); double prrs = potentially_runnable_resource_share(); double resource_share_fraction, rrs_fraction, prrs_fraction; if (trs) { resource_share_fraction = p->resource_share / trs; } else { resource_share_fraction = 1; } if (rrs) { rrs_fraction = p->resource_share / rrs; } else { rrs_fraction = 1; } if (prrs) { prrs_fraction = p->resource_share / prrs; } else { prrs_fraction = 1; } // if hostid is zero, rpc_seqno better be also // if (!p->hostid) { p->rpc_seqno = 0; } mf.init_file(f); fprintf(f, "<scheduler_request>\n" " <authenticator>%s</authenticator>\n" " <hostid>%d</hostid>\n" " <rpc_seqno>%d</rpc_seqno>\n" " <core_client_major_version>%d</core_client_major_version>\n" " <core_client_minor_version>%d</core_client_minor_version>\n" " <core_client_release>%d</core_client_release>\n" " <resource_share_fraction>%f</resource_share_fraction>\n" " <rrs_fraction>%f</rrs_fraction>\n" " <prrs_fraction>%f</prrs_fraction>\n" " <duration_correction_factor>%f</duration_correction_factor>\n" " <allow_multiple_clients>%d</allow_multiple_clients>\n" " <sandbox>%d</sandbox>\n", p->authenticator, p->hostid, p->rpc_seqno, core_client_version.major, core_client_version.minor, core_client_version.release, resource_share_fraction, rrs_fraction, prrs_fraction, p->duration_correction_factor, config.allow_multiple_clients?1:0, g_use_sandbox?1:0 ); work_fetch.write_request(f, p); // write client capabilities // fprintf(f, " <client_cap_plan_class>1</client_cap_plan_class>\n" ); write_platforms(p, mf); if (strlen(p->code_sign_key)) { fprintf(f, " <code_sign_key>\n%s\n</code_sign_key>\n", p->code_sign_key); } // send working prefs // fprintf(f, "<working_global_preferences>\n"); global_prefs.write(mf); fprintf(f, "</working_global_preferences>\n"); // send master global preferences if present and not host-specific // if (!global_prefs.host_specific && boinc_file_exists(GLOBAL_PREFS_FILE_NAME)) { FILE* fprefs = fopen(GLOBAL_PREFS_FILE_NAME, "r"); if (fprefs) { copy_stream(fprefs, f); fclose(fprefs); } PROJECT* pp = lookup_project(global_prefs.source_project); if (pp && strlen(pp->email_hash)) { fprintf(f, "<global_prefs_source_email_hash>%s</global_prefs_source_email_hash>\n", pp->email_hash ); } } // Of the projects with same email hash as this one, // send the oldest cross-project ID. // Use project URL as tie-breaker. // PROJECT* winner = p; for (i=0; i<projects.size(); i++ ) { PROJECT* project = projects[i]; if (project == p) continue; if (strcmp(project->email_hash, p->email_hash)) continue; if (project->cpid_time < winner->cpid_time) { winner = project; } else if (project->cpid_time == winner->cpid_time) { if (strcmp(project->master_url, winner->master_url) < 0) { winner = project; } } } fprintf(f, "<cross_project_id>%s</cross_project_id>\n", winner->cross_project_id ); time_stats.write(mf, true); net_stats.write(mf); if (global_prefs.daily_xfer_period_days) { daily_xfer_history.write_scheduler_request( mf, global_prefs.daily_xfer_period_days ); } // update hardware info, and write host info // host_info.get_host_info(); set_ncpus(); host_info.write(mf, !config.suppress_net_info, false); // get and write disk usage // get_disk_usages(); get_disk_shares(); fprintf(f, " <disk_usage>\n" " <d_boinc_used_total>%f</d_boinc_used_total>\n" " <d_boinc_used_project>%f</d_boinc_used_project>\n" " <d_project_share>%f</d_project_share>\n" " </disk_usage>\n", total_disk_usage, p->disk_usage, p->disk_share ); // copy request values from RSC_WORK_FETCH to COPROC // int j = rsc_index(GPU_TYPE_NVIDIA); if (j > 0) { coprocs.nvidia.req_secs = rsc_work_fetch[j].req_secs; coprocs.nvidia.req_instances = rsc_work_fetch[j].req_instances; coprocs.nvidia.estimated_delay = rsc_work_fetch[j].req_secs?rsc_work_fetch[j].busy_time_estimator.get_busy_time():0; } j = rsc_index(GPU_TYPE_ATI); if (j > 0) { coprocs.ati.req_secs = rsc_work_fetch[j].req_secs; coprocs.ati.req_instances = rsc_work_fetch[j].req_instances; coprocs.ati.estimated_delay = rsc_work_fetch[j].req_secs?rsc_work_fetch[j].busy_time_estimator.get_busy_time():0; } if (coprocs.n_rsc > 1) { coprocs.write_xml(mf, true); } // report completed jobs // unsigned int last_reported_index = 0; p->nresults_returned = 0; for (i=0; i<results.size(); i++) { rp = results[i]; if (rp->project == p && rp->ready_to_report) { p->nresults_returned++; rp->write(mf, true); } if (config.max_tasks_reported && (p->nresults_returned >= config.max_tasks_reported) ) { last_reported_index = i; break; } } read_trickle_files(p, f); // report sticky files as needed // for (i=0; i<file_infos.size(); i++) { FILE_INFO* fip = file_infos[i]; if (fip->project != p) continue; if (!fip->sticky) continue; fprintf(f, " <file_info>\n" " <name>%s</name>\n" " <nbytes>%f</nbytes>\n" " <status>%d</status>\n" " </file_info>\n", fip->name, fip->nbytes, fip->status ); } if (p->send_time_stats_log) { fprintf(f, "<time_stats_log>\n"); time_stats.get_log_after(p->send_time_stats_log, mf); fprintf(f, "</time_stats_log>\n"); } if (p->send_job_log) { fprintf(f, "<job_log>\n"); job_log_filename(*p, buf, sizeof(buf)); send_log_after(buf, p->send_job_log, mf); fprintf(f, "</job_log>\n"); } // send descriptions of app versions // fprintf(f, "<app_versions>\n"); j=0; for (i=0; i<app_versions.size(); i++) { APP_VERSION* avp = app_versions[i]; if (avp->project != p) continue; avp->write(mf, false); avp->index = j++; } fprintf(f, "</app_versions>\n"); // send descriptions of jobs in progress for this project // fprintf(f, "<other_results>\n"); for (i=0; i<results.size(); i++) { rp = results[i]; if (rp->project != p) continue; if ((last_reported_index && (i > last_reported_index)) || !rp->ready_to_report) { fprintf(f, " <other_result>\n" " <name>%s</name>\n" " <app_version>%d</app_version>\n", rp->name, rp->avp->index ); // the following is for backwards compatibility w/ old schedulers // if (strlen(rp->avp->plan_class)) { fprintf(f, " <plan_class>%s</plan_class>\n", rp->avp->plan_class ); } fprintf(f, " </other_result>\n" ); } } fprintf(f, "</other_results>\n"); // if requested by project, send summary of all in-progress results // (for EDF simulation by scheduler) // if (p->send_full_workload) { fprintf(f, "<in_progress_results>\n"); for (i=0; i<results.size(); i++) { rp = results[i]; double x = rp->estimated_runtime_remaining(); if (x == 0) continue; strcpy(buf, ""); int rt = rp->avp->gpu_usage.rsc_type; if (rt) { if (rt == rsc_index(GPU_TYPE_NVIDIA)) { sprintf(buf, " <ncudas>%f</ncudas>\n", rp->avp->gpu_usage.usage); } else if (rt == rsc_index(GPU_TYPE_ATI)) { sprintf(buf, " <natis>%f</natis>\n", rp->avp->gpu_usage.usage); } } fprintf(f, " <ip_result>\n" " <name>%s</name>\n" " <report_deadline>%.0f</report_deadline>\n" " <time_remaining>%.2f</time_remaining>\n" " <avg_ncpus>%f</avg_ncpus>\n" "%s" " </ip_result>\n", rp->name, rp->report_deadline, x, rp->avp->avg_ncpus, buf ); } fprintf(f, "</in_progress_results>\n"); } FILE* cof = boinc_fopen(CLIENT_OPAQUE_FILENAME, "r"); if (cof) { fprintf(f, "<client_opaque>\n<![CDATA[\n"); copy_stream(cof, f); fprintf(f, "\n]]>\n</client_opaque>\n"); } fprintf(f, "</scheduler_request>\n"); fclose(f); return 0; } // the project is uploading, and it started recently // static inline bool actively_uploading(PROJECT* p) { return p->last_upload_start && (gstate.now - p->last_upload_start < WF_DEFER_INTERVAL); } // called from the client's polling loop. // initiate scheduler RPC activity if needed and possible // bool CLIENT_STATE::scheduler_rpc_poll() { PROJECT *p; static double last_time=0; static double last_work_fetch_time = 0; double elapsed_time; if (scheduler_op->state != SCHEDULER_OP_STATE_IDLE) { last_time = now; scheduler_op->poll(); return (scheduler_op->state == SCHEDULER_OP_STATE_IDLE); } if (network_suspended) return false; // check only every 5 sec // if (now - last_time < SCHEDULER_RPC_POLL_PERIOD) return false; last_time = now; if (scheduler_op->check_master_fetch_start()) { return true; } // If we haven't run benchmarks yet, don't do a scheduler RPC. // We need to know CPU speed to handle app versions // if (!host_info.p_calculated) return false; // check for various reasons to contact particular projects. // If we need to contact a project, // see if we should ask it for work as well. // p = next_project_sched_rpc_pending(); if (p) { // if the user requested the RPC, // clear backoffs to allow work requests // if (p->sched_rpc_pending == RPC_REASON_USER_REQ) { for (int i=0; i<coprocs.n_rsc; i++) { p->rsc_pwf[i].clear_backoff(); } } work_fetch.compute_work_request(p); scheduler_op->init_op_project(p, p->sched_rpc_pending); return true; } p = next_project_trickle_up_pending(); if (p) { work_fetch.compute_work_request(p); scheduler_op->init_op_project(p, RPC_REASON_TRICKLE_UP); return true; } // report overdue results // bool suspend_soon = global_prefs.net_times.suspended(now + 1800); suspend_soon |= global_prefs.cpu_times.suspended(now + 1800); p = find_project_with_overdue_results(suspend_soon); if (p && !actively_uploading(p)) { work_fetch.compute_work_request(p); scheduler_op->init_op_project(p, RPC_REASON_RESULTS_DUE); return true; } // should we check work fetch? Do this at most once/minute if (tasks_suspended) return false; if (config.fetch_minimal_work && had_or_requested_work) return false; if (must_check_work_fetch) { last_work_fetch_time = 0; } elapsed_time = now - last_work_fetch_time; if (elapsed_time < WORK_FETCH_PERIOD) return false; must_check_work_fetch = false; last_work_fetch_time = now; p = work_fetch.choose_project(true); if (p) { if (actively_uploading(p)) { if (log_flags.work_fetch_debug) { msg_printf(p, MSG_INFO, "[work_fetch] deferring work fetch; upload active" ); } return false; } scheduler_op->init_op_project(p, RPC_REASON_NEED_WORK); return true; } return false; } static inline bool requested_work() { for (int i=0; i<coprocs.n_rsc; i++) { if (rsc_work_fetch[i].req_secs) return true; } return false; } // Handle the reply from a scheduler // int CLIENT_STATE::handle_scheduler_reply( PROJECT* project, char* scheduler_url ) { SCHEDULER_REPLY sr; FILE* f; int retval; unsigned int i; bool signature_valid, update_global_prefs=false, update_project_prefs=false; char buf[1024], filename[256]; std::string old_gui_urls = project->gui_urls; PROJECT* p2; vector<RESULT*>new_results; project->last_rpc_time = now; if (requested_work()) { had_or_requested_work = true; } get_sched_reply_filename(*project, filename, sizeof(filename)); f = fopen(filename, "r"); if (!f) return ERR_FOPEN; retval = sr.parse(f, project); fclose(f); if (retval) return retval; if (log_flags.sched_ops) { if (requested_work()) { sprintf(buf, ": got %d new tasks", (int)sr.results.size()); } else { strcpy(buf, ""); } msg_printf(project, MSG_INFO, "Scheduler request completed%s", buf); } if (log_flags.sched_op_debug) { if (sr.scheduler_version) { msg_printf(project, MSG_INFO, "[sched_op] Server version %d", sr.scheduler_version ); } } // check that master URL is correct // if (strlen(sr.master_url)) { canonicalize_master_url(sr.master_url); string url1 = sr.master_url; string url2 = project->master_url; downcase_string(url1); downcase_string(url2); if (url1 != url2) { p2 = lookup_project(sr.master_url); if (p2) { msg_printf(project, MSG_USER_ALERT, "You are attached to this project twice. Please remove projects named %s, then add %s", project->project_name, sr.master_url ); } else { msg_printf(project, MSG_INFO, _("You used the wrong URL for this project. When convenient, remove this project, then add %s"), sr.master_url ); } } } // make sure we don't already have a project of same name // bool dup_name = false; for (i=0; i<projects.size(); i++) { p2 = projects[i]; if (project == p2) continue; if (!strcmp(p2->project_name, project->project_name)) { dup_name = true; break; } } if (dup_name) { msg_printf(project, MSG_INFO, "Already attached to a project named %s (possibly with wrong URL)", project->project_name ); msg_printf(project, MSG_INFO, "Consider detaching this project, then trying again" ); } // show messages from server // for (i=0; i<sr.messages.size(); i++) { USER_MESSAGE& um = sr.messages[i]; int prio = (!strcmp(um.priority.c_str(), "notice"))?MSG_SCHEDULER_ALERT:MSG_INFO; string_substitute(um.message.c_str(), buf, sizeof(buf), "%", "%%"); msg_printf(project, prio, "%s", buf); } if (log_flags.sched_op_debug && sr.request_delay) { msg_printf(project, MSG_INFO, "Project requested delay of %.0f seconds", sr.request_delay ); } // if project is down, return error (so that we back off) // and don't do anything else // if (sr.project_is_down) { if (sr.request_delay) { double x = now + sr.request_delay; project->set_min_rpc_time(x, "project is down"); } return ERR_PROJECT_DOWN; } // if the scheduler reply includes global preferences, // insert extra elements, write to disk, and parse // if (sr.global_prefs_xml) { // skip this if we have host-specific prefs // and we're talking to an old scheduler // if (!global_prefs.host_specific || sr.scheduler_version >= 507) { retval = save_global_prefs( sr.global_prefs_xml, project->master_url, scheduler_url ); if (retval) { return retval; } update_global_prefs = true; } else { if (log_flags.sched_op_debug) { msg_printf(project, MSG_INFO, "ignoring prefs from old server; we have host-specific prefs" ); } } } // see if we have a new venue from this project // (this must go AFTER the above, since otherwise // global_prefs_source_project() is meaningless) // if (strcmp(project->host_venue, sr.host_venue)) { safe_strcpy(project->host_venue, sr.host_venue); msg_printf(project, MSG_INFO, "New computer location: %s", sr.host_venue); update_project_prefs = true; if (project == global_prefs_source_project()) { strcpy(main_host_venue, sr.host_venue); update_global_prefs = true; } } if (update_global_prefs) { read_global_prefs(); } // deal with project preferences (should always be there) // If they've changed, write to account file, // then parse to get our venue, and pass to running apps // if (sr.project_prefs_xml) { if (strcmp(project->project_prefs.c_str(), sr.project_prefs_xml)) { project->project_prefs = string(sr.project_prefs_xml); update_project_prefs = true; } } // the account file has GUI URLs and project prefs. // rewrite if either of these has changed // if (project->gui_urls != old_gui_urls || update_project_prefs) { retval = project->write_account_file(); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't write account file: %s", boincerror(retval) ); return retval; } } if (update_project_prefs) { project->parse_account_file(); if (strlen(project->host_venue)) { project->parse_account_file_venue(); } project->parse_preferences_for_user_files(); active_tasks.request_reread_prefs(project); } // if the scheduler reply includes a code-signing key, // accept it if we don't already have one from the project. // Otherwise verify its signature, using the key we already have. // if (sr.code_sign_key) { if (!strlen(project->code_sign_key)) { safe_strcpy(project->code_sign_key, sr.code_sign_key); } else { if (sr.code_sign_key_signature) { retval = check_string_signature2( sr.code_sign_key, sr.code_sign_key_signature, project->code_sign_key, signature_valid ); if (!retval && signature_valid) { safe_strcpy(project->code_sign_key, sr.code_sign_key); } else { msg_printf(project, MSG_INTERNAL_ERROR, "New code signing key doesn't validate" ); } } else { msg_printf(project, MSG_INTERNAL_ERROR, "Missing code sign key signature" ); } } } // copy new entities to client state // for (i=0; i<sr.apps.size(); i++) { APP* app = lookup_app(project, sr.apps[i].name); if (app) { strcpy(app->user_friendly_name, sr.apps[i].user_friendly_name); } else { app = new APP; *app = sr.apps[i]; retval = link_app(project, app); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't handle application %s in scheduler reply", app->name ); delete app; } else { apps.push_back(app); } } } FILE_INFO* fip; for (i=0; i<sr.file_infos.size(); i++) { fip = lookup_file_info(project, sr.file_infos[i].name); if (fip) { fip->merge_info(sr.file_infos[i]); } else { fip = new FILE_INFO; *fip = sr.file_infos[i]; retval = link_file_info(project, fip); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't handle file %s in scheduler reply", fip->name ); delete fip; } else { file_infos.push_back(fip); } } } for (i=0; i<sr.file_deletes.size(); i++) { fip = lookup_file_info(project, sr.file_deletes[i].c_str()); if (fip) { if (log_flags.file_xfer_debug) { msg_printf(project, MSG_INFO, "[file_xfer_debug] Got server request to delete file %s", fip->name ); } fip->sticky = false; } } for (i=0; i<sr.app_versions.size(); i++) { if (project->anonymous_platform) { msg_printf(project, MSG_INTERNAL_ERROR, "App version returned from anonymous platform project; ignoring" ); continue; } APP_VERSION& avpp = sr.app_versions[i]; if (strlen(avpp.platform) == 0) { strcpy(avpp.platform, get_primary_platform()); } else { if (!is_supported_platform(avpp.platform)) { msg_printf(project, MSG_INTERNAL_ERROR, "App version has unsupported platform %s", avpp.platform ); continue; } } if (avpp.missing_coproc) { msg_printf(project, MSG_INTERNAL_ERROR, "App version uses non-existent %s GPU", avpp.missing_coproc_name ); } APP* app = lookup_app(project, avpp.app_name); if (!app) { msg_printf(project, MSG_INTERNAL_ERROR, "Missing app %s", avpp.app_name ); continue; } APP_VERSION* avp = lookup_app_version( app, avpp.platform, avpp.version_num, avpp.plan_class ); if (avp) { // update performance-related info; // generally this shouldn't change, // but if it does it's better to use the new stuff // avp->avg_ncpus = avpp.avg_ncpus; avp->max_ncpus = avpp.max_ncpus; avp->flops = avpp.flops; strcpy(avp->cmdline, avpp.cmdline); avp->gpu_usage = avpp.gpu_usage; strlcpy(avp->api_version, avpp.api_version, sizeof(avp->api_version)); avp->dont_throttle = avpp.dont_throttle; avp->needs_network = avpp.needs_network; // if we had download failures, clear them // avp->clear_errors(); continue; } avp = new APP_VERSION; *avp = avpp; retval = link_app_version(project, avp); if (retval) { delete avp; continue; } app_versions.push_back(avp); } for (i=0; i<sr.workunits.size(); i++) { if (lookup_workunit(project, sr.workunits[i].name)) continue; WORKUNIT* wup = new WORKUNIT; *wup = sr.workunits[i]; wup->project = project; retval = link_workunit(project, wup); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't handle task %s in scheduler reply", wup->name ); delete wup; continue; } wup->clear_errors(); workunits.push_back(wup); } double est_rsc_runtime[MAX_RSC]; for (int j=0; j<coprocs.n_rsc; j++) { est_rsc_runtime[j] = 0; } for (i=0; i<sr.results.size(); i++) { if (lookup_result(project, sr.results[i].name)) { msg_printf(project, MSG_INTERNAL_ERROR, "Already have task %s\n", sr.results[i].name ); continue; } RESULT* rp = new RESULT; *rp = sr.results[i]; retval = link_result(project, rp); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't handle task %s in scheduler reply", rp->name ); delete rp; continue; } if (strlen(rp->platform) == 0) { strcpy(rp->platform, get_primary_platform()); rp->version_num = latest_version(rp->wup->app, rp->platform); } rp->avp = lookup_app_version( rp->wup->app, rp->platform, rp->version_num, rp->plan_class ); if (!rp->avp) { msg_printf(project, MSG_INTERNAL_ERROR, "No app version found for app %s platform %s ver %d class %s; discarding %s", rp->wup->app->name, rp->platform, rp->version_num, rp->plan_class, rp->name ); delete rp; continue; } if (rp->avp->missing_coproc) { msg_printf(project, MSG_INTERNAL_ERROR, "Missing coprocessor for task %s; aborting", rp->name ); rp->abort_inactive(EXIT_MISSING_COPROC); } else { rp->set_state(RESULT_NEW, "handle_scheduler_reply"); int rt = rp->avp->gpu_usage.rsc_type; if (rt > 0) { est_rsc_runtime[rt] += rp->estimated_runtime(); gpus_usable = true; // trigger a check of whether GPU is actually usable } else { est_rsc_runtime[0] += rp->estimated_runtime(); } } rp->wup->version_num = rp->version_num; rp->received_time = now; new_results.push_back(rp); results.push_back(rp); } sort_results(); if (log_flags.sched_op_debug) { if (sr.results.size()) { for (int j=0; j<coprocs.n_rsc; j++) { msg_printf(project, MSG_INFO, "[sched_op] estimated total %s task duration: %.0f seconds", rsc_name(j), est_rsc_runtime[j]/time_stats.availability_frac(j) ); } } } // update records for ack'ed results // for (i=0; i<sr.result_acks.size(); i++) { if (log_flags.sched_op_debug) { msg_printf(project, MSG_INFO, "[sched_op] handle_scheduler_reply(): got ack for task %s\n", sr.result_acks[i].name ); } RESULT* rp = lookup_result(project, sr.result_acks[i].name); if (rp) { rp->got_server_ack = true; } else { msg_printf(project, MSG_INTERNAL_ERROR, "Got ack for task %s, but can't find it", sr.result_acks[i].name ); } } // handle result abort requests // for (i=0; i<sr.result_abort.size(); i++) { RESULT* rp = lookup_result(project, sr.result_abort[i].name); if (rp) { ACTIVE_TASK* atp = lookup_active_task_by_result(rp); if (atp) { atp->abort_task(EXIT_ABORTED_BY_PROJECT, "aborted by project - no longer usable" ); } else { rp->abort_inactive(EXIT_ABORTED_BY_PROJECT); } } else { msg_printf(project, MSG_INTERNAL_ERROR, "Server requested abort of unknown task %s", sr.result_abort[i].name ); } } for (i=0; i<sr.result_abort_if_not_started.size(); i++) { RESULT* rp = lookup_result(project, sr.result_abort_if_not_started[i].name); if (!rp) { msg_printf(project, MSG_INTERNAL_ERROR, "Server requested conditional abort of unknown task %s", sr.result_abort_if_not_started[i].name ); continue; } if (rp->not_started) { rp->abort_inactive(EXIT_ABORTED_BY_PROJECT); } } // remove acked trickle files // if (sr.message_ack) { remove_trickle_files(project); } if (sr.send_full_workload) { project->send_full_workload = true; } project->dont_use_dcf = sr.dont_use_dcf; project->send_time_stats_log = sr.send_time_stats_log; project->send_job_log = sr.send_job_log; project->trickle_up_pending = false; // The project returns a hostid only if it has created a new host record. // In that case reset RPC seqno // if (sr.hostid) { if (project->hostid) { // if we already have a host ID for this project, // we must have sent it a stale seqno, // which usually means our state file was copied from another host. // So generate a new host CPID. // generate_new_host_cpid(); msg_printf(project, MSG_INFO, "Generated new computer cross-project ID: %s", host_info.host_cpid ); } //msg_printf(project, MSG_INFO, "Changing host ID from %d to %d", project->hostid, sr.hostid); project->hostid = sr.hostid; project->rpc_seqno = 0; } #ifdef ENABLE_AUTO_UPDATE if (sr.auto_update.present) { if (!sr.auto_update.validate_and_link(project)) { auto_update = sr.auto_update; } } #endif project->project_files = sr.project_files; project->link_project_files(); project->create_project_file_symlinks(); if (log_flags.state_debug) { msg_printf(project, MSG_INFO, "[state] handle_scheduler_reply(): State after handle_scheduler_reply():" ); print_summary(); } // the following must precede the backoff and request_delay checks, // since it overrides them // if (sr.next_rpc_delay) { project->next_rpc_time = now + sr.next_rpc_delay; } else { project->next_rpc_time = 0; } work_fetch.handle_reply(project, &sr, new_results); project->nrpc_failures = 0; project->min_rpc_time = 0; if (sr.request_delay) { double x = now + sr.request_delay; project->set_min_rpc_time(x, "requested by project"); } if (sr.got_rss_feeds) { handle_sr_feeds(sr.sr_feeds, project); } update_trickle_up_urls(project, sr.trickle_up_urls); // garbage collect in case the project sent us some irrelevant FILE_INFOs; // avoid starting transfers for them // gstate.garbage_collect_always(); return 0; } #endif // SIM void CLIENT_STATE::check_project_timeout() { unsigned int i; for (i=0; i<projects.size(); i++) { PROJECT* p = projects[i]; if (p->possibly_backed_off && now > p->min_rpc_time) { p->possibly_backed_off = false; char buf[256]; sprintf(buf, "Backoff ended for %s", p->get_project_name()); request_work_fetch(buf); } } } // find a project that needs to have its master file fetched // PROJECT* CLIENT_STATE::next_project_master_pending() { unsigned int i; PROJECT* p; for (i=0; i<projects.size(); i++) { p = projects[i]; if (p->waiting_until_min_rpc_time()) continue; if (p->suspended_via_gui) continue; if (p->master_url_fetch_pending) { return p; } } return 0; } // find a project for which a scheduler RPC has been requested // - by user // - by an account manager // - by the project // - because the project was just attached (for verification) // PROJECT* CLIENT_STATE::next_project_sched_rpc_pending() { unsigned int i; PROJECT* p; for (i=0; i<projects.size(); i++) { p = projects[i]; bool honor_backoff = true; bool honor_suspend = true; // is a scheduler-requested RPC due? // if (!p->sched_rpc_pending && p->next_rpc_time && p->next_rpc_time<now) { // don't do it if project is set to no new work // and has no jobs currently // if (!p->dont_request_more_work || p->has_results()) { p->sched_rpc_pending = RPC_REASON_PROJECT_REQ; } } switch (p->sched_rpc_pending) { case RPC_REASON_USER_REQ: honor_backoff = false; honor_suspend = false; break; case RPC_REASON_RESULTS_DUE: break; case RPC_REASON_NEED_WORK: break; case RPC_REASON_TRICKLE_UP: break; case RPC_REASON_ACCT_MGR_REQ: // This is critical for acct mgrs, to propagate new host CPIDs honor_suspend = false; break; case RPC_REASON_INIT: break; case RPC_REASON_PROJECT_REQ: break; } if (honor_backoff && p->waiting_until_min_rpc_time()) { continue; } if (honor_suspend && p->suspended_via_gui) { continue; } if (p->sched_rpc_pending) { return p; } } return 0; } PROJECT* CLIENT_STATE::next_project_trickle_up_pending() { unsigned int i; PROJECT* p; for (i=0; i<projects.size(); i++) { p = projects[i]; if (p->waiting_until_min_rpc_time()) continue; if (p->suspended_via_gui) continue; if (p->trickle_up_pending) { return p; } } return 0; } // find a project with finished results that should be reported. // This means: // - we're not backing off contacting the project // - no upload for that project is active // - the result is ready_to_report (compute done; files uploaded) // - we're within a day of the report deadline, // or at least a day has elapsed since the result was completed, // or we have a sporadic connection // or the project is in "don't request more work" state // or a network suspend period is coming up soon // PROJECT* CLIENT_STATE::find_project_with_overdue_results( bool network_suspend_soon ) { unsigned int i; RESULT* r; for (i=0; i<results.size(); i++) { r = results[i]; if (!r->ready_to_report) continue; PROJECT* p = r->project; if (p->waiting_until_min_rpc_time()) continue; if (p->suspended_via_gui) continue; #ifndef SIM if (actively_uploading(p)) continue; #endif if (p->dont_request_more_work) { return p; } if (r->report_immediately) { return p; } if (config.report_results_immediately) { return p; } if (net_status.have_sporadic_connection) { return p; } if (network_suspend_soon) { return p; } double cushion = std::max(REPORT_DEADLINE_CUSHION, work_buf_min()); if (gstate.now > r->report_deadline - cushion) { return p; } if (gstate.now > r->completed_time + SECONDS_PER_DAY) { return p; } } return 0; } // trigger work fetch // void CLIENT_STATE::request_work_fetch(const char* where) { if (log_flags.work_fetch_debug) { msg_printf(0, MSG_INFO, "[work_fetch] Request work fetch: %s", where); } must_check_work_fetch = true; }
gpl-3.0
HeySoftware/ServiQS
vendor/league/uri/src/Interfaces/Path.php
4410
<?php /** * League.Uri (http://uri.thephpleague.com) * * @package League.uri * @author Ignace Nyamagana Butera <nyamsprod@gmail.com> * @copyright 2013-2015 Ignace Nyamagana Butera * @license https://github.com/thephpleague/uri/blob/master/LICENSE (MIT License) * @version 4.2.0 * @link https://github.com/thephpleague/uri/ */ namespace League\Uri\Interfaces; use InvalidArgumentException; /** * Value object representing a URI Path component. * * Instances of this interface are considered immutable; all methods that * might change state MUST be implemented such that they retain the internal * state of the current instance and return an instance that contains the * changed state. * * @package League.uri * @author Ignace Nyamagana Butera <nyamsprod@gmail.com> * @since 4.0.0 * @see https://tools.ietf.org/html/rfc3986#section-3.3 */ interface Path extends Component { const FTP_TYPE_ASCII = 1; const FTP_TYPE_BINARY = 2; const FTP_TYPE_DIRECTORY = 3; const FTP_TYPE_EMPTY = 4; /** * Returns an instance without dot segments * * This method MUST retain the state of the current instance, and return * an instance that contains the path component normalized by removing * the dot segment. * * @return static */ public function withoutDotSegments(); /** * Returns an instance without duplicate delimiters * * This method MUST retain the state of the current instance, and return * an instance that contains the path component normalized by removing * multiple consecutive empty segment * * @return static */ public function withoutEmptySegments(); /** * Returns whether or not the path has a trailing delimiter * * @return bool */ public function hasTrailingSlash(); /** * Returns an instance with a trailing slash * * This method MUST retain the state of the current instance, and return * an instance that contains the path component with a trailing slash * * * @return static */ public function withTrailingSlash(); /** * Returns an instance without a trailing slash * * This method MUST retain the state of the current instance, and return * an instance that contains the path component without a trailing slash * * @return static */ public function withoutTrailingSlash(); /** * Returns whether or not the path is absolute or relative * * @return bool */ public function isAbsolute(); /** * Returns an instance with a leading slash * * This method MUST retain the state of the current instance, and return * an instance that contains the path component with a leading slash * * * @return static */ public function withLeadingSlash(); /** * Returns an instance without a leading slash * * This method MUST retain the state of the current instance, and return * an instance that contains the path component without a leading slash * * @return static */ public function withoutLeadingSlash(); /** * DEPRECATION WARNING! This method will be removed in the next major point release * * @deprecated deprecated since version 4.2 * * Retrieve the optional type associated to the path. * * The value returned MUST be one of the interface constant type * If no type is associated the return constant must be self::FTP_TYPE_EMPTY * * @see http://tools.ietf.org/html/rfc1738#section-3.2.2 * * @return int a typecode constant. */ public function getTypecode(); /** * DEPRECATION WARNING! This method will be removed in the next major point release * * @deprecated deprecated since version 4.2 * * Return an instance with the specified typecode. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified type appended to the path. * if not * * Using self::FTP_TYPE_EMPTY is equivalent to removing the typecode. * * @param int $type one typecode constant. * * @throws InvalidArgumentException for invalid typecode. * * @return static * */ public function withTypecode($type); }
gpl-3.0
jinzekid/codehub
python/py3_6venv/FlaskDev/hello_渲染模版.py
532
# Author: Jason Lu from flask import Flask, render_template, make_response from flask_bootstrap import Bootstrap app = Flask(__name__) bootstrap = Bootstrap(app) @app.route('/') def index(): return render_template('index.html') @app.route('/user/<name>') def user(name): return render_template('user.html', name=name) @app.errorhandler(404) def not_found(error): resp = make_response(render_template('error.html'), 404) return resp; if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
gpl-3.0
Fxe/biosynth-framework
biosynth-integration/src/main/java/edu/uminho/biosynth/core/data/integration/chimera/service/IntegrationStatisticsService.java
818
package edu.uminho.biosynth.core.data.integration.chimera.service; import java.util.Map; import pt.uminho.sysbio.biosynth.integration.IntegratedCluster; import pt.uminho.sysbio.biosynth.integration.IntegrationSet; public interface IntegrationStatisticsService { public int countTotalMetaboliteMembers(); public int countIntegratedMetaboliteMembers(IntegrationSet integrationSet); public Map<String, Integer> countTotalMetaboliteMembersByMajor(); public Map<String, Integer> countIntegratedMetaboliteMembersByMajor(IntegrationSet integrationSet); public Map<Integer, Integer> getIntegratedClusterPropertyFrequency( IntegrationSet integrationSet, String property); Map<String, Integer> getIntegratedClusterDatabaseFreq(IntegratedCluster integratedCluster); //CrossReferences ignored per db // }
gpl-3.0
popstarfreas/PhaseClient
app/node_modules/phasemobile/swipe/handler.ts
163
import SwipeDirection from "phasemobile/swipe/direction"; type Handler = (element: HTMLElement, direction: SwipeDirection) => void; export default Handler;
gpl-3.0
helencoder/WCPcms
WCP/Home/Controller/IndexController.class.php
763
<?php namespace Home\Controller; use Think\Controller; /** * 项目入口控制器 */ class IndexController extends Controller { //项目入口跳转行为(访问人员记录) public function index() { //sleep for 5 seconds //sleep(5); //存储访问用户记录(访问人员记录、时间、IP等) $res = save_browse_user_records(); if ($res) { //页面重定向 redirect(U('Home/Index/Display/main'), 0); } else { $this->save_errmsg_records(); //页面重定向 redirect(U('Home/Index/Display/main'), 0); } } /* * 存储错误记录函数 * * */ function save_errmsg_records() { } }
gpl-3.0
EverCraft/EverAPI
src/main/java/fr/evercraft/everapi/plugin/EPlugin.java
13087
/* * This file is part of EverAPI. * * EverAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EverAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EverAPI. If not, see <http://www.gnu.org/licenses/>. */ package fr.evercraft.everapi.plugin; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.concurrent.CopyOnWriteArraySet; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.game.GameReloadEvent; import org.spongepowered.api.event.game.state.GameInitializationEvent; import org.spongepowered.api.event.game.state.GameLoadCompleteEvent; import org.spongepowered.api.event.game.state.GamePostInitializationEvent; import org.spongepowered.api.event.game.state.GamePreInitializationEvent; import org.spongepowered.api.event.game.state.GameStartingServerEvent; import org.spongepowered.api.event.game.state.GameStoppingEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.scheduler.SpongeExecutorService; import com.google.common.base.Preconditions; import com.google.inject.Inject; import fr.evercraft.everapi.EverAPI; import fr.evercraft.everapi.exception.PluginDisableException; import fr.evercraft.everapi.exception.ServerDisableException; import fr.evercraft.everapi.plugin.command.ECommand; import fr.evercraft.everapi.plugin.file.EConfig; import fr.evercraft.everapi.plugin.file.EFile; import fr.evercraft.everapi.plugin.file.EMessage; import fr.evercraft.everapi.server.EServer; import fr.evercraft.everapi.stats.Metrics; public abstract class EPlugin<T extends EPlugin<T>> { @Inject private Game game; @Inject private PluginContainer pluginContainer; @Inject @ConfigDir(sharedRoot = false) private Path path; @Inject private Metrics metrics; private EverAPI everapi; private boolean enable; private final CopyOnWriteArraySet<EFile<T>> files; private final CopyOnWriteArraySet<ECommand<T>> commands; private ELogger logger; protected void onFirst() throws PluginDisableException, ServerDisableException{}; protected abstract void onPreEnable() throws PluginDisableException, ServerDisableException; protected void onEnable() throws PluginDisableException, ServerDisableException{} protected void onPostEnable() throws PluginDisableException, ServerDisableException{} protected abstract void onCompleteEnable() throws PluginDisableException, ServerDisableException; protected void onStartServer() throws PluginDisableException, ServerDisableException{} protected void onStopServer() throws PluginDisableException, ServerDisableException{} protected abstract void onDisable() throws PluginDisableException, ServerDisableException; public abstract EConfig<T> getConfigs(); public abstract EMessage<T> getMessages(); public abstract EnumPermission[] getPermissions(); public EPlugin(){ this.enable = true; this.files = new CopyOnWriteArraySet<EFile<T>>(); this.commands = new CopyOnWriteArraySet<ECommand<T>>(); } @Listener(order=Order.FIRST) public void onGamePreInitializationFirst(GamePreInitializationEvent event) { try { this.setupEverAPI(); if (this.getEverAPI().isEnable() && this.enable) { this.onFirst(); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); this.disable(); } catch (ServerDisableException e) { e.execute(); } } @Listener public void onGamePreInitialization(GamePreInitializationEvent event) { try { if (this.getEverAPI().isEnable() && this.enable) { this.onPreEnable(); this.getELogger().debug("---------------------------------------------------------"); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); this.disable(); } catch (ServerDisableException e) { e.execute(); } } @Listener public void onGameInitializationEvent(GameInitializationEvent event) { try { if (this.getEverAPI().isEnable() && this.enable){ this.getELogger().debug("------------------------- Enable ------------------------"); this.onEnable(); this.getELogger().debug("---------------------------------------------------------"); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); this.disable(); } catch (ServerDisableException e) { e.execute(); } } @Listener public void onGamePostInitializationEvent(GamePostInitializationEvent event) { try { if (this.getEverAPI().isEnable() && this.enable){ this.getELogger().debug("---------------------- Post-Enable ----------------------"); this.onPostEnable(); this.getELogger().debug("---------------------------------------------------------"); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); this.disable(); } catch (ServerDisableException e) { e.execute(); } } @Listener public void onGameLoadCompleteEvent(GameLoadCompleteEvent event) { try { this.setupEverAPI(); if (this.getEverAPI().isEnable() && this.enable){ this.getELogger().debug("-------------------- Complete-Enable --------------------"); this.onCompleteEnable(); this.getELogger().debug("---------------------------------------------------------"); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); this.disable(); } catch (ServerDisableException e) { e.execute(); } } @Listener public void onGameStartingServerEvent(GameStartingServerEvent event) { try { if (this.getEverAPI().isEnable() && this.enable){ this.getELogger().debug("---------------------- Start-Server ---------------------"); this.onStartServer(); this.getELogger().debug("---------------------------------------------------------"); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); this.disable(); } catch (ServerDisableException e) { e.execute(); } } @Listener public void onReload(GameReloadEvent event){ this.reload(); } public void reload(){ try { if (this.getEverAPI().isEnable() && this.enable) { this.getELogger().debug("------------------------- Reload ------------------------"); this.onReload(); this.getELogger().debug("---------------------------------------------------------"); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); this.disable(); } catch (ServerDisableException e) { e.execute(); } } protected void onReload() throws PluginDisableException, ServerDisableException { this.reloadConfigurations(); this.reloadCommands(); } @Listener public void onGameStoppingEvent(GameStoppingServerEvent event) throws ServerDisableException { try { if (this.getEverAPI().isEnable() && this.enable){ this.getELogger().debug("----------------------- Stop-Server ---------------------"); this.onStopServer(); this.getELogger().debug("---------------------------------------------------------"); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); this.disable(); } catch (ServerDisableException e) { e.execute(); } } @Listener public void onGameStoppingEvent(GameStoppingEvent event) throws ServerDisableException { disable(); } public void disable() { try { if (this.enable){ this.getELogger().debug("------------------------- Disable -----------------------"); this.onDisable(); this.enable = false; this.getELogger().debug("---------------------------------------------------------"); } } catch (PluginDisableException e) { this.getELogger().info(e.getMessage()); } catch (ServerDisableException e) { e.execute(); } } @Inject private void setLogger(Logger logger) { this.logger = new ELogger(logger); } /* * Accesseur */ /** * Retourne Game * @return Game */ public Game getGame(){ return this.game; } /** * Retourne Path * @return Path */ public Path getPath(){ return this.path; } /** * Retourne Logger * @return Logger */ public ELogger getELogger(){ return this.logger; } /** * Retourne l'ID du plugin * @return L'ID du plugin */ public String getId(){ return this.pluginContainer.getId(); } /** * Retourne le nom du plugin * @return Le nom du plugin */ public String getName(){ return this.pluginContainer.getName(); } /** * Retourne la version du plugin * @return La version du plugin */ public Optional<String> getVersion(){ return this.pluginContainer.getVersion(); } /** * Retourne la description du plugin * @return La description du plugin */ public Optional<String> getDescription(){ return this.pluginContainer.getDescription(); } /** * Retourne la description du plugin * @return La description du plugin */ public Optional<String> getUrl(){ return this.pluginContainer.getUrl(); } /** * Retourne la description du plugin * @return La description du plugin */ public List<String> getAuthors(){ return this.pluginContainer.getAuthors(); } /** * Retourne True si le plugin est activé * @return True si le plugin est activé */ public boolean isEnable(){ return this.enable; } /* * EverAPI */ /** * Retourne EverAPI * @return EverAPI */ public EverAPI getEverAPI(){ return this.everapi; } /** * Initialise le plugin EverAPI * @return True si le plugin EverAPI est activé * @throws ServerDisableException */ protected void setupEverAPI() throws ServerDisableException { Optional<PluginContainer> plugin = this.game.getPluginManager().getPlugin("everapi"); if (plugin.isPresent()) { Optional<?> everapi = plugin.get().getInstance(); if (everapi.isPresent() && everapi.get() instanceof EverAPI) { this.everapi = (EverAPI) everapi.get(); } else { throw new ServerDisableException(this, "Le plugin EverAPI n'est pas activé"); } } else { throw new ServerDisableException(this, "Le plugin EverAPI n'est pas sur le serveur"); } } /* * Ajout de fonctionnalité */ /** * Retourne EServer * @return EServer */ public EServer getEServer(){ return this.getEverAPI().getEServer(); } public EChat getChat() { return this.getEverAPI().getChat(); } public SpongeExecutorService getThreadAsync() { return this.getEverAPI().getThreadAsync(); } public SpongeExecutorService getThreadSync() { return this.getEverAPI().getThreadSync(); } public Metrics getMetrics() { return this.metrics; } /* * Configuration */ /** * Ajoute un fichier de configuration à la liste */ public void registerConfiguration(final EFile<T> file) { this.files.add(file); } /** * Supprime un fichier de configuration à la liste */ public void removeConfiguration(final EFile<T> file) { this.files.remove(file); } /** * Recharge tous les fichiers de configuration de la liste */ public void reloadConfigurations(){ for (EFile<T> file : this.files){ file.reload(); } } /* * Command */ /** * Ajoute une commande à la liste */ public void registerCommand(final ECommand<T> command) { this.commands.add(command); } /** * Supprime une commande à la liste */ public void removeCommand(final ECommand<T> command) { this.commands.remove(command); } /** * Recharge toutes les commandes de la liste */ public void reloadCommands() { for (ECommand<T> command : this.commands){ command.reload(); } } public PluginContainer getPluginContainer() { Optional<PluginContainer> optPlugin = this.getGame().getPluginManager().fromInstance(this); Preconditions.checkArgument(optPlugin.isPresent(), "Provided object is not a plugin instance"); return optPlugin.get(); } public Cause getCurrentCause() { return this.game.getCauseStackManager().getCurrentCause(); } }
gpl-3.0
slq/tokfm-parser
src/main/java/com/slq/scrappy/tokfm/TokFm.java
3859
package com.slq.scrappy.tokfm; import com.slq.scrappy.tokfm.podcast.PodcastData; import com.slq.scrappy.tokfm.podcast.PodcastDownloadService; import com.slq.scrappy.tokfm.podcast.PodcastInterceptorChain; import com.slq.scrappy.tokfm.podcast.Podcasts; import com.slq.scrappy.tokfm.podcast.ResponseProcessor; import com.slq.scrappy.tokfm.podcast.interceptor.FileAlreadyExistsPodcastInterceptor; import com.slq.scrappy.tokfm.podcast.interceptor.FilenameMatchingPodcastInterceptor; import com.slq.scrappy.tokfm.podcast.interceptor.PodcastDownloadInterceptor; import com.slq.scrappy.tokfm.podcast.interceptor.PodcastInterceptor; import com.slq.scrappy.tokfm.podcast.interceptor.SkipExistingFilesPodcastInterceptor; import com.slq.scrappy.tokfm.podcast.repository.FilePodcastRepository; import com.slq.scrappy.tokfm.podcast.repository.PodcastRepository; import com.slq.tokfm.api.Podcast; import com.slq.tokfm.internal.HttpPodcastInfoService; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.LinkedList; import java.util.List; import static java.lang.String.format; public class TokFm { public static final String START_URL = "http://audycje.tokfm.pl/podcasts?offset=%d"; private static final String MATCH_PATTERN_OPTION = "m"; private static final String SKIP_EXISTING_OPTION = "s"; private static final int ITERATION_MAX_COUNT = 100000; private PodcastDownloadService podcastDownloadService; private ResponseProcessor responseProcessor; public TokFm(PodcastDownloadService podcastDownloadService, ResponseProcessor responseProcessor) { this.podcastDownloadService = podcastDownloadService; this.responseProcessor = responseProcessor; } public void downloadPodcasts(String[] args) throws IOException, NoSuchAlgorithmException, ParseException { // create Options object Options options = new Options(); // add t option options.addOption(SKIP_EXISTING_OPTION, false, "skip existing podcasts") .addOption(MATCH_PATTERN_OPTION, true, "match podcast name with pattern"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); List<PodcastInterceptor> interceptors = new LinkedList<>(); if (cmd.hasOption(MATCH_PATTERN_OPTION)) { interceptors.add(new FilenameMatchingPodcastInterceptor(cmd.getOptionValue(MATCH_PATTERN_OPTION))); } if (cmd.hasOption(SKIP_EXISTING_OPTION)) { interceptors.add(new SkipExistingFilesPodcastInterceptor()); } else { PodcastRepository podcastRepository = new FilePodcastRepository(); interceptors.add(new FileAlreadyExistsPodcastInterceptor(podcastRepository)); } interceptors.add(new PodcastDownloadInterceptor(podcastDownloadService, responseProcessor)); PodcastInterceptorChain chain = new PodcastInterceptorChain(interceptors); download(chain); } private void download(PodcastInterceptorChain chain) throws IOException { for (int offset = 0; offset < ITERATION_MAX_COUNT; offset++) { String url = format(START_URL, offset); Podcasts podcasts = podcastDownloadService.listPodcasts(url); podcasts.forEach(chain::process); } } public static void main(String[] args) throws IOException, NoSuchAlgorithmException, ParseException { //HttpClient client = HttpClientFactory.createNtlmProxyClient(); //HttpClient client = HttpClientFactory.createClient(); //TokFm tokFm = new TokFm(new PodcastDownloadService(client), new ResponseProcessor()); //tokFm.downloadPodcasts(args); List<PodcastData> podcasts = new HttpPodcastInfoService().getAll(); podcasts.stream() .map(Podcast::getSeriesName) .forEach(System.out::println); } }
gpl-3.0
petre2dor/piGarden
devices/controller/gpio/md-rd/read_dev.py
173
import time import random print '{"httpCode": "200", "type": "SUCCESS", "message": "All good.", "data": [{"type": "RAINING", "value": "'+str(random.randrange(0, 2))+'"}]}'
gpl-3.0
S1Products/S1WifiServer
Libraries/MessageRoutingEngine/src/info/s1products/server/event/PacketNotifiedListener.java
662
/******************************************************************************* * Copyright (c) 2013 Shuichi Miura. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Shuichi Miura - initial API and implementation ******************************************************************************/ package info.s1products.server.event; public interface PacketNotifiedListener { void packetNotified(PacketNotifiedEvent event); }
gpl-3.0
MNKgod/darkstar
scripts/globals/abilities/pets/searing_light.lua
1090
--------------------------------------------------- -- Searing Light --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/magic"); --------------------------------------------------- function onAbilityCheck(player, target, ability) local level = player:getMainLvl() * 2; if(player:getMP()<level) then return 87,0; end return 0,0; end; function onPetAbility(target, pet, skill) local dINT = math.floor(pet:getStat(MOD_INT) - target:getStat(MOD_INT)); local level = pet:getMainLvl() local damage = 26 + (level * 6); damage = damage + (dINT * 1.5); damage = MobMagicalMove(pet,target,skill,damage,ELE_LIGHT,1,TP_NO_EFFECT,0); damage = mobAddBonuses(pet, nil, target, damage.dmg, ELE_LIGHT); damage = AvatarFinalAdjustments(damage,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,1); target:delHP(damage); target:updateEnmityFromDamage(pet,damage); return damage; end
gpl-3.0
zymtech/leetcode
datastructure/tree/TreeNode.py
185
# -*- coding: utf-8 -*- # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None
gpl-3.0
wuhaining/-wuhaining.github.io
ApplicationTest/bpmWebService/src/oracle/bpel/services/workflow/query/model/LogicalOperatorEnumType.java
826
package oracle.bpel.services.workflow.query.model; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for LogicalOperatorEnumType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="LogicalOperatorEnumType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="AND"/> * &lt;enumeration value="OR"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "LogicalOperatorEnumType") @XmlEnum public enum LogicalOperatorEnumType { AND, OR; public String value() { return name(); } public static LogicalOperatorEnumType fromValue(String v) { return valueOf(v); } }
gpl-3.0
joruri/joruri-maps
lib/gis/model/base/status.rb
457
# encoding: utf-8 module Gis::Model::Base::Status def state_select [["有効","enabled"],["無効","disabled"]] end def state_show select = state_select select.each{|a| return a[0] if a[1] == state} return nil end def user_kind_select [["個別ユーザ管理",1],["所属管理",2]] end def user_kind_show select = user_kind_select select.each{|a| return a[0] if a[1] == user_kind} return nil end end
gpl-3.0
michaelkbradshaw/cummulative-quiz
moodleCQuiz/root/mod/cquiz/accessmanager.php
18773
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Classes to enforce the various access rules that can apply to a cquiz. * * @package mod * @subpackage cquiz * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * This class keeps track of the various access rules that apply to a particular * cquiz, with convinient methods for seeing whether access is allowed. * * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class cquiz_access_manager { /** @var cquiz the cquiz settings object. */ protected $cquizobj; /** @var int the time to be considered as 'now'. */ protected $timenow; /** @var array of cquiz_access_rule_base. */ protected $rules = array(); /** * Create an instance for a particular cquiz. * @param object $cquizobj An instance of the class cquiz from attemptlib.php. * The cquiz we will be controlling access to. * @param int $timenow The time to use as 'now'. * @param bool $canignoretimelimits Whether this user is exempt from time * limits (has_capability('mod/cquiz:ignoretimelimits', ...)). */ public function __construct($cquizobj, $timenow, $canignoretimelimits) { $this->cquizobj = $cquizobj; $this->timenow = $timenow; $this->rules = $this->make_rules($cquizobj, $timenow, $canignoretimelimits); } /** * Make all the rules relevant to a particular cquiz. * @param cquiz $cquizobj information about the cquiz in question. * @param int $timenow the time that should be considered as 'now'. * @param bool $canignoretimelimits whether the current user is exempt from * time limits by the mod/cquiz:ignoretimelimits capability. * @return array of {@link cquiz_access_rule_base}s. */ protected function make_rules($cquizobj, $timenow, $canignoretimelimits) { $rules = array(); foreach (self::get_rule_classes() as $ruleclass) { $rule = $ruleclass::make($cquizobj, $timenow, $canignoretimelimits); if ($rule) { $rules[$ruleclass] = $rule; } } $superceededrules = array(); foreach ($rules as $rule) { $superceededrules += $rule->get_superceded_rules(); } foreach ($superceededrules as $superceededrule) { unset($rules['cquizaccess_' . $superceededrule]); } return $rules; } /** * @return array of all the installed rule class names. */ protected static function get_rule_classes() { return get_plugin_list_with_class('cquizaccess', '', 'rule.php'); } /** * Add any form fields that the access rules require to the settings form. * * Note that the standard plugins do not use this mechanism, becuase all their * settings are stored in the cquiz table. * * @param mod_cquiz_mod_form $cquizform the cquiz settings form that is being built. * @param MoodleQuickForm $mform the wrapped MoodleQuickForm. */ public static function add_settings_form_fields( mod_cquiz_mod_form $cquizform, MoodleQuickForm $mform) { foreach (self::get_rule_classes() as $rule) { $rule::add_settings_form_fields($cquizform, $mform); } } /** * The the options for the Browser security settings menu. * * @return array key => lang string. */ public static function get_browser_security_choices() { $options = array('-' => get_string('none', 'cquiz')); foreach (self::get_rule_classes() as $rule) { $options += $rule::get_browser_security_choices(); } return $options; } /** * Validate the data from any form fields added using {@link add_settings_form_fields()}. * @param array $errors the errors found so far. * @param array $data the submitted form data. * @param array $files information about any uploaded files. * @param mod_cquiz_mod_form $cquizform the cquiz form object. * @return array $errors the updated $errors array. */ public static function validate_settings_form_fields(array $errors, array $data, $files, mod_cquiz_mod_form $this) { foreach (self::get_rule_classes() as $rule) { $errors = $rule::validate_settings_form_fields($errors, $data, $files, $this); } return $errors; } /** * Save any submitted settings when the cquiz settings form is submitted. * * Note that the standard plugins do not use this mechanism, becuase all their * settings are stored in the cquiz table. * * @param object $cquiz the data from the cquiz form, including $cquiz->id * which is the is of the cquiz being saved. */ public static function save_settings($cquiz) { foreach (self::get_rule_classes() as $rule) { $rule::save_settings($cquiz); } } /** * Build the SQL for loading all the access settings in one go. * @param int $cquizid the cquiz id. * @param string $basefields initial part of the select list. * @return array with two elements, the sql and the placeholder values. * If $basefields is '' then you must allow for the possibility that * there is no data to load, in which case this method returns $sql = ''. */ protected static function get_load_sql($cquizid, $rules, $basefields) { $allfields = $basefields; $alljoins = '{cquiz} cquiz'; $allparams = array('cquizid' => $cquizid); foreach ($rules as $rule) { list($fields, $joins, $params) = $rule::get_settings_sql($cquizid); if ($fields) { if ($allfields) { $allfields .= ', '; } $allfields .= $fields; } if ($joins) { $alljoins .= ' ' . $joins; } if ($params) { $allparams += $params; } } if ($allfields === '') { return array('', array()); } return array("SELECT $allfields FROM $alljoins WHERE cquiz.id = :cquizid", $allparams); } /** * Load any settings required by the access rules. We try to do this with * a single DB query. * * Note that the standard plugins do not use this mechanism, becuase all their * settings are stored in the cquiz table. * * @param int $cquizid the cquiz id. * @return array setting value name => value. The value names should all * start with the name of the corresponding plugin to avoid collisions. */ public static function load_settings($cquizid) { global $DB; $rules = self::get_rule_classes(); list($sql, $params) = self::get_load_sql($cquizid, $rules, ''); if ($sql) { $data = (array) $DB->get_record_sql($sql, $params); } else { $data = array(); } foreach ($rules as $rule) { $data += $rule::get_extra_settings($cquizid); } return $data; } /** * Load the cquiz settings and any settings required by the access rules. * We try to do this with a single DB query. * * Note that the standard plugins do not use this mechanism, becuase all their * settings are stored in the cquiz table. * * @param int $cquizid the cquiz id. * @return object mdl_cquiz row with extra fields. */ public static function load_cquiz_and_settings($cquizid) { global $DB; $rules = self::get_rule_classes(); list($sql, $params) = self::get_load_sql($cquizid, $rules, 'cquiz.*'); $cquiz = $DB->get_record_sql($sql, $params, MUST_EXIST); foreach ($rules as $rule) { foreach ($rule::get_extra_settings($cquizid) as $name => $value) { $cquiz->$name = $value; } } return $cquiz; } /** * @return array the class names of all the active rules. Mainly useful for * debugging. */ public function get_active_rule_names() { $classnames = array(); foreach ($this->rules as $rule) { $classnames[] = get_class($rule); } return $classnames; } /** * Accumulates an array of messages. * @param array $messages the current list of messages. * @param string|array $new the new messages or messages. * @return array the updated array of messages. */ protected function accumulate_messages($messages, $new) { if (is_array($new)) { $messages = array_merge($messages, $new); } else if (is_string($new) && $new) { $messages[] = $new; } return $messages; } /** * Provide a description of the rules that apply to this cquiz, such * as is shown at the top of the cquiz view page. Note that not all * rules consider themselves important enough to output a description. * * @return array an array of description messages which may be empty. It * would be sensible to output each one surrounded by &lt;p> tags. */ public function describe_rules() { $result = array(); foreach ($this->rules as $rule) { $result = $this->accumulate_messages($result, $rule->description()); } return $result; } /** * Whether or not a user should be allowed to start a new attempt at this cquiz now. * If there are any restrictions in force now, return an array of reasons why access * should be blocked. If access is OK, return false. * * @param int $numattempts the number of previous attempts this user has made. * @param object|false $lastattempt information about the user's last completed attempt. * if there is not a previous attempt, the false is passed. * @return mixed An array of reason why access is not allowed, or an empty array * (== false) if access should be allowed. */ public function prevent_new_attempt($numprevattempts, $lastattempt) { $reasons = array(); foreach ($this->rules as $rule) { $reasons = $this->accumulate_messages($reasons, $rule->prevent_new_attempt($numprevattempts, $lastattempt)); } return $reasons; } /** * Whether the user should be blocked from starting a new attempt or continuing * an attempt now. If there are any restrictions in force now, return an array * of reasons why access should be blocked. If access is OK, return false. * * @return mixed An array of reason why access is not allowed, or an empty array * (== false) if access should be allowed. */ public function prevent_access() { $reasons = array(); foreach ($this->rules as $rule) { $reasons = $this->accumulate_messages($reasons, $rule->prevent_access()); } return $reasons; } /** * @param int|null $attemptid the id of the current attempt, if there is one, * otherwise null. * @return bool whether a check is required before the user starts/continues * their attempt. */ public function is_preflight_check_required($attemptid) { foreach ($this->rules as $rule) { if ($rule->is_preflight_check_required($attemptid)) { return true; } } return false; } /** * Build the form required to do the pre-flight checks. * @param moodle_url $url the form action URL. * @param int|null $attemptid the id of the current attempt, if there is one, * otherwise null. * @return mod_cquiz_preflight_check_form the form. */ public function get_preflight_check_form(moodle_url $url, $attemptid) { return new mod_cquiz_preflight_check_form($url->out_omit_querystring(), array('rules' => $this->rules, 'cquizobj' => $this->cquizobj, 'attemptid' => $attemptid, 'hidden' => $url->params())); } /** * The pre-flight check has passed. This is a chance to record that fact in * some way. * @param int|null $attemptid the id of the current attempt, if there is one, * otherwise null. */ public function notify_preflight_check_passed($attemptid) { foreach ($this->rules as $rule) { $rule->notify_preflight_check_passed($attemptid); } } /** * Inform the rules that the current attempt is finished. This is use, for example * by the password rule, to clear the flag in the session. */ public function current_attempt_finished() { foreach ($this->rules as $rule) { $rule->current_attempt_finished(); } } /** * Do any of the rules mean that this student will no be allowed any further attempts at this * cquiz. Used, for example, to change the label by the grade displayed on the view page from * 'your current grade is' to 'your final grade is'. * * @param int $numattempts the number of previous attempts this user has made. * @param object $lastattempt information about the user's last completed attempt. * @return bool true if there is no way the user will ever be allowed to attempt * this cquiz again. */ public function is_finished($numprevattempts, $lastattempt) { foreach ($this->rules as $rule) { if ($rule->is_finished($numprevattempts, $lastattempt)) { return true; } } return false; } /** * Sets up the attempt (review or summary) page with any properties required * by the access rules. * * @param moodle_page $page the page object to initialise. */ public function setup_attempt_page($page) { foreach ($this->rules as $rule) { $rule->setup_attempt_page($page); } } /** * Compute when the attempt must be submitted. * * @param object $attempt the data from the relevant cquiz_attempts row. * @return int|false the attempt close time. * False if there is no limit. */ public function get_end_time($attempt) { $timeclose = false; foreach ($this->rules as $rule) { $ruletimeclose = $rule->end_time($attempt); if ($ruletimeclose !== false && ($timeclose === false || $ruletimeclose < $timeclose)) { $timeclose = $ruletimeclose; } } return $timeclose; } /** * Compute what should be displayed to the user for time remaining in this attempt. * * @param object $attempt the data from the relevant cquiz_attempts row. * @param int $timenow the time to consider as 'now'. * @return int|false the number of seconds remaining for this attempt. * False if no limit should be displayed. */ public function get_time_left_display($attempt, $timenow) { $timeleft = false; foreach ($this->rules as $rule) { $ruletimeleft = $rule->time_left_display($attempt, $timenow); if ($ruletimeleft !== false && ($timeleft === false || $ruletimeleft < $timeleft)) { $timeleft = $ruletimeleft; } } return $timeleft; } /** * @return bolean if this cquiz should only be shown to students in a popup window. */ public function attempt_must_be_in_popup() { foreach ($this->rules as $rule) { if ($rule->attempt_must_be_in_popup()) { return true; } } return false; } /** * @return array any options that are required for showing the attempt page * in a popup window. */ public function get_popup_options() { $options = array(); foreach ($this->rules as $rule) { $options += $rule->get_popup_options(); } return $options; } /** * Send the user back to the cquiz view page. Normally this is just a redirect, but * If we were in a secure window, we close this window, and reload the view window we came from. * * This method does not return; * * @param mod_cquiz_renderer $output the cquiz renderer. * @param string $message optional message to output while redirecting. */ public function back_to_view_page($output, $message = '') { if ($this->attempt_must_be_in_popup()) { echo $output->close_attempt_popup($this->cquizobj->view_url(), $message); die(); } else { redirect($this->cquizobj->view_url(), $message); } } /** * Make some text into a link to review the cquiz, if that is appropriate. * * @param string $linktext some text. * @param object $attempt the attempt object * @return string some HTML, the $linktext either unmodified or wrapped in a * link to the review page. */ public function make_review_link($attempt, $reviewoptions, $output) { // If the attempt is still open, don't link. if (in_array($attempt->state, array(cquiz_attempt::IN_PROGRESS, cquiz_attempt::OVERDUE))) { return $output->no_review_message(''); } $when = cquiz_attempt_state($this->cquizobj->get_cquiz(), $attempt); $reviewoptions = mod_cquiz_display_options::make_from_cquiz( $this->cquizobj->get_cquiz(), $when); if (!$reviewoptions->attempt) { return $output->no_review_message($this->cquizobj->cannot_review_message($when, true)); } else { return $output->review_link($this->cquizobj->review_url($attempt->id), $this->attempt_must_be_in_popup(), $this->get_popup_options()); } } }
gpl-3.0
Novatouch/Corba
LivreEnLigne/src/LivreEnLigne/_BanqueStub.java
2535
package LivreEnLigne; /** * Interface definition : Banque * * @author OpenORB Compiler */ public class _BanqueStub extends org.omg.CORBA.portable.ObjectImpl implements Banque { static final String[] _ids_list = { "IDL:LivreEnLigne/Banque:1.0" }; public String[] _ids() { return _ids_list; } private final static Class _opsClass = LivreEnLigne.BanqueOperations.class; /** * Operation verifierCoordonneesBancaires */ public void verifierCoordonneesBancaires(String pCompte, String pCode) throws LivreEnLigne.ExceptionMoneyTransferRefused { while(true) { if (!this._is_local()) { org.omg.CORBA.portable.InputStream _input = null; try { org.omg.CORBA.portable.OutputStream _output = this._request("verifierCoordonneesBancaires",true); _output.write_string(pCompte); _output.write_string(pCode); _input = this._invoke(_output); return; } catch(org.omg.CORBA.portable.RemarshalException _exception) { continue; } catch(org.omg.CORBA.portable.ApplicationException _exception) { String _exception_id = _exception.getId(); if (_exception_id.equals(LivreEnLigne.ExceptionMoneyTransferRefusedHelper.id())) { throw LivreEnLigne.ExceptionMoneyTransferRefusedHelper.read(_exception.getInputStream()); } throw new org.omg.CORBA.UNKNOWN("Unexpected User Exception: "+ _exception_id); } finally { this._releaseReply(_input); } } else { org.omg.CORBA.portable.ServantObject _so = _servant_preinvoke("verifierCoordonneesBancaires",_opsClass); if (_so == null) continue; LivreEnLigne.BanqueOperations _self = (LivreEnLigne.BanqueOperations) _so.servant; try { _self.verifierCoordonneesBancaires( pCompte, pCode); return; } finally { _servant_postinvoke(_so); } } } } }
gpl-3.0
axkr/symja_android_library
symja_android_library/tools/src/main/java/org/matheclipse/core/mathcell/PlotButtonExample.java
351
package org.matheclipse.core.mathcell; public class PlotButtonExample extends BasePlotExample { @Override public String exampleFunction() { return "Manipulate(Plot(f(x), {x, 0, 2*Pi}), {f, {Sin, Cos, Tan, Cot}})"; } public static void main(String[] args) { PlotButtonExample p = new PlotButtonExample(); p.generateHTML(); } }
gpl-3.0
Studio182/Crystal-Mail
plugins/managesieve/managesieve.js
16077
/* Sieve Filters (tab) */ if (window.cmail) { cmail.addEventListener('init', function(evt) { var tab = $('<span>').attr('id', 'settingstabpluginmanagesieve').addClass('tablink'); var button = $('<a>').attr('href', cmail.env.comm_path+'&_action=plugin.managesieve') .attr('title', cmail.gettext('managesieve.managefilters')) .html(cmail.gettext('managesieve.filters')) .bind('click', function(e){ return cmail.command('plugin.managesieve', this) }) .appendTo(tab); // add button and register commands cmail.add_element(tab, 'tabs'); cmail.register_command('plugin.managesieve', function() { cmail.goto_url('plugin.managesieve') }, true); cmail.register_command('plugin.managesieve-save', function() { cmail.managesieve_save() }, true); cmail.register_command('plugin.managesieve-add', function() { cmail.managesieve_add() }, true); cmail.register_command('plugin.managesieve-del', function() { cmail.managesieve_del() }, true); cmail.register_command('plugin.managesieve-up', function() { cmail.managesieve_up() }, true); cmail.register_command('plugin.managesieve-down', function() { cmail.managesieve_down() }, true); cmail.register_command('plugin.managesieve-set', function() { cmail.managesieve_set() }, true); cmail.register_command('plugin.managesieve-setadd', function() { cmail.managesieve_setadd() }, true); cmail.register_command('plugin.managesieve-setdel', function() { cmail.managesieve_setdel() }, true); cmail.register_command('plugin.managesieve-setact', function() { cmail.managesieve_setact() }, true); cmail.register_command('plugin.managesieve-setget', function() { cmail.managesieve_setget() }, true); if (cmail.env.action == 'plugin.managesieve') { if (cmail.gui_objects.sieveform) { cmail.enable_command('plugin.managesieve-save', true); } else { cmail.enable_command('plugin.managesieve-del', 'plugin.managesieve-up', 'plugin.managesieve-down', false); cmail.enable_command('plugin.managesieve-add', 'plugin.managesieve-setadd', !cmail.env.sieveconnerror); } if (cmail.gui_objects.filterslist) { var p = cmail; cmail.filters_list = new crystal_list_widget(cmail.gui_objects.filterslist, {multiselect:false, draggable:false, keyboard:false}); cmail.filters_list.addEventListener('select', function(o){ p.managesieve_select(o); }); cmail.filters_list.init(); cmail.filters_list.focus(); cmail.enable_command('plugin.managesieve-set', true); cmail.enable_command('plugin.managesieve-setact', 'plugin.managesieve-setget', cmail.gui_objects.filtersetslist.length); cmail.enable_command('plugin.managesieve-setdel', cmail.gui_objects.filtersetslist.length > 1); $('#'+cmail.buttons['plugin.managesieve-setact'][0].id).attr('title', cmail.gettext('managesieve.filterset' + (cmail.gui_objects.filtersetslist.value == cmail.env.active_set ? 'deact' : 'act'))); } } if (cmail.gui_objects.sieveform && cmail.env.rule_disabled) $('#disabled').attr('checked', true); }); }; /*********************************************************/ /********* Managesieve filters methods *********/ /*********************************************************/ crystal_webmail.prototype.managesieve_add = function() { this.load_managesieveframe(); this.filters_list.clear_selection(); }; crystal_webmail.prototype.managesieve_del = function() { var id = this.filters_list.get_single_selection(); if (confirm(this.get_label('managesieve.filterdeleteconfirm'))) this.http_request('plugin.managesieve', '_act=delete&_fid='+this.filters_list.rows[id].uid, true); }; crystal_webmail.prototype.managesieve_up = function() { var id = this.filters_list.get_single_selection(); this.http_request('plugin.managesieve', '_act=up&_fid='+this.filters_list.rows[id].uid, true); }; crystal_webmail.prototype.managesieve_down = function() { var id = this.filters_list.get_single_selection(); this.http_request('plugin.managesieve', '_act=down&_fid='+this.filters_list.rows[id].uid, true); }; crystal_webmail.prototype.managesieve_rowid = function(id) { var i, rows = this.filters_list.rows; for (i=0; i<rows.length; i++) if (rows[i] != null && rows[i].uid == id) return i; } crystal_webmail.prototype.managesieve_updatelist = function(action, name, id, disabled) { this.set_busy(true); switch (action) { case 'delete': this.filters_list.remove_row(this.managesieve_rowid(id)); this.filters_list.clear_selection(); this.enable_command('plugin.managesieve-del', 'plugin.managesieve-up', 'plugin.managesieve-down', false); this.show_contentframe(false); // re-numbering filters var i, rows = this.filters_list.rows; for (i=0; i<rows.length; i++) { if (rows[i] != null && rows[i].uid > id) rows[i].uid = rows[i].uid-1; } break; case 'down': var from, fromstatus, status, rows = this.filters_list.rows; // we need only to replace filter names... for (var i=0; i<rows.length; i++) { if (rows[i]==null) { // removed row continue; } else if (rows[i].uid == id) { from = rows[i].obj; fromstatus = $(from).hasClass('disabled'); } else if (rows[i].uid == id+1) { name = rows[i].obj.cells[0].innerHTML; status = $(rows[i].obj).hasClass('disabled'); rows[i].obj.cells[0].innerHTML = from.cells[0].innerHTML; from.cells[0].innerHTML = name; $(from)[status?'addClass':'removeClass']('disabled'); $(rows[i].obj)[fromstatus?'addClass':'removeClass']('disabled'); this.filters_list.highlight_row(i); break; } } // ... and disable/enable Down button this.filters_listbuttons(); break; case 'up': var from, status, fromstatus, rows = this.filters_list.rows; // we need only to replace filter names... for (var i=0; i<rows.length; i++) { if (rows[i] == null) { // removed row continue; } else if (rows[i].uid == id-1) { from = rows[i].obj; fromstatus = $(from).hasClass('disabled'); this.filters_list.highlight_row(i); } else if (rows[i].uid == id) { name = rows[i].obj.cells[0].innerHTML; status = $(rows[i].obj).hasClass('disabled'); rows[i].obj.cells[0].innerHTML = from.cells[0].innerHTML; from.cells[0].innerHTML = name; $(from)[status?'addClass':'removeClass']('disabled'); $(rows[i].obj)[fromstatus?'addClass':'removeClass']('disabled'); break; } } // ... and disable/enable Up button this.filters_listbuttons(); break; case 'update': var rows = parent.cmail.filters_list.rows; for (var i=0; i<rows.length; i++) if (rows[i] && rows[i].uid == id) { rows[i].obj.cells[0].innerHTML = name; if (disabled) $(rows[i].obj).addClass('disabled'); else $(rows[i].obj).removeClass('disabled'); break; } break; case 'add': var row, new_row, td, list = parent.cmail.filters_list; if (!list) break; for (var i=0; i<list.rows.length; i++) if (list.rows[i] != null && String(list.rows[i].obj.id).match(/^rcmrow/)) row = list.rows[i].obj; if (row) { new_row = parent.document.createElement('tr'); new_row.id = 'rcmrow'+id; td = parent.document.createElement('td'); new_row.appendChild(td); list.insert_row(new_row, false); if (disabled) $(new_row).addClass('disabled'); if (row.cells[0].className) td.className = row.cells[0].className; td.innerHTML = name; list.highlight_row(id); parent.cmail.enable_command('plugin.managesieve-del', 'plugin.managesieve-up', true); } else // refresh whole page parent.cmail.goto_url('plugin.managesieve'); break; } this.set_busy(false); }; crystal_webmail.prototype.managesieve_select = function(list) { var id = list.get_single_selection(); if (id != null) this.load_managesieveframe(list.rows[id].uid); }; crystal_webmail.prototype.managesieve_save = function() { if (parent.cmail && parent.cmail.filters_list && this.gui_objects.sieveform.name != 'filtersetform') { var id = parent.cmail.filters_list.get_single_selection(); if (id != null) this.gui_objects.sieveform.elements['_fid'].value = parent.cmail.filters_list.rows[id].uid; } this.gui_objects.sieveform.submit(); }; // load filter frame crystal_webmail.prototype.load_managesieveframe = function(id) { if (typeof(id) != 'undefined' && id != null) { this.enable_command('plugin.managesieve-del', true); this.filters_listbuttons(); } else this.enable_command('plugin.managesieve-up', 'plugin.managesieve-down', 'plugin.managesieve-del', false); if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) { target = window.frames[this.env.contentframe]; this.set_busy(true, 'loading'); target.location.href = this.env.comm_path+'&_action=plugin.managesieve&_framed=1&_fid='+id; } }; // enable/disable Up/Down buttons crystal_webmail.prototype.filters_listbuttons = function() { var id = this.filters_list.get_single_selection(), rows = this.filters_list.rows; for (var i=0; i<rows.length; i++) { if (rows[i] == null) { // removed row } else if (i == id) { this.enable_command('plugin.managesieve-up', false); break; } else { this.enable_command('plugin.managesieve-up', true); break; } } for (var i=rows.length-1; i>0; i--) { if (rows[i] == null) { // removed row } else if (i == id) { this.enable_command('plugin.managesieve-down', false); break; } else { this.enable_command('plugin.managesieve-down', true); break; } } }; // operations on filters form crystal_webmail.prototype.managesieve_ruleadd = function(id) { this.http_post('plugin.managesieve', '_act=ruleadd&_rid='+id); }; crystal_webmail.prototype.managesieve_rulefill = function(content, id, after) { if (content != '') { // create new element var div = document.getElementById('rules'), row = document.createElement('div'); this.managesieve_insertrow(div, row, after); // fill row after inserting (for IE) row.setAttribute('id', 'rulerow'+id); row.className = 'rulerow'; row.innerHTML = content; this.managesieve_formbuttons(div); } }; crystal_webmail.prototype.managesieve_ruledel = function(id) { if (confirm(this.get_label('managesieve.ruledeleteconfirm'))) { var row = document.getElementById('rulerow'+id); row.parentNode.removeChild(row); this.managesieve_formbuttons(document.getElementById('rules')); } }; crystal_webmail.prototype.managesieve_actionadd = function(id) { this.http_post('plugin.managesieve', '_act=actionadd&_aid='+id); }; crystal_webmail.prototype.managesieve_actionfill = function(content, id, after) { if (content != '') { var div = document.getElementById('actions'), row = document.createElement('div'); this.managesieve_insertrow(div, row, after); // fill row after inserting (for IE) row.className = 'actionrow'; row.setAttribute('id', 'actionrow'+id); row.innerHTML = content; this.managesieve_formbuttons(div); } }; crystal_webmail.prototype.managesieve_actiondel = function(id) { if (confirm(this.get_label('managesieve.actiondeleteconfirm'))) { var row = document.getElementById('actionrow'+id); row.parentNode.removeChild(row); this.managesieve_formbuttons(document.getElementById('actions')); } }; // insert rule/action row in specified place on the list crystal_webmail.prototype.managesieve_insertrow = function(div, row, after) { for (var i=0; i<div.childNodes.length; i++) { if (div.childNodes[i].id == (div.id == 'rules' ? 'rulerow' : 'actionrow') + after) break; } if (div.childNodes[i+1]) div.insertBefore(row, div.childNodes[i+1]); else div.appendChild(row); }; // update Delete buttons status crystal_webmail.prototype.managesieve_formbuttons = function(div) { var i, button, buttons = []; // count and get buttons for (i=0; i<div.childNodes.length; i++) { if (div.id == 'rules' && div.childNodes[i].id) { if (/rulerow/.test(div.childNodes[i].id)) buttons.push('ruledel' + div.childNodes[i].id.replace(/rulerow/, '')); } else if (div.childNodes[i].id) { if (/actionrow/.test(div.childNodes[i].id)) buttons.push( 'actiondel' + div.childNodes[i].id.replace(/actionrow/, '')); } } for (i=0; i<buttons.length; i++) { button = document.getElementById(buttons[i]); if (i>0 || buttons.length>1) { $(button).removeClass('disabled'); button.removeAttribute('disabled'); } else { $(button).addClass('disabled'); button.setAttribute('disabled', true); } } }; // Set change crystal_webmail.prototype.managesieve_set = function() { var script = $(this.gui_objects.filtersetslist).val(); location.href = this.env.comm_path+'&_action=plugin.managesieve&_set='+script; }; // Script download crystal_webmail.prototype.managesieve_setget = function() { var script = $(this.gui_objects.filtersetslist).val(); location.href = this.env.comm_path+'&_action=plugin.managesieve&_act=setget&_set='+script; }; // Set activate crystal_webmail.prototype.managesieve_setact = function() { if (!this.gui_objects.filtersetslist) return false; var script = this.gui_objects.filtersetslist.value, action = (script == cmail.env.active_set ? 'deact' : 'setact'); this.http_post('plugin.managesieve', '_act='+action+'&_set='+script); }; // Set activate flag in sets list after set activation crystal_webmail.prototype.managesieve_reset = function() { if (!this.gui_objects.filtersetslist) return false; var list = this.gui_objects.filtersetslist, opts = list.getElementsByTagName('option'), label = ' (' + this.get_label('managesieve.active') + ')', regx = new RegExp(RegExp.escape(label)+'$'); for (var x=0; x<opts.length; x++) { if (opts[x].value != cmail.env.active_set && opts[x].innerHTML.match(regx)) opts[x].innerHTML = opts[x].innerHTML.replace(regx, ''); else if (opts[x].value == cmail.env.active_set) opts[x].innerHTML = opts[x].innerHTML + label; } // change title of setact button $('#'+cmail.buttons['plugin.managesieve-setact'][0].id).attr('title', cmail.gettext('managesieve.filterset' + (list.value == cmail.env.active_set ? 'deact' : 'act'))); }; // Set delete crystal_webmail.prototype.managesieve_setdel = function() { if (!this.gui_objects.filtersetslist) return false; if (!confirm(this.get_label('managesieve.setdeleteconfirm'))) return false; var script = this.gui_objects.filtersetslist.value; this.http_post('plugin.managesieve', '_act=setdel&_set='+script); }; // Set add crystal_webmail.prototype.managesieve_setadd = function() { this.filters_list.clear_selection(); this.enable_command('plugin.managesieve-up', 'plugin.managesieve-down', 'plugin.managesieve-del', false); if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) { target = window.frames[this.env.contentframe]; this.set_busy(true, 'loading'); target.location.href = this.env.comm_path+'&_action=plugin.managesieve&_framed=1&_newset=1'; } }; crystal_webmail.prototype.managesieve_reload = function(set) { this.env.reload_set = set; window.setTimeout(function() { location.href = cmail.env.comm_path + '&_action=plugin.managesieve' + (cmail.env.reload_set ? '&_set=' + cmail.env.reload_set : '') }, 500); };
gpl-3.0
PhotonQyv/mastalab
app/src/main/java/fr/gouv/etalab/mastodon/client/Entities/Emojis.java
1364
/* Copyright 2017 Thomas Schneider * * This file is a part of Mastalab * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License along with Mastalab; if not, * see <http://www.gnu.org/licenses>. */ package fr.gouv.etalab.mastodon.client.Entities; /** * Created by Thomas on 20/10/2017. */ public class Emojis { private String shortcode; private String static_url; private String url; public String getShortcode() { return shortcode; } public void setShortcode(String shortcode) { this.shortcode = shortcode; } public String getStatic_url() { return static_url; } public void setStatic_url(String static_url) { this.static_url = static_url; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
gpl-3.0
Firestorm980/jmcdsn
parts/modules/acf-module-call_to_action.php
973
<!-- parts/modules/acf-module-call_to_action.php --> <?php /** * JMCDSN - ACF Module : CTA * * @package jmcdsn */ $module_id = uniqid( 'module_' ); $module_base = get_sub_field( 'module_base' ); $module_ctas = get_sub_field( 'module_ctas' ); ?> <section id="<?php echo esc_attr( $module_id ); ?>" class="section section--acf-module section--acf-module-cta" aria-labelledby="<?php echo esc_attr( $module_id . '-heading' ); ?>"> <?php jmcdsn_acf_module_base( $module_base, $module_id ); ?> <div class="section__module"> <?php foreach ( $module_ctas as $cta ) : ?> <?php $is_internal = ( 'internal' === $cta['cta_type']['value'] ); $cta_link = ( $is_internal ) ? $cta['cta_internal_link'] : $cta['cta_external_link']; ?> <div class="cta"> <a class="button button--cta" href="<?php echo esc_url( $cta_link ); ?>"><?php echo esc_html( $cta['cta_text'] ); ?></a> </div> <?php endforeach; ?> </div> </section>
gpl-3.0
searchfirst/Lenore
app/webroot/js/lib/ckeditor/skins/ob/skin.js
1138
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.skins.add('ob',(function(){var a=[];if(CKEDITOR.env.ie&&CKEDITOR.env.version<7)a.push('icons.png','images/sprites_ie6.png','images/dialog_sides.gif');return{preload:a,editor:{css:['editor.css']},dialog:{css:['dialog.css']},templates:{css:['templates.css']},margins:[0,14,18,14]};})());(function(){CKEDITOR.dialog?a():CKEDITOR.on('dialogPluginReady',a);function a(){CKEDITOR.dialog.on('resize',function(b){var c=b.data,d=c.width,e=c.height,f=c.dialog,g=f.parts.contents;if(c.skin!='ob')return;g.setStyles({width:d+'px',height:e+'px'});if(!CKEDITOR.env.ie)return;var h=function(){var i=f.parts.dialog.getChild([0,0,0]),j=i.getChild(0),k=i.getChild(2);k.setStyle('width',j.$.offsetWidth+'px');k=i.getChild(7);k.setStyle('width',j.$.offsetWidth-28+'px');k=i.getChild(4);k.setStyle('height',e+j.getChild(0).$.offsetHeight+'px');k=i.getChild(5);k.setStyle('height',e+j.getChild(0).$.offsetHeight+'px');};setTimeout(h,100);if(b.editor.lang.dir=='rtl')setTimeout(h,1000);});};})();
gpl-3.0
undisputed-seraphim/KanColleAPI
KanColleAPI/Request/Nyukyo.cs
522
using System.Text; namespace KanColle.Request.Nyukyo { public class Nyukyo { public static string START = "api_req_nyukyo/start/"; public static string Start (int ship_id, int ndock_id, int highspeed = 0) { StringBuilder str = new StringBuilder(); str.AppendFormat("api_verno={0}&", 1); str.AppendFormat("api_ndock_id&", ndock_id); str.Append("api_token={0}&"); str.AppendFormat("api_highspeed={0}&", highspeed); str.AppendFormat("api_ship_id={0}", ship_id); return str.ToString(); } } }
gpl-3.0
versionstudio/vibestreamer
src/sqlite3x/sqlite3x_exception.cpp
1233
/* Copyright (C) 2004-2005 Cory Nelson This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. CVS Info : $Author: phrostbyte $ $Date: 2005/06/16 20:46:40 $ $Revision: 1.1 $ */ #include <sqlite3.h> #include "sqlite3x.hpp" namespace sqlite3x { database_error::database_error(const char *msg) : runtime_error(msg) {} database_error::database_error(sqlite3_connection &con) : runtime_error(sqlite3_errmsg(con.db)) {} }
gpl-3.0
drytoastman/wwscc
swingapps/src/org/wwscc/registration/DriverRenderer.java
1242
package org.wwscc.registration; import java.awt.Color; import java.awt.Component; import java.awt.Font; import javax.swing.DefaultListCellRenderer; import javax.swing.JList; import org.wwscc.storage.Driver; public class DriverRenderer extends DefaultListCellRenderer { Font font = getFont().deriveFont(14f); Font offFont = font.deriveFont(Font.ITALIC); Color offSelect = new Color(200, 200, 200); public Component getListCellRendererComponent(JList<?> list, Object o, int i, boolean selected, boolean c) { super.getListCellRendererComponent(list, o, i, selected, c); if (o instanceof Driver) { setFont(font); setText(((Driver)o).getFullName()); if (selected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setForeground(list.getForeground()); setBackground(list.getBackground()); } } else { setFont(offFont); setText(o.toString()); if (selected) { setForeground(list.getSelectionForeground()); setBackground(offSelect); } else { setForeground(Color.GRAY); setBackground(list.getBackground()); } } return this; } }
gpl-3.0
opencart/opencart
upload/admin/controller/marketplace/marketplace.php
38525
<?php namespace Opencart\Admin\Controller\Marketplace; class Marketplace extends \Opencart\System\Engine\Controller { public function index(): void { $this->load->language('marketplace/marketplace'); $this->document->setTitle($this->language->get('heading_title')); if (isset($this->request->get['filter_search'])) { $filter_search = $this->request->get['filter_search']; } else { $filter_search = ''; } if (isset($this->request->get['filter_category'])) { $filter_category = $this->request->get['filter_category']; } else { $filter_category = ''; } if (isset($this->request->get['filter_license'])) { $filter_license = $this->request->get['filter_license']; } else { $filter_license = ''; } if (isset($this->request->get['filter_rating'])) { $filter_rating = $this->request->get['filter_rating']; } else { $filter_rating = ''; } if (isset($this->request->get['filter_member_type'])) { $filter_member_type = $this->request->get['filter_member_type']; } else { $filter_member_type = ''; } if (isset($this->request->get['filter_member'])) { $filter_member = $this->request->get['filter_member']; } else { $filter_member = ''; } if (isset($this->request->get['sort'])) { $sort = $this->request->get['sort']; } else { $sort = 'date_modified'; } if (isset($this->request->get['page'])) { $page = (int)$this->request->get['page']; } else { $page = 1; } $url = ''; if (isset($this->request->get['filter_search'])) { $url .= '&filter_search=' . $this->request->get['filter_search']; } if (isset($this->request->get['filter_category'])) { $url .= '&filter_category=' . $this->request->get['filter_category']; } if (isset($this->request->get['filter_license'])) { $url .= '&filter_license=' . $this->request->get['filter_license']; } if (isset($this->request->get['filter_rating'])) { $url .= '&filter_rating=' . $this->request->get['filter_rating']; } if (isset($this->request->get['filter_member_type'])) { $url .= '&filter_member_type=' . $this->request->get['filter_member_type']; } if (isset($this->request->get['filter_member'])) { $url .= '&filter_member=' . $this->request->get['filter_member']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $data['breadcrumbs'] = []; $data['breadcrumbs'][] = [ 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token']) ]; $data['breadcrumbs'][] = [ 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url) ]; $time = time(); // We create a hash from the data in a similar method to how amazon does things. $string = 'api/marketplace/list' . "\n"; $string .= $this->config->get('opencart_username') . "\n"; $string .= $this->request->server['HTTP_HOST'] . "\n"; $string .= VERSION . "\n"; $string .= $time . "\n"; $signature = base64_encode(hash_hmac('sha1', $string, $this->config->get('opencart_secret'), 1)); $url = '&username=' . urlencode($this->config->get('opencart_username')); $url .= '&domain=' . $this->request->server['HTTP_HOST']; $url .= '&version=' . urlencode(VERSION); $url .= '&time=' . $time; $url .= '&signature=' . rawurlencode($signature); if (isset($this->request->get['filter_search'])) { $url .= '&filter_search=' . urlencode($this->request->get['filter_search']); } if (isset($this->request->get['filter_category'])) { $url .= '&filter_category=' . $this->request->get['filter_category']; } if (isset($this->request->get['filter_license'])) { $url .= '&filter_license=' . $this->request->get['filter_license']; } if (isset($this->request->get['filter_rating'])) { $url .= '&filter_rating=' . $this->request->get['filter_rating']; } if (isset($this->request->get['filter_member_type'])) { $url .= '&filter_member_type=' . $this->request->get['filter_member_type']; } if (isset($this->request->get['filter_member'])) { $url .= '&filter_member=' . urlencode($this->request->get['filter_member']); } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $curl = curl_init(OPENCART_SERVER . 'index.php?route=api/marketplace' . $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_FORBID_REUSE, 1); curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1); curl_setopt($curl, CURLOPT_POST, 1); $response = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); $response_info = json_decode($response, true); $extension_total = (int)$response_info['extension_total']; $url = ''; if (isset($this->request->get['filter_search'])) { $url .= '&filter_search=' . $this->request->get['filter_search']; } if (isset($this->request->get['filter_category'])) { $url .= '&filter_category=' . $this->request->get['filter_category']; } if (isset($this->request->get['filter_license'])) { $url .= '&filter_license=' . $this->request->get['filter_license']; } if (isset($this->request->get['filter_rating'])) { $url .= '&filter_rating=' . $this->request->get['filter_rating']; } if (isset($this->request->get['filter_member_type'])) { $url .= '&filter_member_type=' . $this->request->get['filter_member_type']; } if (isset($this->request->get['filter_member'])) { $url .= '&filter_member=' . $this->request->get['filter_member']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $data['promotions'] = []; if ($response_info['promotions'] && $page == 1) { foreach ($response_info['promotions'] as $result) { $data['promotions'][] = [ 'name' => utf8_decode($result['name']), 'description' => utf8_decode($result['description']), 'image' => $result['image'], 'license' => $result['license'], 'price' => $result['price'], 'rating' => $result['rating'], 'rating_total' => $result['rating_total'], 'href' => $this->url->link('marketplace/marketplace|info', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $result['extension_id'] . $url) ]; } } $data['extensions'] = []; if ($response_info['extensions']) { foreach ($response_info['extensions'] as $result) { $data['extensions'][] = [ 'name' => utf8_decode($result['name']), 'description' => utf8_decode($result['description']), 'image' => $result['image'], 'license' => $result['license'], 'price' => $result['price'], 'rating' => $result['rating'], 'rating_total' => $result['rating_total'], 'href' => $this->url->link('marketplace/marketplace|info', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $result['extension_id'] . $url) ]; } } if (isset($response_info['error'])) { $data['error_signature'] = $response_info['error']; } else { $data['error_signature'] = ''; } // Categories $url = ''; if (isset($this->request->get['filter_search'])) { $url .= '&filter_search=' . $this->request->get['filter_search']; } if (isset($this->request->get['filter_license'])) { $url .= '&filter_license=' . $this->request->get['filter_license']; } if (isset($this->request->get['filter_rating'])) { $url .= '&filter_rating=' . $this->request->get['filter_rating']; } if (isset($this->request->get['filter_member_type'])) { $url .= '&filter_member_type=' . $this->request->get['filter_member_type']; } if (isset($this->request->get['filter_member'])) { $url .= '&filter_member=' . $this->request->get['filter_member']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } $data['categories'] = []; $data['categories'][] = [ 'text' => $this->language->get('text_all'), 'value' => '', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_theme'), 'value' => 'theme', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=theme' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_marketplace'), 'value' => 'marketplace', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=marketplace' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_language'), 'value' => 'language', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=language' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_payment'), 'value' => 'payment', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=payment' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_shipping'), 'value' => 'shipping', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=shipping' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_module'), 'value' => 'module', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=module' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_total'), 'value' => 'total', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=total' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_feed'), 'value' => 'feed', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=feed' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_report'), 'value' => 'report', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=report' . $url) ]; $data['categories'][] = [ 'text' => $this->language->get('text_other'), 'value' => 'other', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_category=other' . $url) ]; // Licenses $url = ''; if (isset($this->request->get['filter_search'])) { $url .= '&filter_search=' . $this->request->get['filter_search']; } if (isset($this->request->get['filter_category'])) { $url .= '&filter_category=' . $this->request->get['filter_category']; } if (isset($this->request->get['filter_rating'])) { $url .= '&filter_rating=' . $this->request->get['filter_rating']; } if (isset($this->request->get['filter_member_type'])) { $url .= '&filter_member_type=' . $this->request->get['filter_member_type']; } if (isset($this->request->get['filter_member'])) { $url .= '&filter_member=' . $this->request->get['filter_member']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $data['licenses'] = []; $data['licenses'][] = [ 'text' => $this->language->get('text_all'), 'value' => '', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url) ]; $data['licenses'][] = [ 'text' => $this->language->get('text_recommended'), 'value' => 'recommended', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_license=recommended' . $url) ]; $data['licenses'][] = [ 'text' => $this->language->get('text_free'), 'value' => 'free', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_license=free' . $url) ]; $data['licenses'][] = [ 'text' => $this->language->get('text_paid'), 'value' => 'paid', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_license=paid' . $url) ]; $data['licenses'][] = [ 'text' => $this->language->get('text_purchased'), 'value' => 'purchased', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_license=purchased' . $url) ]; // Sort $url = ''; if (isset($this->request->get['filter_search'])) { $url .= '&filter_search=' . $this->request->get['filter_search']; } if (isset($this->request->get['filter_category'])) { $url .= '&filter_category=' . $this->request->get['filter_category']; } if (isset($this->request->get['filter_license'])) { $url .= '&filter_license=' . $this->request->get['filter_license']; } if (isset($this->request->get['filter_rating'])) { $url .= '&filter_rating=' . $this->request->get['filter_rating']; } if (isset($this->request->get['filter_member_type'])) { $url .= '&filter_member_type=' . $this->request->get['filter_member_type']; } if (isset($this->request->get['filter_member'])) { $url .= '&filter_member=' . $this->request->get['filter_member']; } $data['sorts'] = []; $data['sorts'][] = [ 'text' => $this->language->get('text_date_modified'), 'value' => 'date_modified', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url . '&sort=date_modified') ]; $data['sorts'][] = [ 'text' => $this->language->get('text_date_added'), 'value' => 'date_added', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url . '&sort=date_added') ]; $data['sorts'][] = [ 'text' => $this->language->get('text_rating'), 'value' => 'rating', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url . '&sort=rating') ]; $data['sorts'][] = [ 'text' => $this->language->get('text_name'), 'value' => 'name', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url . '&sort=name') ]; $data['sorts'][] = [ 'text' => $this->language->get('text_price'), 'value' => 'price', 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url . '&sort=price') ]; // Pagination $url = ''; if (isset($this->request->get['filter_search'])) { $url .= '&filter_search=' . $this->request->get['filter_search']; } if (isset($this->request->get['filter_category'])) { $url .= '&filter_category=' . $this->request->get['filter_category']; } if (isset($this->request->get['filter_license'])) { $url .= '&filter_license=' . $this->request->get['filter_license']; } if (isset($this->request->get['filter_rating'])) { $url .= '&filter_rating=' . $this->request->get['filter_rating']; } if (isset($this->request->get['filter_member_type'])) { $url .= '&filter_member_type=' . $this->request->get['filter_member_type']; } if (isset($this->request->get['filter_member'])) { $url .= '&filter_member=' . $this->request->get['filter_member']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } $data['pagination'] = $this->load->controller('common/pagination', [ 'total' => $extension_total, 'page' => $page, 'limit' => 12, 'url' => $this->url->link('marketplace/marketplace|list', 'user_token=' . $this->session->data['user_token'] . $url . '&page={page}') ]); $data['filter_search'] = $filter_search; $data['filter_category'] = $filter_category; $data['filter_license'] = $filter_license; $data['filter_member_type'] = $filter_member_type; $data['filter_rating'] = $filter_rating; $data['sort'] = $sort; $data['user_token'] = $this->session->data['user_token']; $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('marketplace/marketplace_list', $data)); } public function info(): object|null { if (isset($this->request->get['extension_id'])) { $extension_id = (int)$this->request->get['extension_id']; } else { $extension_id = 0; } $time = time(); // We create a hash from the data in a similar method to how amazon does things. $string = 'api/marketplace/info' . "\n"; $string .= $this->config->get('opencart_username') . "\n"; $string .= $this->request->server['HTTP_HOST'] . "\n"; $string .= VERSION . "\n"; $string .= $extension_id . "\n"; $string .= $time . "\n"; $signature = base64_encode(hash_hmac('sha1', $string, $this->config->get('opencart_secret'), 1)); $url = '&username=' . urlencode($this->config->get('opencart_username')); $url .= '&domain=' . $this->request->server['HTTP_HOST']; $url .= '&version=' . urlencode(VERSION); $url .= '&extension_id=' . $extension_id; $url .= '&time=' . $time; $url .= '&signature=' . rawurlencode($signature); $curl = curl_init(OPENCART_SERVER . 'index.php?route=api/marketplace/info' . $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_FORBID_REUSE, 1); curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1); curl_setopt($curl, CURLOPT_POST, 1); $response = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); $response_info = json_decode($response, true); if ($response_info) { $this->load->language('marketplace/marketplace'); $this->document->setTitle($this->language->get('heading_title')); if (isset($response_info['error'])) { $data['error_signature'] = $response_info['error']; } else { $data['error_signature'] = ''; } $url = ''; if (isset($this->request->get['filter_search'])) { $url .= '&filter_search=' . $this->request->get['filter_search']; } if (isset($this->request->get['filter_category'])) { $url .= '&filter_category=' . $this->request->get['filter_category']; } if (isset($this->request->get['filter_license'])) { $url .= '&filter_license=' . $this->request->get['filter_license']; } if (isset($this->request->get['filter_username'])) { $url .= '&filter_username=' . $this->request->get['filter_username']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $data['back'] = $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url); $data['breadcrumbs'] = []; $data['breadcrumbs'][] = [ 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token']) ]; $data['breadcrumbs'][] = [ 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . $url) ]; $this->load->helper('bbcode'); $data['banner'] = $response_info['banner']; $data['extension_id'] = (int)$this->request->get['extension_id']; $data['name'] = $response_info['name']; $data['description'] = $response_info['description']; $data['documentation'] = $response_info['documentation']; $data['price'] = $response_info['price']; $data['license'] = $response_info['license']; $data['license_period'] = $response_info['license_period']; $data['purchased'] = $response_info['purchased']; $data['rating'] = $response_info['rating']; $data['rating_total'] = $response_info['rating_total']; $data['downloaded'] = $response_info['downloaded']; $data['sales'] = $response_info['sales']; $data['date_added'] = date($this->language->get('date_format_short'), strtotime($response_info['date_added'])); $data['date_modified'] = date($this->language->get('date_format_short'), strtotime($response_info['date_modified'])); $data['member_username'] = $response_info['member_username']; $data['member_image'] = $response_info['member_image']; $data['member_date_added'] = $response_info['member_date_added']; $data['filter_member'] = $this->url->link('marketplace/marketplace', 'user_token=' . $this->session->data['user_token'] . '&filter_member=' . $response_info['member_username']); $data['comment_total'] = $response_info['comment_total']; $data['images'] = []; foreach ($response_info['images'] as $result) { $data['images'][] = [ 'thumb' => $result['thumb'], 'popup' => $result['popup'] ]; } $this->load->model('setting/extension'); $data['downloads'] = []; if ($response_info['downloads']) { $this->session->data['extension_download'][$extension_id] = $response_info['downloads']; } else { $this->session->data['extension_download'][$extension_id] = []; $this->session->data['extension_download'][$extension_id] = []; } $this->document->addStyle('view/javascript/jquery/magnific/magnific-popup.css'); $this->document->addScript('view/javascript/jquery/magnific/jquery.magnific-popup.min.js'); $data['user_token'] = $this->session->data['user_token']; $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('marketplace/marketplace_info', $data)); return null; } else { return new \Opencart\System\Engine\Action('error/not_found'); } } public function extension(): void { $this->load->language('marketplace/marketplace'); if (isset($this->request->get['extension_id'])) { $extension_id = (int)$this->request->get['extension_id']; } else { $extension_id = 0; } $this->load->model('setting/extension'); $data['downloads'] = []; if (isset($this->session->data['extension_download'][$extension_id])) { $results = $this->session->data['extension_download'][$extension_id]; foreach ($results as $result) { if (substr($result['filename'], -10) == '.ocmod.zip') { $extension_install_info = $this->model_setting_extension->getInstallByExtensionDownloadId($result['extension_download_id']); // Download if (!$extension_install_info) { $download = $this->url->link('marketplace/marketplace|download', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $extension_id . '&extension_download_id=' . $result['extension_download_id']); } else { $download = ''; } // Install if ($extension_install_info && !$extension_install_info['status']) { $install = $this->url->link('marketplace/installer|install', 'user_token=' . $this->session->data['user_token'] . '&extension_install_id=' . $extension_install_info['extension_install_id']); } else { $install = ''; } // Uninstall if ($extension_install_info && $extension_install_info['status']) { $uninstall = $this->url->link('marketplace/installer|uninstall', 'user_token=' . $this->session->data['user_token'] . '&extension_install_id=' . $extension_install_info['extension_install_id']); } else { $uninstall = ''; } // Delete if ($extension_install_info && !$extension_install_info['status']) { $delete = $this->url->link('marketplace/installer|delete', 'user_token=' . $this->session->data['user_token'] . '&extension_install_id=' . $extension_install_info['extension_install_id']); } else { $delete = ''; } $data['downloads'][] = [ 'name' => $result['name'], 'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])), 'download' => $download, 'install' => $install, 'uninstall' => $uninstall, 'delete' => $delete ]; } } } $this->response->setOutput($this->load->view('marketplace/marketplace_extension', $data)); } public function purchase(): void { $this->load->language('marketplace/marketplace'); $json = []; if (isset($this->request->get['extension_id'])) { $extension_id = (int)$this->request->get['extension_id']; } else { $extension_id = 0; } if (!$this->user->hasPermission('modify', 'marketplace/marketplace')) { $json['error'] = $this->language->get('error_permission'); } if (!$this->config->get('opencart_username') || !$this->config->get('opencart_secret')) { $json['error'] = $this->language->get('error_opencart'); } if (!$this->request->post['pin']) { $json['error'] = $this->language->get('error_pin'); } if (!$json) { $time = time(); // We create a hash from the data in a similar method to how amazon does things. $string = 'api/marketplace/purchase' . "\n"; $string .= $this->config->get('opencart_username') . "\n"; $string .= $this->request->server['HTTP_HOST'] . "\n"; $string .= VERSION . "\n"; $string .= $extension_id . "\n"; $string .= $this->request->post['pin'] . "\n"; $string .= $time . "\n"; $signature = base64_encode(hash_hmac('sha1', $string, $this->config->get('opencart_secret'), 1)); $url = '&username=' . urlencode($this->config->get('opencart_username')); $url .= '&domain=' . $this->request->server['HTTP_HOST']; $url .= '&version=' . urlencode(VERSION); $url .= '&extension_id=' . $extension_id; $url .= '&time=' . $time; $url .= '&signature=' . rawurlencode($signature); $curl = curl_init(OPENCART_SERVER . 'index.php?route=api/marketplace/purchase' . $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FORBID_REUSE, 1); curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); $response = curl_exec($curl); curl_close($curl); $response_info = json_decode($response, true); if (isset($response_info['success'])) { // If purchase complete we update the status for all downloads to be available. if (isset($this->session->data['extension_download'][$extension_id])) { $results = $this->session->data['extension_download'][$extension_id]; foreach (array_keys($results) as $key) { $this->session->data['extension_download'][$extension_id][$key]['status'] = 1; } } $json['success'] = $response_info['success']; } elseif (isset($response_info['error'])) { $json['error'] = $response_info['error']; } else { $json['error'] = $this->language->get('error_purchase'); } } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } public function download(): void { $this->load->language('marketplace/marketplace'); $json = []; if (isset($this->request->get['extension_id'])) { $extension_id = (int)$this->request->get['extension_id']; } else { $extension_id = 0; } if (isset($this->request->get['extension_download_id'])) { $extension_download_id = (int)$this->request->get['extension_download_id']; } else { $extension_download_id = 0; } if (!$this->user->hasPermission('modify', 'marketplace/marketplace')) { $json['error'] = $this->language->get('error_permission'); } if (!$json) { $time = time(); // We create a hash from the data in a similar method to how amazon does things. $string = 'api/marketplace/download' . "\n"; $string .= $this->config->get('opencart_username') . "\n"; $string .= $this->request->server['HTTP_HOST'] . "\n"; $string .= VERSION . "\n"; $string .= $extension_id . "\n"; $string .= $extension_download_id . "\n"; $string .= $time . "\n"; $signature = base64_encode(hash_hmac('sha1', $string, $this->config->get('opencart_secret'), 1)); $url = '&username=' . urlencode($this->config->get('opencart_username')); $url .= '&domain=' . $this->request->server['HTTP_HOST']; $url .= '&version=' . urlencode(VERSION); $url .= '&extension_id=' . $extension_id; $url .= '&extension_download_id=' . $extension_download_id; $url .= '&time=' . $time; $url .= '&signature=' . rawurlencode($signature); $curl = curl_init(OPENCART_SERVER . 'index.php?route=api/marketplace/download&extension_download_id=' . $extension_download_id . $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FORBID_REUSE, 1); curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); $response = curl_exec($curl); $response_info = json_decode($response, true); curl_close($curl); if (isset($response_info['download'])) { if (substr($response_info['filename'], -10) == '.ocmod.zip') { $handle = fopen(DIR_STORAGE . 'marketplace/' . $response_info['filename'], 'w'); $download = file_get_contents($response_info['download']); fwrite($handle, $download); fclose($handle); $this->load->model('setting/extension'); $extension_data = [ 'extension_id' => $extension_id, 'extension_download_id' => $extension_download_id, 'name' => $response_info['name'], 'code' => basename($response_info['filename'], '.ocmod.zip'), 'author' => $response_info['author'], 'version' => $response_info['version'], 'link' => '' ]; $json['extension_install_id'] = $this->model_setting_extension->addInstall($extension_data); $json['success'] = $this->language->get('text_success'); } else { $json['redirect'] = $response_info['download']; } } elseif (isset($response_info['error'])) { $json['error'] = $response_info['error']; } else { $json['error'] = $this->language->get('error_download'); } } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } public function addComment(): void { $this->load->language('marketplace/marketplace'); $json = []; if (isset($this->request->get['extension_id'])) { $extension_id = (int)$this->request->get['extension_id']; } else { $extension_id = 0; } if (isset($this->request->get['parent_id'])) { $parent_id = (int)$this->request->get['parent_id']; } else { $parent_id = 0; } if (!$this->user->hasPermission('modify', 'marketplace/marketplace')) { $json['error'] = $this->language->get('error_permission'); } if (!$this->config->get('opencart_username') || !$this->config->get('opencart_secret')) { $json['error'] = $this->language->get('error_opencart'); } if (!$json) { $time = time(); // We create a hash from the data in a similar method to how amazon does things. $string = 'api/marketplace/addcomment' . "\n"; $string .= urlencode($this->config->get('opencart_username')) . "\n"; $string .= $this->request->server['HTTP_HOST'] . "\n"; $string .= urlencode(VERSION) . "\n"; $string .= $extension_id . "\n"; $string .= $parent_id . "\n"; $string .= urlencode(base64_encode($this->request->post['comment'])) . "\n"; $string .= $time . "\n"; $signature = base64_encode(hash_hmac('sha1', $string, $this->config->get('opencart_secret'), 1)); $url = '&username=' . $this->config->get('opencart_username'); $url .= '&domain=' . $this->request->server['HTTP_HOST']; $url .= '&version=' . VERSION; $url .= '&extension_id=' . $extension_id; $url .= '&parent_id=' . $parent_id; $url .= '&time=' . $time; $url .= '&signature=' . rawurlencode($signature); $curl = curl_init(OPENCART_SERVER . 'index.php?route=api/marketplace/addcomment&extension_id=' . $extension_id . $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FORBID_REUSE, 1); curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, ['comment' => $this->request->post['comment']]); $response = curl_exec($curl); curl_close($curl); $response_info = json_decode($response, true); if (isset($response_info['success'])) { $json['success'] = $response_info['success']; } elseif (isset($response_info['error'])) { $json['error'] = $response_info['error']; } else { $json['error'] = $this->language->get('error_comment'); } } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } public function comment(): void { $this->load->language('marketplace/marketplace'); if (isset($this->request->get['extension_id'])) { $extension_id = (int)$this->request->get['extension_id']; } else { $extension_id = 0; } if (isset($this->request->get['page'])) { $page = (int)$this->request->get['page']; } else { $page = 1; } $data['button_more'] = $this->language->get('button_more'); $data['button_reply'] = $this->language->get('button_reply'); $curl = curl_init(OPENCART_SERVER . 'index.php?route=api/marketplace/comment&extension_id=' . $extension_id . '&page=' . $page); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FORBID_REUSE, 1); curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); $response = curl_exec($curl); curl_close($curl); $json = json_decode($response, true); $data['comments'] = []; $comment_total = $json['comment_total']; if ($json['comments']) { $results = $json['comments']; foreach ($results as $result) { if ($result['reply_total'] > 5) { $next = $this->url->link('marketplace/marketplace|reply', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $extension_id . '&parent_id=' . $result['extension_comment_id'] . '&page=2'); } else { $next = ''; } $data['comments'][] = [ 'extension_comment_id' => $result['extension_comment_id'], 'member' => $result['member'], 'image' => $result['image'], 'comment' => $result['comment'], 'date_added' => $result['date_added'], 'reply' => $result['reply'], 'add' => $this->url->link('marketplace/marketplace|addcomment', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $extension_id . '&parent_id=' . $result['extension_comment_id']), 'refresh' => $this->url->link('marketplace/marketplace|reply', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $extension_id . '&parent_id=' . $result['extension_comment_id'] . '&page=1'), 'next' => $next ]; } } $data['pagination'] = $this->load->controller('common/pagination', [ 'total' => $comment_total, 'page' => $page, 'limit' => 20, 'url' => $this->url->link('marketplace/marketplace|comment', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $extension_id . '&page={page}') ]); $data['refresh'] = $this->url->link('marketplace/marketplace|comment', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $extension_id . '&page=' . $page); $this->response->setOutput($this->load->view('marketplace/marketplace_comment', $data)); } public function reply(): void { $this->load->language('marketplace/marketplace'); if (isset($this->request->get['extension_id'])) { $extension_id = (int)$this->request->get['extension_id']; } else { $extension_id = 0; } if (isset($this->request->get['parent_id'])) { $parent_id = (int)$this->request->get['parent_id']; } else { $parent_id = 0; } if (isset($this->request->get['page'])) { $page = (int)$this->request->get['page']; } else { $page = 1; } $curl = curl_init(OPENCART_SERVER . 'index.php?route=api/marketplace/comment&extension_id=' . $extension_id . '&parent_id=' . $parent_id . '&page=' . $page); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FORBID_REUSE, 1); curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); $response = curl_exec($curl); $json = json_decode($response, true); $data['replies'] = []; $reply_total = $json['reply_total']; if ($json['replies']) { $results = $json['replies']; foreach ($results as $result) { $data['replies'][] = [ 'extension_comment_id' => $result['extension_comment_id'], 'member' => $result['member'], 'image' => $result['image'], 'comment' => $result['comment'], 'date_added' => $result['date_added'] ]; } } $data['refresh'] = $this->url->link('marketplace/marketplace|reply', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $extension_id . '&parent_id=' . $parent_id . '&page=' . $page); if (($page * 5) < $reply_total) { $data['next'] = $this->url->link('marketplace/marketplace|reply', 'user_token=' . $this->session->data['user_token'] . '&extension_id=' . $extension_id . '&parent_id=' . $parent_id . '&page=' . ($page + 1)); } else { $data['next'] = ''; } $this->response->setOutput($this->load->view('marketplace/marketplace_reply', $data)); } }
gpl-3.0
greaternemo/a-roguelike
ARL/Fov.js
26609
// ARL.Fov // Field of view calculation ARL.Fov = function() {}; /* ARL.Fov.prototype. */ ARL.Fov.prototype.buildRings = function(params) { let aLoc = params.aLoc; let aRange = params.aRange; let mapSize = GCON('PHYS_BASE').mapSize; let locX = parseInt(aLoc.split(',')[0]); let locY = parseInt(aLoc.split(',')[1]); let curX = null; let curY = null; let dX = null; let dY = null; let fullRange = [ [aLoc] ]; let fullSet = []; let curRange = null; let curSet = null; let curLoc = null; let firstLoc = null; for (curRange = 1; curRange <= aRange; curRange += 1) { curSet = []; // we start with the northernmost loc and proceed clockwise dX = 0; dY = 0 - curRange; curX = locX + dX; curY = locY + dY; // we save this here to check it later // this way we can test an actual loc instead of a vague false value firstLoc = SIG('enpair', [curX, curY]); if ((curX > -1 && curX < mapSize.mWidth) && (curY > -1 && curY < mapSize.mHeight)) { curLoc = SIG('enpair', [curX, curY]); } else { curLoc = false; } curSet.push(curLoc); fullSet.push(curLoc); // N, go SE until E while (dX < curRange) { dX += 1; dY += 1; curX = locX + dX; curY = locY + dY; // console.log('dX < curRange: ' + dX + '/' + curRange); if ((curX > -1 && curX < mapSize.mWidth) && (curY > -1 && curY < mapSize.mHeight)) { curLoc = SIG('enpair', [curX, curY]); } else { curLoc = false; } curSet.push(curLoc); fullSet.push(curLoc); } // E, go SW until S while (dY < curRange) { dX -= 1; dY += 1; curX = locX + dX; curY = locY + dY; // console.log('dY < curRange: ' + dY + '/' + curRange); if ((curX > -1 && curX < mapSize.mWidth) && (curY > -1 && curY < mapSize.mHeight)) { curLoc = SIG('enpair', [curX, curY]); } else { curLoc = false; } curSet.push(curLoc); fullSet.push(curLoc); } // S, go NW until W while (dX > -curRange) { dX -= 1; dY -= 1; curX = locX + dX; curY = locY + dY; // console.log('dX > -curRange: ' + dX + '/' + -curRange); if ((curX > -1 && curX < mapSize.mWidth) && (curY > -1 && curY < mapSize.mHeight)) { curLoc = SIG('enpair', [curX, curY]); } else { curLoc = false; } curSet.push(curLoc); fullSet.push(curLoc); } // W, go NE until N while (dY > -curRange) { dX += 1; dY -= 1; curX = locX + dX; curY = locY + dY; // console.log('dY > -curRange: ' + dY + '/' + -curRange); // the last loc we generate should be our origin loc // we bail out when we get back to it if (SIG('enpair', [curX, curY]) === firstLoc) { continue; } if ((curX > -1 && curX < mapSize.mWidth) && (curY > -1 && curY < mapSize.mHeight)) { curLoc = SIG('enpair', [curX, curY]); } else { curLoc = false; } curSet.push(curLoc); fullSet.push(curLoc); } fullRange.push(curSet.slice()); } // console.log(fullSet); return fullRange; }; ARL.Fov.prototype.buildDiagonals = function(params) { let aLoc = params.aLoc; let aRange = params.aRange; // note: you shouldn't run this with params.aRange <= 0 // Currently, you can't see the wall in a corner. This should fix that. // We are going to cast a ray along each diagonal from the current location. // This function will just precompute the values so we can avoid cramming more // code into the big updateVisibility function. (As much as we can, anyway.) // Update: I added diagonals to each loc in SIDE_REFS just to support this. // You're welcome. // We're calculating the diagonal range here because in a 4-way movement system, // each diagonal space is 2 spaces away. Divide by 2, round down. // So for a visual range of 5, we take half (2.5), round down (2). // This lets us populate our locs with locs at range [0, 2] and [2, 4]. let diagRange = (aRange / 2) - (aRange % 2); let sideRefs = GCON('SIDE_REFS'); let diagLocs = {}; let diagDirs = GCON('DIAG_DIRS').slice(); let curDir = null; let curLoc = null; let curLocData = null; let dXY = null; while (diagDirs.length) { curDir = diagDirs.shift(); diagLocs[curDir] = []; dX = curDir.split('')[1]; dY = curDir.split('')[0]; dXY = curDir; // remember to reset this on each iteration of the outer loop, // then it will be updated with each iteration of the inner loop curLoc = aLoc; while (diagLocs[curDir].length < diagRange) { curLocData = { loc: null, locXY: null, }; if (curLoc) { curLocData.loc = curLoc; curLocData.locXY = sideRefs[curLoc][dXY]; } else { curLocData.loc = false; curLocData.locXY = false; } // then update the curLoc for the next loop, then push the curLocData curLoc = curLocData.locXY; diagLocs[curDir].push(curLocData); } } /* note: this is what we have: diagLocs = { 'NE': [ { loc: '10,10', locX: '11,10', locY: '10,11', locXY: '11,11', }, { loc: '11,11', locX: '12,11', locY: '11,12', locXY: '12,12', }, (...) ], 'SE': [(...)], 'SW': [(...)], 'NW': [(...)], } for each diagDir, calculate each diagLoc from the curLoc, indexed by distance each diagLoc */ return diagLocs; }; ARL.Fov.prototype.addArcToRange = function(params) { let anArc = params.anArc; let aRange = params.aRange; // arc will be a pair of fractions, e.g. // [[1, 8], [3, 8]] let rangeIdx = null; let curArc = null; let arcStart = false; let arcEnd = false; let isWithin = { found: 0, start: null, end: null, }; let newArc = [ [null, null], [null, null] ]; let idxDiff = null; if (aRange.length === 0) { aRange.push(anArc); return aRange; } if (aRange.length === 1 && SIG('fracEqualTo', [aRange[0][0], [0, 1]]) && SIG('fracEqualTo', [aRange[0][1], [1, 1]])) { // everything is shadowed, don't even bother lol return aRange; } for (rangeIdx in aRange) { if (aRange[rangeIdx].length === 2) { curArc = aRange[rangeIdx]; // does my arcStart point fall in this range if (SIG('fracGreaterOrEqual', [anArc[0], curArc[0]]) && SIG('fracLesserOrEqual', [anArc[0], curArc[1]])) { // it does, so we add this index to isWithin isWithin.start = rangeIdx; isWithin.found += 1; arcStart = true; } // does my arcEnd point fall in this range if (SIG('fracGreaterOrEqual', [anArc[1], curArc[0]]) && SIG('fracLesserOrEqual', [anArc[1], curArc[1]])) { isWithin.end = rangeIdx; isWithin.found += 1; arcEnd = true; } if (arcStart === true && arcEnd === true) { // if we got it already, don't even sweat the rest break; } } } if (isWithin.found === 0) { for (rangeIdx in aRange) { if (aRange[rangeIdx].length === 2) { curArc = aRange[rangeIdx]; if (aRange.length === 1) { // only one other shadow, we're either before or after it if (SIG('fracGreaterThan', [anArc[0], curArc[0]]) === true) { aRange.push(anArc); return aRange; } else { aRange.unshift(anArc); return aRange; } } else { // does anArc come before the first arc in the range? if (parseInt(rangeIdx) === 0 && SIG('fracLesserThan', [anArc[1], curArc[0]])) { aRange.unshift(anArc); return aRange; } // does anArc come after the last arc in the range? else if (parseInt(rangeIdx) === aRange.length - 1 && SIG('fracGreaterThan', [anArc[0], curArc[1]])) { aRange.push(anArc); return aRange; } // does anArc fall between two arcs in the range? else if (parseInt(rangeIdx) > 0 && SIG('fracLesserThan', [anArc[1], curArc[0]]) && SIG('fracGreaterThan', [anArc[0], aRange[rangeIdx - 1][1]])) { aRange.splice(rangeIdx, 0, anArc); return aRange; } } } } } else if (isWithin.found === 1) { // does anArc start inside another arc? if (arcStart === true) { newArc[0] = SIG('fracLesserOf', [anArc[0], aRange[isWithin.start][0]]); newArc[1] = SIG('fracGreaterOf', [anArc[1], aRange[isWithin.start][1]]); aRange.splice(isWithin.start, 1, newArc); return aRange; } // does anArc end inside another arc? else if (arcEnd === true) { newArc[0] = SIG('fracLesserOf', [anArc[0], aRange[isWithin.end][0]]); newArc[1] = SIG('fracGreaterOf', [anArc[1], aRange[isWithin.end][1]]); aRange.splice(isWithin.end, 1, newArc); return aRange; } } // doea anArc start in one arc and end inside another? else if (isWithin.found === 2) { newArc[0] = SIG('fracLesserOf', [anArc[0], aRange[isWithin.start][0]]); newArc[1] = SIG('fracGreaterOf', [anArc[1], aRange[isWithin.end][1]]); idxDiff = (isWithin.end - isWithin.start) + 1; // we pull out everything that we're about to replace // then cram in the new stuff aRange.splice(isWithin.start, idxDiff, newArc); // then we send back the new range //console.log('new aRange: ' + aRange); return aRange; } // if all else fails, for the love of god just return aRange return aRange; }; ARL.Fov.prototype.checkRangeForArc = function(params) { let anArc = params.anArc; let aRange = params.aRange; let rangeIdx = null; let curArc = null; let arcStart = false; let arcEnd = false; // to be in shadow, the entirety of this range must // fall into a single shadow range. for (rangeIdx = 0; rangeIdx < aRange.length; rangeIdx += 1) { curArc = aRange[rangeIdx]; arcStart = false; arcEnd = false; // does my arcStart point fall in this range if (SIG('fracGreaterOrEqual', [anArc[0], curArc[0]]) && SIG('fracLesserOrEqual', [anArc[0], curArc[1]])) { arcStart = true; } // does my arcEnd point fall in this range if (SIG('fracGreaterOrEqual', [anArc[1], curArc[0]]) && SIG('fracLesserOrEqual', [anArc[1], curArc[1]])) { arcEnd = true; } if (arcStart === true && arcEnd === true) { return true; } } // if it's not in any of the ranges, it's visible. return false; }; ARL.Fov.prototype.updateMobFovOnCurrentFloor = function() { // for each mob on the current floor, // build the rings for each mob's field of view // calculate the mob's vInViewLocs // update the mob's known locs let curFloor = GCON('PHYS_MAP')[GCON('CURRENT_FLOOR')]; let curFloorMap = GCON('FLOOR_MAP')[GCON('CURRENT_FLOOR')]; let curFloorMobs = curFloorMap.fMobs.slice(); let curMobIdx = null; let curMob = null; // we mark ANY loc we touch here as dirty. let touchedLocs = new Set(); let fullRange = null; let diagLocs = null; let oldView = null; let newView = null; let newKnown = null; let ringIdx = null; let aRing = null; let locIdx = null; let aLoc = null; let curArcSize = null; let halfCurArcSize = null; let curAngle = null; let curArc = null; let isArcSplit = null; let arcOverlap = null; let shadowRange = null; let diagDirs = null; let curDir = null; let curDiagLoc = null; let thisLoc = null; let nextLoc = null; // LET'S DO THIS for (curMobIdx in curFloorMobs) { if (GET(curFloorMobs[curMobIdx])) { curMob = GET(curFloorMobs[curMobIdx]); // These need to be reassigned values for each mob fullRange = SIG('buildRings', { aLoc: curMob.mPosition.pLocXY, aRange: curMob.mVision.vFov, }); diagLocs = SIG('buildDiagonals', { aLoc: curMob.mPosition.pLocXY, aRange: curMob.mVision.vFov, }); oldView = new Set(curMob.mVision.vInViewLocs.slice()); newView = new Set(); newKnown = new Set(curMob.mVision.vKnownLocs.slice()); ringIdx = null; aRing = null; locIdx = null; aLoc = null; curArcSize = null; halfCurArcSize = null; curAngle = null; curArc = null; isArcSplit = null; arcOverlap = null; shadowRange = []; // This is a clusterfuck, so let me break it down, yikes // We iterate over each ring for (ringIdx in fullRange) { // This breaks if there are no locs in the ring, which SHOULD NOT HAPPEN if (fullRange[ringIdx].length) { aRing = fullRange[ringIdx]; // We iterate over each loc in each ring for (locIdx in aRing) { // There are only two possible types of values for aRing[locIdx]: // false OR any loc in the form 'x,y' if (aRing[locIdx] === false || aRing[locIdx].split(',').length === 2) { aLoc = aRing[locIdx]; // we need this now since our rings are generated to include // false values in the place of any loc that's off the grid if (aLoc === false) { continue; } // if we haven't touched it yet, we are now touching it // using a Set for this instead of an array builds in some validation touchedLocs.add(aLoc); // Now comes the shadowcasting. // first we derive our arc size, which is the number of arcs // the current ring is divided into. isArcSplit = false; curArcSize = [1, aRing.length]; halfCurArcSize = [1, curArcSize[1] * 2]; curAngle = [locIdx, curArcSize[1]]; curArc = [ [null, null], [null, null] ]; // to derive the current arc, we take the curArcSize and // multiply it by 2, then we subtract that from the curAngle // to get our min and add it to the curAngle for the max. curArc[0] = SIG('fracDiff', [curAngle, halfCurArcSize]); // since we always start at the top, at 0 degrees, we never // have to worry about going over 1, only under 0, so we can // do this validation here and then check if our min is > // our max later safely. if (curArc[0][0] < 0) { // if it's negative, adding 1 will just loop us around curArc[0][0] += curArc[0][1]; } curArc[1] = SIG('fracSum', [curAngle, halfCurArcSize]); // does this arc overlap 0, if yes, split it if (SIG('fracGreaterOf', [curArc[0], curArc[1]]) === curArc[0]) { isArcSplit = true; arcOverlap = [ [null, null], [curArc[1][1], curArc[1][1]] ]; arcOverlap[0] = curArc.shift(); curArc.unshift([0, arcOverlap[1][1]]); } if (isArcSplit === true) { // then we check to see if we can see the block if (SIG('checkRangeForArc', { anArc: curArc, aRange: shadowRange }) && SIG('checkRangeForArc', { anArc: arcOverlap, aRange: shadowRange }) ) { // if both return true, it is fully in shadow and we can move on // curFloor[aLoc].aVisible = false; } else { // curFloor[aLoc].aVisible = true; newView.add(aLoc); oldView.delete(aLoc); newKnown.add(aLoc); // then we check to see if the tile blocks LOS if (GCON('TERRAIN_BASE')[curFloor[aLoc].aTerrain].tSeeThru === false) { // add it to the shadow range if it's not already there shadowRange = SIG('addArcToRange', { anArc: curArc, aRange: shadowRange }); shadowRange = SIG('addArcToRange', { anArc: arcOverlap, aRange: shadowRange }); } } } else { // then we check to see if we can see the block if (SIG('checkRangeForArc', { anArc: curArc, aRange: shadowRange}) ) { // if it returns true, it is fully in shadow and we can move on // curFloor[aLoc].aVisible = false; } else { // curFloor[aLoc].aVisible = true; newView.add(aLoc); oldView.delete(aLoc); newKnown.add(aLoc); // then we check to see if the tile blocks LOS if (GCON('TERRAIN_BASE')[curFloor[aLoc].aTerrain].tSeeThru === false) { // add it to the shadow range if it's not already there shadowRange = SIG('addArcToRange', { anArc: curArc, aRange: shadowRange }); } } } // THIS IS THE DEAL WITH newView AND oldView // Originally, we toggled the visibility of tiles when we calculated the shadows // Then we put them in the newView if they were visible // So the newView is the list of visible tiles // After our updates, we're going to compile the entire newView and then update visibility based on that // We... should be able to calculate which tiles are no longer visible by using all the locs that // are known but not currently in view. // if it's visible, you know it now if you didn't already /* if (curFloor[aLoc].aVisible === true) { newView.push(aLoc); // update this for all mobs if (GCON('PLAYER_MOB').mVision.vKnownLocs.indexOf(aLoc) === -1) { GCON('PLAYER_MOB').mVision.vKnownLocs.push(aLoc); } } // regardless, we splice it out of oldView if it's there if (oldView.indexOf(aLoc) !== -1) { oldView.splice(oldView.indexOf(aLoc), 1); } */ } } } } // THEN we check the diagonals to see if any of those tricky inside corner spaces are in view diagDirs = GCON('DIAG_DIRS').slice(); curDir = null; curDiagLoc = null; thisLoc = null; nextLoc = null; while (diagDirs.length) { curDir = diagDirs.shift(); while (diagLocs[curDir].length) { curDiagLoc = diagLocs[curDir].shift(); // if anything here is false, we just move on, it will loop itself out if (curDiagLoc.loc === false || curDiagLoc.locXY === false) { continue; } thisLoc = curDiagLoc.loc; nextLoc = curDiagLoc.locXY; // if we can see through the tile, it's visible, and the next tile isn't visible, // we mark it visible and handle it appropriately. if ( GCON('TERRAIN_BASE')[curFloor[thisLoc].aTerrain].tSeeThru === true && newView.has(thisLoc) === true && newView.has(nextLoc) === false) { //curFloor[nextLoc].aVisible = true; // I don't think this should ever be in there if it's not visible??? newView.add(nextLoc); oldView.delete(nextLoc); newKnown.add(nextLoc); /* if (newView.indexOf(nextLoc) === -1) { newView.push(nextLoc); } // replace this with a check that uses the current mob if (GCON('PLAYER_MOB').mVision.vKnownLocs.indexOf(nextLoc) === -1) { GCON('PLAYER_MOB').mVision.vKnownLocs.push(nextLoc); } if (oldView.indexOf(nextLoc) !== -1) { oldView.splice(oldView.indexOf(nextLoc), 1); } */ } } } // then we clean up all the known cells that are now out of view oldView = [...oldView]; while (oldView.length > 0) { touchedLocs.add(oldView.shift()); } // finish this mob up here // then we assign the newView as the new gInViewLocs // replace this with an assignment that uses the current mob curMob.mVision.vInViewLocs = [...newView]; curMob.mVision.vKnownLocs = [...newKnown]; // HELLA HACKY HACK FOR FIXING GOBBOS WANDERING INTO PITS // This should make the entire map visible to the player at all times /* if (curMob.mIdentity.iType === 'player') { curMob.mVision.vInViewLocs = [...GCON('PHYS_LOCS')]; curMob.mVision.vKnownLocs = [...GCON('PHYS_LOCS')]; } */ } } // ok, then we reconcile the updated field of view with the visibility of the physMap // oh my god we already do that as part of handleTileUpdates, FUCK WOW // last thing we do here is handle all those updates. SIG('handleTileUpdates', [...touchedLocs]); }; /* * * * Courtesy Spaces * * */
gpl-3.0
kingtang/spring-learn
spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java
9656
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.springframework.core.GenericTypeResolver.*; import static org.springframework.util.ReflectionUtils.*; /** * @author Juergen Hoeller * @author Sam Brannen */ public class GenericTypeResolverTests { @Test public void simpleInterfaceType() { assertEquals(String.class, resolveTypeArgument(MySimpleInterfaceType.class, MyInterfaceType.class)); } @Test public void simpleCollectionInterfaceType() { assertEquals(Collection.class, resolveTypeArgument(MyCollectionInterfaceType.class, MyInterfaceType.class)); } @Test public void simpleSuperclassType() { assertEquals(String.class, resolveTypeArgument(MySimpleSuperclassType.class, MySuperclassType.class)); } @Test public void simpleCollectionSuperclassType() { assertEquals(Collection.class, resolveTypeArgument(MyCollectionSuperclassType.class, MySuperclassType.class)); } @Test public void nullIfNotResolvable() { GenericClass<String> obj = new GenericClass<String>(); assertNull(resolveTypeArgument(obj.getClass(), GenericClass.class)); } @Test public void methodReturnTypes() { assertEquals(Integer.class, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "integer"), MyInterfaceType.class)); assertEquals(String.class, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "string"), MyInterfaceType.class)); assertEquals(null, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "raw"), MyInterfaceType.class)); assertEquals(null, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "object"), MyInterfaceType.class)); } @Test public void testResolveType() { Method intMessageMethod = findMethod(MyTypeWithMethods.class, "readIntegerInputMessage", MyInterfaceType.class); MethodParameter intMessageMethodParam = new MethodParameter(intMessageMethod, 0); assertEquals(MyInterfaceType.class, resolveType(intMessageMethodParam.getGenericParameterType(), new HashMap<TypeVariable, Type>())); Method intArrMessageMethod = findMethod(MyTypeWithMethods.class, "readIntegerArrayInputMessage", MyInterfaceType[].class); MethodParameter intArrMessageMethodParam = new MethodParameter(intArrMessageMethod, 0); assertEquals(MyInterfaceType[].class, resolveType(intArrMessageMethodParam.getGenericParameterType(), new HashMap<TypeVariable, Type>())); Method genericArrMessageMethod = findMethod(MySimpleTypeWithMethods.class, "readGenericArrayInputMessage", Object[].class); MethodParameter genericArrMessageMethodParam = new MethodParameter(genericArrMessageMethod, 0); Map<TypeVariable, Type> varMap = getTypeVariableMap(MySimpleTypeWithMethods.class); assertEquals(Integer[].class, resolveType(genericArrMessageMethodParam.getGenericParameterType(), varMap)); } @Test public void testBoundParameterizedType() { assertEquals(B.class, resolveTypeArgument(TestImpl.class, ITest.class)); } @Test public void testGetTypeVariableMap() throws Exception { Map<TypeVariable, Type> map; map = GenericTypeResolver.getTypeVariableMap(MySimpleInterfaceType.class); assertThat(map.toString(), equalTo("{T=class java.lang.String}")); map = GenericTypeResolver.getTypeVariableMap(MyCollectionInterfaceType.class); assertThat(map.toString(), equalTo("{T=java.util.Collection<java.lang.String>}")); map = GenericTypeResolver.getTypeVariableMap(MyCollectionSuperclassType.class); assertThat(map.toString(), equalTo("{T=java.util.Collection<java.lang.String>}")); map = GenericTypeResolver.getTypeVariableMap(MySimpleTypeWithMethods.class); assertThat(map.toString(), equalTo("{T=class java.lang.Integer}")); map = GenericTypeResolver.getTypeVariableMap(TopLevelClass.class); assertThat(map.toString(), equalTo("{}")); map = GenericTypeResolver.getTypeVariableMap(TypedTopLevelClass.class); assertThat(map.toString(), equalTo("{T=class java.lang.Integer}")); map = GenericTypeResolver.getTypeVariableMap(TypedTopLevelClass.TypedNested.class); assertThat(map.size(), equalTo(2)); Type t = null; Type x = null; for (Map.Entry<TypeVariable, Type> entry : map.entrySet()) { if(entry.getKey().toString().equals("T")) { t = entry.getValue(); } else { x = entry.getValue(); } } assertThat(t, equalTo((Type) Integer.class)); assertThat(x, equalTo((Type) Long.class)); } @Test public void getGenericsCannotBeResolved() throws Exception { // SPR-11030 Class<?>[] resolved = GenericTypeResolver.resolveTypeArguments(List.class, Iterable.class); // Note: to be changed to return null in Spring 4.0 assertThat(resolved, equalTo(new Class[] {Object.class})); } @Test public void getRawMapTypeCannotBeResolved() throws Exception { // SPR-11052 Class<?>[] resolved = GenericTypeResolver.resolveTypeArguments(Map.class, Map.class); assertNull(resolved); } @Test public void getGenericsOnArrayFromParamCannotBeResolved() throws Exception { // SPR-11044 MethodParameter methodParameter = MethodParameter.forMethodOrConstructor( WithArrayBase.class.getDeclaredMethod("array", Object[].class), 0); Class<?> resolved = GenericTypeResolver.resolveParameterType(methodParameter, WithArray.class); assertThat(resolved, equalTo((Class) Object[].class)); } @Test public void getGenericsOnArrayFromReturnCannotBeResolved() throws Exception { // SPR-11044 Class<?> resolved = GenericTypeResolver.resolveReturnType( WithArrayBase.class.getDeclaredMethod("array", Object[].class), WithArray.class); assertThat(resolved, equalTo((Class) Object[].class)); } public interface MyInterfaceType<T> { } public class MySimpleInterfaceType implements MyInterfaceType<String> { } public class MyCollectionInterfaceType implements MyInterfaceType<Collection<String>> { } public abstract class MySuperclassType<T> { } public class MySimpleSuperclassType extends MySuperclassType<String> { } public class MyCollectionSuperclassType extends MySuperclassType<Collection<String>> { } public static class MyTypeWithMethods<T> { public MyInterfaceType<Integer> integer() { return null; } public MySimpleInterfaceType string() { return null; } public Object object() { return null; } @SuppressWarnings("rawtypes") public MyInterfaceType raw() { return null; } public String notParameterized() { return null; } public String notParameterizedWithArguments(Integer x, Boolean b) { return null; } /** * Simulates a factory method that wraps the supplied object in a proxy of the * same type. */ public static <T> T createProxy(T object) { return null; } /** * Similar to {@link #createProxy(Object)} but adds an additional argument before * the argument of type {@code T}. Note that they may potentially be of the same * time when invoked! */ public static <T> T createNamedProxy(String name, T object) { return null; } /** * Simulates factory methods found in libraries such as Mockito and EasyMock. */ public static <MOCK> MOCK createMock(Class<MOCK> toMock) { return null; } /** * Similar to {@link #createMock(Class)} but adds an additional method argument * before the parameterized argument. */ public static <T> T createNamedMock(String name, Class<T> toMock) { return null; } /** * Similar to {@link #createNamedMock(String, Class)} but adds an additional * parameterized type. */ public static <V extends Object, T> T createVMock(V name, Class<T> toMock) { return null; } /** * Extract some value of the type supported by the interface (i.e., by a concrete, * non-generic implementation of the interface). */ public static <T> T extractValueFrom(MyInterfaceType<T> myInterfaceType) { return null; } /** * Extract some magic value from the supplied map. */ public static <K, V> V extractMagicValue(Map<K, V> map) { return null; } public void readIntegerInputMessage(MyInterfaceType<Integer> message) { } public void readIntegerArrayInputMessage(MyInterfaceType<Integer>[] message) { } public void readGenericArrayInputMessage(T[] message) { } } public static class MySimpleTypeWithMethods extends MyTypeWithMethods<Integer> { } static class GenericClass<T> { } class A{} class B<T>{} class ITest<T>{} class TestImpl<I extends A, T extends B<I>> extends ITest<T>{ } static class TopLevelClass<T> { class Nested<X> { } } static class TypedTopLevelClass extends TopLevelClass<Integer> { class TypedNested extends Nested<Long> { } } static abstract class WithArrayBase<T> { public abstract T[] array(T... args); } static abstract class WithArray<T> extends WithArrayBase<T> { } }
gpl-3.0
R-Blouin/Etk.Excel
Etk/EtkException.cs
1319
using System; using System.Runtime.Serialization; using Etk.Tools.Log; namespace Etk { [Serializable] public class EtkException : Exception { private readonly ILogger log = Logger.Instance; public EtkException() : base() { } public EtkException(string message) : base(message) { log.LogException(LogType.Error, this, message); } public EtkException(string message, bool logException) : base(message) { if (logException) log.LogException(LogType.Error, this, message); } public EtkException(string message, Exception innerException) : base(message, innerException) { log.LogException(LogType.Error, this, base.Message); } public EtkException(string message, Exception innerException, bool logException) : base(message, innerException) { if (logException) log.LogException(LogType.Error, this, message); } protected EtkException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
gpl-3.0
ianj-als/omtc
src/test/java/com/capitati/omtc/core/session/SessionTests.java
6880
package com.capitati.omtc.core.session; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; import java.util.Set; import java.util.UUID; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.capitati.omtc.core.notification.IResourceUploadObserver; import com.capitati.omtc.core.resources.IResource; import com.capitati.omtc.core.resources.IResourceReader; import com.capitati.omtc.core.resources.IResourceWriter; import com.google.common.base.Predicate; public class SessionTests { class TestSession extends Session { protected TestSession( final UUID theIdentifier, final AbstractExecutorService theDelegationExecutorService, final int bufferSize) { super(theIdentifier, theDelegationExecutorService, bufferSize); } public Set<IResource> retrieveResources(final Predicate<IResource> theFilter) throws Exception { return null; } public void removeResource(final IResource resource) throws Exception { } } private static final String MESSAGE = "Whose was it? His who is gone. " + "Who shall have it? He who will come. " + "Where was the sun? Over the oak. " + "Where was the shadow? Under the elm. " + "How was it stepped? North by ten and by ten, east by five and by five, " + "south by two and by two, west by one and by one, and so under. " + "What shall we give for it? All that is ours. " + "Why should we give it? For the sake of the trust."; private final UUID resourceId = UUID.randomUUID(); private final Date resourceBirthDate = new Date(); private URI resourceUri; private Mockery mockery; private AbstractExecutorService executor; private Session session; @Before public void setUp() throws URISyntaxException { mockery = new JUnit4Mockery(); resourceUri = new URI("test://some_resource_or_other"); executor = new ThreadPoolExecutor( 1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1)); session = new TestSession(UUID.randomUUID(), executor, MESSAGE.length() / 4); } @After public void tearDown() { executor.shutdown(); } @Test public void testSuccessfulUpload() throws Exception { final IResourceTransferDelegate delegate = new ResourceUploadDelegate( MESSAGE, resourceId, resourceUri, resourceBirthDate); final IResourceUploadObserver observer = mockery.mock(IResourceUploadObserver.class, "successUploadObserver"); final IResource targetResource = delegate.getResource(session); mockery.checking(new Expectations() {{ oneOf(observer).onSuccess( with(equal(session)), with(equal(targetResource))); }}); final Future<IResource> futureResource = session.uploadResource(delegate, observer); final IResource resource = futureResource.get(); Assert.assertSame("Wrong resource", targetResource, resource); } @Test(expected = SessionTestException.class) public void testReaderReadFailureOnUpload() throws Throwable { final Exception targetException = new SessionTestException(); final IResourceReader resourceReader = mockery.mock(IResourceReader.class, "resourceReader"); final IResourceWriter resourceWriter = mockery.mock(IResourceWriter.class, "resourceWriter"); final IResourceTransferDelegate delegate = mockery.mock(IResourceTransferDelegate.class, "badUploadDelegate"); final IResourceUploadObserver observer = mockery.mock(IResourceUploadObserver.class, "badUploadObserver"); final IResource resource = mockery.mock(IResource.class, "badResource"); mockery.checking(new Expectations() {{ allowing(delegate).getResource(with(equal(session))); will(returnValue(resource)); oneOf(resourceReader).read(with(any(byte[].class))); will(throwException(targetException)); oneOf(resourceReader).close(); oneOf(resourceWriter).close(); oneOf(delegate).getResourceReader(with(equal(session))); will(returnValue(resourceReader)); oneOf(delegate).getResourceWriter(with(equal(session))); will(returnValue(resourceWriter)); oneOf(observer).onError( with(equal(session)), with(equal(resource)), with(equal(targetException))); }}); final Future<IResource> futureResource = session.uploadResource(delegate, observer); try { @SuppressWarnings("unused") final IResource future = futureResource.get(); } catch(final ExecutionException ex) { throw ex.getCause(); } } @Test(expected = SessionTestException.class) public void testWriterWriteFailureOnUpload() throws Throwable { final Exception targetException = new SessionTestException(); final IResourceReader resourceReader = mockery.mock(IResourceReader.class, "resourceReader"); final IResourceWriter resourceWriter = mockery.mock(IResourceWriter.class, "resourceWriter"); final IResourceTransferDelegate delegate = mockery.mock(IResourceTransferDelegate.class, "badUploadDelegate"); final IResourceUploadObserver observer = mockery.mock(IResourceUploadObserver.class, "badUploadObserver"); final IResource resource = mockery.mock(IResource.class, "badResource"); mockery.checking(new Expectations() {{ allowing(delegate).getResource(with(equal(session))); will(returnValue(resource)); oneOf(resourceReader).read(with(any(byte[].class))); will(returnValue(7)); oneOf(resourceReader).close(); oneOf(resourceWriter).write(with(any(byte[].class)), with(any(int.class))); will(throwException(targetException)); oneOf(resourceWriter).close(); oneOf(delegate).getResourceReader(with(equal(session))); will(returnValue(resourceReader)); oneOf(delegate).getResourceWriter(with(equal(session))); will(returnValue(resourceWriter)); oneOf(observer).onError( with(equal(session)), with(equal(resource)), with(equal(targetException))); }}); final Future<IResource> futureResource = session.uploadResource(delegate, observer); try { @SuppressWarnings("unused") final IResource future = futureResource.get(); } catch(final ExecutionException ex) { throw ex.getCause(); } } }
gpl-3.0
elmsln/elmsln
core/dslmcode/cores/haxcms-1/build/es5-amd/node_modules/@polymer/polymer/lib/utils/mixin.js
2774
define(["exports", "./boot.js"], function (_exports, _boot) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.dedupingMixin = void 0; /** @license Copyright (c) 2017 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // unique global id for deduping mixins. var dedupeId = 0; /** * @constructor * @extends {Function} * @private */ function MixinFunction() {} /** @type {(WeakMap | undefined)} */ MixinFunction.prototype.__mixinApplications; /** @type {(Object | undefined)} */ MixinFunction.prototype.__mixinSet; /* eslint-disable valid-jsdoc */ /** * Wraps an ES6 class expression mixin such that the mixin is only applied * if it has not already been applied its base argument. Also memoizes mixin * applications. * * @template T * @param {T} mixin ES6 class expression mixin to wrap * @return {T} * @suppress {invalidCasts} */ var dedupingMixin = function dedupingMixin(mixin) { var mixinApplications = /** @type {!MixinFunction} */ mixin.__mixinApplications; if (!mixinApplications) { mixinApplications = new WeakMap(); /** @type {!MixinFunction} */ mixin.__mixinApplications = mixinApplications; } // maintain a unique id for each mixin var mixinDedupeId = dedupeId++; function dedupingMixin(base) { var baseSet = /** @type {!MixinFunction} */ base.__mixinSet; if (baseSet && baseSet[mixinDedupeId]) { return base; } var map = mixinApplications; var extended = map.get(base); if (!extended) { extended = /** @type {!Function} */ mixin(base); map.set(base, extended); // copy inherited mixin set from the extended class, or the base class // NOTE: we avoid use of Set here because some browser (IE11) // cannot extend a base Set via the constructor. var mixinSet = Object.create( /** @type {!MixinFunction} */ extended.__mixinSet || baseSet || null); mixinSet[mixinDedupeId] = true; /** @type {!MixinFunction} */ extended.__mixinSet = mixinSet; } return extended; } return dedupingMixin; }; /* eslint-enable valid-jsdoc */ _exports.dedupingMixin = dedupingMixin; });
gpl-3.0
furylynx/MAE
libmae/src/mae/fl/laban/mv/direction_symbol.cpp
12093
#include "direction_symbol.hpp" namespace mae { namespace fl { namespace laban { namespace mv { direction_symbol::direction_symbol(e_level vertical, e_direction horizontal, std::shared_ptr<pin> modification_pin, std::shared_ptr<pin> relationship_pin, std::shared_ptr<i_dynamics_sign> dynamics, std::shared_ptr<space_measurement> space_measurement, e_contact_hook contact_hook) { vertical_ = vertical; horizontal_ = horizontal; modification_pin_ = modification_pin; relationship_pin_ = relationship_pin; dynamics_ = dynamics; space_measurement_ = space_measurement; contact_hook_ = contact_hook; if (vertical == e_level::NONE_LEVEL || horizontal == e_direction::NONE_DIRECTION) { throw std::invalid_argument("Direction and level must not be NONE."); } } direction_symbol::~direction_symbol() { } e_level direction_symbol::get_vertical() const { return vertical_; } e_direction direction_symbol::get_horizontal() const { return horizontal_; } std::shared_ptr<pin> direction_symbol::get_modification_pin() const { return modification_pin_; } std::shared_ptr<pin> direction_symbol::get_relationship_pin() const { return relationship_pin_; } std::shared_ptr<i_dynamics_sign> direction_symbol::get_dynamics() const { return dynamics_; } std::shared_ptr<space_measurement> direction_symbol::get_space_measurement() const { return space_measurement_; } e_contact_hook direction_symbol::get_contact_hook() const { return contact_hook_; } bool direction_symbol::equals(std::shared_ptr<i_symbol> a) const { if (std::shared_ptr<direction_symbol> a_dir = std::dynamic_pointer_cast<direction_symbol>(a)) { if (a_dir->get_horizontal() == horizontal_ && a_dir->get_vertical() == vertical_ && a_dir->get_contact_hook() == contact_hook_) { //check modification pin if ((modification_pin_ != nullptr && modification_pin_->equals(a_dir->get_modification_pin())) || (modification_pin_ == nullptr && a_dir->get_modification_pin() == nullptr)) { //check relationship pin if ((relationship_pin_ != nullptr && relationship_pin_->equals(a_dir->get_relationship_pin())) || (relationship_pin_ == nullptr && a_dir->get_relationship_pin() == nullptr)) { //check dynamics sign if ((dynamics_ != nullptr && dynamics_->equals(a_dir->get_dynamics())) || (dynamics_ == nullptr && a_dir->get_dynamics() == nullptr)) { //check space measurement if ((space_measurement_ != nullptr && space_measurement_->equals(a_dir->get_space_measurement())) || (space_measurement_ == nullptr && a_dir->get_space_measurement() == nullptr)) { return true; } } } } } } return false; } std::string direction_symbol::xml(unsigned int indent, std::string namesp) const { std::stringstream indent_stream; for (unsigned int i = 0; i < indent; i++) { indent_stream << "\t"; } std::string ns = namesp; if (ns.size() > 0 && ns.at(ns.size() - 1) != ':') { ns.push_back(':'); } std::stringstream sstr; //print accent sign sstr << indent_stream.str() << "<" << ns << "direction>" << std::endl; sstr << indent_stream.str() << "\t" << "<" << ns << "vertical>" << e_level_c::str(vertical_) << "</" << ns << "vertical>" << std::endl; sstr << indent_stream.str() << "\t" << "<" << ns << "horizontal>" << e_direction_c::str(horizontal_) << "</" << ns << "horizontal>" << std::endl; if (modification_pin_ != nullptr) { sstr << indent_stream.str() << "\t" << "<" << ns << "modificationPin>" << std::endl; sstr << modification_pin_->xml(indent + 1, namesp); sstr << indent_stream.str() << "\t" << "</" << ns << "modificationPin>" << std::endl; } if (relationship_pin_ != nullptr) { sstr << indent_stream.str() << "\t" << "<" << ns << "relationshipPin>" << std::endl; sstr << relationship_pin_->xml(indent + 1, namesp); sstr << indent_stream.str() << "\t" << "</" << ns << "relationshipPin>" << std::endl; } if (space_measurement_ != nullptr) { sstr << space_measurement_->xml(indent + 1, namesp); } if (dynamics_ != nullptr) { sstr << dynamics_->xml(indent + 1, namesp); } if (contact_hook_ != e_contact_hook::NONE_CONTACT_HOOK) { sstr << indent_stream.str() << "\t" << "<" << ns << "contactHook>" << e_contact_hook_c::str(contact_hook_) << "</" << ns << "contactHook>" << std::endl; } sstr << indent_stream.str() << "</" << ns << "direction>" << std::endl; return sstr.str(); } std::string direction_symbol::svg(std::string identifier, double posx, double posy, double width, double height, bool left) const { std::stringstream sstr; //TODO relationship pin, dynamics, contact hook //double orig_height = height; if (space_measurement_ != nullptr) { height -= width; if (height < 0) { height = 0.01; } } if (horizontal_ == e_direction::PLACE) { sstr << "\t\t<rect" << std::endl; sstr << "\t\t\twidth=\"" << width << "\"" << std::endl; sstr << "\t\t\theight=\"" << height << "\"" << std::endl; sstr << "\t\t\tx=\"" << posx << "\"" << std::endl; sstr << "\t\t\ty=\"" << posy << "\"" << std::endl; } else if (horizontal_ == e_direction::LEFT) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx+width << "," << posy << " " << 0 << "," << height << " " << -width << "," << -height/2.0 << " " << width << "," << -height/2.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::RIGHT) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx << "," << posy << " " << 0 << "," << height << " " << width << "," << -height/2.0 << " " << -width << "," << -height/2.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::FORWARD && left) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx << "," << posy+height/3.0 << " " << width/2.0 << "," << 0 << " " << 0 << "," << -height/3.0 << " " << width/2.0 << "," << 0 << " " << 0 << "," << height << " " << -width << "," << 0 << " " << 0 << "," << -2*height/3.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::FORWARD && !left) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx+width << "," << posy+height/3.0 << " " << -width/2.0 << "," << 0 << " " << 0 << "," << -height/3.0 << " " << -width/2.0 << "," << 0 << " " << 0 << "," << height << " " << width << "," << 0 << " " << 0 << "," << -2*height/3.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::BACKWARD && left) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx << "," << posy+height-height/3.0 << " " << width/2.0 << "," << 0 << " " << 0 << "," << height/3.0 << " " << width/2.0 << "," << 0 << " " << 0 << "," << -height << " " << -width << "," << 0 << " " << 0 << "," << 2*height/3.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::BACKWARD && !left) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx+width << "," << posy+height-height/3.0 << " " << -width/2.0 << "," << 0 << " " << 0 << "," << height/3.0 << " " << -width/2.0 << "," << 0 << " " << 0 << "," << -height << " " << width << "," << 0 << " " << 0 << "," << 2*height/3.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::RIGHT_FORWARD) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx << "," << posy+height/3.0 << " " << width << "," << -height/3.0 << " " << 0 << "," << height << " " << -width << "," << 0 << " " << 0 << "," << -2*height/3.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::LEFT_FORWARD) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx+width << "," << posy+height/3.0 << " " << -width << "," << -height/3.0 << " " << 0 << "," << height << " " << width << "," << 0 << " " << 0 << "," << -2*height/3.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::RIGHT_BACKWARD) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx << "," << posy+height-height/3.0 << " " << width << "," << height/3.0 << " " << 0 << "," << -height << " " << -width << "," << 0 << " " << 0 << "," << 2*height/3.0 << " z\"" << std::endl; } else if (horizontal_ == e_direction::LEFT_BACKWARD) { sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << posx+width << "," << posy+height-height/3.0 << " " << -width << "," << height/3.0 << " " << 0 << "," << -height << " " << width << "," << 0 << " " << 0 << "," << 2*height/3.0 << " z\"" << std::endl; } else { return ""; } sstr << "\t\t\tid=\"" << identifier << "\"" << std::endl; sstr << "\t\t\tstyle=\""; if (vertical_ == e_level::HIGH) { sstr << "fill:url(#fillpattern);fill-opacity:1;stroke:#000000;stroke-width:2pt;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"; } else if (vertical_ == e_level::LOW) { sstr << "fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:2pt;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"; } else if (vertical_ == e_level::MIDDLE) { sstr << "fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:2pt;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"; } else { return ""; } sstr << "\" />" << std::endl; if (vertical_ == e_level::MIDDLE) { double circ_x = posx + width/2.0; double circ_y = posy + height/2.0; double circ_r = width/12.0; if (horizontal_ == e_direction::RIGHT) { circ_x -= width/6.0; } else if (horizontal_ == e_direction::LEFT) { circ_x += width/6.0; } else if (horizontal_ == e_direction::FORWARD) { circ_y += height/6.0; } else if (horizontal_ == e_direction::BACKWARD) { circ_y -= height/6.0; } if (height < circ_r) { circ_r = height; } //draw circle sstr << "\t\t<path" << std::endl; sstr << "\t\t\td=\"m " << circ_x + circ_r << "," << circ_y << " a " << circ_r << "," << circ_r << " 0 1 1 -" << circ_r*2 << ",0 " << circ_r << "," << circ_r << " 0 1 1 " << circ_r*2 << ",0 z\"" << std::endl; sstr << "\t\t\tid=\"" << identifier << "-middot\"" << std::endl; sstr << "\t\t\tstyle=\"fill:#000000;fill-opacity:1;stroke:none\" />" << std::endl; } if (space_measurement_ != nullptr) { //draw space measurement double spm_y = posy + height + width*0.1; double spm_w = width*0.8; double spm_h = width*0.8; double spm_x = posx + width*0.1; sstr << space_measurement_->svg(identifier, spm_x, spm_y, spm_w, spm_h); } if (modification_pin_ != nullptr) { //draw pin double mpin_w = width*0.8; double mpin_h = width*0.8; double mpin_y = posy + height/2.0 - mpin_h/2.0; double mpin_x = posx + width/2.0 - mpin_w/2.0; sstr << space_measurement_->svg(identifier, mpin_x, mpin_y, mpin_w, mpin_h); } return sstr.str(); } std::string direction_symbol::str() const { std::stringstream sstr; sstr << "(" << e_direction_c::str(horizontal_) << "+" << e_level_c::str(vertical_) << ")"; return sstr.str(); } } // namespace mv } // namespace laban } // namespace fl } // namespace mae
gpl-3.0
ftninformatika/bisis-v5
bisis-swing-client/src/main/java/com/ftninformatika/bisis/libenv/PubTypeTreeModel.java
2511
/** * */ package com.ftninformatika.bisis.libenv; import com.ftninformatika.bisis.format.PubTypes; import com.ftninformatika.bisis.format.UField; import com.ftninformatika.bisis.format.UFormat; import com.ftninformatika.bisis.format.USubfield; import java.util.Vector; import javax.swing.event.EventListenerList; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; /** * @author dimicb * * models stabla koje sadrzi polja i potpolja * odgovarajuceg tipa publikacije * slican je kao models stabla u * editoru, ali ne sadrzi indikatore */ public class PubTypeTreeModel implements TreeModel { private int pubTypeId; private UFormat pubType; /** Listeners. */ protected EventListenerList listenerList = new EventListenerList(); private Vector<TreeModelListener> treeModelListeners = new Vector<TreeModelListener>(); public PubTypeTreeModel(int pubTypeId) { this.pubTypeId = pubTypeId; pubType = PubTypes.getPubType(pubTypeId); } public Object getChild(Object parent, int index) { if(parent instanceof UFormat) return ((UFormat)parent).getField(index); else if(parent instanceof UField) return ((UField)parent).getSubfields().get(index); return null; } public int getChildCount(Object parent) { if(parent instanceof UFormat) return ((UFormat)parent).getFields().size(); else if(parent instanceof UField) return ((UField)parent).getSubfieldCount(); return 0; } public int getIndexOfChild(Object parent, Object child) { return 0; } public Object getRoot() { return pubType; } public boolean isLeaf(Object node) { return (node instanceof USubfield); } public void valueForPathChanged(TreePath path, Object newValue) { } public void addTreeModelListener(TreeModelListener l){ treeModelListeners.addElement(l); } public void removeTreeModelListener(TreeModelListener l) { treeModelListeners.removeElement(l); } public void fireTreeStructureChanged() { TreeModelEvent e = new TreeModelEvent(this, new Object[] {pubType}); for (TreeModelListener tml : treeModelListeners) { tml.treeStructureChanged(e); } } public int getPubTypeId() { return pubTypeId; } public void setPubTypeId(int pubTypeId) { this.pubTypeId = pubTypeId; pubType = PubTypes.getPubType(pubTypeId); fireTreeStructureChanged(); } }
gpl-3.0
codehaus/geobatch
flowmanagers/jgsflodess/src/main/java/it/geosolutions/geobatch/registry/RegistryConfiguratorAction.java
2820
/* * GeoBatch - Open Source geospatial batch processing system * http://geobatch.codehaus.org/ * Copyright (C) 2007-2008-2009 GeoSolutions S.A.S. * http://www.geo-solutions.it * * GPLv3 + Classpath exception * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.geosolutions.geobatch.registry; import it.geosolutions.geobatch.flow.event.action.BaseAction; import java.io.IOException; import java.util.EventObject; import java.util.Map; import java.util.logging.Logger; /** * Comments here ... * * @author AlFa * * @version $ GeoServerConfiguratorAction.java $ Revision: 0.1 $ 12/feb/07 12:07:06 */ public abstract class RegistryConfiguratorAction<T extends EventObject>extends BaseAction<T> { /** * Default logger */ protected final static Logger LOGGER = Logger.getLogger(RegistryConfiguratorAction.class.toString()); protected final RegistryActionConfiguration configuration; /** * Constructs a producer. * The operation name will be the same than the parameter descriptor name. * * @throws IOException */ public RegistryConfiguratorAction(RegistryActionConfiguration configuration) { this.configuration = configuration; // // // // get required parameters // // // if ((configuration.getGeoserverURL() == null) || "".equals(configuration.getGeoserverURL())) { throw new IllegalStateException("GeoServerURL is null."); } } /** * @param queryParams * @return */ protected static String getQueryString(Map<String, String> queryParams) { StringBuilder queryString = new StringBuilder(); if (queryParams != null) for (Map.Entry<String, String> entry : queryParams.entrySet()) { if(queryString.length() > 0) queryString.append("&"); queryString.append(entry.getKey()).append("=").append(entry.getValue()); } return queryString.toString(); } public RegistryActionConfiguration getConfiguration() { return configuration; } @Override public String toString() { return getClass().getSimpleName() + "[" + "cfg:"+getConfiguration() + "]"; } }
gpl-3.0
dronekit/dronekit-server
src/main/scala/com/geeksville/scalatra/JettyLauncher.scala
1394
/** * ***************************************************************************** * Copyright 2013 Kevin Hester * * See LICENSE.txt for license details. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package com.geeksville.scalatra import org.eclipse.jetty.server.Server import org.eclipse.jetty.servlet.{ DefaultServlet, ServletContextHandler } import org.eclipse.jetty.webapp.WebAppContext import com.geeksville.nestor._ object JettyLauncher { // this is my entry object as specified in sbt project definition def main(args: Array[String]) { val port = if (System.getenv("PORT") != null) System.getenv("PORT").toInt else 8080 val server = new Server(port) val context = new WebAppContext() context setContextPath "/" context.setResourceBase("src/main/webapp") //context.addServlet(classOf[MainServlet], "/*") //context.addServlet(classOf[DeviceServlet], "/api/*") // context.addServlet(classOf[DefaultServlet], "/") server.setHandler(context) server.start server.join } }
gpl-3.0
papamas/DMS-KANGREG-XI-MANADO
src/main/java/com/openkm/extension/frontend/client/widget/dropbox/ConfirmPopup.java
4497
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.extension.frontend.client.widget.dropbox; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.openkm.frontend.client.extension.comunicator.GeneralComunicator; import com.openkm.frontend.client.extension.comunicator.UtilComunicator; /** * Confirm panel * * @author sochoa * */ public class ConfirmPopup extends DialogBox { public static final int NO_ACTION = 0; public static final int CONFIRM_EXPORT_DOCUMENT = 1; public static final int CONFIRM_EXPORT_FOLDER = 2; private VerticalPanel vPanel; private HorizontalPanel hPanel; private HTML text; private Button cancelButton; private Button acceptButton; private int action = 0; /** * Confirm popup */ public ConfirmPopup() { // Establishes auto-close when click outside super(false,true); setText(GeneralComunicator.i18nExtension("confirm.label")); vPanel = new VerticalPanel(); hPanel = new HorizontalPanel(); text = new HTML(); text.setStyleName("okm-NoWrap"); cancelButton = new Button(GeneralComunicator.i18n("button.cancel"), new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }); acceptButton = new Button(GeneralComunicator.i18n("button.accept"), new ClickHandler() { @Override public void onClick(ClickEvent event) { execute(); hide(); } }); vPanel.setWidth("300px"); vPanel.setHeight("50px"); cancelButton.setStyleName("okm-NoButton"); acceptButton.setStyleName("okm-YesButton"); text.setHTML(""); hPanel.add(cancelButton); hPanel.add(UtilComunicator.hSpace("5px")); hPanel.add(acceptButton); vPanel.add(UtilComunicator.vSpace("5px")); vPanel.add(text); vPanel.add(UtilComunicator.vSpace("5px")); vPanel.add(hPanel); vPanel.add(UtilComunicator.vSpace("5px")); vPanel.setCellHorizontalAlignment(text, VerticalPanel.ALIGN_CENTER); vPanel.setCellHorizontalAlignment(hPanel, VerticalPanel.ALIGN_CENTER); super.hide(); setWidget(vPanel); } /** * Execute the confirmed action */ private void execute() { switch (action) { case CONFIRM_EXPORT_DOCUMENT : case CONFIRM_EXPORT_FOLDER : Dropbox.get().folderSelectPopup.show(); break; } action = NO_ACTION; // Resets action value } /** * Sets the action to be confirmed * * @param action The action to be confirmed */ public void setConfirm(int action) { this.action = action; switch (action) { case CONFIRM_EXPORT_DOCUMENT : text.setHTML(GeneralComunicator.i18nExtension("dropbox.confirm.export.document")); break; case CONFIRM_EXPORT_FOLDER : text.setHTML(GeneralComunicator.i18nExtension("dropbox.confirm.export.folder")); break; } } /** * Language refresh */ public void langRefresh() { setText(GeneralComunicator.i18n("confirm.label")); cancelButton.setText(GeneralComunicator.i18n("button.cancel")); acceptButton.setText(GeneralComunicator.i18n("button.accept")); } /** * Shows de popup */ public void show(){ setText(GeneralComunicator.i18n("confirm.label")); int left = (Window.getClientWidth()-300)/2; int top = (Window.getClientHeight()-125)/2; setPopupPosition(left,top); super.show(); } }
gpl-3.0
TEDICpy/wp-tedic-theme
inc/template-tags.php
4603
<?php /** * Custom template tags for this theme. * * Eventually, some of the functionality here could be replaced by core features. * * @package zerif */ if ( ! function_exists( 'zerif_paging_nav' ) ) : /** * Display navigation to next/previous set of posts when applicable. */ function zerif_paging_nav() { echo '<div class="clear"></div>'; ?> <nav class="navigation paging-navigation" role="navigation"> <h1 class="screen-reader-text"><?php _e( 'Posts navigation', 'zerif-lite' ); ?></h1> <div class="nav-links"> <?php if ( get_next_posts_link() ) : ?> <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Entradas antiguas', 'zerif-lite' ) ); ?></div> <?php endif; ?> <?php if ( get_previous_posts_link() ) : ?> <div class="nav-next"><?php previous_posts_link( __( 'Entradas nuevas <span class="meta-nav">&rarr;</span>', 'zerif-lite' ) ); ?></div> <?php endif; ?> </div><!-- .nav-links --> </nav><!-- .navigation --> <?php } endif; if ( ! function_exists( 'zerif_post_nav' ) ) : /** * Display navigation to next/previous post when applicable. */ function zerif_post_nav() { // Don't print empty markup if there's nowhere to navigate. $previous = ( is_attachment() ) ? get_post( get_post()->post_parent ) : get_adjacent_post( false, '', true ); $next = get_adjacent_post( false, '', false ); if ( ! $next && ! $previous ) { return; } ?> <nav class="navigation post-navigation" role="navigation"> <h1 class="screen-reader-text"><?php _e( 'Post navigation', 'zerif-lite' ); ?></h1> <div class="nav-links"> <?php previous_post_link( '<div class="nav-previous">%link</div>', _x( '<span class="meta-nav">&larr;</span> %title', 'Previous post link', 'zerif-lite' ) ); next_post_link( '<div class="nav-next">%link</div>', _x( '%title <span class="meta-nav">&rarr;</span>', 'Next post link', 'zerif-lite' ) ); ?> </div><!-- .nav-links --> </nav><!-- .navigation --> <?php } endif; if ( ! function_exists( 'zerif_posted_on' ) ) : /** * Prints HTML with meta information for the current post-date/time and author. */ function zerif_posted_on() { $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>'; if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) { $time_string .= '<time class="updated" datetime="%3$s">%4$s</time>'; } $time_string = sprintf( $time_string, esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ), esc_attr( get_the_modified_date( 'c' ) ), esc_html( get_the_modified_date() ) ); printf( __( '<span class="posted-on">Publicado el %1$s</span><span class="byline"> por %2$s</span>', 'zerif-lite' ), sprintf( '<a href="%1$s" rel="bookmark">%2$s</a>', esc_url( get_permalink() ), $time_string ), sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s">%2$s</a></span>', esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ), esc_html( get_the_author() ) ) ); } endif; /** * Returns true if a blog has more than 1 category. * * @return bool */ function zerif_categorized_blog() { if ( false === ( $all_the_cool_cats = get_transient( 'zerif_categories' ) ) ) { // Create an array of all the categories that are attached to posts. $all_the_cool_cats = get_categories( array( 'fields' => 'ids', 'hide_empty' => 1, // We only need to know if there is more than one category. 'number' => 2, ) ); // Count the number of categories that are attached to the posts. $all_the_cool_cats = count( $all_the_cool_cats ); set_transient( 'zerif_categories', $all_the_cool_cats ); } if ( $all_the_cool_cats > 1 ) { // This blog has more than 1 category so zerif_categorized_blog should return true. return true; } else { // This blog has only 1 category so zerif_categorized_blog should return false. return false; } } /** * Flush out the transients used in zerif_categorized_blog. */ function zerif_category_transient_flusher() { // Like, beat it. Dig? delete_transient( 'zerif_categories' ); } add_action( 'edit_category', 'zerif_category_transient_flusher' ); add_action( 'save_post', 'zerif_category_transient_flusher' );
gpl-3.0
matthenning/ciliatus
app/Http/Controllers/Web/SetupController.php
1381
<?php namespace App\Http\Controllers\Web; use App\Http\Controllers\Controller; use App\Property; use Illuminate\Http\Request; /** * Class SetupController * @package App\Http\Controllers\Web */ class SetupController extends Controller { /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function start() { $setup_complete_property = Property::where('type', 'SetupCompleted')->get()->first(); if (!is_null($setup_complete_property)) { return view ('setup.err_completed'); } return view('setup.start'); } /** * @param Request $request * @param $id * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function step(Request $request, $id) { $this->setLocale(); switch ($id) { case 1: return view('setup.step_1'); case 2: return view('setup.step_2'); default: return view('setup.start'); } } /** * */ private function setLocale() { $p = Property::where('type', 'SetupConfiguration')->where('name', 'language')->get()->first(); if (is_null($p)) { app()->setLocale('en'); } else { app()->setLocale($p->value); } } }
gpl-3.0
pH-7/Slim-URL-Shortener
constants.php
540
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2013, Pierre-Henry Soria. All Rights Reserved. * @link http://github.com/pH-7/Slim-URL-Shortener * @license GNU General Public License <http://www.gnu.org/licenses/gpl.html> */ namespace PHS; defined('PHS') or die('Forbidden acces'); define('ROOT_PATH', __DIR__ . '/'); define('VENDOR_PATH', ROOT_PATH . 'Vendor/'); define('LANG_PATH', ROOT_PATH . 'i18n/locale'); define('TPL_CACHE', ROOT_PATH . 'cache/twig/');
gpl-3.0
shree-shubham/Unitype
Sets-STL.cpp
685
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <set> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ set <int> s; int N = 0; cin >> N; for (int i = 0; i < N; i++) { int q = 0, x = 0; cin >> q; cin >> x; if (q == 1) s.insert(x); else if (q == 2) s.erase(x); else { set<int>::iterator itr=s.find(x); if (itr == s.end()) cout<<"No"<<endl; else cout<<"Yes"<<endl; } } return 0; }
gpl-3.0
cschwan/hep-ps
src/initial_state.cpp
1684
#include "hep/ps/initial_state.hpp" #include <map> #include <stdexcept> #include <utility> namespace hep { parton_set partons_in_initial_state_set(initial_state_set set) { parton_set result; for (auto const state : set) { result.add(state_parton_one(state)); result.add(state_parton_two(state)); } return result; } initial_state partons_to_initial_state(parton one, parton two) { static std::map<std::pair<parton, parton>, initial_state> map; static bool initialized = false; if (!initialized) { for (auto state : initial_state_list()) { map.emplace(std::make_pair(state_parton_one(state), state_parton_two(state)), state); } initialized = true; } auto const result = map.find({ one, two }); if (result == map.end()) { throw std::invalid_argument("no initial state found for given partons"); } return result->second; } template <typename T> T casimir_operator(initial_state state, std::size_t index) { if (index == 0) { switch (state_parton_one(state)) { case parton::photon: return T(); case parton::gluon: return T(3.0); default: return T(4.0) / T(3.0); } } else if (index == 1) { switch (state_parton_two(state)) { case parton::photon: return T(); case parton::gluon: return T(3.0); default: return T(4.0) / T(3.0); } } assert( false ); } // -------------------- EXPLICIT TEMPLATE INSTANTIATIONS -------------------- template double casimir_operator(initial_state, std::size_t); }
gpl-3.0
Sectan/GolangFundamentals
12_functions/11_self-executing/main.go
388
// A function literal can invoked directly. // Golang Spec: https://golang.org/ref/spec#Function_literals // Interesting stackoverflow post: https://stackoverflow.com/questions/16008604/why-add-after-closure-body-in-golang package main import "fmt" func main() { defer func() { fmt.Println("Anonymous function with defer") }() func() { fmt.Println("Anonymous function") }() }
gpl-3.0
erickok/ratebeer
app/src/main/java/com/ratebeer/android/ShareHelper.java
2228
package com.ratebeer.android; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.net.Uri; import com.ratebeer.android.api.Api; import java.util.ArrayList; import java.util.List; import java.util.Locale; public final class ShareHelper { private static final String URL_BEER = Api.DOMAIN + "/b/%1$d/"; private static final String URL_BREWERY = Api.DOMAIN + "/brewers/b/%1$d/"; private static final String URL_PLACE = Api.DOMAIN + "/p/p/%1$d/"; private final Context context; public ShareHelper(Context context) {this.context = context;} public void shareBeer(long id, String name) { shareLink(name, String.format(Locale.US, URL_BEER, id)); } public void shareBrewery(long id, String name) { shareLink(name, String.format(Locale.US, URL_BREWERY, id)); } public void sharePlace(long id, String name) { shareLink(name, String.format(Locale.US, URL_PLACE, id)); } private void shareLink(String name, String url) { Intent openIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); List<Intent> browserIntents = new ArrayList<>(); for (ResolveInfo openInfo : context.getPackageManager().queryIntentActivities(openIntent, 0)) { if (!openInfo.activityInfo.packageName.equals(BuildConfig.APPLICATION_ID)) { Intent browserIntent = new Intent(); browserIntent.setComponent(new ComponentName(openInfo.activityInfo.packageName, openInfo.activityInfo.name)); browserIntent.setAction(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse(url)); browserIntents.add(browserIntent); } } String shareText = context.getString(R.string.app_sharetext, name, url); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, shareText); Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, shareIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, context.getString(R.string.app_openorshare)); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, browserIntents.toArray(new Intent[browserIntents.size()])); context.startActivity(chooserIntent); } }
gpl-3.0
HParker/tin
spec/app_spec.rb
617
# frozen_string_literal: true require_relative 'spec_helper' include Mote::Helpers scope do test 'home' do get '/' assert_equal 200, last_response.status end test 'help' do get '/?q=help' assert_equal 200, last_response.status assert_equal JSON.parse(last_response.body), 'title' => 'Help help', 'body' => mote('./plugins/help/help.mote', {}), 'refresh_rate' => 0, 'refresh_url' => '' end test 'comp' do get '/comp?pack=default' assert_equal 200, last_response.status assert_equal JSON.parse(last_response.body)[0].keys, %w(command info) end end
gpl-3.0
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/database/SenderKeySharedDatabase.java
6000
package org.thoughtcrime.securesms.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import androidx.annotation.NonNull; import org.signal.core.util.logging.Log; import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper; import org.thoughtcrime.securesms.recipients.Recipient; import org.whispersystems.libsignal.SignalProtocolAddress; import org.whispersystems.signalservice.api.push.DistributionId; import org.thoughtcrime.securesms.recipients.RecipientId; import org.thoughtcrime.securesms.util.CursorUtil; import org.thoughtcrime.securesms.util.SqlUtil; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Keeps track of which recipients are aware of which distributionIds. For the storage of sender * keys themselves, see {@link SenderKeyDatabase}. */ public class SenderKeySharedDatabase extends Database { private static final String TAG = Log.tag(SenderKeySharedDatabase.class); public static final String TABLE_NAME = "sender_key_shared"; private static final String ID = "_id"; public static final String DISTRIBUTION_ID = "distribution_id"; public static final String ADDRESS = "address"; public static final String DEVICE = "device"; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + DISTRIBUTION_ID + " TEXT NOT NULL, " + ADDRESS + " TEXT NOT NULL, " + DEVICE + " INTEGER NOT NULL, " + "UNIQUE(" + DISTRIBUTION_ID + "," + ADDRESS + ", " + DEVICE + ") ON CONFLICT REPLACE);"; SenderKeySharedDatabase(Context context, SQLCipherOpenHelper databaseHelper) { super(context, databaseHelper); } /** * Mark that a distributionId has been shared with the provided recipients */ public void markAsShared(@NonNull DistributionId distributionId, @NonNull Collection<SignalProtocolAddress> addresses) { SQLiteDatabase db = databaseHelper.getSignalWritableDatabase(); db.beginTransaction(); try { for (SignalProtocolAddress address : addresses) { ContentValues values = new ContentValues(); values.put(ADDRESS, address.getName()); values.put(DEVICE, address.getDeviceId()); values.put(DISTRIBUTION_ID, distributionId.toString()); db.insertWithOnConflict(TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } /** * Get the set of recipientIds that know about the distributionId in question. */ public @NonNull Set<SignalProtocolAddress> getSharedWith(@NonNull DistributionId distributionId) { SQLiteDatabase db = databaseHelper.getSignalReadableDatabase(); String query = DISTRIBUTION_ID + " = ?"; String[] args = SqlUtil.buildArgs(distributionId); Set<SignalProtocolAddress> addresses = new HashSet<>(); try (Cursor cursor = db.query(TABLE_NAME, new String[]{ ADDRESS, DEVICE }, query, args, null, null, null)) { while (cursor.moveToNext()) { String address = CursorUtil.requireString(cursor, ADDRESS); int device = CursorUtil.requireInt(cursor, DEVICE); addresses.add(new SignalProtocolAddress(address, device)); } } return addresses; } /** * Clear the shared statuses for all provided addresses. */ public void delete(@NonNull DistributionId distributionId, @NonNull Collection<SignalProtocolAddress> addresses) { SQLiteDatabase db = databaseHelper.getSignalWritableDatabase(); String query = DISTRIBUTION_ID + " = ? AND " + ADDRESS + " = ? AND " + DEVICE + " = ?"; db.beginTransaction(); try { for (SignalProtocolAddress address : addresses) { db.delete(TABLE_NAME, query, SqlUtil.buildArgs(distributionId, address.getName(), address.getDeviceId())); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } /** * Clear all shared statuses for a given distributionId. */ public void deleteAllFor(@NonNull DistributionId distributionId) { SQLiteDatabase db = databaseHelper.getSignalWritableDatabase(); db.delete(TABLE_NAME, DISTRIBUTION_ID + " = ?", SqlUtil.buildArgs(distributionId)); } /** * Clear the shared status for all distributionIds for a set of addresses. */ public void deleteAllFor(@NonNull Collection<SignalProtocolAddress> addresses) { SQLiteDatabase db = databaseHelper.getSignalWritableDatabase(); String query = ADDRESS + " = ? AND " + DEVICE + " = ?"; db.beginTransaction(); try { for (SignalProtocolAddress address : addresses) { db.delete(TABLE_NAME, query, SqlUtil.buildArgs(address.getName(), address.getDeviceId())); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } /** * Clear the shared status for all distributionIds for a given recipientId. */ public void deleteAllFor(@NonNull RecipientId recipientId) { SQLiteDatabase db = databaseHelper.getSignalWritableDatabase(); Recipient recipient = Recipient.resolved(recipientId); if (recipient.hasUuid()) { db.delete(TABLE_NAME, ADDRESS + " = ?", SqlUtil.buildArgs(recipient.getUuid().get().toString())); } else { Log.w(TAG, "Recipient doesn't have a UUID! " + recipientId); } } /** * Clears all database content. */ public void deleteAll() { SQLiteDatabase db = databaseHelper.getSignalWritableDatabase(); db.delete(TABLE_NAME, null, null); } }
gpl-3.0
forgodsake/TowerPlus
Android/src/com/fuav/android/utils/AndroidApWarningParser.java
9130
package com.fuav.android.utils; import com.o3dr.services.android.lib.drone.attribute.error.ErrorType; import com.fuav.android.core.model.AutopilotWarningParser; import com.fuav.android.core.drone.autopilot.MavLinkDrone; import java.util.Locale; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ALTITUDE_DISPARITY; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ARM_COMPASS_CALIBRATION_RUNNING; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ARM_GYRO_CALIBRATION_FAILED; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ARM_LEANING; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ARM_MODE_NOT_ARMABLE; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ARM_ROTOR_NOT_SPINNING; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ARM_SAFETY_SWITCH; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ARM_THROTTLE_BELOW_FAILSAFE; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.ARM_THROTTLE_TOO_HIGH; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.AUTO_TUNE_FAILED; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.CRASH_DISARMING; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.EKF_VARIANCE; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.LOW_BATTERY; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.NO_DATAFLASH_INSERTED; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.NO_ERROR; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PARACHUTE_TOO_LOW; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_ACCELEROMETERS_NOT_HEALTHY; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_ACRO_BAL_ROLL_PITCH; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_BAROMETER_NOT_HEALTHY; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_CHECK_ANGLE_MAX; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_CHECK_BOARD_VOLTAGE; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_CHECK_FAILSAFE_THRESHOLD_VALUE; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_CHECK_FENCE; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_CHECK_MAGNETIC_FIELD; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_COMPASS_NOT_CALIBRATED; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_COMPASS_NOT_HEALTHY; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_COMPASS_OFFSETS_TOO_HIGH; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_DUPLICATE_AUX_SWITCH_OPTIONS; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_EKF_HOME_VARIANCE; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_GPS_GLITCH; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_GYROS_NOT_HEALTHY; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_HIGH_GPS_HDOP; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_INCONSISTENT_ACCELEROMETERS; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_INCONSISTENT_COMPASSES; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_INCONSISTENT_GYROS; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_INS_NOT_CALIBRATED; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_NEED_GPS_LOCK; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.PRE_ARM_RC_NOT_CALIBRATED; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.RC_FAILSAFE; import static com.o3dr.services.android.lib.drone.attribute.error.ErrorType.WAITING_FOR_NAVIGATION_ALIGNMENT; /** * Autopilot error parser. * Created by fhuya on 12/16/14. */ public class AndroidApWarningParser implements AutopilotWarningParser { @Override public String getDefaultWarning() { return NO_ERROR.name(); } /** * Maps the ArduPilot warnings set to the 3DR Services warnings set. * * @param warning warning originating from the ArduPilot autopilot * @return equivalent 3DR Services warning type */ @Override public String parseWarning(MavLinkDrone drone, String warning) { if (android.text.TextUtils.isEmpty(warning)) return null; ErrorType errorType = getErrorType(warning); if(errorType == null) return null; return errorType.name(); } private ErrorType getErrorType(String warning){ switch (warning.toLowerCase(Locale.US)) { case "arm: thr below fs": case "arm: throttle below failsafe": return ARM_THROTTLE_BELOW_FAILSAFE; case "arm: gyro calibration failed": return ARM_GYRO_CALIBRATION_FAILED; case "arm: mode not armable": return ARM_MODE_NOT_ARMABLE; case "arm: rotor not spinning": return ARM_ROTOR_NOT_SPINNING; case "arm: altitude disparity": case "prearm: altitude disparity": return ALTITUDE_DISPARITY; case "arm: leaning": return ARM_LEANING; case "arm: throttle too high": return ARM_THROTTLE_TOO_HIGH; case "arm: safety switch": return ARM_SAFETY_SWITCH; case "arm: compass calibration running": return ARM_COMPASS_CALIBRATION_RUNNING; case "prearm: rc not calibrated": return PRE_ARM_RC_NOT_CALIBRATED; case "prearm: barometer not healthy": return PRE_ARM_BAROMETER_NOT_HEALTHY; case "prearm: compass not healthy": return PRE_ARM_COMPASS_NOT_HEALTHY; case "prearm: compass not calibrated": return PRE_ARM_COMPASS_NOT_CALIBRATED; case "prearm: compass offsets too high": return PRE_ARM_COMPASS_OFFSETS_TOO_HIGH; case "prearm: check mag field": return PRE_ARM_CHECK_MAGNETIC_FIELD; case "prearm: inconsistent compasses": return PRE_ARM_INCONSISTENT_COMPASSES; case "prearm: check fence": return PRE_ARM_CHECK_FENCE; case "prearm: ins not calibrated": return PRE_ARM_INS_NOT_CALIBRATED; case "prearm: accelerometers not healthy": return PRE_ARM_ACCELEROMETERS_NOT_HEALTHY; case "prearm: inconsistent accelerometers": return PRE_ARM_INCONSISTENT_ACCELEROMETERS; case "prearm: gyros not healthy": return PRE_ARM_GYROS_NOT_HEALTHY; case "prearm: inconsistent gyros": return PRE_ARM_INCONSISTENT_GYROS; case "prearm: check board voltage": return PRE_ARM_CHECK_BOARD_VOLTAGE; case "prearm: duplicate aux switch options": return PRE_ARM_DUPLICATE_AUX_SWITCH_OPTIONS; case "prearm: check fs_thr_value": return PRE_ARM_CHECK_FAILSAFE_THRESHOLD_VALUE; case "prearm: check angle_max": return PRE_ARM_CHECK_ANGLE_MAX; case "prearm: acro_bal_roll/pitch": return PRE_ARM_ACRO_BAL_ROLL_PITCH; case "prearm: need 3d fix": return PRE_ARM_NEED_GPS_LOCK; case "prearm: ekf-home variance": return PRE_ARM_EKF_HOME_VARIANCE; case "prearm: high gps hdop": return PRE_ARM_HIGH_GPS_HDOP; case "prearm: gps glitch": case "prearm: bad velocity": return PRE_ARM_GPS_GLITCH; case "prearm: waiting for navigation alignment": case "arm: waiting for navigation alignment": return WAITING_FOR_NAVIGATION_ALIGNMENT; case "no dataflash inserted": return NO_DATAFLASH_INSERTED; case "low battery!": return LOW_BATTERY; case "autotune: failed": return AUTO_TUNE_FAILED; case "crash: disarming": return CRASH_DISARMING; case "parachute: too low": return PARACHUTE_TOO_LOW; case "ekf variance": return EKF_VARIANCE; case "rc failsafe": return RC_FAILSAFE; default: return null; } } }
gpl-3.0
deos/PermaTabs-Mod
chrome/permatabs/content/prefsWindow.js
3011
function PrefsWindow() { this.onLoad = function() { this.transparency('permaTabsPrefColor'); this.transparency('permaTabsPrefLabelColor'); this.disablefields(); }; this.onSave = function() { var wm = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator); var en = wm.getEnumerator(""); while(en.hasMoreElements()) { var w = en.getNext(); if(w.permaTabs && w.permaTabs.initialized) { w.permaTabs.colorPermaTabs(); w.permaTabs.setToolbarButtonType(); } } }; this.disablefields = function() { var pref = { "Distinguish" : "permaTabsPrefDistinguish", "LabelSet" : "permaTabsPrefLabelSet", "ToggleKey" : "permaTabsPrefToggleKeyActive", "HomeKey" : "permaTabsPrefHomeKeyActive", "SetHomeKey" : "permaTabsPrefSetHomeKeyActive" }; for(i in pref) { var opt = document.getElementById(pref[i]); pref[i] = (opt.hasAttribute('checked') && opt.getAttribute('checked')=='true'); } document.getElementById('permaTabsPrefColor').setAttribute('disabled', !pref['Distinguish']); document.getElementById('permaTabsPrefColorTransparent').setAttribute('disabled', !pref['Distinguish']); document.getElementById('permaTabsPrefLabelColor').setAttribute('disabled', !pref['LabelSet']); document.getElementById('permaTabsPrefLabelColorTransparent').setAttribute('disabled', !pref['LabelSet']); document.getElementById('permaTabsPrefToggleKeyModificator').setAttribute('disabled', !pref['ToggleKey']); document.getElementById('PermaTabsPrefToggleKey').setAttribute('disabled', !pref['ToggleKey']); document.getElementById('permaTabsPrefHomeKeyModificator').setAttribute('disabled', !pref['HomeKey']); document.getElementById('PermaTabsPrefHomeKey').setAttribute('disabled', !pref['HomeKey']); document.getElementById('permaTabsPrefSetHomeKeyModificator').setAttribute('disabled', !pref['SetHomeKey']); document.getElementById('PermaTabsPrefSetHomeKey').setAttribute('disabled', !pref['SetHomeKey']); }; this.transparency = function(id, toggle) { var colorpicker = document.getElementById(id); var button = document.getElementById(id+'Transparent'); if(toggle) { document.getElementById(colorpicker.getAttribute("preference"))._setValue('transparent'); colorpicker.color = 'transparent'; if(document.getElementById(colorpicker.getAttribute("preference")).instantApply) { //linux/mac!! what now? } } button.setAttribute('checked', (colorpicker.getAttribute('color')=="transparent")); }; this.closeAllPermaTabs = function() { var wm = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator); var en = wm.getEnumerator(""); while(en.hasMoreElements()) { var w = en.getNext(); if(w.permaTabs && w.permaTabs.initialized) { w.permaTabs.closeAllPermaTabs(false, window); } } } } this.prefsWindow = new PrefsWindow;
gpl-3.0
tfg13/LanXchange
modules/android/src/main/java/de/tobifleig/lxc/plaf/android/activity/MainActivity.java
33985
/* * Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.android.activity; import java.io.*; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.os.Environment; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.content.ClipData; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.view.*; import android.widget.TextView; import de.tobifleig.lxc.R; import de.tobifleig.lxc.data.LXCFile; import de.tobifleig.lxc.data.VirtualFile; import de.tobifleig.lxc.data.impl.InMemoryFile; import de.tobifleig.lxc.data.impl.RealFile; import de.tobifleig.lxc.log.LXCLogBackend; import de.tobifleig.lxc.log.LXCLogger; import de.tobifleig.lxc.plaf.GuiInterface; import de.tobifleig.lxc.plaf.android.AndroidGuiListener; import de.tobifleig.lxc.plaf.android.ConnectivityChangeListener; import de.tobifleig.lxc.plaf.android.ConnectivityChangeReceiver; import de.tobifleig.lxc.plaf.android.GuiInterfaceBridge; import de.tobifleig.lxc.plaf.android.NonFileContent; import de.tobifleig.lxc.plaf.android.PermissionTools; import de.tobifleig.lxc.plaf.android.service.AndroidSingleton; import de.tobifleig.lxc.plaf.android.ui.FileListView; import net.rdrei.android.dirchooser.DirectoryChooserConfig; import net.rdrei.android.dirchooser.DirectoryChooserFragment; /** * Platform for Android / Default Activity * * no automated updates (managed by Google Play) * * @author Tobias Fleig <tobifleig googlemail com> */ public class MainActivity extends AppCompatActivity implements CancelablePermissionPromptActivity { /** * Intent from service, requests LanXchange termination * This activity may be paused/stopped when the intent is received, so this cannot show a dialog if transfers * are running. */ public static final String ACTION_STOP_FROMSERVICE = "de.tobifleig.lxc.plaf.android.activity.ACTION_STOP_FROMSERVICE"; /** * Intent fired by this activity. Upon reception, the activity is visible, so dialogs can be used. */ public static final String ACTION_STOP_FROMACTIVITY = "de.tobifleig.lxc.plaf.android.activity.ACTION_STOP_FROMACTIVITY"; /** * Intent from notification created by service, requests display of LanXchange core error message. */ public static final String ACTION_SHOW_ERROR = "de.tobifleig.lxc.plaf.android.activity.ACTION_SHOW_ERROR"; private static final int RETURNCODE_FILEINTENT = 42; public static final int RETURNCODE_PERMISSION_PROMPT_STORAGE = 43; private LXCLogger logger; private AndroidGuiListener guiListener; private GuiInterfaceBridge guiBridge; /** * Holds the quickshare-List until the user answered the storage permission prompt. */ private List<VirtualFile> permissionPromptQuickshare; /** * Holds the requested file to download until the user answered the storage permission prompt. */ private LXCFile permissionPromptDownloadFile; /** * True, if the user tried to share a file when the storate permission prompt fired. */ private boolean permissionPromptShareFile; /** * Handles network state changes (wifi coming online) */ private ConnectivityChangeReceiver networkStateChangeReceiver; /** * The view that displays all shared and available files */ private FileListView fileListView; /** * Marker to detect when we return from settings. */ private boolean launchedSettings = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); logger = LXCLogBackend.getLogger("main-activity"); // Check intent first List<VirtualFile> quickShare = null; Intent launchIntent = getIntent(); if (launchIntent.getAction() != null && (launchIntent.getAction().equals(Intent.ACTION_SEND) || launchIntent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) { quickShare = computeInputIntent(launchIntent); if (quickShare == null) { // unable to access file, inform user handleShareError(launchIntent); } // disarm intent to prevent sharing the same file twice on screen rotate launchIntent.setAction(null); } else if (launchIntent.getAction() != null && launchIntent.getAction().equals(ACTION_SHOW_ERROR)) { showErrorDialog(this, launchIntent.getCharSequenceExtra(Intent.EXTRA_TEXT)); } // load layout setContentView(R.layout.main); // layout is loaded, setup main view fileListView = (FileListView) findViewById(R.id.fileList); // set up action bar logo if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayUseLogoEnabled(true); getSupportActionBar().setLogo(R.drawable.ic_branding_white); } // set up the text displayed when there are no files TextView emptyText = (TextView) ((LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.empty_list, null); fileListView.setEmptyView(emptyText); ViewGroup root = (ViewGroup) findViewById(R.id.main_layout); CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.WRAP_CONTENT, CoordinatorLayout.LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.CENTER; root.addView(emptyText, layoutParams); ConnectivityChangeReceiver.setConnectivityListener(new ConnectivityChangeListener() { @Override public void setWifiState(boolean isWifi) { setWifiWarning(!isWifi); } }); networkStateChangeReceiver = new ConnectivityChangeReceiver(); guiBridge = new GuiInterfaceBridge() { @Override public void update() { fileListView.updateGui(); } @Override public void notifyFileChange(int fileOrigin, int operation, int firstIndex, int numberOfFiles, List<LXCFile> affectedFiles) { if (fileOrigin == GuiInterface.UPDATE_ORIGIN_LOCAL) { // local implies: only 1 file at a time if (operation == GuiInterface.UPDATE_OPERATION_ADD) { fileListView.notifyLocalFileAdded(); } else if (operation == GuiInterface.UPDATE_OPERATION_REMOVE) { fileListView.notifyLocalFileRemoved(firstIndex); } } else if (fileOrigin == GuiInterface.UPDATE_ORIGIN_REMOTE) { if (operation == GuiInterface.UPDATE_OPERATION_ADD) { fileListView.notifyRemoteFilesAdded(numberOfFiles); } else if (operation == GuiInterface.UPDATE_OPERATION_REMOVE) { fileListView.notifyRemoteFilesRemoved(firstIndex, numberOfFiles); } } } @Override public void notifyJobChange(int operation, LXCFile file, int index) { if (operation == GuiInterface.UPDATE_OPERATION_ADD) { fileListView.notifyLocalJobAdded(file, index); } else if (operation == GuiInterface.UPDATE_OPERATION_REMOVE) { fileListView.notifyLocalJobRemoved(file, index); } } @Override public boolean confirmCloseWithTransfersRunning() { AlertDialog.Builder builder = new AlertDialog.Builder(findViewById(R.id.main_layout).getContext()); builder.setMessage(R.string.dialog_closewithrunning_text); builder.setTitle(R.string.dialog_closewithrunning_title); builder.setPositiveButton(R.string.dialog_closewithrunning_yes, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { guiListener.shutdown(true, true, false); AndroidSingleton.onRealDestroy(); finish(); } }); builder.setNegativeButton(R.string.dialog_closewithrunning_no, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do nothing } }); AlertDialog dialog = builder.create(); dialog.show(); // always return false // if the user decides to kill lanxchange anyway, shutdown is called again return false; } @Override public void showError(Context context, String error) { View main = findViewById(R.id.main_layout); main.post(new Runnable() { @Override public void run() { showErrorDialog(main.getContext(), error); } }); } }; // setup floating action button findViewById(R.id.fab_add).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { permissionPromptShareFile = true; if (PermissionTools.verifyStoragePermission(MainActivity.this, MainActivity.this)) { permissionPromptShareFile = false; shareFile(); } } }); AndroidSingleton.onCreateMainActivity(this, guiBridge, quickShare); // now handle normal intents (ACTION_SEND* has been disarmed by deleting the action) if (launchIntent.getAction() != null) { onNewIntent(launchIntent); } } private void showErrorDialog(Context context, CharSequence error) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.error_generic_from_core_title); builder.setMessage(error); builder.setCancelable(false); builder.setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.show(); } private void shareFile() { Intent chooseFile = new Intent(); chooseFile.setAction(Intent.ACTION_GET_CONTENT); chooseFile.addCategory(Intent.CATEGORY_OPENABLE); if (android.os.Build.VERSION.SDK_INT >= 18) { chooseFile.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } chooseFile.setType("*/*"); startActivityForResult(chooseFile, RETURNCODE_FILEINTENT); } @Override public void onStart() { super.onStart(); // Re-Check that Service is running. In some rare cases, this may not be the case. AndroidSingleton.onCreateMainActivity(this, guiBridge, null); AndroidSingleton.onMainActivityVisible(0); } @Override public void onStop() { super.onStop(); // notify service about the gui becoming invisible. // service will stop itself after a while to preserve resources AndroidSingleton.onMainActivityHidden(0); } @Override protected void onPause() { super.onPause(); getBaseContext().unregisterReceiver(networkStateChangeReceiver); } @Override protected void onResume() { super.onResume(); // set up connectivity listener and trigger once to get the current status getBaseContext().registerReceiver(networkStateChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); networkStateChangeReceiver.onReceive(getBaseContext(), null); // returning from settings? if (launchedSettings) { launchedSettings = false; guiListener.reloadConfiguration(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.lxc_layout, menu); return true; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.quit: if (guiListener.shutdown(false, true, false)) { AndroidSingleton.onRealDestroy(); finish(); } return true; case R.id.settings: // display settings Intent showSettings = new Intent(); showSettings.setClass(getBaseContext(), SettingsActivity.class); launchedSettings = true; startActivity(showSettings); return true; case R.id.help: // display help Intent showHelp = new Intent(); showHelp.setClass(getBaseContext(), HelpActivity.class); startActivity(showHelp); return true; case R.id.about: // display about Intent showAbout = new Intent(); showAbout.setClass(getBaseContext(), AboutActivity.class); startActivity(showAbout); return true; case R.id.pcversion: // display info about pc version Intent showPCVersion = new Intent(); showPCVersion.setClass(getBaseContext(), PCVersionActivity.class); startActivity(showPCVersion); return true; default: return super.onOptionsItemSelected(item); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data == null) { // User pressed "back"/"cancel" etc return; } ArrayList<VirtualFile> files = new ArrayList<VirtualFile>(); // multiple files if (android.os.Build.VERSION.SDK_INT >= 18 && data.getClipData() != null) { List<VirtualFile> virtualFiles = virtualFilesFromClipData(data.getClipData()); if (virtualFiles != null && !virtualFiles.isEmpty()) { files.addAll(virtualFiles); } else { handleShareError(data); } } else if (data.getData() != null) { VirtualFile virtualFile = uriToVirtualFile(data.getData()); if (virtualFile != null) { files.add(virtualFile); } else { handleShareError(data); } } if (!files.isEmpty()) { offerFiles(files); } } @Override protected void onNewIntent(Intent intent) { if (intent.getAction() == null) { return; } switch (intent.getAction()) { case Intent.ACTION_MAIN: return; case ACTION_STOP_FROMSERVICE: // try shutdown, but do not ask for transfers yet (the dialog will never show because this activity may // currently be invisible if (guiListener.shutdown(false, false, false)) { // no transfers running, shutdown went through AndroidSingleton.onRealDestroy(); finish(); } else { // transfers running, need to prompt user // for this, the activity has to be visible - this means this method must return // re-fire intent Intent quitIntent = new Intent(this, MainActivity.class); quitIntent.setAction(MainActivity.ACTION_STOP_FROMACTIVITY); startActivity(quitIntent); } break; case ACTION_STOP_FROMACTIVITY: if (guiListener.shutdown(false, true, false)) { // no transfers running, shutdown went through AndroidSingleton.onRealDestroy(); finish(); } break; case Intent.ACTION_SEND: case Intent.ACTION_SEND_MULTIPLE: // share List<VirtualFile> files = computeInputIntent(intent); if (files != null && !files.isEmpty()) { if (guiListener == null) { // service not ready yet, cache AndroidSingleton.onEarlyShareIntent(files); } else { permissionPromptQuickshare = files; if (PermissionTools.verifyStoragePermission(this, this)) { offerFiles(files); permissionPromptQuickshare = null; }// otherwise prompt is going up, flow continues in callback } } else { handleShareError(intent); } break; case ACTION_SHOW_ERROR: showErrorDialog(this, intent.getCharSequenceExtra(Intent.EXTRA_TEXT)); break; default: logger.warn("Received unknown intent! " + intent.getAction()); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == RETURNCODE_PERMISSION_PROMPT_STORAGE) { if (grantResults.length == 0) { // cancelled, try again PermissionTools.verifyStoragePermission(this, this); return; } if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // continue what the user tried to do when the permission dialog fired Thread t = new Thread(new Runnable() { @Override public void run() { if (permissionPromptQuickshare != null) { offerFiles(permissionPromptQuickshare); permissionPromptQuickshare = null; } else if (permissionPromptDownloadFile != null) { guiListener.downloadFile(permissionPromptDownloadFile, false); permissionPromptDownloadFile = null; } else if (permissionPromptShareFile) { shareFile(); permissionPromptShareFile = false; } } }); t.setName("lxc_helper_useraction"); t.setDaemon(true); t.start(); } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) { cancelPermissionPromptAction(); } } } /** * Cancels the action that resulted in a permission prompt going up */ public void cancelPermissionPromptAction() { // cancel action and tell user if (permissionPromptDownloadFile != null) { permissionPromptDownloadFile.setLocked(false); fileListView.updateGui(); } permissionPromptDownloadFile = null; permissionPromptQuickshare = null; permissionPromptShareFile = false; Snackbar.make(findViewById(android.R.id.content), R.string.snackbar_action_cancelled_permission_storage_missing, Snackbar.LENGTH_LONG).show(); } /** * Called when importing content to share failed. * Logs the Intent for debug purposes and displays a Toast. * */ private void handleShareError(final Intent failedIntent) { logger.error("Sharing failed. Intent details:"); logger.error("Intent object: " + failedIntent); logger.error("Intent action: " + failedIntent.getAction()); logger.error("Intent dataString: " + failedIntent.getDataString()); logger.error("Intent data: " + failedIntent.getData()); logger.error("Intent type: " + failedIntent.getType()); logger.error("Intent scheme: " + failedIntent.getScheme()); logger.error("Intent package: " + failedIntent.getPackage()); logger.error("Intent extras: " + failedIntent.getExtras()); logger.error("Intent clipData: " + failedIntent.getClipData()); AlertDialog.Builder builder = new AlertDialog.Builder(findViewById(R.id.main_layout).getContext()); builder.setTitle(R.string.error_cantoffer_title); builder.setMessage(R.string.error_cantoffer_text); builder.setPositiveButton(R.string.error_cantoffer_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do nothing } }); builder.setNeutralButton(R.string.error_cantoffer_mail, new DialogInterface.OnClickListener() { @SuppressLint("NewApi") @Override public void onClick(DialogInterface dialog, int which) { String uriText = "mailto:" + Uri.encode("mail@lanxchange.com") + "?subject=" + Uri.encode("Cannot share file") + "&body=" + Uri.encode("Hi!\n\nSharing some files failed :(\nPlease help!\n(feel free to write more)" + "\n---------------------------------------" + "\ntechnical info (do not remove this): " + "\n---------------------------------------" + "\n" + failedIntent + "\n" + failedIntent.getAction() + "\n" + failedIntent.getDataString() + "\n" + failedIntent.getData() + "\n" + failedIntent.getType() + "\n" + failedIntent.getScheme() + "\n" + failedIntent.getPackage() + "\n" + failedIntent.getExtras() + "\n" + failedIntent.getClipData()); startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(uriText))); } }); builder.show(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private List<VirtualFile> virtualFilesFromClipData(ClipData clipdata) { ArrayList<VirtualFile> result = new ArrayList<VirtualFile>(); for (int i = 0; i < clipdata.getItemCount(); i++) { ClipData.Item item = clipdata.getItemAt(i); // may contain Uri or String if (item.getUri() != null) { VirtualFile file = uriToVirtualFile(item.getUri()); if (file != null) { result.add(file); } } else if (item.getText() != null) { // plain text try { ByteArrayOutputStream arrayOutput = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(arrayOutput); writer.write(item.getText().toString()); writer.close(); result.add(new InMemoryFile("text.txt", arrayOutput.toByteArray())); } catch (IOException ex) { logger.error("Unable to create InMemoryFile from clipdata", ex); } } } return result; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private List<VirtualFile> computeInputIntent(Intent intent) { if (intent.getAction().equals(Intent.ACTION_SEND)) { // use ClipData if available (newer api) ClipData clip = intent.getClipData(); if (clip != null) { return virtualFilesFromClipData(clip); } else { // no clip, try extra stream Object data = intent.getExtras().get(Intent.EXTRA_STREAM); if (data != null && (data.toString().startsWith("file://") || data.toString().startsWith("content:"))) { // Make file available asap: ArrayList<Uri> uris = new ArrayList<Uri>(); uris.add(Uri.parse(intent.getExtras().get(Intent.EXTRA_STREAM).toString())); return urisToVirtualFiles(uris); } } } else if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { // there is a legacy and a new way to receive multiple files // try the new first if (intent.getClipData() != null) { return virtualFilesFromClipData(intent.getClipData()); } else if (intent.getStringArrayListExtra(Intent.EXTRA_STREAM) != null) { ArrayList<Uri> uris = new ArrayList<Uri>(); @SuppressWarnings("rawtypes") ArrayList uriStrings = intent.getStringArrayListExtra(Intent.EXTRA_STREAM); for (Object uriString : uriStrings) { uris.add(Uri.parse(uriString.toString())); } return urisToVirtualFiles(uris); } } return null; } private void setWifiWarning(boolean displayWarning) { findViewById(R.id.noWifiWarning).setVisibility(displayWarning ? View.VISIBLE : View.GONE); } /** * Offers files. * * @param files the files to offer */ private void offerFiles(List<VirtualFile> files) { if (files.isEmpty()) { logger.error("invalid input!"); return; } LXCFile lxcfile = new LXCFile(files, files.get(0).getName()); guiListener.offerFile(lxcfile); } private List<VirtualFile> urisToVirtualFiles(List<Uri> uris) { List<VirtualFile> list = new ArrayList<VirtualFile>(); for (Uri uri : uris) { VirtualFile virtualFile = uriToVirtualFile(uri); if (virtualFile != null) { list.add(virtualFile); } } return list; } private VirtualFile uriToVirtualFile(Uri uri) { String uriString = uri.toString(); VirtualFile file = null; // Handle kitkat files if (uriString.startsWith("content://")) { ContentResolver resolver = getBaseContext().getContentResolver(); // get file name String[] projection = { MediaStore.Files.FileColumns.DISPLAY_NAME }; Cursor cursor = resolver.query(uri, projection, null, null, null); if (cursor != null) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME); cursor.moveToFirst(); String name = cursor.getString(column_index); try { ParcelFileDescriptor desc = resolver.openFileDescriptor(uri, "r"); file = new NonFileContent(name, desc, uri, resolver); } catch (FileNotFoundException ex) { logger.error("Unable to open fd and create NonFileContent", ex); } cursor.close(); } } else if (uriString.startsWith("file://")) { // seems to be useable right away file = new RealFile(new File(uri.getPath())); } return file; } private void promptDownloadTarget(LXCFile file) { // create dialog/fragment here final DirectoryChooserConfig config = DirectoryChooserConfig.builder() .allowReadOnlyDirectory(false) .newDirectoryName("LanXchange") .allowNewDirectoryNameModification(true) .initialDirectory(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getString("pref_downloadPath", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) .getAbsolutePath())) .build(); final DirectoryChooserFragment dialog = DirectoryChooserFragment.newInstance(config); dialog.show(getFragmentManager(), null); dialog.setDirectoryChooserListener(new DirectoryChooserFragment.OnFragmentInteractionListener() { @Override public void onSelectDirectory(@NonNull String path) { dialog.dismiss(); Thread t = new Thread(new Runnable() { @Override public void run() { guiListener.downloadFile(file, new File(path)); } }); t.setName("lxc_helper_initdl_" + file.getShownName()); t.setDaemon(true); t.start(); } @Override public void onCancelChooser() { dialog.dismiss(); file.setLocked(false); fileListView.updateGui(); } }); } /** * Sets the GuiListener. Will be called by AndroidSingleton when LXC is * ready. If this Activity has been recreated and LXC is still running, * AndroidSingleton calls this within onCreateMainActivity * * @param guiListener * out future GuiListener */ public void setGuiListener(final AndroidGuiListener guiListener) { this.guiListener = guiListener; // special gui listener for filelistview, catches download call to check permissions first fileListView.setGuiListener(new AndroidGuiListener(guiListener) { @Override public void guiHidden(int depth) { guiListener.guiHidden(depth); } @Override public void guiVisible(int depth) { guiListener.guiVisible(depth); } @Override public void downloadFile(LXCFile file, boolean chooseTarget) { permissionPromptDownloadFile = file; if (PermissionTools.verifyStoragePermission(MainActivity.this, MainActivity.this)) { permissionPromptDownloadFile = null; // prompt for download target? if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("pref_askDownloadTarget", false)) { promptDownloadTarget(file); } else { // use default dl target guiListener.downloadFile(file, chooseTarget); } } // otherwise prompt is going up, flow continues in callback } }); fileListView.updateGui(); } /** * When this activity is started with an ACTION_SEND Intent, the path of the * file to share will end up here. * * @param uris a list of Uris to share */ public void quickShare(List<VirtualFile> uris) { permissionPromptQuickshare = uris; if (PermissionTools.verifyStoragePermission(this, this)) { offerFiles(uris); permissionPromptQuickshare = null; } // otherwise prompt is going up, flow continues in callback } /** * Used by AndroidSingleton to copy some error codes from LXCService. */ public void onErrorCode(int errorCode) { switch (errorCode) { case 1: AlertDialog.Builder builder = new AlertDialog.Builder(findViewById(R.id.main_layout).getContext()); builder.setTitle(R.string.error_sdcard_title); builder.setMessage(R.string.error_sdcard_text); builder.setCancelable(false); builder.setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); // critical, force exit guiListener.shutdown(true, false, false); AndroidSingleton.onRealDestroy(); finish(); } }); builder.show(); break; } } }
gpl-3.0
TRCIMPLAN/trcimplan.github.io
lib/IBCColoniasTorreon/UniversidadAgrariaAntonioNarro.php
4690
<?php /** * TrcIMPLAN Sitio Web - IBCColoniasTorreon UniversidadAgrariaAntonioNarro * * Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package TrcIMPLANSitioWeb */ namespace IBCColoniasTorreon; /** * Clase UniversidadAgrariaAntonioNarro */ class UniversidadAgrariaAntonioNarro extends \IBCBase\PublicacionWeb { /** * Constructor */ public function __construct() { // Ejecutar constructor en el padre parent::__construct(); // Título, autor y fecha $this->nombre = 'Universidad Agraria Antonio Narro'; $this->fecha = '2017-05-29T20:31:44'; // El nombre del archivo a crear $this->archivo = 'universidad-agraria-antonio-narro'; // La descripción y claves dan información a los buscadores y redes sociales $this->descripcion = 'Colonia Universidad Agraria Antonio Narro en Torreón, Coahuila de Zaragoza, México.'; $this->claves = 'IMPLAN, Torreon, Indicadores, Colonia, Universidad Agraria Antonio Narro'; } // constructor /** * Datos * * @return array Arreglo asociativo */ public function datos() { return array( 'Demografía' => array( '2010' => array( 'Población total' => 3, 'Porcentaje de población masculina' => 47.61, 'Porcentaje de población femenina' => 52.39, 'Porcentaje de población de 0 a 14 años' => 27.30, 'Porcentaje de población de 15 a 64 años' => 65.53, 'Porcentaje de población de 65 y más años' => 6.40, 'Porcentaje de población no especificada' => 0.77, 'Fecundidad promedio' => 2.41, 'Porcentaje de población con discapacidad' => 6.23 ) ), 'Características Económicas' => array( '2010' => array( 'Población Económicamente Activa' => 54.55, 'Población Económicamente Activa masculina' => 67.07, 'Población Económicamente Activa femenina' => 32.93, 'Población Ocupada' => 90.50, 'Población Ocupada masculina' => 65.48, 'Población Ocupada femenina' => 34.52, 'Población Desocupada' => 9.50, 'Derechohabiencia' => 70.48 ) ), 'Viviendas' => array( '2010' => array( 'Hogares' => 0 ) ), 'Unidades Económicas' => array( '2010' => array( 'Total Actividades Económicas' => 11, 'Primer actividad nombre' => 'Preparación de Alimentos y Bebidas', 'Primer actividad porcentaje' => 63.64, 'Segunda actividad nombre' => 'Educativos', 'Segunda actividad porcentaje' => 9.09, 'Tercera actividad nombre' => 'Otros servicios, excepto Gobierno', 'Tercera actividad porcentaje' => 9.09, 'Cuarta actividad nombre' => 'Profesionales, Científicos, Técnicos', 'Cuarta actividad porcentaje' => 9.09, 'Quinta actividad nombre' => 'Comercio Mayoreo', 'Quinta actividad porcentaje' => 9.09 ) ) ); } // datos /** * Mapas * * @return string */ public function mapas() { return array( 'Límites' => \Configuracion\IBCTorreonConfig::LIMITES, 'Centro latitud' => 25.5559549674044, 'Centro longitud' => -103.371351853293 ); } // mapas /** * Reseña * * @return string */ public function resena() { return ''; } // resena } // Clase UniversidadAgrariaAntonioNarro ?>
gpl-3.0
neo4j/neo4j-browser
src/shared/modules/sidebar/sidebarDuck.ts
3340
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import { GlobalState } from 'shared/globalState' export const NAME = 'sidebar' export const TOGGLE = 'sidebar/TOGGLE' export const OPEN = 'sidebar/OPEN' export const SET_DRAFT_SCRIPT = 'sidebar/SET_DRAFT_SCRIPT' export const TRACK_CANNY_CHANGELOG = 'sidebar/CANNY_CHANGELOG_OPENED' export const TRACK_CANNY_FEATURE_REQUEST = 'sidebar/CANNY_FEATURE_REQUEST_OPENED' export function getOpenDrawer(state: GlobalState): string | null { return state[NAME].drawer } export function getCurrentDraft(state: GlobalState): string | null { return state[NAME].draftScript } export function getScriptDraftId(state: GlobalState): string | null { return state[NAME].scriptId || null } export const GUIDE_DRAWER_ID = 'guides' // SIDEBAR type DrawerId = | 'dbms' | 'db' | 'documents' | 'sync' | 'favorites' | 'about' | 'project files' | 'settings' | typeof GUIDE_DRAWER_ID | null export interface SidebarState { drawer: DrawerId | null draftScript: string | null scriptId: string | null } const initialState: SidebarState = { drawer: null, draftScript: null, scriptId: null } function toggleDrawer(state: SidebarState, drawer: DrawerId): SidebarState { // When toggling the drawer we clear the script draft if (drawer === state.drawer) { return { draftScript: null, drawer: null, scriptId: null } } return { draftScript: null, drawer, scriptId: null } } type SidebarAction = ToggleAction | SetDraftScriptAction | OpenSidebarAction interface ToggleAction { type: typeof TOGGLE drawerId: DrawerId } export interface OpenSidebarAction { type: typeof OPEN drawerId: DrawerId } export interface SetDraftScriptAction { type: typeof SET_DRAFT_SCRIPT cmd: string | null scriptId: string | null drawerId: DrawerId } export default function reducer( state = initialState, action: SidebarAction ): SidebarState { switch (action.type) { case TOGGLE: return toggleDrawer(state, action.drawerId) case OPEN: return { ...state, drawer: action.drawerId } case SET_DRAFT_SCRIPT: return { drawer: action.drawerId, scriptId: action.scriptId, draftScript: action.cmd } } return state } export function toggle(drawerId: DrawerId): ToggleAction { return { type: TOGGLE, drawerId } } export function open(drawerId: DrawerId): OpenSidebarAction { return { type: OPEN, drawerId } } export function setDraftScript( cmd: string | null, drawerId: DrawerId, scriptId: string | null = null ): SetDraftScriptAction { return { type: SET_DRAFT_SCRIPT, cmd, drawerId, scriptId } }
gpl-3.0
knotman90/google-interview
problems/codeforces/1066A.cpp
453
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <iterator> #include <limits> #include <numeric> #include <unordered_map> #include <vector> using namespace std; int main() { int t; cin>>t; while(t--) { int L,v,l,r; cin>>L>>v>>l>>r; const int tot = L/v; const int l1 = v*((l+v-1)/v); int train = 0; if( (l1 <= r) ) train = 1+(r-l1)/v; int ans = max(0,tot-train); cout<<ans<<endl; } return 0; }
gpl-3.0
EyeSeeTea/pictureapp
app/src/ereferrals/java/org/eyeseetea/malariacare/layout/listeners/LogoutAndLoginRequiredOnPreferenceClickListener.java
2863
package org.eyeseetea.malariacare.layout.listeners; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.preference.DialogPreference; import android.preference.Preference; import android.util.Log; import org.eyeseetea.malariacare.LoginActivity; import org.eyeseetea.malariacare.R; import org.eyeseetea.malariacare.SettingsActivity; import org.eyeseetea.malariacare.data.authentication.AuthenticationManager; import org.eyeseetea.malariacare.domain.usecase.LogoutUseCase; import org.eyeseetea.malariacare.receivers.AlarmPushReceiver; /** * Listener that moves to the LoginActivity before changing DHIS config */ public class LogoutAndLoginRequiredOnPreferenceClickListener implements Preference.OnPreferenceClickListener { private static final String TAG = "LoginPreferenceListener"; /** * Reference to the activity so you can use this from the activity or the fragment */ SettingsActivity settingsActivity; public LogoutAndLoginRequiredOnPreferenceClickListener(SettingsActivity activity) { this.settingsActivity = activity; } @Override public boolean onPreferenceClick(final Preference preference) { new AlertDialog.Builder(settingsActivity) .setTitle(settingsActivity.getString(R.string.app_logout)) .setMessage(settingsActivity.getString(R.string.settings_menu_logout_message)) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { logout(); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ((DialogPreference) preference).getDialog().dismiss(); dialog.cancel(); } }).create().show(); return true; } private void logout() { Log.d(TAG, "Logging out..."); AuthenticationManager authenticationManager = new AuthenticationManager(settingsActivity); LogoutUseCase logoutUseCase = new LogoutUseCase(authenticationManager); AlarmPushReceiver.cancelPushAlarm(settingsActivity); logoutUseCase.execute(new LogoutUseCase.Callback() { @Override public void onLogoutSuccess() { Intent loginIntent = new Intent(settingsActivity, LoginActivity.class); settingsActivity.finish(); settingsActivity.startActivity(loginIntent); } @Override public void onLogoutError(String message) { Log.e(TAG, message); } }); } }
gpl-3.0
yadickson/autoplsp
src/main/java/com/github/yadickson/autoplsp/package-info.java
82
/** * Generator class package folder. */ package com.github.yadickson.autoplsp;
gpl-3.0
derniercri/boo-js
flow-typed/npm/babel-plugin-transform-class-properties_vx.x.x.js
1022
// flow-typed signature: b671973e8dc64046a1b0c930cac8671a // flow-typed version: <<STUB>>/babel-plugin-transform-class-properties_v^6.24.1/flow_v0.43.1 /** * This is an autogenerated libdef stub for: * * 'babel-plugin-transform-class-properties' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-plugin-transform-class-properties' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-plugin-transform-class-properties/lib/index' { declare module.exports: any; } // Filename aliases declare module 'babel-plugin-transform-class-properties/lib/index.js' { declare module.exports: $Exports<'babel-plugin-transform-class-properties/lib/index'>; }
gpl-3.0
hitech95/Smart-CCraft
src/main/java/it/kytech/smartccraft/tileentity/TileChargeStationMK4.java
1047
/** * This file is part of SmartCCraft * * Copyright (c) 2015 hitech95 <https://github.com/hitech95> * Copyright (c) contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.kytech.smartccraft.tileentity; import java.util.ArrayList; import java.util.List; /** * Created by M2K on 29/06/2014. */ public class TileChargeStationMK4 extends TileChargeStation { public TileChargeStationMK4() { super(3); } }
gpl-3.0
ballotpath/BallotPath
BPAdmin/components/renderers/view_renderer.php
4592
<?php class ViewRenderer extends Renderer { function RenderDetailPageEdit($page) { $this->RenderPage($page); } function RenderPage(Page $Page) { $this->SetHTTPContentTypeByPage($Page); $Page->BeforePageRender->Fire(array(&$Page)); $customParams = array(); $layoutTemplate = $Page->GetCustomTemplate(PagePart::Layout, PageMode::View, 'common/layout.tpl', $customParams); $this->DisplayTemplate('view/page.tpl', array('Page' => $Page), array_merge($customParams, array( 'App' => $Page->GetSingleRecordViewData(), 'Authentication' => $Page->GetAuthenticationViewData(), 'LayoutTemplateName' => $layoutTemplate, 'PageList' => $this->RenderDef($Page->GetReadyPageList()), 'Grid' => $this->Render($Page->GetGrid()), 'HideSideBarByDefault' => $Page->GetHidePageListByDefault() ) ) ); } function RenderGrid(Grid $Grid) { $customParams = array(); $template = $Grid->GetPage()->GetCustomTemplate(PagePart::RecordCard, PageMode::View, 'view/grid.tpl', $customParams); $this->DisplayTemplate($template, array( 'Grid' => $Grid->GetViewSingleRowViewData($this), ), array_merge($customParams, array( 'Authentication' => $Grid->GetPage()->GetAuthenticationViewData() ) ) ); } protected function ShowHtmlNullValue() { return true; } } class PrintOneRecordRenderer extends ViewRenderer { function RenderDetailPageEdit($page) { $this->RenderPage($page); } function RenderPage(Page $Page) { $this->SetHTTPContentTypeByPage($Page); $Page->BeforePageRender->Fire(array(&$Page)); $this->DisplayTemplate('view/print_page.tpl', array('Page' => $Page), array( 'Grid' => $this->Render($Page->GetGrid()) )); } function RenderGrid(Grid $Grid) { $primaryKeyMap = array(); $Grid->GetDataset()->Open(); $Row = array(); if($Grid->GetDataset()->Next()) { $primaryKeyMap = $Grid->GetDataset()->GetPrimaryKeyValuesMap(); foreach($Grid->GetSingleRecordViewColumns() as $Column) $Row[] = $this->Render($Column); } $this->DisplayTemplate('view/print_grid.tpl', array( 'Grid' => $Grid, 'Columns' => $Grid->GetSingleRecordViewColumns()), array( 'Title' => $Grid->GetPage()->GetShortCaption(), 'PrimaryKeyMap' => $primaryKeyMap, 'ColumnCount' => count($Grid->GetSingleRecordViewColumns()), 'Row' => $Row, )); } protected function ChildPagesAvailable() { return false; } } class DeleteRenderer extends Renderer { function RenderDetailPageEdit($page) { $this->RenderPage($page); } function RenderPage(Page $Page) { $this->DisplayTemplate('delete/page.tpl', array('Page' => $Page), array( 'Grid' => $this->Render($Page->GetGrid()) )); } function RenderGrid(Grid $Grid) { $primaryKeyMap = array(); $Grid->GetDataset()->Open(); $Row = array(); $hiddenValues = ''; if($Grid->GetDataset()->Next()) { foreach($Grid->GetSingleRecordViewColumns() as $column) $Row[] = $this->Render($column); $hiddenValues = array(OPERATION_PARAMNAME => OPERATION_COMMIT_DELETE); AddPrimaryKeyParametersToArray($hiddenValues, $Grid->GetDataset()->GetPrimaryKeyValues()); $primaryKeyMap = $Grid->GetDataset()->GetPrimaryKeyValuesMap(); } $this->DisplayTemplate('delete/grid.tpl', array( 'Grid' => $Grid, 'Columns' => $Grid->GetSingleRecordViewColumns()), array( 'Title' => $Grid->GetPage()->GetShortCaption(), 'PrimaryKeyMap' => $primaryKeyMap, 'ColumnCount' => count($Grid->GetSingleRecordViewColumns()), 'Row' => $Row, 'HiddenValues' => $hiddenValues )); } }
gpl-3.0
chathura77/agentworld
AgentWorld/src/SimpleCreature.java
15012
/** * This class has got the attributes and the methods that a simple creature * has. A simple creature may move around in the grid world randomly, by taking * random moves for random amounts of times. * * Copyright (C) 2012 Chathura M. Sarathchandra Magurawalage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * @author Chathura M. Sarathchadra Magurawalage * 77.chathura@gmail.com * csarata@essex.ac.uk */ package AgentWorld; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.geom.Rectangle2D; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedList; import java.util.Vector; import javax.swing.JComponent; public class SimpleCreature extends JComponent { /** * The generated serial ID */ private static final long serialVersionUID = -3847917082797376928L; /** * The current location of the creature */ protected Point p; /** * Width of the creature */ protected static final double width = 10; /** * Height of the creature */ protected static final double height = 10; /** * The energy left of the creature */ protected int energy = 100; /** * true if alive, false otherwise. */ protected boolean alive = true; /** * The plants that the creature carry */ protected final LinkedList<Plant> plants = new LinkedList<Plant>(); /** * The amount of pixels that it travel at a time */ protected final double dr = 1; /** * The bounds of the grid */ protected static Rectangle2D bounds; /** * The current square of the creature, */ protected Point currentSquare; /** * The amount of plants that a simple creature can carry */ protected static int PLANT_LIMIT = 4; /** * The combination one */ protected final static int COMBO_ONE = 0; /** * The combination two */ public final static int COMBO_TWO = 1; /** * The combination three */ public final static int COMBO_THREE = 2; /** * The limit the creature waits until it eats */ private static final int PLANT_EAT_LIMIT = 50; /** * The speed that the energy will be consumed */ protected static final long ENERGY_CONS_SPEED = 1000; /** * The amount of energy that it will loose each time it moves to another * square */ private static final int DIFF_SQUARE_ENERGY_CONS_AMOUNT = 7; /** * The amount of energy that it will loose each time it is in the same * square as it is. */ private static final int ENERGY_CONS_AMOUNT = 5; /** * The combination one utility */ public static int COMBO_ONE_AMOUNT = 450; /** * The combination two utility */ public static int COMBO_TWO_AMOUNT = 420; /** * The combination three utility */ public static int COMBO_THREE_AMOUNT = 400; /** * The amount of creatures */ public static Integer nCreatures = 0; /** * The creature number */ protected int cNumber; /** * The Constructor * * @param point * - The position of the creature starts moving * @param bounds * - The bounds of the grid */ public SimpleCreature(Point point, Rectangle2D bounds) { p = point; SimpleCreature.bounds = bounds; setOpaque(false); countEnergy(); getClosePlants(); currentSquare = getCurrentSquare(p); synchronized (nCreatures) { cNumber = nCreatures = nCreatures + 1; } WorldFrame.log.append("A new Creature has been added to the world " + getCreautreNumber() + " \n"); } @Override public void paintComponent(Graphics g) { g.setColor(Color.BLUE); g.fillOval((int) p.getX(), (int) p.getY(), (int) width, (int) height); } /** * This method count downs the energy, if the energy goes down '0' the * creature dies. * * If it is carrying any plants, eat one of them, if the current energy of * the creature is less than 50 */ protected void countEnergy() { Thread timer = new Thread(new Runnable() { @Override public void run() { while (energy > 0 && isAlive() || (plants.size() > 0 && energy > 0 && isAlive())) { if (energy < PLANT_EAT_LIMIT) { if (isCombination(COMBO_ONE)) { eatCombinationOne(); } else if (isCombination(COMBO_TWO)) { eatCombinationTwo(); } else if (isCombination(COMBO_THREE)) { eatCombinationThree(); } else { if (plants.size() > 0) { Plant first = plants.poll(); WorldFrame.log.append("Simple Creature " + getCreautreNumber() + " ate a plant type of" + first.getType() + " \n"); energy += first.getEnergy(); } } } try { Thread.sleep(ENERGY_CONS_SPEED); } catch (InterruptedException e) { e.printStackTrace(); } // if the creature moves to a different square the energy // level goes down more if (isSquareChanged()) { energy -= DIFF_SQUARE_ENERGY_CONS_AMOUNT; } else { energy -= ENERGY_CONS_AMOUNT; } } kill(); } }); timer.setDaemon(true); timer.start(); } /** * Eat the combination three */ protected void eatCombinationThree() { int magenta = 0; int yellow = 0; for (Iterator<Plant> it = plants.iterator(); it.hasNext();) { Plant pl = it.next(); if (pl.getType() == Plant.MAGENTA_PLANT && magenta < 1) { it.remove(); magenta++; } if (pl.getType() == Plant.YELLOW_PLANT && yellow < 1) { it.remove(); yellow++; } if (magenta == 1 && yellow == 1) { break; } } energy += COMBO_THREE_AMOUNT; System.out.println("The combo 3 " + energy); WorldFrame.log.append("Simple Creature " + getCreautreNumber() + " ate a combination three \n"); } /** * Eat the combination two */ protected void eatCombinationTwo() { int yellow = 0; int red = 0; for (Iterator<Plant> it = plants.iterator(); it.hasNext();) { Plant pl = it.next(); if (pl.getType() == Plant.YELLOW_PLANT && yellow < 1) { it.remove(); yellow++; } if (pl.getType() == Plant.RED_PLANT && red < 1) { it.remove(); red++; } // stops looping than required if (yellow == 1 && red == 1) { break; } } energy += COMBO_TWO_AMOUNT; System.out.println("The combo 2 " + energy); WorldFrame.log.append("Simple Creature " + getCreautreNumber() + " ate a combination two \n"); } /** * Eat the combination one */ protected void eatCombinationOne() { int green = 0; int red = 0; for (Iterator<Plant> it = plants.iterator(); it.hasNext();) { Plant pl = it.next(); if (pl.getType() == Plant.GREEN_PLANT && green < 1) { it.remove(); green++; } if (pl.getType() == Plant.RED_PLANT && red < 1) { it.remove(); red++; } // stops looping than required if (green == 1 && red == 1) { break; } } energy += COMBO_ONE_AMOUNT; System.out.println("The combo 1 " + energy); WorldFrame.log.append("Simple Creature " + getCreautreNumber() + " ate a combination one \n"); } /** * Check if there is a possible plant combination in the plants that the * creature carry * * @param comType * Combination type * @return true, if the particular combination exist, false otherwise. */ protected boolean isCombination(int comType) { int green = 0; int red = 0; int yellow = 0; switch (comType) { case COMBO_ONE: for (Iterator<Plant> it = plants.iterator(); it.hasNext();) { Plant pl = it.next(); if (pl.getType() == Plant.GREEN_PLANT && green < 1) { green++; } if (pl.getType() == Plant.RED_PLANT && red < 1) { red++; } if (green > 0 && red > 0) { return true; } } break; case COMBO_TWO: yellow = 0; red = 0; for (Iterator<Plant> it = plants.iterator(); it.hasNext();) { Plant pl = it.next(); if (pl.getType() == Plant.YELLOW_PLANT && yellow < 1) { yellow++; } if (pl.getType() == Plant.RED_PLANT && red < 1) { red++; } System.out.println("yellow " + yellow + " red " + red); if (yellow > 0 && red > 0) { return true; } } break; case COMBO_THREE: green = 0; yellow = 0; int magenta = 0; for (Iterator<Plant> it = plants.iterator(); it.hasNext();) { Plant pl = it.next(); if (pl.getType() == Plant.MAGENTA_PLANT && magenta < 1) { magenta++; } if (pl.getType() == Plant.YELLOW_PLANT && yellow < 1) { yellow++; } if (magenta > 0 && yellow > 0) { return true; } } break; default: break; } return false; } /** * if the creature has moved to a different square * * @return ture, if the creature has changed to a different square, false * otherwise */ protected boolean isSquareChanged() { Point cPoint = getCurrentSquare(p); if (p.equals(currentSquare)) { return false; } else { currentSquare = cPoint; } return true; } /** * This method finds the closest plant to the creature * * If the creature and the plant is in the same square, the creature takes * the plant */ protected void getClosePlants() { Thread radarThread = new Thread(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { // True if this creature is alive while (isAlive()) { // clone the Grid.plants, the centralised repository of // plants, so there will less concurrent conflict Vector<Plant> pla; synchronized (Grid.plants) { pla = (Vector<Plant>) Grid.plants.clone(); for (Iterator<Plant> iterator = pla.iterator(); iterator .hasNext();) { Plant plant = iterator.next(); Point pos = plant.getPosition(); try { if (isPlantInRange(pos)) { if (plants.size() < PLANT_LIMIT) { setPosition(pos); plant.take(); plants.add(plant); iterator.remove(); synchronized (Grid.plants) { // assigns the remaining plants to // the // main // plant repository Grid.plants = pla; } } } } catch (ConcurrentModificationException e2) { continue; } } } } } }); radarThread.setDaemon(true); radarThread.start(); } /** * This method finds if the creature is in the same square as the plant * given * * @param plantPos * - The position of the plant * @return - true if it is in the same square as the creature otherwise, * return false. * */ protected boolean isPlantInRange(Point plantPos) { Point creaturePosR = getCurrentSquare(p); boolean result = false; if (plantPos != null) { Point plantPosR = getCurrentSquare(plantPos); result = creaturePosR.equals(plantPosR); } return result; } /** * Gets the current square of the given position. * * @param position * - The current position of the creature / plant * @return - The current square. */ protected Point getCurrentSquare(Point position) { Point p = new Point(); p.x = (int) (position.getX() - (position.getX() % 100)); p.y = (int) (position.getY() - (position.getY() % 100)); return p; } /** * Current state of the creature * * @return - true, if alive, false otherwise */ public boolean isAlive() { return alive; } /** * Kills the creature */ public void kill() { WorldFrame.log.append("Creature " + getCreautreNumber() + " is dead\n"); alive = false; } /** * Get the energy that the creature has got left * * @return - The remaining energy */ public int getEnergy() { return energy; } /** * Check if the creature can move up * * @return - true if the creature can move up, otherwise false. */ public boolean isUpMovable() { return p.getY() > bounds.getMinY(); } /** * Move up */ public void moveUp() { p.y -= dr; } /** * Check if the creature can move down * * @return - True if the creature can move down, false otherwise */ public boolean isDownMovable() { return p.getY() + width <= Grid.BOUND_MAX_Y; } /** * Move down */ public void moveDown() { p.y += dr; } /** * Move right */ public void moveRight() { p.x += dr; } /** * Check if the creature can move right * * @return - true, if the creature can move right, otherwise false. */ public boolean isRightMovable() { return p.getX() + width <= Grid.BOUND_MAX_X; } /** * Move left */ public void moveLeft() { p.x -= dr; } /** * Move to north east */ public void moveNorthEast() { p.x += dr; p.y -= dr; } /** * Move to east */ public void moveSouthEast() { p.x += dr; p.y += dr; } /** * Move to south west */ public void moveSouthWest() { p.x -= dr; p.y += dr; } /** * Move to north west */ public void moveNorthWest() { p.x -= dr; p.y -= dr; } /** * Check if the creature can move left * * @return - true if the creature can move left, otherwise false. */ public boolean isLeftMovable() { return p.getX() > bounds.getMinX(); } /** * Sets the current position of the creature * * @param plantP * - The position to be set */ protected void setPosition(Point plantP) { p = (Point) plantP.clone(); if (p.getX() >= Grid.BOUND_MAX_X - 20) { p.x = Grid.BOUND_MAX_X - 20; } if (p.getY() >= Grid.BOUND_MAX_Y - 20) { p.y = Grid.BOUND_MAX_Y - 20; } } /** * Get the position of the creature * * @return The position */ protected Point getPosition() { return p; } /** * Get the unique creature number * * @return the creature number */ public int getCreautreNumber() { return cNumber; } }
gpl-3.0
ericpony/safety-prover
SafetyProver/src/main/java/encoding/AutomataEncoding.java
3550
package encoding; import elimination.AcceptanceTree; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.sat4j.specs.ContradictionException; import org.sat4j.specs.TimeoutException; import java.util.HashSet; import java.util.List; import java.util.Set; public class AutomataEncoding { private static final Logger LOGGER = LogManager.getLogger(); private ISatSolver solver; private int startIndexOfTransVars = 1; private int startIndexOfZVars = 1; private int numStates; private int numLabels; private AcceptanceTree acceptance = null; public AutomataEncoding(ISatSolver solver, int numStates, int numLabels) { this.solver = solver; this.numStates = numStates; this.numLabels = numLabels; allocateBoolVars(solver); } private void allocateBoolVars(ISatSolver solver) { //vars for transition and accepting states startIndexOfTransVars = solver.getNextSATVar(); startIndexOfZVars = startIndexOfTransVars + numStates * numStates * numLabels; solver.setNextSATVar(startIndexOfZVars + numStates); } public void encode() throws ContradictionException, TimeoutException { int indexRunner = this.startIndexOfTransVars; for (int source = 1; source <= numStates; source++) { for (int label = 0; label < numLabels; label++) { int[] transWithSourceAndLabel = new int[numStates]; for (int destination = 1; destination <= numStates; destination++) { transWithSourceAndLabel[destination - 1] = indexRunner; indexRunner++; } //Determinisitc: No pair of transitions same source, input for (int i = 0; i < transWithSourceAndLabel.length; i++) { for (int j = i + 1; j < transWithSourceAndLabel.length; j++) { int[] notBothTransition = new int[]{-transWithSourceAndLabel[i], -transWithSourceAndLabel[j]}; solver.addClause(notBothTransition); } } } } acceptance = new AcceptanceTree(this); } /** * Extract acceptantance states from SAT * States are counted from 1 */ public Set<Integer> extractAcceptingStates(int[] model) { Set<Integer> acceptingStates = new HashSet<Integer>(); for (int q = 1; q <= numStates; q++) { if (model[getIndexZVar(q) - 1] > 0) { acceptingStates.add(q); } } return acceptingStates; } public int acceptWord(List<Integer> v) throws ContradictionException { return acceptance.insert(v); } /* * q start from 1 */ public int getIndexZVar(int q) { return this.startIndexOfZVars + q - 1; } /* * source, dest start from 1 * label start from 0 */ public int getTransBoolVar(int source, int label, int dest) { source--; dest--; return startIndexOfTransVars + dest + numStates * (label + numLabels * source); } public int getStartIndexOfTransVars() { return startIndexOfTransVars; } public int getStartIndexOfZVars() { return startIndexOfZVars; } public int getNumStates() { return numStates; } public int getNumLabels() { return numLabels; } public ISatSolver getSolver() { return solver; } }
gpl-3.0