code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'PASSWORD': '', } } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
nvbn/deploy_trigger
deploy_trigger/settings/local_nvbn.py
Python
mit
1,371
// -*- c++ -*- // Generated by gmmproc 2.44.0 -- DO NOT MODIFY! #ifndef _GDKMM_DEVICEMANAGER_H #define _GDKMM_DEVICEMANAGER_H #include <glibmm/ustring.h> #include <sigc++/sigc++.h> /* Copyright (C) 20010 The gtkmm Development Team * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <vector> #include <gdkmm/device.h> #include <gdkmm/display.h> #include <gdk/gdk.h> #ifndef DOXYGEN_SHOULD_SKIP_THIS typedef struct _GdkDeviceManager GdkDeviceManager; typedef struct _GdkDeviceManagerClass GdkDeviceManagerClass; #endif /* DOXYGEN_SHOULD_SKIP_THIS */ #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace Gdk { class DeviceManager_Class; } // namespace Gdk #endif //DOXYGEN_SHOULD_SKIP_THIS namespace Gdk { /** Functions for handling input devices. * * In addition to a single pointer and keyboard for user interface input, * GDK contains support for a variety of input devices, including graphics * tablets, touchscreens and multiple pointers/keyboards interacting * simultaneously with the user interface. Under X, the support for multiple * input devices is done through the XInput 2 extension, * which also supports additional features such as sub-pixel positioning * information and additional device-dependent information. * * By default, and if the platform supports it, GDK is aware of multiple * keyboard/pointer pairs and multitouch devices, this behavior can be * changed by calling gdk_disable_multidevice() before Gdk::Display::open(), * although there would rarely be a reason to do that. For a widget or * window to be dealt as multipointer aware, * Gdk::Window::set_support_multidevice() or * Gtk::Widget::set_support_multidevice() must have been called on it. * * Conceptually, in multidevice mode there are 2 device types. Virtual * devices (or master devices) are represented by the pointer cursors * and keyboard foci that are seen on the screen. Physical devices (or * slave devices) represent the hardware that is controlling the virtual * devices, and thus have no visible cursor on the screen. * * Virtual devices are always paired, so there is a keyboard device for every * pointer device. Associations between devices may be inspected through * Gdk::Device::get_associated_device(). * * There may be several virtual devices, and several physical devices could * be controlling each of these virtual devices. Physical devices may also * be "floating", which means they are not attached to any virtual device. * * By default, GDK will automatically listen for events coming from all * master devices, setting the Gdk::Device for all events coming from input * devices, * * Events containing device information are GDK_MOTION_NOTIFY, * GDK_BUTTON_PRESS, GDK_2BUTTON_PRESS, GDK_3BUTTON_PRESS, * GDK_BUTTON_RELEASE, GDK_SCROLL, GDK_KEY_PRESS, GDK_KEY_RELEASE, * GDK_ENTER_NOTIFY, GDK_LEAVE_NOTIFY, GDK_FOCUS_CHANGE, * GDK_PROXIMITY_IN, GDK_PROXIMITY_OUT, GDK_DRAG_ENTER, GDK_DRAG_LEAVE, * GDK_DRAG_MOTION, GDK_DRAG_STATUS, GDK_DROP_START, GDK_DROP_FINISHED * and GDK_GRAB_BROKEN. * * Although gdk_window_set_support_multidevice() must be called on * \#GdkWindows in order to support additional features of multiple pointer * interaction, such as multiple per-device enter/leave events, the default * setting will emit just one enter/leave event pair for all devices on the * window. See Gdk::Window::set_support_multidevice() documentation for more * information. * * In order to listen for events coming from other than a virtual device, * Gdk::Window::set_device_events() must be called. Generally, this method * can be used to modify the event mask for any given device. * * Input devices may also provide additional information besides X/Y. * For example, graphics tablets may also provide pressure and X/Y tilt * information. This information is device-dependent, and may be * queried through Gdk::Devie::get_axis(). In multidevice mode, virtual * devices will change axes in order to always represent the physical * device that is routing events through it. Whenever the physical device * changes, the Gdk::Device::property_n_axes() property will be notified, and * Gdk::Device::list_axes() will return the new device axes. * * Devices may also have associated keys or * macro buttons. Such keys can be globally set to map into normal X * keyboard events. The mapping is set using Gdk::Device::set_key(). * * In order to query the device hierarchy and be aware of changes in the * device hierarchy (such as virtual devices being created or removed, or * physical devices being plugged or unplugged), GDK provides * Gdk::DeviceManager. On X11, multidevice support is implemented through * XInput 2. Unless gdk_disable_multidevice() is called, the XInput 2.x * Gdk::DeviceManager implementation will be used as the input source. Otherwise * either the core or XInput 1.x implementations will be used. * * @newin{3,0} */ class DeviceManager : public Glib::Object { #ifndef DOXYGEN_SHOULD_SKIP_THIS public: typedef DeviceManager CppObjectType; typedef DeviceManager_Class CppClassType; typedef GdkDeviceManager BaseObjectType; typedef GdkDeviceManagerClass BaseClassType; private: friend class DeviceManager_Class; static CppClassType devicemanager_class_; private: // noncopyable DeviceManager(const DeviceManager&); DeviceManager& operator=(const DeviceManager&); protected: explicit DeviceManager(const Glib::ConstructParams& construct_params); explicit DeviceManager(GdkDeviceManager* castitem); #endif /* DOXYGEN_SHOULD_SKIP_THIS */ public: virtual ~DeviceManager(); /** Get the GType for this class, for use with the underlying GObject type system. */ static GType get_type() G_GNUC_CONST; #ifndef DOXYGEN_SHOULD_SKIP_THIS static GType get_base_type() G_GNUC_CONST; #endif ///Provides access to the underlying C GObject. GdkDeviceManager* gobj() { return reinterpret_cast<GdkDeviceManager*>(gobject_); } ///Provides access to the underlying C GObject. const GdkDeviceManager* gobj() const { return reinterpret_cast<GdkDeviceManager*>(gobject_); } ///Provides access to the underlying C instance. The caller is responsible for unrefing it. Use when directly setting fields in structs. GdkDeviceManager* gobj_copy(); private: protected: DeviceManager(); public: /** Gets the Gdk::Display associated to @a device_manager. * * @newin{3,0} * * @return The Gdk::Display to which * @a device_manager is associated to, or #<tt>0</tt>. This memory is * owned by GDK and must not be freed or unreferenced. */ Glib::RefPtr<Display> get_display(); /** Gets the Gdk::Display associated to @a device_manager. * * @newin{3,0} * * @return The Gdk::Display to which * @a device_manager is associated to, or #<tt>0</tt>. This memory is * owned by GDK and must not be freed or unreferenced. */ Glib::RefPtr<const Display> get_display() const; /** Returns the list of devices of type @a type currently attached to * @a device_manager. * * @newin{3,0} * * @param type Device type to get. * @return A list of * Gdk::Devices. The returned list must be * freed with Glib::list_free(). The list elements are owned by * GTK+ and must not be freed or unreffed. */ std::vector< Glib::RefPtr<Device> > list_devices(DeviceType type); /** Returns the list of devices of type @a type currently attached to * @a device_manager. * * @newin{3,0} * * @param type Device type to get. * @return A list of * Gdk::Devices. The returned list must be * freed with Glib::list_free(). The list elements are owned by * GTK+ and must not be freed or unreffed. */ std::vector< Glib::RefPtr<const Device> > list_devices(DeviceType type) const; /** Returns the client pointer, that is, the master pointer that acts as the core pointer * for this application. In X11, window managers may change this depending on the interaction * pattern under the presence of several pointers. * * You should use this function seldomly, only in code that isn’t triggered by a Gdk::Event * and there aren’t other means to get a meaningful Gdk::Device to operate on. * * @newin{3,0} * * @return The client pointer. This memory is * owned by GDK and must not be freed or unreferenced. */ Glib::RefPtr<Device> get_client_pointer(); /** Returns the client pointer, that is, the master pointer that acts as the core pointer * for this application. In X11, window managers may change this depending on the interaction * pattern under the presence of several pointers. * * You should use this function seldomly, only in code that isn’t triggered by a Gdk::Event * and there aren’t other means to get a meaningful Gdk::Device to operate on. * * @newin{3,0} * * @return The client pointer. This memory is * owned by GDK and must not be freed or unreferenced. */ Glib::RefPtr<const Device> get_client_pointer() const; //TODO: Signals, properties. public: public: //C++ methods used to invoke GTK+ virtual functions: protected: //GTK+ Virtual Functions (override these to change behaviour): //Default Signal Handlers:: }; } // namespace Gdk namespace Glib { /** A Glib::wrap() method for this object. * * @param object The C instance. * @param take_copy False if the result should take ownership of the C instance. True if it should take a new copy or ref. * @result A C++ instance that wraps this C instance. * * @relates Gdk::DeviceManager */ Glib::RefPtr<Gdk::DeviceManager> wrap(GdkDeviceManager* object, bool take_copy = false); } #endif /* _GDKMM_DEVICEMANAGER_H */
utilForever/Wings
Libraries/gtkmm/include/gtkmm/gdkmm/devicemanager.h
C
mit
10,474
--- layout: center permalink: /404.html --- # 404 Looks like this page doesn't exist. If this seems like an error, please email me.
ParisMi/ParisMi.github.io
404.md
Markdown
mit
135
I write a shell script to indent LaTeX documents with the perl package `[latexindent](https://www.ctan.org/pkg/latexindent)`. # How to use? Usage: ``` ./latexindent.sh path/filename.tex ``` What the shell script does are: - generate the indented tex documents which is still named `filename.tex` - backup the original tex file `filename.tex` as `filename.tex.old` # The usage of latexindent ```bash latexindent.pl version 2.1R usage: latexindent.pl [options] [file][.tex] -h help (see the documentation for detailed instructions and examples) -o output to another file; sample usage latexindent.pl -o myfile.tex outputfile.tex -w overwrite the current file- a backup will be made, but still be careful -s silent mode- no output will be given to the terminal -t tracing mode- verbose information given to the log file -l use localSettings.yaml (assuming it exists in the directory of your file) -d ONLY use defaultSettings.yaml, ignore ALL user files -c=cruft directory used to specify the location of backup files and indent.log ```
sparkandshine/tools
documents_output/latex_indent/ReadMe.md
Markdown
mit
1,115
''' Yescoin base58 encoding and decoding. Based on https://yescointalk.org/index.php?topic=1026.0 (public domain) ''' import hashlib # for compatibility with following code... class SHA256: new = hashlib.sha256 if str != bytes: # Python 3.x def ord(c): return c def chr(n): return bytes( (n,) ) __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) b58chars = __b58chars def b58encode(v): """ encode v, which is a string of bytes, to base58. """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += (256**i) * ord(c) result = '' while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = div result = __b58chars[long_value] + result # Yescoin does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s nPad = 0 for c in v: if c == '\0': nPad += 1 else: break return (__b58chars[0]*nPad) + result def b58decode(v, length = None): """ decode v into a string of len bytes """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base**i) result = bytes() while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + result long_value = div result = chr(long_value) + result nPad = 0 for c in v: if c == __b58chars[0]: nPad += 1 else: break result = chr(0)*nPad + result if length is not None and len(result) != length: return None return result def checksum(v): """Return 32-bit checksum based on SHA256""" return SHA256.new(SHA256.new(v).digest()).digest()[0:4] def b58encode_chk(v): """b58encode a string, with 32-bit checksum""" return b58encode(v + checksum(v)) def b58decode_chk(v): """decode a base58 string, check and remove checksum""" result = b58decode(v) if result is None: return None h3 = checksum(result[:-4]) if result[-4:] == checksum(result[:-4]): return result[:-4] else: return None def get_bcaddress_version(strAddress): """ Returns None if strAddress is invalid. Otherwise returns integer version of address. """ addr = b58decode_chk(strAddress) if addr is None or len(addr)!=21: return None version = addr[0] return ord(version) if __name__ == '__main__': # Test case (from http://gitorious.org/yescoin/python-base58.git) assert get_bcaddress_version('15VjRaDX9zpbA8LVnbrCAFzrVzN7ixHNsC') is 0 _ohai = 'o hai'.encode('ascii') _tmp = b58encode(_ohai) assert _tmp == 'DYB3oMS' assert b58decode(_tmp, 5) == _ohai print("Tests passed")
thormuller/yescoin2
contrib/testgen/base58.py
Python
mit
2,818
/* * The MIT License (MIT) * * Copyright (c) 2013-2017 Charkey. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package cn.simastudio.charkey.learning.simulatestack; /** * <p>Recursion to Stack, 防止栈溢出</p> * <p>Created by Charkey on 2016/7/22.</p> */ public class SimulateSysStack { private static int recursion1(int n) { if (n <= 1) { return 1; } else { return n * recursion1(n - 1); } } private static int recursion2(int n) { boolean back = false; int res = 1; int[] stack = new int[n]; int front = -1; do { if (!back) { if (n <= 1) { res = 1; back = true; continue; } stack[++front] = n--; } else { res *= stack[front--]; } } while (front >= 0); return res; } public static void main(String[] args) { System.out.println(recursion1(10)); System.out.println(recursion2(10)); } }
CharkeyQK/AlgorithmDataStructure
src/cn/simastudio/charkey/learning/simulatestack/SimulateSysStack.java
Java
mit
2,135
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef WIN32 // for posix_fallocate #ifdef __linux__ #define _POSIX_C_SOURCE 200112L #endif #include <fcntl.h> #include <sys/stat.h> #include <sys/resource.h> #endif #include "util.h" #include "sync.h" #include "version.h" #include "ui_interface.h" #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() // Work around clang compilation problem in Boost 1.46: // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION namespace boost { namespace program_options { std::string to_internal(const std::string&); } } #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/foreach.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> #include <stdarg.h> #ifdef WIN32 #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <io.h> /* for _commit */ #include "shlobj.h" #elif defined(__linux__) # include <sys/prctl.h> #endif using namespace std; map<string, string> mapArgs; map<string, vector<string> > mapMultiArgs; bool fDebug = false; bool fDebugNet = false; bool fPrintToConsole = false; bool fPrintToDebugger = false; bool fDaemon = false; bool fServer = false; bool fCommandLine = false; string strMiscWarning; bool fTestNet = false; bool fBloomFilters = true; bool fNoListen = false; bool fLogTimestamps = false; CMedianFilter<int64> vTimeOffsets(200,0); volatile bool fReopenDebugLog = false; bool fCachedPath[2] = {false, false}; // Init OpenSSL library multithreading support static CCriticalSection** ppmutexOpenSSL; void locking_callback(int mode, int i, const char* file, int line) { if (mode & CRYPTO_LOCK) { ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } else { LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } } LockedPageManager LockedPageManager::instance; // Init class CInit { public: CInit() { // Init OpenSSL library multithreading support ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*)); for (int i = 0; i < CRYPTO_num_locks(); i++) ppmutexOpenSSL[i] = new CCriticalSection(); CRYPTO_set_locking_callback(locking_callback); #ifdef WIN32 // Seed random number generator with screen scrape and other hardware sources RAND_screen(); #endif // Seed random number generator with performance counter RandAddSeed(); } ~CInit() { // Shutdown OpenSSL library multithreading support CRYPTO_set_locking_callback(NULL); for (int i = 0; i < CRYPTO_num_locks(); i++) delete ppmutexOpenSSL[i]; OPENSSL_free(ppmutexOpenSSL); } } instance_of_cinit; void RandAddSeed() { // Seed with CPU performance counter int64 nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memset(&nCounter, 0, sizeof(nCounter)); } void RandAddSeedPerfmon() { RandAddSeed(); // This can take up to 2 seconds, so only do it every 10 minutes static int64 nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data unsigned char pdata[250000]; memset(pdata, 0, sizeof(pdata)); unsigned long nSize = sizeof(pdata); long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize); RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(pdata, nSize, nSize/100.0); OPENSSL_cleanse(pdata, nSize); printf("RandAddSeed() %lu bytes\n", nSize); } #endif } uint64 GetRand(uint64 nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax; uint64 nRand = 0; do RAND_bytes((unsigned char*)&nRand, sizeof(nRand)); while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; RAND_bytes((unsigned char*)&hash, sizeof(hash)); return hash; } // // OutputDebugStringF (aka printf -- there is a #define that we really // should get rid of one day) has been broken a couple of times now // by well-meaning people adding mutexes in the most straightforward way. // It breaks because it may be called by global destructors during shutdown. // Since the order of destruction of static/global objects is undefined, // defining a mutex as a global object doesn't work (the mutex gets // destroyed, and then some later destructor calls OutputDebugStringF, // maybe indirectly, and you get a core dump at shutdown trying to lock // the mutex). static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT; // We use boost::call_once() to make sure these are initialized in // in a thread-safe manner the first time it is called: static FILE* fileout = NULL; static boost::mutex* mutexDebugLog = NULL; static void DebugPrintInit() { assert(fileout == NULL); assert(mutexDebugLog == NULL); boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; fileout = fopen(pathDebug.string().c_str(), "a"); if (fileout) setbuf(fileout, NULL); // unbuffered mutexDebugLog = new boost::mutex(); } int OutputDebugStringF(const char* pszFormat, ...) { int ret = 0; // Returns total number of characters written if (fPrintToConsole) { // print to console va_list arg_ptr; va_start(arg_ptr, pszFormat); ret += vprintf(pszFormat, arg_ptr); va_end(arg_ptr); } else if (!fPrintToDebugger) { static bool fStartedNewLine = true; boost::call_once(&DebugPrintInit, debugPrintInitFlag); if (fileout == NULL) return ret; boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); // reopen the log file, if requested if (fReopenDebugLog) { fReopenDebugLog = false; boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL) setbuf(fileout, NULL); // unbuffered } // Debug print useful for profiling if (fLogTimestamps && fStartedNewLine) ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str()); if (pszFormat[strlen(pszFormat) - 1] == '\n') fStartedNewLine = true; else fStartedNewLine = false; va_list arg_ptr; va_start(arg_ptr, pszFormat); ret += vfprintf(fileout, pszFormat, arg_ptr); va_end(arg_ptr); } #ifdef WIN32 if (fPrintToDebugger) { static CCriticalSection cs_OutputDebugStringF; // accumulate and output a line at a time { LOCK(cs_OutputDebugStringF); static std::string buffer; va_list arg_ptr; va_start(arg_ptr, pszFormat); buffer += vstrprintf(pszFormat, arg_ptr); va_end(arg_ptr); int line_start = 0, line_end; while((line_end = buffer.find('\n', line_start)) != -1) { OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str()); line_start = line_end + 1; ret += line_end-line_start; } buffer.erase(0, line_start); } } #endif return ret; } string vstrprintf(const char *format, va_list ap) { char buffer[50000]; char* p = buffer; int limit = sizeof(buffer); int ret; loop { va_list arg_ptr; va_copy(arg_ptr, ap); #ifdef WIN32 ret = _vsnprintf(p, limit, format, arg_ptr); #else ret = vsnprintf(p, limit, format, arg_ptr); #endif va_end(arg_ptr); if (ret >= 0 && ret < limit) break; if (p != buffer) delete[] p; limit *= 2; p = new char[limit]; if (p == NULL) throw std::bad_alloc(); } string str(p, p+ret); if (p != buffer) delete[] p; return str; } string real_strprintf(const char *format, int dummy, ...) { va_list arg_ptr; va_start(arg_ptr, dummy); string str = vstrprintf(format, arg_ptr); va_end(arg_ptr); return str; } string real_strprintf(const std::string &format, int dummy, ...) { va_list arg_ptr; va_start(arg_ptr, dummy); string str = vstrprintf(format.c_str(), arg_ptr); va_end(arg_ptr); return str; } bool error(const char *format, ...) { va_list arg_ptr; va_start(arg_ptr, format); std::string str = vstrprintf(format, arg_ptr); va_end(arg_ptr); printf("ERROR: %s\n", str.c_str()); return false; } void ParseString(const string& str, char c, vector<string>& v) { if (str.empty()) return; string::size_type i1 = 0; string::size_type i2; loop { i2 = str.find(c, i1); if (i2 == str.npos) { v.push_back(str.substr(i1)); return; } v.push_back(str.substr(i1, i2-i1)); i1 = i2+1; } } string FormatMoney(int64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. int64 n_abs = (n > 0 ? n : -n); int64 quotient = n_abs/COIN; int64 remainder = n_abs%COIN; string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder); // Right-trim excess zeros before the decimal point: int nTrim = 0; for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i) ++nTrim; if (nTrim) str.erase(str.size()-nTrim, nTrim); if (n < 0) str.insert((unsigned int)0, 1, '-'); else if (fPlus && n > 0) str.insert((unsigned int)0, 1, '+'); return str; } bool ParseMoney(const string& str, int64& nRet) { return ParseMoney(str.c_str(), nRet); } bool ParseMoney(const char* pszIn, int64& nRet) { string strWhole; int64 nUnits = 0; const char* p = pszIn; while (isspace(*p)) p++; for (; *p; p++) { if (*p == '.') { p++; int64 nMult = CENT*10; while (isdigit(*p) && (nMult > 0)) { nUnits += nMult * (*p++ - '0'); nMult /= 10; } break; } if (isspace(*p)) break; if (!isdigit(*p)) return false; strWhole.insert(strWhole.end(), *p); } for (; *p; p++) if (!isspace(*p)) return false; if (strWhole.size() > 10) // guard against 63 bit overflow return false; if (nUnits < 0 || nUnits > COIN) return false; int64 nWhole = atoi64(strWhole); int64 nValue = nWhole*COIN + nUnits; nRet = nValue; return true; } // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything // even possibly remotely dangerous like & or > static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@"); string SanitizeString(const string& str) { string strResult; for (std::string::size_type i = 0; i < str.size(); i++) { if (safeChars.find(str[i]) != std::string::npos) strResult.push_back(str[i]); } return strResult; } static const signed char phexdigit[256] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, }; bool IsHex(const string& str) { BOOST_FOREACH(unsigned char c, str) { if (phexdigit[c] < 0) return false; } return (str.size() > 0) && (str.size()%2 == 0); } vector<unsigned char> ParseHex(const char* psz) { // convert hex dump to vector vector<unsigned char> vch; loop { while (isspace(*psz)) psz++; signed char c = phexdigit[(unsigned char)*psz++]; if (c == (signed char)-1) break; unsigned char n = (c << 4); c = phexdigit[(unsigned char)*psz++]; if (c == (signed char)-1) break; n |= c; vch.push_back(n); } return vch; } vector<unsigned char> ParseHex(const string& str) { return ParseHex(str.c_str()); } static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet) { // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set if (name.find("-no") == 0) { std::string positive("-"); positive.append(name.begin()+3, name.end()); if (mapSettingsRet.count(positive) == 0) { bool value = !GetBoolArg(name); mapSettingsRet[positive] = (value ? "1" : "0"); } } } void ParseParameters(int argc, const char* const argv[]) { mapArgs.clear(); mapMultiArgs.clear(); for (int i = 1; i < argc; i++) { std::string str(argv[i]); std::string strValue; size_t is_index = str.find('='); if (is_index != std::string::npos) { strValue = str.substr(is_index+1); str = str.substr(0, is_index); } #ifdef WIN32 boost::to_lower(str); if (boost::algorithm::starts_with(str, "/")) str = "-" + str.substr(1); #endif if (str[0] != '-') break; mapArgs[str] = strValue; mapMultiArgs[str].push_back(strValue); } // New 0.6 features: BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs) { string name = entry.first; // interpret --foo as -foo (as long as both are not set) if (name.find("--") == 0) { std::string singleDash(name.begin()+1, name.end()); if (mapArgs.count(singleDash) == 0) mapArgs[singleDash] = entry.second; name = singleDash; } // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set InterpretNegativeSetting(name, mapArgs); } } std::string GetArg(const std::string& strArg, const std::string& strDefault) { if (mapArgs.count(strArg)) return mapArgs[strArg]; return strDefault; } int64 GetArg(const std::string& strArg, int64 nDefault) { if (mapArgs.count(strArg)) return atoi64(mapArgs[strArg]); return nDefault; } bool GetBoolArg(const std::string& strArg, bool fDefault) { if (mapArgs.count(strArg)) { if (mapArgs[strArg].empty()) return true; return (atoi(mapArgs[strArg]) != 0); } return fDefault; } bool SoftSetArg(const std::string& strArg, const std::string& strValue) { if (mapArgs.count(strArg)) return false; mapArgs[strArg] = strValue; return true; } bool SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } string EncodeBase64(const unsigned char* pch, size_t len) { static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; string strRet=""; strRet.reserve((len+2)/3*4); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase64[enc >> 2]; left = (enc & 3) << 4; mode = 1; break; case 1: // we have two bits strRet += pbase64[left | (enc >> 4)]; left = (enc & 15) << 2; mode = 2; break; case 2: // we have four bits strRet += pbase64[left | (enc >> 6)]; strRet += pbase64[enc & 63]; mode = 0; break; } } if (mode) { strRet += pbase64[left]; strRet += '='; if (mode == 1) strRet += '='; } return strRet; } string EncodeBase64(const string& str) { return EncodeBase64((const unsigned char*)str.c_str(), str.size()); } vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid) { static const int decode64_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; vector<unsigned char> vchRet; vchRet.reserve(strlen(p)*3/4); int mode = 0; int left = 0; while (1) { int dec = decode64_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 6 left = dec; mode = 1; break; case 1: // we have 6 bits and keep 4 vchRet.push_back((left<<2) | (dec>>4)); left = dec & 15; mode = 2; break; case 2: // we have 4 bits and get 6, we keep 2 vchRet.push_back((left<<4) | (dec>>2)); left = dec & 3; mode = 3; break; case 3: // we have 2 bits and get 6 vchRet.push_back((left<<6) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 4n base64 characters processed: ok break; case 1: // 4n+1 base64 character processed: impossible *pfInvalid = true; break; case 2: // 4n+2 base64 characters processed: require '==' if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1) *pfInvalid = true; break; case 3: // 4n+3 base64 characters processed: require '=' if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } string DecodeBase64(const string& str) { vector<unsigned char> vchRet = DecodeBase64(str.c_str()); return string((const char*)&vchRet[0], vchRet.size()); } string EncodeBase32(const unsigned char* pch, size_t len) { static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; string strRet=""; strRet.reserve((len+4)/5*8); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase32[enc >> 3]; left = (enc & 7) << 2; mode = 1; break; case 1: // we have three bits strRet += pbase32[left | (enc >> 6)]; strRet += pbase32[(enc >> 1) & 31]; left = (enc & 1) << 4; mode = 2; break; case 2: // we have one bit strRet += pbase32[left | (enc >> 4)]; left = (enc & 15) << 1; mode = 3; break; case 3: // we have four bits strRet += pbase32[left | (enc >> 7)]; strRet += pbase32[(enc >> 2) & 31]; left = (enc & 3) << 3; mode = 4; break; case 4: // we have two bits strRet += pbase32[left | (enc >> 5)]; strRet += pbase32[enc & 31]; mode = 0; } } static const int nPadding[5] = {0, 6, 4, 3, 1}; if (mode) { strRet += pbase32[left]; for (int n=0; n<nPadding[mode]; n++) strRet += '='; } return strRet; } string EncodeBase32(const string& str) { return EncodeBase32((const unsigned char*)str.c_str(), str.size()); } vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid) { static const int decode32_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; vector<unsigned char> vchRet; vchRet.reserve((strlen(p))*5/8); int mode = 0; int left = 0; while (1) { int dec = decode32_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 5 left = dec; mode = 1; break; case 1: // we have 5 bits and keep 2 vchRet.push_back((left<<3) | (dec>>2)); left = dec & 3; mode = 2; break; case 2: // we have 2 bits and keep 7 left = left << 5 | dec; mode = 3; break; case 3: // we have 7 bits and keep 4 vchRet.push_back((left<<1) | (dec>>4)); left = dec & 15; mode = 4; break; case 4: // we have 4 bits, and keep 1 vchRet.push_back((left<<4) | (dec>>1)); left = dec & 1; mode = 5; break; case 5: // we have 1 bit, and keep 6 left = left << 5 | dec; mode = 6; break; case 6: // we have 6 bits, and keep 3 vchRet.push_back((left<<2) | (dec>>3)); left = dec & 7; mode = 7; break; case 7: // we have 3 bits, and keep 0 vchRet.push_back((left<<5) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 8n base32 characters processed: ok break; case 1: // 8n+1 base32 characters processed: impossible case 3: // +3 case 6: // +6 *pfInvalid = true; break; case 2: // 8n+2 base32 characters processed: require '======' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1) *pfInvalid = true; break; case 4: // 8n+4 base32 characters processed: require '====' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1) *pfInvalid = true; break; case 5: // 8n+5 base32 characters processed: require '===' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1) *pfInvalid = true; break; case 7: // 8n+7 base32 characters processed: require '=' if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } string DecodeBase32(const string& str) { vector<unsigned char> vchRet = DecodeBase32(str.c_str()); return string((const char*)&vchRet[0], vchRet.size()); } bool WildcardMatch(const char* psz, const char* mask) { loop { switch (*mask) { case '\0': return (*psz == '\0'); case '*': return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask)); case '?': if (*psz == '\0') return false; break; default: if (*psz != *mask) return false; break; } psz++; mask++; } } bool WildcardMatch(const string& str, const string& mask) { return WildcardMatch(str.c_str(), mask.c_str()); } static std::string FormatException(std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(NULL, pszModule, sizeof(pszModule)); #else const char* pszModule = "blizzardcoin"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void LogException(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n%s", message.c_str()); } void PrintException(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n\n************************\n%s\n", message.c_str()); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); strMiscWarning = message; throw; } void PrintExceptionContinue(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n\n************************\n%s\n", message.c_str()); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); strMiscWarning = message; } boost::filesystem::path GetDefaultDataDir() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin // Mac: ~/Library/Application Support/Bitcoin // Unix: ~/.bitcoin #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "Blizzardcoin"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac pathRet /= "Library/Application Support"; fs::create_directory(pathRet); return pathRet / "Blizzardcoin"; #else // Unix return pathRet / ".blizzardcoin"; #endif #endif } const boost::filesystem::path &GetDataDir(bool fNetSpecific) { namespace fs = boost::filesystem; static fs::path pathCached[2]; static CCriticalSection csPathCached; fs::path &path = pathCached[fNetSpecific]; // This can be called during exceptions by printf, so we cache the // value so we don't have to do memory allocations after that. if (fCachedPath[fNetSpecific]) return path; LOCK(csPathCached); if (mapArgs.count("-datadir")) { path = fs::system_complete(mapArgs["-datadir"]); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific && GetBoolArg("-testnet", false)) path /= "testnet3"; fs::create_directories(path); fCachedPath[fNetSpecific] = true; return path; } boost::filesystem::path GetConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-conf", "blizzardcoin.conf")); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile; return pathConfigFile; } void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()) return; // No bitcoin.conf file is OK // clear path cache after loading config file fCachedPath[0] = fCachedPath[1] = false; set<string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override bitcoin.conf string strKey = string("-") + it->string_key; if (mapSettingsRet.count(strKey) == 0) { mapSettingsRet[strKey] = it->value[0]; // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set) InterpretNegativeSetting(strKey, mapSettingsRet); } mapMultiSettingsRet[strKey].push_back(it->value[0]); } } boost::filesystem::path GetPidFile() { boost::filesystem::path pathPidFile(GetArg("-pid", "blizzardcoind.pid")); if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile; return pathPidFile; } #ifndef WIN32 void CreatePidFile(const boost::filesystem::path &path, pid_t pid) { FILE* file = fopen(path.string().c_str(), "w"); if (file) { fprintf(file, "%d\n", pid); fclose(file); } } #endif bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest) { #ifdef WIN32 return MoveFileExA(src.string().c_str(), dest.string().c_str(), MOVEFILE_REPLACE_EXISTING); #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } void FileCommit(FILE *fileout) { fflush(fileout); // harmless if redundantly called #ifdef WIN32 _commit(_fileno(fileout)); #else #if defined(__linux__) || defined(__NetBSD__) fdatasync(fileno(fileout)); #elif defined(__APPLE__) && defined(F_FULLFSYNC) fcntl(fileno(fileout), F_FULLFSYNC, 0); #else fsync(fileno(fileout)); #endif #endif } int GetFilesize(FILE* file) { int nSavePos = ftell(file); int nFilesize = -1; if (fseek(file, 0, SEEK_END) == 0) nFilesize = ftell(file); fseek(file, nSavePos, SEEK_SET); return nFilesize; } bool TruncateFile(FILE *file, unsigned int length) { #if defined(WIN32) return _chsize(_fileno(file), length) == 0; #else return ftruncate(fileno(file), length) == 0; #endif } // this function tries to raise the file descriptor limit to the requested number. // It returns the actual file descriptor limit (which may be more or less than nMinFD) int RaiseFileDescriptorLimit(int nMinFD) { #if defined(WIN32) return 2048; #else struct rlimit limitFD; if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) { if (limitFD.rlim_cur < (rlim_t)nMinFD) { limitFD.rlim_cur = nMinFD; if (limitFD.rlim_cur > limitFD.rlim_max) limitFD.rlim_cur = limitFD.rlim_max; setrlimit(RLIMIT_NOFILE, &limitFD); getrlimit(RLIMIT_NOFILE, &limitFD); } return limitFD.rlim_cur; } return nMinFD; // getrlimit failed, assume it's fine #endif } // this function tries to make a particular range of a file allocated (corresponding to disk space) // it is advisory, and the range specified in the arguments will never contain live data void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) { #if defined(WIN32) // Windows-specific version HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); LARGE_INTEGER nFileSize; int64 nEndPos = (int64)offset + length; nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF; nFileSize.u.HighPart = nEndPos >> 32; SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN); SetEndOfFile(hFile); #elif defined(MAC_OSX) // OSX specific version fstore_t fst; fst.fst_flags = F_ALLOCATECONTIG; fst.fst_posmode = F_PEOFPOSMODE; fst.fst_offset = 0; fst.fst_length = (off_t)offset + length; fst.fst_bytesalloc = 0; if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) { fst.fst_flags = F_ALLOCATEALL; fcntl(fileno(file), F_PREALLOCATE, &fst); } ftruncate(fileno(file), fst.fst_length); #elif defined(__linux__) // Version using posix_fallocate off_t nEndPos = (off_t)offset + length; posix_fallocate(fileno(file), 0, nEndPos); #else // Fallback version // TODO: just write one byte per block static const char buf[65536] = {}; fseek(file, offset, SEEK_SET); while (length > 0) { unsigned int now = 65536; if (length < now) now = length; fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway length -= now; } #endif } void ShrinkDebugFile() { // Scroll debug.log if it's getting too big boost::filesystem::path pathLog = GetDataDir() / "debug.log"; FILE* file = fopen(pathLog.string().c_str(), "r"); if (file && GetFilesize(file) > 10 * 1000000) { // Restart the file with some of the end char pch[200000]; fseek(file, -sizeof(pch), SEEK_END); int nBytes = fread(pch, 1, sizeof(pch), file); fclose(file); file = fopen(pathLog.string().c_str(), "w"); if (file) { fwrite(pch, 1, nBytes, file); fclose(file); } } else if(file != NULL) fclose(file); } // // "Never go to sea with two chronometers; take one or three." // Our three time sources are: // - System clock // - Median of other nodes clocks // - The user (asking the user to fix the system clock if the first two disagree) // static int64 nMockTime = 0; // For unit testing int64 GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64 nMockTimeIn) { nMockTime = nMockTimeIn; } static int64 nTimeOffset = 0; int64 GetTimeOffset() { return nTimeOffset; } int64 GetAdjustedTime() { return GetTime() + GetTimeOffset(); } void AddTimeData(const CNetAddr& ip, int64 nTime) { int64 nOffsetSample = nTime - GetTime(); // Ignore duplicates static set<CNetAddr> setKnown; if (!setKnown.insert(ip).second) return; // Add data vTimeOffsets.input(nOffsetSample); printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64 nMedian = vTimeOffsets.median(); std::vector<int64> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 35 * 60) // Blizzardcoin: changed maximum adjust to 35 mins to avoid letting peers change our time too much in case of an attack. { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH(int64 nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Blizzardcoin will not work properly."); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } if (fDebug) { BOOST_FOREACH(int64 n, vSorted) printf("%+"PRI64d" ", n); printf("| "); } printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60); } } uint32_t insecure_rand_Rz = 11; uint32_t insecure_rand_Rw = 11; void seed_insecure_rand(bool fDeterministic) { //The seed values have some unlikely fixed points which we avoid. if(fDeterministic) { insecure_rand_Rz = insecure_rand_Rw = 11; } else { uint32_t tmp; do { RAND_bytes((unsigned char*)&tmp, 4); } while(tmp == 0 || tmp == 0x9068ffffU); insecure_rand_Rz = tmp; do { RAND_bytes((unsigned char*)&tmp, 4); } while(tmp == 0 || tmp == 0x464fffffU); insecure_rand_Rw = tmp; } } string FormatVersion(int nVersion) { if (nVersion%100 == 0) return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100); else return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100); } string FormatFullVersion() { return CLIENT_BUILD; } // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014) std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) ss << "(" << boost::algorithm::join(comments, "; ") << ")"; ss << "/"; return ss.str(); } #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate) { namespace fs = boost::filesystem; char pszPath[MAX_PATH] = ""; if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n"); return fs::path(""); } #endif boost::filesystem::path GetTempPath() { #if BOOST_FILESYSTEM_VERSION == 3 return boost::filesystem::temp_directory_path(); #else // TODO: remove when we don't support filesystem v2 anymore boost::filesystem::path path; #ifdef WIN32 char pszPath[MAX_PATH] = ""; if (GetTempPathA(MAX_PATH, pszPath)) path = boost::filesystem::path(pszPath); #else path = boost::filesystem::path("/tmp"); #endif if (path.empty() || !boost::filesystem::is_directory(path)) { printf("GetTempPath(): failed to find temp path\n"); return boost::filesystem::path(""); } return path; #endif } void runCommand(std::string strCommand) { int nErr = ::system(strCommand.c_str()); if (nErr) printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr); } void RenameThread(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__)) // TODO: This is currently disabled because it needs to be verified to work // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be // removed. pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED) // pthread_setname_np is XCode 10.6-and-later #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 pthread_setname_np(name); #endif #else // Prevent warnings for unused parameters... (void)name; #endif } bool NewThread(void(*pfn)(void*), void* parg) { try { boost::thread(pfn, parg); // thread detaches when out of scope } catch(boost::thread_resource_error &e) { printf("Error creating thread: %s\n", e.what()); return false; } return true; }
blizzardcoin/blizzardcoin
src/util.cpp
C++
mit
43,245
use ::structopt::StructOpt; /// /// The structure of the commands for the app. /// /// A large amount of this is generated by StructOpt. /// See that project for how to write large amounts of this. /// /// The gist however is that we make a struct that will hold /// all of our arguments. Commands are then parsed, and then /// turned into this struct. /// #[derive(StructOpt, Debug)] #[structopt(name = "ls-pretty", about = "Like ls, but pretty.")] pub struct Args { /// Enable logging, use multiple `v`s to increase verbosity. #[structopt(short = "a", long = "all", help = "Set to show all hidden files and directories.")] pub all: bool, /// Set the minimum width of the directory column. #[structopt(default_value = "0", short = "d", long = "directory-width", help = "Minimum width of the directory column.")] pub dirs_width: usize, /// Optional path to the folder we are going to perform the list on. #[structopt(default_value = ".", help = "Set to show all hidden files and directories.")] pub path: String, } impl Args { /// /// Builds a new args from the main arguments given. /// pub fn new_from_args() -> Args { return Args::from_args(); } }
joe-askattest/ls-pretty
src/args.rs
Rust
mit
1,225
//repl read eval print loop console.log('start');
WakeUpPig/node2015
1.node/start.js
JavaScript
mit
58
import React from 'react'; import Document, { Head, Main, NextScript } from 'next/document'; import { ServerStyleSheets } from '@material-ui/core/styles'; import theme from '../components/theme'; export default class MyDocument extends Document { render() { return ( <html lang="en"> <Head> <meta charSet="utf-8" /> <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no" /> {/* PWA primary color */} <meta name="theme-color" content={theme.palette.primary.main} /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:300,300i,400,400i,600,600i,700,700i&display=swap" /> </Head> <body> <Main /> <NextScript /> </body> </html> ); } } MyDocument.getInitialProps = async ctx => { // Resolution order // // On the server: // 1. app.getInitialProps // 2. page.getInitialProps // 3. document.getInitialProps // 4. app.render // 5. page.render // 6. document.render // // On the server with error: // 1. document.getInitialProps // 2. app.render // 3. page.render // 4. document.render // // On the client // 1. app.getInitialProps // 2. page.getInitialProps // 3. app.render // 4. page.render // Render app and page and get the context of the page with collected side effects. const sheets = new ServerStyleSheets(); const originalRenderPage = ctx.renderPage; ctx.renderPage = () => originalRenderPage({ enhanceApp: App => props => sheets.collect(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, // Styles fragment is rendered after the app and page rendering finish. styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()], }; };
gariasf/gariasf.com
pages/_document.tsx
TypeScript
mit
1,935
<div id="slideWrap1" class="slide_wrap"> <button type="button" class="btn_prev">prev</button> <button type="button" class="btn_next">next</button> <ul class="slide_list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </div> <div id="slideWrap2" class="slide_wrap"> <button type="button" class="btn_prev">prev</button> <button type="button" class="btn_next">next</button> <ul class="slide_list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> </ul> </div> <script> window.onload = function(){ (function($) { // doonam jquerySlider version 0.1 // $(selector).jquerySlider({ // currentNum:1 start view number // }); var plugin_name = "jquerySlider"; $.fn[plugin_name] = function(options) { var $element = $(this); var defaults = { currentNum:0 }; var opts = $.extend({}, $.fn[plugin_name].defaults, options); var list = $element.children(".slide_list").find("li"); var listLen = list.length; var listWidth = Math.round($element.children(".slide_list").width()); var consTructors = { init : function() { $btnNext = $element.children(".btn_next"); $btnPrev = $element.children(".btn_prev"); consTructors.sliderSet(); consTructors.btnControler(); }, btnControler : function() { $btnNext.on("click", function(e){ e.preventDefault(); consTructors.sliderAction("next"); }); $btnPrev.on("click", function(e){ e.preventDefault(); consTructors.sliderAction("prev"); }); }, sliderSet : function(){ for ( var i=0 ; i<listLen ; i++){ $(list[i]).css({left:listWidth*(i-opts.currentNum)}); } }, sliderAction : function(strChk){ if (strChk=="next"){ if (opts.currentNum != listLen-1){ opts.currentNum = opts.currentNum+1; consTructors.slideContents(); } }else if (strChk=="prev"){ if(opts.currentNum != 0){ opts.currentNum = opts.currentNum-1; consTructors.slideContents(); } } }, slideContents : function (){ for ( var i=0 ; i<listLen ; i++){ $(list[i]).stop().animate({left:listWidth*(i-opts.currentNum)}); } } } consTructors.init(); } })(jQuery); $("#slideWrap1").jquerySlider({ currentNum:0 }); $("#slideWrap2").jquerySlider({ currentNum:2 }); /*(function(global, $) { var plugin_name = "jquerySlider"; var $element, opts, $btnNext, $btnPrev; var consTructors = { init : function() { $btnNext = $element.children(".btn_next"); $btnPrev = $element.children(".btn_prev"); consTructors.sliderSet(); consTructors.btnControler(opts); }, btnControler : function(opts) { $btnNext.on("click", function(e){ e.preventDefault(); console.log(opts.currentNum) }); }, sliderSet : function(){ var list = $element.children(".slide_list").find("li"); var listLen = list.length; var listWidth = Math.round(list.width()); for ( var i=0 ; i<listLen ; i++){ $(list[i]).css({left:listWidth*(i-opts.currentNum)}); console.log(listWidth*(i-opts.currentNum)) } }, sliderAction : function(){ } } $.fn[plugin_name] = function(options) { var $this = this; return $.each($this, function(index, el){ opts = $.extend({}, $.fn[plugin_name].defaults, options); $element = $this.eq(index); consTructors.init(); }); }; $.fn[plugin_name].defaults = { currentNum:0 }; })(window, window.jQuery); $("#slideWrap1").jquerySlider({ currentNum:4 }); $("#slideWrap2").jquerySlider({ currentNum:1 });*/ }; </script>
doolife/CODEIGNITER
views/brand/info.php
PHP
mit
5,412
#ifndef ODD_64_BIT # if defined(__amd64) || defined(__x86_64) || defined(_WIN64) || defined(_Wp64) # define ODD_64_BIT 1 # else # define ODD_64_BIT 0 # endif #endif
ioddly/odd-old
odd/config.hpp
C++
mit
167
# Pipedrive.FiltersApi All URIs are relative to *https://api.pipedrive.com/v1* Method | HTTP request | Description ------------- | ------------- | ------------- [**addFilter**](FiltersApi.md#addFilter) | **POST** /filters | Add a new filter [**deleteFilter**](FiltersApi.md#deleteFilter) | **DELETE** /filters/{id} | Delete a filter [**deleteFilters**](FiltersApi.md#deleteFilters) | **DELETE** /filters | Delete multiple filters in bulk [**getFilter**](FiltersApi.md#getFilter) | **GET** /filters/{id} | Get one filter [**getFilterHelpers**](FiltersApi.md#getFilterHelpers) | **GET** /filters/helpers | Get all filter helpers [**getFilters**](FiltersApi.md#getFilters) | **GET** /filters | Get all filters [**updateFilter**](FiltersApi.md#updateFilter) | **PUT** /filters/{id} | Update filter ## addFilter > FiltersPostResponse addFilter(opts) Add a new filter Adds a new filter, returns the ID upon success. Note that in the conditions JSON object only one first-level condition group is supported, and it must be glued with &#39;AND&#39;, and only two second level condition groups are supported of which one must be glued with &#39;AND&#39; and the second with &#39;OR&#39;. Other combinations do not work (yet) but the syntax supports introducing them in future. For more information, see the tutorial for &lt;a href&#x3D;\&quot;https://pipedrive.readme.io/docs/adding-a-filter\&quot; target&#x3D;\&quot;_blank\&quot; rel&#x3D;\&quot;noopener noreferrer\&quot;&gt;adding a filter&lt;/a&gt;. ### Example ```javascript import Pipedrive from 'pipedrive'; let defaultClient = Pipedrive.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //api_key.apiKeyPrefix = 'Token'; // Configure OAuth2 access token for authorization: oauth2 let oauth2 = defaultClient.authentications['oauth2']; oauth2.accessToken = 'YOUR ACCESS TOKEN'; let apiInstance = new Pipedrive.FiltersApi(); let opts = Pipedrive.AddFilterRequest.constructFromObject({ // Properties that you want to update }); apiInstance.addFilter(opts).then((data) => { console.log('API called successfully. Returned data: ' + data); }, (error) => { console.error(error); }); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **addFilterRequest** | [**AddFilterRequest**](AddFilterRequest.md)| | [optional] ### Return type [**FiltersPostResponse**](FiltersPostResponse.md) ### Authorization [api_key](../README.md#api_key), [oauth2](../README.md#oauth2) ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json ## deleteFilter > FiltersDeleteResponse deleteFilter(id) Delete a filter Marks a filter as deleted. ### Example ```javascript import Pipedrive from 'pipedrive'; let defaultClient = Pipedrive.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //api_key.apiKeyPrefix = 'Token'; // Configure OAuth2 access token for authorization: oauth2 let oauth2 = defaultClient.authentications['oauth2']; oauth2.accessToken = 'YOUR ACCESS TOKEN'; let apiInstance = new Pipedrive.FiltersApi(); let id = 56; // Number | The ID of the filter apiInstance.deleteFilter(id).then((data) => { console.log('API called successfully. Returned data: ' + data); }, (error) => { console.error(error); }); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **id** | **Number**| The ID of the filter | ### Return type [**FiltersDeleteResponse**](FiltersDeleteResponse.md) ### Authorization [api_key](../README.md#api_key), [oauth2](../README.md#oauth2) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ## deleteFilters > FiltersBulkDeleteResponse deleteFilters(ids) Delete multiple filters in bulk Marks multiple filters as deleted. ### Example ```javascript import Pipedrive from 'pipedrive'; let defaultClient = Pipedrive.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //api_key.apiKeyPrefix = 'Token'; // Configure OAuth2 access token for authorization: oauth2 let oauth2 = defaultClient.authentications['oauth2']; oauth2.accessToken = 'YOUR ACCESS TOKEN'; let apiInstance = new Pipedrive.FiltersApi(); let ids = "ids_example"; // String | The comma-separated filter IDs to delete apiInstance.deleteFilters(ids).then((data) => { console.log('API called successfully. Returned data: ' + data); }, (error) => { console.error(error); }); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ids** | **String**| The comma-separated filter IDs to delete | ### Return type [**FiltersBulkDeleteResponse**](FiltersBulkDeleteResponse.md) ### Authorization [api_key](../README.md#api_key), [oauth2](../README.md#oauth2) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ## getFilter > FiltersGetResponse getFilter(id) Get one filter Returns data about a specific filter. Note that this also returns the condition lines of the filter. ### Example ```javascript import Pipedrive from 'pipedrive'; let defaultClient = Pipedrive.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //api_key.apiKeyPrefix = 'Token'; // Configure OAuth2 access token for authorization: oauth2 let oauth2 = defaultClient.authentications['oauth2']; oauth2.accessToken = 'YOUR ACCESS TOKEN'; let apiInstance = new Pipedrive.FiltersApi(); let id = 56; // Number | The ID of the filter apiInstance.getFilter(id).then((data) => { console.log('API called successfully. Returned data: ' + data); }, (error) => { console.error(error); }); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **id** | **Number**| The ID of the filter | ### Return type [**FiltersGetResponse**](FiltersGetResponse.md) ### Authorization [api_key](../README.md#api_key), [oauth2](../README.md#oauth2) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ## getFilterHelpers > Object getFilterHelpers() Get all filter helpers Returns all supported filter helpers. It helps to know what conditions and helpers are available when you want to &lt;a href&#x3D;\&quot;/docs/api/v1/Filters#addFilter\&quot;&gt;add&lt;/a&gt; or &lt;a href&#x3D;\&quot;/docs/api/v1/Filters#updateFilter\&quot;&gt;update&lt;/a&gt; filters. For more information, see the tutorial for &lt;a href&#x3D;\&quot;https://pipedrive.readme.io/docs/adding-a-filter\&quot; target&#x3D;\&quot;_blank\&quot; rel&#x3D;\&quot;noopener noreferrer\&quot;&gt;adding a filter&lt;/a&gt;. ### Example ```javascript import Pipedrive from 'pipedrive'; let defaultClient = Pipedrive.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //api_key.apiKeyPrefix = 'Token'; let apiInstance = new Pipedrive.FiltersApi(); apiInstance.getFilterHelpers().then((data) => { console.log('API called successfully. Returned data: ' + data); }, (error) => { console.error(error); }); ``` ### Parameters This endpoint does not need any parameter. ### Return type **Object** ### Authorization [api_key](../README.md#api_key) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ## getFilters > FiltersBulkGetResponse getFilters(opts) Get all filters Returns data about all filters. ### Example ```javascript import Pipedrive from 'pipedrive'; let defaultClient = Pipedrive.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //api_key.apiKeyPrefix = 'Token'; // Configure OAuth2 access token for authorization: oauth2 let oauth2 = defaultClient.authentications['oauth2']; oauth2.accessToken = 'YOUR ACCESS TOKEN'; let apiInstance = new Pipedrive.FiltersApi(); let opts = { 'type': new Pipedrive.FilterType() // FilterType | The types of filters to fetch }; apiInstance.getFilters(opts).then((data) => { console.log('API called successfully. Returned data: ' + data); }, (error) => { console.error(error); }); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **type** | [**FilterType**](.md)| The types of filters to fetch | [optional] ### Return type [**FiltersBulkGetResponse**](FiltersBulkGetResponse.md) ### Authorization [api_key](../README.md#api_key), [oauth2](../README.md#oauth2) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ## updateFilter > FiltersPostResponse updateFilter(id, opts) Update filter Updates an existing filter. ### Example ```javascript import Pipedrive from 'pipedrive'; let defaultClient = Pipedrive.ApiClient.instance; // Configure API key authorization: api_key let api_key = defaultClient.authentications['api_key']; api_key.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //api_key.apiKeyPrefix = 'Token'; // Configure OAuth2 access token for authorization: oauth2 let oauth2 = defaultClient.authentications['oauth2']; oauth2.accessToken = 'YOUR ACCESS TOKEN'; let apiInstance = new Pipedrive.FiltersApi(); let id = 56; // Number | The ID of the filter let opts = Pipedrive.UpdateFilterRequest.constructFromObject({ // Properties that you want to update }); apiInstance.updateFilter(id, opts).then((data) => { console.log('API called successfully. Returned data: ' + data); }, (error) => { console.error(error); }); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **id** | **Number**| The ID of the filter | **updateFilterRequest** | [**UpdateFilterRequest**](UpdateFilterRequest.md)| | [optional] ### Return type [**FiltersPostResponse**](FiltersPostResponse.md) ### Authorization [api_key](../README.md#api_key), [oauth2](../README.md#oauth2) ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json
pipedrive/client-nodejs
docs/FiltersApi.md
Markdown
mit
11,139
"use strict"; class FeatsPage extends ListPage { constructor () { const pageFilter = new PageFilterFeats(); super({ dataSource: "data/feats.json", pageFilter, listClass: "feats", sublistClass: "subfeats", dataProps: ["feat"], isPreviewable: true, }); } getListItem (feat, ftI, isExcluded) { this._pageFilter.mutateAndAddToFilters(feat, isExcluded); const eleLi = document.createElement("div"); eleLi.className = `lst__row flex-col ${isExcluded ? "lst__row--blacklisted" : ""}`; const source = Parser.sourceJsonToAbv(feat.source); const hash = UrlUtil.autoEncodeHash(feat); eleLi.innerHTML = `<a href="#${hash}" class="lst--border lst__row-inner"> <span class="col-0-3 px-0 flex-vh-center lst__btn-toggle-expand self-flex-stretch">[+]</span> <span class="bold col-3-5 px-1">${feat.name}</span> <span class="col-3-5 ${feat._slAbility === VeCt.STR_NONE ? "list-entry-none " : ""}">${feat._slAbility}</span> <span class="col-3 ${feat._slPrereq === VeCt.STR_NONE ? "list-entry-none " : ""}">${feat._slPrereq}</span> <span class="source col-1-7 text-center ${Parser.sourceJsonToColor(feat.source)} pr-0" title="${Parser.sourceJsonToFull(feat.source)}" ${BrewUtil.sourceJsonToStyle(feat.source)}>${source}</span> </a> <div class="flex ve-hidden relative lst__wrp-preview"> <div class="vr-0 absolute lst__vr-preview"></div> <div class="flex-col py-3 ml-4 lst__wrp-preview-inner"></div> </div>`; const listItem = new ListItem( ftI, eleLi, feat.name, { hash, source, ability: feat._slAbility, prerequisite: feat._slPrereq, }, { uniqueId: feat.uniqueId ? feat.uniqueId : ftI, isExcluded, }, ); eleLi.addEventListener("click", (evt) => this._list.doSelect(listItem, evt)); eleLi.addEventListener("contextmenu", (evt) => ListUtil.openContextMenu(evt, this._list, listItem)); return listItem; } handleFilterChange () { const f = this._filterBox.getValues(); this._list.filter(item => this._pageFilter.toDisplay(f, this._dataList[item.ix])); FilterBox.selectFirstVisible(this._dataList); } getSublistItem (feat, pinId) { const hash = UrlUtil.autoEncodeHash(feat); const $ele = $(`<div class="lst__row lst__row--sublist flex-col"> <a href="#${hash}" class="lst--border lst__row-inner"> <span class="bold col-4 pl-0">${feat.name}</span> <span class="col-4 ${feat._slAbility === VeCt.STR_NONE ? "list-entry-none" : ""}">${feat._slAbility}</span> <span class="col-4 ${feat._slPrereq === VeCt.STR_NONE ? "list-entry-none" : ""} pr-0">${feat._slPrereq}</span> </a> </div>`) .contextmenu(evt => ListUtil.openSubContextMenu(evt, listItem)) .click(evt => ListUtil.sublist.doSelect(listItem, evt)); const listItem = new ListItem( pinId, $ele, feat.name, { hash, ability: feat._slAbility, prerequisite: feat._slPrereq, }, ); return listItem; } doLoadHash (id) { const feat = this._dataList[id]; $("#pagecontent").empty().append(RenderFeats.$getRenderedFeat(feat)); ListUtil.updateSelected(); } async pDoLoadSubHash (sub) { sub = this._filterBox.setFromSubHashes(sub); await ListUtil.pSetFromSubHashes(sub); } } const featsPage = new FeatsPage(); window.addEventListener("load", () => featsPage.pOnLoad());
TheGiddyLimit/astranauta.github.io
js/feats.js
JavaScript
mit
3,311
jQuery(document).ready(function($){ var nameDefault = 'Your name...'; var emailDefault = 'Your email...'; var messageDefault = 'Your message...'; // Setting up existing forms setupforms(); function setupforms() { // Applying default values setupDefaultText('#name',nameDefault); setupDefaultText('#email',emailDefault); setupDefaultText('#message',messageDefault); // Focus / Blur check against defaults focusField('#name'); focusField('#email'); focusField('#message'); } function setupDefaultText(fieldID,fieldDefault) { $(fieldID).val(fieldDefault); $(fieldID).attr('data-default', fieldDefault); } function evalDefault(fieldID) { if($(fieldID).val() != $(fieldID).attr('data-default')) { return false; } else { return true; } } function hasDefaults(formType) { switch (formType) { case "contact" : if(evalDefault('#name') && evalDefault('#email') && evalDefault('#message')) { return true; } else { return false; } default : return false; } } function focusField(fieldID) { $(fieldID).focus(function(evaluation) { if(evalDefault(fieldID)) { $(fieldID).val(''); } }).blur(function(evaluation) { if(evalDefault(fieldID) || $(fieldID).val() === '') { $(fieldID).val($(fieldID).attr('data-default')); } }); } $('.button-submit').click(function(event) { event.preventDefault(); }); $('#submit-contact').bind('click', function(){ if(!hasDefaults('contact')) { $('#form-contact').submit(); } }); $("#form-contact").validate({ rules: { name: { required: true, minlength: 3 }, email: { required: true, email: true }, message: { required: true, minlength: 10 } }, messages: { name: { required: "Please enter your name.", minlength: "Name must have at least 3 characters." }, email: { required: "Please enter your email address.", email: "This is not a valid email address format." }, message: { required: "Please enter a message.", minlength: "Message must have at least 10 characters." } } }); function validateContact() { if(!$('#form-contact').valid()) { return false; } else { return true; } } $("#form-contact").ajaxForm({ beforeSubmit: validateContact, type: "POST", url: "assets/php/contact-form-process.php", data: $("#form-contact").serialize(), success: function(msg){ $("#form-message").ajaxComplete(function(event, request, settings){ if(msg == 'OK') // Message Sent? Show the 'Thank You' message { result = '<span class="form-message-success"><i class="icon-thumbs-up"></i> Your message was sent. Thank you!</span>'; clear = true; } else { result = '<span class="form-message-error"><i class="icon-thumbs-down"></i> ' + msg +'</span>'; clear = false; } $(this).html(result); if(clear == true) { $('#name').val(''); $('#email').val(''); $('#message').val(''); } }); } }); });
lightnin/lightnin.github.io
assets/js/jquery.validation.settings.js
JavaScript
mit
3,099
import {assert, should, test} from 'gs-testing'; import {filter} from './filter'; import {$pipe} from './pipe'; test('@tools/collect/operators/filter', () => { should('exclude items that do not pass the check function', () => { assert($pipe(new Set([1, 2, 3, 4]), filter(i => i % 2 === 0))).to.startWith([2, 4]); }); });
garysoed/gs-tools
src/collect/operators/filter.test.ts
TypeScript
mit
331
package seedu.tasklist.commons.core; import java.io.FileWriter; import java.io.IOException; import java.util.Objects; import java.util.logging.Level; import org.json.JSONException; import org.json.simple.JSONObject; import org.json.simple.parser.*; /** * Config values used by the app */ public class Config { public static final String DEFAULT_CONFIG_FILE = "config.json"; // Config values customizable through config file private String appTitle = "Lazyman's Friend"; private Level logLevel = Level.INFO; private String userPrefsFilePath = "preferences.json"; private String taskListFilePath = "data/tasklist.xml"; private String taskListName = "MyTaskList"; public Config() { } public String getAppTitle() { return appTitle; } public void setAppTitle(String appTitle) { this.appTitle = appTitle; } public Level getLogLevel() { return logLevel; } public void setLogLevel(Level logLevel) { this.logLevel = logLevel; } public String getUserPrefsFilePath() { return userPrefsFilePath; } public void setUserPrefsFilePath(String userPrefsFilePath) { this.userPrefsFilePath = userPrefsFilePath; } /* @@author A0135769N */ public String getTaskListFilePath() { return taskListFilePath; } // Method replaces the existing file path with the new file path specified by user. public void setTaskListFilePath(String taskListFilePath) throws JSONException, IOException, ParseException { JSONObject obj = new JSONObject(); obj.put("taskListFilePath", taskListFilePath); obj.put("userPrefsFilePath", "preferences.json"); obj.put("appTitle", "Lazyman's Friend"); obj.put("logLevel", "INFO"); obj.put("taskListName", "MyTaskList"); try (FileWriter file = new FileWriter("config.json")) { file.write(obj.toJSONString()); System.out.println("Successfully Copied JSON Object to File..."); System.out.println("\nJSON Object: " + obj); } this.taskListFilePath = taskListFilePath; } public String getTaskListName() { return taskListName; } public void setTaskListName(String taskListName) { this.taskListName = taskListName; } @Override public boolean equals(Object other) { if (other == this){ return true; } if (!(other instanceof Config)){ //this handles null as well. return false; } Config o = (Config)other; return Objects.equals(appTitle, o.appTitle) && Objects.equals(logLevel, o.logLevel) && Objects.equals(userPrefsFilePath, o.userPrefsFilePath) && Objects.equals(taskListFilePath, o.taskListFilePath) && Objects.equals(taskListName, o.taskListName); } @Override public int hashCode() { return Objects.hash(appTitle, logLevel, userPrefsFilePath, taskListFilePath, taskListName); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("App title : " + appTitle); sb.append("\nCurrent log level : " + logLevel); sb.append("\nPreference file Location : " + userPrefsFilePath); sb.append("\nLocal data file location : " + taskListFilePath); sb.append("\nTaskList name : " + taskListName); return sb.toString(); } }
CS2103AUG2016-T11-C1/main
src/main/java/seedu/tasklist/commons/core/Config.java
Java
mit
3,496
### lx-switch ```javascript { 'key': 'modelName', 'type': 'lx-switch', 'templateOptions': { 'label': 'A switch label', 'description': 'A switch help description', 'disabled': false, // ng-disabled 'checked': false, // ng-checked } } ``` Read more about [LumX switches](http://ui.lumapps.com/css/switches).
formly-js/angular-formly-templates-lumx
docs/switch.md
Markdown
mit
330
package main import ( "fmt" "io" "os" "github.com/jessevdk/go-flags" "bom" ) func addBom(r io.Reader, w io.Writer, target bom.BOM) { buf := make([]byte, 1024) c, _ := r.Read(buf) if c == 0 { return } b := bom.GetBom(buf) if b == bom.NOTBOM { w.Write([]byte(target)) } w.Write(buf[:c]) for { c, _ := r.Read(buf) if c == 0 { break } w.Write(buf[:c]) } } func removeBom(r io.Reader, w io.Writer, target bom.BOM) { buf := make([]byte, 1024) c, _ := r.Read(buf) if c == 0 { return } b := bom.GetBom(buf) if b == target { w.Write(buf[len(b):c]) } else { w.Write(buf[:c]) } for { c, _ := r.Read(buf) if c == 0 { break } w.Write(buf[:c]) } } func main() { var opts struct { Remove bool `short:"r" long:"remove" description:"remove bom."` Target string `short:"t" long:"target" default:"8" description:"target format (8|16le|16be|32le|32be)."` } parser := flags.NewParser(&opts, flags.Default) parser.Usage = "[OPTION]...[FILE]" args, err := parser.Parse() if err != nil { return } var target bom.BOM switch opts.Target { case "8": target = bom.UTF8 case "16le": target = bom.UTF16LE case "16be": target = bom.UTF16BE case "32le": target = bom.UTF32LE case "32be": target = bom.UTF32BE default: fmt.Fprintf(os.Stderr, "unknown target: %s\n", opts.Target) return } var r io.Reader = os.Stdin if len(args) > 0 && args[0] != "-" { f, err := os.Open(args[0]) if err != nil { fmt.Fprintf(os.Stderr, "cannot open file: %s\n", args[0]) return } defer f.Close() r = f } if opts.Remove { removeBom(r, os.Stdout, target) } else { addBom(r, os.Stdout, target) } }
makiuchi-d/bomber
src/bomber.go
GO
mit
1,682
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>透明度技巧</title> <style> div{ width:200px; height:200px; margin:20; background-color: hsl(120,56%,75%); } .demo1{ opacity: .8; background-image: -webkit-linear-gradient(top 45deg, #871F16, #A82AF2); background-image: linear-gradient(top 45deg,#871F16,#A82AF2); /*IE5~7*/ filter: alpha(opacity=0.8); /*IE8*/ -ms-filter:"progid:DXImageTransform.Microsoft.alpha(opacity=0.8)"; } .demo2{ opacity: .6; background-image: -webkit-linear-gradient(top right, #A22B84, #8DC393); background-image: linear-gradient(top right,#A22B84,#8DC393); filter: alpha(opacity=0.6); /*IE5~7*/ filter: alpha(opacity=0.6); /*IE8*/ -ms-filter:"progid:DXImageTransform.Microsoft.alpha(opacity=0.8)"; } .demo3{ opacity: .4; background-image: -webkit-linear-gradient(top left, #31A15E, #CF8F23); background-image: linear-gradient(top left,#A22B84,#8DC393); filter: alpha(opacity=0.4); /*IE5~7*/ filter: alpha(opacity=0.4); /*IE8*/ -ms-filter:"progid:DXImageTransform.Microsoft.alpha(opacity=0.8)"; } .demo4{ opacity: .3; background-image: -webkit-linear-gradient(90deg, #58A22B, #C0D5C2); background-image: linear-gradient(90deg,#58A22B, #C0D5C2); filter: alpha(opacity=0.3); /*IE5~7*/ filter: alpha(opacity=0.3); /*IE8*/ -ms-filter:"progid:DXImageTransform.Microsoft.alpha(opacity=0.8)"; } .demo5{ opacity: .2; background-image: -webkit-linear-gradient(135deg, #A2402B, #292F29); background-image: linear-gradient(135deg ,#A2402B, #292F29); filter: alpha(opacity=0.2); /*IE5~7*/ filter: alpha(opacity=0.2); /*IE8*/ -ms-filter:"progid:DXImageTransform.Microsoft.alpha(opacity=0.8)"; } </style> </head> <body> <div class="demo1"></div> <div class="demo2"></div> <div class="demo3"></div> <div class="demo4"></div> <div class="demo5"></div> </body> </html>
crperlin/Study
Book/图解CSS3核心技术与案例实战/opacity.html
HTML
mit
1,965
<html> <head> <title>Anna Krien's panel show appearances</title> <script type="text/javascript" src="../common.js"></script> <link rel="stylesheet" media="all" href="../style.css" type="text/css"/> <script type="text/javascript" src="../people.js"></script> <!--#include virtual="head.txt" --> </head> <body> <!--#include virtual="nav.txt" --> <div class="page"> <h1>Anna Krien's panel show appearances</h1> <p>Anna Krien has appeared in <span class="total">1</span> episodes between 2012-2012. Note that these appearances may be for more than one person if multiple people have the same name.</p> <div class="performerholder"> <table class="performer"> <tr style="vertical-align:bottom;"> <td><div style="height:100px;" class="performances female" title="1"></div><span class="year">2012</span></td> </tr> </table> </div> <ol class="episodes"> <li><strong>2012-09-10</strong> / <a href="../shows/qanda.html">Q&A</a></li> </ol> </div> </body> </html>
slowe/panelshows
people/ixlh4t8w.html
HTML
mit
976
module YAML # Load the document contained in +filename+. Returns the yaml contained in # +filename+ as a ruby object def self.load_stream_from_file filename File.open(filename, 'r:bom|utf-8') { |f| self.load_stream f, filename } end end
dmorrill10/dmorrill10-utils
lib/dmorrill10-utils/yaml.rb
Ruby
mit
249
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { # Explanation of Unidic tags: # https://www.gavo.t.u-tokyo.ac.jp/~mine/japanese/nlp+slp/UNIDIC_manual.pdf # Universal Dependencies Mapping: # http://universaldependencies.org/ja/overview/morphology.html # http://universaldependencies.org/ja/pos/all.html "記号,一般,*,*":{POS: PUNCT}, # this includes characters used to represent sounds like ドレミ "記号,文字,*,*":{POS: PUNCT}, # this is for Greek and Latin characters used as sumbols, as in math "感動詞,フィラー,*,*": {POS: INTJ}, "感動詞,一般,*,*": {POS: INTJ}, # this is specifically for unicode full-width space "空白,*,*,*": {POS: X}, "形状詞,一般,*,*":{POS: ADJ}, "形状詞,タリ,*,*":{POS: ADJ}, "形状詞,助動詞語幹,*,*":{POS: ADJ}, "形容詞,一般,*,*":{POS: ADJ}, "形容詞,非自立可能,*,*":{POS: AUX}, # XXX ADJ if alone, AUX otherwise "助詞,格助詞,*,*":{POS: ADP}, "助詞,係助詞,*,*":{POS: ADP}, "助詞,終助詞,*,*":{POS: PART}, "助詞,準体助詞,*,*":{POS: SCONJ}, # の as in 走るのが速い "助詞,接続助詞,*,*":{POS: SCONJ}, # verb ending て "助詞,副助詞,*,*":{POS: PART}, # ばかり, つつ after a verb "助動詞,*,*,*":{POS: AUX}, "接続詞,*,*,*":{POS: SCONJ}, # XXX: might need refinement "接頭辞,*,*,*":{POS: NOUN}, "接尾辞,形状詞的,*,*":{POS: ADJ}, # がち, チック "接尾辞,形容詞的,*,*":{POS: ADJ}, # -らしい "接尾辞,動詞的,*,*":{POS: NOUN}, # -じみ "接尾辞,名詞的,サ変可能,*":{POS: NOUN}, # XXX see 名詞,普通名詞,サ変可能,* "接尾辞,名詞的,一般,*":{POS: NOUN}, "接尾辞,名詞的,助数詞,*":{POS: NOUN}, "接尾辞,名詞的,副詞可能,*":{POS: NOUN}, # -後, -過ぎ "代名詞,*,*,*":{POS: PRON}, "動詞,一般,*,*":{POS: VERB}, "動詞,非自立可能,*,*":{POS: VERB}, # XXX VERB if alone, AUX otherwise "動詞,非自立可能,*,*,AUX":{POS: AUX}, "動詞,非自立可能,*,*,VERB":{POS: VERB}, "副詞,*,*,*":{POS: ADV}, "補助記号,AA,一般,*":{POS: SYM}, # text art "補助記号,AA,顔文字,*":{POS: SYM}, # kaomoji "補助記号,一般,*,*":{POS: SYM}, "補助記号,括弧開,*,*":{POS: PUNCT}, # open bracket "補助記号,括弧閉,*,*":{POS: PUNCT}, # close bracket "補助記号,句点,*,*":{POS: PUNCT}, # period or other EOS marker "補助記号,読点,*,*":{POS: PUNCT}, # comma "名詞,固有名詞,一般,*":{POS: PROPN}, # general proper noun "名詞,固有名詞,人名,一般":{POS: PROPN}, # person's name "名詞,固有名詞,人名,姓":{POS: PROPN}, # surname "名詞,固有名詞,人名,名":{POS: PROPN}, # first name "名詞,固有名詞,地名,一般":{POS: PROPN}, # place name "名詞,固有名詞,地名,国":{POS: PROPN}, # country name "名詞,助動詞語幹,*,*":{POS: AUX}, "名詞,数詞,*,*":{POS: NUM}, # includes Chinese numerals "名詞,普通名詞,サ変可能,*":{POS: NOUN}, # XXX: sometimes VERB in UDv2; suru-verb noun "名詞,普通名詞,サ変可能,*,NOUN":{POS: NOUN}, "名詞,普通名詞,サ変可能,*,VERB":{POS: VERB}, "名詞,普通名詞,サ変形状詞可能,*":{POS: NOUN}, # ex: 下手 "名詞,普通名詞,一般,*":{POS: NOUN}, "名詞,普通名詞,形状詞可能,*":{POS: NOUN}, # XXX: sometimes ADJ in UDv2 "名詞,普通名詞,形状詞可能,*,NOUN":{POS: NOUN}, "名詞,普通名詞,形状詞可能,*,ADJ":{POS: ADJ}, "名詞,普通名詞,助数詞可能,*":{POS: NOUN}, # counter / unit "名詞,普通名詞,副詞可能,*":{POS: NOUN}, "連体詞,*,*,*":{POS: ADJ}, # XXX this has exceptions based on literal token "連体詞,*,*,*,ADJ":{POS: ADJ}, "連体詞,*,*,*,PRON":{POS: PRON}, "連体詞,*,*,*,DET":{POS: DET}, }
raphael0202/spaCy
spacy/ja/tag_map.py
Python
mit
4,024
/*------------------------------------*\ #COMPONENTS-BUTTONS \*------------------------------------*/ .c-button { border: 0; border-radius: var(--border-radius-50); cursor: pointer; display: inline-block; font-family: var(--font-default); font-size: var(--font-size-30); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 600; line-height: 1.5em; margin: 0; padding: 0.5rem 1.25rem; text-decoration: none; vertical-align: bottom; background: var(--color-primary-50); color: var(--color-white); &:hover { background: var(--color-primary-70); color: var(--color-white); } &:active, &:focus { box-shadow: inset 0 1px 3px color(var(--color-black) alpha(80%)); } } .c-button--small { padding: 0.5rem 0.9rem; line-height: 1; font-size: var(--font-size-20); border-radius: var(--border-radius-10); } .c-button--large { padding: 0.75rem 1.75rem; } .c-button--neutral { background: var(--color-neutral-10); color: var(--color-neutral-70); &:hover { background: var(--color-neutral-30); color: var(--color-neutral-70); } &:active, &:focus { box-shadow: inset 0 1px 3px color(var(--color-black) alpha(80%)); } } .c-button--success { background: var(--color-success-50); color: var(--color-white); &:hover { background: var(--color-success-70); color: var(--color-white); } &:active, &:focus { box-shadow: inset 0 1px 3px color(var(--color-black) alpha(80%)); } } .c-button--alert { background: var(--color-alert-50); color: var(--color-white); &:hover { background: var(--color-alert-70); color: var(--color-white); } &:active, &:focus { box-shadow: inset 0 1px 3px color(var(--color-black) alpha(80%)); } } .c-button--disabled { background: var(--color-neutral-30); color: var(--color-neutral-50); pointer-events: none; }
jquintozamora/react-webpack-postCSS
app/stylesheets/_components.button.css
CSS
mit
1,912
<?php /* * This file is part of the NelmioApiDocBundle package. * * (c) Nelmio * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Nelmio\ApiDocBundle\Tests\Functional\Entity\ArrayItemsError; /** * @author Guilhem N. <guilhem@gniot.fr> */ class Foo { /** * @var string */ public $articles; /** * @var Bar[] */ public $bars; }
nelmio/NelmioApiDocBundle
Tests/Functional/Entity/ArrayItemsError/Foo.php
PHP
mit
463
require "edgrid_rb/version" require "edgrid_rb/my_edgrid_helper" require 'rails' require 'active_support/core_ext/numeric/time' require 'active_support/dependencies' module EdgridRb class Engine < ::Rails::Engine initializer "my_gem.include_view_helpers" do |app| ActiveSupport.on_load :action_view do include MyEdgridHelper end end end end
zephiro/edgrid_rb
lib/edgrid_rb.rb
Ruby
mit
372
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Config\Tests\Loader; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Loader\Loader; use Symfony\Component\Config\Exception\FileLoaderLoadException; class LoaderTest extends \PHPUnit_Framework_TestCase { /** * @covers Symfony\Component\Config\Loader\Loader::getResolver * @covers Symfony\Component\Config\Loader\Loader::setResolver */ public function testGetSetResolver() { $resolver = new LoaderResolver(); $loader = new ProjectLoader1(); $loader->setResolver($resolver); $this->assertSame($resolver, $loader->getResolver(), '->setResolver() sets the resolver loader'); } /** * @covers Symfony\Component\Config\Loader\Loader::resolve */ public function testResolve() { $loader1 = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface'); $loader1->expects($this->once())->method('supports')->will($this->returnValue(true)); $resolver = new LoaderResolver(array($loader1)); $loader = new ProjectLoader1(); $loader->setResolver($resolver); $this->assertSame($loader, $loader->resolve('foo.foo'), '->resolve() finds a loader'); $this->assertSame($loader1, $loader->resolve('foo.xml'), '->resolve() finds a loader'); $loader1 = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface'); $loader1->expects($this->once())->method('supports')->will($this->returnValue(false)); $resolver = new LoaderResolver(array($loader1)); $loader = new ProjectLoader1(); $loader->setResolver($resolver); try { $loader->resolve('FOOBAR'); $this->fail('->resolve() throws a FileLoaderLoadException if the resource cannot be loaded'); } catch (FileLoaderLoadException $e) { $this->assertInstanceOf('Symfony\Component\Config\Exception\FileLoaderLoadException', $e, '->resolve() throws a FileLoaderLoadException if the resource cannot be loaded'); } } } class ProjectLoader1 extends Loader { public function load($resource, $type = null) { } public function supports($resource, $type = null) { return is_string($resource) && 'foo' === pathinfo($resource, PATHINFO_EXTENSION); } public function getType() { } }
lrt/lrt
vendor/symfony/symfony/src/Symfony/Component/Config/Tests/Loader/LoaderTest.php
PHP
mit
2,672
module Griddler VERSION = '1.3.0' end
joeadcock/griddler
lib/griddler/version.rb
Ruby
mit
40
import {VNode} from '../VNode'; const booleanAttrs = [ 'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'compact', 'controls', 'declare', 'default', 'defaultchecked', 'defaultmuted', 'defaultselected', 'defer', 'disabled', 'draggable', 'enabled', 'formnovalidate', 'hidden', 'indeterminate', 'inert', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nohref', 'noresize', 'noshade', 'novalidate', 'nowrap', 'open', 'pauseonexit', 'readonly', 'required', 'reversed', 'scoped', 'seamless', 'selected', 'sortable', 'spellcheck', 'translate', 'truespeed', 'typemustmatch', 'visible' ]; const booleanAttrsDict = {}; for (let i = 0, len = booleanAttrs.length; i < len; i++) { booleanAttrsDict[booleanAttrs[i]] = true; }; function updateAttrs(oldVnode: VNode, vnode: VNode) { let key: any; let cur: any; let old: any; let elm = vnode.elm; let oldAttrs = oldVnode.data.attrs || {}; let attrs = vnode.data.attrs || {}; // update modified attributes, add new attributes for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { // TODO: add support to namespaced attributes (setAttributeNS) if (!cur && booleanAttrsDict[key]) { (<HTMLElement> elm).removeAttribute(key); } else { (<HTMLElement> elm).setAttribute(key, cur); } } } //remove removed attributes for (key in oldAttrs) { if (!(key in attrs)) { (<HTMLElement> elm).removeAttribute(key); } } } const AttrsModule = { update: updateAttrs, create: updateAttrs, }; export default AttrsModule;
TylorS/xs-dom
src/module/attributes.ts
TypeScript
mit
1,595
package leetcode; /* http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ */ public class RemoveDuplicatesFromListII { public static ListNode deleteDuplicates(ListNode root) { if (root == null) { return root; } ListNode ret = new ListNode(root.val); ListNode prev = null; ListNode retItr = ret; root=root.next; boolean duplicate = false; while (root != null) { if (root.val == retItr.val) { duplicate = true; } else { if (duplicate) { retItr = prev; } if(retItr==null) { ret=new ListNode(root.val); retItr=ret; }else { retItr.next = new ListNode(root.val); prev = retItr; retItr = retItr.next; } duplicate =false; } root=root.next; } if (duplicate) { if(prev!=null) { prev.next = null; }else { return null; } } return ret; }}
rekbun/leetcode
src/leetcode/RemoveDuplicatesFromListII.java
Java
mit
862
class AddParentIdToSubmisssions < ActiveRecord::Migration def change add_column :submissions, :parent_id, :integer end end
tommaxwell/chakra
db/migrate/20130831010355_add_parent_id_to_submisssions.rb
Ruby
mit
130
-- Clamps a value between minimum and maximum, inclusive. --# My own implementation to avoid calling into Mathf function Clamp(n, Min, Max) --# Try explicit if/else rather than using math.min/max. --# Ironic, the idented version probably uses more bytes than we save... if n < Min then return Min elseif n > Max then return Max else return n end end
ZerothAngel/FtDScripts
lib/clamp.lua
Lua
mit
359
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataFactory.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Microsoft Azure Cosmos Database (CosmosDB) linked service. /// </summary> [Newtonsoft.Json.JsonObject("CosmosDb")] [Rest.Serialization.JsonTransformation] public partial class CosmosDbLinkedService : LinkedService { /// <summary> /// Initializes a new instance of the CosmosDbLinkedService class. /// </summary> public CosmosDbLinkedService() { CustomInit(); } /// <summary> /// Initializes a new instance of the CosmosDbLinkedService class. /// </summary> /// <param name="connectionString">The connection string. Type: string, /// SecureString or AzureKeyVaultSecretReference.</param> /// <param name="additionalProperties">Unmatched properties from the /// message are deserialized this collection</param> /// <param name="connectVia">The integration runtime reference.</param> /// <param name="description">Linked service description.</param> /// <param name="parameters">Parameters for linked service.</param> /// <param name="annotations">List of tags that can be used for /// describing the Dataset.</param> /// <param name="accountKey">The Azure key vault secret reference of /// accountKey in connection string.</param> /// <param name="encryptedCredential">The encrypted credential used for /// authentication. Credentials are encrypted using the integration /// runtime credential manager. Type: string (or Expression with /// resultType string).</param> public CosmosDbLinkedService(object connectionString, IDictionary<string, object> additionalProperties = default(IDictionary<string, object>), IntegrationRuntimeReference connectVia = default(IntegrationRuntimeReference), string description = default(string), IDictionary<string, ParameterSpecification> parameters = default(IDictionary<string, ParameterSpecification>), IList<object> annotations = default(IList<object>), AzureKeyVaultSecretReference accountKey = default(AzureKeyVaultSecretReference), object encryptedCredential = default(object)) : base(additionalProperties, connectVia, description, parameters, annotations) { ConnectionString = connectionString; AccountKey = accountKey; EncryptedCredential = encryptedCredential; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the connection string. Type: string, SecureString or /// AzureKeyVaultSecretReference. /// </summary> [JsonProperty(PropertyName = "typeProperties.connectionString")] public object ConnectionString { get; set; } /// <summary> /// Gets or sets the Azure key vault secret reference of accountKey in /// connection string. /// </summary> [JsonProperty(PropertyName = "typeProperties.accountKey")] public AzureKeyVaultSecretReference AccountKey { get; set; } /// <summary> /// Gets or sets the encrypted credential used for authentication. /// Credentials are encrypted using the integration runtime credential /// manager. Type: string (or Expression with resultType string). /// </summary> [JsonProperty(PropertyName = "typeProperties.encryptedCredential")] public object EncryptedCredential { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (ConnectionString == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ConnectionString"); } if (AccountKey != null) { AccountKey.Validate(); } } } }
shahabhijeet/azure-sdk-for-net
src/SDKs/DataFactory/Management.DataFactory/Generated/Models/CosmosDbLinkedService.cs
C#
mit
4,772
.world { color: green; } .unused { color: blue; }
FullHuman/purgecss
packages/purgecss/__tests__/test_examples/cli/simple/src/style2.css
CSS
mit
55
$(document).ready(function() { /* initialize the external events -----------------------------------------------------------------*/ $('#external-events div.external-event').each(function() { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end var eventObject = { title: $.trim($(this).text()), // use the element's text as the event title className: $.trim($(this).attr("class").split(' ')[1]) // get the class name color[x] }; // store the Event Object in the DOM element so we can get to it later $(this).data('eventObject', eventObject); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); /* initialize the calendar -----------------------------------------------------------------*/ var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'agendaWeek,agendaDay' }, defaultView: 'agendaDay', timeFormat: 'H:mm{ - H:mm}', axisFormat: 'H:mm', minTime: '8:00', maxTime: '22:00', allDaySlot: false, monthNames: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'], monthNamesShort: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'], dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'], titleFormat: { month: 'yyyy MMMM', week: "yyyy'年' MMM d'日'{ '&#8212;'[ MMM] d'日' }", day: "dddd, yyyy'年' MMM d'日'" }, /*defaultEventMinutes: 120, */ selectable: true, selectHelper: true, select: function(start, end, allDay) { var type = false; var color = false; var execute = function(){ $("input").each(function(){ (this.checked == true) ? type = $(this).val() : null; (this.checked == true) ? color = $(this).attr('id') : null; }); $("#dialog-form").dialog("close"); calendar.fullCalendar('renderEvent', { title: type, start: start, end: end, allDay: allDay, className: color }, true // make the event "stick" ); calendar.fullCalendar('unselect'); }; var cancel = function() { $("#dialog-form").dialog("close"); } var dialogOpts = { modal: true, position: "center", buttons: { "确定": execute, "取消": cancel } }; $("#dialog-form").dialog(dialogOpts); }, editable: true, eventMouseover: function(event, domEvent) { /* for(var key in event){ $("<p>").text(key + ':' + event[key]).appendTo($("body")); }; */ var layer = '<div id="events-layer" class="fc-transparent" style="position:absolute; width:100%; height:100%; top:-1px; text-align:right; z-index:100"><a><img src="images/icon_edit.gif" title="edit" width="14" id="edbut'+event._id+'" border="0" style="padding-right:3px; padding-top:2px;" /></a><a><img src="images/icon_delete.png" title="delete" width="14" id="delbut'+event._id+'" border="0" style="padding-right:5px; padding-top:2px;" /></a></div>'; $(this).append(layer); $("#delbut"+event._id).hide(); $("#delbut"+event._id).fadeIn(300); $("#delbut"+event._id).click(function() { calendar.fullCalendar('removeEvents', event._id); //$.post("delete.php", {eventId: event._id}); calendar.fullCalendar('refetchEvents'); }); $("#edbut"+event._id).hide(); $("#edbut"+event._id).fadeIn(300); $("#edbut"+event._id).click(function() { //var title = prompt('Current Event Title: ' + event.title + '\n\nNew Event Title: '); /* if(title){ $.post("update_title.php", {eventId: event.id, eventTitle: title}); calendar.fullCalendar('refetchEvents'); } */ var type = false; var color = false; var execute = function(){ $("input").each(function(){ (this.checked == true) ? type = $(this).val() : null; (this.checked == true) ? color = $(this).attr('id') : null; }); $("#dialog-form").dialog("close"); event.title = type; event.className = color; calendar.fullCalendar('updateEvent', event); calendar.fullCalendar('refetchEvents'); }; var cancel = function() { $("#dialog-form").dialog("close"); } var dialogOpts = { modal: true, position: "center", buttons: { "确定": execute, "取消": cancel } }; $("#dialog-form").dialog(dialogOpts); }); }, eventMouseout: function(calEvent, domEvent) { $("#events-layer").remove(); }, droppable: true, // this allows things to be dropped onto the calendar !!! drop: function(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); // we need to copy it, so that multiple events don't have a reference to the same object var copiedEventObject = $.extend({}, originalEventObject); // assign it the date that was reported copiedEventObject.start = date; copiedEventObject.end = (date.getTime() + 7200000)/1000; copiedEventObject.allDay = false; // render the event on the calendar // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/) $('#calendar').fullCalendar('renderEvent', copiedEventObject, true); } }); });
vectortiny/FullCalendar_adapt
demos/js/lsn.js
JavaScript
mit
5,894
using System.Collections.Generic; using System.Linq; using Sharepoint.Client.Fluent.Contracts.Entities; using Sharepoint.Client.Fluent.Exceptions; using Sharepoint.Client.Fluent.Exceptions.Interactors; using Sharepoint.Client.Fluent.FluentBase; using SP = Microsoft.SharePoint.Client; namespace Sharepoint.Client.Fluent.Lists.Operations { public class SharepointListAddOperations : SharepointFluentBase { private SP.List sharepointList; private Dictionary<string, string> titleToInternalName; internal SharepointListAddOperations(SP.List sharepointList, ISharepointContext sharepointContext) : base(sharepointContext) { ExceptionFactory.GetInteractor<NullCheckInteractor>() .CheckForConstructorArgumentNull(sharepointList, nameof(sharepointList), typeof(SharepointListAddOperations)); this.sharepointList = sharepointList; this.titleToInternalName = new Dictionary<string, string>(); } /// <summary> /// Adding is only performed when the calling code itself calls the execute operation (--> performance reason) /// </summary> /// <param name="item"></param> /// <returns></returns> public SharepointRetrievedListOperations Item(SharepointListItem item) { if (!item.Values.All(s => this.titleToInternalName.ContainsKey(s.ColumnName))) { SP.ClientContext clientContext = this.sharepointContext.GetClientContext(); clientContext.Load(this.sharepointList.Fields); clientContext.ExecuteQuery(); foreach (var column in item.Values) { if (column.ColumnName == "Title" && !this.titleToInternalName.ContainsKey("Title")) { this.titleToInternalName.Add("Title", "Title"); } else { this.sharepointList.Fields.Where( s => !this.titleToInternalName.ContainsKey(column.ColumnName) && s.Title == column.ColumnName) .ToList() .ForEach(s => this.titleToInternalName.Add(s.Title, s.InternalName)); } } } var itemCreationInfo = new SP.ListItemCreationInformation(); var listItem = this.sharepointList.AddItem(itemCreationInfo); foreach (var column in item.Values) { listItem[this.titleToInternalName[column.ColumnName]] = column.ColumnValue; } listItem.Update(); return new SharepointRetrievedListOperations(this.sharepointList, this.sharepointContext); } /// <summary> /// Adding is only performed when the calling code itself calls the execute operation (--> performance reason) /// </summary> /// <param name="items"></param> /// <returns></returns> public SharepointRetrievedListOperations Items(List<SharepointListItem> items) { items.ForEach(s => this.Item(s)); return new SharepointRetrievedListOperations(this.sharepointList, this.sharepointContext); } } }
manuelzelenka/Sharepoint.Client.Fluent
Sharepoint.Client.Fluent/Sharepoint.Client.Fluent/Lists/Operations/SharepointListAddOperations.cs
C#
mit
3,324
# -*- coding: UTF-8 -*- DOWNLOADER_VERSION = "0.0.1" DOWNLOADER_LOG_FILE = "downloader.log" DOWNLOADER_LOG_SIZE = 10485760 DOWNLOADER_LOG_COUNT = 10 DOWNLOADER_LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" DOWNLOADER_REQUIREMENTS_PATH = "requirements.txt"
arsenypoga/ImageboardDownloader
DownloaderConstants.py
Python
mit
278
require_relative "range/conversions" require_relative "range/include_range" require_relative "range/overlaps" require_relative "range/each"
ttanimichi/rails
activesupport/lib/active_support/core_ext/range.rb
Ruby
mit
140
/* * Copyright 2020 Vonage * * 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 com.vonage.client.account; public class PricingRequest { private String countryCode; public PricingRequest(String countryCode) { this.countryCode = countryCode; } public String getCountryCode() { return countryCode; } }
Nexmo/nexmo-java-sdk
src/main/java/com/vonage/client/account/PricingRequest.java
Java
mit
878
# Atlas.Orm Atlas is a [data mapper](http://martinfowler.com/eaaCatalog/dataMapper.html) implementation for **persistence models** (*not* domain models). As such, Atlas uses the term "record" to indicate that its objects are *not* domain objects. Use Atlas records directly for simple data source interactions at first. As a domain model grows within the application, use Atlas records to populate domain objects. (Note that an Atlas record is a "passive" record, not an [active record](http://martinfowler.com/eaaCatalog/activeRecord.html). It is disconnected from the database.) Documentation is at <http://atlasphp.io>.
atlasphp/Atlas.Orm
README.md
Markdown
mit
626
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int left=0,right=numbers.size()-1; while(numbers[left]+numbers[right] != target) { if(numbers[left]+numbers[right] < target) left++; else right--; } vector<int> result; result.push_back(left+1); result.push_back(right+1); return result; } };
moranzcw/LeetCode
Algorithms/167.Two-Sum-II---Input-array-is-sorted/solution.cpp
C++
mit
459
#ifndef HANDLEBARS_HELPERS_H #define HANDLEBARS_HELPERS_H #include <functional> #include <QHash> #include <QList> #include <QVariant> namespace Handlebars { using escape_fn = std::function< QString (const QString&) >; class RenderingContext; class Node; using helper_params = QVariantList; using helper_options = QVariantHash; using helper_fn = std::function< QVariant ( const RenderingContext & context, const helper_params & params, const helper_options & options )>; using block_helper_fn = std::function< void ( RenderingContext & context, const helper_params & params, const helper_options & options, const QList<Node*> & first, const QList<Node*> & last )>; using helpers = QHash< QString, helper_fn >; using block_helpers = QHash< QString, block_helper_fn >; }// namespace Handlebars #endif // HANDLEBARS_HELPERS_H
mdhooge/qt-handlebars
src/handlebars/HandlebarsHelpers.h
C
mit
925
#!/usr/bin/env node var app = require('./app'), config = require('./config'); app.set('port', process.env.PORT || config.app.port); var server = app.listen(app.get('port'), function() { "use strict"; console.log('Express server listening on port ' + server.address().port); });
junwang1216/iDawn
web/server.js
JavaScript
mit
293
class mmpmon(object): def __init__(self): self.name = 'mmpmon' self.nodefields = { '_n_': 'nodeip', '_nn_': 'nodename', '_rc_': 'status', '_t_': 'seconds', '_tu_': 'microsecs', '_br_': 'bytes_read', '_bw_': 'bytes_written', '_oc_': 'opens', '_cc_': 'closes', '_rdc_': 'reads', '_wc_': 'writes', '_dir_': 'readdir', '_iu_': 'inode_updates' } self.nodelabels = {} self.fsfields = { '_n_': 'nodeip', '_nn_': 'nodename', '_rc_': 'status', '_t_': 'seconds', '_tu_': 'microsecs', '_cl_': 'cluster', '_fs_': 'filesystem', '_d_': 'disks', '_br_': 'bytes_read', '_bw_': 'bytes_written', '_oc_': 'opens', '_cc_': 'closes', '_rdc_': 'reads', '_wc_': 'writes', '_dir_': 'readdir', '_iu_': 'inode_updates' } self.fslabels = {} def _add_nodes(self, nodelist): """Add nodes to the mmpmon nodelist""" return def _reset_stats(self): """Reset the IO stats""" return
stevec7/gpfs
gpfs/mmpmon.py
Python
mit
1,059
## API Report File for "@angular/common_http_testing" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import { HttpEvent } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http'; import { HttpRequest } from '@angular/common/http'; import { Observer } from 'rxjs'; // @public export class HttpClientTestingModule { } // @public export abstract class HttpTestingController { abstract expectNone(url: string, description?: string): void; abstract expectNone(params: RequestMatch, description?: string): void; abstract expectNone(matchFn: ((req: HttpRequest<any>) => boolean), description?: string): void; abstract expectNone(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), description?: string): void; abstract expectOne(url: string, description?: string): TestRequest; abstract expectOne(params: RequestMatch, description?: string): TestRequest; abstract expectOne(matchFn: ((req: HttpRequest<any>) => boolean), description?: string): TestRequest; abstract expectOne(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), description?: string): TestRequest; abstract match(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean)): TestRequest[]; abstract verify(opts?: { ignoreCancelled?: boolean; }): void; } // @public export interface RequestMatch { // (undocumented) method?: string; // (undocumented) url?: string; } // @public export class TestRequest { constructor(request: HttpRequest<any>, observer: Observer<HttpEvent<any>>); get cancelled(): boolean; error(error: ErrorEvent, opts?: { headers?: HttpHeaders | { [name: string]: string | string[]; }; status?: number; statusText?: string; }): void; event(event: HttpEvent<any>): void; flush(body: ArrayBuffer | Blob | boolean | string | number | Object | (boolean | string | number | Object | null)[] | null, opts?: { headers?: HttpHeaders | { [name: string]: string | string[]; }; status?: number; statusText?: string; }): void; // (undocumented) request: HttpRequest<any>; } // (No @packageDocumentation comment for this package) ```
mgechev/angular
goldens/public-api/common/http/testing/testing.md
Markdown
mit
2,323
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace LuminoBuild.Tasks { class MakePackage_macOS : BuildTask { public override string CommandName => "MakePackage_macOS"; public override void Build(Builder builder) { var orgName = Path.Combine(builder.LuminoBuildDir, builder.LocalPackageName); var tmpName = Path.Combine(builder.LuminoBuildDir, builder.ReleasePackageName); Directory.Move(orgName, tmpName); if (!BuildEnvironment.FromCI) { Utils.CreateZipFile(tmpName, tmpName + ".zip"); Directory.Move(tmpName, orgName); } } } }
lriki/Lumino
tools/LuminoBuild/Tasks/MakePackage_macOS.cs
C#
mit
748
--- title: Vuex Store description: Vuex Store example with Nuxt.js github: vuex-store livedemo: https://vuex-store.nuxtjs.org documentation: /guide/vuex-store ---
jbruni/docs
en/examples/vuex-store.md
Markdown
mit
163
"use strict"; /** * Storing multiple constant values inside of an object * Keep in mind the values in the object mean they can be modified * Which makes no sense for a constant, use wisely if you do this */ app.service('$api', ['$http', '$token', '$rootScope', '$sweetAlert', '$msg', 'SERVER_URL', function ($http, $token, $rootScope, $sweetAlert, $msg, SERVER_URL) { const SERVER_URI = SERVER_URL + 'api/'; var config = { headers: {'Authorization': $token.getFromCookie() || $token.getFromLocal() || $token.getFromSession()} }; /* Authentication Service ----------------------------------------------*/ this.isAuthorized = function (module_name) { return $http.get(SERVER_URI + 'check_auth', { headers: {'Authorization': $token.getFromCookie() || $token.getFromLocal() || $token.getFromSession()}, params: {'module_name': module_name} }); }; this.authenticate = function (data) { return $http.post(SERVER_URI + 'login', data); }; this.resetPassword = function (email) { return $http.post(SERVER_URI + 'reset_password', email); }; this.exit = function () { $token.deleteFromAllStorage(); return $http.get(SERVER_URI + 'logout', {params: {user: $rootScope.user} }) }; /* User Service ----------------------------------------------*/ this.findMember = function (params) { config.params = params; if (params.search) { return $http.post(SERVER_URI + 'all_users', params.search, config); } return $http.get(SERVER_URI + 'all_users', config); }; this.removeMember = function (data) { return $http.delete(SERVER_URI + 'remove_profile/' + data, config); }; this.updateUserProfile = function (data) { return $http.put(SERVER_URI + 'update_profile', data, config); }; this.usersCount = function () { return $http.get(SERVER_URI + 'users_count', config); }; /* Shop Service ----------------------------------------------*/ this.makePayment = function (params) { config.params = params; return $http.get(SERVER_URI + 'execute_payment', config); }; /* Chat Service ----------------------------------------------*/ this.getChatList = function (params) { return $http.get(SERVER_URI+'chat_list', config); }; this.saveMessage = function(data) { return $http.post(SERVER_URI + 'save_message', data, config); }; this.getConversation = function () { }; /* Product Service ----------------------------------------------*/ this.products = function (params) { config.params = params; if (params.search) { return $http.post(SERVER_URI + 'product_list', params.search, config); } return $http.get(SERVER_URI + 'product_list', config); }; this.productDetail = function (id) { config.params = {id: id}; return $http.get(SERVER_URI + 'product_detail', config); }; this.buyProduct = function (params) { config.params = params; return $http.get(SERVER_URI + 'buy_product', config); }; this.handleError = function (res) { switch (res.status) { case 400: $sweetAlert.error(res.statusText, $msg.AUTHENTICATION_ERROR); break; case 403: $sweetAlert.error(res.statusText, $msg.AUTHENTICATION_ERROR); break; case 500: $sweetAlert.error(res.statusText, $msg.INTERNAL_SERVER_ERROR); break; case 503: $sweetAlert.error(res.statusText, $msg.SERVICE_UNAVAILABLE); break; case 404: $sweetAlert.error(res.statusText, $msg.NOT_FOUND_ERROR); break; default: $sweetAlert.error(res.statusText, $msg.INTERNAL_SERVER_ERROR); break; } }; }]);
shobhit-github/RetailerStock
ngApp/src/services/httpService.js
JavaScript
mit
4,478
from keras.models import model_from_json import theano.tensor as T from utils.readImgFile import readImg from utils.crop import crop_detection from utils.ReadPascalVoc2 import prepareBatch import os import numpy as np def Acc(imageList,model,sample_number=5000,thresh=0.3): correct = 0 object_num = 0 count = 0 for image in imageList: count += 1 #Get prediction from neural network img = crop_detection(image.imgPath,new_width=448,new_height=448) img = np.expand_dims(img, axis=0) out = model.predict(img) out = out[0] for i in range(49): preds = out[i*25:(i+1)*25] if(preds[24] > thresh): object_num += 1 row = i/7 col = i%7 ''' centerx = 64 * col + 64 * preds[0] centery = 64 * row + 64 * preds[1] h = preds[2] * preds[2] h = h * 448.0 w = preds[3] * preds[3] w = w * 448.0 left = centerx - w/2.0 right = centerx + w/2.0 up = centery - h/2.0 down = centery + h/2.0 if(left < 0): left = 0 if(right > 448): right = 447 if(up < 0): up = 0 if(down > 448): down = 447 ''' class_num = np.argmax(preds[4:24]) #Ground Truth box = image.boxes[row][col] if(box.has_obj): for obj in box.objs: true_class = obj.class_num if(true_class == class_num): correct += 1 break return correct*1.0/object_num def Recall(imageList,model,sample_number=5000,thresh=0.3): correct = 0 obj_num = 0 count = 0 for image in imageList: count += 1 #Get prediction from neural network img = crop_detection(image.imgPath,new_width=448,new_height=448) img = np.expand_dims(img, axis=0) out = model.predict(img) out = out[0] #for each ground truth, see we have predicted a corresponding result for i in range(49): preds = out[i*25:i*25+25] row = i/7 col = i%7 box = image.boxes[row][col] if(box.has_obj): for obj in box.objs: obj_num += 1 true_class = obj.class_num #see what we predict if(preds[24] > thresh): predcit_class = np.argmax(preds[4:24]) if(predcit_class == true_class): correct += 1 return correct*1.0/obj_num def MeasureAcc(model,sample_number,vocPath,imageNameFile): imageList = prepareBatch(0,sample_number,imageNameFile,vocPath) acc = Acc(imageList,model) re = Recall(imageList,model) return acc,re
PatrickChrist/CDTM-Deep-Learning-Drones
Yolonese/utils/MeasureAccuray.py
Python
mit
2,954
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="author" content="Guillaume Bourque"> <title>Les Ateliers 374</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../la374css.css"> </head> <body class="project"> <div class="header"> <div class="row"> <a href="../index.html"> <img src="../images/full_size/LA374.jpg" alt="Logo Les Ateliers 374" id="logo"> </a> </div> <div class="row"> <hr id="sub-banner"> </div> <div class="nav row"> <ul> <li><a href="../about.html"><button type="button"> <span lang="en">About</span> <span lang="fr">À propos</span> </button></a></li> <li><a href="../index.html"><button type="button"> Portfolio </button></a></li> <li><a href="../contact.html"><button type="button"> Contact </button></a></li> <li><button type="button" id="language"> <span lang="en">Fr</span> <span lang="fr">En</span> </button></li> </ul> </div> </div> <div class="content"> <div class="title row col-"> <h1> <span lang="en">Built-in shelving and media cabinetry</span> <span lang="fr">Rangement de télévision encastré</span> </h1> </div> <div class="description row col-"> <p> <span lang="en"> A bare, stepped wall surface is transformed to create shelving and cabinets that neatly conceal wiring and electronics. Clean lines and matte painted finish help the addition integrate seamlessly with the existing décor. </span> <span lang="fr"> Un mur vierge est ici modifié pour renfermer discrètement le filage et les composantes d'un système multimédia. Des lignes épurées et une finition matte permettent une intégration subtile et conforme au décor existant de la pièce. </span> </p> </div> <div class="pictures"> <div class="row parent"><div class="row parent no-padding"> <div class="col-" id="turner-1"> <a class="slideshow"> <img src="../images/layout_600/Turner 1.jpg" alt="Turner 1"> </a> </div> <div class="col-" id="turner-5"> <a class="slideshow"> <img src="../images/layout_600/Turner 5.jpg" alt="Turner 5"> </a> </div> </div></div> <div class="row"> <div class="col-" id="turner-before"> <a class="slideshow"> <img src="../images/layout_600/Turner before.png" alt="Turner before"> </a> </div> <div class="col-" id="turner-after"> <a class="slideshow"> <img src="../images/layout_600/Turner after.png" alt="Turner after"> </a> </div> <div class="col-" id="turner-3"> <a class="slideshow"> <img src="../images/layout_600/Turner 3.jpg" alt="Turner 3"> </a> </div> <div class="col-" id="turner-4"> <a class="slideshow"> <img src="../images/layout_600/Turner 4.jpg" alt="Turner 4"> </a> </div> </div> </div> </div> <!--To load jQuery and Javascript code--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="../la374js.js"></script> </body> </html>
guillaumebourque2/la374
portfolio/media_cabinetry.html
HTML
mit
3,072
# -*- encoding: utf-8 -*- from supriya.tools import osctools from supriya.tools.requesttools.Request import Request class GroupQueryTreeRequest(Request): r'''A /g_queryTree request. :: >>> from supriya.tools import requesttools >>> request = requesttools.GroupQueryTreeRequest( ... node_id=0, ... include_controls=True, ... ) >>> request GroupQueryTreeRequest( include_controls=True, node_id=0 ) :: >>> message = request.to_osc_message() >>> message OscMessage(57, 0, 1) :: >>> message.address == requesttools.RequestId.GROUP_QUERY_TREE True ''' ### CLASS VARIABLES ### __slots__ = ( '_include_controls', '_node_id', ) ### INITIALIZER ### def __init__( self, include_controls=False, node_id=None, ): Request.__init__(self) self._node_id = node_id self._include_controls = bool(include_controls) ### PUBLIC METHODS ### def to_osc_message(self): request_id = int(self.request_id) node_id = int(self.node_id) include_controls = int(self.include_controls) message = osctools.OscMessage( request_id, node_id, include_controls, ) return message ### PUBLIC PROPERTIES ### @property def include_controls(self): return self._include_controls @property def node_id(self): return self._node_id @property def response_specification(self): from supriya.tools import responsetools return { responsetools.QueryTreeResponse: None, } @property def request_id(self): from supriya.tools import requesttools return requesttools.RequestId.GROUP_QUERY_TREE
andrewyoung1991/supriya
supriya/tools/requesttools/GroupQueryTreeRequest.py
Python
mit
1,918
/** * @file Link files. * @function filelink * @param {string} src - Source file (actual file) path. * @param {string} dest - Destination file (link) path. * @param {object} [options] - Optional settings. * @param {string} [options.type='symlink'] - Link type * @param {boolean} [options.mkdirp] - Make parent directories. * @param {boolean} [options.force] - Force to symlink or not. * @param {function} callback - Callback when done. */ 'use strict' const fs = require('fs') const argx = require('argx') const path = require('path') const {mkdirpAsync, existsAsync, statAsync} = require('asfs') const _cleanDest = require('./_clean_dest') const _followSymlink = require('./_follow_symlink') /** @lends filelink */ async function filelink (src, dest, options) { let args = argx(arguments) if (args.pop('function')) { throw new Error('Callback is no more supported. Use promise interface instead') } options = args.pop('object') || {} const cwd = options.cwd || process.cwd() src = path.resolve(cwd, args.shift('string')) dest = path.resolve(cwd, args.shift('string')) const type = options.type || 'symlink' const force = !!options.force const destDir = path.dirname(dest) src = await _followSymlink(src) if (options.mkdirp) { await mkdirpAsync(destDir) } else { let exists = await existsAsync(destDir) if (!exists) { throw new Error(`Directory not exists: ${destDir}`) } } let srcName = path.relative(destDir, src) let destName = path.relative(destDir, dest) let before = (await existsAsync(dest)) && (await statAsync(dest)) if (force) { await _cleanDest(dest) } process.chdir(destDir) _doLinkSync(srcName, destName, type) process.chdir(cwd) let after = (await existsAsync(dest)) && (await statAsync(dest)) await new Promise((resolve) => process.nextTick(() => resolve())) let unchanged = (before && before.size) === (after && after.size) return !unchanged } module.exports = filelink function _doLinkSync (src, dest, type) { switch (type) { case 'link': fs.linkSync(src, dest) break case 'symlink': fs.symlinkSync(src, dest) break default: throw new Error('Unknown type:' + type) } }
okunishinishi/node-filelink
lib/filelink.js
JavaScript
mit
2,238
#ifndef SELECTION_SORT_H #define SELECTION_SORT_H #include <stddef.h> void selection_sort(int array[], size_t length); #endif // SELECTION_SORT_H
michaelreneer/Algorithms
c/algorithms/selection_sort.h
C
mit
150
using Microsoft.AspNetCore.Authentication; namespace MarginTrading.DataReader.Middleware { public class KeyAuthOptions : AuthenticationSchemeOptions { public const string DefaultHeaderName = "api-key"; public const string AuthenticationScheme = "Automatic"; } }
LykkeCity/MT
src/MarginTrading.DataReader/Middleware/KeyAuthOptions.cs
C#
mit
294
// File auto generated by STUHashTool using static STULib.Types.Generic.Common; namespace STULib.Types.Dump { [STU(0xEFF3DFB0)] public class STU_EFF3DFB0 : STU_100002C0 { [STUField(0x20AE2CCB)] public STULib.Types.Dump.Enums.STUEnum_1E2FFF3B m_20AE2CCB; } }
kerzyte/OWLib
STULib/Types/Dump/STU_EFF3DFB0.cs
C#
mit
287
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Phaser Source: tween/Tween.js</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.cerulean.css"> </head> <body> <div class="container-fluid"> <div class="navbar navbar-fixed-top navbar-inverse"> <div class="navbar-inner"> <a class="brand" href="index.html">Phaser</a> <ul class="nav"> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="Phaser.html">Phaser</a> </li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"> <a href="Phaser.Animation.html">Animation</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationManager.html">AnimationManager</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationParser.html">AnimationParser</a> </li> <li class="class-depth-1"> <a href="Phaser.ArrayList.html">ArrayList</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapData.html">BitmapData</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapText.html">BitmapText</a> </li> <li class="class-depth-1"> <a href="Phaser.Button.html">Button</a> </li> <li class="class-depth-1"> <a href="Phaser.Cache.html">Cache</a> </li> <li class="class-depth-1"> <a href="Phaser.Camera.html">Camera</a> </li> <li class="class-depth-1"> <a href="Phaser.Canvas.html">Canvas</a> </li> <li class="class-depth-1"> <a href="Phaser.Circle.html">Circle</a> </li> <li class="class-depth-1"> <a href="Phaser.Color.html">Color</a> </li> <li class="class-depth-1"> <a href="Phaser.Device.html">Device</a> </li> <li class="class-depth-1"> <a href="Phaser.Easing.html">Easing</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Back.html">Back</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Bounce.html">Bounce</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Circular.html">Circular</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Cubic.html">Cubic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Elastic.html">Elastic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Exponential.html">Exponential</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Linear.html">Linear</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quadratic.html">Quadratic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quartic.html">Quartic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quintic.html">Quintic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Sinusoidal.html">Sinusoidal</a> </li> <li class="class-depth-1"> <a href="Phaser.Ellipse.html">Ellipse</a> </li> <li class="class-depth-1"> <a href="Phaser.Events.html">Events</a> </li> <li class="class-depth-1"> <a href="Phaser.Filter.html">Filter</a> </li> <li class="class-depth-1"> <a href="Phaser.Frame.html">Frame</a> </li> <li class="class-depth-1"> <a href="Phaser.FrameData.html">FrameData</a> </li> <li class="class-depth-1"> <a href="Phaser.Game.html">Game</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectCreator.html">GameObjectCreator</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectFactory.html">GameObjectFactory</a> </li> <li class="class-depth-1"> <a href="Phaser.Gamepad.html">Gamepad</a> </li> <li class="class-depth-1"> <a href="Phaser.GamepadButton.html">GamepadButton</a> </li> <li class="class-depth-1"> <a href="Phaser.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="Phaser.Group.html">Group</a> </li> <li class="class-depth-1"> <a href="Phaser.Image.html">Image</a> </li> <li class="class-depth-1"> <a href="Phaser.Input.html">Input</a> </li> <li class="class-depth-1"> <a href="Phaser.InputHandler.html">InputHandler</a> </li> <li class="class-depth-1"> <a href="Phaser.Key.html">Key</a> </li> <li class="class-depth-1"> <a href="Phaser.Keyboard.html">Keyboard</a> </li> <li class="class-depth-1"> <a href="Phaser.Line.html">Line</a> </li> <li class="class-depth-1"> <a href="Phaser.LinkedList.html">LinkedList</a> </li> <li class="class-depth-1"> <a href="Phaser.Loader.html">Loader</a> </li> <li class="class-depth-1"> <a href="Phaser.LoaderParser.html">LoaderParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Math.html">Math</a> </li> <li class="class-depth-1"> <a href="Phaser.Mouse.html">Mouse</a> </li> <li class="class-depth-1"> <a href="Phaser.MSPointer.html">MSPointer</a> </li> <li class="class-depth-1"> <a href="Phaser.Net.html">Net</a> </li> <li class="class-depth-1"> <a href="Phaser.Particle.html">Particle</a> </li> <li class="class-depth-1"> <a href="Phaser.Particles.html">Particles</a> </li> <li class="class-depth-3"> <a href="Phaser.Particles.Arcade.Emitter.html">Emitter</a> </li> <li class="class-depth-1"> <a href="Phaser.Physics.html">Physics</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.Body.html">Body</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Ninja.html">Ninja</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.AABB.html">AABB</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Circle.html">Circle</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Tile.html">Tile</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.P2.html">P2</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.BodyDebug.html">BodyDebug</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.DistanceConstraint.html">DistanceConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.FixtureList.html">FixtureList</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.GearConstraint.html">GearConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.InversePointProxy.html">InversePointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.LockConstraint.html">LockConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Material.html">Material</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PointProxy.html">PointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PrismaticConstraint.html">PrismaticConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RevoluteConstraint.html">RevoluteConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Spring.html">Spring</a> </li> <li class="class-depth-1"> <a href="Phaser.Plugin.html">Plugin</a> </li> <li class="class-depth-1"> <a href="Phaser.PluginManager.html">PluginManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Point.html">Point</a> </li> <li class="class-depth-1"> <a href="Phaser.Pointer.html">Pointer</a> </li> <li class="class-depth-1"> <a href="Phaser.Polygon.html">Polygon</a> </li> <li class="class-depth-1"> <a href="Phaser.QuadTree.html">QuadTree</a> </li> <li class="class-depth-1"> <a href="Phaser.RandomDataGenerator.html">RandomDataGenerator</a> </li> <li class="class-depth-1"> <a href="Phaser.Rectangle.html">Rectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="Phaser.RequestAnimationFrame.html">RequestAnimationFrame</a> </li> <li class="class-depth-1"> <a href="Phaser.RetroFont.html">RetroFont</a> </li> <li class="class-depth-1"> <a href="Phaser.ScaleManager.html">ScaleManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Signal.html">Signal</a> </li> <li class="class-depth-1"> <a href="Phaser.SignalBinding.html">SignalBinding</a> </li> <li class="class-depth-1"> <a href="Phaser.SinglePad.html">SinglePad</a> </li> <li class="class-depth-1"> <a href="Phaser.Sound.html">Sound</a> </li> <li class="class-depth-1"> <a href="Phaser.SoundManager.html">SoundManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="Phaser.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="Phaser.Stage.html">Stage</a> </li> <li class="class-depth-1"> <a href="Phaser.State.html">State</a> </li> <li class="class-depth-1"> <a href="Phaser.StateManager.html">StateManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Text.html">Text</a> </li> <li class="class-depth-1"> <a href="Phaser.Tile.html">Tile</a> </li> <li class="class-depth-1"> <a href="Phaser.Tilemap.html">Tilemap</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapLayer.html">TilemapLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapParser.html">TilemapParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Tileset.html">Tileset</a> </li> <li class="class-depth-1"> <a href="Phaser.TileSprite.html">TileSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.Time.html">Time</a> </li> <li class="class-depth-1"> <a href="Phaser.Timer.html">Timer</a> </li> <li class="class-depth-1"> <a href="Phaser.TimerEvent.html">TimerEvent</a> </li> <li class="class-depth-1"> <a href="Phaser.Touch.html">Touch</a> </li> <li class="class-depth-1"> <a href="Phaser.Tween.html">Tween</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenManager.html">TweenManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Utils.html">Utils</a> </li> <li class="class-depth-2"> <a href="Phaser.Utils.Debug.html">Debug</a> </li> <li class="class-depth-1"> <a href="Phaser.World.html">World</a> </li> </ul> </li> </ul> </div> </div> <div class="row-fluid"> <div class="span12"> <div id="main"> <h1 class="page-title">Source: tween/Tween.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums">/** * @author Richard Davey &lt;rich@photonstorm.com> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Tween constructor * Create a new &lt;code>Tween&lt;/code>. * * @class Phaser.Tween * @constructor * @param {object} object - Target object will be affected by this tween. * @param {Phaser.Game} game - Current game instance. * @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. */ Phaser.Tween = function (object, game, manager) { /** * Reference to the target object. * @property {object} _object * @private */ this._object = object; /** * @property {Phaser.Game} game - A reference to the currently running Game. */ this.game = game; /** * @property {Phaser.TweenManager} _manager - Reference to the TweenManager. * @private */ this._manager = manager; /** * @property {object} _valuesStart - Private value object. * @private */ this._valuesStart = {}; /** * @property {object} _valuesEnd - Private value object. * @private */ this._valuesEnd = {}; /** * @property {object} _valuesStartRepeat - Private value object. * @private */ this._valuesStartRepeat = {}; /** * @property {number} _duration - Private duration counter. * @private * @default */ this._duration = 1000; /** * @property {number} _repeat - Private repeat counter. * @private * @default */ this._repeat = 0; /** * @property {boolean} _yoyo - Private yoyo flag. * @private * @default */ this._yoyo = false; /** * @property {boolean} _reversed - Private reversed flag. * @private * @default */ this._reversed = false; /** * @property {number} _delayTime - Private delay counter. * @private * @default */ this._delayTime = 0; /** * @property {number} _startTime - Private start time counter. * @private * @default null */ this._startTime = null; /** * @property {function} _easingFunction - The easing function used for the tween. * @private */ this._easingFunction = Phaser.Easing.Linear.None; /** * @property {function} _interpolationFunction - The interpolation function used for the tween. * @private */ this._interpolationFunction = Phaser.Math.linearInterpolation; /** * @property {array} _chainedTweens - A private array of chained tweens. * @private */ this._chainedTweens = []; /** * @property {boolean} _onStartCallbackFired - Private flag. * @private * @default */ this._onStartCallbackFired = false; /** * @property {function} _onUpdateCallback - An onUpdate callback. * @private * @default null */ this._onUpdateCallback = null; /** * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. * @private * @default null */ this._onUpdateCallbackContext = null; /** * @property {boolean} _paused - Is this Tween paused or not? * @private * @default */ this._paused = false; /** * @property {number} _pausedTime - Private pause timer. * @private * @default */ this._pausedTime = 0; /** * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? * @private */ this._codePaused = false; /** * @property {boolean} pendingDelete - If this tween is ready to be deleted by the TweenManager. * @default */ this.pendingDelete = false; // Set all starting values present on the target object - why? this will copy loads of properties we don't need - commenting out for now // for (var field in object) // { // this._valuesStart[field] = parseFloat(object[field], 10); // } /** * @property {Phaser.Signal} onStart - The onStart event is fired when the Tween begins. */ this.onStart = new Phaser.Signal(); /** * @property {Phaser.Signal} onLoop - The onLoop event is fired if the Tween loops. */ this.onLoop = new Phaser.Signal(); /** * @property {Phaser.Signal} onComplete - The onComplete event is fired when the Tween completes. Does not fire if the Tween is set to loop. */ this.onComplete = new Phaser.Signal(); /** * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state, waiting to start, are considered as being running. * @default */ this.isRunning = false; }; Phaser.Tween.prototype = { /** * Configure the Tween * * @method Phaser.Tween#to * @param {object} properties - Properties you want to tween. * @param {number} [duration=1000] - Duration of this tween in ms. * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Linear.None. * @param {boolean} [autoStart=false] - Whether this tween will start automatically or not. * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as Number.MAX_VALUE. This ignores any chained tweens. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. * @return {Phaser.Tween} This Tween object. */ to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { duration = duration || 1000; ease = ease || null; autoStart = autoStart || false; delay = delay || 0; repeat = repeat || 0; yoyo = yoyo || false; if (yoyo && repeat === 0) { repeat = 1; } var self; if (this._parent) { self = this._manager.create(this._object); this._lastChild.chain(self); this._lastChild = self; } else { self = this; this._parent = this; this._lastChild = this; } self._repeat = repeat; self._duration = duration; self._valuesEnd = properties; if (ease !== null) { self._easingFunction = ease; } if (delay > 0) { self._delayTime = delay; } self._yoyo = yoyo; if (autoStart) { return this.start(); } else { return this; } }, /** * Starts the tween running. Can also be called by the autoStart parameter of Tween.to. * * @method Phaser.Tween#start * @return {Phaser.Tween} Itself. */ start: function () { if (this.game === null || this._object === null) { return; } this._manager.add(this); this.isRunning = true; this._onStartCallbackFired = false; this._startTime = this.game.time.now + this._delayTime; for (var property in this._valuesEnd) { // check if an Array was provided as property value if (Array.isArray(this._valuesEnd[property])) { if (this._valuesEnd[property].length === 0) { continue; } // create a local copy of the Array with the start value at the front this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property]); } this._valuesStart[property] = this._object[property]; if (!Array.isArray(this._valuesStart[property])) { this._valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings } this._valuesStartRepeat[property] = this._valuesStart[property] || 0; } return this; }, /** * This will generate an array populated with the tweened object values from start to end. * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and similar functions. * It ignores delay and repeat counts and any chained tweens. Just one play through of tween data is returned, including yoyo if set. * * @method Phaser.Tween#generateData * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. * @return {array} An array of tweened values. */ generateData: function (frameRate, data) { if (this.game === null || this._object === null) { return null; } this._startTime = 0; for (var property in this._valuesEnd) { // Check if an Array was provided as property value if (Array.isArray(this._valuesEnd[property])) { if (this._valuesEnd[property].length === 0) { continue; } // create a local copy of the Array with the start value at the front this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property]); } this._valuesStart[property] = this._object[property]; if (!Array.isArray(this._valuesStart[property])) { this._valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings } this._valuesStartRepeat[property] = this._valuesStart[property] || 0; } // Simulate the tween. We will run for frameRate * (this._duration / 1000) (ms) var time = 0; var total = Math.floor(frameRate * (this._duration / 1000)); var tick = this._duration / total; var output = []; while (total--) { var property; var elapsed = (time - this._startTime) / this._duration; elapsed = elapsed > 1 ? 1 : elapsed; var value = this._easingFunction(elapsed); var blob = {}; for (property in this._valuesEnd) { var start = this._valuesStart[property] || 0; var end = this._valuesEnd[property]; if (end instanceof Array) { blob[property] = this._interpolationFunction(end, value); } else { // Parses relative end values with start as base (e.g.: +10, -3) if (typeof(end) === 'string') { end = start + parseFloat(end, 10); } // protect against non numeric properties. if (typeof(end) === 'number') { blob[property] = start + ( end - start ) * value; } } } output.push(blob); time += tick; } if (this._yoyo) { var reversed = output.slice(); reversed.reverse(); output = output.concat(reversed); } if (typeof data !== 'undefined') { data = data.concat(output); return data; } else { return output; } }, /** * Stops the tween if running and removes it from the TweenManager. If there are any onComplete callbacks or events they are not dispatched. * * @method Phaser.Tween#stop * @return {Phaser.Tween} Itself. */ stop: function () { this.isRunning = false; this._onUpdateCallback = null; this._manager.remove(this); return this; }, /** * Sets a delay time before this tween will start. * * @method Phaser.Tween#delay * @param {number} amount - The amount of the delay in ms. * @return {Phaser.Tween} Itself. */ delay: function (amount) { this._delayTime = amount; return this; }, /** * Sets the number of times this tween will repeat. * * @method Phaser.Tween#repeat * @param {number} times - How many times to repeat. * @return {Phaser.Tween} Itself. */ repeat: function (times) { this._repeat = times; return this; }, /** * A tween that has yoyo set to true will run through from start to finish, then reverse from finish to start. * Used in combination with repeat you can create endless loops. * * @method Phaser.Tween#yoyo * @param {boolean} yoyo - Set to true to yoyo this tween. * @return {Phaser.Tween} Itself. */ yoyo: function(yoyo) { this._yoyo = yoyo; if (yoyo && this._repeat === 0) { this._repeat = 1; } return this; }, /** * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. * * @method Phaser.Tween#easing * @param {function} easing - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. * @return {Phaser.Tween} Itself. */ easing: function (easing) { this._easingFunction = easing; return this; }, /** * Set interpolation function the tween will use, by default it uses Phaser.Math.linearInterpolation. * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. * * @method Phaser.Tween#interpolation * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) * @return {Phaser.Tween} Itself. */ interpolation: function (interpolation) { this._interpolationFunction = interpolation; return this; }, /** * You can chain tweens together by passing a reference to the chain function. This enables one tween to call another on completion. * You can pass as many tweens as you like to this function, they will each be chained in sequence. * * @method Phaser.Tween#chain * @return {Phaser.Tween} Itself. */ chain: function () { this._chainedTweens = arguments; return this; }, /** * Loop a chain of tweens * * Usage: * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) * .loop(); * @method Phaser.Tween#loop * @return {Phaser.Tween} Itself. */ loop: function() { this._lastChild.chain(this); return this; }, /** * Sets a callback to be fired each time this tween updates. Note: callback will be called in the context of the global scope. * * @method Phaser.Tween#onUpdateCallback * @param {function} callback - The callback to invoke each time this tween is updated. * @return {Phaser.Tween} Itself. */ onUpdateCallback: function (callback, callbackContext) { this._onUpdateCallback = callback; this._onUpdateCallbackContext = callbackContext; return this; }, /** * Pauses the tween. * * @method Phaser.Tween#pause */ pause: function () { this._codePaused = true; this._paused = true; this._pausedTime = this.game.time.now; }, /** * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. * @method Phaser.Tween#_pause * @private */ _pause: function () { if (!this._codePaused) { this._paused = true; this._pausedTime = this.game.time.now; } }, /** * Resumes a paused tween. * * @method Phaser.Tween#resume */ resume: function () { if (this._paused) { this._paused = false; this._codePaused = false; this._startTime += (this.game.time.now - this._pausedTime); } }, /** * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. * @method Phaser.Tween#_resume * @private */ _resume: function () { if (this._codePaused) { return; } else { this._startTime += this.game.time.pauseDuration; this._paused = false; } }, /** * Core tween update function called by the TweenManager. Does not need to be invoked directly. * * @method Phaser.Tween#update * @param {number} time - A timestamp passed in by the TweenManager. * @return {boolean} false if the tween has completed and should be deleted from the manager, otherwise true (still active). */ update: function (time) { if (this.pendingDelete) { return false; } if (this._paused || time &lt; this._startTime) { return true; } var property; if (time &lt; this._startTime) { return true; } if (this._onStartCallbackFired === false) { this.onStart.dispatch(this._object); this._onStartCallbackFired = true; } var elapsed = (time - this._startTime) / this._duration; elapsed = elapsed > 1 ? 1 : elapsed; var value = this._easingFunction(elapsed); for (property in this._valuesEnd) { var start = this._valuesStart[property] || 0; var end = this._valuesEnd[property]; if (end instanceof Array) { this._object[property] = this._interpolationFunction(end, value); } else { // Parses relative end values with start as base (e.g.: +10, -3) if (typeof(end) === 'string') { end = start + parseFloat(end, 10); } // protect against non numeric properties. if (typeof(end) === 'number') { this._object[property] = start + ( end - start ) * value; } } } if (this._onUpdateCallback !== null) { this._onUpdateCallback.call(this._onUpdateCallbackContext, this, value); } if (elapsed == 1) { if (this._repeat > 0) { if (isFinite(this._repeat)) { this._repeat--; } // reassign starting values, restart by making startTime = now for (property in this._valuesStartRepeat) { if (typeof(this._valuesEnd[property]) === 'string') { this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property], 10); } if (this._yoyo) { var tmp = this._valuesStartRepeat[property]; this._valuesStartRepeat[property] = this._valuesEnd[property]; this._valuesEnd[property] = tmp; this._reversed = !this._reversed; } this._valuesStart[property] = this._valuesStartRepeat[property]; } this._startTime = time + this._delayTime; this.onLoop.dispatch(this._object); return true; } else { this.isRunning = false; this.onComplete.dispatch(this._object); for (var i = 0, numChainedTweens = this._chainedTweens.length; i &lt; numChainedTweens; i ++) { this._chainedTweens[i].start(time); } return false; } } return true; } }; Phaser.Tween.prototype.constructor = Phaser.Tween; </pre> </article> </section> </div> <div class="clearfix"></div> <footer> <span class="copyright"> Phaser Copyright © 2012-2014 Photon Storm Ltd. </span> <br /> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.0-dev</a> on Tue Apr 29 2014 14:51:17 GMT+0100 (BST) using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>. </span> </footer> </div> <br clear="both"> </div> </div> <script src="scripts/sunlight.js"></script> <script src="scripts/sunlight.javascript.js"></script> <script src="scripts/sunlight-plugin.doclinks.js"></script> <script src="scripts/sunlight-plugin.linenumbers.js"></script> <script src="scripts/sunlight-plugin.menu.js"></script> <script src="scripts/jquery.min.js"></script> <script src="scripts/jquery.scrollTo.js"></script> <script src="scripts/jquery.localScroll.js"></script> <script src="scripts/bootstrap-dropdown.js"></script> <script src="scripts/toc.js"></script> <script> Sunlight.highlightAll({lineNumbers:true, showMenu: true, enableDoclinks :true}); </script> <script> $( function () { $( "#toc" ).toc( { anchorName : function(i, heading, prefix) { return $(heading).attr("id") || ( prefix + i ); }, selectors : "h1,h2,h3,h4", showAndHide : false, scrollTo : 60 } ); $( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); } ); </script> </body> </html>
BoldBigflank/attbee
docs/Tween.js.html
HTML
mit
35,765
#!/usr/bin/env python """ The pyligadb module is a small python wrapper for the OpenLigaDB webservice. The pyligadb module has been released as open source under the MIT License. Copyright (c) 2014 Patrick Dehn Due to suds, the wrapper is very thin, but the docstrings may be helpful. Most of the methods of pyligadb return a list containing the requested data as objects. So the attributes of the list items are accessible via the dot notation (see example below). For a more detailed description of the return values see the original documentation: http://www.openligadb.de/Webservices/Sportsdata.asmx Example use (prints all matches at round 14 in season 2010 from the Bundesliga): >>> from pyligadb.pyligadb import API >>> matches = API().getMatchdataByGroupLeagueSaison(14, 'bl1', 2010) >>> for match in matches: >>> print u"{} vs. {}".format(match.nameTeam1, match.nameTeam2) 1. FSV Mainz 05 vs. 1. FC Nuernberg 1899 Hoffenheim vs. Bayer Leverkusen ... ... """ __version__ = "0.1.1" try: from suds.client import Client except ImportError: raise Exception("pyligadb requires the suds library to work. " "https://fedorahosted.org/suds/") class API: def __init__(self): self.client = Client('http://www.openligadb.de/Webservices/' 'Sportsdata.asmx?WSDL').service def getAvailGroups(self, leagueShortcut, leagueSaison): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer) @return: A list of available groups (half-final, final, etc.) for the specified league and season. """ return self.client.GetAvailGroups(leagueShortcut, leagueSaison)[0] def getAvailLeagues(self): """ @return: A list of all in OpenLigaDB available leagues. """ return self.client.GetAvailLeagues()[0] def getAvailLeaguesBySports(self, sportID): """ @param sportID: The id related to a specific sport. Use getAvailSports() to get all IDs. @return: A list of all in OpenLigaDB available leagues of the specified sport. """ return self.client.GetAvailLeaguesBySports(sportID)[0] def getAvailSports(self): """ @return: An object containing all in OpenLigaDB available sports. """ return self.client.GetAvailSports()[0] def getCurrentGroup(self, leagueShortcut): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @return: An object containing information about the current group for the specified league (i.e. the round ("Spieltag") of the German Bundesliga). """ return self.client.GetCurrentGroup(leagueShortcut) def getCurrentGroupOrderID(self, leagueShortcut): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @return: The current group-ID for the specified league (see getCurrentGroup()) as int value. """ return self.client.GetCurrentGroupOrderID(leagueShortcut) def getGoalGettersByLeagueSaison(self, leagueShortcut, leagueSaison): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer). @return: A list of scorers from the specified league and season, sorted by goals scored. """ return self.client.GetGoalGettersByLeagueSaison(leagueShortcut, leagueSaison)[0] def getGoalsByLeagueSaison(self, leagueShortcut, leagueSaison): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer). @return: A list of all goals from the specified league and season. """ return self.client.GetGoalsByLeagueSaison(leagueShortcut, leagueSaison)[0] def getGoalsByMatch(self, matchID): """ @param matchID: The ID of a specific Match. Use i.e. getLastMatch() to obtain an ID. @return: A list of all goals from the specified match or None. """ result = self.client.GetGoalsByMatch(matchID) if result == "": return None else: return result[0] def getLastChangeDateByGroupLeagueSaison(self, groupOrderID, leagueShortcut, leagueSaison): """ @param groupOrderID: The id of a specific group. Use i.e. getCurrentGroupOrderID() to obtain an ID. @param leagueShortcut: Shortcut for a specific leagueself. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer). @return: The date of the last change as datetime object. """ return self.client.GetLastChangeDateByGroupLeagueSaison(groupOrderID, leagueShortcut, leagueSaison) def getLastChangeDateByLeagueSaison(self, leagueShortcut, leagueSaison): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer). @return: The date of the last change as datetime object. """ return self.client.GetLastChangeDateByLeagueSaison(leagueShortcut, leagueSaison) def getLastMatch(self, leagueShortcut): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @return: An object containing information about the last match from the specified league. """ return self.client.GetLastMatch(leagueShortcut) def getLastMatchByLeagueTeam(self, leagueID, teamID): """ @param leagueID: Shortcut for a specific league. Use getAvailLeagues() to get all IDs. @param teamID: The ID of a team, which cab be obtained by using getTeamsByLeagueSaison() @return: An object containing information about the last played match """ return self.client.GetLastMatchByLeagueTeam(leagueID, teamID) def getMatchByMatchID(self, matchID): """ @param matchID: The ID of a specific Match. Use i.e. getNextMatch() to obtain an ID. @return: An object containing information about the specified match. """ return self.client.GetMatchByMatchID(matchID) def getMatchdataByGroupLeagueSaison(self, groupOrderID, leagueShortcut, leagueSaison): """ @param groupOrderID: The ID of a specific group. Use i.e. getCurrentGroupOrderID() to obtain an ID. @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer). @return: A list of matches. Each list item is an object containing detailed information about the specified group/round. """ return self.client.GetMatchdataByGroupLeagueSaison(groupOrderID, leagueShortcut, leagueSaison)[0] def getMatchdataByGroupLeagueSaisonJSON(self, groupOrderID, leagueShortcut, leagueSaison): """ @param groupOrderID: The ID of a specific group. Use i.e. getCurrentGroupOrderID() to obtain an ID. @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer). @return: A JSON-Object containing detailed information about the specified group/round. """ return self.client.GetMatchdataByGroupLeagueSaison(groupOrderID, leagueShortcut, leagueSaison) def getMatchdataByLeagueDateTime(self, fromDateTime, toDateTime, leagueShortcut): """ @param fromDateTime: limit the result to matches later than fromDateTime @type fromDateTime: datetime.datetime @param toDateTime: limit the result to matches earlier than toDateTime @type toDateTime: datetime.datetime @return: A list of matches in the specified period. """ return self.client.GetMatchdataByLeagueDateTime(fromDateTime, toDateTime, leagueShortcut)[0] def getMatchdataByLeagueSaison(self, leagueShortcut, leagueSaison): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer). @return: A list of all matches in the specified league and season. @note: May take some time... """ return self.client.GetMatchdataByLeagueSaison(leagueShortcut, leagueSaison)[0] def getMatchdataByTeams(self, teamID1, teamID2): """ @param teamID1: ID of the first team. Use i.e. getTeamsByLeagueSaison() to obtain team IDs. @param teamID1: ID of the second team. @return: A list of matches, at which the specified teams play against each other. """ return self.client.GetMatchdataByTeams(teamID1, teamID2)[0] def getNextMatch(self, leagueShortcut): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @return: An object containing information about the next match from the specified league. """ return self.client.GetNextMatch(leagueShortcut) def getNextMatchByLeagueTeam(self, leagueID, teamID): """ @param leagueID: Shortcut for a specific league. Use getAvailLeagues() to get all IDs. @param teamID: The ID of a team, which cab be obtained by using getTeamsByLeagueSaison() @return: An object containing information about the next match """ return self.client.GetNextMatchByLeagueTeam(leagueID, teamID) def getTeamsByLeagueSaison(self, leagueShortcut, leagueSaison): """ @param leagueShortcut: Shortcut for a specific league. Use getAvailLeagues() to get all shortcuts. @param leagueSaison: A specific season (i.e. the date 2011 as integer). @return: A list of all teams playing in the specified league and season. """ return self.client.GetTeamsByLeagueSaison(leagueShortcut, leagueSaison)[0]
pedesen/pyligadb
pyligadb.py
Python
mit
11,013
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Comp4615Component } from './comp-4615.component'; describe('Comp4615Component', () => { let component: Comp4615Component; let fixture: ComponentFixture<Comp4615Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Comp4615Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Comp4615Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
angular/angular-cli-stress-test
src/app/components/comp-4615/comp-4615.component.spec.ts
TypeScript
mit
847
<div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> Import Data Prodi </div> <div class="panel-body"> <h3>Sebelum mengupload, pastikan file anda berformat .xls/.xlsx</h3> <br> <div class="row"> <?php echo form_open_multipart('admin/Prodi/do_upload',array('accept-charset'=>"utf-8")); ?> <div class="col-lg-12"> <div class="form-group"> <label>Unduh Format Prodi</label> <td><a href="javascript:prd_download('prodi.xls')"><?php echo "prodi.xls"; ?></a></td> </div> <div class="form-group"> <label>File Prodi</label> <input class="form-control" type="file" name="file" id="file"> <label><input type="checkbox" name="drop" value="1" /> <u>Kosongkan tabel sql terlebih dahulu.</u> </label> </div> </div> <div class="col-lg-12"> <button type="submit" class="btn btn-primary">Import</button> <a class="btn btn-danger" href="<?php echo base_url('admin/Prodi'); ?>">Batal</a> </div> <?php echo form_close(); ?> </div> </div> </div> </div> </div> <script src="<?php echo base_url('assets/template/Bluebox/assets/js/jquery-1.10.2.js');?>"></script> <script type="text/javascript"> function prd_download(file) { file_name = file; window.location.href = "<?php echo site_url('admin/Dashboard/file_download') ?>?file_name="+ file_name; } </script>
andresiantana/employee_web
application/modules/admin/views/prodi/import.php
PHP
mit
1,864
using Twilio.TwiML; class Example { static void Main() { var response = new VoiceResponse(); response.Dial("415-123-4567"); response.Redirect("http://www.foo.com/nextInstructions"); System.Console.WriteLine(response.ToString()); } }
teoreteetik/api-snippets
twiml/voice/redirect/redirect-2/redirect-2.5.x.cs
C#
mit
280
#SimpleFtp | | Production | Dev | | ----------:| ---------- | --- | | AppVeyor | [![Build status](https://ci.appveyor.com/api/projects/status/najmvwr4ff7l637x?svg=true)](https://ci.appveyor.com/project/PureKrome/simpleftp-33rxa) | [![Build status](https://ci.appveyor.com/api/projects/status/3uegfn36fu0hw2ji?svg=true)](https://ci.appveyor.com/project/PureKrome/simpleftp) | NuGet | [![NuGet Badge](https://buildstats.info/nuget/SimpleFtp)](https://www.nuget.org/packages/SimpleFtp/) | [![MyGet Badge](https://buildstats.info/myget/simpleftp/simpleftp)](https://www.myget.org/feed/simpleftp/package/nuget/simpleftp) | --- ### SimpleFtp This library is a simple interface and wrapper-class for the `System.Net.WebClient` class. This helps make testing easier (e.g. you can inject this into your services to remove any hard integration dependencies). ### Usage. 1. `install-package simpleftp` (choose from NuGet (for stable) or MyGet (for development)) 2. add some code to where u wish to use it ``` // Note: safety checks, etc are obmitted for brevity. // -------------------------------- // Create some service, which does some Ftp stuff. // -------------------------------- private readonly IFtpService _ftpService; public SomeService(IFtpService ftpService) { _ftpService = ftpService; } // This is the method which will end up doing some Ftp stuff. public async Task SomeMethodAsync() { var someFileContent = "whatever"; var someFileName = "whatever.txt"; // Boom! Money-shot. await _ftpService.UploadAsync(someFileContent, someFileName); } // -------------------------------- // Lets now consume the service (which does some ftp stuff) // -------------------------------- // Setup the service... var loggingService = new LoggingService(); var ftpService = new FtpService("ftp.blahblah.com", "someUsername", "somePassword", loggingService); var someService = new SomeService(ftpService); // Execute your custom code, which ends up executing the underlying FTP method. await someService.SomeMethodAsync(); ``` Hope this helps! --- [![I'm happy to accept tips](http://img.shields.io/gittip/purekrome.svg?style=flat-square)](https://gratipay.com/PureKrome/) ![Lic: MIT](http://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)
PureKrome/SimpleFtp
README.md
Markdown
mit
2,353
/* * Example Unity Component * (c) Copyright 2017, Warwick Molloy * GitHub repo WazzaMo/UnityComponents * Provided under the terms of the MIT License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.UI; using Tools.Common; using Actor.Shader; namespace ActorKitExamples.ComputeShaders.Script { public class ParallelSumDriverComponent : MonoBehaviour { const string SHADER_PATH = "ParallelSum", KERNEL_NAME = "ParallelSumCS", BUFFER_VALUESIN = "valuesIn", BUFFER_RESULTOUT = "sumOut"; public float[] __ValuesIn = null; public Text _Output = null; private ComputeShader _Shader; private int _SumKernel; private float __SumOut; private ComputeBuffer _ValuesInBuffer; private ComputeBuffer _SumOutBuffer; private bool _IsReady; private void Start() { SetupShader(); CheckOutput(); SetupValuesBuffer(); SetupSumOut(); } public void Run() { if (_IsReady) { _Shader.Dispatch(_SumKernel, 1, 1, 1); float[] sumVal = new float[1]; _SumOutBuffer.GetData(sumVal); _Output.text = sumVal[0].ToString(); } } private void OnDestroy() { DisposablesUtil.DisposeAll(_ValuesInBuffer, _SumOutBuffer); } private void SetupShader() { _Shader = ComputeShaderUtil.FindComputeOrWarn(SHADER_PATH, out _IsReady); _SumKernel = _Shader.FindKernelOrWarn(KERNEL_NAME, ref _IsReady); } private void SetupValuesBuffer() { _IsReady = _IsReady && __ValuesIn != null; if (_IsReady) { _ValuesInBuffer = ComputeBufferUtil.CreateBufferForSimpleArray<float>(__ValuesIn); _Shader.SetBuffer(_SumKernel, BUFFER_VALUESIN, _ValuesInBuffer); } } private void SetupSumOut() { __SumOut = 0f; if (_IsReady) { _SumOutBuffer = ComputeBufferUtil.CreateBufferForStruct<float>(__SumOut); _Shader.SetBuffer(_SumKernel, BUFFER_RESULTOUT, _SumOutBuffer); } } private void CheckOutput() { this.AreAllEditorValuesConfigured(ref _IsReady, _Output); } } }
WazzaMo/UnityComponents
ActorKitExamples/ComputeShaders/Script/ParallelSumDriverComponent.cs
C#
mit
2,456
// EXPRESS SERVER HERE // // BASE SETUP var express = require('express'), app = express(), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), session = require('express-session'), methodOverride = require('method-override'), // routes = require('./routes/routes'), morgan = require('morgan'), serveStatic = require('serve-static'), errorHandler = require('errorhandler'); // =========================CONFIGURATION===========================// // =================================================================// app.set('port', process.env.PORT || 9001); /* * Set to 9001 to not interfere with Gulp 9000. * If you're using Cloud9, or an IDE that uses a different port, process.env.PORT will * take care of your problems. You don't need to set a new port. */ app.use(serveStatic('app', {'index': 'true'})); // Set to True or False if you want to start on Index or not app.use('/bower_components', express.static(__dirname + '/bower_components')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(morgan('dev')); app.use(cookieParser('secret')); app.use(session({secret: 'evernote now', resave: true, saveUninitialized: true})); app.use(function(req, res, next) { res.locals.session = req.session; next(); }); if (process.env.NODE_ENV === 'development') { app.use(errorHandler()); } // ==========================ROUTER=================================// // =================================================================// // ROUTES FOR THE API - RUN IN THE ORDER LISTED var router = express.Router(); // ------------- ROUTES ---------------- // // REGISTERING THE ROUTES app.use('/', router); // STARTING THE SERVER console.log('Serving on port ' + app.get('port') + '. Serving more Nodes than Big Macs!'); app.listen(app.get('port')); // Not used if Gulp is activated - it is bypassed exports = module.exports = app; // This is needed otherwise the index.js for routes will not work
Kinddle/soxy
server/server.js
JavaScript
mit
2,047
//Capturar possibles errors process.on('uncaughtException', function(err) { console.log(err); }); //Importar mòdul net var net = require('net') //Port d'escolta del servidor var port = 8002; //Crear servidor TCP net.createServer(function(socket){ socket.on('data', function(data){ //Parse dades JSON var json=JSON.parse(data); //Importar mòdul theThingsCoAP var theThingsCoAP = require('../../') //Crear client theThingsCoAP var client = theThingsCoAP.createClient() client.on('ready', function () { read(json.endDate) }) //Funció per llegir dades de la plataforma thethings.iO function read(endDate){ client.thingRead(json.key, {limit: 100,endDate: endDate, startDate: json.startDate}, function (error, data) { if (typeof data!=='undefined' && data!==null){ if (data.length > 0) { var dataSend="" var coma="," for (var i=0;i<=(data.length - 1);i++){ dataSend=dataSend+data[i].value+coma+data[i].datetime.split('T')[1]+coma } socket.write(dataSend); read(data[data.length - 1].datetime.split('.')[0].replace(/-/g, '').replace(/:/g, '').replace('T', '')) }else{ socket.write("</FINAL>"); } } }) } }); //Configuració del port en el servidor TCP }).listen(port);
rromero83/thethingsio-coap-openDemo
openDemo/read/Read.js
JavaScript
mit
1,304
using System; using System.Text; using System.Collections.Generic; using System.Linq; using NHibernate.Mapping.ByCode.Conformist; using NHibernate.Mapping.ByCode; using nHibernateSample.Domain; namespace nHibernateSample.Mapping { public class CDDAMap : ClassMapping<CDDA> { public CDDAMap() { Schema("dbo"); Lazy(true); Id(x => x.Primarykey, map => map.Generator(Generators.Guid)); Property(x => x.Totaltracks); Property(x => x.Name); ManyToOne( x => x.Publisher, map => { map.Column("Publisher"); map.Cascade(Cascade.None); }); } } }
Flexberry/FlexberryORM-DemoApp
nHibernate/nHibernateSample/Mapping/CDDAMap.cs
C#
mit
766
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace VigenereBruteForce.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("VigenereBruteForce.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
Skinner927/Vigenere-Key-Guesser
VigenereBruteForce/VigenereBruteForce/Properties/Resources.Designer.cs
C#
mit
2,795
#ifndef __H_VECTOR__ #define __H_VECTOR__ struct Vector3D { float x, y, z; }; #endif /* __H_VECTOR__ */
cthielen/coriolis
vector.h
C
mit
107
import { GET_WAREHOUSES_FULL_LIST, GET_WAREHOUSE, GET_COMPANIES, GET_SUPERVISORS } from '../actions/warehouses'; import humanize from 'humanize'; import Moment from 'moment'; const INITIAL_STATE = { warehousesList: [], warehouseDetail: {}, warehouseId: 0, companiesList: [], supervisorsList: [] }; export default function(state = INITIAL_STATE, action) { switch(action.type) { case GET_WAREHOUSES_FULL_LIST: return { ...state, warehousesList: action.payload.data.map(function(warehouse) { return { company: warehouse.company, supervisor: warehouse.supervisor, email: warehouse.email, telephone: warehouse.telephone, address: warehouse.address, contact_name: warehouse.contact_name, action: warehouse.id }; }) }; case GET_WAREHOUSE: return { ...state, warehouseDetail: { company: action.payload.data[0].company_id, supervisor: action.payload.data[0].supervisor_id, name: action.payload.data[0].name, email: action.payload.data[0].email, telephone: action.payload.data[0].telephone, address: action.payload.data[0].address, tax: action.payload.data[0].tax, contact_name: action.payload.data[0].contact_name }, warehouseId: action.payload.data[0].id } case GET_COMPANIES: return { ...state, companiesList: action.payload.data.map(function(company) { return { value: company.id, label: company.name } }) } case GET_SUPERVISORS: return { ...state, supervisorsList: action.payload.data.map(function(supervisor) { return { value: supervisor.id, label: supervisor.name } }) } default: return state; } }
Xabadu/VendOS
src/reducers/reducer_warehouses.js
JavaScript
mit
2,069
set_unless[:unicorn][:cow_friendly] = "true"
kmayer/cookbooks
unicorn/attributes/unicorn.rb
Ruby
mit
45
<?php namespace JPI\UserBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder->root('jpi_user'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
guenillon/solux
src/JPI/UserBundle/DependencyInjection/Configuration.php
PHP
mit
859
# 从 dva 迁移 ## 1. 新建模型 将 effect 移入模型类中,可定义 async 函数,函数内如果需要使修改立即生效,可调用 `this.applyChange()` ```ts export class FooModel extends BaseStore { data: { xxx: number }; bar() { this.data.xxx = 1; this.applyChange(); // render 1 this.data.xxx = 2; this.data.xxx = 3; } // render 3 } ``` ## 2. 切换 connect 将 `import { connect } from 'odux';` 切换为 `import { connect } from 'odux';`。 odux 的 connect 兼容 react-redux/dva 的 connect。(类组件) \*同一组件内混合使用注意: - 目前 connect 传递的 dispatch 不会过 dva 的 promise、saga 中间件,promise dispatch 不可用 ## 3. 添加注入 - 将 connect 中相关的 pick 删除 - 添加模型 @inject ```ts @connect((state) => ({ --- foo: state.foo, })) export class FooComponent extends React.PureComponent { @inject() fooModel: FooModel; @inject({ getter: ioc => ioc.get(FooModel).data }) fooModel: { xxx: number }; render() { --- const { foo } = this.props; +++ const foo = this.fooModel; } } ```
zhang740/odux
docs/move-from-dva_zh-CN.md
Markdown
mit
1,120
<!DOCTYPE html> <!--[if IEMobile 7]><html class="iem7 no-js" lang="en" dir="ltr"><![endif]--> <!--[if lt IE 7]><html class="lt-ie9 lt-ie8 lt-ie7 no-js" lang="en" dir="ltr"><![endif]--> <!--[if (IE 7)&(!IEMobile)]><html class="lt-ie9 lt-ie8 no-js" lang="en" dir="ltr"><![endif]--> <!--[if IE 8]><html class="lt-ie9 no-js" lang="en" dir="ltr"><![endif]--> <!--[if (gt IE 8)|(gt IEMobile 7)]><!--> <html class="no-js not-oldie" lang="en" dir="ltr"> <!--<![endif]--> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="HandheldFriendly" content="true" /> <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" /> <meta name="MobileOptimized" content="width" /> <meta http-equiv="cleartype" content="on" /> <meta http-equiv="ImageToolbar" content="false" /> <meta name="viewport" content="width=device-width" /> <meta name="version" content="20161218" /> <!--googleon: all--> <meta name="DC.description" content="" /> <meta name="DC.title" content="" /> <title> Pyrolytic Cook Stoves and Biochar Production in Kenya: A Whole Systems Approach to Sustainable Energy, Environmental Health, and Human Prosperity| Research Project Database | Grantee Research Project | ORD | US EPA</title> <!--googleoff: snippet--> <meta name="keywords" content="" /> <link rel="shortlink" href="" /> <link rel="canonical" href="" /> <meta name="DC.creator" content="" /> <meta name="DC.language" content="en" /> <meta name="DC.Subject.epachannel" content="" /> <meta name="DC.type" content="" /> <meta name="DC.date.created" content="" /> <meta name="DC.date.modified" content="2012-11-27" /> <!--googleoff: all--> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" /> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" /> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" /> <!--[if lt IE 9]><link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/ie.css" media="all" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" /> <link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" /> <link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" /> <!--[if lt IE 9]><script src="https://www.epa.gov/sites/all/themes/epa/js/html5.js"></script><![endif]--> <style type="text/css"> /*This style needed for highlight link. Please do not remove*/ .hlText { font-family: "Arial"; color: red; font-weight: bold; font-style: italic; background-color: yellow; } .tblClass { font-size:smaller; min-width: 10%; line-height: normal; } </style> </head> <!-- NOTE, figure out body classes! --> <body class="node-type-(web-area|page|document|webform) (microsite|resource-directory)" > <!-- Google Tag Manager --> <noscript> <iframe src="//www.googletagmanager.com/ns.html?id=GTM-L8ZB" height="0" width="0" style="display:none;visibility:hidden"></iframe> </noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-L8ZB');</script> <!-- End Google Tag Manager --> <div class="skip-links"><a href="#main-content" class="skip-link element-invisible element-focusable">Jump to main content</a></div> <header class="masthead clearfix" role="banner"> <img class="site-logo" src="https://www.epa.gov/sites/all/themes/epa/logo.png" alt="" /> <hgroup class="site-name-and-slogan"> <h1 class="site-name"><a href="https://www.epa.gov/" title="Go to the home page" rel="home"><span>US EPA</span></a></h1> <div class="site-slogan">United States Environmental Protection Agency</div> </hgroup> <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch"> <label class="element-hidden" for="search-box">Search</label> <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/> <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button> <input type="hidden" name="fld" value="" /> <input type="hidden" name="areaname" value="" /> <input type="hidden" name="areacontacts" value="" /> <input type="hidden" name="areasearchurl" value="" /> <input type="hidden" name="typeofsearch" value="epa" /> <input type="hidden" name="result_template" value="2col.ftl" /> <input type="hidden" name="filter" value="sample4filt.hts" /> </form> </header> <section id="main-content" class="main-content clearfix" role="main"> <div class="region-preface clearfix"> <div id="block-pane-epa-web-area-connect" class="block block-pane contextual-links-region"> <ul class="menu utility-menu"> <li class="menu-item"><a href="https://www.epa.gov/research-grants/forms/contact-us-about-research-grants" class="menu-link contact-us">Contact Us</a></li> </ul> </div> </div> <div class="main-column clearfix"> <!--googleon: all--> <div class="panel-pane pane-node-content" > <div class="pane-content"> <div class="node node-page clearfix view-mode-full"> <div class="box multi related-info right clear-right" style="max-width:300px; font-size:14px;"><!--googleoff: index--> <h5 class="pane-title">Project Research Results</h5> <div class="pane-content"> <ul> <li><a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.abstractDetail/abstract/9871/report/F">Final Report</a></li> <li><a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.abstractDetail/abstract/10195">P3 Phase II</a> </li> </ul> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.publications/abstract/9871">2 publications for this project</a><br /> </div> <!-- RFA Search start --> <h5 class="pane-title">Related Information</h5> <div class="pane-content"> <ul><li><a href="https://www.epa.gov/research-grants/">Research Grants</a></li> <li><a href="https://www.epa.gov/P3">P3: Student Design Competition</a></li> <li><a href="https://www.epa.gov/research-fellowships/">Research Fellowships</a></li> <li><a href="https://www.epa.gov/sbir/">Small Business Innovation Research (SBIR)</a></li> <li><a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/search.welcome">Grantee Research Project Results Search</a></li> </ul> </div> <!-- RFA Search End --><!--googleon: index--> </div> <a name="content"></a> <h2> Pyrolytic Cook Stoves and Biochar Production in Kenya: A Whole Systems Approach to Sustainable Energy, Environmental Health, and Human Prosperity</h2> <b>EPA Grant Number:</b> SU835341<br /> <b>Title:</b> Pyrolytic Cook Stoves and Biochar Production in Kenya: A Whole Systems Approach to Sustainable Energy, Environmental Health, and Human Prosperity<br /> <b>Investigators:</b> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13890"> Hestrin, Rachel </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13303"> Edwards, Rufus D. </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13895"> Fisher, Elizabeth </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13893"> Guerena, David </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13894"> Lehmann, Johannes </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13892"> Torres, Dorisel </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13891"> Zwetsloot, Marie </a> <br /> <b>Current Investigators:</b> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13894"> Lehmann, Johannes </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/16078"> Davis, Jennifer </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13895"> Fisher, Elizabeth </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13893"> Guerena, David </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13890"> Hestrin, Rachel </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/16079"> Hsu, Tedman </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13892"> Torres, Dorisel </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13891"> Zwetsloot, Marie </a> <br /> <strong>Institution:</strong> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.institutionInfo/institution/8"> <b>Cornell University</b> </a> <br /> <strong>EPA Project Officer:</strong> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/13325"> Lank, Gregory </a> <br /> <b>Phase:</b> I<br /> <b>Project Period:</b> August 15, 2012 through August 14, 2013 <br /> <b>Project Amount:</b> $14,990 <br /> <b>RFA:</b> P3 Awards: A National Student Design Competition for Sustainability Focusing on People, Prosperity and the Planet (2012) <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.rfatext/rfa_id/548">RFA Text</a>&nbsp;|&nbsp; <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/recipients.display/rfa_id/548">Recipients Lists</a> <br /> <b>Research Category:</b> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/963">Pollution Prevention/Sustainable Development</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/1085">P3 Challenge Area - Agriculture</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/1154">P3 Challenge Area - Cook Stoves</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/1176">P3 Awards</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/1175">Sustainability</a> <br /> <br> <h3>Objective:</h3> <p> The principal objectives of this project are to improve human welfare and environmental health by (1) reducing air pollution from cook stoves, (2) conserving natural resources, (3) improving economic prosperity, and (4) minimizing water contamination from fertilizer. The development of pyrolytic cook stoves addresses these problems by generating clean and efficient energy, while simultaneously producing biochar. Biochar application to the soil can sequester carbon, mitigate soil degradation, improve nutrient use efficiency, and reduce pollution.</p> <p></p> <h3>Approach:</h3> <p> The project will achieve its objectives by (1) designing and testing a combined pyrolysis-biochar cook stove that is clean-burning, efficient, and user friendly, (2) assessing the stove&rsquo;s performance in rural Kenyan households, and (3) evaluating the potential for biochar to improve ecosystem services and water quality. Participatory research is an essential aspect of the project and will inform stove development, implementation, and biochar field trials. Collaboration between students in the United States, students in Kenya, and Kenyan stakeholders will enhance the understanding of relevant problems and ensure that approaches to these problems are appropriate and effective.</p> <p></p> <h3>Expected Results:</h3> <p> Anticipated results include reduced indoor air pollution, increased combustion efficiency, enhanced soil ecosystem services, improved water quality, and improved economic prosperity. Decreased emissions of particulate matter and greenhouse gases will contribute to human health and reduce stove contributions to climate change. Greater fuel efficiency will conserve natural resources and reduce the amount of time and resources spent gathering biomass. Additionally, the biochar produced by these stoves will sequester carbon from the atmosphere, maintain soil health, reduce dependence on synthetic fertilizers, and mitigate water contamination, which will contribute both to environmental health and human prosperity. The results from this work will inform further research, including the evaluation of pyrolysis stoves and biochar application for landscape-scale implementation.</p> <p></p> <h3>Publications and Presentations:</h3> Publications have been submitted on this project: <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.publications/abstract/9871">View all 2 publications for this project</a> </p> <h3>Supplemental Keywords:</h3> <i>fertilizer runoff, green engineering, utilization of agricultural waste streams, land conservation, soil health, soil fertility, renewable feedstocks</i> <p /> <P><h3>Relevant Websites:</h3> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.abstractDetail/abstract/10190/report/0">Phase 2 Abstract</a> <P><h3>Progress and Final Reports:</h3> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.abstractDetail/abstract/9871/report/F">Final Report</a><br> </P> <h3>P3 Phase II:</h3> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.abstractDetail/abstract/10195">Pyrolytic Cook Stoves And Biochar Production In Kenya: A Whole Systems Approach to Sustainable Energy, Environmental Health, and Human Prosperity</a> <br> </P> </div> </div> </div> <div id="block-epa-og-footer" class="block block-epa-og"> <p class="pagetop"><a href="#content">Top of Page</a></p> <!--googleoff: all--> <p id="epa-og-footer"> The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA. Conclusions drawn by the principal investigators have not been reviewed by the Agency. </p> </div> <!--googleoff: all--> </div> </section> <nav class="nav simple-nav simple-main-nav" role="navigation"> <div class="nav__inner"> <h2 class="element-invisible">Main menu</h2> <ul class="menu" role="menu"> <li class="menu-item" id="menu-learn" role="presentation"><a href="https://www.epa.gov/environmental-topics" title="Learn about EPA's environmental topics to help protect the environment in your home, workplace, and community and EPA&#039;s research mission is to conduct leading-edge research and foster the sound use of science and technology." class="menu-link" role="menuitem">Environmental Topics</a></li> <li class="menu-item" id="menu-lawsregs" role="presentation"><a href="https://www.epa.gov/laws-regulations" title="Laws written by Congress provide the authority for EPA to write regulations. Regulations explain the technical, operational, and legal details necessary to implement laws." class="menu-link" role="menuitem">Laws &amp; Regulations</a></li> <li class="menu-item" id="menu-about" role="presentation"><a href="https://www.epa.gov/aboutepa" title="Learn more about: our mission and what we do, how we are organized, and our history." class="menu-link" role="menuitem">About EPA</a></li> </ul> </div> </nav> <footer class="main-footer clearfix" role="contentinfo"> <div class="main-footer__inner"> <div class="region-footer"> <div class="block block-pane block-pane-epa-global-footer"> <div class="row cols-3"> <div class="col size-1of3"> <div class="col__title">Discover.</div> <ul class="menu"> <li><a href="https://www.epa.gov/accessibility">Accessibility</a></li> <li><a href="https://www.epa.gov/aboutepa/administrator-gina-mccarthy">EPA Administrator</a></li> <li><a href="https://www.epa.gov/planandbudget">Budget &amp; Performance</a></li> <li><a href="https://www.epa.gov/contracts">Contracting</a></li> <li><a href="https://www.epa.gov/home/grants-and-other-funding-opportunities">Grants</a></li> <li><a href="https://www.epa.gov/ocr/whistleblower-protections-epa-and-how-they-relate-non-disclosure-agreements-signed-epa-employees">No FEAR Act Data</a></li> <li><a href="https://www.epa.gov/home/privacy-and-security-notice">Privacy and Security</a></li> </ul> </div> <div class="col size-1of3"> <div class="col__title">Connect.</div> <ul class="menu"> <li><a href="https://www.data.gov/">Data.gov</a></li> <li><a href="https://www.epa.gov/office-inspector-general/about-epas-office-inspector-general">Inspector General</a></li> <li><a href="https://www.epa.gov/careers">Jobs</a></li> <li><a href="https://www.epa.gov/newsroom">Newsroom</a></li> <li><a href="https://www.whitehouse.gov/open">Open Government</a></li> <li><a href="http://www.regulations.gov/">Regulations.gov</a></li> <li><a href="https://www.epa.gov/newsroom/email-subscriptions">Subscribe</a></li> <li><a href="https://www.usa.gov/">USA.gov</a></li> <li><a href="https://www.whitehouse.gov/">White House</a></li> </ul> </div> <div class="col size-1of3"> <div class="col__title">Ask.</div> <ul class="menu"> <li><a href="https://www.epa.gov/home/forms/contact-us">Contact Us</a></li> <li><a href="https://www.epa.gov/home/epa-hotlines">Hotlines</a></li> <li><a href="https://www.epa.gov/foia">FOIA Requests</a></li> <li><a href="https://www.epa.gov/home/frequent-questions-specific-epa-programstopics">Frequent Questions</a></li> </ul> <div class="col__title">Follow.</div> <ul class="social-menu"> <li><a class="menu-link social-facebook" href="https://www.facebook.com/EPA">Facebook</a></li> <li><a class="menu-link social-twitter" href="https://twitter.com/epa">Twitter</a></li> <li><a class="menu-link social-youtube" href="https://www.youtube.com/user/USEPAgov">YouTube</a></li> <li><a class="menu-link social-flickr" href="https://www.flickr.com/photos/usepagov">Flickr</a></li> <li><a class="menu-link social-instagram" href="https://instagram.com/epagov">Instagram</a></li> </ul> <p class="last-updated">Last updated on Tuesday, November 27, 2012</p> </div> </div> </div> </div> </div> </footer> <script src="https://www.epa.gov/sites/all/libraries/template2/jquery.js"></script> <script src="https://www.epa.gov/sites/all/libraries/template/js.js"></script> <script src="https://www.epa.gov/sites/all/modules/custom/epa_core/js/alert.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.core.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.widget.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.position.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.autocomplete.min.js"></script> <!--[if lt IE 9]><script src="https://www.epa.gov/sites/all/themes/epa/js/ie.js"></script><![endif]--> <!-- REMOVE if not using --> <script language=javascript> <!-- // Activate cloak // pressing enter will not default submit the first defined button but the programmed defined button function chkCDVal(cdVal) { var isErr = true; try{ var CDParts = cdVal.split(','); var st = CDParts[0]; var cd = CDParts[1]; var objRegExp = new RegExp('[0-9][0-9]'); if (!isNaN(st)) { isErr = false; } if (!objRegExp.test(cd) || (cd.length>3)){ isErr = false; } } catch(err){ isErr = false; } return isErr; } function checkCongDist(cdtxt) { //alert(cdtxt.value); if (!chkCDVal(cdtxt.value)) { alert('Congressional District MUST be in the following format: state, district; example: Virginia, 08'); return false; } else { return true; } } function fnTrapKD(btn, event) { var btn = getObject(btn); if (document.all) { if (event.keyCode == 13) { event.returnValue=false;event.cancel = true;btn.click(); } } else { if (event.which == 13) { event.returnValue=false;event.cancelBubble = true;btn.click(); } } } function CheckFilter() { if (document.searchform.presetTopic.options[document.searchform.presetTopic.selectedIndex].value == 'NA'){ alert('You must select a subtopic. \n This item is not selectable'); document.searchform.presetTopic.options[0].selected = true; } } function openHelpWindow(url,title,scrollable) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars='+scrollable+',menubar=no,status=no'); win.focus(); } function openNewWindow(url,title,scrollable) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars='+scrollable+',menubar=no,status=no'); } function openNewWindow(url,title) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNewMapWindow(url,title) { var win = window.open(url,"title",'width=800,height=450,left=320,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNoticeWindow(url,title) { var win = window.open(url,"title",'width=300,height=150,left=500,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNewSearchWindow(site,subj) { title = 'window'; var win = window.open('https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.pubsearch/site/' + site + '/redirect/' + subj,"title",'width=640,height=480,resizable=1,scrollbars=yes,menubar=yes,status=no'); } function autoCheck(name) { document.forms['thisForm'].elements[name].checked = true; } function alertUser() { var ok = alert("This search might take longer than expected. Please refrain from hitting the refresh or reload button on your browser. The search results will appear after the search is complete. Thank you."); } function closePopupWindow(redirectUrl) { opener.location = redirectUrl; opener.focus(); this.close(); } //--> </script> </body> </html>
1wheel/scraping
epa-grants/research/raw/09871.html
HTML
mit
26,221
from django.contrib import admin from app.models import Home, Room, Thermostat, Door, Light, Refrigerator """ Administrator interface customization This module contains customization classes to the admin interface rendered by Django. This file is interpreted at run time to serve the custom administrator actions that correspond to the application's custom models. """ class ThermostatAdmin(admin.ModelAdmin): """ ModelAdmin """ list_display = ('name','home','current_temp','set_temp','pk') search_fields = ('name','home') class ThermostatInline(admin.StackedInline): """ StackedInline """ model = Thermostat class DoorAdmin(admin.ModelAdmin): """ ModelAdmin """ list_display = ('name','room','is_locked','is_open','pk') search_fields = ('name','room') class DoorInline(admin.StackedInline): """ StackedInline """ model = Door class LightAdmin(admin.ModelAdmin): """ ModelAdmin """ list_display = ('name','room','is_on','pk') search_fields = ('name','room') class LightInline(admin.StackedInline): """ StackedInline """ model = Light class RefrigeratorAdmin(admin.ModelAdmin): """ ModelAdmin """ list_display = ('name','room','fridge_set_temp','fridge_current_temp','freezer_set_temp','freezer_current_temp','pk') search_fields = ('name','room') class RefrigeratorInline(admin.StackedInline): """ StackedInline """ model = Refrigerator class RoomAdmin(admin.ModelAdmin): """ ModelAdmin """ list_display = ('name','home','room_type','pk') search_fields = ('name','home') inlines = (DoorInline, LightInline, RefrigeratorInline,) class RoomInline(admin.StackedInline): """ StackedInline """ model = Room class HomeAdmin(admin.ModelAdmin): list_display = ('name','owner','position','secret_key','pk') search_fields = ('name',) readonly_fields=('secret_key',) inlines = (ThermostatInline, RoomInline, ) admin.site.register(Home, HomeAdmin) admin.site.register(Thermostat, ThermostatAdmin) admin.site.register(Room, RoomAdmin) admin.site.register(Door, DoorAdmin) admin.site.register(Light, LightAdmin) admin.site.register(Refrigerator, RefrigeratorAdmin)
brabsmit/home-control
homecontrol/app/admin.py
Python
mit
2,233
""" Annotates Old Bird call detections in the BirdVox-70k archive. The annotations classify clips detected by the Old Bird Tseep and Thrush detectors according to the archive's ground truth call clips. This script must be run from the archive directory. """ from django.db.models import F from django.db.utils import IntegrityError import pandas as pd # Set up Django. This must happen before any use of Django, including # ORM class imports. import vesper.util.django_utils as django_utils django_utils.set_up_django() from vesper.django.app.models import ( AnnotationInfo, Clip, Processor, Recording, StringAnnotation, User) import vesper.django.app.model_utils as model_utils import scripts.old_bird_detector_eval.utils as utils # Set this `True` to skip actually annotating the Old Bird detections. # The script will still compute the classifications and print precision, # recall, and F1 statistics. This is useful for testing purposes, since # the script runs considerably faster when it doesn't annotate. ANNOTATE = True GROUND_TRUTH_DETECTOR_NAME = 'BirdVox-70k' # The elements of the pairs of numbers are (0) the approximate start offset # of a call within an Old Bird detector clip, and (1) the approximate # maximum duration of a call. The units of both numbers are seconds. DETECTOR_DATA = ( ('Old Bird Tseep Detector Redux 1.1', 'Call.High'), ('Old Bird Thrush Detector Redux 1.1', 'Call.Low'), ) CLASSIFICATION_ANNOTATION_NAME = 'Classification' CENTER_INDEX_ANNOTATION_NAME = 'Call Center Index' CENTER_FREQ_ANNOTATION_NAME = 'Call Center Freq' SAMPLE_RATE = 24000 def main(): rows = annotate_old_bird_calls() raw_df = create_raw_df(rows) aggregate_df = create_aggregate_df(raw_df) add_precision_recall_f1(raw_df) add_precision_recall_f1(aggregate_df) print(raw_df.to_csv()) print(aggregate_df.to_csv()) def annotate_old_bird_calls(): center_index_annotation_info = \ AnnotationInfo.objects.get(name=CENTER_INDEX_ANNOTATION_NAME) center_freq_annotation_info = \ AnnotationInfo.objects.get(name=CENTER_FREQ_ANNOTATION_NAME) classification_annotation_info = \ AnnotationInfo.objects.get(name=CLASSIFICATION_ANNOTATION_NAME) user = User.objects.get(username='Vesper') sm_pairs = model_utils.get_station_mic_output_pairs_list() ground_truth_detector = Processor.objects.get( name=GROUND_TRUTH_DETECTOR_NAME) rows = [] for detector_name, annotation_value in DETECTOR_DATA: short_detector_name = detector_name.split()[2] old_bird_detector = Processor.objects.get(name=detector_name) window = utils.OLD_BIRD_CLIP_CALL_CENTER_WINDOWS[short_detector_name] for station, mic_output in sm_pairs: station_num = int(station.name.split()[1]) print('{} {}...'.format(short_detector_name, station_num)) ground_truth_clips = list(model_utils.get_clips( station=station, mic_output=mic_output, detector=ground_truth_detector, annotation_name=CLASSIFICATION_ANNOTATION_NAME, annotation_value=annotation_value)) ground_truth_call_center_indices = \ [c.start_index + c.length // 2 for c in ground_truth_clips] ground_truth_call_count = len(ground_truth_clips) old_bird_clips = list(model_utils.get_clips( station=station, mic_output=mic_output, detector=old_bird_detector)) old_bird_clip_count = len(old_bird_clips) clips = [(c.start_index, c.length) for c in old_bird_clips] matches = utils.match_clips_with_calls( clips, ground_truth_call_center_indices, window) old_bird_call_count = len(matches) rows.append([ short_detector_name, station_num, ground_truth_call_count, old_bird_call_count, old_bird_clip_count]) if ANNOTATE: # Clear any existing annotations. for clip in old_bird_clips: model_utils.unannotate_clip( clip, classification_annotation_info, creating_user=user) # Create new annotations. for i, j in matches: old_bird_clip = old_bird_clips[i] call_center_index = ground_truth_call_center_indices[j] ground_truth_clip = ground_truth_clips[j] # Annotate Old Bird clip call center index. model_utils.annotate_clip( old_bird_clip, center_index_annotation_info, str(call_center_index), creating_user=user) # Get ground truth clip call center frequency. annotations = \ model_utils.get_clip_annotations(ground_truth_clip) call_center_freq = annotations[CENTER_FREQ_ANNOTATION_NAME] # Annotate Old Bird clip call center frequency. model_utils.annotate_clip( old_bird_clip, center_freq_annotation_info, call_center_freq, creating_user=user) model_utils.annotate_clip( old_bird_clip, classification_annotation_info, annotation_value, creating_user=user) return rows def create_raw_df(rows): columns = [ 'Detector', 'Station', 'Ground Truth Calls', 'Old Bird Calls', 'Old Bird Clips'] return pd.DataFrame(rows, columns=columns) def create_aggregate_df(df): data = [ sum_counts(df, 'Tseep'), sum_counts(df, 'Thrush'), sum_counts(df, 'All') ] columns = [ 'Detector', 'Ground Truth Calls', 'Old Bird Calls', 'Old Bird Clips'] return pd.DataFrame(data, columns=columns) def sum_counts(df, detector): if detector != 'All': df = df.loc[df['Detector'] == detector] return [ detector, df['Ground Truth Calls'].sum(), df['Old Bird Calls'].sum(), df['Old Bird Clips'].sum()] def add_precision_recall_f1(df): p = df['Old Bird Calls'] / df['Old Bird Clips'] r = df['Old Bird Calls'] / df['Ground Truth Calls'] df['Precision'] = to_percent(p) df['Recall'] = to_percent(r) df['F1'] = to_percent(2 * p * r / (p + r)) def to_percent(x): return round(1000 * x) / 10 if __name__ == '__main__': main()
HaroldMills/Vesper
scripts/old_bird_detector_eval/annotate_old_bird_calls.py
Python
mit
6,952
<html><body> <h4>Windows 10 x64 (18362.388)</h4><br> <h2>_TP_CALLBACK_PRIORITY</h2> <font face="arial"> TP_CALLBACK_PRIORITY_HIGH = 0n0<br> TP_CALLBACK_PRIORITY_NORMAL = 0n1<br> TP_CALLBACK_PRIORITY_LOW = 0n2<br> TP_CALLBACK_PRIORITY_INVALID = 0n3<br> TP_CALLBACK_PRIORITY_COUNT = 0n3<br> </font></body></html>
epikcraw/ggool
public/Windows 10 x64 (18362.388)/_TP_CALLBACK_PRIORITY.html
HTML
mit
332
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\"" /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "Pods-ASTextInputAccessoryView_Example/ASPlaceholderTextView.framework" install_framework "Pods-ASTextInputAccessoryView_Example/ASTextInputAccessoryView.framework" install_framework "Pods-ASTextInputAccessoryView_Example/PMKVObserver.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "Pods-ASTextInputAccessoryView_Example/ASPlaceholderTextView.framework" install_framework "Pods-ASTextInputAccessoryView_Example/ASTextInputAccessoryView.framework" install_framework "Pods-ASTextInputAccessoryView_Example/PMKVObserver.framework" fi
ashare80/ASTextInputAccessoryView
Example/Pods/Target Support Files/Pods-ASTextInputAccessoryView_Example/Pods-ASTextInputAccessoryView_Example-frameworks.sh
Shell
mit
3,966
module Tabletop class Randomizer attr_reader :possible_values, :value def initialize(keywords = {}) @possible_values = keywords.fetch(:possible_values) { [] }.to_a @value = keywords.fetch(:value) { random_value } check_value! end def valid_value?(val) possible_values.include?(val) end def set_to(new_val) check_value!(new_val) new_with(new_val) end def randomize set_to(random_value) end private def new_with(value) self.class.new(value: value) end def check_value!(val = @value) raise ArgumentError, "#{val} is not a valid value for #{self}" unless valid_value?(val) end def random_value possible_values.sample end end end
nicknovitski/tabletop
lib/tabletop/randomizers/randomizer.rb
Ruby
mit
762
dhtmlXForm.prototype.items.calendar = { render: function(item, data) { var t = this; item._type = "calendar"; item._enabled = true; this.doAddLabel(item, data); this.doAddInput(item, data, "INPUT", "TEXT", true, true, "dhxform_textarea"); item.childNodes[item._ll?1:0].childNodes[0]._idd = item._idd; item._f = (data.dateFormat||"%d-%m-%Y"); // formats item._f0 = (data.serverDateFormat||item._f); // formats for save-load, if set - use them for saving and loading only item._c = new dhtmlXCalendarObject(item.childNodes[item._ll?1:0].childNodes[0], data.skin||item.getForm().skin||"dhx_skyblue"); item._c._nullInInput = true; // allow null value from input item._c.enableListener(item.childNodes[item._ll?1:0].childNodes[0]); item._c.setDateFormat(item._f); if (!data.enableTime) item._c.hideTime(); if (!isNaN(data.weekStart)) item._c.setWeekStartDay(data.weekStart); if (typeof(data.calendarPosition) != "undefined") item._c.setPosition(data.calendarPosition); item._c._itemIdd = item._idd; item._c.attachEvent("onBeforeChange", function(d) { if (item._value != d) { // call some events if (item.checkEvent("onBeforeChange")) { if (item.callEvent("onBeforeChange",[item._idd, item._value, d]) !== true) { return false; } } // accepted item._value = d; t.setValue(item, d); item.callEvent("onChange", [this._itemIdd, item._value]); } return true; }); this.setValue(item, data.value); return this; }, getCalendar: function(item) { return item._c; }, setSkin: function(item, skin) { item._c.setSkin(skin); }, setValue: function(item, value) { if (!value || value == null || typeof(value) == "undefined" || value == "") { item._value = null; item.childNodes[item._ll?1:0].childNodes[0].value = ""; } else { item._value = (value instanceof Date ? value : item._c._strToDate(value, item._f0)); item.childNodes[item._ll?1:0].childNodes[0].value = item._c._dateToStr(item._value, item._f); } item._c.setDate(item._value); window.dhtmlXFormLs[item.getForm()._rId].vals[item._idd] = item.childNodes[item._ll?1:0].childNodes[0].value; }, getValue: function(item, asString) { var d = item._c.getDate(); if (asString===true && d == null) return ""; return (asString===true?item._c._dateToStr(d,item._f0):d); }, destruct: function(item) { // unload calendar instance item._c.unload(); item._c = null; try {delete item._c;} catch(e){} item._f = null; try {delete item._f;} catch(e){} item._f0 = null; try {delete item._f0;} catch(e){} // remove custom events/objects item.childNodes[item._ll?1:0].childNodes[0]._idd = null; // unload item this.d2(item); item = null; } }; (function(){ for (var a in {doAddLabel:1,doAddInput:1,doUnloadNestedLists:1,setText:1,getText:1,enable:1,disable:1,isEnabled:1,setWidth:1,setReadonly:1,isReadonly:1,setFocus:1,getInput:1}) dhtmlXForm.prototype.items.calendar[a] = dhtmlXForm.prototype.items.input[a]; })(); dhtmlXForm.prototype.items.calendar.d2 = dhtmlXForm.prototype.items.input.destruct; dhtmlXForm.prototype.getCalendar = function(name) { return this.doWithItem(name, "getCalendar"); };
lincong1987/foxhis-website
js/dhtmlx/form/ext/calendar.js
JavaScript
mit
3,369
/** * The MIT License * * Copyright (c) 2014 Martin Crawford and contributors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.atreus.core.tests.entities.errors; import org.atreus.core.annotations.*; import org.atreus.impl.types.cql.StringTypeStrategy; import java.util.Map; /** * InvalidMapStrategyTestEntity * * @author Martin Crawford */ @AtreusEntity public class InvalidMapStrategyTestEntity { // Constants ---------------------------------------------------------------------------------------------- Constants // Instance Variables ---------------------------------------------------------------------------- Instance Variables @AtreusPrimaryKey private String id; @AtreusFieldType(StringTypeStrategy.class) @AtreusCollection(type = String.class) @AtreusMap(key = String.class) private Map mapField; // Constructors ---------------------------------------------------------------------------------------- Constructors // Public Methods ------------------------------------------------------------------------------------ Public Methods // Protected Methods ------------------------------------------------------------------------------ Protected Methods // Private Methods ---------------------------------------------------------------------------------- Private Methods // Getters & Setters ------------------------------------------------------------------------------ Getters & Setters public String getId() { return id; } public void setId(String id) { this.id = id; } public Map getMapField() { return mapField; } public void setMapField(Map mapField) { this.mapField = mapField; } } // end of class
bemisguided/atreus
src/test/java/org/atreus/core/tests/entities/errors/InvalidMapStrategyTestEntity.java
Java
mit
2,737
<?php namespace ThreeDCart\Api\Soap\Resource\Customer; use ThreeDCart\Api\Soap\Resource\SoapResource; use ThreeDCart\Api\Soap\Resource\VisitorInterface; /** * Class AdditionalFields * * @package ThreeDCart\Api\Soap\Resource\Customer */ class AdditionalFields extends SoapResource { /** @var string */ private $AdditionalField1; /** @var string */ private $AdditionalField2; /** @var string */ private $AdditionalField3; /** * @return string */ public function getAdditionalField1() { return $this->AdditionalField1; } /** * @param string $AdditionalField1 */ public function setAdditionalField1($AdditionalField1) { $this->AdditionalField1 = $AdditionalField1; } /** * @return string */ public function getAdditionalField2() { return $this->AdditionalField2; } /** * @param string $AdditionalField2 */ public function setAdditionalField2($AdditionalField2) { $this->AdditionalField2 = $AdditionalField2; } /** * @return string */ public function getAdditionalField3() { return $this->AdditionalField3; } /** * @param string $AdditionalField3 */ public function setAdditionalField3($AdditionalField3) { $this->AdditionalField3 = $AdditionalField3; } public function accept(VisitorInterface $visitor) { $visitor->visitCustomerAdditionalFields($this); } }
Menes1337/3dcart-api-php-client
src/Api/Soap/Resource/Customer/AdditionalFields.php
PHP
mit
1,543
<div class="modal-header"> <button type="button" class="close pull-right" ng-click="cancel()" aria-hidden="true">&times;</button> <h3>{{label()}}</h3> </div> <div class="modal-body"> <form novalidate class="form" name="form" ng-submit="add()"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" ng-model="model.name" required> </div> <div class="form-group"> <label>Location</label> <input type="text" class="form-control" ng-model="model.location" required> </div> <div class="form-group"> <label>Type</label> <select ui-select2 ng-model="model.type" required> <option value="Internship">Internship</option> <option value="Part-Time">Part-Time</option> <option value="Full-Time">Full-Time</option> </select> </div> <div class="form-group"> <label>Experience</label> <select ui-select2 ng-model="model.experience" required> <option value="Internship">Internship</option> <option value="Entry">Entry</option> <option value="Mid-Level">Mid-Level</option> <option value="High-Level">High-Level</option> </select> </div> <div class="form-group"> <label>Status</label> <select ui-select2 ng-model="model.status" required> <option value="Pending">Pending</option> <option value="Available">Available</option> <option value="Offered">Offered</option> <option value="Filled">Filled</option> </select> </div> <div class="form-group"> <label>Visibility</label> <select ui-select2 ng-model="model.visibility"> <option value="Public">Public</option> <option value="Private">Private</option> </select> </div> <div class="form-group"> <label>Salary</label> <input type="number" class="form-control" ng-model="model.salary"> </div> <div class="form-group"> <label>Description</label> <textarea class="form-control" ng-model="model.description"></textarea> </div> </form> </div> <div class="modal-footer"> <button class="btn btn-default" ng-click="cancel()">Cancel</button> <button class="btn btn-primary" ng-click="add()" ng-disabled="form.$invalid">{{label()}}</button> </div>
kesne/case-comp
app/views/partials/addJob.html
HTML
mit
2,604
import {Component} from 'angular2/core'; import {RouteConfig, RouterOutlet} from 'angular2/router'; import {MovieList} from './movie-list.component'; import {MovieDetail} from './movie-detail.component'; import {MovieService} from './movie.service'; @Component({ template: ` <h2>Movie List</h2> <router-outlet></router-outlet> `, directives: [RouterOutlet], providers: [MovieService] }) @RouteConfig([ { path: '/', name: 'Movies', component: MovieList, useAsDefault: true }, { path: '/:id', name: 'MovieDetail', component: MovieDetail }, { path: '/new', name: 'AddMovie', component: MovieDetail } ]) export class MovieComponent { }
bodiddlie/angular2-vs2015-example
TypescriptNG2/app/movies/movie.component.ts
TypeScript
mit
693
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SimpleAuth.WebApiTest.Infrastructure")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SimpleAuth.WebApiTest.Infrastructure")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b6f7b042-aaf0-4d80-8cc9-38b421514d41")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
devdigital/SimpleAuth
Source/SimpleAuth.WebApiTest.Infrastructure/Properties/AssemblyInfo.cs
C#
mit
1,448
package com.main; import java.util.HashMap; import java.util.Map; import com.shubham.server.main.WSBaseTask; import com.shubham.service.MyService; public class TaskSelectiveStatus implements WSBaseTask{ Map<String, Boolean> list = new HashMap<>(); @Override public Object work(String[] args) { list.clear(); list.put("home", true); list.put("download", true); list.put("music", MyService.database.getBoolean("music")); list.put("gallery", MyService.database.getBoolean("gallery")); list.put("contact", MyService.database.getBoolean("contacts")); list.put("call-log", MyService.database.getBoolean("call_log")); list.put("file", MyService.database.getBoolean("file")); list.put("app", MyService.database.getBoolean("app")); list.put("sms", MyService.database.getBoolean("sms")); return list; } }
pentestershubham/Playstack
Playstack Android Application/Playstack/Task/com/main/TaskSelectiveStatus.java
Java
mit
845
class CfSim::Portal attr_reader :name, :latitude, :longitude def initialize(name, latitude, longitude) @name = name @latitude = latitude @longitude = longitude end def ==(other) eql?(other) end def eql?(other) @name == other.name && @latitude == other.latitude && @longitude == other.longitude end def hash @name.hash + @latitude + @longitude end def to_s "#{name}(#{latitude}, #{longitude})" end end
pinzolo/cf_sim
lib/cf_sim/portal.rb
Ruby
mit
456
--- title: A Grey Stone Fixed in Memory date: 2006-03-30T00:33:00+00:00 author: Pedro Ávila excerpt: With the news came more rain, soft and slow as I can ever remember in this Beast of a City. layout: post location: São Paulo, Brazil categories: - Rants - Travels tags: - Blues - Life - Sleep - Solitude --- With the news came more rain, soft and slow as I can ever remember in this City. It is nothing like our neighborhood back home. I remember a few things I enjoyed about growing up there, not the least of which was mowing and raking Helen's lawn. It was an excuse to force us kids into working, not for the money, but for the experience: pleasure and pain. _A job well done is it's own reward_, and all that stuff. Mom's usual psychology worked magic around our growing minds, but it was also a pleasure it was for Helen, to have two growing kids on which to dump her chocolate covered macademia nuts and Shasta Cola in between raking and mowing her lawn on brisk autumn days. Everyone was better off because of it. What a saint. Growing up in the posh end of the East Bay didn't give us many chances for this sort of thing as people are usually secluded and dead long before they ever die. Helen never gave that seclusion a chance. Like Bill, the firefighter and gardener across the street, seeing her out walking up and down that stretch no matter how slowly was a cherished routine. It helped assure us that things were as they should be, and going well at that. -- Helen died today. I just learned of it through a message I had been ignoring all day. They've already had her funeral back home, half a world away. She would have liked that it was done so soon after her passing, though. She may have moved slowly but she liked things to be done, and I can't remember her ever being shy about it. I would have liked to have been there, of course, as I'm sure it was full of people celebrating her life, with smiles as bright as the summer that approaches, and plenty of tears as light as her white hair. It's comforting to remember that I will always have the fig tree, though. She used to give us loads of figs that she couldn't handle off of her aging tree that apparently had learned over the years to produce the really good stuff. Later, she saw we liked them so much that she gave us a branch of her tree and we planted it in our front yard and watched it grow with inordinate speed. Already it produces such sweetness as hers and towers over our front yard. Already it has given a branch to another tree in our backyard. One day it will offer me another branch, and I will plant it with the care to which it is accustomed. Life goes on, I suppose. I would have liked to be kissed goodbye one last time though, as she invariably did, even if it was to cross the street on her way home. I would have liked to hear her say one last time, that I'm a ‘good kid', because she would say it with meaning whether I was doing what I could to make my family happy or bringing her some pao de queijo, or just telling her that the figs she gave us were out of sight. She was the kind of person that didn't see the difference in the actions because the motivation was the same... I'm a ‘good kid' and that's that. I will miss her dearly. -- I perceive that but for the rain, the river _Tiete_ is dulled and motionless, like a festering lagoon by the freeway. The sounds of the City have smoothed out a bit now and a fog has fallen over it such as to make San Francisco envious. It is not silent, nor is it still, but for a fleeting moment, or series of moments, all the noises -- somehow in sync -- go unheard. An idle night for an idle day, it seems. Who knew so much peace could be had in a moment? Maybe I will sleep tonight... maybe. Who knows? _**Estanplaza Hotel, 12th floor balcony, Sao Paulo -- March, 2006**_
narcan/narcan.github.io
_posts/2006-03-30-a-grey-stone-fixed-in-memory.md
Markdown
mit
3,851
<?php namespace BeWelcome\RoxBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * BeWelcome\RoxBundle\Entity\RoxMemberAddress * * @ORM\Table(name="addresses") * @ORM\Entity(repositoryClass="BeWelcome\RoxBundle\Repository\RoxProfileRepository") */ class RoxMemberAddress { /** * @var integer $id * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * Get id * * @return integer */ public function getId() { return $this->id; } }
Toub/bewelcome-symfony
src/BeWelcome/RoxBundle/Entity/RoxMemberAddress.php
PHP
mit
555
<?php namespace App\Repository; /** * Class BaseRepository * * @package App\Repository */ abstract class BaseRepository { /** @var string */ protected $basePath; public function __construct($dataFolder) { $this->basePath = __DIR__.'/../../../'.$dataFolder; } /** * @return array */ protected function getData() { if (!file_exists($this->getDataPath())) { return []; } return json_decode(file_get_contents($this->getDataPath()), true)[$this->getDataName()]; } /** * @return string */ private function getDataPath() { return $this->basePath.'/'.$this->getDataName().'.json'; } /** * @return string */ abstract protected function getDataName(); }
dpcat237/pasishnyi-denys-techtask-20170209
src/App/Repository/BaseRepository.php
PHP
mit
797
<?php namespace Mmo\Bundle\ExperimentBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('mmo_experiment'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
morelmathieu/web-api
src/Mmo/Bundle/ExperimentBundle/DependencyInjection/Configuration.php
PHP
mit
890
from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse import datetime, time, requests, re, os import bs4 from django.contrib.admin.views.decorators import staff_member_required from decimal import * # Create your views here. from .models import Gas, Region, Station, Site, Ship, Harvester, Setup, APICheck from .forms import GasForm, SiteForm, SiteAnalyzer def about(request): return render(request, 'home/about.html') def home(request): if request.method == "POST": form = GasForm(data=request.POST) if form.is_valid(): data = form.cleaned_data harv = data['harvester'] cycle = harv.cycle yld = harv.yld ship = data['ship'] yld_bonus = ship.yld_bonus if data['skill'] > 5: skill = 5 if data['skill'] < 1: skill = 1 else: skill = data['skill'] cycle_bonus = skill * .05 else: form = GasForm() cycle = 40 yld = 20 cycle_bonus = 0.25 yld_bonus = 1 if cycle_bonus > .25: cycle_bonus = Decimal(0.25) c = cycle * (1 - cycle_bonus) y = yld * (1 + yld_bonus) gases = Gas.objects.all() isk_min = {} for gas in gases: g = gas.name vol = gas.volume isk_min_val = ((Decimal(y) / Decimal(gas.volume)) * 2) * (60 / Decimal(c)) * Decimal(gas.last_price) isk_mthree = Decimal(gas.last_price) / Decimal(gas.volume) isk_min[g] = [isk_min_val, isk_mthree] u = APICheck.objects.get(id=1) context = {'isk_min': isk_min, 'form': form, 'updated': str(u.updated)} return render(request, "home/home.html", context) def sites(request): if request.method == "POST": form = SiteForm(data=request.POST) if form.is_valid(): data = form.cleaned_data harv = data['harvester'] cycle = Decimal(harv.cycle) yld = Decimal(harv.yld) ship = data['ship'] yld_bonus = Decimal(ship.yld_bonus) cargo = Decimal(ship.cargo) num = Decimal(data['num']) if data['skill'] > 5: skill = 5 if data['skill'] < 1: skill = 1 else: skill = data['skill'] cycle_bonus = skill * .05 extra_data = data['extra_data'] else: form = SiteForm() cycle = Decimal(40) yld = Decimal(20) cycle_bonus = Decimal(0.25) yld_bonus = Decimal(1) num = Decimal(1) cargo = 10000 extra_data = False c = cycle * (Decimal(1) - Decimal(cycle_bonus)) y = yld * (Decimal(1) + Decimal(yld_bonus)) sites = Site.objects.all() sites_calc = {} for site in sites: p_price = site.p_gas.last_price s_price = site.s_gas.last_price p_vol = site.p_gas.volume s_vol = site.s_gas.volume p_isk_min = ((Decimal(y) / Decimal(p_vol)) * 2) * (60 / Decimal(c)) * Decimal(p_price) * num s_isk_min = ((Decimal(y) / Decimal(s_vol)) * 2) * (60 / Decimal(c)) * Decimal(s_price) * num if p_isk_min < s_isk_min: best_gas = site.s_gas best_gas_isk_min = s_isk_min best_qty = site.s_qty other_gas = site.p_gas other_gas_isk_min = p_isk_min other_qty = site.p_qty else: best_gas = site.p_gas best_gas_isk_min = p_isk_min best_qty = site.p_qty other_gas = site.s_gas other_gas_isk_min = s_isk_min other_qty = site.s_qty p_units_min = ((y / best_gas.volume) * 2) * (60 / c) * num s_units_min = ((y / other_gas.volume) * 2) * (60 / c) * num time_to_clear = (best_qty / p_units_min) + (other_qty / s_units_min) isk_pres = (p_price * site.p_qty) + (s_price * site.s_qty) site_isk_min = Decimal(isk_pres) / Decimal(time_to_clear) #extra data calculations primary_time_to_clear = (best_qty / p_units_min) secondary_time_to_clear = (other_qty / s_units_min) #blue_loot_isk #time to kill site ships_needed = ((site.p_qty * p_vol) + (site.s_qty * s_vol)) / (cargo) sites_calc[site.name] = [isk_pres, best_gas, best_gas_isk_min, other_gas, other_gas_isk_min, site_isk_min, time_to_clear, primary_time_to_clear, secondary_time_to_clear, ships_needed] u = APICheck.objects.get(id=1) context = {'form': form, 'sites_calc': sites_calc, 'updated': str(u.updated), 'extra_data': extra_data} return render(request, "home/sites.html", context) def site_an(request): if request.method == 'POST': form = SiteAnalyzer(data=request.POST) if form.is_valid(): data = form.cleaned_data scan = data['scan'] num = Decimal(data['num']) ship = data['ship'] harvester = data['harvester'] skill = Decimal(data['skill']) show_data = True else: form = SiteAnalyzer() show_data = False skill = 0 yld = 0 num = 1 ship = Ship.objects.get(id=1) harvester = Harvester.objects.get(id=1) cycle_bonus = skill * Decimal(0.05) yld = harvester.yld c = harvester.cycle * (1 - cycle_bonus) y = yld * (1 + ship.yld_bonus) * num #parse Dscan sites = [] proc_sites = [] if show_data == True: #print(scan) scan_re = re.compile(r'Gas Site *(\S* \S* \S*) *') scan_re_b = re.compile(r'(Instrumental Core Reservoir|Ordinary Perimeter Reservoir|Minor Perimeter Reservoir|Bountiful Frontier Reservoir|Barren Perimeter Reservoir|Token Perimeter Reservoir|Sizable Perimeter Reservoir|Vast Frontier Reservoir|Vital Core Reservoir)') scan_results = scan_re.findall(scan) if scan_results == []: scan_results = scan_re_b.findall(scan) print(scan_results) for res in scan_results: sites.append(res) for s in sites: site = Site.objects.get(name=s) site_name = site.name site_isk = (site.p_gas.last_price * site.p_qty) + (site.s_gas.last_price * site.s_qty) #ninja scanning #determine best gas p_isk_min = ((Decimal(y) / Decimal(site.p_gas.volume)) * 2) * (60 / Decimal(c)) * Decimal(site.p_gas.last_price) s_isk_min = ((Decimal(y) / Decimal(site.s_gas.volume)) * 2) * (60 / Decimal(c)) * Decimal(site.s_gas.last_price) if p_isk_min >= s_isk_min: first_cloud = site.p_gas first_qty = site.p_qty sec_cloud = site.s_gas sec_qty = site.s_qty if p_isk_min <= s_isk_min: first_cloud = site.s_gas first_qty = site.s_qty sec_cloud = site.p_gas sec_qty = site.p_qty #calculate how much you can get in 15 minutes units_15 = ((Decimal(y) / Decimal(first_cloud.volume)) * 2) * (60 / Decimal(c)) * 15 if units_15 <= first_qty: ninja_isk = units_15 * first_cloud.last_price if ninja_isk > site_isk: ninja_isk = site_isk m_per_s = (units_15 / num) * first_cloud.volume #if it is more than the qty in the best cloud, calculate the remaining time if units_15 > first_qty: min_left = 15 - (first_qty / (units_15 / 15)) sec_units_min = ((Decimal(y) / Decimal(sec_cloud.volume)) * 2) * (60 / Decimal(c)) rem_units = sec_units_min * min_left ninja_isk = (rem_units * sec_cloud.last_price) + (first_qty * first_cloud.last_price) if ninja_isk > site_isk: ninja_isk = site_isk m_per_s = ((units_15 / num) * first_cloud.volume) + ((rem_units / num) * sec_cloud.volume) if m_per_s * num > (site.p_qty * site.p_gas.volume) + (site.s_qty * site.s_gas.volume): m_per_s = ((site.p_qty * site.p_gas.volume) + (site.s_qty * site.s_gas.volume)) / num sipm = ninja_isk / 15 / num nips = ninja_isk / num if site_name == 'Ordinary Perimeter Reservoir': sipm = 0 m_per_s = 0 nips = 0 ninja_isk = 0 ninja_si = (site_name, site_isk, sipm, first_cloud.name, m_per_s, nips, ninja_isk) #print(ninja_si) proc_sites.append(ninja_si) t_site_isk = 0 t_sipm = 0 t_sipm_c = 0 t_m_per_s = 0 t_nips = 0 t_ninja_isk = 0 for s in proc_sites: t_site_isk = t_site_isk + s[1] t_sipm = t_sipm + s[2] if s[0] != "Ordinary Perimeter Reservoir": t_sipm_c = t_sipm_c + 1 t_m_per_s = t_m_per_s + s[4] t_nips = t_nips + s[5] t_ninja_isk = t_ninja_isk + s[6] ships = t_m_per_s / ship.cargo if t_sipm_c == 0: t_sipm_c = 1 if t_site_isk == 0: t_site_isk = 1 percent = (t_ninja_isk / t_site_isk) * 100 totals = (t_site_isk, t_sipm / t_sipm_c, t_m_per_s, t_nips, t_ninja_isk, ships, percent) t_min = t_sipm_c * 15 u = APICheck.objects.get(id=1) #site clearing #take sites #isk present, blue loot isk present, time to fully clear site, rat dps, rat ehp context = {'show_data': show_data, 'form': form, 'sites': sites, 'proc_sites': proc_sites, 'totals': totals, 't_min': t_min, 'updated': str(u.updated)} return render(request, "home/site_an.html", context) def pull_prices(request): tag_re = re.compile(r'<.*>(.*)</.*>') gs = Gas.objects.all() id_str = '' for g in gs: gid = g.item_id id_str = id_str+'&typeid='+gid #r = Region.objects.get(id=1) #r = r.region_id r = '10000002' url = 'http://api.eve-central.com/api/marketstat?'+id_str+'&regionlimit='+r xml_raw = requests.get(url) if xml_raw.status_code == requests.codes.ok: path = 'data/prices.xml' xml = open(path, 'w') xml.write(xml_raw.text) xml.close() status = 'OK' else: status = 'Error' xml_file = open(path, 'r') xml = xml_file.read() soup = bs4.BeautifulSoup(xml, 'xml') types = soup.find_all('type') for t in types: t_dict = dict(t.attrs) type_id = t_dict['id'] buy = t.buy avg = buy.find_all('max') avg_in = tag_re.search(str(avg)) avg_in = avg_in.group(1) avg_price = Decimal(avg_in) avg_price = round(avg_price, 2) g = Gas.objects.get(item_id=type_id) g.last_price = avg_price g.save() gases = Gas.objects.all() a, c = APICheck.objects.get_or_create(id=1) a.save() context = {'status': status, 'gases': gases} return render(request, "home/pull_prices.html", context) @staff_member_required def wipe_db(request): s = Site.objects.all() s.delete() g = Gas.objects.all() g.delete() r = Region.objects.all() r.delete() s = Station.objects.all() s.delete() s = Ship.objects.all() s.delete() h = Harvester.objects.all() h.delete() s = Setup.objects.all() s.delete() return HttpResponseRedirect(reverse('home:home')) @staff_member_required def setup_site(request): try: s = Setup.objects.get(id=1) if s==1: return HttpResponseRedirect(reverse('home:home')) except: g = Gas(name='Fullerite-C28',item_id='30375', volume='2') g.save() g = Gas(name='Fullerite-C32',item_id='30376', volume='5') g.save() g = Gas(name='Fullerite-C320',item_id='30377', volume='5') g.save() g = Gas(name='Fullerite-C50',item_id='30370', volume='1') g.save() g = Gas(name='Fullerite-C540',item_id='30378', volume='10') g.save() g = Gas(name='Fullerite-C60',item_id='30371', volume='1') g.save() g = Gas(name='Fullerite-C70',item_id='30372', volume='1') g.save() g = Gas(name='Fullerite-C72',item_id='30373', volume='2') g.save() g = Gas(name='Fullerite-C84',item_id='30374', volume='2') g.save() r = Region(name='The Forge', region_id='10000002') r.save() s = Station(name='Jita IV - Moon 4 - Caldari Navy Assembly Plant ( Caldari Administrative Station )',station_id='60003760') s.save() s = Ship(name='Venture',cargo=5000,yld_bonus=1.00) s.save() s = Ship(name='Prospect',cargo=10000,yld_bonus=1.00) s.save() h = Harvester(name='Gas Cloud Harvester I',harv_id='25266',cycle=30,yld=10) h.save() h = Harvester(name='\'Crop\' Gas Cloud Harvester',harv_id='25540',cycle=30,yld=10) h.save() h = Harvester(name='\'Plow\' Gas Cloud Harvester',harv_id='25542',cycle=30,yld=10) h.save() h = Harvester(name='Gas Cloud Harvester II',harv_id='25812',cycle=40,yld=20) h.save() h = Harvester(name='Syndicate Gas Cloud Harvester',harv_id='28788',cycle=30,yld=10) h.save() c50 = Gas.objects.get(name='Fullerite-C50') c60 = Gas.objects.get(name='Fullerite-C60') c70 = Gas.objects.get(name='Fullerite-C70') c72 = Gas.objects.get(name='Fullerite-C72') c84 = Gas.objects.get(name='Fullerite-C84') c28 = Gas.objects.get(name='Fullerite-C28') c32 = Gas.objects.get(name='Fullerite-C32') c320 = Gas.objects.get(name='Fullerite-C320') c540 = Gas.objects.get(name='Fullerite-C540') s = Site(name='Barren Perimeter Reservoir',p_gas=c50,s_gas=c60,p_qty=3000,s_qty=1500) s.save() s = Site(name='Token Perimeter Reservoir',p_gas=c60,s_gas=c70,p_qty=3000,s_qty=1500) s.save() s = Site(name='Ordinary Perimeter Reservoir',p_gas=c72,s_gas=c84,p_qty=3000,s_qty=1500) s.save() s = Site(name='Sizable Perimeter Reservoir',p_gas=c84,s_gas=c50,p_qty=3000,s_qty=1500) s.save() s = Site(name='Minor Perimeter Reservoir',p_gas=c70,s_gas=c72,p_qty=3000,s_qty=1500) s.save() s = Site(name='Bountiful Frontier Reservoir',p_gas=c28,s_gas=c32,p_qty=5000,s_qty=1000) s.save() s = Site(name='Vast Frontier Reservoir',p_gas=c32,s_gas=c28,p_qty=5000,s_qty=1000) s.save() s = Site(name='Instrumental Core Reservoir',p_gas=c320,s_gas=c540,p_qty=6000,s_qty=500) s.save() s = Site(name='Vital Core Reservoir',p_gas=c540,s_gas=c320,p_qty=6000,s_qty=500) s.save() try: os.mkdir('data/') except: pass s = Setup(setup=1) s.save() return HttpResponseRedirect(reverse('home:home'))
inspectorbean/gasbuddy
home/views.py
Python
mit
14,960
--- layout: post title: How to Connect to a SQL Database from Jupyter Notebook --- ## Connecting Jupyter Notebooks to SQL Server In order to access your local SQL database, you'll need to install pyodbc if it's not already installed as part of your Anaconda installation. The [documentation](https://github.com/mkleehammer/pyodbc/wiki) goes over connecting to Acess, Excel, MySQL, Oracle, PostgreSQL, Teradata and different flavors of SSMS. In this tutorial, I'm going to go over how to connect to SQL Server using Windows.
strongdan/blog
_drafts/2017-11-21-Python-SQL-DBMS.md
Markdown
mit
529
#!/usr/bin/env python3 """ 2018 AOC Day 09 """ import argparse import typing import unittest class Node(object): ''' Class representing node in cyclic linked list ''' def __init__(self, prev: 'Node', next: 'Node', value: int): ''' Create a node with explicit parameters ''' self._prev = prev self._next = next self._value = value @staticmethod def default() -> 'Node': ''' Create a node linked to itself with value 0 ''' node = Node(None, None, 0) # type: ignore node._prev = node node._next = node return node def forward(self, n: int = 1) -> 'Node': ''' Go forward n nodes ''' current = self for _ in range(n): current = current._next return current def back(self, n: int = 1) -> 'Node': ''' Go backward n nodes ''' current = self for _ in range(n): current = current._prev return current def insert(self, value: int) -> 'Node': ''' Insert new node after current node with given value, and return newly inserted Node ''' new_node = Node(self, self._next, value) self._next._prev = new_node self._next = new_node return self._next def remove(self) -> 'Node': ''' Remove current Node and return the following Node ''' self._prev._next = self._next self._next._prev = self._prev return self._next def value(self) -> int: ''' Get value ''' return self._value def chain_values(self): values = [self.value()] current = self.forward() while current != self: values.append(current.value()) current = current.forward() return values def part1(nplayers: int, highest_marble: int) -> int: """ Solve part 1 """ current = Node.default() player = 0 scores = {p: 0 for p in range(nplayers)} for idx in range(1, highest_marble + 1): if idx % 23 == 0: scores[player] += idx current = current.back(7) scores[player] += current.value() current = current.remove() else: current = current.forward().insert(idx) player = (player + 1) % nplayers return max(scores.values()) def part2(nplayers: int, highest_node: int) -> int: """ Solve part 2 """ return part1(nplayers, highest_node) def main(): """ Run 2018 Day 09 """ parser = argparse.ArgumentParser(description='Advent of Code 2018 Day 09') parser.add_argument('nplayers', type=int, help='# of players') parser.add_argument( 'highest_marble', type=int, help='highest-valued marble', ) opts = parser.parse_args() print('Part 1:', part1(opts.nplayers, opts.highest_marble)) print('Part 2:', part2(opts.nplayers, opts.highest_marble * 100)) if __name__ == '__main__': main() class ExampleTest(unittest.TestCase): def test_part1(self): examples = { (9, 25): 32, (10, 1618): 8317, (13, 7999): 146373, (17, 1104): 2764, (21, 6111): 54718, (30, 5807): 37305, } for example, expected in examples.items(): self.assertEqual(part1(*example), expected)
devonhollowood/adventofcode
2018/day09.py
Python
mit
3,328
using System; using LeagueSharp.Common; namespace MetaSmite { class Program { static void Main(string[] args) { CustomEvents.Game.OnGameLoad += OnGameLoad; } private static void OnGameLoad(EventArgs args) { MetaSmite.Load(); } } }
metaphorce/leaguesharp
MetaSmite/Program.cs
C#
mit
320
--- title: "BBC : Le système hollandais de service de santé à but non lucratif" date: 2016-01-18 20:41 layout: post category: [article] tags: ["Buurtzorg", "Jos de Blok"] illustration: /images/buurtzorg-bbc.jpg --- Un portrait de Buurtzorg et Jos de Blok par Eleanor Bradford de BBC Scotland. [Lire l'article de BBC Scotland](http://www.bbc.com/news/uk-scotland-33259198)
organisationsliberees/organisationsliberees.github.io
_posts/2016-01-18-bbc-le-systeme-hollandais-de-service-de-sante-à-but-non-lucratif.md
Markdown
mit
378
import Data.Char (digitToInt) main = print problem40Value problem40Value :: Int problem40Value = d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000 where d1 = digitToInt $ list !! 0 d10 = digitToInt $ list !! 9 d100 = digitToInt $ list !! 99 d1000 = digitToInt $ list !! 999 d10000 = digitToInt $ list !! 9999 d100000 = digitToInt $ list !! 99999 d1000000 = digitToInt $ list !! 999999 list = concat $ map show [1..]
jchitel/ProjectEuler.hs
Problems/Problem0040.hs
Haskell
mit
496
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'app.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^add/$', 'cart.views.add'), url(r'^clear/$', 'cart.views.clear'), url(r'^show/$', 'cart.views.show'), url(r'^remove/(?P<pk>\d+)/$', 'cart.views.remove'), url(r'^checkout/$', 'cart.views.checkout'), )
sheeshmohsin/shopping_site
app/cart/urls.py
Python
mit
546
let charLS; function jpegLSDecode (data, isSigned) { // prepare input parameters const dataPtr = charLS._malloc(data.length); charLS.writeArrayToMemory(data, dataPtr); // prepare output parameters const imagePtrPtr = charLS._malloc(4); const imageSizePtr = charLS._malloc(4); const widthPtr = charLS._malloc(4); const heightPtr = charLS._malloc(4); const bitsPerSamplePtr = charLS._malloc(4); const stridePtr = charLS._malloc(4); const allowedLossyErrorPtr = charLS._malloc(4); const componentsPtr = charLS._malloc(4); const interleaveModePtr = charLS._malloc(4); // Decode the image const result = charLS.ccall( 'jpegls_decode', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number'], [dataPtr, data.length, imagePtrPtr, imageSizePtr, widthPtr, heightPtr, bitsPerSamplePtr, stridePtr, componentsPtr, allowedLossyErrorPtr, interleaveModePtr] ); // Extract result values into object const image = { result, width: charLS.getValue(widthPtr, 'i32'), height: charLS.getValue(heightPtr, 'i32'), bitsPerSample: charLS.getValue(bitsPerSamplePtr, 'i32'), stride: charLS.getValue(stridePtr, 'i32'), components: charLS.getValue(componentsPtr, 'i32'), allowedLossyError: charLS.getValue(allowedLossyErrorPtr, 'i32'), interleaveMode: charLS.getValue(interleaveModePtr, 'i32'), pixelData: undefined }; // Copy image from emscripten heap into appropriate array buffer type const imagePtr = charLS.getValue(imagePtrPtr, '*'); if (image.bitsPerSample <= 8) { image.pixelData = new Uint8Array(image.width * image.height * image.components); image.pixelData.set(new Uint8Array(charLS.HEAP8.buffer, imagePtr, image.pixelData.length)); } else if (isSigned) { image.pixelData = new Int16Array(image.width * image.height * image.components); image.pixelData.set(new Int16Array(charLS.HEAP16.buffer, imagePtr, image.pixelData.length)); } else { image.pixelData = new Uint16Array(image.width * image.height * image.components); image.pixelData.set(new Uint16Array(charLS.HEAP16.buffer, imagePtr, image.pixelData.length)); } // free memory and return image object charLS._free(dataPtr); charLS._free(imagePtr); charLS._free(imagePtrPtr); charLS._free(imageSizePtr); charLS._free(widthPtr); charLS._free(heightPtr); charLS._free(bitsPerSamplePtr); charLS._free(stridePtr); charLS._free(componentsPtr); charLS._free(interleaveModePtr); return image; } function initializeJPEGLS () { // check to make sure codec is loaded if (typeof CharLS === 'undefined') { throw new Error('No JPEG-LS decoder loaded'); } // Try to initialize CharLS // CharLS https://github.com/cornerstonejs/charls if (!charLS) { charLS = CharLS(); if (!charLS || !charLS._jpegls_decode) { throw new Error('JPEG-LS failed to initialize'); } } } function decodeJPEGLS (imageFrame, pixelData) { initializeJPEGLS(); const image = jpegLSDecode(pixelData, imageFrame.pixelRepresentation === 1); // throw error if not success or too much data if (image.result !== 0 && image.result !== 6) { throw new Error(`JPEG-LS decoder failed to decode frame (error code ${image.result})`); } imageFrame.columns = image.width; imageFrame.rows = image.height; imageFrame.pixelData = image.pixelData; return imageFrame; } export default decodeJPEGLS; export { initializeJPEGLS };
google/cornerstoneWADOImageLoader
src/webWorker/decodeTask/decoders/decodeJPEGLS.js
JavaScript
mit
3,494
/** * Class names to use for display elements. */ export interface ClassNames { /** * Class name for the contents container. */ contentArea: string; /** * Class name for each menu's div. */ menu: string; /** * Class name for each menu's children container. */ menuChildren: string; /** * Class name for the inner area div. */ menusInnerArea: string; /** * Class name for a faked inner area div. */ menusInnerAreaFake: string; /** * Class name for the surrounding area div. */ menusOuterArea: string; /** * Class name for each menu title div. */ menuTitle: string; /** * Class name for an option's container. */ option: string; /** * Class name for the left half of a two-part option. */ optionLeft: string; /** * Class name for the right half of a two-part option. */ optionRight: string; /** * Class name for each options container div. */ options: string; /** * Class name for each options list within its container. */ optionsList: string; } /** * Default class names to use for display elements. */ export const defaultClassNames: ClassNames = { contentArea: "content-area", menu: "menu", menuChildren: "menu-children", menuTitle: "menu-title", menusInnerArea: "menus-inner-area", menusInnerAreaFake: "menus-inner-area-fake", menusOuterArea: "menus-outer-area", option: "option", optionLeft: "option-left", optionRight: "option-right", options: "options", optionsList: "options-list", };
FullScreenShenanigans/EightBittr
packages/userwrappr/src/Bootstrapping/ClassNames.ts
TypeScript
mit
1,672
{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} module Arith where import Control.Exception import Data.Int import Data.Text as T type T = Int64 zero :: T zero = 0 neg :: T -> T neg x | x == minBound = throw Overflow | otherwise = -x add :: T -> T -> T add x y = if | p x && p y && n sum -> throw Overflow | n x && n y && p sum -> throw Underflow | otherwise -> sum where sum = x + y p x = x > 0 n x = x < 0 sub x y = add x (neg y) fromText :: Int -> Text -> T fromText scale txt = case splitOn "." txt of [i] -> read . unpack $ T.concat [i, padding scale] [i, d] -> if T.any (/= '0') post then throw LossOfPrecision else read . unpack $ T.concat [i, pre, padding $ scale - T.length pre] where (pre, post) = T.splitAt scale d _ -> error "no parse" where padding n = T.replicate n "0" -- TODO: can we simplify this? Sounds very complex toText :: Int -> T -> Text toText 0 x = pack $ show x toText scale x = if | x == 0 -> "0" | x > 0 -> toTextPos x | otherwise -> T.concat ["-", toTextPos $ neg x] where toTextPos x = case T.splitAt (T.length textPadded - scale) textPadded of ("", d) -> T.concat ["0.", d] (i, d) -> T.concat [i, ".", d] where text = pack $ show x textPadded = T.concat [padding $ scale - T.length text, text] padding n = T.replicate n "0"
gip/cinq-cloches-ledger
src/Arith.hs
Haskell
mit
1,475
{% assign base = 'DTILabs' %} {% assign depth = page.url | split: '/' | size | minus: 1 %} {% if depth <= 1 %}{% assign base = '.' %} {% elsif depth == 2 %}{% assign base = '..' %} {% elsif depth == 3 %}{% assign base = '../..' %} {% elsif depth == 4 %}{% assign base = '../../..' %}{% endif %}
RolandRP/DTILabs
_includes/base.html
HTML
mit
298