code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/** * @(#)MenuScroller.java 1.5.0 04/02/12 * Code taken from https://tips4java.wordpress.com/2009/02/01/menu-scroller/ */ package darrylbu.util; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.MenuSelectionManager; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; /** * A class that provides scrolling capabilities to a long menu dropdown or * popup menu. A number of items can optionally be frozen at the top and/or * bottom of the menu. * <P> * <B>Implementation note:</B> The default number of items to display * at a time is 15, and the default scrolling interval is 125 milliseconds. * <P> * * @version 1.5.0 04/05/12 * @author Darryl */ public class MenuScroller { private JPopupMenu menu; private Component[] menuItems; private MenuScrollItem upItem; private MenuScrollItem downItem; private final MenuScrollListener menuListener = new MenuScrollListener(); private int scrollCount; private int interval; private int topFixedCount; private int bottomFixedCount; private int firstIndex = 0; private int keepVisibleIndex = -1; /** * Registers a menu to be scrolled with the default number of items to * display at a time and the default scrolling interval. * * @param menu the menu * @return the MenuScroller */ public static MenuScroller setScrollerFor(JMenu menu) { return new MenuScroller(menu); } /** * Registers a popup menu to be scrolled with the default number of items to * display at a time and the default scrolling interval. * * @param menu the popup menu * @return the MenuScroller */ public static MenuScroller setScrollerFor(JPopupMenu menu) { return new MenuScroller(menu); } /** * Registers a menu to be scrolled with the default number of items to * display at a time and the specified scrolling interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @return the MenuScroller * @throws IllegalArgumentException if scrollCount is 0 or negative */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount) { return new MenuScroller(menu, scrollCount); } /** * Registers a popup menu to be scrolled with the default number of items to * display at a time and the specified scrolling interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @return the MenuScroller * @throws IllegalArgumentException if scrollCount is 0 or negative */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount) { return new MenuScroller(menu, scrollCount); } /** * Registers a menu to be scrolled, with the specified number of items to * display at a time and the specified scrolling interval. * * @param menu the menu * @param scrollCount the number of items to be displayed at a time * @param interval the scroll interval, in milliseconds * @return the MenuScroller * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval) { return new MenuScroller(menu, scrollCount, interval); } /** * Registers a popup menu to be scrolled, with the specified number of items to * display at a time and the specified scrolling interval. * * @param menu the popup menu * @param scrollCount the number of items to be displayed at a time * @param interval the scroll interval, in milliseconds * @return the MenuScroller * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval) { return new MenuScroller(menu, scrollCount, interval); } /** * Registers a menu to be scrolled, with the specified number of items * to display in the scrolling region, the specified scrolling interval, * and the specified numbers of items fixed at the top and bottom of the * menu. * * @param menu the menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0. * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative * @return the MenuScroller */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { return new MenuScroller(menu, scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Registers a popup menu to be scrolled, with the specified number of items * to display in the scrolling region, the specified scrolling interval, * and the specified numbers of items fixed at the top and bottom of the * popup menu. * * @param menu the popup menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative * @return the MenuScroller */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { return new MenuScroller(menu, scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * default number of items to display at a time, and default scrolling * interval. * * @param menu the menu */ public MenuScroller(JMenu menu) { this(menu, 15); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * default number of items to display at a time, and default scrolling * interval. * * @param menu the popup menu */ public MenuScroller(JPopupMenu menu) { this(menu, 15); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display at a time, and default scrolling * interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public MenuScroller(JMenu menu, int scrollCount) { this(menu, scrollCount, 150); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display at a time, and default scrolling * interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public MenuScroller(JPopupMenu menu, int scrollCount) { this(menu, scrollCount, 150); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display at a time, and specified scrolling * interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @param interval the scroll interval, in milliseconds * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public MenuScroller(JMenu menu, int scrollCount, int interval) { this(menu, scrollCount, interval, 0, 0); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display at a time, and specified scrolling * interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @param interval the scroll interval, in milliseconds * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public MenuScroller(JPopupMenu menu, int scrollCount, int interval) { this(menu, scrollCount, interval, 0, 0); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display in the scrolling region, the * specified scrolling interval, and the specified numbers of items fixed at * the top and bottom of the menu. * * @param menu the menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative */ public MenuScroller(JMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { this(menu.getPopupMenu(), scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display in the scrolling region, the * specified scrolling interval, and the specified numbers of items fixed at * the top and bottom of the popup menu. * * @param menu the popup menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative */ public MenuScroller(JPopupMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { if (scrollCount <= 0 || interval <= 0) { throw new IllegalArgumentException("scrollCount and interval must be greater than 0"); } if (topFixedCount < 0 || bottomFixedCount < 0) { throw new IllegalArgumentException("topFixedCount and bottomFixedCount cannot be negative"); } upItem = new MenuScrollItem(MenuIcon.UP, -1); downItem = new MenuScrollItem(MenuIcon.DOWN, +1); setScrollCount(scrollCount); setInterval(interval); setTopFixedCount(topFixedCount); setBottomFixedCount(bottomFixedCount); this.menu = menu; menu.addPopupMenuListener(menuListener); } /** * Returns the scroll interval in milliseconds * * @return the scroll interval in milliseconds */ public int getInterval() { return interval; } /** * Sets the scroll interval in milliseconds * * @param interval the scroll interval in milliseconds * @throws IllegalArgumentException if interval is 0 or negative */ public void setInterval(int interval) { if (interval <= 0) { throw new IllegalArgumentException("interval must be greater than 0"); } upItem.setInterval(interval); downItem.setInterval(interval); this.interval = interval; } /** * Returns the number of items in the scrolling portion of the menu. * * @return the number of items to display at a time */ public int getscrollCount() { return scrollCount; } /** * Sets the number of items in the scrolling portion of the menu. * * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public void setScrollCount(int scrollCount) { if (scrollCount <= 0) { throw new IllegalArgumentException("scrollCount must be greater than 0"); } this.scrollCount = scrollCount; MenuSelectionManager.defaultManager().clearSelectedPath(); } /** * Returns the number of items fixed at the top of the menu or popup menu. * * @return the number of items */ public int getTopFixedCount() { return topFixedCount; } /** * Sets the number of items to fix at the top of the menu or popup menu. * * @param topFixedCount the number of items */ public void setTopFixedCount(int topFixedCount) { if (firstIndex <= topFixedCount) { firstIndex = topFixedCount; } else { firstIndex += (topFixedCount - this.topFixedCount); } this.topFixedCount = topFixedCount; } /** * Returns the number of items fixed at the bottom of the menu or popup menu. * * @return the number of items */ public int getBottomFixedCount() { return bottomFixedCount; } /** * Sets the number of items to fix at the bottom of the menu or popup menu. * * @param bottomFixedCount the number of items */ public void setBottomFixedCount(int bottomFixedCount) { this.bottomFixedCount = bottomFixedCount; } /** * Scrolls the specified item into view each time the menu is opened. Call this method with * <code>null</code> to restore the default behavior, which is to show the menu as it last * appeared. * * @param item the item to keep visible * @see #keepVisible(int) */ public void keepVisible(JMenuItem item) { if (item == null) { keepVisibleIndex = -1; } else { int index = menu.getComponentIndex(item); keepVisibleIndex = index; } } /** * Scrolls the item at the specified index into view each time the menu is opened. Call this * method with <code>-1</code> to restore the default behavior, which is to show the menu as * it last appeared. * * @param index the index of the item to keep visible * @see #keepVisible(javax.swing.JMenuItem) */ public void keepVisible(int index) { keepVisibleIndex = index; } /** * Removes this MenuScroller from the associated menu and restores the * default behavior of the menu. */ public void dispose() { if (menu != null) { menu.removePopupMenuListener(menuListener); menu = null; } } /** * Ensures that the <code>dispose</code> method of this MenuScroller is * called when there are no more refrences to it. * * @exception Throwable if an error occurs. * @see MenuScroller#dispose() */ @Deprecated protected void finalize() throws Throwable { dispose(); } private void refreshMenu() { if (menuItems != null && menuItems.length > 0) { firstIndex = Math.max(topFixedCount, firstIndex); firstIndex = Math.min(menuItems.length - bottomFixedCount - scrollCount, firstIndex); upItem.setEnabled(firstIndex > topFixedCount); downItem.setEnabled(firstIndex + scrollCount < menuItems.length - bottomFixedCount); menu.removeAll(); for (int i = 0; i < topFixedCount; i++) { menu.add(menuItems[i]); } if (topFixedCount > 0) { menu.addSeparator(); } menu.add(upItem); for (int i = firstIndex; i < scrollCount + firstIndex; i++) { menu.add(menuItems[i]); } menu.add(downItem); if (bottomFixedCount > 0) { menu.addSeparator(); } for (int i = menuItems.length - bottomFixedCount; i < menuItems.length; i++) { menu.add(menuItems[i]); } JComponent parent = (JComponent) upItem.getParent(); parent.revalidate(); parent.repaint(); } } private class MenuScrollListener implements PopupMenuListener { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { setMenuItems(); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { restoreMenuItems(); } @Override public void popupMenuCanceled(PopupMenuEvent e) { restoreMenuItems(); } private void setMenuItems() { menuItems = menu.getComponents(); if (keepVisibleIndex >= topFixedCount && keepVisibleIndex <= menuItems.length - bottomFixedCount && (keepVisibleIndex > firstIndex + scrollCount || keepVisibleIndex < firstIndex)) { firstIndex = Math.min(firstIndex, keepVisibleIndex); firstIndex = Math.max(firstIndex, keepVisibleIndex - scrollCount + 1); } if (menuItems.length > topFixedCount + scrollCount + bottomFixedCount) { refreshMenu(); } } private void restoreMenuItems() { menu.removeAll(); for (Component component : menuItems) { menu.add(component); } } } private class MenuScrollTimer extends Timer { public MenuScrollTimer(final int increment, int interval) { super(interval, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { firstIndex += increment; refreshMenu(); } }); } } private class MenuScrollItem extends JMenuItem implements ChangeListener { private MenuScrollTimer timer; public MenuScrollItem(MenuIcon icon, int increment) { setIcon(icon); setDisabledIcon(icon); timer = new MenuScrollTimer(increment, interval); addChangeListener(this); } public void setInterval(int interval) { timer.setDelay(interval); } @Override public void stateChanged(ChangeEvent e) { if (isArmed() && !timer.isRunning()) { timer.start(); } if (!isArmed() && timer.isRunning()) { timer.stop(); } } } private enum MenuIcon implements Icon { UP(9, 1, 9), DOWN(1, 9, 1); final int[] xPoints = {1, 5, 9}; final int[] yPoints; MenuIcon(int... yPoints) { this.yPoints = yPoints; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { Dimension size = c.getSize(); Graphics g2 = g.create(size.width / 2 - 5, size.height / 2 - 5, 10, 10); g2.setColor(Color.GRAY); g2.drawPolygon(xPoints, yPoints, 3); if (c.isEnabled()) { g2.setColor(Color.BLACK); g2.fillPolygon(xPoints, yPoints, 3); } g2.dispose(); } @Override public int getIconWidth() { return 0; } @Override public int getIconHeight() { return 10; } } }
Idrinth/WARAddonClient
src/main/java/darrylbu/util/MenuScroller.java
Java
mit
18,868
/**************************************************************************** ** Meta object code from reading C++ file 'walletstack.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../src/qt/walletstack.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'walletstack.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_WalletStack[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 17, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 18, 13, 12, 12, 0x0a, 44, 12, 12, 12, 0x0a, 63, 12, 12, 12, 0x0a, 83, 12, 12, 12, 0x0a, 101, 12, 12, 12, 0x0a, 123, 12, 12, 12, 0x0a, 151, 146, 12, 12, 0x0a, 178, 12, 12, 12, 0x2a, 198, 146, 12, 12, 0x0a, 226, 12, 12, 12, 0x2a, 247, 146, 12, 12, 0x0a, 277, 12, 12, 12, 0x2a, 307, 300, 12, 12, 0x0a, 327, 12, 12, 12, 0x0a, 342, 12, 12, 12, 0x0a, 361, 12, 12, 12, 0x0a, 376, 12, 12, 12, 0x0a, 0 // eod }; static const char qt_meta_stringdata_WalletStack[] = { "WalletStack\0\0name\0setCurrentWallet(QString)\0" "gotoOverviewPage()\0gotoMessagingPage()\0" "gotoHistoryPage()\0gotoAddressBookPage()\0" "gotoReceiveCoinsPage()\0addr\0" "gotoSendCoinsPage(QString)\0" "gotoSendCoinsPage()\0gotoSignMessageTab(QString)\0" "gotoSignMessageTab()\0gotoVerifyMessageTab(QString)\0" "gotoVerifyMessageTab()\0status\0" "encryptWallet(bool)\0backupWallet()\0" "changePassphrase()\0unlockWallet()\0" "setEncryptionStatus()\0" }; void WalletStack::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); WalletStack *_t = static_cast<WalletStack *>(_o); switch (_id) { case 0: _t->setCurrentWallet((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 1: _t->gotoOverviewPage(); break; case 2: _t->gotoMessagingPage(); break; case 3: _t->gotoHistoryPage(); break; case 4: _t->gotoAddressBookPage(); break; case 5: _t->gotoReceiveCoinsPage(); break; case 6: _t->gotoSendCoinsPage((*reinterpret_cast< QString(*)>(_a[1]))); break; case 7: _t->gotoSendCoinsPage(); break; case 8: _t->gotoSignMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break; case 9: _t->gotoSignMessageTab(); break; case 10: _t->gotoVerifyMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break; case 11: _t->gotoVerifyMessageTab(); break; case 12: _t->encryptWallet((*reinterpret_cast< bool(*)>(_a[1]))); break; case 13: _t->backupWallet(); break; case 14: _t->changePassphrase(); break; case 15: _t->unlockWallet(); break; case 16: _t->setEncryptionStatus(); break; default: ; } } } const QMetaObjectExtraData WalletStack::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject WalletStack::staticMetaObject = { { &QStackedWidget::staticMetaObject, qt_meta_stringdata_WalletStack, qt_meta_data_WalletStack, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &WalletStack::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *WalletStack::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *WalletStack::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_WalletStack)) return static_cast<void*>(const_cast< WalletStack*>(this)); return QStackedWidget::qt_metacast(_clname); } int WalletStack::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QStackedWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 17) qt_static_metacall(this, _c, _id, _a); _id -= 17; } return _id; } QT_END_MOC_NAMESPACE
danielmash/matchcoin-wallet
build/moc_walletstack.cpp
C++
mit
4,766
// ref: http://www.cplusplus.com/reference/future/future/ // future example #include <iostream> // std::cout #include <future> // std::async, std::future #include <chrono> // std::chrono::milliseconds // a non-optimized way of checking for prime numbers: bool is_prime (int x) { for (int i=2; i<x; ++i) if (x%i==0) return false; return true; } int main () { // call function asynchronously: // std::future<bool> fut = std::async (is_prime,444444443); // <--- BAD! std::future<bool> fut = std::async (std::launch::async, []() { return is_prime(444444443); }); // do something while waiting for function to set future: std::cout << "checking, please wait"; std::chrono::milliseconds span (100); while (fut.wait_for(span)==std::future_status::timeout) std::cout << '.' << std::flush; bool x = fut.get(); // retrieve return value std::cout << "\n444444443 " << (x?"is":"is not") << " prime.\n"; return 0; }
flavio-fernandes/oclock
misc/junk/c++/future3.cpp
C++
mit
967
<div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h3 class="page-header">Causas</h3> <div class="form-group" style="width: 100%" > <div style="width: 40%; float: left;"> <?php echo "<code><a class='btn btn-primary btn btn-large' href='$base/disenio/insert/'> <span class='glyphicon-plus'></span> Nuevo</a></code>"; ?> </div> <div style="width: 25%; float: right;"> <div class="panel panel-green"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">Buscar</a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse"> <div class="panel-body"> <form method="POST" action="<?php echo base_url() . "causa/Buscar"; ?>"> <table> <tr> <td> <label>Buscar: </label> </td> <td> <input type="text" name="dato" class="form-control" placeholder="Abollado" required="TRUE"> </td> <td> <span class="input-group-btn"> <button class="btn btn-default" type="submit"><i class="fa fa-search"></i></button> </span> </td> </tr> </table> </form> </div> </div> </div> </div> </div> </div> </div> <br> <br> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> <div class="form-group input-group" > <form method="POST" action="<?php echo base_url() . "causa/Lim"; ?>"> <table> <tr> <td> <label>Mostrar: </label> </td> <td> <select name="dato" class="form-control" required="TRUE"> <option value="">Selecciona</option> <option value="10">10</option> <option value="50">50</option> <option value="100">100</option> <option value="1000">Todos</option> </select> </td> <td> <span class="input-group-btn"> <button class="btn btn-default" type="submit"><i class="fa fa-search"></i></button> </span> </td> </tr> </table> </form> </div> </div> <div class="panel-body"> <div class="row"> <div class="table-responsive"> <?php echo '<table class ="table table-bordered>"'; echo '<TR><TD>'; echo '<b><center>Causa'; echo '</TD><TD colspan=2>'; echo '<b><center>Acción '; echo '</TD></TR>'; foreach ($datos as $obj){ echo '</TD><TD>'; echo $obj->getTipoCausa(); echo '</TD><TD>'; echo "<a class = 'fa fa-trash-o fa-lg' href='$base/causa/delete/" . $obj->getIdCausa() . "'></a>"; echo '</TD><TD>'; echo "<a class = 'fa fa-pencil fa-fw' href='$base/causa/update/" .$obj->getIdCausa() . "'></a>"; echo '</TD></TR>'; } echo '</table>'; if (empty($datos)) { echo '<div style="text-align: center" class="alert-danger"><strong>No existen registros!!!</strong> Intenta con otro dato <span class="glyphicon glyphicon-alert"><span/></div >'; } echo '</div>'; ?> </div> </div> </div> </div> </div> </div> </div>
SoldierVega/SIRSJ1
application/views/causa/listCausa.php
PHP
mit
5,886
<?php declare(strict_types=1); namespace Phpcq\Runner\Console\Definition\OptionValue; final class OptionParamsDefinition extends OptionValueDefinition { /** * @var array<string,mixed> */ private $params; /** @param array<string,mixed> $params */ public function __construct(bool $required, array $params) { parent::__construct($required); $this->params = $params; } /** @return array<string,mixed> */ public function getParams(): array { return $this->params; } }
phpcq/phpcq
src/Console/Definition/OptionValue/OptionParamsDefinition.php
PHP
mit
544
package kv import ( "sort" "github.com/gocontrib/nosql/q" ) type lookup struct { collection *collection tx Tx } func (c lookup) find(f []interface{}) keys { return c.and(f) } func (c lookup) condition(f interface{}) keys { switch t := f.(type) { case q.Not: return emptyKeys case q.And: return c.and(t) case q.Or: return c.or(t) case q.M: var set hashset for name, val := range t { var keys = c.field(name, val) if set == nil { set = newHashset(keys) continue } var set2 = make(hashset) for _, k := range keys { if set.has(k) { set2.add(k) } } set = set2 if len(set) == 0 { return emptyKeys } } if set == nil { return emptyKeys } return set.toArray() } return emptyKeys } func (c lookup) field(name string, value interface{}) keys { if name == "id" || name == "_id" { var s, ok = value.(string) if !ok { return emptyKeys } return keys{s} } var idxName = "idx_" + c.collection.name + "_" + name idx, err := c.tx.Bucket(idxName, false) if err != nil || idx == nil { return emptyKeys } switch v := value.(type) { case string: raw, err := idx.Get([]byte(v)) if err != nil || raw == nil { return emptyKeys } return unmarshalKeys(raw) } return emptyKeys } func (c lookup) and(f []interface{}) keys { if len(f) == 1 { return c.condition(f[0]) } var set = newHashset(c.condition(f[0])) if len(set) == 0 { return emptyKeys } for i := 1; i < len(f); i++ { var keys = c.condition(f[i]) var set2 = make(hashset) for _, k := range keys { if set.has(k) { set2.add(k) } } set = set2 if len(set) == 0 { return emptyKeys } } return set.toArray() } func (c lookup) or(f []interface{}) keys { if len(f) == 1 { return c.condition(f[0]) } var set = newHashset(c.condition(f[0])) for i := 1; i < len(f); i++ { var keys = c.condition(f[i]) for _, k := range keys { set.add(k) } } return set.toArray() } // determines whether given filter(s) can use index tables func (c lookup) isSuitable(f interface{}) bool { switch t := f.(type) { case q.Not: return false case q.And: for _, i := range t { if !c.isSuitable(i) { return false } } return true case q.Or: for _, i := range t { if !c.isSuitable(i) { return false } } return true case []interface{}: for _, i := range t { if !c.isSuitable(i) { return false } } return true case q.M: for name, v := range t { switch v.(type) { case q.In: return false case q.NotIn: return false case q.Op: return false } // now only strings are indexed s, ok := v.(string) if !ok { return len(s) > 0 } if name == "id" || name == "_id" { return true } var idxName = "idx_" + c.collection.name + "_" + name idx, err := c.tx.Bucket(idxName, false) if err != nil || idx == nil { return false } } return true } return false } // hashset of strings type hashset map[string]struct{} func (s hashset) has(k string) bool { _, h := s[k] return h } func (s hashset) add(k string) bool { if _, h := s[k]; h { return false } s[k] = struct{}{} return true } func (s hashset) toArray() []string { var a []string for k := range s { a = append(a, k) } sort.Strings(a) return a } func newHashset(keys []string) hashset { var t = make(hashset) for _, k := range keys { t.add(k) } return t }
gocontrib/nosql
kv/lookup.go
GO
mit
3,434
<?php declare(strict_types=1); namespace Gos\Bundle\WebSocketBundle\Tests\Server\Type; use Gos\Bundle\WebSocketBundle\Event\ServerLaunchedEvent; use Gos\Bundle\WebSocketBundle\GosWebSocketEvents; use Gos\Bundle\WebSocketBundle\Server\App\ServerBuilderInterface; use Gos\Bundle\WebSocketBundle\Server\Type\WebSocketServer; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Ratchet\MessageComponentInterface; use React\EventLoop\LoopInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class WebSocketServerTest extends TestCase { /** * @var MockObject|ServerBuilderInterface */ private $serverBuilder; /** * @var MockObject|LoopInterface */ private $loop; /** * @var MockObject|EventDispatcherInterface */ private $eventDispatcher; protected function setUp(): void { parent::setUp(); $this->serverBuilder = $this->createMock(ServerBuilderInterface::class); $this->loop = $this->createMock(LoopInterface::class); $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); } /** * @runInSeparateProcess */ public function testTheServerIsLaunched(): void { $this->serverBuilder->expects(self::once()) ->method('buildMessageStack') ->willReturn($this->createMock(MessageComponentInterface::class)); $this->eventDispatcher->expects(self::once()) ->method('dispatch') ->with(self::isInstanceOf(ServerLaunchedEvent::class), GosWebSocketEvents::SERVER_LAUNCHED); $this->loop->expects(self::once()) ->method('run'); (new WebSocketServer($this->serverBuilder, $this->loop, $this->eventDispatcher)) ->launch('127.0.0.1', 1337, false); } /** * @runInSeparateProcess */ public function testTheServerIsLaunchedWithTlsSupport(): void { $this->serverBuilder->expects(self::once()) ->method('buildMessageStack') ->willReturn($this->createMock(MessageComponentInterface::class)); $this->eventDispatcher->expects(self::once()) ->method('dispatch') ->with(self::isInstanceOf(ServerLaunchedEvent::class), GosWebSocketEvents::SERVER_LAUNCHED); $this->loop->expects(self::once()) ->method('run'); (new WebSocketServer($this->serverBuilder, $this->loop, $this->eventDispatcher, true, ['verify_peer' => false])) ->launch('127.0.0.1', 1337, false); } }
GeniusesOfSymfony/WebSocketBundle
tests/Server/Type/WebSocketServerTest.php
PHP
mit
2,570
from . import server import sys server.main(*sys.argv)
TeamNext/qos.py
qos/__main__.py
Python
mit
55
<?php //error_reporting(E_ALL); //ini_set('display_errors', 'On'); ini_set("memory_limit","300M"); set_time_limit(0); $phpModelName = $_GET["layer"]; function getModel($modelname) { include "dbconnect.php"; $modelquery = pg_query($db, "SELECT ST_AsText(geom), \"ID\" FROM public.\"$modelname\"; "); $polygonString = ""; $polyhedralString = ""; $tinzString = ""; $lineString = ""; $pointString = ""; $polyhedralsurfaceID = array(); $tinzID = array(); $linestringID = array(); $pointID = array(); $polygonID = array(); function PolygonZM($pzmModel) { // Unfortunately nearly unreadable, however a lot more efficent than the original code. It essentially a series of string replacements. return str_replace(" nan", "", str_replace(")", "", str_replace("(", "", str_replace(")", "", str_replace("),", " &&& ", $aModel = str_replace("POLYGON ZM (", "", str_replace(" -999999", "", $pzmModel))))))); } function PolyhedralSurfaceZ($pszModel) { return str_replace(")", "", str_replace("(", "", str_replace("POLYHEDRALSURFACE Z (", "", str_replace(" nan", "", $pszModel)))); } function TINZ($tinzModel) { return str_replace(")", "", str_replace("(", " ||| ", str_replace("TIN Z (", "", str_replace(" nan", "", $tinzModel)))); } function LineStringZ($lineString) { return str_replace(")", "", str_replace("(", "", str_replace("LINESTRING ZM", "", str_replace(" -999999", "", str_replace(" nan", "", $lineString))))); } function PointZ($pointString) { return str_replace(")", "", str_replace("(", "", str_replace("POINT ZM", "", str_replace(" -999999", "", str_replace(" nan", "", $pointString))))); } function checkGeometryType($aGeometry) { if (substr( $aGeometry, 0, 10 ) === "POLYGON ZM") { return array("POLYGON ZM", PolygonZM($aGeometry) . " ::: "); } if (substr( $aGeometry, 0, 19 ) === "POLYHEDRALSURFACE Z") { return array("POLYHEDRALSURFACE Z", PolyhedralSurfaceZ($aGeometry) . " ::: "); } if (substr( $aGeometry, 0, 5 ) === "TIN Z") { return array("TIN Z", TINZ($aGeometry)); } if (substr( $aGeometry, 0, 12 ) === "LINESTRING Z") { return array("LINESTRING Z", LineStringZ($aGeometry)); } if (substr( $aGeometry, 0, 7 ) === "POINT Z") { return array("POINT Z", PointZ($aGeometry)); } } while ($model = pg_fetch_row($modelquery)) { if (substr( $model[0], 0, 18 ) === "GEOMETRYCOLLECTION") { $cleanedCollection = str_replace("GEOMETRYCOLLECTION Z (", "", $model[0]); if (substr( $cleanedCollection, 0, 5 ) === "TIN Z") { $TINZgeom = checkGeometryType($cleanedCollection); $tinzString .= $TINZgeom[1] . " %%% "; array_push( $tinzID, $model[1] ); } else { $splitCollection = explode("),", $cleanedCollection); foreach($splitCollection as $collection){ $geomtype = checkGeometryType($collection); if ($geomtype[0] == "POLYHEDRALSURFACE Z") { $polyhedralString .= $geomtype[1]; } if ($geomtype[0] == "POLYGON ZM") { $polygonString .= $geomtype[1]; } } if ($polyhedralString != "") { $polyhedralString .= " %%% "; array_push($polyhedralsurfaceID, $model[1]); } if ($polygonString != "") { $polygonString .= " %%% "; array_push($polygonID, $model[1]); } } } else { $geomtype = checkGeometryType($model[0]); if ($geomtype[0] == "POLYHEDRALSURFACE Z") { $polyhedralString .= $geomtype[1] . " %%% "; array_push($polyhedralsurfaceID, $model[1]); continue; } if ($geomtype[0] == "POLYGON ZM") { $polygonString .= $geomtype[1] . " %%% "; array_push($polygonID, $model[1]); continue; } if ($geomtype[0] == "LINESTRING Z") { $lineString .= $geomtype[1] . " %%% "; array_push($linestringID, $model[1]); continue; } if ($geomtype[0] == "TIN Z") { $tinzString .= $geomtype[1] . " %%% "; array_push($tinzID, $model[1]); continue; } if ($geomtype[0] == "POINT Z") { $pointString .= $geomtype[1] . " %%% "; array_push($pointID, $model[1]); } } } return json_encode( array( array("POLYGON ZM", $polygonString, $polygonID), array("POLYHEDRALSURFACE Z", $polyhedralString, $polyhedralsurfaceID), array("TIN Z", $tinzString, $tinzID), array("LINESTRING Z", $lineString, $linestringID), array("POINT Z", $pointString, $pointID) ) ); } echo getModel($phpModelName); ?>
JamesMilnerUK/Lacuna
ajax/getdataajax.php
PHP
mit
4,445
/* * Rotate Image * Total Accepted: 10296 Total Submissions: 33430 * * You are given an n x n 2D matrix representing an image. * * Rotate the image by 90 degrees (clockwise). * * Follow up: * Could you do this in-place? */ class Solution { public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); for (int i = 0; i < n / 2; i++) { for (int j = i; j < n - 1 - i; j++) { int i1 = i; int i2 = j; int i3 = n - 1 - i; int i4 = n - 1 - j; int j1 = j; int j2 = n - 1 - i; int j3 = n - 1 - j; int j4 = i; singleRotate(i1, j1, i2, j2, i3, j3, i4, j4, matrix); } } } void singleRotate(int i1, int j1, int i2, int j2, int i3, int j3, int i4, int j4, vector<vector<int> > &matrix) { swap(matrix[i1][j1], matrix[i2][j2]); swap(matrix[i1][j1], matrix[i4][j4]); swap(matrix[i3][j3], matrix[i4][j4]); } };
liyiji/LeetCode
008_Rotate_Image.cpp
C++
mit
1,079
__author__ = 'heddevanderheide' # Django specific from django.conf.urls import patterns, include, url urlpatterns = patterns('', url('', include('fabric_interface.urls')) )
Hedde/fabric_interface
src/main/urls.py
Python
mit
179
using System.Runtime.InteropServices; namespace Meziantou.Framework.Win32.Natives; [StructLayout(LayoutKind.Explicit)] internal struct JOBOBJECT_INFO { [FieldOffset(0)] public JOBOBJECT_EXTENDED_LIMIT_INFORMATION32 ExtendedLimits32; [FieldOffset(0)] public JOBOBJECT_EXTENDED_LIMIT_INFORMATION64 ExtendedLimits64; public static JOBOBJECT_INFO From(JobObjectLimits limits) { var info = new JOBOBJECT_INFO(); if (Environment.Is64BitProcess) { info.ExtendedLimits64.BasicLimits.ActiveProcessLimit = limits.ActiveProcessLimit; info.ExtendedLimits64.BasicLimits.Affinity = limits.Affinity; info.ExtendedLimits64.BasicLimits.MaximumWorkingSetSize = (uint)limits.MaximumWorkingSetSize; info.ExtendedLimits64.BasicLimits.MinimumWorkingSetSize = (uint)limits.MinimumWorkingSetSize; info.ExtendedLimits64.BasicLimits.PerJobUserTimeLimit = limits.PerJobUserTimeLimit; info.ExtendedLimits64.BasicLimits.PerProcessUserTimeLimit = limits.PerProcessUserTimeLimit; info.ExtendedLimits64.BasicLimits.PriorityClass = limits.PriorityClass; info.ExtendedLimits64.BasicLimits.SchedulingClass = limits.SchedulingClass; info.ExtendedLimits64.ProcessMemoryLimit = limits.ProcessMemoryLimit; info.ExtendedLimits64.JobMemoryLimit = limits.JobMemoryLimit; info.ExtendedLimits64.BasicLimits.LimitFlags = limits.InternalFlags; } else { info.ExtendedLimits32.BasicLimits.ActiveProcessLimit = limits.ActiveProcessLimit; info.ExtendedLimits32.BasicLimits.Affinity = limits.Affinity; info.ExtendedLimits32.BasicLimits.MaximumWorkingSetSize = (uint)limits.MaximumWorkingSetSize; info.ExtendedLimits32.BasicLimits.MinimumWorkingSetSize = (uint)limits.MinimumWorkingSetSize; info.ExtendedLimits32.BasicLimits.PerJobUserTimeLimit = limits.PerJobUserTimeLimit; info.ExtendedLimits32.BasicLimits.PerProcessUserTimeLimit = limits.PerProcessUserTimeLimit; info.ExtendedLimits32.BasicLimits.PriorityClass = limits.PriorityClass; info.ExtendedLimits32.BasicLimits.SchedulingClass = limits.SchedulingClass; info.ExtendedLimits32.ProcessMemoryLimit = (uint)limits.ProcessMemoryLimit; info.ExtendedLimits32.JobMemoryLimit = (uint)limits.JobMemoryLimit; info.ExtendedLimits32.BasicLimits.LimitFlags = limits.InternalFlags; } return info; } }
meziantou/Meziantou.Framework
src/Meziantou.Framework.Win32.Jobs/Natives/JOBOBJECT_INFO.cs
C#
mit
2,557
'use strict'; describe('Protractor Demo App', function() { // it('should add a todo', function() { // browser.get('https://angularjs.org'); // browser.sleep(5000); // element(by.model('todoList.todoText')).sendKeys('write first protractor test'); // element(by.css('[value="add"]')).click(); // browser.sleep(5000); // var todoList = element.all(by.repeater('todo in todoList.todos')); // expect(todoList.count()).toEqual(3); // expect(todoList.get(2).getText()).toEqual('write first protractor test'); // // You wrote your first test, cross it off the list // todoList.get(2).element(by.css('input')).click(); // var completedAmount = element.all(by.css('.done-true')); // expect(completedAmount.count()).toEqual(2); // browser.sleep(10000); // }); it('should take a quiz' ,function () { //browser.get('http://biotility.herokuapp.com/'); browser.get('http://localhost:3000/'); browser.sleep(2000); element(by.css('[value="Applications_quiz"]')).click(); browser.sleep(1000); element(by.css('[value="start"]')).click(); browser.sleep(1000); element(by.css('[value="1"]')).click(); browser.sleep(2000); element(by.css('[value="next"]')).click(); element(by.css('[value="3"]')).click(); browser.sleep(2000); element(by.css('[value="next"]')).click(); element(by.css('[value="1"]')).click(); browser.sleep(2000); element(by.css('[value="next"]')).click(); element(by.css('[value="T"]')).click(); browser.sleep(2000); element(by.css('[value="next"]')).click(); element(by.css('[value="finished"]')).click(); browser.sleep(2000); // var score = element(by.class('results-s')); // //expect(score.value).toEqual(4); // //var score = angular // expect(score.getText()).toEqual('You got 4 / 4 questions correct.'); // browser.sleep(2000); }); // beforeEach(module( ApplicationConfiguration.registerModule('quiz') )); // var $controller; // beforeEach(inject(function(_$controller_){ // // The injector unwraps the underscores (_) from around the parameter names when matching // $controller = _$controller_; // })); // describe('$QuizController', function() { // it('sets the strength to "strong" if the password length is >8 chars', function() { // var $scope = {}; // var controller = $controller('PasswordController', { $scope: $scope }); // $scope.password = 'longerthaneightchars'; // $scope.grade(); // expect($scope.strength).toEqual('strong'); // }); // }); });
SoftwareEngineering5c/Biotility
modules/quiz/tests/e2e/quiz.e2e.tests.js
JavaScript
mit
2,664
namespace ContactSample.Models { public enum BusinessAreaEnum { Others = 0, CallCenter = 1, PostSales = 2, PreSales = 3, Delivery = 4 } }
GlaucoGodoi/AspNet-MVC5-Angular
ContactSample/Models/BusinessAreaEnum.cs
C#
mit
192
import { Injectable } from '@angular/core'; import { ModelConstructor, BaseModel } from '../../shared/models/base/base-model'; import { BaseRepository } from 'app/core/repositories/base-repository'; import { ViewModelConstructor, BaseViewModel } from 'app/site/base/base-view-model'; /** * Unifies the ModelConstructor and ViewModelConstructor. */ interface UnifiedConstructors { COLLECTIONSTRING: string; new (...args: any[]): any; } /** * Every types supported: (View)ModelConstructors, repos and collectionstrings. */ type TypeIdentifier = UnifiedConstructors | BaseRepository<any, any> | string; /** * Registeres the mapping between collection strings, models constructors, view * model constructors and repositories. * All models need to be registered! */ @Injectable({ providedIn: 'root' }) export class CollectionStringMapperService { /** * Maps collection strings to mapping entries */ private collectionStringMapping: { [collectionString: string]: [ ModelConstructor<BaseModel>, ViewModelConstructor<BaseViewModel>, BaseRepository<BaseViewModel, BaseModel> ]; } = {}; public constructor() {} /** * Registers the combination of a collection string, model, view model and repository * @param collectionString * @param model */ public registerCollectionElement<V extends BaseViewModel, M extends BaseModel>( collectionString: string, model: ModelConstructor<M>, viewModel: ViewModelConstructor<V>, repository: BaseRepository<V, M> ): void { this.collectionStringMapping[collectionString] = [model, viewModel, repository]; } /** * @param obj The object to get the collection string from. * @returns the collectionstring */ public getCollectionString(obj: TypeIdentifier): string { if (typeof obj === 'string') { return obj; } else { return obj.COLLECTIONSTRING; } } /** * @param obj The object to get the model constructor from. * @returns the model constructor */ public getModelConstructor<M extends BaseModel>(obj: TypeIdentifier): ModelConstructor<M> { return this.collectionStringMapping[this.getCollectionString(obj)][0] as ModelConstructor<M>; } /** * @param obj The object to get the view model constructor from. * @returns the view model constructor */ public getViewModelConstructor<M extends BaseViewModel>(obj: TypeIdentifier): ViewModelConstructor<M> { return this.collectionStringMapping[this.getCollectionString(obj)][1] as ViewModelConstructor<M>; } /** * @param obj The object to get the repository from. * @returns the repository */ public getRepository<V extends BaseViewModel, M extends BaseModel>(obj: TypeIdentifier): BaseRepository<V, M> { return this.collectionStringMapping[this.getCollectionString(obj)][2] as BaseRepository<V, M>; } }
emanuelschuetze/OpenSlides
client/src/app/core/core-services/collectionStringMapper.service.ts
TypeScript
mit
3,031
<?php namespace ModuleGenerator\PhpGenerator\WidgetName; final class WidgetNameDataTransferObject { /** @var string */ public $name; /** @var WidgetName|null */ private $widgetNameClass; public function __construct(WidgetName $widgetName = null) { $this->widgetNameClass = $widgetName; if (!$this->widgetNameClass instanceof WidgetName) { return; } $this->name = $this->widgetNameClass->getName(); } public function hasExistingWidgetName(): bool { return $this->widgetNameClass instanceof WidgetName; } public function getWidgetNameClass(): WidgetName { return $this->widgetNameClass; } }
carakas/fork-cms-module-generator
src/PhpGenerator/WidgetName/WidgetNameDataTransferObject.php
PHP
mit
709
<?php namespace jeus\QuickstrikeBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Deck * * @ORM\Table(name="quickstrike_deck") * @ORM\Entity(repositoryClass="jeus\QuickstrikeBundle\Repository\DeckRepository") */ class Deck { const NOMBRE_CARTE_PAR_DECK = 60; /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="nom", type="string", length=50) */ private $nom; /** * @var boolean * * @ORM\Column(name="valide", type="boolean") */ private $valide; /** * @ORM\ManyToOne(targetEntity="jeus\JoueurBundle\Entity\Joueur", inversedBy="Decks") */ protected $joueur; /** * @ORM\OneToOne(targetEntity="jeus\QuickstrikeBundle\Entity\Carte") * @ORM\JoinColumn(nullable=true) */ protected $chamberRecto; /** * @ORM\OneToOne(targetEntity="jeus\QuickstrikeBundle\Entity\Carte") * @ORM\JoinColumn(nullable=true) */ protected $chamberVerso; /** * @ORM\OneToOne(targetEntity="jeus\QuickstrikeBundle\Entity\Carte") * @ORM\JoinColumn(nullable=true) */ protected $CarteDepart; /** * @ORM\OneToMany(targetEntity="jeus\QuickstrikeBundle\Entity\CarteDeck", mappedBy="Deck", cascade={"remove"}) * @ORM\JoinColumn(nullable=true) */ protected $Cartes; /** * Constructor */ public function __construct() { $this->Cartes = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nom * * @param string $nom * @return Deck */ public function setNom($nom) { $this->nom = $nom; return $this; } /** * Get nom * * @return string */ public function getNom() { return $this->nom; } /** * Set valide * * @param boolean $valide * @return Deck */ public function setValide($valide) { $this->valide = $valide; return $this; } /** * Get valide * * @return boolean */ public function getValide() { return $this->valide; } /** * Set joueur * * @param \jeus\JoueurBundle\Entity\Joueur $joueur * @return Deck */ public function setJoueur(\jeus\JoueurBundle\Entity\Joueur $joueur) { $this->joueur = $joueur; return $this; } /** * Get joueur * * @return \jeus\JoueurBundle\Entity\Joueur */ public function getJoueur() { return $this->joueur; } /** * Set chamberRecto * * @param \jeus\QuickstrikeBundle\Entity\Carte $chamberRecto * @return Deck */ public function setChamberRecto(\jeus\QuickstrikeBundle\Entity\Carte $chamberRecto) { $this->chamberRecto = $chamberRecto; return $this; } /** * Get chamberRecto * * @return \jeus\QuickstrikeBundle\Entity\Carte */ public function getChamberRecto() { return $this->chamberRecto; } /** * Set chamberVerso * * @param \jeus\QuickstrikeBundle\Entity\Carte $chamberVerso * @return Deck */ public function setChamberVerso(\jeus\QuickstrikeBundle\Entity\Carte $chamberVerso) { $this->chamberVerso = $chamberVerso; return $this; } /** * Get chamberVerso * * @return \jeus\QuickstrikeBundle\Entity\Carte */ public function getChamberVerso() { return $this->chamberVerso; } /** * Set CarteDepart * * @param \jeus\QuickstrikeBundle\Entity\Carte $CarteDepart * @return Deck */ public function setCarteDepart(\jeus\QuickstrikeBundle\Entity\Carte $CarteDepart) { $this->CarteDepart = $CarteDepart; return $this; } /** * Get CarteDepart * * @return \jeus\QuickstrikeBundle\Entity\Carte */ public function getCarteDepart() { return $this->CarteDepart; } /** * Add carte * * @param \jeus\QuickstrikeBundle\Entity\CarteDeck $carte * @return Deck */ public function addCarte(\jeus\QuickstrikeBundle\Entity\CarteDeck $carte) { $this->Cartes[] = $carte; return $this; } /** * Remove carte * * @param \jeus\QuickstrikeBundle\Entity\CarteDeck $carte * @return Carte */ public function removeCarte(\jeus\QuickstrikeBundle\Entity\CarteDeck $carte) { $this->Cartes->removeElement($carte); return $this; } /** * Get cartes * * @return \jeus\QuickstrikeBundle\Entity\CarteDeck */ public function getCartes() { return $this->Cartes; } public function carteAjoutable(\jeus\QuickstrikeBundle\Entity\CarteDeck $CarteDeck) { $erreur = ''; //return $erreur; if ($CarteDeck->getCarte()->getTypeCarte()->getTag() == 'CHAMBER') { foreach ($this->getCartes() as $CarteDeckEnCours) { if ( ($CarteDeck->getId() != $CarteDeckEnCours->getId()) && ($CarteDeckEnCours->getCarte()->getTypeCarte()->getTag() == 'CHAMBER') ) { $erreur = 'Une chamber maximum par deck'; } } } else { $CarteDeckChamber = null; foreach ($this->getCartes() as $CarteDeckEnCours) { if ($CarteDeckEnCours->getCarte()->getTypeCarte()->getTag() == 'CHAMBER') { $CarteDeckChamber = $CarteDeckEnCours; break; } } if ($CarteDeckChamber == null) $erreur = "Vous devez choisir une chamber avant de rajouter d'autre carte"; if ( ($erreur == '') && ($CarteDeck->getCarte()->getPersonnageChamber() != '') && ($CarteDeck->getCarte()->getPersonnageChamber() != $CarteDeckChamber->getCarte()->getPersonnageChamber()) ) { $erreur = "Cette carte est à jouer avec " . $CarteDeck->getCarte()->getPersonnageChamber(); } if ($erreur == '') { $tableauTraits = array(); foreach ($CarteDeckChamber->getCarte()->getTraitCartes() as $TraitCarte) { $tableauTraits[] = $TraitCarte->getId(); } foreach ($CarteDeck->getCarte()->getTraitCartes() as $TraitCarte) { if ((!in_array($TraitCarte->getId(), $tableauTraits)) && ($TraitCarte->getTag()!='NEUTRE')) { $erreur = "Cette carte n'a pas le bon trait"; break; } } } if ($erreur == '') { $nombre = 0; foreach ($this->getCartes() as $CarteDeckEnCours) { if ( ($CarteDeckEnCours->getId() != $CarteDeck->getId()) && ($CarteDeckEnCours->getCarte()->getId() == $CarteDeck->getCarte()->getId()) ) { $nombre++; } } if ($nombre >= 4) $erreur = "Vous avez déjà le maximum d'exemplaire pour cette carte"; } } return $erreur; } public function isValide() { $avertissement = ''; //return $avertissement; $Chamber = null; $nombreCarte = null; foreach ($this->getCartes() as $CarteDeckEnCours) { if ($CarteDeckEnCours->getCarte()->getTypeCarte()->getTag() == 'CHAMBER') { $Chamber = $CarteDeckEnCours; } else { $nombreCarte++; } } if ($Chamber == null) $avertissement = "Il faut une Chamber dans le deck"; if ($nombreCarte != self::NOMBRE_CARTE_PAR_DECK) { $avertissement = $nombreCarte." Un deck doit contenir ".self::NOMBRE_CARTE_PAR_DECK." cartes"; } $this->setValide ($avertissement==''); return $avertissement; } }
jsmagghe/tcg
src/jeus/QuickstrikeBundle/Entity/Deck.php
PHP
mit
8,513
# frozen_string_literal: true module Svelte # Version VERSION = '0.3.0' end
notonthehighstreet/svelte
lib/svelte/version.rb
Ruby
mit
81
package com.github.ompc.greys.core; import com.github.ompc.greys.core.util.AliEagleEyeUtils; import com.github.ompc.greys.core.util.GaMethod; import com.github.ompc.greys.core.util.LazyGet; /** * 通知点 */ public final class Advice { public final ClassLoader loader; private final LazyGet<Class<?>> clazzRef; private final LazyGet<GaMethod> methodRef; private final LazyGet<String> aliEagleEyeTraceIdRef; public final Object target; public final Object[] params; public final Object returnObj; public final Throwable throwExp; private final static int ACCESS_BEFORE = 1; private final static int ACCESS_AFTER_RETUNING = 1 << 1; private final static int ACCESS_AFTER_THROWING = 1 << 2; public final boolean isBefore; public final boolean isThrow; public final boolean isReturn; public final boolean isThrowing; public final boolean isReturning; // 回放过程processId // use for TimeTunnelCommand.doPlay() // public final Integer playIndex; /** * for finish * * @param loader 类加载器 * @param clazzRef 类 * @param methodRef 方法 * @param target 目标类 * @param params 调用参数 * @param returnObj 返回值 * @param throwExp 抛出异常 * @param access 进入场景 */ private Advice( ClassLoader loader, LazyGet<Class<?>> clazzRef, LazyGet<GaMethod> methodRef, Object target, Object[] params, Object returnObj, Throwable throwExp, int access) { this.loader = loader; this.clazzRef = clazzRef; this.methodRef = methodRef; this.aliEagleEyeTraceIdRef = lazyGetAliEagleEyeTraceId(loader); this.target = target; this.params = params; this.returnObj = returnObj; this.throwExp = throwExp; isBefore = (access & ACCESS_BEFORE) == ACCESS_BEFORE; isThrow = (access & ACCESS_AFTER_THROWING) == ACCESS_AFTER_THROWING; isReturn = (access & ACCESS_AFTER_RETUNING) == ACCESS_AFTER_RETUNING; this.isReturning = isReturn; this.isThrowing = isThrow; // playIndex = PlayIndexHolder.getInstance().get(); } // 获取阿里巴巴中间件鹰眼ID private LazyGet<String> lazyGetAliEagleEyeTraceId(final ClassLoader loader) { return new LazyGet<String>() { @Override protected String initialValue() throws Throwable { return AliEagleEyeUtils.getTraceId(loader); } }; } /** * 构建Before通知点 */ public static Advice newForBefore( ClassLoader loader, LazyGet<Class<?>> clazzRef, LazyGet<GaMethod> methodRef, Object target, Object[] params) { return new Advice( loader, clazzRef, methodRef, target, params, null, //returnObj null, //throwExp ACCESS_BEFORE ); } /** * 构建正常返回通知点 */ public static Advice newForAfterRetuning( ClassLoader loader, LazyGet<Class<?>> clazzRef, LazyGet<GaMethod> methodRef, Object target, Object[] params, Object returnObj) { return new Advice( loader, clazzRef, methodRef, target, params, returnObj, null, //throwExp ACCESS_AFTER_RETUNING ); } /** * 构建抛异常返回通知点 */ public static Advice newForAfterThrowing( ClassLoader loader, LazyGet<Class<?>> clazzRef, LazyGet<GaMethod> methodRef, Object target, Object[] params, Throwable throwExp) { return new Advice( loader, clazzRef, methodRef, target, params, null, //returnObj throwExp, ACCESS_AFTER_THROWING ); } /** * 获取Java类 * * @return Java Class */ public Class<?> getClazz() { return clazzRef.get(); } /** * 获取Java方法 * * @return Java Method */ public GaMethod getMethod() { return methodRef.get(); } /** * 本次调用是否支持阿里巴巴中间件鹰眼系统 * * @return true:支持;false:不支持; */ public boolean isAliEagleEyeSupport() { return AliEagleEyeUtils.isEagleEyeSupport(aliEagleEyeTraceIdRef.get()); } /** * 获取本次调用阿里巴巴中间件鹰眼跟踪号 * * @return 本次调用阿里巴巴中间件鹰眼跟踪号 */ public String getAliEagleEyeTraceId() { return aliEagleEyeTraceIdRef.get(); } /** * 本次调用是否支持中间件跟踪<br/> * 在很多大公司中,会有比较多的中间件调用链路渲染技术用来记录和支撑分布式调用场景下的系统串联<br/> * 用于串联各个系统调用的一般是一个全局唯一的跟踪号,如果当前调用支持被跟踪,则返回true;<br/> * <p> * 在阿里中,进行跟踪的调用号被称为EagleEye * * @return true:支持被跟踪;false:不支持 */ public boolean isTraceSupport() { return GlobalOptions.isEnableTraceId && isAliEagleEyeSupport(); } /** * {{@link #getAliEagleEyeTraceId()}} 的别名,方便命令行使用 * * @return 本次调用的跟踪号 */ public String getTraceId() { return getAliEagleEyeTraceId(); } }
yuweijun/learning-programming
linux/greys/core/src/main/java/com/github/ompc/greys/core/Advice.java
Java
mit
5,911
import convexpress from "convexpress"; import * as config from "config"; const options = { info: { title: "lk-app-back", version: "1.0.2" }, host: config.HOST }; export default convexpress(options) .serveSwagger() .convroute(require("api/buckets/post")) .convroute(require("api/deployments/post"));
lk-architecture/lk-app-back
src/api/index.js
JavaScript
mit
342
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class Parameters { private ArrayList<Point> data = new ArrayList<Point>(); public Parameters(String path) { readData(path); } public String plot(Integer n) { String plot = "["; Double[] kdist = kdistance(n); ArrayList<Double> plotter = new ArrayList<Double>(); for(int i = 0 ; i < kdist.length ; i++) { plotter.add(kdist[i]); } Collections.sort(plotter); for(int i = 0 ; i < kdist.length ; i++) { plot += plotter.get(i) + " "; } plot = plot.substring(0, plot.length() - 1) + "]"; System.out.println(plot); return plot; } @SuppressWarnings("unchecked") public Double[] kdistance(Integer n) { ArrayList<Point> points = (ArrayList<Point>) data.clone(); Double[][] dists = distances(points); Double[] kdist = new Double[dists.length]; for(int i = 0 ; i < kdist.length ; i++) { kdist[i] = kdist(dists[i], n); } return kdist; } private Double kdist(Double[] vector, Integer n) { ArrayList<Double> temp = new ArrayList<Double>(); for(int i = 0 ; i < vector.length ; i++) { temp.add(vector[i]); } Collections.sort(temp); return temp.get(n); } private Double[][] distances(ArrayList<Point> points) { Double[][] dists = new Double[points.size()][points.size()]; for(int a = 0 ; a < dists.length ; a++) { Point one = points.get(a); for(int b = 0 ; b < dists[0].length ; b++) { Point two = points.get(b); dists[a][b] = new Double(two.distance(one)); } } return dists; } private void readData(String path) { try { BufferedReader br = new BufferedReader(new FileReader(new File(path))); String line = ""; while( (line = br.readLine()) != null ) { String[] aux = line.split("\t"); Double[] coord = new Double[aux.length]; for(int i = 0 ; i < aux.length ; i++) { coord[i] = new Double(aux[i]); } data.add(new Point(coord)); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { Parameters param = new Parameters("C:\\Git\\DataMiningProject\\DBSCAN\\conjunto_agrupamento.data.txt"); param.plot(4); } }
lucasbrunialti/DataMiningProject
DBSCAN/Parameters.java
Java
mit
2,493
export default class FormController { constructor($stateParams, $state, EquipamentoServico, Notification) { this.record = {} this.title = 'Adicionando registro' this._service = EquipamentoServico if ($stateParams.id) { this.title = 'Editando registro' this._service.findById($stateParams.id) .then(data => { this.record = data }) } this._state = $state this._notify = Notification } save() { this._service.save(this.record) .then(resp => { this._notify.success('Registro salvo com sucesso!') this._state.go('equipamento.list') }).catch(erro => { this._notify.error('Erro ao salvar o registro!') console.log(erro) }) } } FormController.$inject = ['$stateParams', '$state', 'EquipamentoServico', 'Notification']
lucionei/chamadotecnico
chamadosTecnicosFinal-app/src/app/equipamentos/form.controller.js
JavaScript
mit
977
using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.iOS; using Xamarin.UITest.Queries; namespace MessageBarUITests { [TestFixture] public class Tests { iOSApp app; [SetUp] public void BeforeEachTest() { // TODO: If the iOS app being tested is included in the solution then open // the Unit Tests window, right click Test Apps, select Add App Project // and select the app projects that should be tested. // // The iOS project should have the Xamarin.TestCloud.Agent NuGet package // installed. To start the Test Cloud Agent the following code should be // added to the FinishedLaunching method of the AppDelegate: // // #if ENABLE_TEST_CLOUD // Xamarin.Calabash.Start(); // #endif app = ConfigureApp .iOS // TODO: Update this path to point to your iOS app and uncomment the // code if the app is not included in the solution. //.AppBundle ("../../../iOS/bin/iPhoneSimulator/Debug/MessageBarUITests.iOS.app") .StartApp(); } [Test] public void WhenTappedOnTheInfoButtonShowInformationMessage() { app.Tap("Show Info"); app.Screenshot("Before messagebar"); app.WaitForElement(e => e.Id("MessageBar")); app.Screenshot("Messagebar dispalyed"); var title = app.Query(e => e.Id("MessageBar").Invoke("Title")).FirstOrDefault(); var text = app.Query(e => e.Id("MessageBar").Invoke("Description")).FirstOrDefault(); var type = app.Query(e => e.Id("MessageBar").Invoke("MessageType")).FirstOrDefault(); Assert.AreEqual("Info", title); Assert.AreEqual("This is information", text); Assert.AreEqual(type, 2); } [Test] public void GivenAMessageWhenTappedThenDismissTheMessageBar(){ app.Tap("Show Info"); app.WaitForElement(e => e.Id("MessageBar")); app.Screenshot("Messagebar dispalyed"); app.Tap(e => e.Id("MessageBar")); app.Screenshot("Messagebar dismissed"); //var expectedCount = app.Query(e => e.Id("MessageBar")).Count(); //Assert.AreEqual(0, expectedCount, "Mesagebar still visible"); } } }
prashantvc/Xamarin.iOS-MessageBar
MessageBarUITests/Tests.cs
C#
mit
2,113
<?php namespace luya\admin\aws; use Yii; use yii\base\InvalidConfigException; use Flow\Config; use Flow\Request; use Flow\File; use luya\helpers\FileHelper; use luya\admin\helpers\Storage; use luya\admin\ngrest\base\ActiveWindow; /** * Flow Uploader ActiveWindow enables multi image upload with chunck ability. * * The Flow ActiveWindow will not store any data in the filemanager as its thought to be used in large image upload * scenarios like galleries. The image are chuncked into parts in order to enable large image uploads. * * Example use: * * ```php * public function ngRestActiveWindows() * { * return [ * ['class' => \luya\admin\aws\FlowActiveWindow::class, 'label' => 'My Gallery'], * ]; * } * ``` * * The attached model class must implement the interface {{\luya\admin\aws\FlowActiveWindowInterface}} in order to interact with thw Activ Window. * * There is also a helper Trait {{\luya\admin\aws\FlowActiveWindowTrait}} you can include in order to work with a relation table. * * @author Basil Suter <basil@nadar.io> * @since 1.0.0 */ class FlowActiveWindow extends ActiveWindow { /** * @var string The name of the module where the active windows is located in order to finde the view path. */ public $module = '@admin'; /** * @inheritdoc */ public function index() { return $this->render('index'); } /** * @inheritdoc */ public function defaultLabel() { return 'Flow Uploader'; } /** * @inheritdoc */ public function defaultIcon() { return 'cloud_upload'; } /** * @inheritdoc */ public function getModel() { $model = parent::getModel(); if (!$model instanceof FlowActiveWindowInterface) { throw new InvalidConfigException("The model ".$this->model->className()."which attaches the FlowActiveWindow must be an instance of luya\admin\aws\FlowActiveWindowInterface."); } return $model; } /** * Returns a list of uploaded images. * * @return array */ public function callbackList() { $data = $this->model->flowListImages(); $images = []; foreach (Yii::$app->storage->findImages(['in', 'id', $data]) as $item) { $images[$item->id] = $item->applyFilter('small-crop')->toArray(); } return $this->sendSuccess('list loaded', [ 'images' => $images, ]); } /** * Remove a given image from the collection. * * @param integer $imageId * @return array */ public function callbackRemove($imageId) { $image = Yii::$app->storage->getImage($imageId); if ($image) { $this->model->flowDeleteImage($image); if (Storage::removeImage($image->id, true)) { return $this->sendSuccess('image has been removed'); } } return $this->sendError('Unable to remove this image'); } /** * Flow Uploader Upload. * * @return string */ public function callbackUpload() { $config = new Config(); $config->setTempDir($this->getTempFolder()); $file = new File($config); $request = new Request(); if ($_SERVER['REQUEST_METHOD'] === 'GET') { if ($file->checkChunk()) { header("HTTP/1.1 200 Ok"); } else { header("HTTP/1.1 204 No Content"); exit; } } else { if ($file->validateChunk()) { $file->saveChunk(); } else { // error, invalid chunk upload request, retry header("HTTP/1.1 400 Bad Request"); exit; } } if ($file->validateFile() && $file->save($this->getUploadFolder() . '/'.$request->getFileName())) { // File upload was completed $file = Yii::$app->storage->addFile($this->getUploadFolder() . '/'.$request->getFileName(), $request->getFileName(), 0, true); if ($file) { @unlink($this->getUploadFolder() . '/'.$request->getFileName()); $image = Yii::$app->storage->addImage($file->id); if ($image) { $image->applyFilter('small-crop'); $this->model->flowSaveImage($image); return 'done'; } } } else { // This is not a final chunk, continue to upload } } protected function getTempFolder() { $folder = Yii::getAlias('@runtime/flow-cache'); if (!file_exists($folder)) { FileHelper::createDirectory($folder, 0777); } return $folder; } protected function getUploadFolder() { $folder = Yii::getAlias('@runtime/flow-upload'); if (!file_exists($folder)) { FileHelper::createDirectory($folder, 0777); } return $folder; } }
nandes2062/luya
modules/admin/src/aws/FlowActiveWindow.php
PHP
mit
5,238
def add_generic_attachment_columns(t, want_image_columns) t.string :storage_key, :null => false t.string :content_type, :null => false t.integer :size, :null => false t.datetime :created_at, :null => false t.datetime :updated_at t.integer :width, :null => false if want_image_columns t.integer :height, :null => false if want_image_columns end ActiveRecord::Schema.define(:version => 0) do create_table :unprocesseds, :force => true do |t| t.string :original_filename, :null => false add_generic_attachment_columns(t, false) end create_table :images, :force => true do |t| t.string :original_filename, :null => false add_generic_attachment_columns(t, true) end create_table :derived_images, :force => true do |t| t.string :original_type, :null => false t.integer :original_id, :null => false t.string :format_name, :null => false add_generic_attachment_columns(t, true) end create_table :other_images, :force => true do |t| # for testing derived_image owner polymorphism t.string :original_filename, :null => false add_generic_attachment_columns(t, true) end create_table :all_in_one_table_images, :force => true do |t| t.string :original_filename # will be null for deriveds t.string :original_type # will be null for originals t.integer :original_id # ditto t.string :format_name # ditto add_generic_attachment_columns(t, true) end end
willbryant/attachment_saver
test/schema.rb
Ruby
mit
1,565
class CreateCommentVotes < ActiveRecord::Migration def change create_table :comment_votes do |t| t.boolean :like, null: false t.integer :user_id, null: false t.integer :comment_id, null: false t.timestamps null: false end end end
sayuloveit/rails-hacker-news-jr
hacker_news_jr/db/migrate/20150716211717_create_comment_votes.rb
Ruby
mit
267
namespace topCoder { using System; using System.Collections.Generic; class p1 { public void foo() { string[] sp = Console.ReadLine().Split(' '); int n = int.Parse(sp[0]); int m = int.Parse(sp[1]); int k = int.Parse(sp[2]); int[] x = new int[k]; int[] y = new int[k]; for (int i = 0; i < k; i++) { sp = Console.ReadLine().Split(' '); x[i] = int.Parse(sp[0])-1; y[i] = int.Parse(sp[1])-1; } bool[][] b = new bool[n][]; for (int i = 0; i < n; i++) { b[i] = new bool[m]; } int r = 0; for (; r < k; r++) { int xx = x[r]; int yy = y[r]; if (b[xx][yy]) continue; if ( ((xx-1 >= 0 && b[xx-1][yy]) && (xx-1>=0 && yy-1>=0 && b[xx-1][yy-1]) && (yy-1>=0 && b[xx][yy-1])) || ((xx+1 < n && b[xx+1][yy]) && (xx+1 < n && yy+1 < m && b[xx+1][yy+1]) && (yy+1 < m && b[xx][yy+1])) || ((xx-1 >= 0 && b[xx-1][yy]) && (xx-1 >= 0 && yy+1 < m && b[xx-1][yy+1]) && (yy+1 < m && b[xx][yy+1])) || ((yy-1>= 0&& b[xx][yy-1]) && (xx+1 < n && yy-1 >= 0 && b[xx+1][yy-1]) && (xx+1 < n && b[xx+1][yy])) ) break; else b[xx][yy] = true; } if (r >= k) r = -1; Console.WriteLine(r+1); } } }
karunasagark/ps
TopCoder-C#/288/p1.cs
C#
mit
1,194
/* ======================================== ID: mathema6 TASK: friday LANG: C++11 (...for USACO solutions) * File Name : friday.cpp * Creation Date : 03-01-2015 * Last Modified : * Created By : Karel Ha <mathemage@gmail.com> * URL : http://cerberus.delosent.com:791/usacoprob2?a=nJinR3Por13&S=friday * Duration : 30 min ==========================================*/ #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cassert> #include <string> #include <cctype> #include <fstream> #include <unordered_set> #include <unordered_map> using namespace std; #define FOR(I,A,B) for(int I = (A); I < (B); ++I) #define REP(I,N) FOR(I,0,N) #define ALL(A) (A).begin(), (A).end() #define MSG(a) cout << #a << " == " << a << endl; // uncomment following line for debug mode // #define DEBUG bool isLeap(short year) { return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); } int main() { ifstream fin ("friday.in"); // 31 28 31 30 31 30 31 31 30 31 30 31 short offset[12] = {3, 0, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3} ; int n; fin >> n; short day = 0; // 13th Jan 1900 vector<int> histogram(7); REP(year,n) { REP(month,12) { histogram[day]++; day += offset[month]; if (month == 1 && isLeap(1900 + year)) day++; day %= 7; } } ofstream fout ("friday.out"); REP(i,7) { fout << histogram[i]; if (i < 6) fout << " "; else fout << endl; } return 0; }
mathemage/CompetitiveProgramming
usaco/train.usaco.org/1.2/friday/friday.cpp
C++
mit
1,781
using System; using System.Collections.Generic; using Microsoft.AspNet.Http; namespace Glimpse.Server { public class GlimpseServerOptions { public bool AllowRemote { get; set; } public string BasePath { get; set; } public Action<IDictionary<string, string>> OverrideResources { get; set; } public Func<HttpContext, bool> AllowClientAccess { get; set; } public Func<HttpContext, bool> AllowAgentAccess { get; set; } } }
peterblazejewicz/Glimpse.Prototype
src/Glimpse.Server.Core/GlimpseServerOptions.cs
C#
mit
478
using System.Diagnostics; namespace NWamp.Messages { /// <summary> /// Message class used to subscribe client to Pub/Sub topic. /// </summary> [DebuggerDisplay("[{Type}, \"{TopicUri}\"]")] public class SubscribeMessage : IMessage { /// <summary> /// Initializes a new instance of the <see cref="SubscribeMessage"/> class. /// </summary> /// <remarks>Use this constructor for serialization only.</remarks> public SubscribeMessage() { } /// <summary> /// Initializes a new instance of the <see cref="SubscribeMessage"/> class. /// </summary> /// <param name="topicUri">URI or CURIE identifying Pub/Sub topic</param> public SubscribeMessage(string topicUri) { TopicUri = topicUri; } /// <summary> /// Gets type of this message: <see cref="MessageTypes.Subscribe"/>. /// </summary> public MessageTypes Type { get { return MessageTypes.Subscribe; } } /// <summary> /// Gets or sets URI or CURIE identifying Pub/Sub topic, message sender want subscribe to. /// </summary> public string TopicUri { get; set; } /// <summary> /// Parses current message to array of objects, ready to serialize it directly into WAMP message frame. /// </summary> public object[] ToArray() { return new object[] { MessageTypes.Subscribe, TopicUri }; } } }
Horusiath/NWamp
NWamp/Messages/SubscribeMessage.cs
C#
mit
1,512
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using Microsoft.Xaml.Behaviors; namespace MahApps.Metro.Behaviors { /// <summary> /// <para> /// Sets the first TabItem with Visibility="<see cref="Visibility.Visible"/>" as /// the SelectedItem of the TabControl. /// </para> /// <para> /// If there is no visible TabItem, null is set as the SelectedItem /// </para> /// </summary> public class TabControlSelectFirstVisibleTabBehavior : Behavior<TabControl> { protected override void OnAttached() { AssociatedObject.SelectionChanged += OnSelectionChanged; } private void OnSelectionChanged(object sender, SelectionChangedEventArgs args) { List<TabItem> tabItems = AssociatedObject.Items.Cast<TabItem>().ToList(); TabItem selectedItem = AssociatedObject.SelectedItem as TabItem; //if the selected item is visible already, return if (selectedItem != null && selectedItem.Visibility == Visibility.Visible) { return; } //get first visible item TabItem firstVisible = tabItems.FirstOrDefault(t => t.Visibility == Visibility.Visible); if (firstVisible != null) { AssociatedObject.SelectedIndex = tabItems.IndexOf(firstVisible); } else { //there is no visible item //Raises SelectionChanged again one time (second time, oldValue == newValue) AssociatedObject.SelectedItem = null; } } protected override void OnDetaching() { AssociatedObject.SelectionChanged -= OnSelectionChanged; } } }
ye4241/MahApps.Metro
src/MahApps.Metro/Behaviors/TabControlSelectFirstVisibleTabBehavior.cs
C#
mit
2,051
#ifndef __DEFINES_HPP_ #define __DEFINES_HPP_ // Compiler defines #if defined (_MSC_VER) #define FORCE_INLINE __forceinline #elif defined (__GNUG__) #define FORCE_INLINE __attribute__((always_inline)) #elif defined (__clang__) #define FORCE_INLINE __forceinline #endif // Plateform defines #if defined(_WIN32) || defined(_WIN64) #define WINDOWS //#define _CRT_SECURE_NO_WARNINGS #elif defined (__APPLE__) #define APPLE #elif defined (__linux__) #define LINUX #elif defined (__unix__) #define UNIX #else #define UNKNOW_PLATFORM #endif #define FALSE 0 #define TRUE 1 //if(!expr) doesn't work #define ASSERT(expr)\ if(!(expr)) \ throw #define LOG_ASSERT(expr, msg) \ if(!(expr)) { \ DadEngine::Core::LogAssert(msg, __FILE__, __LINE__);\ throw; } #endif //__DEFINES_HPP_
Gotatang/DadEngine_2.0
include/dadengine/core/defines.hpp
C++
mit
801
package iso20022 // Status and reason of an instructed order. type StatusAndReason7 struct { // Status and reason for the transaction. StatusAndReason *Status2Choice `xml:"StsAndRsn"` // Details of the transactions reported. Transaction []*Transaction14 `xml:"Tx,omitempty"` } func (s *StatusAndReason7) AddStatusAndReason() *Status2Choice { s.StatusAndReason = new(Status2Choice) return s.StatusAndReason } func (s *StatusAndReason7) AddTransaction() *Transaction14 { newValue := new(Transaction14) s.Transaction = append(s.Transaction, newValue) return newValue }
fgrid/iso20022
StatusAndReason7.go
GO
mit
580
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class DischargeTime extends AbstractTag { protected $Id = '0038,0032'; protected $Name = 'DischargeTime'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Discharge Time'; }
romainneutron/PHPExiftool
lib/PHPExiftool/Driver/Tag/DICOM/DischargeTime.php
PHP
mit
788
/***************************************************** * * Designed and programmed by Mohamed Adam Chaieb. * *****************************************************/ /* Constructs a new tile. */ function Tile(position, level) { this.x = position.x; this.y = position.y; this.level = level; }; /* Updates the position of the tile. */ Tile.prototype.updatePosition = function(position) { this.x = position.x; this.y = position.y; };
mac-adam-chaieb/Isometric-2048
js/tile.js
JavaScript
mit
444
package main import ( "bytes" "encoding/json" "flag" "fmt" "io" "io/ioutil" "net/http" "os" "os/exec" "path" "time" "github.com/nchern/red/app" color "gopkg.in/fatih/color.v1" ) const ( jsonIndent = " " filenameBase = "query" queryFilename = filenameBase + ".red" outFilename = filenameBase + ".redout" ) var ( editor = env("EDITOR", "vim") editorFlags = env("EDITOR_FLAGS", "-O") appHomePath = path.Join(os.Getenv("HOME"), ".red") queryFilePath = path.Join(appHomePath, queryFilename) outFilePath = path.Join(appHomePath, outFilename) client = &http.Client{ Timeout: 3 * time.Second, } flagCmd = flag.String("c", "edit", "Command to exectue. One of: edit, run, example") flagSourceFile = flag.String("s", queryFilePath, "Source file with queries. Might be under edit in the editor of choice") flagOutputFile = flag.String("o", outFilePath, "File to write query results. '-' means stdout") flagDuplicateStdin = flag.Bool("d", true, "Duplicate query to stdin") // opens the editor of preference to edit requests cmdEdit = "edit" // runs a given query, either from stdin or a query file(TODO: make it accept "-") cmdRun = "run" // prints out example of request file cmdExample = "example" ) func openEditor() error { if _, err := os.Stat(*flagSourceFile); os.IsNotExist(err) { if err := os.MkdirAll(appHomePath, 0700); err != nil { return err } // path/to/whatever does not exist if err := ioutil.WriteFile(queryFilePath, app.MustAsset(app.TemplateAsset), 0644); err != nil { return err } } cmd := exec.Command(editor, *flagSourceFile) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } func doRequest(req *app.HTTPRequest) (int, []byte, error) { src, err := req.JSON() if err != nil { return 0, nil, err } httpReq, err := http.NewRequest(req.Method, req.URL(), bytes.NewBufferString(src)) if err != nil { return 0, nil, err } httpReq.Header = req.Headers resp, err := client.Do(httpReq) if err != nil { return 0, nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return 0, nil, err } return resp.StatusCode, tryFormatJSON(body), nil } func runQuery(primaryReader io.Reader, secondryReader io.Reader, out io.Writer) error { request, err := app.ParseRequest(primaryReader) if err != nil { return err } if sel, err := app.TryParseAsync(secondryReader); err == nil { // got the whole query file or it is enough input to use parsed data from stdin if sel.Validate() == nil { request = sel } else { request.URI = sel.URI request.Method = sel.Method request.CopyBodyFrom(sel) } } if err := request.Validate(); err != nil { return err } code, body, err := doRequest(request) if err != nil { return err } if _, err := fmt.Fprintf(out, "#> %d %s %s\n\n", code, request.Method, request.URL()); err != nil { return err } _, err = out.Write(body) return err } func example() error { data := app.MustAsset(app.TemplateAsset) fmt.Fprintln(os.Stdout, string(data)) return nil } func run() error { srcReader, err := os.Open(*flagSourceFile) if err != nil { return err } defer srcReader.Close() w := os.Stdout if *flagOutputFile != "-" { w, err = os.Create(*flagOutputFile) if err != nil { return err } defer w.Close() } var secondary io.Reader = os.Stdin if *flagDuplicateStdin { // TODO: get rid of the logic especially if we can accept "-" from cmd line(see corresponding todo)? // Mirror stdin to stout - this allows processing selections in vim correctly secondary = io.TeeReader(os.Stdin, os.Stdout) } return runQuery(srcReader, secondary, w) } func doCmd() error { switch *flagCmd { case cmdEdit: return openEditor() case cmdExample: return example() case cmdRun: return run() } return fmt.Errorf("Unknown action: %s", *flagCmd) } func main() { flag.Parse() if err := doCmd(); err != nil { if err == app.ErrFormatFailed { os.Exit(1) } switch err := err.(type) { case *exec.ExitError: case *app.JsonifyError: if syntaxErr, ok := err.Inner.(*json.SyntaxError); ok { errorf("Bad JSON query: %s", err) fmt.Fprintf(os.Stderr, "%s\n", color.RedString(err.Highlighted(syntaxErr.Offset))) break } errorf("%s", err) default: errorf("%s", err) } os.Exit(1) } } func errorf(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, "%s ", color.RedString("ERROR")) fmt.Fprintf(os.Stderr, format+"\n", args...) } func notEmpty(val, defaultVal string) string { if val != "" { return val } return defaultVal } func env(key, defaultVal string) string { return notEmpty(os.Getenv(key), defaultVal) } func tryFormatJSON(body []byte) []byte { var out bytes.Buffer if err := json.Indent(&out, body, "", jsonIndent); err != nil { return body } return out.Bytes() }
nchern/red
main.go
GO
mit
4,910
#ifdef WITH_SDL2 #pragma once #include <SDL.h> #include "../Window.hpp" #include "psychic-ui/ApplicationBase.hpp" #if defined(PSYCHIC_UI_WITH_GLAD) #if defined(PSYCHIC_UI_SHARED) && !defined(GLAD_GLAPI_EXPORT) #define GLAD_GLAPI_EXPORT #endif #include <glad/glad.h> #endif #if defined(ANDROID) #include <GLES/gl.h> #elif defined(UNIX) #include <GL/gl.h> #elif defined(APPLE) #include <OpenGL/gl.h> #elif defined(IOS) #include <OpenGLES/ES2/gl.h> #endif namespace psychic_ui { class SDL2SystemWindow; class SDL2Application : public ApplicationBase { friend class SDL2SystemWindow; public: static std::unordered_map<unsigned int, std::unique_ptr<SDL2SystemWindow>> sdl2Windows; void init() override; void mainloop() override; void open(std::shared_ptr<Window> window) override; void close(std::shared_ptr<Window> window) override; void shutdown() override; protected: bool running{false}; void sdl2PollEvents(); }; class SDL2SystemWindow : public SystemWindow { friend class SDL2Application; public: SDL2SystemWindow(SDL2Application *application, std::shared_ptr<Window> window); ~SDL2SystemWindow(); SDL_Window *sdl2Window() const; void handleEvent(const SDL_Event &e); void liveResize(int width, int height); bool render() override; protected: SDL2Application *_sdl2Application{nullptr}; SDL_Window *_sdl2Window{nullptr}; SDL_GLContext _sdl2GlContext{nullptr}; /** * Mapping of internal cursors enum to glfw int cursor */ SDL_Cursor *_cursors[6]; void setTitle(const std::string &title) override; void setFullscreen(bool fullscreen) override; bool getMinimized() const override; void setMinimized(bool minimized) override; bool getMaximized() const override; void setMaximized(bool maximized) override; void setVisible(bool visible) override; void setCursor(int cursor) override; void startDrag() override; void stopDrag() override; void setSize(int width, int height) override; void setPosition(int x, int y) override; void startTextInput() override; void stopTextInput() override; static Mod mapMods(int mods); static Key mapKey(int keycode); }; } #endif
ubald/psychic-ui
psychic-ui/applications/SDL2Application.hpp
C++
mit
2,428
// This software is part of OpenMono, see http://developer.openmono.com // Released under the MIT license, see LICENSE.txt #include "encoder.hpp" #include "constants.hpp" Encoder::Encoder (PinName pinA, PinName pinB) : lastA(0), lastB(0), channelA(pinA), channelB(pinB) { #ifndef EMUNO // Pull up A. CyPins_SetPinDriveMode(pinA, CY_PINS_DM_RES_UP); CyPins_SetPin(pinA); // Pull up B. CyPins_SetPinDriveMode(pinB, CY_PINS_DM_RES_UP); CyPins_SetPin(pinB); #endif reset(); #ifndef EMUNO // Samples every 100µs. ticker.attach_us(this, &Encoder::sample, 100); #endif } void Encoder::reset () { pulses = 0; } int Encoder::getPulses () { return pulses; } void Encoder::sample () { uint8_t a = channelA.read(); uint8_t b = channelB.read();; if (a != lastA || b != lastB) { translate(a, b); lastA = a; lastB = b; } } void Encoder::translate (uint8_t a, uint8_t b) { // 00 -> 01 -> 11 -> 10 -> ... = clockwise rotation. if ( (lastA == 0 && lastB == 0 && a == 0 && b >= 1) || (lastA == 0 && lastB >= 1 && a >= 1 && b >= 1) || (lastA >= 1 && lastB >= 1 && a >= 1 && b == 0) || (lastA >= 1 && lastB == 0 && a == 0 && b == 0) ) { ++pulses; } // 01 -> 00 -> 10 -> 11 -> ... = counter clockwise rotation. else if ( (lastA == 0 && lastB >= 1 && a == 0 && b == 0) || (lastA == 0 && lastB == 0 && a >= 1 && b == 0) || (lastA >= 1 && lastB == 0 && a >= 1 && b >= 1) || (lastA >= 1 && lastB >= 1 && a == 0 && b >= 1) ) { --pulses; } }
getopenmono/pong
encoder.cpp
C++
mit
1,532
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z" /></g> , 'InsertLink');
cherniavskii/material-ui
packages/material-ui-icons/src/InsertLink.js
JavaScript
mit
360
<?php namespace Madrasse\AdminBundle\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('madrasse_admin'); // 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; } }
fardus/madrasse-gestion
src/Madrasse/AdminBundle/DependencyInjection/Configuration.php
PHP
mit
883
<?php /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\Phpdoc; use PhpCsFixer\AbstractProxyFixer; /** * @author Graham Campbell <graham@alt-three.com> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> */ final class PhpdocNoAccessFixer extends AbstractProxyFixer { /** * {@inheritdoc} */ public function getDescription() { return '@access annotations should be omitted from phpdocs.'; } /** * {@inheritdoc} */ protected function createProxyFixer() { $fixer = new GeneralPhpdocAnnotationRemoveFixer(); $fixer->configure(array('access')); return $fixer; } }
julienfalque/PHP-CS-Fixer
src/Fixer/Phpdoc/PhpdocNoAccessFixer.php
PHP
mit
896
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Capercali.Entities { public class Runner : IEntity { public long Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int SiNumber { get; set; } public string Club { get; set; } public string Adress { get; set; } public string PLZ { get; set; } public string Location { get; set; } public string Email { get; set; } } }
yannisgu/capercali
src/Capercali.Entities/Runner.cs
C#
mit
633
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Globalization; using System.Web.Mvc; namespace WMATC.Models { public class Player { [Required] [Key] public int PlayerId { get; set; } public string Name { get; set; } public int? FactionId { get; set; } [ForeignKey("FactionId")] public virtual Faction Faction { get; set; } public string Caster1 { get; set; } [AllowHtml] public string List1 { get; set; } public string Theme1 { get; set; } public string Caster2 { get; set; } [AllowHtml] public string List2 { get; set; } public string Theme2 { get; set; } public int TeamId { get; set; } [ForeignKey("TeamId")] public Team Team { get; set; } } }
ThatRickGuy/WMATC
WMATC/Models/Player.cs
C#
mit
953
from random import randint from django.conf import settings from django.contrib.auth.models import User from django.db import models, connection from django.db.models.aggregates import Avg, Max from polymorphic.models import PolymorphicModel from solo.models import SingletonModel class Judge(PolymorphicModel): name = models.CharField(max_length=30) def __str__(self): return self.name class HumanJudge(Judge): user = models.OneToOneField(to=User, related_name='judge', null=True, default=None) class AutomatedJudge(Judge): ip_address = models.GenericIPAddressField(unique=True) port = models.PositiveIntegerField(default=settings.DEFAULT_JUDGE_PORT) @classmethod def get_random_judge(cls): count = cls.objects.count() random_index = randint(0, count-1) return cls.objects.all()[random_index] class JudgeRequest(models.Model): time = models.DateTimeField(auto_now_add=True) is_closed = models.BooleanField(default=False) feature = models.ForeignKey(to='features.Feature', related_name='judge_requests') team = models.ForeignKey(to='teams.Team', related_name='judge_requests') def __str__(self): return '{} for {}'.format(str(self.team), str(self.feature)) @property def assignee1(self): return self.assignees.first() or None @property def assignee2(self): if self.assignees.count() < 2: return None return self.assignees.last() or None @property def judge1_score(self): return getattr(self.assignee1, 'score', '--') @property def judge2_score(self): return getattr(self.assignee2, 'score', '--') @property def score(self): return self.assignees.aggregate(score=Avg('score'))['score'] or 0 @property def message(self): assignee = self.assignees.first() if not assignee: return "" return str(assignee.message) @property def is_passed(self): if connection.vendor == 'postgresql': from django.contrib.postgres.aggregates import BoolOr agg = BoolOr else: agg = Max return self.assignees.aggregate(is_passed=agg('is_passed'))['is_passed'] or False class JudgeRequestAssignment(models.Model): judge = models.ForeignKey(to=Judge, related_name='assignments') score = models.FloatField(null=True, blank=True) is_passed = models.BooleanField(default=False) judge_request = models.ForeignKey(to=JudgeRequest, related_name='assignees') message = models.TextField(null=True, blank=True) def __str__(self): return '{} assigned to {} with score {}'.format(str(self.judge), str(self.judge_request), str(self.score)) class Config(SingletonModel): day = models.IntegerField(default=1) is_frozen = models.BooleanField(default=False) frozen_scoreboard = models.TextField(default="", blank=True) assign_to_automated_judge = models.BooleanField(default=True) timeout_minutes = models.PositiveIntegerField(default=10)
Kianoosh76/webelopers-scoreboard
jury/models.py
Python
mit
3,183
/* * LCADeviceRoomba * * MIT License * * Copyright (c) 2016 * * Geoffrey Mastenbroek, geoffrey.mastenbroek@student.hu.nl * Feiko Wielsma, feiko.wielsma@student.hu.nl * Robbin van den Berg, robbin.vandenberg@student.hu.nl * Arnoud den Haring, arnoud.denharing@student.hu.nl * * 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 com.maschel.lcadevice.roomba.Simulator; import com.maschel.lca.lcadevice.device.Component; import com.maschel.lca.lcadevice.device.Device; import com.maschel.lca.lcadevice.device.actuator.Actuator; import com.maschel.lca.lcadevice.device.sensor.Sensor; import com.maschel.lcadevice.roomba.Arguments; import com.maschel.roomba.RoombaJSSC; import com.maschel.roomba.RoombaJSSCSerial; import com.maschel.roomba.song.RoombaNote; import com.maschel.roomba.song.RoombaNoteDuration; import com.maschel.roomba.song.RoombaSongNote; /* * RoombaDeviceSimulator class * Simulator class that simulates the Roomba device, by generating random values for the sensors/actuators. * Used to hold all the manufacturer implementations of reading the sensors and actuating actuators. * All the Components, Sensors and Actuators are created and added to the rootComponend in the setup() method. */ public class RoombaDeviceSimulator extends Device { private static final RandomGenerator rg = new RandomGenerator(); private static String ID = ""; private static final int SENSOR_UPDATE_INTERVAL = 50; public RoombaDeviceSimulator() { super(ID, SENSOR_UPDATE_INTERVAL); } public void setup() { // Generate random device id ID = rg.nextSessionId(); /* * We use a hierarchical Component model here. * 'roomba' is the main Component, which has a few subcomponents ('motors' and 'battery') * Many basic functions like 'startup' or 'clean' are under the 'roomba' component. * The 'motors' component has different Components under it which represent the different motors of the Roomba. * It also has the 'drive' Actuator directly under it. * */ Component roombaComponent = new Component("roomba"); addComponent(roombaComponent); Component motorsComponent = new Component("motors"); roombaComponent.add(motorsComponent); Component leftMotorComponent = new Component("leftMotorWheel"); Component rightMotorComponent = new Component("rightMotorWheel"); Component mainBrushComponent = new Component("mainBrushMotor"); Component sideBrushComponent = new Component("sideBrushMotor"); roombaComponent.add(leftMotorComponent); roombaComponent.add(rightMotorComponent); roombaComponent.add(mainBrushComponent); roombaComponent.add(sideBrushComponent); Component batteryComponent = new Component("battery"); roombaComponent.add(new Actuator<Void>("clean") { public void actuate(Void args) throws IllegalArgumentException { return; } }); roombaComponent.add(new Actuator<Void>("cleanMax") { public void actuate(Void args) throws IllegalArgumentException { return; } }); roombaComponent.add(new Actuator<Void>("cleanSpot") { public void actuate(Void args) throws IllegalArgumentException { return; } }); roombaComponent.add(new Actuator<Void>("seekDock") { public void actuate(Void args) throws IllegalArgumentException { return; } }); roombaComponent.add(new Actuator<Void>("startup") { public void actuate(Void args) throws IllegalArgumentException { return; } }); roombaComponent.add(new Actuator<Void>("powerOff") { public void actuate(Void args) throws IllegalArgumentException { return; } }); roombaComponent.add(new Actuator<String>("digitLedsAscii") { public void actuate(String args) throws IllegalArgumentException { if(args.length() != 4) { throw new IllegalArgumentException(); } return; } }); roombaComponent.add(new Actuator<String>("playMusic") { public void actuate(String args) throws IllegalArgumentException { return; } }); // Motors motorsComponent.add(new Actuator<Arguments.DriveArguments>("drive") { @Override public void actuate(Arguments.DriveArguments driveArguments) throws IllegalArgumentException { return; } }); motorsComponent.add(new Sensor("distanceTraveled", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(-32768, 32767); } }); leftMotorComponent.add(new Sensor("motorCurrentLeft", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(-32768, 32767); } }); rightMotorComponent.add(new Sensor("motorCurrentRight", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(-32768, 32767); } }); mainBrushComponent.add(new Sensor("motorCurrentMainBrush", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(-32768, 32767); } }); sideBrushComponent.add(new Sensor("motorCurrentSideBrush", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(-32768, 32767); } }); //BatteryComponent batteryComponent.add(new Sensor("chargingState", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(0, 5); } }); batteryComponent.add(new Sensor("batteryVoltage", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(0, 65535); } }); batteryComponent.add(new Sensor("batteryCurrent", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(-32768, 32768) + 1; } }); batteryComponent.add(new Sensor("batteryTemperature", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(-128, 127); } }); batteryComponent.add(new Sensor("batteryCharge", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(0, 65535); } }); batteryComponent.add(new Sensor("batteryCapacity", SENSOR_UPDATE_INTERVAL) { @Override public Integer readSensor() { return rg.randomInteger(0, 65535); } }); roombaComponent.add(batteryComponent); } public void connect() { return; } public void update() { return; } public Boolean deviceReadyForAnalyticDataSync() { return null; } public void disconnect() { return; } }
maschel/LCADeviceRoomba
src/main/java/com/maschel/lcadevice/roomba/Simulator/RoombaDeviceSimulator.java
Java
mit
8,709
#pragma once #ifndef LINE_HPP #define LINE_HPP #include <initializer_list> #include <map> #include <string> #include <vector> #include "route.hpp" using RouteName = std::string; using RouteNames = std::vector<RouteName>; using StepsByRoute = std::pair<RouteName, Steps>; using StepsRoutes = std::vector<StepsByRoute>; class Line { public: Route& addRoute(const std::string& rstr) { return routes_[rstr]; } void removeRoute(const std::string& rstr) { routes_.erase(routes_.find(rstr)); } RouteNames getRouteNames() const { return getKeyVector(routes_); } std::string getPlatform(const RouteName& routen, const Stop& stop) const { return routes_.at(routen).getPlatform(stop); } StopSet getStopSet() const; StepsRoutes getForwardStepsRoutes() const; StepsRoutes getBackwardStepsRoutes() const; TimeLine getStopTimes(Day day, const RouteName& routen, const Stop& stop) const { return routes_.at(routen).getStopTimes(day, stop); } TimeLine getStopTimes(Day day, const Stop& stop) const; Time getArriveTime(Day day, const RouteName& routen, const Stop& from, Time leave, const Stop& to) const { return routes_.at(routen).getArriveTime(day, from, leave, to); } std::string getRouteDescription(const RouteName& routen) const { return routes_.at(routen).description(); } private: std::map<RouteName, Route> routes_; }; #endif // LINE_HPP
gonmator/busplan
busplan/line.hpp
C++
mit
1,470
<?php /* * This file is part of the NAD package. * * (c) Ivan Proskuryakov * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NAD\ResourceBundle\Request; use FOS\RestBundle\Request\RequestBodyParamConverter; use JMS\Serializer\DeserializationContext; use JMS\Serializer\Serializer; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter as SensioParamConverter; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Doctrine\ORM\EntityManager; use Symfony\Component\Validator\Validator\ValidatorInterface; use NAD\ResourceBundle\Exception\ValidationFailedException; use JMS\Serializer\SerializationContext; /** * Class ParamConverter * * @author Mohammadreza Razzaghi <razzaghi229@gmail.com> */ class ParamConverter extends RequestBodyParamConverter { /** * @var EntityManager */ protected $em; /** * @var EventDispatcherInterface */ private $dispatcher; /** * @param Serializer $serializer * @param EntityManager $entityManager * @param ValidatorInterface $validator * @param EventDispatcherInterface $dispatcher */ public function __construct( Serializer $serializer, EntityManager $entityManager, ValidatorInterface $validator, EventDispatcherInterface $dispatcher ) { parent::__construct($serializer, null, null, $validator, 'error'); $this->em = $entityManager; $this->dispatcher = $dispatcher; } /** * execute * * @param Request $request * @param SensioParamConverter $configuration * * @return bool|mixed */ public function execute(Request $request, SensioParamConverter $configuration) { $name = $configuration->getName(); $options = $configuration->getOptions(); $resolvedClass = $configuration->getClass(); $id = $request->attributes->get('id'); $method = $request->getMethod(); $rawPayload = $request->getContent(); switch (true) { case ('GET' === $method): $convertedValue = $this->loadEntity($resolvedClass, $id, $maxDepth = true); break; case ('DELETE' === $method): $convertedValue = $this->loadEntity($resolvedClass, $id); break; case ('PUT' === $method): $payload = array_merge( array('id' => $id), json_decode($rawPayload, true) ); $convertedValue = $this->updateEntity($resolvedClass, json_encode($payload)); break; case ('POST' === $method): $convertedValue = $this->updateEntity($resolvedClass, $rawPayload); break; } return $convertedValue; } /** * @param $resolvedClass * @param $id * @param $maxDepth * * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException * @throws \Doctrine\ORM\TransactionRequiredException * @throws NotFoundHttpException * * @return mixed $entity */ protected function loadEntity($resolvedClass, $id, $maxDepth = false) { $entity = $this->em->find($resolvedClass, $id); if (null === $entity) { throw new NotFoundHttpException('Not found'); } if ($maxDepth) { $entity = $this->serializer->serialize( $entity, 'json', SerializationContext::create()->enableMaxDepthChecks() ); return json_decode($entity, true); } return $entity; } /** * @param $resolvedClass * @param $rawPayload * * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException * @throws \Doctrine\ORM\TransactionRequiredException * @throws NotFoundHttpException * * @return mixed $entity */ protected function updateEntity($resolvedClass, $rawPayload) { $serializerGroups = isset($options['serializerGroups']) ? $options['serializerGroups'] : null; $deserializationContext = DeserializationContext::create(); if ($serializerGroups) { $deserializationContext ->setGroups($serializerGroups) ; } $convertedValue = $this->serializer->deserialize( $rawPayload, $resolvedClass, 'json' ); $violations = $this->validator->validate($convertedValue); if ($violations->count()) { throw new ValidationFailedException($violations); } return $convertedValue; } }
razzaghi/NAD
src/NAD/ResourceBundle/Request/ParamConverter.php
PHP
mit
5,072
import knockout = require("knockout"); class Item { public Id:KnockoutObservable<string> = knockout.observable(""); public Title:KnockoutObservable<string> = knockout.observable(""); constructor(data:{Id:string; Title:string }) { this.Id(data.Id); this.Title(data.Title); } public DragStart(target:Item, event:JQueryEventObject):boolean { var dragEvent = <DragEvent>event.originalEvent; dragEvent.dataTransfer.setData("application/x-tieritem", this.Id()); dragEvent.dataTransfer.effectAllowed = "move"; return true; } } export = Item;
Lillemanden/TierList
TierList/App/Components/Item/Item.ts
TypeScript
mit
563
#!/usr/bin/env ruby require 'i3rb' include I3::API include I3::Bar::Widgets host = I3::Bar::Widgets::HOSTNAME host.color = "#00FFFF" host.add_event_callback do |w| system "xterm", "-e", "top" end cmus = I3::Bar::Widgets::CMUS cmus.add_event_callback do |w,e| if e["button"]== 1 system "cmus-remote", "--pause" end end bar = I3::Bar.get_instance do |b| include I3::Bar::Widgets b.add_widgets [ host, CMUS, WIFI, TEMPERATURE, BATTERY, CALENDAR ] b.add_event_callback do |w,e| $stderr.puts e.inspect end b.start_events_capturing b.run 1 end
MinasMazar/dotfiles
i3.symlink/i3ba.rb
Ruby
mit
574
import { connect } from 'react-redux'; import { makeSelectClaimForUri } from 'lbry-redux'; import LivestreamLink from './view'; const select = (state, props) => ({ channelClaim: makeSelectClaimForUri(props.uri)(state), }); export default connect(select)(LivestreamLink);
lbryio/lbry-app
ui/component/livestreamLink/index.js
JavaScript
mit
275
#include "AnimationComponentModule.h" #include "AnimationComponent.h" using namespace PaintsNow; using namespace PaintsNow::NsMythForest; using namespace PaintsNow::NsSnowyStream; AnimationComponentModule::AnimationComponentModule(Engine& engine) : ModuleImpl<AnimationComponent>(engine) {}
paintsnow/paintsnow
Source/Utility/MythForest/Component/Animation/AnimationComponentModule.cpp
C++
mit
292
var request = require("request"); var util = require("util"); var async = require("async"); var config = require("./config"); var log = require("./log"); var error = require("./error"); var tools = require("./tools"); var buffer = require("./buffer"); var api = {}; //url:http://127.0.0.1/path //data: an object //ifbuff: whether buffer the post //cb(err, result) api.post = function(url, data, ifbuff, cb) { var datastr = tools.objToString(data); async.series([ function(callback) { if(ifbuff){ buffer.get(url + datastr, function(err, res_get){ if(err){ callback(err, null); return; } if(!res_get){ //buffer not hit callback(null, null); }else{ //buffer hit callback(1, tools.stringToObj(res_get)); } }); }else{ //not a buff request callback(null, null); } }, function(callback) { //buffer not hit //request for data options = { method: "POST", url: url, timeout: config.request.timeout, // body:datastr, json:data }; request(options, function(err, res, body){ if(err) { log.toolslog("error", util.format("at api.post: request url:%s, data: %j, error:%s", url, data, err)); callback(error.get("syserr", null)); }else{ //set buffer if(ifbuff){ buffer.set(url + datastr, body); } callback(null, tools.stringToObj(body)); } }); } ], function(err, result){ if(err == 1) { //buffer hit, get from first callback cb(null, result[0]); }else{ //buffer not hit, get from second callback cb(err, result[1]); } }); } api.wait = function(res, listName) { res.wait(listName); } api.nowait = function(res, listName) { res.nowait(listName); } api.sendText = function(res, text) { res.reply(text); } api.sendImage = function(res, mediaId) { res.reply({ type: "image", content: { mediaId: mediaId } }); } api.sendVoice = function(res, mediaId) { res.reply({ type: "voice", content: { mediaId: mediaId } }); } api.sendVideo = function(res, mediaId, thumbMediaId) { res.reply({ type: "video", content: { mediaId: mediaId, thumbMediaId: thumbMediaId } }); } api.sendMusic = function(res, title, description, musicUrl, hqMusicUrl) { res.reply({ title: title, description: description, musicUrl: musicUrl, hqMusicUrl: hqMusicUrl }); } //articls is an array of object of {title, description, picurl, url} /* just like below: articls = [{ title: title, description: description, picurl: picurl, url: url },{ title: title2, description: description2, picurl: picurl2, url: url2 }] */ api.sendTextImage = function(res, articls) { res.reply(articls); } api.writelog = function(level, str) { log.userlog(level, str); } module.exports = api;
JustAnotherCan/wechat-ship
server/core/api.js
JavaScript
mit
2,796
uis.directive('uiSelect', ['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout', function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) { return { restrict: 'EA', templateUrl: function(tElement, tAttrs) { var theme = tAttrs.theme || uiSelectConfig.theme; return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html'); }, replace: true, transclude: true, require: ['uiSelect', '^ngModel'], scope: true, controller: 'uiSelectCtrl', controllerAs: '$select', compile: function(tElement, tAttrs) { // Allow setting ngClass on uiSelect var match = /{(.*)}\s*{(.*)}/.exec(tAttrs.ngClass); if(match) { var combined = '{'+ match[1] +', '+ match[2] +'}'; tAttrs.ngClass = combined; tElement.attr('ng-class', combined); } //Multiple or Single depending if multiple attribute presence if (angular.isDefined(tAttrs.multiple)) tElement.append('<ui-select-multiple/>').removeAttr('multiple'); else tElement.append('<ui-select-single/>'); if (tAttrs.inputId) tElement.querySelectorAll('input.ui-select-search')[0].id = tAttrs.inputId; return function(scope, element, attrs, ctrls, transcludeFn) { var $select = ctrls[0]; var ngModel = ctrls[1]; $select.generatedId = uiSelectConfig.generateId(); $select.baseTitle = attrs.title || 'Select box'; $select.focusserTitle = $select.baseTitle + ' focus'; $select.focusserId = 'focusser-' + $select.generatedId; $select.closeOnSelect = function() { if (angular.isDefined(attrs.closeOnSelect)) { return $parse(attrs.closeOnSelect)(); } else { return uiSelectConfig.closeOnSelect; } }(); scope.$watch('skipFocusser', function() { var skipFocusser = scope.$eval(attrs.skipFocusser); $select.skipFocusser = skipFocusser !== undefined ? skipFocusser : uiSelectConfig.skipFocusser; }); $select.onSelectCallback = $parse(attrs.onSelect); $select.onRemoveCallback = $parse(attrs.onRemove); //Limit the number of selections allowed $select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined; //Set reference to ngModel from uiSelectCtrl $select.ngModel = ngModel; $select.choiceGrouped = function(group){ return $select.isGrouped && group && group.name; }; if(attrs.tabindex){ attrs.$observe('tabindex', function(value) { $select.focusInput.attr('tabindex', value); element.removeAttr('tabindex'); }); } scope.$watch('$select.items', function(){ }); scope.$watch('searchEnabled', function() { var searchEnabled = scope.$eval(attrs.searchEnabled); $select.searchEnabled = searchEnabled !== undefined ? searchEnabled : uiSelectConfig.searchEnabled; }); scope.$watch('sortable', function() { var sortable = scope.$eval(attrs.sortable); $select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable; }); attrs.$observe('disabled', function() { // No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string $select.disabled = attrs.disabled !== undefined ? attrs.disabled : false; }); attrs.$observe('resetSearchInput', function() { // $eval() is needed otherwise we get a string instead of a boolean var resetSearchInput = scope.$eval(attrs.resetSearchInput); $select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true; }); attrs.$observe('paste', function() { $select.paste = scope.$eval(attrs.paste); }); attrs.$observe('tagging', function() { if(attrs.tagging !== undefined) { // $eval() is needed otherwise we get a string instead of a boolean var taggingEval = scope.$eval(attrs.tagging); $select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined}; } else { $select.tagging = {isActivated: false, fct: undefined}; } }); attrs.$observe('taggingLabel', function() { if(attrs.tagging !== undefined ) { // check eval for FALSE, in this case, we disable the labels // associated with tagging if ( attrs.taggingLabel === 'false' ) { $select.taggingLabel = false; } else { $select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)'; } } }); attrs.$observe('taggingTokens', function() { if (attrs.tagging !== undefined) { var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER']; $select.taggingTokens = {isActivated: true, tokens: tokens }; } }); //Automatically gets focus when loaded if (angular.isDefined(attrs.autofocus)){ $timeout(function(){ $select.setFocus(); }); } //Gets focus based on scope event name (e.g. focus-on='SomeEventName') if (angular.isDefined(attrs.focusOn)){ scope.$on(attrs.focusOn, function() { $timeout(function(){ $select.setFocus(); }); }); } function onDocumentClick(e) { if (!$select.open) return; //Skip it if dropdown is close var contains = false; if (window.jQuery) { // Firefox 3.6 does not support element.contains() // See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains contains = window.jQuery.contains(element[0], e.target); } else { contains = element[0].contains(e.target); } if (!contains && !$select.clickTriggeredSelect) { var skipFocusser; if (!$select.skipFocusser) { //Will lose focus only with certain targets var focusableControls = ['input','button','textarea','select']; var targetController = angular.element(e.target).controller('uiSelect'); //To check if target is other ui-select skipFocusser = targetController && targetController !== $select; //To check if target is other ui-select if (!skipFocusser) skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea } else { skipFocusser = true; } $select.close(skipFocusser); scope.$digest(); } $select.clickTriggeredSelect = false; } // See Click everywhere but here event http://stackoverflow.com/questions/12931369 $document.on('click', onDocumentClick); scope.$on('$destroy', function() { $document.off('click', onDocumentClick); }); // Move transcluded elements to their correct position in main template transcludeFn(scope, function(clone) { // See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html // One day jqLite will be replaced by jQuery and we will be able to write: // var transcludedElement = clone.filter('.my-class') // instead of creating a hackish DOM element: var transcluded = angular.element('<div>').append(clone); var transcludedMatch = transcluded.querySelectorAll('.ui-select-match'); transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes if (transcludedMatch.length !== 1) { throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length); } element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch); var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices'); transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes if (transcludedChoices.length !== 1) { throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length); } element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices); var transcludedNoChoice = transcluded.querySelectorAll('.ui-select-no-choice'); transcludedNoChoice.removeAttr('ui-select-no-choice'); //To avoid loop in case directive as attr transcludedNoChoice.removeAttr('data-ui-select-no-choice'); // Properly handle HTML5 data-attributes if (transcludedNoChoice.length == 1) { element.querySelectorAll('.ui-select-no-choice').replaceWith(transcludedNoChoice); } }); // Support for appending the select field to the body when its open var appendToBody = scope.$eval(attrs.appendToBody); if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) { scope.$watch('$select.open', function(isOpen) { if (isOpen) { positionDropdown(); } else { resetDropdown(); } }); // Move the dropdown back to its original location when the scope is destroyed. Otherwise // it might stick around when the user routes away or the select field is otherwise removed scope.$on('$destroy', function() { resetDropdown(); }); } // Hold on to a reference to the .ui-select-container element for appendToBody support var placeholder = null, originalWidth = ''; function positionDropdown() { // Remember the absolute position of the element var offset = uisOffset(element); // Clone the element into a placeholder element to take its original place in the DOM placeholder = angular.element('<div class="ui-select-placeholder"></div>'); placeholder[0].style.width = offset.width + 'px'; placeholder[0].style.height = offset.height + 'px'; element.after(placeholder); // Remember the original value of the element width inline style, so it can be restored // when the dropdown is closed originalWidth = element[0].style.width; // Now move the actual dropdown element to the end of the body $document.find('body').append(element); element[0].style.position = 'absolute'; element[0].style.left = offset.left + 'px'; element[0].style.top = offset.top + 'px'; element[0].style.width = offset.width + 'px'; } function resetDropdown() { if (placeholder === null) { // The dropdown has not actually been display yet, so there's nothing to reset return; } // Move the dropdown element back to its original location in the DOM placeholder.replaceWith(element); placeholder = null; element[0].style.position = ''; element[0].style.left = ''; element[0].style.top = ''; element[0].style.width = originalWidth; // Set focus back on to the moved element $select.setFocus(); } // Hold on to a reference to the .ui-select-dropdown element for direction support. var dropdown = null, directionUpClassName = 'direction-up'; // Support changing the direction of the dropdown if there isn't enough space to render it. scope.$watch('$select.open', function() { if ($select.dropdownPosition === 'auto' || $select.dropdownPosition === 'up'){ scope.calculateDropdownPos(); } }); var setDropdownPosUp = function(offset, offsetDropdown){ offset = offset || uisOffset(element); offsetDropdown = offsetDropdown || uisOffset(dropdown); dropdown[0].style.position = 'absolute'; dropdown[0].style.top = (offsetDropdown.height * -1) + 'px'; element.addClass(directionUpClassName); }; var setDropdownPosDown = function(offset, offsetDropdown){ element.removeClass(directionUpClassName); offset = offset || uisOffset(element); offsetDropdown = offsetDropdown || uisOffset(dropdown); dropdown[0].style.position = ''; dropdown[0].style.top = ''; }; scope.calculateDropdownPos = function(){ if ($select.open) { dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown'); if (dropdown.length === 0) { return; } // Hide the dropdown so there is no flicker until $timeout is done executing. dropdown[0].style.opacity = 0; // Delay positioning the dropdown until all choices have been added so its height is correct. $timeout(function(){ if ($select.dropdownPosition === 'up'){ //Go UP setDropdownPosUp(); }else{ //AUTO element.removeClass(directionUpClassName); var offset = uisOffset(element); var offsetDropdown = uisOffset(dropdown); //https://code.google.com/p/chromium/issues/detail?id=342307#c4 var scrollTop = $document[0].documentElement.scrollTop || $document[0].body.scrollTop; //To make it cross browser (blink, webkit, IE, Firefox). // Determine if the direction of the dropdown needs to be changed. if (offset.top + offset.height + offsetDropdown.height > scrollTop + $document[0].documentElement.clientHeight) { //Go UP setDropdownPosUp(offset, offsetDropdown); }else{ //Go DOWN setDropdownPosDown(offset, offsetDropdown); } } // Display the dropdown once it has been positioned. dropdown[0].style.opacity = 1; }); } else { if (dropdown === null || dropdown.length === 0) { return; } // Reset the position of the dropdown. dropdown[0].style.position = ''; dropdown[0].style.top = ''; element.removeClass(directionUpClassName); } }; }; } }; }]);
90TechSAS/ui-select
src/uiSelectDirective.js
JavaScript
mit
15,230
package cz.muni.fi.pa165.languageschool.test; import java.util.Collection; import javax.persistence.EntityManager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * * @author Michal Fučík (395624) michal.fuca.fucik(at)gmail.com */ //@RunWith(SpringJUnit4ClassRunner.class) ////@ContextConfiguration(locations = { //// "classpath:testApplicationContext.xml"}) //@TransactionConfiguration(defaultRollback = true) //@Transactional public abstract class BaseTest { protected EntityManager em; public void assertCollectionEquals(Collection<Object> exp, Collection<Object> given) { assertEquals(exp.getClass(), given.getClass()); assertEquals(exp.size(), given.size()); for(Object l: exp) { if (!given.contains(l)) fail("Tested collection does not contain expected element. " + l); } } }
fuca/languageschool
language-school-bus-impl-module/src/test/java/cz/muni/fi/pa165/languageschool/test/BaseTest.java
Java
mit
1,161
require 'morpheus/api/api_client' class Morpheus::NetworkStaticRoutesInterface < Morpheus::RestInterface def base_path "/api/networks" end def get_static_route(network_id, route_id, params={}, headers={}) validate_id!(network_id) validate_id!(route_id) execute(method: :get, url: "#{base_path}/#{network_id}/routes/#{route_id}", params: params, headers: headers) end def list_static_routes(network_id, params={}, headers={}) validate_id!(network_id) execute(method: :get, url: "#{base_path}/#{network_id}/routes", params: params, headers: headers) end def create_static_route(network_id, payload, params={}, headers={}) validate_id!(network_id) execute(method: :post, url: "#{base_path}/#{network_id}/routes", params: params, payload: payload, headers: headers) end def update_static_route(network_id, route_id, payload, params={}, headers={}) validate_id!(network_id) validate_id!(route_id) execute(method: :put, url: "#{base_path}/#{network_id}/routes/#{route_id}", params: params, payload: payload, headers: headers) end def delete_static_route(network_id, route_id, params={}, headers={}) validate_id!(network_id) validate_id!(route_id) execute(method: :delete, url: "#{base_path}/#{network_id}/routes/#{route_id}", params: params, headers: headers) end end
gomorpheus/morpheus-cli
lib/morpheus/api/network_static_routes_interface.rb
Ruby
mit
1,349
import {singularize} from './noun'; export { singularize };
Yomguithereal/talisman
src/inflectors/spanish/index.js
JavaScript
mit
63
import time import json import redis import subprocess from subprocess import Popen, check_output import shlex import os from py_cf_new_py3.chain_flow_py3 import CF_Base_Interpreter from redis_graph_py3 import farm_template_py3 class Process_Control(object ): def __init__(self): pass def run_process_to_completion(self,command_string, shell_flag = False, timeout_value = None): try: command_parameters = shlex.split(command_string) return_value = check_output(command_parameters, stderr=subprocess.STDOUT , shell = shell_flag, timeout = timeout_value) return [0,return_value.decode()] except subprocess.CalledProcessError as cp: return [ cp.returncode , cp.output.decode() ] except : return [-1,""] def launch_process(self,command_string,stderr=None,shell=True): command_parameters = shlex.split(command_string) try: process_handle = Popen(command_parameters, stderr=open(self.error_file,'w' )) return [ True, process_handle ] except: return [False, None] def monitor_process(self, process_handle): returncode = process_handle.poll() if returncode == None: return [ True, 0] else: del process_handle return [ False, returncode ] def kill_process(self,process_handle): try: process_handle.kill() process_handle.wait() del process_handle except: pass class Manage_A_Python_Process(Process_Control): def __init__(self,command_string, restart_flag = True, error_directory = "/tmp"): super(Process_Control,self) self.restart_flag = restart_flag command_string = "python3 "+command_string self.command_string = command_string command_list= shlex.split(command_string) script_file_list = command_list[1].split("/") self.script_file_name = script_file_list[-1].split(".")[0] temp = error_directory + "/"+self.script_file_name self.error_file = temp+".err" self.error_file_rollover = temp +".errr" self.error = False self.enabled = True self.active = False def get_script(self): return self.script_file_name def launch(self): if( (self.enabled == True) and (self.active == False )): temp = self.launch_process(self.command_string, stderr=self.error_file) return_value = temp[0] self.handle = temp[1] self.active = return_value if self.active == False: self.rollover() self.error = True else: self.error = False def monitor(self): if self.enabled == True: if self.active == True: return_value = self.monitor_process(self.handle) if return_value[0] == True: return True self.active = False self.rollover() if self.restart_flag == True: self.launch() return False def rollover(self): os.system("mv "+self.error_file+" " +self.error_file_rollover) def kill(self): self.active = False self.error = False self.enabled = False self.kill_process(self.handle) self.rollover() class System_Control(object): def __init__(self, redis_handle, error_queue_key, web_command_queue_key, web_process_data_key, web_display_list_key, command_string_list ): self.redis_handle = redis_handle self.error_queue_key = error_queue_key self.web_command_queue_key = web_command_queue_key self.web_process_data_key = web_process_data_key self.web_display_list_key = web_display_list_key self.command_string_list = command_string_list self.startup_list = [] self.process_hash = {} self.process_state = {} for command_string in command_string_list: temp_class = Manage_A_Python_Process( command_string ) python_script = temp_class.get_script() self.startup_list.append(python_script) self.process_hash[python_script] = temp_class self.redis_handle.set(self.web_display_list_key,json.dumps(self.startup_list)) self.update_web_display() def launch_processes( self,*unused ): for script in self.startup_list: temp = self.process_hash[script] temp.launch() if temp.error == True: return_data = json.dumps({ "script": script, "error_file" : temp.temp.error_file_rollover}) self.redis_handle.publish(self.error_queue_key,return_data) temp.error = False def monitor( self, *unused ): for script in self.startup_list: temp = self.process_hash[script] temp.monitor() if temp.error == True: return_data = json.dumps({ "script": script, "error_file" : temp.temp.error_file_rollover}) self.redis_handle.publish(self.error_queue_key,return_data) temp.error = False self.update_web_display() def process_web_queue( self, *unused ): if self.redis_handle.llen(self.web_command_queue_key) > 0 : data_json = redis_handle.lpop(self.web_command_queue_key) self.redis_handle.ltrim(self.web_command_queue_key,0,-1) # empty redis queue data = json.loads(data_json) print("made it here") for script,item in data.items(): temp = self.process_hash[script] try: if item["enabled"] == True: if temp.enabled == False: temp.enabled = True temp.active = False #print(script,"---------------------------launch") temp.launch() else: if temp.enabled == True: temp.enabled = False #print(script,"----------------------------kill") temp.kill() except: pass print(self.process_hash[script].active) print(self.process_hash[script].enabled) self.update_web_display() def update_web_display(self): process_state = {} for script in self.startup_list: temp = self.process_hash[script] process_state[script] = {"name":script,"enabled":temp.enabled,"active":temp.active,"error":temp.error} self.redis_handle.set(self.web_process_data_key,json.dumps(process_state)) def add_chains(self,cf): cf.define_chain("initialization",True) cf.insert.one_step(self.launch_processes) cf.insert.enable_chains( ["monitor_web_command_queue","monitor_active_processes"] ) cf.insert.terminate() cf.define_chain("monitor_web_command_queue", False) cf.insert.wait_event_count( event = "TIME_TICK", count = 1) cf.insert.one_step(self.process_web_queue) cf.insert.reset() cf.define_chain("monitor_active_processes",False) cf.insert.wait_event_count( event = "TIME_TICK",count = 10) cf.insert.one_step(self.monitor) cf.insert.reset() if __name__ == "__main__": cf = CF_Base_Interpreter() gm = farm_template_py3.Graph_Management( "PI_1", "main_remote", "LaCima_DataStore") process_data = gm.match_terminal_relationship("PROCESS_CONTROL")[0] redis_data = process_data["redis"] redis_handle = redis.StrictRedis( host=redis_data["ip"], port=redis_data["port"], db=redis_data["db"], decode_responses=True) web_command_queue_key =process_data['web_command_key'] error_queue_key = process_data['error_queue_key'] command_string_list = process_data["command_string_list"] web_process_data_key = process_data["web_process_data"] web_display_list_key = process_data["web_display_list"] print(web_process_data_key,web_display_list_key) system_control = System_Control( redis_handle = redis_handle, error_queue_key = error_queue_key, web_command_queue_key = web_command_queue_key, web_process_data_key = web_process_data_key, web_display_list_key = web_display_list_key, command_string_list = command_string_list ) system_control.add_chains(cf) cf.execute()
glenn-edgar/local_controller_3
process_control_py3.py
Python
mit
9,357
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ISpliceable } from 'vs/base/common/sequence'; import { Iterator, ISequence } from 'vs/base/common/iterator'; import { Emitter, Event, EventBufferer } from 'vs/base/common/event'; import { tail2 } from 'vs/base/common/arrays'; import { ITreeFilterDataResult, TreeVisibility, ITreeFilter, ITreeModel, ITreeNode, ITreeElement } from 'vs/base/browser/ui/tree/tree'; interface IMutableTreeNode<T, TFilterData> extends ITreeNode<T, TFilterData> { readonly parent: IMutableTreeNode<T, TFilterData> | undefined; readonly children: IMutableTreeNode<T, TFilterData>[]; collapsible: boolean; collapsed: boolean; renderNodeCount: number; visible: boolean; filterData: TFilterData | undefined; } function isFilterResult<T>(obj: any): obj is ITreeFilterDataResult<T> { return typeof obj === 'object' && 'visibility' in obj && 'data' in obj; } function treeNodeToElement<T>(node: IMutableTreeNode<T, any>): ITreeElement<T> { const { element, collapsed } = node; const children = Iterator.map(Iterator.fromArray(node.children), treeNodeToElement); return { element, children, collapsed }; } function getVisibleState(visibility: boolean | TreeVisibility): TreeVisibility { switch (visibility) { case true: return TreeVisibility.Visible; case false: return TreeVisibility.Hidden; default: return visibility; } } export interface IIndexTreeModelOptions<T, TFilterData> { collapseByDefault?: boolean; // defaults to false filter?: ITreeFilter<T, TFilterData>; } export class IndexTreeModel<T extends Exclude<any, undefined>, TFilterData = void> implements ITreeModel<T, TFilterData, number[]> { private root: IMutableTreeNode<T, TFilterData>; private eventBufferer = new EventBufferer(); private _onDidChangeCollapseState = new Emitter<ITreeNode<T, TFilterData>>(); readonly onDidChangeCollapseState: Event<ITreeNode<T, TFilterData>> = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event); private _onDidChangeRenderNodeCount = new Emitter<ITreeNode<T, TFilterData>>(); readonly onDidChangeRenderNodeCount: Event<ITreeNode<T, TFilterData>> = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event); private collapseByDefault: boolean; private filter?: ITreeFilter<T, TFilterData>; constructor(private list: ISpliceable<ITreeNode<T, TFilterData>>, rootElement: T, options: IIndexTreeModelOptions<T, TFilterData> = {}) { this.collapseByDefault = typeof options.collapseByDefault === 'undefined' ? false : options.collapseByDefault; this.filter = options.filter; this.root = { parent: undefined, element: rootElement, children: [], depth: 0, collapsible: false, collapsed: false, renderNodeCount: 0, visible: true, filterData: undefined }; } splice( location: number[], deleteCount: number, toInsert?: ISequence<ITreeElement<T>>, onDidCreateNode?: (node: ITreeNode<T, TFilterData>) => void, onDidDeleteNode?: (node: ITreeNode<T, TFilterData>) => void ): Iterator<ITreeElement<T>> { if (location.length === 0) { throw new Error('Invalid tree location'); } const { parentNode, listIndex, revealed } = this.getParentNodeWithListIndex(location); const treeListElementsToInsert: ITreeNode<T, TFilterData>[] = []; const nodesToInsertIterator = Iterator.map(Iterator.from(toInsert), el => this.createTreeNode(el, parentNode, parentNode.visible ? TreeVisibility.Visible : TreeVisibility.Hidden, revealed, treeListElementsToInsert, onDidCreateNode)); const nodesToInsert: IMutableTreeNode<T, TFilterData>[] = []; let renderNodeCount = 0; Iterator.forEach(nodesToInsertIterator, node => { nodesToInsert.push(node); renderNodeCount += node.renderNodeCount; }); const lastIndex = location[location.length - 1]; const deletedNodes = parentNode.children.splice(lastIndex, deleteCount, ...nodesToInsert); if (revealed) { const visibleDeleteCount = deletedNodes.reduce((r, node) => r + node.renderNodeCount, 0); this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount); this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert); } if (deletedNodes.length > 0 && onDidDeleteNode) { const visit = (node: ITreeNode<T, TFilterData>) => { onDidDeleteNode(node); node.children.forEach(visit); }; deletedNodes.forEach(visit); } return Iterator.map(Iterator.fromArray(deletedNodes), treeNodeToElement); } getListIndex(location: number[]): number { return this.getTreeNodeWithListIndex(location).listIndex; } setCollapsed(location: number[], collapsed: boolean): boolean { const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location); return this.eventBufferer.bufferEvents(() => this._setCollapsed(node, listIndex, revealed, collapsed)); } toggleCollapsed(location: number[]): void { const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location); this.eventBufferer.bufferEvents(() => this._setCollapsed(node, listIndex, revealed)); } collapseAll(): void { const queue = [...this.root.children]; let listIndex = 0; this.eventBufferer.bufferEvents(() => { while (queue.length > 0) { const node = queue.shift()!; const revealed = listIndex < this.root.children.length; this._setCollapsed(node, listIndex, revealed, true); queue.push(...node.children); listIndex++; } }); } isCollapsed(location: number[]): boolean { return this.getTreeNode(location).collapsed; } refilter(): void { const previousRenderNodeCount = this.root.renderNodeCount; const toInsert = this.updateNodeAfterFilterChange(this.root); this.list.splice(0, previousRenderNodeCount, toInsert); } private _setCollapsed(node: IMutableTreeNode<T, TFilterData>, listIndex: number, revealed: boolean, collapsed?: boolean | undefined): boolean { if (!node.collapsible) { return false; } if (typeof collapsed === 'undefined') { collapsed = !node.collapsed; } if (node.collapsed === collapsed) { return false; } node.collapsed = collapsed; if (revealed) { const previousRenderNodeCount = node.renderNodeCount; const toInsert = this.updateNodeAfterCollapseChange(node); this.list.splice(listIndex + 1, previousRenderNodeCount - 1, toInsert.slice(1)); this._onDidChangeCollapseState.fire(node); } return true; } private createTreeNode( treeElement: ITreeElement<T>, parent: IMutableTreeNode<T, TFilterData>, parentVisibility: TreeVisibility, revealed: boolean, treeListElements: ITreeNode<T, TFilterData>[], onDidCreateNode?: (node: ITreeNode<T, TFilterData>) => void ): IMutableTreeNode<T, TFilterData> { const node: IMutableTreeNode<T, TFilterData> = { parent, element: treeElement.element, children: [], depth: parent.depth + 1, collapsible: typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : (typeof treeElement.collapsed !== 'undefined'), collapsed: typeof treeElement.collapsed === 'undefined' ? this.collapseByDefault : treeElement.collapsed, renderNodeCount: 1, visible: true, filterData: undefined }; const visibility = this._filterNode(node, parentVisibility); if (revealed) { treeListElements.push(node); } const childElements = Iterator.from(treeElement.children); const childRevealed = revealed && visibility !== TreeVisibility.Hidden && !node.collapsed; const childNodes = Iterator.map(childElements, el => this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode)); let hasVisibleDescendants = false; let renderNodeCount = 1; Iterator.forEach(childNodes, child => { node.children.push(child); hasVisibleDescendants = hasVisibleDescendants || child.visible; renderNodeCount += child.renderNodeCount; }); node.collapsible = node.collapsible || node.children.length > 0; node.visible = visibility === TreeVisibility.Recurse ? hasVisibleDescendants : (visibility === TreeVisibility.Visible); if (!node.visible) { node.renderNodeCount = 0; if (revealed) { treeListElements.pop(); } } else if (!node.collapsed) { node.renderNodeCount = renderNodeCount; } if (onDidCreateNode) { onDidCreateNode(node); } return node; } private updateNodeAfterCollapseChange(node: IMutableTreeNode<T, TFilterData>): ITreeNode<T, TFilterData>[] { const previousRenderNodeCount = node.renderNodeCount; const result: ITreeNode<T, TFilterData>[] = []; this._updateNodeAfterCollapseChange(node, result); this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount); return result; } private _updateNodeAfterCollapseChange(node: IMutableTreeNode<T, TFilterData>, result: ITreeNode<T, TFilterData>[]): number { if (node.visible === false) { return 0; } result.push(node); node.renderNodeCount = 1; if (!node.collapsed) { for (const child of node.children) { node.renderNodeCount += this._updateNodeAfterCollapseChange(child, result); } } this._onDidChangeRenderNodeCount.fire(node); return node.renderNodeCount; } private updateNodeAfterFilterChange(node: IMutableTreeNode<T, TFilterData>): ITreeNode<T, TFilterData>[] { const previousRenderNodeCount = node.renderNodeCount; const result: ITreeNode<T, TFilterData>[] = []; this._updateNodeAfterFilterChange(node, node.visible ? TreeVisibility.Visible : TreeVisibility.Hidden, result); this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount); return result; } private _updateNodeAfterFilterChange(node: IMutableTreeNode<T, TFilterData>, parentVisibility: TreeVisibility, result: ITreeNode<T, TFilterData>[], revealed = true): boolean { let visibility: TreeVisibility; if (node !== this.root) { visibility = this._filterNode(node, parentVisibility); if (visibility === TreeVisibility.Hidden) { node.visible = false; return false; } if (revealed) { result.push(node); } } const resultStartLength = result.length; node.renderNodeCount = node === this.root ? 0 : 1; let hasVisibleDescendants = false; if (!node.collapsed || visibility! !== TreeVisibility.Hidden) { for (const child of node.children) { hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility!, result, revealed && !node.collapsed) || hasVisibleDescendants; } } if (node !== this.root) { node.visible = visibility! === TreeVisibility.Recurse ? hasVisibleDescendants : (visibility! === TreeVisibility.Visible); } if (!node.visible) { node.renderNodeCount = 0; if (revealed) { result.pop(); } } else if (!node.collapsed) { node.renderNodeCount += result.length - resultStartLength; } this._onDidChangeRenderNodeCount.fire(node); return node.visible; } private _updateAncestorsRenderNodeCount(node: IMutableTreeNode<T, TFilterData> | undefined, diff: number): void { if (diff === 0) { return; } while (node) { node.renderNodeCount += diff; this._onDidChangeRenderNodeCount.fire(node); node = node.parent; } } private _filterNode(node: IMutableTreeNode<T, TFilterData>, parentVisibility: TreeVisibility): TreeVisibility { const result = this.filter ? this.filter.filter(node.element, parentVisibility) : TreeVisibility.Visible; if (typeof result === 'boolean') { node.filterData = undefined; return result ? TreeVisibility.Visible : TreeVisibility.Hidden; } else if (isFilterResult<TFilterData>(result)) { node.filterData = result.data; return getVisibleState(result.visibility); } else { node.filterData = undefined; return getVisibleState(result); } } // cheap private getTreeNode(location: number[], node: IMutableTreeNode<T, TFilterData> = this.root): IMutableTreeNode<T, TFilterData> { if (!location || location.length === 0) { return node; } const [index, ...rest] = location; if (index < 0 || index > node.children.length) { throw new Error('Invalid tree location'); } return this.getTreeNode(rest, node.children[index]); } // expensive private getTreeNodeWithListIndex(location: number[]): { node: IMutableTreeNode<T, TFilterData>, listIndex: number, revealed: boolean } { const { parentNode, listIndex, revealed } = this.getParentNodeWithListIndex(location); const index = location[location.length - 1]; if (index < 0 || index > parentNode.children.length) { throw new Error('Invalid tree location'); } const node = parentNode.children[index]; return { node, listIndex, revealed }; } private getParentNodeWithListIndex(location: number[], node: IMutableTreeNode<T, TFilterData> = this.root, listIndex: number = 0, revealed = true): { parentNode: IMutableTreeNode<T, TFilterData>; listIndex: number; revealed: boolean; } { const [index, ...rest] = location; if (index < 0 || index > node.children.length) { throw new Error('Invalid tree location'); } // TODO@joao perf! for (let i = 0; i < index; i++) { listIndex += node.children[i].renderNodeCount; } revealed = revealed && !node.collapsed; if (rest.length === 0) { return { parentNode: node, listIndex, revealed }; } return this.getParentNodeWithListIndex(rest, node.children[index], listIndex + 1, revealed); } getNode(location: number[] = []): ITreeNode<T, TFilterData> { return this.getTreeNode(location); } // TODO@joao perf! getNodeLocation(node: ITreeNode<T, TFilterData>): number[] { const location: number[] = []; while (node.parent) { location.push(node.parent.children.indexOf(node)); node = node.parent; } return location.reverse(); } getParentNodeLocation(location: number[]): number[] { if (location.length <= 1) { return []; } return tail2(location)[0]; } getParentElement(location: number[]): T { const parentLocation = this.getParentNodeLocation(location); const node = this.getTreeNode(parentLocation); return node.element; } getFirstElementChild(location: number[]): T | undefined { const node = this.getTreeNode(location); if (node.children.length === 0) { return undefined; } return node.children[0].element; } getLastElementAncestor(location: number[] = []): T | undefined { const node = this.getTreeNode(location); if (node.children.length === 0) { return undefined; } return this._getLastElementAncestor(node); } private _getLastElementAncestor(node: ITreeNode<T, TFilterData>): T { if (node.children.length === 0) { return node.element; } return this._getLastElementAncestor(node.children[node.children.length - 1]); } }
DustinCampbell/vscode
src/vs/base/browser/ui/tree/indexTreeModel.ts
TypeScript
mit
14,919
<?php declare(strict_types=1); /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\AdminBundle\Tests\Action; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Sonata\AdminBundle\Action\GetShortObjectDescriptionAction; use Sonata\AdminBundle\Action\SetObjectFieldValueAction; use Sonata\AdminBundle\Admin\AbstractAdmin; use Sonata\AdminBundle\Admin\FieldDescriptionInterface; use Sonata\AdminBundle\Admin\Pool; use Sonata\AdminBundle\Model\ModelManagerInterface; use Sonata\AdminBundle\Templating\TemplateRegistryInterface; use Sonata\AdminBundle\Twig\Extension\SonataAdminExtension; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\PropertyAccess\PropertyAccessor; use Symfony\Component\Validator\ConstraintViolation; use Symfony\Component\Validator\ConstraintViolationList; use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Contracts\Translation\TranslatorInterface; use Twig\Environment; use Twig\Loader\ArrayLoader; final class SetObjectFieldValueActionTest extends TestCase { /** * @var Pool */ private $pool; /** * @var Environment */ private $twig; /** * @var GetShortObjectDescriptionAction */ private $action; /** * @var AbstractAdmin */ private $admin; /** * @var ValidatorInterface */ private $validator; protected function setUp(): void { $this->twig = new Environment(new ArrayLoader([ 'admin_template' => 'renderedTemplate', 'field_template' => 'renderedTemplate', ])); $this->pool = $this->prophesize(Pool::class); $this->admin = $this->prophesize(AbstractAdmin::class); $this->pool->getInstance(Argument::any())->willReturn($this->admin->reveal()); $this->admin->setRequest(Argument::type(Request::class))->shouldBeCalled(); $this->validator = $this->prophesize(ValidatorInterface::class); $this->action = new SetObjectFieldValueAction( $this->twig, $this->pool->reveal(), $this->validator->reveal() ); } public function testSetObjectFieldValueAction(): void { $object = new Foo(); $request = new Request([ 'code' => 'sonata.post.admin', 'objectId' => 42, 'field' => 'enabled', 'value' => 1, 'context' => 'list', ], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']); $fieldDescription = $this->prophesize(FieldDescriptionInterface::class); $pool = $this->prophesize(Pool::class); $translator = $this->prophesize(TranslatorInterface::class); $propertyAccessor = new PropertyAccessor(); $templateRegistry = $this->prophesize(TemplateRegistryInterface::class); $container = $this->prophesize(ContainerInterface::class); $this->admin->getObject(42)->willReturn($object); $this->admin->getCode()->willReturn('sonata.post.admin'); $this->admin->hasAccess('edit', $object)->willReturn(true); $this->admin->getListFieldDescription('enabled')->willReturn($fieldDescription->reveal()); $this->admin->update($object)->shouldBeCalled(); $templateRegistry->getTemplate('base_list_field')->willReturn('admin_template'); $container->get('sonata.post.admin.template_registry')->willReturn($templateRegistry->reveal()); $this->pool->getPropertyAccessor()->willReturn($propertyAccessor); $this->twig->addExtension(new SonataAdminExtension( $pool->reveal(), $translator->reveal(), $container->reveal() )); $fieldDescription->getOption('editable')->willReturn(true); $fieldDescription->getAdmin()->willReturn($this->admin->reveal()); $fieldDescription->getType()->willReturn('boolean'); $fieldDescription->getTemplate()->willReturn('field_template'); $fieldDescription->getValue(Argument::cetera())->willReturn('some value'); $this->validator->validate($object)->willReturn(new ConstraintViolationList([])); $response = ($this->action)($request); $this->assertSame(Response::HTTP_OK, $response->getStatusCode()); } public function getTimeZones(): iterable { $default = new \DateTimeZone(date_default_timezone_get()); $custom = new \DateTimeZone('Europe/Rome'); return [ 'empty timezone' => [null, $default], 'disabled timezone' => [false, $default], 'default timezone by name' => [$default->getName(), $default], 'default timezone by object' => [$default, $default], 'custom timezone by name' => [$custom->getName(), $custom], 'custom timezone by object' => [$custom, $custom], ]; } /** * @dataProvider getTimeZones */ public function testSetObjectFieldValueActionWithDate($timezone, \DateTimeZone $expectedTimezone): void { $object = new Bafoo(); $request = new Request([ 'code' => 'sonata.post.admin', 'objectId' => 42, 'field' => 'dateProp', 'value' => '2020-12-12', 'context' => 'list', ], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']); $fieldDescription = $this->prophesize(FieldDescriptionInterface::class); $pool = $this->prophesize(Pool::class); $translator = $this->prophesize(TranslatorInterface::class); $propertyAccessor = new PropertyAccessor(); $templateRegistry = $this->prophesize(TemplateRegistryInterface::class); $container = $this->prophesize(ContainerInterface::class); $this->admin->getObject(42)->willReturn($object); $this->admin->getCode()->willReturn('sonata.post.admin'); $this->admin->hasAccess('edit', $object)->willReturn(true); $this->admin->getListFieldDescription('dateProp')->willReturn($fieldDescription->reveal()); $this->admin->update($object)->shouldBeCalled(); $templateRegistry->getTemplate('base_list_field')->willReturn('admin_template'); $container->get('sonata.post.admin.template_registry')->willReturn($templateRegistry->reveal()); $this->pool->getPropertyAccessor()->willReturn($propertyAccessor); $this->twig->addExtension(new SonataAdminExtension( $pool->reveal(), $translator->reveal(), $container->reveal() )); $fieldDescription->getOption('editable')->willReturn(true); $fieldDescription->getOption('timezone')->willReturn($timezone); $fieldDescription->getAdmin()->willReturn($this->admin->reveal()); $fieldDescription->getType()->willReturn('date'); $fieldDescription->getTemplate()->willReturn('field_template'); $fieldDescription->getValue(Argument::cetera())->willReturn('some value'); $this->validator->validate($object)->willReturn(new ConstraintViolationList([])); $response = ($this->action)($request); $this->assertSame(Response::HTTP_OK, $response->getStatusCode()); $defaultTimezone = new \DateTimeZone(date_default_timezone_get()); $expectedDate = new \DateTime($request->query->get('value'), $expectedTimezone); $expectedDate->setTimezone($defaultTimezone); $this->assertInstanceOf(\DateTime::class, $object->getDateProp()); $this->assertSame($expectedDate->format('Y-m-d'), $object->getDateProp()->format('Y-m-d')); $this->assertSame($defaultTimezone->getName(), $object->getDateProp()->getTimezone()->getName()); } public function testSetObjectFieldValueActionOnARelationField(): void { $object = new Baz(); $associationObject = new Bar(); $request = new Request([ 'code' => 'sonata.post.admin', 'objectId' => 42, 'field' => 'bar', 'value' => 1, 'context' => 'list', ], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']); $fieldDescription = $this->prophesize(FieldDescriptionInterface::class); $modelManager = $this->prophesize(ModelManagerInterface::class); $translator = $this->prophesize(TranslatorInterface::class); $propertyAccessor = new PropertyAccessor(); $templateRegistry = $this->prophesize(TemplateRegistryInterface::class); $container = $this->prophesize(ContainerInterface::class); $this->admin->getObject(42)->willReturn($object); $this->admin->getCode()->willReturn('sonata.post.admin'); $this->admin->hasAccess('edit', $object)->willReturn(true); $this->admin->getListFieldDescription('bar')->willReturn($fieldDescription->reveal()); $this->admin->getClass()->willReturn(\get_class($object)); $this->admin->update($object)->shouldBeCalled(); $container->get('sonata.post.admin.template_registry')->willReturn($templateRegistry->reveal()); $templateRegistry->getTemplate('base_list_field')->willReturn('admin_template'); $this->admin->getModelManager()->willReturn($modelManager->reveal()); $this->twig->addExtension(new SonataAdminExtension( $this->pool->reveal(), $translator->reveal(), $container->reveal() )); $this->pool->getPropertyAccessor()->willReturn($propertyAccessor); $fieldDescription->getType()->willReturn('choice'); $fieldDescription->getOption('editable')->willReturn(true); $fieldDescription->getOption('class')->willReturn(Bar::class); $fieldDescription->getTargetModel()->willReturn(Bar::class); $fieldDescription->getAdmin()->willReturn($this->admin->reveal()); $fieldDescription->getTemplate()->willReturn('field_template'); $fieldDescription->getValue(Argument::cetera())->willReturn('some value'); $modelManager->find(\get_class($associationObject), 1)->willReturn($associationObject); $this->validator->validate($object)->willReturn(new ConstraintViolationList([])); $response = ($this->action)($request); $this->assertSame(Response::HTTP_OK, $response->getStatusCode()); } public function testSetObjectFieldValueActionWithViolations(): void { $bar = new Bar(); $object = new Baz(); $object->setBar($bar); $request = new Request([ 'code' => 'sonata.post.admin', 'objectId' => 42, 'field' => 'bar.enabled', 'value' => 1, 'context' => 'list', ], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']); $fieldDescription = $this->prophesize(FieldDescriptionInterface::class); $propertyAccessor = new PropertyAccessor(); $this->pool->getPropertyAccessor()->willReturn($propertyAccessor); $this->admin->getObject(42)->willReturn($object); $this->admin->hasAccess('edit', $object)->willReturn(true); $this->admin->getListFieldDescription('bar.enabled')->willReturn($fieldDescription->reveal()); $this->validator->validate($bar)->willReturn(new ConstraintViolationList([ new ConstraintViolation('error1', null, [], null, 'enabled', null), new ConstraintViolation('error2', null, [], null, 'enabled', null), ])); $fieldDescription->getOption('editable')->willReturn(true); $fieldDescription->getType()->willReturn('boolean'); $response = ($this->action)($request); $this->assertSame(Response::HTTP_BAD_REQUEST, $response->getStatusCode()); $this->assertSame(json_encode("error1\nerror2"), $response->getContent()); } public function testSetObjectFieldEditableMultipleValue(): void { $object = new StatusMultiple(); $request = new Request([ 'code' => 'sonata.post.admin', 'objectId' => 42, 'field' => 'status', 'value' => [1, 2], 'context' => 'list', ], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']); $fieldDescription = $this->prophesize(FieldDescriptionInterface::class); $pool = $this->prophesize(Pool::class); $template = $this->prophesize(Template::class); $translator = $this->prophesize(TranslatorInterface::class); $propertyAccessor = new PropertyAccessor(); $templateRegistry = $this->prophesize(TemplateRegistryInterface::class); $container = $this->prophesize(ContainerInterface::class); $this->admin->getObject(42)->willReturn($object); $this->admin->getCode()->willReturn('sonata.post.admin'); $this->admin->hasAccess('edit', $object)->willReturn(true); $this->admin->getListFieldDescription('status')->willReturn($fieldDescription->reveal()); $this->admin->update($object)->shouldBeCalled(); $templateRegistry->getTemplate('base_list_field')->willReturn('admin_template'); $container->get('sonata.post.admin.template_registry')->willReturn($templateRegistry->reveal()); $this->pool->getPropertyAccessor()->willReturn($propertyAccessor); $this->twig->addExtension(new SonataAdminExtension( $pool->reveal(), $translator->reveal(), $container->reveal() )); $fieldDescription->getOption('editable')->willReturn(true); $fieldDescription->getOption('multiple')->willReturn(true); $fieldDescription->getAdmin()->willReturn($this->admin->reveal()); $fieldDescription->getType()->willReturn('boolean'); $fieldDescription->getTemplate()->willReturn('field_template'); $fieldDescription->getValue(Argument::cetera())->willReturn(['some value']); $this->validator->validate($object)->willReturn(new ConstraintViolationList([])); $response = ($this->action)($request); $this->assertSame(Response::HTTP_OK, $response->getStatusCode()); } }
jordisala1991/SonataAdminBundle
tests/Action/SetObjectFieldValueActionTest.php
PHP
mit
14,552
module.exports={ "file":1, // fname, mode, contents "filedelete":2, // fname "checkout":3, // fname "checkin":4, // fname "ping":5, // - "pong":6, // - "edit":{ "open":100, // fname "close":101, // fname "open_ok":102, // fname "open_err":103, // fname "close_ok":104, // fname "close_err":105 // fname } };
tomsmeding/gvajnez
msgtype.js
JavaScript
mit
329
package com.mines.main; import com.mines.domain.enums.BoardSize; import com.mines.domain.enums.Difficulty; public class MineField{ private int[][] field; private BoardSize size; private Difficulty diff; private int nrMines = 0; public MineField(){ diff = Difficulty.EASY; size = BoardSize.MEDIUM; neww(); } public MineField(Difficulty d, BoardSize s){ diff = d; size = s; neww(); } public void neww(String...args){ if (args.length == 2){ size = BoardSize.valueOf(args[0].toUpperCase()); diff = Difficulty.valueOf(args[1].toUpperCase()); } nrMines = 0; generateMines(); setSafeSpots(); } public int[][] getField(){ return field; } public int getSize(){ return size.getSize(); } public int getNrMines(){ return nrMines; } /** PRIVATE **/ private void generateMines(){ int sizeInt = size.getSize(); field = new int[sizeInt][sizeInt]; for(int i=0; i < sizeInt; i++){ for(int j=0; j < sizeInt; j++){ field[i][j] = randBoolByDifficulty() ? -1 : 0; } } } private void setSafeSpots(){ int sizeInt = size.getSize(); for(int i=0; i < sizeInt; i++){ for(int j=0; j < sizeInt; j++){ if(field[i][j] != -1) field[i][j] = getNeighbors(i,j); } } } private boolean randBoolByDifficulty(){ if ((Math.random() * (size.getSize() * diff.getDiff())) < size.getSize()){ nrMines++; return true; } else return false; } private int getNeighbors(int i, int j){ int val = 0; for (int k = i-1; k <= i+1; k++){ for (int l = j-1; l <= j+1; l++){ try{ if(field[k][l] == -1) val++; }catch(ArrayIndexOutOfBoundsException e){} } } return val; } }
tonycatapano/JMinesField
src/main/java/com/mines/main/MineField.java
Java
mit
1,804
// Decompiled with JetBrains decompiler // Type: System.Fabric.Management.ServiceModel.ApplicationPoliciesType // Assembly: System.Fabric.Management.ServiceModel, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // MVID: C6D32D4D-966E-4EA3-BD3A-F4CF14D36DBC // Assembly location: C:\Git\ServiceFabricSdkContrib\ServiceFabricSdkContrib.MsBuild\bin\Debug\netstandard2.0\publish\runtimes\win\lib\netstandard2.0\System.Fabric.Management.ServiceModel.dll using System.CodeDom.Compiler; using System.Diagnostics; using System.Xml.Serialization; namespace System.Fabric.Management.ServiceModel { [GeneratedCode("xsd", "4.0.30319.17929")] [DebuggerStepThrough] [XmlType(Namespace = "http://schemas.microsoft.com/2011/01/fabric")] public class ApplicationPoliciesType { private ApplicationPoliciesTypeLogCollectionPolicies logCollectionPoliciesField; private ApplicationPoliciesTypeDefaultRunAsPolicy defaultRunAsPolicyField; private ApplicationHealthPolicyType healthPolicyField; private ApplicationPoliciesTypeSecurityAccessPolicies securityAccessPoliciesField; public ApplicationPoliciesTypeLogCollectionPolicies LogCollectionPolicies { get { return this.logCollectionPoliciesField; } set { this.logCollectionPoliciesField = value; } } public ApplicationPoliciesTypeDefaultRunAsPolicy DefaultRunAsPolicy { get { return this.defaultRunAsPolicyField; } set { this.defaultRunAsPolicyField = value; } } public ApplicationHealthPolicyType HealthPolicy { get { return this.healthPolicyField; } set { this.healthPolicyField = value; } } public ApplicationPoliciesTypeSecurityAccessPolicies SecurityAccessPolicies { get { return this.securityAccessPoliciesField; } set { this.securityAccessPoliciesField = value; } } } }
aL3891/ServiceFabricSdkContrib
System.Fabric.Management.ServiceModel/ApplicationPoliciesType.cs
C#
mit
2,017
# Django settings for obi project. from os.path import abspath, dirname DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'ENGINE': 'django.db.backends.', # Or path to database file if using sqlite3. 'NAME': '', # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', # Empty for localhost through domain sockets or '127.0.0.1' # for localhost through TCP. 'HOST': '', # Set to empty string for default. 'PORT': '', } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/New_York' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = dirname(dirname(abspath(__file__))) + '/static' # URL prefix for static files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '6(5f^qra2a%%(iok=0ktz)xnhx(-f7df3q(tuva4*0dz3c^ug4' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", ) ROOT_URLCONF = 'obi.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'obi.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or # "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.humanize', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'south', 'ui', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. 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, }, } } # Be sure to create your own 'local_settings.py' file as described in README try: from local_settings import * except ImportError: pass
adityadharne/TestObento
obi/obi/settings.py
Python
mit
6,014
require 'cocaine' require 'English' require 'time' require_relative 'result' require_relative 'error' class LittleneckClamAV class Clam def engine version[:engine] if available? end def database_version version[:database_version].to_i if available? end def database_date Time.parse(version[:database_date]) if available? end def available? version[:success] end def scan(path) check_scan! path opts = { swallow_stderr: true, expected_outcodes: [0, 1] } params = ['--no-summary', %("#{path}")].join(' ') output = Cocaine::CommandLine.new(command, params, opts).run parse_result path, output, $CHILD_STATUS.exitstatus end def command 'clamscan' end private def version @version ||= begin opts = { swallow_stderr: true } params = '--version' output = Cocaine::CommandLine.new(command, params, opts).run.strip parse_output(output) rescue Cocaine::ExitStatusError, Cocaine::CommandNotFoundError => e { error: e.message, success: false } end end def parse_output(output) engine, db_version, db_date = output.sub(/^ClamAV /, '').split('/', 3) success = !(db_version && db_date).nil? { output: output, engine: engine, database_version: db_version, database_date: db_date, success: success } end def parse_result(path, output, _code) clean = $CHILD_STATUS.exitstatus == 0 description = output.split(':').last.strip description.sub! ' FOUND', '' Result.new path: path, clean: clean, description: description end def check_scan!(path) exists = File.exist? path if !exists fail Error, "the path #{path} does not exist" elsif !available? message = "#{self.class} is not available" message << "because #{version[:message]}" if version[:message] fail Error, message end end end end
theozaurus/littleneck_clamav
lib/littleneck_clamav/clam.rb
Ruby
mit
2,029
using System; using System.Threading.Tasks; using work.bacome.async; using work.bacome.imapclient.support; using work.bacome.trace; namespace work.bacome.imapclient { public partial class cIMAPClient { internal cMessageHandleList SetUnseenCount(iMailboxHandle pMailboxHandle) { var lContext = mRootContext.NewMethod(nameof(cIMAPClient), nameof(Messages)); var lTask = ZSetUnseenCountAsync(pMailboxHandle, lContext); mSynchroniser.Wait(lTask, lContext); return lTask.Result; } internal Task<cMessageHandleList> SetUnseenCountAsync(iMailboxHandle pMailboxHandle) { var lContext = mRootContext.NewMethod(nameof(cIMAPClient), nameof(MessagesAsync)); return ZSetUnseenCountAsync(pMailboxHandle, lContext); } private async Task<cMessageHandleList> ZSetUnseenCountAsync(iMailboxHandle pMailboxHandle, cTrace.cContext pParentContext) { var lContext = pParentContext.NewMethod(nameof(cIMAPClient), nameof(ZMessagesAsync), pMailboxHandle); if (mDisposed) throw new ObjectDisposedException(nameof(cIMAPClient)); var lSession = mSession; if (lSession == null || lSession.ConnectionState != eConnectionState.selected) throw new InvalidOperationException(kInvalidOperationExceptionMessage.NotSelected); if (pMailboxHandle == null) throw new ArgumentNullException(nameof(pMailboxHandle)); var lCapabilities = lSession.Capabilities; using (var lToken = mCancellationManager.GetToken(lContext)) { var lMC = new cMethodControl(mTimeout, lToken.CancellationToken); if (lCapabilities.ESearch) return await lSession.SetUnseenCountExtendedAsync(lMC, pMailboxHandle, lContext).ConfigureAwait(false); else return await lSession.SetUnseenCountAsync(lMC, pMailboxHandle, lContext).ConfigureAwait(false); } } } }
bacome/imapclient
imapclient/imapclient/client/setunseencount.cs
C#
mit
2,008
import assert from "assert"; import BufSamples from "../../../src/scapi/units/BufSamples"; describe("scapi/units/BufSamples", () => { it(".kr should create control rate node", () => { const node = BufSamples.kr(1); assert.deepEqual(node, { type: "BufSamples", rate: "control", props: [ 1 ] }); }); it(".ir should create scalar rate node", () => { const node = BufSamples.ir(1); assert.deepEqual(node, { type: "BufSamples", rate: "scalar", props: [ 1 ] }); }); it("default rate is control", () => { const node = BufSamples(); assert.deepEqual(node, { type: "BufSamples", rate: "control", props: [ 0 ] }); }); });
mohayonao/neume
test/scapi/units/BufSamples.js
JavaScript
mit
684
<?php namespace AerialShip\SteelMqBundle\Entity; use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\User\UserInterface; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; /** * @ORM\Entity(repositoryClass="AerialShip\SteelMqBundle\Entity\Repository\UserRepository") * @ORM\Table(name="smq_user") */ class User implements UserInterface, \Serializable { const ROLE_USER = 'ROLE_USER'; const ROLE_ADMIN = 'ROLE_ADMIN'; const ROLE_SUPER_ADMIN = 'ROLE_SUPER_ADMIN'; const ROLE_DEFAULT = self::ROLE_USER; private static $allRoles = array( self::ROLE_USER => 1, self::ROLE_ADMIN => 1, self::ROLE_SUPER_ADMIN => 1, ); /** * @param string $role * * @return bool */ public static function isValidRole($role) { return isset(self::$allRoles[$role]); } /** * @var int * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ protected $id; /** * @var string * @ORM\Column(type="string", length=100, unique=true) */ protected $email; /** * @var string * @ORM\Column(type="string", length=100) */ protected $name; /** * @var \DateTime * @ORM\Column(type="datetime") */ protected $createdAt; /** * @var \DateTime|null * @ORM\Column(type="datetime", nullable=true) */ protected $lastLogin; /** * @var string|null */ protected $plainPassword; /** * @var string * @ORM\Column(type="text") */ protected $salt; /** * @var string * @ORM\Column(type="text") */ protected $password; /** * @var array * @ORM\Column(type="array") */ protected $roles = array(); /** * @var string * @ORM\Column(type="string", length=64) */ protected $accessToken; /** * @var string|null * @ORM\Column(type="string", length=64, nullable=true) */ protected $passwordToken; /** * @var \DateTime|null * @ORM\Column(type="datetime", nullable=true) */ protected $passwordRequestAt; /** * @var string * @ORM\Column(type="string", length=16) */ protected $locale = 'en'; /** * @var string * @ORM\Column(type="string", length=32) */ protected $timezone = 'Europe/Oslo'; /** * @var string * @ORM\Column(type="string", length=200, nullable=true) */ protected $pictureUrl; /** * @var ProjectRole[]|ArrayCollection * @ORM\OneToMany( * targetEntity="ProjectRole", * mappedBy="user", * orphanRemoval=true, * cascade={"remove"}, * fetch="EXTRA_LAZY" * ) */ protected $projectRoles; /** * */ public function __construct() { $this->createdAt = new \DateTime(); $this->projectRoles = new ArrayCollection(); $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36); } /** * @return int */ public function getId() { return $this->id; } /** * @return string */ public function getLocale() { return $this->locale; } /** * @param string $locale * @return $this|User */ public function setLocale($locale) { $this->locale = $locale; return $this; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name * @return $this|User */ public function setName($name) { $this->name = $name; return $this; } /** * @return string */ public function getEmail() { return $this->email; } /** * @param string $email * @return $this|User */ public function setEmail($email) { $this->email = $email; return $this; } /** * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * @param \DateTime $createdAt * @return $this|User */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * @return \DateTime|null */ public function getLastLogin() { return $this->lastLogin; } /** * @param \DateTime|null $lastLogin * @return $this|User */ public function setLastLogin($lastLogin) { $this->lastLogin = $lastLogin; return $this; } /** * @return null|string */ public function getPlainPassword() { return $this->plainPassword; } /** * @param null|string $plainPassword * @return $this|User */ public function setPlainPassword($plainPassword) { $this->plainPassword = $plainPassword; return $this; } /** * @return string */ public function getTimezone() { return $this->timezone; } /** * @param string $timezone * @return $this|User */ public function setTimezone($timezone) { $this->timezone = $timezone; return $this; } /** * @return string */ public function getPictureUrl() { return $this->pictureUrl; } /** * @param string $pictureUrl * @return $this|User */ public function setPictureUrl($pictureUrl) { $this->pictureUrl = $pictureUrl; return $this; } /** * @return null|string */ public function getAccessToken() { return $this->accessToken; } /** * @param string $accessToken * @return $this|User */ public function setAccessToken($accessToken) { $this->accessToken = $accessToken; return $this; } /** * @return \DateTime|null */ public function getPasswordRequestAt() { return $this->passwordRequestAt; } /** * @param \DateTime|null $passwordRequestAt * @return $this|User */ public function setPasswordRequestAt(\DateTime $passwordRequestAt = null) { $this->passwordRequestAt = $passwordRequestAt; return $this; } /** * @return null|string */ public function getPasswordToken() { return $this->passwordToken; } /** * @param null|string $passwordToken * @return $this|User */ public function setPasswordToken($passwordToken) { $this->passwordToken = $passwordToken; return $this; } /** * @return ProjectRole[]|ArrayCollection */ public function getProjectRoles() { return $this->projectRoles; } /** * @param string $role * @return User|$this */ public function addRole($role) { $role = strtoupper($role); if ($role === self::ROLE_DEFAULT) { return $this; } if (false == in_array($role, $this->roles, true)) { $this->roles[] = $role; } return $this; } /** * @param string $role * @return User|$this */ public function removeRole($role) { if (false !== $key = array_search(strtoupper($role), $this->roles, true)) { unset($this->roles[$key]); $this->roles = array_values($this->roles); } return $this; } /** * @param array $roles * @return $this|User */ public function setRoles(array $roles) { $this->roles = $roles; return $this; } /** * @param string $password * @return $this|User */ public function setPassword($password) { $this->password = $password; return $this; } /** * @param string $salt * @return $this|User */ public function setSalt($salt) { $this->salt = $salt; return $this; } // UserInterface ------------------------------------------------------------ /** * Returns the roles granted to the user. * * <code> * public function getRoles() * { * return array('ROLE_USER'); * } * </code> * * Alternatively, the roles might be stored on a ``roles`` property, * and populated in any number of different ways when the user object * is created. * * @return Role[] The user roles */ public function getRoles() { $roles = $this->roles; // we need to make sure to have at least one role $roles[] = self::ROLE_DEFAULT; return array_unique($roles); } /** * Returns the password used to authenticate the user. * * This should be the encoded password. On authentication, a plain-text * password will be salted, encoded, and then compared to this value. * * @return string The password */ public function getPassword() { return $this->password; } /** * Returns the salt that was originally used to encode the password. * * This can return null if the password was not encoded using a salt. * * @return string|null The salt */ public function getSalt() { return $this->salt; } /** * Returns the username used to authenticate the user. * * @return string The username */ public function getUsername() { return $this->email; } /** * Removes sensitive data from the user. * * This is important if, at any given point, sensitive information like * the plain-text password is stored on this object. */ public function eraseCredentials() { $this->plainPassword = null; } // Serializable ---------------------------------------------------------------------- /** * (PHP 5 &gt;= 5.1.0)<br/> * String representation of object * @link http://php.net/manual/en/serializable.serialize.php * @return string the string representation of the object or null */ public function serialize() { return serialize(array( $this->id, $this->email, $this->name, $this->locale, $this->timezone, $this->pictureUrl, $this->roles, )); } /** * (PHP 5 &gt;= 5.1.0)<br/> * Constructs the object * @link http://php.net/manual/en/serializable.unserialize.php * @param string $serialized <p> * The string representation of the object. * </p> * @return void */ public function unserialize($serialized) { $data = unserialize($serialized); // add a few extra elements in the array to ensure that we have enough keys when unserializing // older data which does not include all properties. $data = array_merge($data, array_fill(0, 2, null)); list( $this->id, $this->email, $this->name, $this->locale, $this->timezone, $this->pictureUrl, $this->roles ) = $data; } }
aerialship/steel-mq
src/AerialShip/SteelMqBundle/Entity/User.php
PHP
mit
11,457
<?php namespace GuildWars2\Api\Entity; use GuildWars2\Api\SetEntityBase; abstract class ItemInfoBase extends SetEntityBase { private $_itemId; private $_amount; private $_skinId; private $_upgradeIds; private $_infusionIds; private $_bindType; private $_boundCharacterName; protected function init() { $this->_itemId = null; $this->_amount = null; $this->_skinId = null; $this->_upgradeIds = []; $this->_infusionIds = []; $this->_bindType = null; $this->_boundCharacterName = null; } /** * @return mixed */ public function getItemId() { return $this->_itemId; } /** * @return Item */ public function getItem() { return $this->getApi()->items->getOne($this->_itemId); } /** * @return mixed */ public function getAmount() { return $this->_amount; } /** * @return mixed */ public function getSkinId() { return $this->_skinId; } /** * @return mixed */ public function getUpgradeIds() { return $this->_upgradeIds; } /** * @return mixed */ public function getInfusionIds() { return $this->_infusionIds; } /** * @return mixed */ public function getBindType() { return $this->_bindType; } /** * @return mixed */ public function getBoundCharacterName() { return $this->_boundCharacterName; } protected function set($key, $value) { switch ($key) { case 'id': $this->_itemId = intval($value); break; case 'count': $this->_amount = $value; break; case 'skin': $this->_skinId = $value; break; case 'upgrades': $this->_upgradeIds = array_map('intval', $value); break; case 'infusions': $this->_infusionIds = array_map('intval', $value); break; case 'binding': $this->_bindType = $value; break; case 'bound_to': $this->_boundCharacterName = $value; break; } } }
TorbenKoehn/gw2-php
Api/Entity/ItemInfoBase.php
PHP
mit
2,373
#pragma once /* LightedMaterial.hpp * * Copyright (C) 2017 Dynamic Reflectance * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ //std #include <string> #include <vector> namespace core { namespace utils { std::vector<std::string> tokenize(const std::string& a_data, const std::vector<char>& a_white_spaces, const std::vector<char>& a_separators); } // namespace utils } // namespace core
dynamicreflectance/core
utils/source/Tokenizer.hpp
C++
mit
558
import { combineReducers } from 'redux'; import { routerReducer as routing } from 'react-router-redux'; import account from '../reducers/account'; import authentication from '../reducers/authentication'; import user from '../reducers/user'; import modelPortfolio from '../reducers/modelPortfolio'; import portfolio from '../reducers/portfolio'; import investmentAmount from '../reducers/investmentAmount'; import message from '../reducers/message'; import rebalancing from '../reducers/rebalancing'; import view from '../reducers/view'; import * as types from '../types'; const isFetching = (state = false, action) => { switch (action.type) { case types.CREATE_REQUEST: return true; case types.REQUEST_SUCCESS: case types.REQUEST_FAILURE: return false; default: return state; } }; const rootReducer = combineReducers({ isFetching, authentication, account, modelPortfolio, portfolio, user, investmentAmount, message, rebalancing, view, routing, }); export default rootReducer;
AlexisDeschamps/portfolio-rebalancer
app/reducers/index.js
JavaScript
mit
1,039
var mongo = require('mongodb'); var fs = require('fs'); var path = require("path"); var Server = mongo.Server, Db = mongo.Db, BSON = mongo.BSONPure; var server = new Server('localhost', 27017, {auto_reconnect: true}); db = new Db('vivudb', server); function getExtPart(str){ var n=str.split("."); return n[n.length - 1]; } function getNamePart(str){ var n=str.split("."); return n[0]; } function removeSubstring(str,strrm){ var newstr = str.replace(strrm,""); return newstr; } exports.uploadAudio = function(req, res){ var addInbox = function(inbox) { console.log("Starting add Inbox: "); console.log(inbox); console.log(inbox.UserID); var gcm = new GLOBAL.GCMessage; var saveInbox = function( ){ db.collection('inboxs', function(err, collection) { collection.insert(inbox, {safe:true}, function(err, result) { if (err) { res.send({'error':'An error has occurred'}); } else{ console.log('Success: ' + JSON.stringify(result[0])); res.send(result[0]); } }); }); // end Inbox collection } var findDeviceByUserIdAndSend = function (id) { console.log("findDeviceByUserIdAndSend"); console.log('Retrieving all devices by user id: ' + id); // get all device by userId db.collection('devices', function(err, collection) { collection.find({'UserID':id.toString()}).toArray(function(err, items) { var ltsDevicesIds = []; for(var i = 0;i <items.length;i++){ ltsDevicesIds.push(items[i].DeviceID); } gcm.addRegIdList(ltsDevicesIds); gcm.addMessageData("inbox",inbox); gcm.send( ); saveInbox( ); }); // end device collection }); } // step 2.1 var increaseNoInbox = function (noCfs) { // increase Inbox Id console.log("increaseNoInbox"); inbox.InboxID = ++noCfs; findDeviceByUserIdAndSend(inbox.UserID); } // step 2.2 var userUnknown = function( ) { console.log("userUnknown"); res.send({'unknown':'There are no user in this system'}); } // step 1 var getNoCfsByUserId = function(userid){ try{ console.log("getNoCfsByUserId: "+ userid); db.collection('users', function(err, users) { users.findOne({'UserID':userid}, function(err, item) { if(item != null){ item.noCfs++; users.save(item); increaseNoInbox(item.noCfs); } else{ userUnknown(); } }); }); } catch(e){ console.log("Error at getNoCfsByUserId"); } } getNoCfsByUserId(inbox.UserID); }// end add inbox function var inbox = JSON.parse(req.body.json); console.log("json: "); console.log(inbox); //update Inbox var updateInbox = function(seqNo){ try{ var link = GLOBAL.HOSTNAME + "/cfs/audio/"+seqNo; inbox.ContentVoice = link; addInbox(inbox); } catch(e){ console.log("error in updateInbox in uploadAudio "); res.send({error:"Error from server"}); } } var saveAudio = function(seqNo){ console.log('Adding New Audio'); staticDir = removeSubstring(GLOBAL.__dirname,"/vivuserver/trunk"); //var audioDir = GLOBAL.__dirname + "/public/audio/"; var audioDir = staticDir + "/staticserver/public/audio/"; console.log("audio Dir: "+audioDir); //var fileName = req.files.source.name; var fileName = seqNo+"."+getExtPart(req.files.source.name); console.log("source: "+req.files.source.path); console.log("dest: "+audioDir + fileName); fs.rename(req.files.source.path, audioDir + fileName, function(err){ if(err != null){ console.log("Server cant rename"); console.log(err); res.send({error:"Error from server"}); } else{ console.log("Success rename"); var soundlib = new GLOBAL.Sound; var sourcepart = getNamePart(fileName); soundlib.convertWavToMp3(audioDir + fileName,audioDir + sourcepart+".mp3",function( ){ fs.unlink(audioDir + fileName,function(err){ console.log("Error delete file: " + err); }); }); updateInbox(seqNo); res.send("Ok"); } } ); } var insertSequence = function( ){ var sequences = {sequenceNo:1}; db.collection('sequences', function(err, collection) { collection.insert(sequences, {safe:true}, function(err, result) { if (err) { console.log("Error when insert first sequence"); res.send({'error':'An error has occurred'}); } else { console.log('Success: ' + JSON.stringify(result[0])); saveAudio(result[0].sequenceNo); } }); }); } var updateSequence = function( ){ db.collection('sequences', function(err, sequences) { sequences.findOne({}, function(err, item) { item.sequenceNo++; sequences.save(item); saveAudio(item.sequenceNo); }); }); } db.collection('sequences', function(err, sequences) { sequences.find().toArray(function(err, items) { if(items.length == 0){ insertSequence( ); } else{ updateSequence( ); } }); }); }
tonycaovn/vivuserver
services/audio.js
JavaScript
mit
5,449
var gulp = require('gulp'); var connect = require('gulp-connect'); var wiredep = require('wiredep').stream; var $ = require('gulp-load-plugins')(); var del = require('del'); var jsReporter = require('jshint-stylish'); var annotateAdfPlugin = require('ng-annotate-adf-plugin'); var pkg = require('./package.json'); var annotateOptions = { plugin: [ annotateAdfPlugin ] }; var templateOptions = { root: '{widgetsPath}/deviceInventory/src', module: 'adf.widget.deviceInventory' }; /** lint **/ gulp.task('csslint', function(){ gulp.src('src/**/*.css') .pipe($.csslint()) .pipe($.csslint.reporter()); }); gulp.task('jslint', function(){ gulp.src('src/**/*.js') .pipe($.jshint()) .pipe($.jshint.reporter(jsReporter)); }); gulp.task('lint', ['csslint', 'jslint']); /** serve **/ gulp.task('templates', function(){ return gulp.src('src/**/*.html') .pipe($.angularTemplatecache('templates.tpl.js', templateOptions)) .pipe(gulp.dest('.tmp/dist')); }); gulp.task('sample', ['templates'], function(){ var files = gulp.src(['src/**/*.js', 'src/**/*.css', 'src/**/*.less', '.tmp/dist/*.js']) .pipe($.if('*.js', $.angularFilesort())); gulp.src('sample/index.html') .pipe(wiredep({ directory: './components/', bowerJson: require('./bower.json'), devDependencies: true, dependencies: true })) .pipe($.inject(files)) .pipe(gulp.dest('.tmp/dist')) .pipe(connect.reload()); }); gulp.task('watch', function(){ gulp.watch(['src/**'], ['sample']); }); gulp.task('serve', ['watch', 'sample'], function(){ connect.server({ root: ['.tmp/dist', '.'], livereload: true, port: 9002 }); }); /** build **/ gulp.task('css', function(){ gulp.src(['src/**/*.css', 'src/**/*.less']) .pipe($.if('*.less', $.less())) .pipe($.concat(pkg.name + '.css')) .pipe(gulp.dest('dist')) .pipe($.rename(pkg.name + '.min.css')) .pipe($.minifyCss()) .pipe(gulp.dest('dist')); }); gulp.task('js', function() { gulp.src(['src/**/*.js', 'src/**/*.html']) .pipe($.if('*.html', $.minifyHtml())) .pipe($.if('*.html', $.angularTemplatecache(pkg.name + '.tpl.js', templateOptions))) .pipe($.angularFilesort()) .pipe($.if('*.js', $.replace(/'use strict';/g, ''))) .pipe($.concat(pkg.name + '.js')) .pipe($.headerfooter('(function(window, undefined) {\'use strict\';\n', '})(window);')) .pipe($.ngAnnotate(annotateOptions)) .pipe(gulp.dest('dist')) .pipe($.rename(pkg.name + '.min.js')) .pipe($.uglify()) .pipe(gulp.dest('dist')); }); /** clean **/ gulp.task('clean', function(cb){ del(['dist', '.tmp'], cb); }); gulp.task('default', ['css', 'js']);
reshak/angular-dashboard-framework
sample/widgets/deviceInventory/gulpfile.js
JavaScript
mit
2,787
from rest_framework import serializers from rest_auth.serializers import UserDetailsSerializer class UserSerializer(UserDetailsSerializer): website = serializers.URLField(source="userprofile.website", allow_blank=True, required=False) about = serializers.CharField(source="userprofile.about", allow_blank=True, required=False) class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('website', 'about') def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) website = profile_data.get('website') about = profile_data.get('about') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if profile_data: if website: profile.website = website if about: profile.about = about profile.save() return instance
ZachLiuGIS/reactjs-auth-django-rest
django_backend/user_profile/serializers.py
Python
mit
1,016
/** @license React vundefined * react.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.React = {})); }(this, (function (exports) { 'use strict'; var ReactVersion = '18.0.0-bdd6d5064-20211001'; // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = 0xeac7; var REACT_PORTAL_TYPE = 0xeaca; exports.Fragment = 0xeacb; exports.StrictMode = 0xeacc; exports.Profiler = 0xead2; var REACT_PROVIDER_TYPE = 0xeacd; var REACT_CONTEXT_TYPE = 0xeace; var REACT_FORWARD_REF_TYPE = 0xead0; exports.Suspense = 0xead1; exports.SuspenseList = 0xead8; var REACT_MEMO_TYPE = 0xead3; var REACT_LAZY_TYPE = 0xead4; var REACT_SCOPE_TYPE = 0xead7; var REACT_OPAQUE_ID_TYPE = 0xeae0; var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; var REACT_OFFSCREEN_TYPE = 0xeae2; var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; var REACT_CACHE_TYPE = 0xeae4; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; REACT_ELEMENT_TYPE = symbolFor('react.element'); REACT_PORTAL_TYPE = symbolFor('react.portal'); exports.Fragment = symbolFor('react.fragment'); exports.StrictMode = symbolFor('react.strict_mode'); exports.Profiler = symbolFor('react.profiler'); REACT_PROVIDER_TYPE = symbolFor('react.provider'); REACT_CONTEXT_TYPE = symbolFor('react.context'); REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); exports.Suspense = symbolFor('react.suspense'); exports.SuspenseList = symbolFor('react.suspense_list'); REACT_MEMO_TYPE = symbolFor('react.memo'); REACT_LAZY_TYPE = symbolFor('react.lazy'); REACT_SCOPE_TYPE = symbolFor('react.scope'); REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); REACT_CACHE_TYPE = symbolFor('react.cache'); } var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } var hasOwnProperty = Object.prototype.hasOwnProperty; var _assign = function (to, from) { for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } }; var assign = Object.assign || function (target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource != null) { _assign(to, Object(nextSource)); } } return to; }; /** * Keeps track of the current dispatcher. */ var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; /** * Keeps track of the current batch's configuration such as how long an update * should suspend for if it needs to. */ var ReactCurrentBatchConfig = { transition: 0 }; { ReactCurrentBatchConfig._updatedFibers = new Set(); } var ReactCurrentActQueue = { current: null, // Our internal tests use a custom implementation of `act` that works by // mocking the Scheduler package. Use this field to disable the `act` warning. // TODO: Maybe the warning should be disabled by default, and then turned // on at the testing frameworks layer? Instead of what we do now, which // is check if a `jest` global is defined. disableActWarning: false, // Used to reproduce behavior of `batchedUpdates` in legacy mode. isBatchingLegacy: false, didScheduleLegacyUpdate: false }; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactDebugCurrentFrame = {}; var currentExtraStackFrame = null; function setExtraStackFrame(stack) { { currentExtraStackFrame = stack; } } { ReactDebugCurrentFrame.setExtraStackFrame = function (stack) { { currentExtraStackFrame = stack; } }; // Stack implementation injected by the current renderer. ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function () { var stack = ''; // Add an extra top frame while an element is being validated if (currentExtraStackFrame) { stack += currentExtraStackFrame; } // Delegate to the injected renderer-specific implementation var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ''; } return stack; }; } var ReactSharedInternals = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentBatchConfig: ReactCurrentBatchConfig, ReactCurrentOwner: ReactCurrentOwner, // Used by renderers to avoid bundling object-assign twice in UMD bundles: assign: assign }; { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; } // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. function warn(format) { { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning('warn', format, args); } } } function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } // eslint-disable-next-line react-internal/safe-string-coercion var argsWithFormat = args.map(function (item) { return String(item); }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, 'setState'); } }; var emptyObject = {}; { Object.freeze(emptyObject); } /** * Base class helpers for the updating state of a component. */ function Component(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ Component.prototype.setState = function (partialState, callback) { if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) { throw Error( 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.' ); } this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ Component.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function () { warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; // an immutable object with a single mutable value function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } /* * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol * and Temporal.* types. See https://github.com/facebook/react/pull/22064. * * The functions in this module will throw an easier-to-understand, * easier-to-debug exception with a clear errors message message explaining the * problem. (Instead of a confusing exception thrown inside the implementation * of the `value` object). */ // $FlowFixMe only called in DEV, so void return is not possible. function typeName(value) { { // toStringTag is needed for namespaced types like Temporal.Instant var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; return type; } } // $FlowFixMe only called in DEV, so void return is not possible. function willCoercionThrow(value) { { if (value !== null && typeof value === 'object' && value.$$typeof === REACT_OPAQUE_ID_TYPE) { // OpaqueID type is expected to throw, so React will handle it. Not sure if // it's expected that string coercion will throw, but we'll assume it's OK. // See https://github.com/facebook/react/issues/20127. return; } try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { // If you ended up here by following an exception call stack, here's what's // happened: you supplied an object or symbol value to React (as a prop, key, // DOM attribute, CSS property, string ref, etc.) and when React tried to // coerce it to a string using `'' + value`, an exception was thrown. // // The most common types that will cause this exception are `Symbol` instances // and Temporal objects like `Temporal.Instant`. But any object that has a // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this // exception. (Library authors do this to prevent users from using built-in // numeric operators like `+` or comparison operators like `>=` because custom // methods are needed to perform accurate arithmetic or comparison.) // // To fix the problem, coerce this object or symbol value to a string before // passing it to React. The most reliable way is usually `String(value)`. // // To find which value is throwing, check the browser or debugger console. // Before this exception was thrown, there should be `console.error` output // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the // problem and how that type was used: key, atrribute, input value prop, etc. // In most cases, this console output also shows the component and its // ancestor components where the exception happened. // // eslint-disable-next-line react-internal/safe-string-coercion return '' + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type) { return type.displayName || 'Context'; } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. function getComponentNameFromType(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case exports.Fragment: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case exports.Profiler: return 'Profiler'; case exports.StrictMode: return 'StrictMode'; case exports.Suspense: return 'Suspense'; case exports.SuspenseList: return 'SuspenseList'; case REACT_CACHE_TYPE: return 'Cache'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } } } return null; } var hasOwnProperty$1 = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty$1.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty$1.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); didWarnAboutStringRefs[componentName] = true; } } } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://reactjs.org/docs/react-api.html#createelement */ function createElement(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } /** * Clone and return a new ReactElement using element as the starting point. * See https://reactjs.org/docs/react-api.html#cloneelement */ function cloneElement(element, config, children) { if (element === null || element === undefined) { throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." ); } var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = key.replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return text.replace(userProvidedKeyEscapeRegex, '$&/'); } /** * Generate a key string that identifies a element within a set. * * @param {*} element A element that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getElementKey(element, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof element === 'object' && element !== null && element.key != null) { // Explicit key { checkKeyStringCoercion(element.key); } return escape('' + element.key); } // Implicit key determined by the index in the set return index.toString(36); } function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case 'string': case 'number': invokeCallback = true; break; case 'object': switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { var _child = children; var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows: var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; if (isArray(mappedChild)) { var escapedChildKey = ''; if (childKey != null) { escapedChildKey = escapeUserProvidedKey(childKey) + '/'; } mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { { // The `if` statement here prevents auto-disabling of the safe // coercion ESLint rule, so we must manually disable it below. // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { checkKeyStringCoercion(mappedChild.key); } } mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number // eslint-disable-next-line react-internal/safe-string-coercion escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey); } array.push(mappedChild); } return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getElementKey(child, i); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { var iterableChildren = children; { // Warn about using Maps as children if (iteratorFn === iterableChildren.entries) { if (!didWarnAboutMaps) { warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(iterableChildren); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getElementKey(child, ii++); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else if (type === 'object') { // eslint-disable-next-line react-internal/safe-string-coercion var childrenString = String(children); throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.' ); } } return subtreeCount; } /** * Maps children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenmap * * The provided mapFunction(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; var count = 0; mapIntoArray(children, result, '', '', function (child) { return func.call(context, child, count++); }); return result; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrencount * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children) { var n = 0; mapChildren(children, function () { n++; // Don't return anything }); return n; } /** * Iterates through children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenforeach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { mapChildren(children, function () { forEachFunc.apply(this, arguments); // Don't return anything. }, forEachContext); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://reactjs.org/docs/react-api.html#reactchildrentoarray */ function toArray(children) { return mapChildren(children, function (child) { return child; }) || []; } /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://reactjs.org/docs/react-api.html#reactchildrenonly * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { if (!isValidElement(children)) { throw Error( 'React.Children.only expected to receive a single React element child.' ); } return children; } function createContext(defaultValue) { // TODO: Second argument used to be an optional `calculateChangedBits` // function. Warn to reserve for future use? var context = { $$typeof: REACT_CONTEXT_TYPE, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; var hasWarnedAboutDisplayNameOnConsumer = false; { // A separate object, but proxies back to the original context object for // backwards compatibility. It has a different $$typeof, so we can properly // warn for the incorrect usage of Context as a Consumer. var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, { Provider: { get: function () { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?'); } return context.Provider; }, set: function (_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function () { return context._currentValue; }, set: function (_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function () { return context._currentValue2; }, set: function (_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function () { return context._threadCount; }, set: function (_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function () { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } return context.Consumer; } }, displayName: { get: function () { return context.displayName; }, set: function (displayName) { if (!hasWarnedAboutDisplayNameOnConsumer) { warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName); hasWarnedAboutDisplayNameOnConsumer = true; } } } }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; function lazyInitializer(payload) { if (payload._status === Uninitialized) { var ctor = payload._result; var thenable = ctor(); // Transition to the next state. // This might throw either because it's missing or throws. If so, we treat it // as still uninitialized and try again next time. Which is the same as what // happens if the ctor or any wrappers processing the ctor throws. This might // end up fixing it if the resolution was a concurrency bug. thenable.then(function (moduleObject) { if (payload._status === Pending || payload._status === Uninitialized) { // Transition to the next state. var resolved = payload; resolved._status = Resolved; resolved._result = moduleObject; } }, function (error) { if (payload._status === Pending || payload._status === Uninitialized) { // Transition to the next state. var rejected = payload; rejected._status = Rejected; rejected._result = error; } }); if (payload._status === Uninitialized) { // In case, we're still uninitialized, then we're waiting for the thenable // to resolve. Set it as pending in the meantime. var pending = payload; pending._status = Pending; pending._result = thenable; } } if (payload._status === Resolved) { var moduleObject = payload._result; { if (moduleObject === undefined) { error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject); } } { if (!('default' in moduleObject)) { error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject); } } return moduleObject.default; } else { throw payload._result; } } function lazy(ctor) { var payload = { // We use these fields to store the result. _status: Uninitialized, _result: ctor }; var lazyType = { $$typeof: REACT_LAZY_TYPE, _payload: payload, _init: lazyInitializer }; { // In production, this would just set it on the object. var defaultProps; var propTypes; // $FlowFixMe Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function () { return defaultProps; }, set: function (newDefaultProps) { error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); defaultProps = newDefaultProps; // Match production behavior more closely: // $FlowFixMe Object.defineProperty(lazyType, 'defaultProps', { enumerable: true }); } }, propTypes: { configurable: true, get: function () { return propTypes; }, set: function (newPropTypes) { error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); propTypes = newPropTypes; // Match production behavior more closely: // $FlowFixMe Object.defineProperty(lazyType, 'propTypes', { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); } else if (typeof render !== 'function') { error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); } else { if (render.length !== 0 && render.length !== 2) { error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?'); } } } var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; { var ownName; Object.defineProperty(elementType, 'displayName', { enumerable: false, configurable: true, get: function () { return ownName; }, set: function (name) { ownName = name; // The inner component shouldn't inherit this display name in most cases, // because the component may be used elsewhere. // But it's nice for anonymous functions to inherit the name, // so that our component-stack generation logic will display their frames. // An anonymous function generally suggests a pattern like: // React.forwardRef((props, ref) => {...}); // This kind of inner function is not used elsewhere so the side effect is okay. if (!render.name && !render.displayName) { render.displayName = name; } } }); } return elementType; } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. var enableCache = false; // Only used in www builds. var enableScopeAPI = false; // Experimental Create Event Handle API. var warnOnSubscriptionInsideStartTransition = false; var REACT_MODULE_REFERENCE = 0; if (typeof Symbol === 'function') { REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); } function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === exports.SuspenseList || type === REACT_LEGACY_HIDDEN_TYPE || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCache ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { return true; } } return false; } function memo(type, compare) { { if (!isValidElementType(type)) { error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); } } var elementType = { $$typeof: REACT_MEMO_TYPE, type: type, compare: compare === undefined ? null : compare }; { var ownName; Object.defineProperty(elementType, 'displayName', { enumerable: false, configurable: true, get: function () { return ownName; }, set: function (name) { ownName = name; // The inner component shouldn't inherit this display name in most cases, // because the component may be used elsewhere. // But it's nice for anonymous functions to inherit the name, // so that our component-stack generation logic will display their frames. // An anonymous function generally suggests a pattern like: // React.memo((props) => {...}); // This kind of inner function is not used elsewhere so the side effect is okay. if (!type.name && !type.displayName) { type.displayName = name; } } }); } return elementType; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; { if (dispatcher === null) { error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); } } // Will result in a null access error if accessed outside render phase. We // intentionally don't throw our own error because this is in a hot path. // Also helps ensure this is inlined. return dispatcher; } function useContext(Context) { var dispatcher = resolveDispatcher(); { // TODO: add a more generic warning for invalid values. if (Context._context !== undefined) { var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs // and nobody should be using this in existing code. if (realContext.Consumer === Context) { error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); } else if (realContext.Provider === Context) { error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); } } } return dispatcher.useContext(Context); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, deps); } function useLayoutEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, deps); } function useCallback(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, deps); } function useImperativeHandle(ref, create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } function useTransition() { var dispatcher = resolveDispatcher(); return dispatcher.useTransition(); } function useDeferredValue(value) { var dispatcher = resolveDispatcher(); return dispatcher.useDeferredValue(value); } function useOpaqueIdentifier() { var dispatcher = resolveDispatcher(); return dispatcher.useOpaqueIdentifier(); } function useMutableSource(source, getSnapshot, subscribe) { var dispatcher = resolveDispatcher(); return dispatcher.useMutableSource(source, getSnapshot, subscribe); } // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if ( !fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher$1.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher$1.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case exports.Suspense: return describeBuiltInComponentFrame('Suspense'); case exports.SuspenseList: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(hasOwnProperty$1); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { // eslint-disable-next-line react-internal/prod-error-codes var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); setExtraStackFrame(stack); } else { setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentNameFromType(ReactCurrentOwner.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(source) { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== undefined) { return getSourceInfoErrorAddendum(elementProps.__source); } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } { setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentNameFromType(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentNameFromType(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } { error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } } var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === exports.Fragment) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.'); } // Legacy hook: remove it Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); Object.defineProperty(this, 'type', { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } function createMutableSource(source, getVersion) { var mutableSource = { _getVersion: getVersion, _source: source, _workInProgressVersionPrimary: null, _workInProgressVersionSecondary: null }; { mutableSource._currentPrimaryRenderer = null; mutableSource._currentSecondaryRenderer = null; // Used to detect side effects that update a mutable source during render. // See https://github.com/facebook/react/issues/19948 mutableSource._currentlyRenderingFiber = null; mutableSource._initialVersionAsOfFirstRender = null; } return mutableSource; } var enableSchedulerDebugging = false; var enableProfiling = false; var frameYieldMs = 5; function push(heap, node) { var index = heap.length; heap.push(node); siftUp(heap, node, index); } function peek(heap) { return heap.length === 0 ? null : heap[0]; } function pop(heap) { if (heap.length === 0) { return null; } var first = heap[0]; var last = heap.pop(); if (last !== first) { heap[0] = last; siftDown(heap, last, 0); } return first; } function siftUp(heap, node, i) { var index = i; while (index > 0) { var parentIndex = index - 1 >>> 1; var parent = heap[parentIndex]; if (compare(parent, node) > 0) { // The parent is larger. Swap positions. heap[parentIndex] = node; heap[index] = parent; index = parentIndex; } else { // The parent is smaller. Exit. return; } } } function siftDown(heap, node, i) { var index = i; var length = heap.length; var halfLength = length >>> 1; while (index < halfLength) { var leftIndex = (index + 1) * 2 - 1; var left = heap[leftIndex]; var rightIndex = leftIndex + 1; var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. if (compare(left, node) < 0) { if (rightIndex < length && compare(right, left) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { heap[index] = left; heap[leftIndex] = node; index = leftIndex; } } else if (rightIndex < length && compare(right, node) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { // Neither child is smaller. Exit. return; } } } function compare(a, b) { // Compare sort index first, then task id. var diff = a.sortIndex - b.sortIndex; return diff !== 0 ? diff : a.id - b.id; } // TODO: Use symbols? var ImmediatePriority = 1; var UserBlockingPriority = 2; var NormalPriority = 3; var LowPriority = 4; var IdlePriority = 5; function markTaskErrored(task, ms) { } /* eslint-disable no-var */ var getCurrentTime; var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; if (hasPerformanceNow) { var localPerformance = performance; getCurrentTime = function () { return localPerformance.now(); }; } else { var localDate = Date; var initialTime = localDate.now(); getCurrentTime = function () { return localDate.now() - initialTime; }; } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. // Math.pow(2, 30) - 1 // 0b111111111111111111111111111111 var maxSigned31BitInt = 1073741823; // Times out immediately var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out var USER_BLOCKING_PRIORITY_TIMEOUT = 250; var NORMAL_PRIORITY_TIMEOUT = 5000; var LOW_PRIORITY_TIMEOUT = 10000; // Never times out var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap var taskQueue = []; var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. var currentTask = null; var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. var isPerformingWork = false; var isHostCallbackScheduled = false; var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; function advanceTimers(currentTime) { // Check for tasks that are no longer delayed and add them to the queue. var timer = peek(timerQueue); while (timer !== null) { if (timer.callback === null) { // Timer was cancelled. pop(timerQueue); } else if (timer.startTime <= currentTime) { // Timer fired. Transfer to the task queue. pop(timerQueue); timer.sortIndex = timer.expirationTime; push(taskQueue, timer); } else { // Remaining timers are pending. return; } timer = peek(timerQueue); } } function handleTimeout(currentTime) { isHostTimeoutScheduled = false; advanceTimers(currentTime); if (!isHostCallbackScheduled) { if (peek(taskQueue) !== null) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } } } } function flushWork(hasTimeRemaining, initialTime) { isHostCallbackScheduled = false; if (isHostTimeoutScheduled) { // We scheduled a timeout but it's no longer needed. Cancel it. isHostTimeoutScheduled = false; cancelHostTimeout(); } isPerformingWork = true; var previousPriorityLevel = currentPriorityLevel; try { if (enableProfiling) { try { return workLoop(hasTimeRemaining, initialTime); } catch (error) { if (currentTask !== null) { var currentTime = getCurrentTime(); markTaskErrored(currentTask, currentTime); currentTask.isQueued = false; } throw error; } } else { // No catch in prod code path. return workLoop(hasTimeRemaining, initialTime); } } finally { currentTask = null; currentPriorityLevel = previousPriorityLevel; isPerformingWork = false; } } function workLoop(hasTimeRemaining, initialTime) { var currentTime = initialTime; advanceTimers(currentTime); currentTask = peek(taskQueue); while (currentTask !== null && !(enableSchedulerDebugging )) { if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { // This currentTask hasn't expired, and we've reached the deadline. break; } var callback = currentTask.callback; if (typeof callback === 'function') { currentTask.callback = null; currentPriorityLevel = currentTask.priorityLevel; var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; var continuationCallback = callback(didUserCallbackTimeout); currentTime = getCurrentTime(); if (typeof continuationCallback === 'function') { currentTask.callback = continuationCallback; } else { if (currentTask === peek(taskQueue)) { pop(taskQueue); } } advanceTimers(currentTime); } else { pop(taskQueue); } currentTask = peek(taskQueue); } // Return whether there's additional work if (currentTask !== null) { return true; } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } return false; } } function unstable_runWithPriority(priorityLevel, eventHandler) { switch (priorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: case LowPriority: case IdlePriority: break; default: priorityLevel = NormalPriority; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_next(eventHandler) { var priorityLevel; switch (currentPriorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: // Shift down to normal priority priorityLevel = NormalPriority; break; default: // Anything lower than normal priority should remain at the current level. priorityLevel = currentPriorityLevel; break; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_wrapCallback(callback) { var parentPriorityLevel = currentPriorityLevel; return function () { // This is a fork of runWithPriority, inlined for performance. var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = parentPriorityLevel; try { return callback.apply(this, arguments); } finally { currentPriorityLevel = previousPriorityLevel; } }; } function unstable_scheduleCallback(priorityLevel, callback, options) { var currentTime = getCurrentTime(); var startTime; if (typeof options === 'object' && options !== null) { var delay = options.delay; if (typeof delay === 'number' && delay > 0) { startTime = currentTime + delay; } else { startTime = currentTime; } } else { startTime = currentTime; } var timeout; switch (priorityLevel) { case ImmediatePriority: timeout = IMMEDIATE_PRIORITY_TIMEOUT; break; case UserBlockingPriority: timeout = USER_BLOCKING_PRIORITY_TIMEOUT; break; case IdlePriority: timeout = IDLE_PRIORITY_TIMEOUT; break; case LowPriority: timeout = LOW_PRIORITY_TIMEOUT; break; case NormalPriority: default: timeout = NORMAL_PRIORITY_TIMEOUT; break; } var expirationTime = startTime + timeout; var newTask = { id: taskIdCounter++, callback: callback, priorityLevel: priorityLevel, startTime: startTime, expirationTime: expirationTime, sortIndex: -1 }; if (startTime > currentTime) { // This is a delayed task. newTask.sortIndex = startTime; push(timerQueue, newTask); if (peek(taskQueue) === null && newTask === peek(timerQueue)) { // All tasks are delayed, and this is the task with the earliest delay. if (isHostTimeoutScheduled) { // Cancel an existing timeout. cancelHostTimeout(); } else { isHostTimeoutScheduled = true; } // Schedule a timeout. requestHostTimeout(handleTimeout, startTime - currentTime); } } else { newTask.sortIndex = expirationTime; push(taskQueue, newTask); // wait until the next time we yield. if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } return newTask; } function unstable_pauseExecution() { } function unstable_continueExecution() { if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } function unstable_getFirstCallbackNode() { return peek(taskQueue); } function unstable_cancelCallback(task) { // remove from the queue because you can't remove arbitrary nodes from an // array based heap, only the first one.) task.callback = null; } function unstable_getCurrentPriorityLevel() { return currentPriorityLevel; } var isMessageLoopRunning = false; var scheduledHostCallback = null; var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main // thread, like user events. By default, it yields multiple times per frame. // It does not attempt to align with frame boundaries, since most tasks don't // need to be frame aligned; for those that do, use requestAnimationFrame. var frameInterval = frameYieldMs; var startTime = -1; function shouldYieldToHost() { var timeElapsed = getCurrentTime() - startTime; if (timeElapsed < frameInterval) { // The main thread has only been blocked for a really short amount of time; // smaller than a single frame. Don't yield yet. return false; } // The main thread has been blocked for a non-negligible amount of time. We return true; } function requestPaint() { } function forceFrameRate(fps) { if (fps < 0 || fps > 125) { // Using console['error'] to evade Babel and ESLint console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); return; } if (fps > 0) { frameInterval = Math.floor(1000 / fps); } else { // reset the framerate frameInterval = frameYieldMs; } } var performWorkUntilDeadline = function () { if (scheduledHostCallback !== null) { var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread // has been blocked. startTime = currentTime; var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the // error can be observed. // // Intentionally not using a try-catch, since that makes some debugging // techniques harder. Instead, if `scheduledHostCallback` errors, then // `hasMoreWork` will remain true, and we'll continue the work loop. var hasMoreWork = true; try { hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); } finally { if (hasMoreWork) { // If there's more work, schedule the next message event at the end // of the preceding one. schedulePerformWorkUntilDeadline(); } else { isMessageLoopRunning = false; scheduledHostCallback = null; } } } else { isMessageLoopRunning = false; } // Yielding to the browser will give it a chance to paint, so we can }; var schedulePerformWorkUntilDeadline; if (typeof localSetImmediate === 'function') { // Node.js and old IE. // There's a few reasons for why we prefer setImmediate. // // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. // (Even though this is a DOM fork of the Scheduler, you could get here // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) // https://github.com/facebook/react/issues/20756 // // But also, it runs earlier which is the semantic we want. // If other browsers ever implement it, it's better to use it. // Although both of these would be inferior to native scheduling. schedulePerformWorkUntilDeadline = function () { localSetImmediate(performWorkUntilDeadline); }; } else if (typeof MessageChannel !== 'undefined') { // DOM and Worker environments. // We prefer MessageChannel because of the 4ms setTimeout clamping. var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = performWorkUntilDeadline; schedulePerformWorkUntilDeadline = function () { port.postMessage(null); }; } else { // We should only fallback here in non-browser environments. schedulePerformWorkUntilDeadline = function () { localSetTimeout(performWorkUntilDeadline, 0); }; } function requestHostCallback(callback) { scheduledHostCallback = callback; if (!isMessageLoopRunning) { isMessageLoopRunning = true; schedulePerformWorkUntilDeadline(); } } function requestHostTimeout(callback, ms) { taskTimeoutID = localSetTimeout(function () { callback(getCurrentTime()); }, ms); } function cancelHostTimeout() { localClearTimeout(taskTimeoutID); taskTimeoutID = -1; } var unstable_requestPaint = requestPaint; var unstable_Profiling = null; var Scheduler = /*#__PURE__*/Object.freeze({ __proto__: null, unstable_ImmediatePriority: ImmediatePriority, unstable_UserBlockingPriority: UserBlockingPriority, unstable_NormalPriority: NormalPriority, unstable_IdlePriority: IdlePriority, unstable_LowPriority: LowPriority, unstable_runWithPriority: unstable_runWithPriority, unstable_next: unstable_next, unstable_scheduleCallback: unstable_scheduleCallback, unstable_cancelCallback: unstable_cancelCallback, unstable_wrapCallback: unstable_wrapCallback, unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel, unstable_shouldYield: shouldYieldToHost, unstable_requestPaint: unstable_requestPaint, unstable_continueExecution: unstable_continueExecution, unstable_pauseExecution: unstable_pauseExecution, unstable_getFirstCallbackNode: unstable_getFirstCallbackNode, get unstable_now () { return getCurrentTime; }, unstable_forceFrameRate: forceFrameRate, unstable_Profiling: unstable_Profiling }); var ReactSharedInternals$1 = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentOwner: ReactCurrentOwner, ReactCurrentBatchConfig: ReactCurrentBatchConfig, // Used by renderers to avoid bundling object-assign twice in UMD bundles: assign: assign, // Re-export the schedule API(s) for UMD bundles. // This avoids introducing a dependency on a new UMD global in a minor update, // Since that would be a breaking change (e.g. for all existing CodeSandboxes). // This re-export is only required for UMD bundles; // CJS bundles use the shared NPM package. Scheduler: Scheduler }; { ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue; ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame; } function startTransition(scope) { var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = 1; try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; { if (prevTransition !== 1 && warnOnSubscriptionInsideStartTransition && ReactCurrentBatchConfig._updatedFibers) { var updatedFibersCount = ReactCurrentBatchConfig._updatedFibers.size; if (updatedFibersCount > 10) { warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); } ReactCurrentBatchConfig._updatedFibers.clear(); } } } } var didWarnAboutMessageChannel = false; var enqueueTaskImpl = null; function enqueueTask(task) { if (enqueueTaskImpl === null) { try { // read require off the module object to get around the bundlers. // we don't want them to detect a require and bundle a Node polyfill. var requireString = ('require' + Math.random()).slice(0, 7); var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's // version of setImmediate, bypassing fake timers if any. enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate; } catch (_err) { // we're in a browser // we can't use regular timers because they may still be faked // so we try MessageChannel+postMessage instead enqueueTaskImpl = function (callback) { { if (didWarnAboutMessageChannel === false) { didWarnAboutMessageChannel = true; if (typeof MessageChannel === 'undefined') { error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.'); } } } var channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(undefined); }; } } return enqueueTaskImpl(task); } var actScopeDepth = 0; var didWarnNoAwaitAct = false; function act(callback) { { // `act` calls can be nested, so we track the depth. This represents the // number of `act` scopes on the stack. var prevActScopeDepth = actScopeDepth; actScopeDepth++; if (ReactCurrentActQueue.current === null) { // This is the outermost `act` scope. Initialize the queue. The reconciler // will detect the queue and use it instead of Scheduler. ReactCurrentActQueue.current = []; } var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; var result; try { // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only // set to `true` while the given callback is executed, not for updates // triggered during an async event, because this is how the legacy // implementation of `act` behaved. ReactCurrentActQueue.isBatchingLegacy = true; result = callback(); // Replicate behavior of original `act` implementation in legacy mode, // which flushed updates immediately after the scope function exits, even // if it's an async function. if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { var queue = ReactCurrentActQueue.current; if (queue !== null) { ReactCurrentActQueue.didScheduleLegacyUpdate = false; flushActQueue(queue); } } } catch (error) { popActScope(prevActScopeDepth); throw error; } finally { ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; } if (result !== null && typeof result === 'object' && typeof result.then === 'function') { var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait // for it to resolve before exiting the current scope. var wasAwaited = false; var thenable = { then: function (resolve, reject) { wasAwaited = true; thenableResult.then(function (returnValue) { popActScope(prevActScopeDepth); if (actScopeDepth === 0) { // We've exited the outermost act scope. Recursively flush the // queue until there's no remaining work. recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } }, function (error) { // The callback threw an error. popActScope(prevActScopeDepth); reject(error); }); } }; { if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') { // eslint-disable-next-line no-undef Promise.resolve().then(function () {}).then(function () { if (!wasAwaited) { didWarnNoAwaitAct = true; error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);'); } }); } } return thenable; } else { var returnValue = result; // The callback is not an async function. Exit the current scope // immediately, without awaiting. popActScope(prevActScopeDepth); if (actScopeDepth === 0) { // Exiting the outermost act scope. Flush the queue. var _queue = ReactCurrentActQueue.current; if (_queue !== null) { flushActQueue(_queue); ReactCurrentActQueue.current = null; } // Return a thenable. If the user awaits it, we'll flush again in // case additional work was scheduled by a microtask. var _thenable = { then: function (resolve, reject) { // Confirm we haven't re-entered another `act` scope, in case // the user does something weird like await the thenable // multiple times. if (ReactCurrentActQueue.current === null) { // Recursively flush the queue until there's no remaining work. ReactCurrentActQueue.current = []; recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } } }; return _thenable; } else { // Since we're inside a nested `act` scope, the returned thenable // immediately resolves. The outer scope will flush the queue. var _thenable2 = { then: function (resolve, reject) { resolve(returnValue); } }; return _thenable2; } } } } function popActScope(prevActScopeDepth) { { if (prevActScopeDepth !== actScopeDepth - 1) { error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. '); } actScopeDepth = prevActScopeDepth; } } function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { { var queue = ReactCurrentActQueue.current; if (queue !== null) { try { flushActQueue(queue); enqueueTask(function () { if (queue.length === 0) { // No additional work was scheduled. Finish. ReactCurrentActQueue.current = null; resolve(returnValue); } else { // Keep flushing work until there's none left. recursivelyFlushAsyncActWork(returnValue, resolve, reject); } }); } catch (error) { reject(error); } } else { resolve(returnValue); } } } var isFlushing = false; function flushActQueue(queue) { { if (!isFlushing) { // Prevent re-entrance. isFlushing = true; var i = 0; try { for (; i < queue.length; i++) { var callback = queue[i]; do { callback = callback(true); } while (callback !== null); } queue.length = 0; } catch (error) { // If something throws, leave the remaining callbacks on the queue. queue = queue.slice(i + 1); throw error; } finally { isFlushing = false; } } } } var createElement$1 = createElementWithValidation ; var cloneElement$1 = cloneElementWithValidation ; var createFactory = createFactoryWithValidation ; var Children = { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray, only: onlyChild }; exports.Children = Children; exports.Component = Component; exports.PureComponent = PureComponent; exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1; exports.cloneElement = cloneElement$1; exports.createContext = createContext; exports.createElement = createElement$1; exports.createFactory = createFactory; exports.createRef = createRef; exports.forwardRef = forwardRef; exports.isValidElement = isValidElement; exports.lazy = lazy; exports.memo = memo; exports.startTransition = startTransition; exports.unstable_act = act; exports.unstable_createMutableSource = createMutableSource; exports.unstable_useMutableSource = useMutableSource; exports.unstable_useOpaqueIdentifier = useOpaqueIdentifier; exports.useCallback = useCallback; exports.useContext = useContext; exports.useDebugValue = useDebugValue; exports.useDeferredValue = useDeferredValue; exports.useEffect = useEffect; exports.useImperativeHandle = useImperativeHandle; exports.useLayoutEffect = useLayoutEffect; exports.useMemo = useMemo; exports.useReducer = useReducer; exports.useRef = useRef; exports.useState = useState; exports.useTransition = useTransition; exports.version = ReactVersion; })));
cdnjs/cdnjs
ajax/libs/react/18.0.0-alpha-bdd6d5064-20211001/umd/react.development.js
JavaScript
mit
112,128
<? $prefix = $_SERVER['DOCUMENT_ROOT']; require_once($prefix . '/common/markdown.php'); require_once($prefix . '/common/smartypants.php'); // Connect to Database include('common/dbconnect.php'); // Only items that have been published // (No posts scheduled for the future) $post_cutoff_time = time(); // Number of Posts $num_of_posts = 14; // Troubleshoot? $troubleshoot = FALSE; // Last Updated $last_updated_query = "SELECT MAX(published_time) AS last_update FROM blog WHERE published_time<$post_cutoff_time"; $last_updated_result = $mysqli->query($last_updated_query); $last_updated_array = $last_updated_result->fetch_array(MYSQLI_ASSOC); $last_updated_timestamp = $last_updated_array['last_update']; $last_updated = date('c', $last_updated_timestamp); // Preamble if(!$troubleshoot){ echo '<?xml version="1.0" encoding="utf-8"?>' . "\n"; echo '<feed xmlns="http://www.w3.org/2005/Atom">' . "\n"; } echo '<title>MEK Studios</title>' . "\n"; echo '<id>tag:www.mekstudios.com,2013-02-10:/notional/20130210055031443</id>' . "\n"; echo '<subtitle type="html">Critical thinking to start your day.&lt;br>A blog of ideas, thoughts, and concepts for consideration.</subtitle>' . "\n"; echo '<link rel="alternate" type="text/html" hreflang="en" href="https://www.mekstudios.com/"/>' . "\n"; echo '<link rel="self" type="application/atom+xml" href="https://www.mekstudios.com/feed/"/>' . "\n"; echo '<rights>Copyright (c) 2013 Michael E. Kirkpatrick</rights>' . "\n"; echo '<updated>' . $last_updated . '</updated>' . "\n"; echo '<author>' . "\n"; echo ' <name>Michael E. Kirkpatrick</name>' . "\n"; echo ' <uri>http://www.mekstudios.com</uri>' . "\n"; echo ' <email>michael@mekstudios.com</email>' . "\n"; echo '</author>' . "\n"; // Cycle through posts $article_query = "SELECT url, link, title, author, published_time, published_month, published_year, updated_time, text, atom_id FROM blog WHERE published_time<$post_cutoff_time ORDER BY published_time DESC LIMIT $num_of_posts"; $article_result = $mysqli->query($article_query); while($article_array = $article_result->fetch_array(MYSQLI_ASSOC)){ echo '<entry>' . "\n"; //echo ' <title type="html">' . htmlspecialchars(html_entity_decode($article_array['title'], ENT_QUOTES | ENT_HTML5, "UTF-8")) . '</title>' . "\n"; echo ' <title type="html">' . htmlspecialchars(SmartyPants($article_array['title'], ENT_QUOTES | ENT_HTML5, "UTF-8")) . '</title>' . "\n"; echo ' <id>' . $article_array['atom_id'] . '</id>' . "\n"; if($article_array['link'] != ''){echo ' <link href="' . htmlspecialchars($article_array['link']) . '" rel="via" type="text/html" />' . "\n";} echo ' <link href="http://www.mekstudios.com/' . $article_array['published_year'] . '/' . $article_array['published_month'] . '/' . $article_array['url'] . '" rel="alternate" type="text/html" />' . "\n"; echo ' <published>' . date('c', $article_array['published_time']) . '</published>' . "\n"; # If Updated if($article_array['updated_time'] != ''){ echo ' <updated>' . date('c', $article_array['updated_time']) . '</updated>' . "\n"; }else{ echo ' <updated>' . date('c', $article_array['published_time']) . '</updated>' . "\n"; } echo ' <author>' . "\n"; echo ' <name>' . $article_array['author'] . '</name>' . "\n"; echo ' </author>' . "\n"; $text_display = SmartyPants(Markdown($article_array['text'])); //$text_display = html_entity_decode($article_array['text'], ENT_QUOTES | ENT_HTML5, "UTF-8"); //$text_display = str_replace('\r\n', '', $text_display); $find = array('&', '<'); $replace = array('&amp;', '&lt;'); $text_display = str_replace($find, $replace, $text_display); echo ' <content type="html">' . $text_display . '</content>' . "\n"; echo '</entry>' . "\n"; } // End of Feed echo '</feed>' . "\n"; ?>
mk14/Long-Beach
atom-feed.php
PHP
mit
3,777
angular.module('ExampleCtrl', []).controller('ExampleCtrl', ['$scope', function($scope) { $scope.createItems = function() { $scope.items = []; for (var i = 0; i < 100; i++) { $scope.items[i] = { ratio: Math.max(0.4, Math.random() * 2), color: '#' + ('000000' + Math.floor(Math.random()*16777215).toString(16)).slice(-6) }; } }; $scope.createItems(); } ]); angular.module('ExampleApp', ['hj.columnify', 'ExampleCtrl']).config(function() {});
homerjam/angular-columnify
example/app.js
JavaScript
mit
557
package model.expression; /** * The type Operation. */ public class Operation { /** * The constant ADD. */ public static final int ADD = 1; /** * The constant SUBTRACT. */ public static final int SUBTRACT = 2; /** * The constant MULTIPLY. */ public static final int MULTIPLY = 3; /** * The constant DIVIDE. */ public static final int DIVIDE = 4; /** * Operation to string. * * @param op the op * @return the string */ public static String operationToString(int op) { switch (op) { case ADD: return "+"; case SUBTRACT: return "-"; case MULTIPLY: return "*"; case DIVIDE: return "/"; default: return ""; } } }
leyyin/university
advanced-programming-methods/labs/toy-interpreter-java/src/model/expression/Operation.java
Java
mit
895
var _ = require('lodash'), EventEmitter = require('events').EventEmitter, config = require('./config'), Channel = require('./channel'), Connection = require('./connection'), Bus = require('./bus'), API = require('./utils'); var subscribedChannels; function Gusher (applicationKey, options) { options || (options = {}); subscribedChannels = {}; this.options = options; this.bus = new Bus(); this.connection = new Connection(this.bus); } Gusher.prototype.subscribe = function (channelName) { var channel = new Channel(channelName, this.bus); subscribedChannels[channelName] = channel; return channel; }; Gusher.prototype.unsubscribe = function (channelName) { }; Gusher.prototype.allChannels = function () { return _.values(subscribedChannels); }; Gusher.prototype.disconnect = function () { this.connection.disconnect(); //TODO actually unsubscribe from each channel }; module.exports = { gusher: Gusher, api: API };
dobrite/gusher
src/javascripts/gusher.js
JavaScript
mit
1,015
var less = require('less'); var lessStr = '.class { width: (1+1)}'; less.render(lessStr, function(e, output) { console.log(output.css); }); console.log(less.render(lessStr));
escray/besike-nodejs-harp
lessExample.js
JavaScript
mit
177
namespace LibMinecraft { public struct Vector3 { public static Vector3 Zero { get { return new Vector3(0, 0, 0); } } public static Vector3 UpX { get { return new Vector3(1, 0, 0); } } public static Vector3 UpY { get { return new Vector3(0, 1, 0); } } public static Vector3 UpZ { get { return new Vector3(0, 0, 1); } } public double X; public double Y; public double Z; public Vector3(double x, double y, double z) { X = x; Y = y; Z = z; } public static Vector3 operator +(Vector3 a, Vector3 b) { return new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z); } public static Vector3 operator -(Vector3 a, Vector3 b) { return new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static Vector3 operator *(Vector3 a, Vector3 b) { return new Vector3(a.X * b.X, a.Y * b.Y, a.Z * b.Z); } public static Vector3 operator /(Vector3 a, Vector3 b) { return new Vector3(a.X / b.X, a.Y / b.Y, a.Z / b.Z); } } }
inku25253/MineProtocol.net
LibMinecraft/Vector3.cs
C#
mit
996
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TheCode { public class Customer { public string Id { get; set; } public string Name { get; set; } public bool Pro { get; set; } } }
chadmichel/UnitTest
TheCode/Customer.cs
C#
mit
298
<?php $ISO_3166_2 = array(); $ISO_3166_2['01'] = "Adana"; $ISO_3166_2['02'] = "Adiyaman"; $ISO_3166_2['03'] = "Afyonkarahisar"; $ISO_3166_2['04'] = "Agri"; $ISO_3166_2['68'] = "Aksaray"; $ISO_3166_2['05'] = "Amasya"; $ISO_3166_2['06'] = "Ankara"; $ISO_3166_2['07'] = "Antalya"; $ISO_3166_2['75'] = "Ardahan"; $ISO_3166_2['08'] = "Artvin"; $ISO_3166_2['09'] = "Aydin"; $ISO_3166_2['10'] = "Balikesir"; $ISO_3166_2['74'] = "Bartin"; $ISO_3166_2['72'] = "Batman"; $ISO_3166_2['69'] = "Bayburt"; $ISO_3166_2['11'] = "Bilecik"; $ISO_3166_2['12'] = "Bingöl"; $ISO_3166_2['13'] = "Bitlis"; $ISO_3166_2['14'] = "Bolu"; $ISO_3166_2['15'] = "Burdur"; $ISO_3166_2['16'] = "Bursa"; $ISO_3166_2['20'] = "Denizli"; $ISO_3166_2['21'] = "Diyarbakir"; $ISO_3166_2['81'] = "Düzce"; $ISO_3166_2['22'] = "Edirne"; $ISO_3166_2['23'] = "Elazig"; $ISO_3166_2['24'] = "Erzincan"; $ISO_3166_2['25'] = "Erzurum"; $ISO_3166_2['26'] = "Eskisehir"; $ISO_3166_2['27'] = "Gaziantep"; $ISO_3166_2['28'] = "Giresun"; $ISO_3166_2['29'] = "Gümüshane"; $ISO_3166_2['30'] = "Hakkâri"; $ISO_3166_2['31'] = "Hatay"; $ISO_3166_2['76'] = "Igdir"; $ISO_3166_2['32'] = "Isparta"; $ISO_3166_2['34'] = "Istanbul"; $ISO_3166_2['35'] = "Izmir"; $ISO_3166_2['46'] = "Kahramanmaras"; $ISO_3166_2['78'] = "Karabük"; $ISO_3166_2['70'] = "Karaman"; $ISO_3166_2['36'] = "Kars"; $ISO_3166_2['37'] = "Kastamonu"; $ISO_3166_2['38'] = "Kayseri"; $ISO_3166_2['79'] = "Kilis"; $ISO_3166_2['71'] = "Kirikkale"; $ISO_3166_2['39'] = "Kirklareli"; $ISO_3166_2['40'] = "Kirsehir"; $ISO_3166_2['41'] = "Kocaeli"; $ISO_3166_2['42'] = "Konya"; $ISO_3166_2['43'] = "Kütahya"; $ISO_3166_2['44'] = "Malatya"; $ISO_3166_2['45'] = "Manisa"; $ISO_3166_2['47'] = "Mardin"; $ISO_3166_2['33'] = "Mersin"; $ISO_3166_2['48'] = "Mugla"; $ISO_3166_2['49'] = "Mus"; $ISO_3166_2['50'] = "Nevsehir"; $ISO_3166_2['51'] = "Nigde"; $ISO_3166_2['52'] = "Ordu"; $ISO_3166_2['80'] = "Osmaniye"; $ISO_3166_2['53'] = "Rize"; $ISO_3166_2['54'] = "Sakarya"; $ISO_3166_2['55'] = "Samsun"; $ISO_3166_2['63'] = "Sanliurfa"; $ISO_3166_2['56'] = "Siirt"; $ISO_3166_2['57'] = "Sinop"; $ISO_3166_2['73'] = "Sirnak"; $ISO_3166_2['58'] = "Sivas"; $ISO_3166_2['59'] = "Tekirdag"; $ISO_3166_2['60'] = "Tokat"; $ISO_3166_2['61'] = "Trabzon"; $ISO_3166_2['62'] = "Tunceli"; $ISO_3166_2['64'] = "Usak"; $ISO_3166_2['65'] = "Van"; $ISO_3166_2['77'] = "Yalova"; $ISO_3166_2['66'] = "Yozgat"; $ISO_3166_2['67'] = "Zonguldak"; $ISO_3166_2['17'] = "Çanakkale"; $ISO_3166_2['18'] = "Çankiri"; $ISO_3166_2['19'] = "Çorum"; ?>
Yarduddles/ISO-3166
PHP/ISO-3166-2-TR.php
PHP
mit
2,522
<?php require_once(__DIR__ . "/../model/config.php"); //takes and stores exp - exp4 //$exp = filter_input(INPUT_POST, "exp", FILTER_SANITIZE_STRING); //$exp1 = filter_input(INPUT_POST, "exp1", FILTER_SANITIZE_STRING); //$exp2 = filter_input(INPUT_POST, "exp2", FILTER_SANITIZE_STRING); //$exp3 = filter_input(INPUT_POST, "exp3", FILTER_SANITIZE_STRING); //$exp4 = filter_input(INPUT_POST, "exp4", FILTER_SANITIZE_STRING); // // //$query = $_SESSION["connection"]->query("UPDATE users SET " // . "exp = $exp, " // . "exp1 = $exp1, " // . "exp2 = $exp2, " // . "exp3 = $exp3, " // . "exp4 = $exp4 WHERE username = \"" . $_SESSION["name"]. "\""); // if($query) { //need for Ajax echo "true"; } else { echo "<p>" . $_SESSION["connection"]->error . "</p>"; }
SimonAnna/final
Php/controller/save-user.php
PHP
mit
815
import React from "react"; import { SelectAddressModal } from "../ImportAccount"; import { roundingNumber } from "../../utils/converter" import PathSelector from "../../containers/CommonElements/PathSelector"; const ImportByDeviceView = (props) => { function choosePath(dpath) { let inputPath = document.getElementById('form-input-custom-path'); let selectedPath = dpath.value; if (!selectedPath) { selectedPath = inputPath.value; dpath = { value: selectedPath, desc: 'Your Custom Path' }; } props.choosePath(dpath); props.analytics.callTrack("trackChoosePathColdWallet", selectedPath); } function getAddress(formAddress) { let data = { address: formAddress.addressString, type: props.walletType, path: props.currentDPath.value + '/' + formAddress.index, }; if (props.currentDPath.bip44) { data.path = `${props.currentDPath.value}/${formAddress.index}'/0/0`; } props.getAddress(data); } function getCurrentList() { let currentListHtml = props.currentAddresses.map((address) => { return ( <div className={"address-item"} key={address.addressString}> <div className="address-item__address"> <div class="name text-lowercase theme__text-6"> <label class="mb-0"> <span class="hash">{address.addressString.slice(0, 12)}...{address.addressString.slice(-8)}</span> </label> </div> </div> <div class="address-item__import"> <div class="balance theme__text-6 common__flexbox-normal" title={address.balance}> {address.balance == '-1' ? <img src={require(`../../../assets/img/${props.theme === 'dark' ? 'waiting-black' : 'waiting-white'}.svg`)}/> : roundingNumber(address.balance) } ETH </div> <div class="import" onClick={() => getAddress(address)}> {props.translate("import.import") || "Import"} </div> </div> </div> ) }) return currentListHtml; } function getListPathHtml() { return ( <PathSelector listItem={props.allDPaths} choosePath={choosePath} walletType={props.walletType} currentDPath={props.currentDPath} analytics={props.analytics} /> ) } function getSelectAddressHtml() { return ( <div className={"import-modal"}> <div class="import-modal__header cold-wallet"> <div className="import-modal__header--title"> {props.translate(`modal.select_${props.walletType}_address`) || 'Select address'} </div> <div class="x" onClick={props.onRequestClose}>&times;</div> </div> <div class="import-modal__body"> <div class="cold-wallet__path"> <div class="cold-wallet__path--title"> {props.translate("modal.select_hd_path") || "Select HD derivation path"} </div> <div className="cold-wallet__path--choose-path theme__background-44"> {getListPathHtml()} </div> </div> {props.isLoading && ( <div className="text-center"> <img src={require(`../../../assets/img/${props.theme === 'dark' ? 'waiting-black' : 'waiting-white'}.svg`)}/> </div> )} {!props.isLoading && ( <div className="cold-wallet__address theme__text-6"> <div className="cold-wallet__address--title"> {props.translate("modal.select_address") || "Select the address you would like to interact with"} </div> <div className="address-list animated fadeIn"> {getCurrentList()} </div> </div> )} </div> <div className={"import-modal__footer import-modal__footer--cold-wallet theme__background-2"}> <div className={'address-button address-button-previous ' + (props.isFirstList ? 'disabled' : '')} onClick={props.getPreAddress}> <div className={"address-arrow address-arrow-left theme__arrow-icon"}/> </div> <div className="address-button address-button-next" onClick={props.getMoreAddress}> <div className={"address-arrow address-arrow-right theme__arrow-icon"}/> </div> </div> </div> ) } return ([ <div key='coldwallet'>{props.content}</div>, <SelectAddressModal key="modal" isOpen={props.modalOpen} onRequestClose={props.onRequestClose} content={getSelectAddressHtml()} translate={props.translate} walletType={props.walletType} /> ]) } export default ImportByDeviceView
KyberNetwork/KyberWallet
src/js/components/ImportAccount/ImportByDeviceView.js
JavaScript
mit
4,782
// Copyright (c) 2014 The Bitcoin Core developers // Copyright (c) 2014-2015 The Singularity developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/transaction.h" #include "main.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(main_tests) BOOST_AUTO_TEST_CASE(subsidy_limit_test) { CAmount nSum = 0; for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) { /* @TODO fix subsidity, add nBits */ CAmount nSubsidy = GetBlockValue(0, nHeight, 0); BOOST_CHECK(nSubsidy <= 25 * COIN); nSum += nSubsidy * 1000; BOOST_CHECK(MoneyRange(nSum)); } BOOST_CHECK(nSum == 1350824726649000ULL); } BOOST_AUTO_TEST_SUITE_END()
grumpydevelop/singularity
src/test/main_tests.cpp
C++
mit
806
class FixColumnName < ActiveRecord::Migration def change rename_column :posts, :user, :username rename_column :tagged_posts, :user, :username add_column :posts, :likes, :integer add_column :tagged_posts, :likes, :integer end end
joannangx/visionaria_app
db/migrate/20161029100010_fix_column_name.rb
Ruby
mit
254
package iso20022 // Details of the securities trade. type SecuritiesTradeDetails54 struct { // Reference assigned to the trade by the investor or the trading party. This reference will be used throughout the trade life cycle to access/update the trade details. TradeIdentification []*Max35Text `xml:"TradId,omitempty"` // Unambiguous identification of a collateral transaction as assigned by the instructing party. CollateralTransactionIdentification []*Max35Text `xml:"CollTxId,omitempty"` // Identification of an account owner transaction that could potentially match with the allegement notified. AccountOwnerTransactionIdentification []*Max35Text `xml:"AcctOwnrTxId,omitempty"` // Identification of the transaction assigned by the processor of the instruction other than the account owner the account servicer and the market infrastructure. ProcessorTransactionIdentification *Max35Text `xml:"PrcrTxId,omitempty"` // Market in which a trade transaction has been executed. PlaceOfTrade *PlaceOfTradeIdentification1 `xml:"PlcOfTrad,omitempty"` // Infrastructure which may be a component of a clearing house and which facilitates clearing and settlement for its members by standing between the buyer and the seller. It may net transactions and it substitutes itself as settlement counterparty for each position. PlaceOfClearing *PlaceOfClearingIdentification1 `xml:"PlcOfClr,omitempty"` // Specifies the date/time on which the trade was executed. TradeDate *TradeDate5Choice `xml:"TradDt,omitempty"` // Date and time at which the securities are to be delivered or received. SettlementDate *SettlementDate9Choice `xml:"SttlmDt"` // Specifies the price of the traded financial instrument. // This is the deal price of the individual trade transaction. // If there is only one trade transaction for the execution of the trade, then the deal price could equal the executed trade price (unless, for example, the price includes commissions or rounding, or some other factor has been applied to the deal price or the executed trade price, or both). DealPrice *Price2 `xml:"DealPric,omitempty"` // Number of days on which the interest rate accrues (daily accrual note). NumberOfDaysAccrued *Max3Number `xml:"NbOfDaysAcrd,omitempty"` // Indicates the conditions under which the order/trade is to be/was executed. TradeTransactionCondition []*TradeTransactionCondition5Choice `xml:"TradTxCond,omitempty"` // Specifies the type of price and information about the price. TypeOfPrice *TypeOfPrice29Choice `xml:"TpOfPric,omitempty"` } func (s *SecuritiesTradeDetails54) AddTradeIdentification(value string) { s.TradeIdentification = append(s.TradeIdentification, (*Max35Text)(&value)) } func (s *SecuritiesTradeDetails54) AddCollateralTransactionIdentification(value string) { s.CollateralTransactionIdentification = append(s.CollateralTransactionIdentification, (*Max35Text)(&value)) } func (s *SecuritiesTradeDetails54) AddAccountOwnerTransactionIdentification(value string) { s.AccountOwnerTransactionIdentification = append(s.AccountOwnerTransactionIdentification, (*Max35Text)(&value)) } func (s *SecuritiesTradeDetails54) SetProcessorTransactionIdentification(value string) { s.ProcessorTransactionIdentification = (*Max35Text)(&value) } func (s *SecuritiesTradeDetails54) AddPlaceOfTrade() *PlaceOfTradeIdentification1 { s.PlaceOfTrade = new(PlaceOfTradeIdentification1) return s.PlaceOfTrade } func (s *SecuritiesTradeDetails54) AddPlaceOfClearing() *PlaceOfClearingIdentification1 { s.PlaceOfClearing = new(PlaceOfClearingIdentification1) return s.PlaceOfClearing } func (s *SecuritiesTradeDetails54) AddTradeDate() *TradeDate5Choice { s.TradeDate = new(TradeDate5Choice) return s.TradeDate } func (s *SecuritiesTradeDetails54) AddSettlementDate() *SettlementDate9Choice { s.SettlementDate = new(SettlementDate9Choice) return s.SettlementDate } func (s *SecuritiesTradeDetails54) AddDealPrice() *Price2 { s.DealPrice = new(Price2) return s.DealPrice } func (s *SecuritiesTradeDetails54) SetNumberOfDaysAccrued(value string) { s.NumberOfDaysAccrued = (*Max3Number)(&value) } func (s *SecuritiesTradeDetails54) AddTradeTransactionCondition() *TradeTransactionCondition5Choice { newValue := new(TradeTransactionCondition5Choice) s.TradeTransactionCondition = append(s.TradeTransactionCondition, newValue) return newValue } func (s *SecuritiesTradeDetails54) AddTypeOfPrice() *TypeOfPrice29Choice { s.TypeOfPrice = new(TypeOfPrice29Choice) return s.TypeOfPrice }
fgrid/iso20022
SecuritiesTradeDetails54.go
GO
mit
4,526
const Discord = require('discord.js'); const client = new Discord.Client({ forceFetchUsers: true, autoReconnect: true, disableEveryone: true, }); const settings = require('./auth.json'); const chalk = require('chalk'); const fs = require('fs'); const moment = require('moment'); require('./util/eventLoader')(client); client.on('message', function (message) { if (message.channel.isPrivate) { return; } if (message.everyoneMentioned) { return; } if (message.type === 'dm') { return; } }); const log = message => { console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] ${message}`); }; client.commands = new Discord.Collection(); client.aliases = new Discord.Collection(); fs.readdir('./commands/', (err, files) => { if (err) console.error(err); log(`Loading a total of ${files.length} commands.`); files.forEach(f => { let props = require(`./commands/${f}`); log(`Loading Command: ${props.help.name}. ✔️`); client.commands.set(props.help.name, props); props.conf.aliases.forEach(alias => { client.aliases.set(alias, props.help.name); }); }); }); client.reload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./commands/${command}`)]; let cmd = require(`./commands/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.elevation = message => { /* This function should resolve to an ELEVATION level which is then sent to the command handler for verification*/ if(!message.guild) return; let permlvl = 0; let follower = message.guild.roles.find('name', settings.followerrolename); if (follower && message.member.roles.has(follower.id)) permlvl = 1; let player = message.guild.roles.find('name', settings.playerrolename); if (player && message.member.roles.has(player.id)) permlvl = 2; let overseer = message.guild.roles.find('name', settings.overseerrolename); if (overseer && message.member.roles.has(overseer.id)) permlvl = 3; let trusted = message.guild.roles.find('name', settings.trustedrolename); if (trusted && message.member.roles.has(trusted.id)) permlvl = 4; let overlord = message.guild.roles.find('name', settings.overlordrolename); if (overlord && message.member.roles.has(overlord.id)) permlvl = 5; if (message.author.id === settings.ownerid) permlvl = 5; return permlvl; }; // var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g; // // client.on('warn', e => { // console.log(chalk.bgYellow(e.replace(regToken, 'that was redacted'))); // }); // // client.on('error', e => { // console.log(chalk.bgRed(e.replace(regToken, 'that was redacted'))); // }); client.login(settings.token);
Ryahn/SoEBot
bot.js
JavaScript
mit
2,929
# -*- coding: utf-8 -*- """ flask_via.examples.basic ======================== A simple ``Flask-Via`` example Flask application. """ from flask import Flask from flask.ext.via import Via from flask.ext.via.routers.default import Functional app = Flask(__name__) def foo(bar=None): return 'Functional Foo View!' routes = [ Functional('/foo', foo), Functional('/foo/<bar>', foo, endpoint='foo2'), ] via = Via() via.init_app(app, routes_module='flask_via.examples.basic') if __name__ == "__main__": app.run(debug=True)
thisissoon/Flask-Via
flask_via/examples/basic.py
Python
mit
542
<?php use App\Match; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\Schema; class CreateMatchesTable extends Migration { public function up() { Schema::create('matches', function(Blueprint $table) { $table->increments('id'); $table->integer('tournamentId')->unsigned(); $table->integer('homeTournamentTeamId')->unsigned(); $table->integer('awayTournamentTeamId')->unsigned(); $table->tinyInteger('homeScore')->unsigned(); $table->tinyInteger('awayScore')->unsigned(); $table->tinyInteger('homePenaltyScore')->unsigned(); $table->tinyInteger('awayPenaltyScore')->unsigned(); $table->enum('gameType', Match::getAvailableGameTypes()); $table->enum('resultType', Match::getAvailableResultTypes()); $table->enum('status', Match::getAvailableStatuses())->default(Match::STATUS_NOT_STARTED); $table->timestamps(); }); Schema::table('matches', function(Blueprint $table) { $table->foreign('homeTournamentTeamId')->references('id')->on('tournament_teams') ->onDelete('restrict') ->onUpdate('restrict'); $table->foreign('awayTournamentTeamId')->references('id')->on('tournament_teams') ->onDelete('restrict') ->onUpdate('restrict'); }); } public function down() { Schema::drop('matches'); } }
nixsolutions/ggf
database/migrations/2015_07_07_144512_create_matches_table.php
PHP
mit
1,556
require('server.babel'); // babel registration (runtime transpilation for node) const path = require('path'); const LodashModuleReplacementPlugin = require('lodash-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const autoprefixer = require('autoprefixer'); const webpack = require('webpack'); const webpackIsomorphicToolsConfig = require('./webpack-isomorphic-tools'); const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin'); const webpackIsomorphicTools = new WebpackIsomorphicToolsPlugin( webpackIsomorphicToolsConfig ); module.exports = { performance: { hints: false, }, context: path.resolve('./'), entry: { main: [ 'src/less/styles.less', // entry point for styles 'src/js/client.jsx', // entry point for js ], }, output: { path: path.resolve('public/assets'), filename: '[name]-[hash].js', chunkFilename: '[name]-[chunkhash].js', publicPath: '/assets/', }, module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, use: [ { loader: 'babel-loader', options: { cacheDirectory: true, // disable babel sourcemaps to see the transpiled code when debugging sourceMap: false, plugins: ['lodash'], }, }, ], }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { sourceMap: false, importLoaders: 1, }, }, { loader: 'postcss-loader', options: { sourceMap: false, plugins() { return [autoprefixer]; }, }, }, ], }), }, { test: /\.less$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { sourceMap: false, minimize: true, importLoaders: 2, }, }, { loader: 'postcss-loader', options: { sourceMap: false, plugins() { return [autoprefixer]; }, }, }, { loader: 'less-loader', options: { sourceMap: false, }, }, ], }), }, { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff', }, }, // loader: 'url?limit=10000&mimetype=application/font-woff', }, { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff', }, }, // loader: 'url?limit=10000&mimetype=application/font-woff', }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/octet-stream', }, }, // loader: 'url?limit=10000&mimetype=application/octet-stream', }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/vnd.ms-fontobject', }, }, }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'image/svg+xml', }, }, }, { test: /\.otf(\?v=\d+\.\d+\.\d+)?$/, use: ['file-loader'], }, { test: webpackIsomorphicTools.regular_expression('images'), use: { loader: 'url-loader', options: { limit: 10240, }, }, // loader: 'url-loader?limit=10240', }, ], }, resolve: { modules: ['./', 'node_modules'], extensions: ['.json', '.js', '.jsx'], }, plugins: [ new ExtractTextPlugin({ filename: '[name]-[chunkhash].css', allChunks: true, }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"', }, __CLIENT__: true, __DEVTOOLS__: false, }), new LodashModuleReplacementPlugin({ // collections: true, // shorthands: true }), // ignore dev config new webpack.IgnorePlugin(/\.\/dev/, /\/config$/), // optimizations new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, sourceMap: false, }), webpackIsomorphicTools, ], };
sankalplakhina/isomorphic-universal-react-redux-boilerplate-seed
webpack/prod.config.js
JavaScript
mit
5,226
using System.ComponentModel.DataAnnotations; namespace OptionsWebSite.ViewModels.Account { public class ExternalLoginConfirmationViewModel { [Required] [EmailAddress] public string Email { get; set; } } }
FriendlyNPC/MVC6_Mac
OptionsWebsite/ViewModels/Account/ExternalLoginConfirmationViewModel.cs
C#
mit
253
package com.dev.lambda.demo; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.junit.BeforeClass; import org.junit.Test; import com.amazonaws.services.lambda.runtime.Context; import com.dev.lambda.demo.model.Input; /** * A simple test harness for locally invoking your Lambda function handler. */ public class LambdaFunctionHandlerTest { private static Input input; @BeforeClass public static void createInput() throws IOException { // TODO: set up your sample input object here. input = new Input(); } private Context createContext() { TestContext ctx = new TestContext(); // TODO: customize your context here if needed. ctx.setFunctionName("Your Function Name"); return ctx; } @Test public void testLambdaFunctionHandler() { LambdaFunctionHandler handler = new LambdaFunctionHandler(); Context ctx = createContext(); String output = handler.handleRequest(input, ctx); // TODO: validate output here if needed. //Assert.assertEquals("Hello from Lambda!", output); } }
kaulavinash/berryme
src/test/java/com/dev/lambda/demo/LambdaFunctionHandlerTest.java
Java
mit
1,143
/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *****************************************************************************/ package org.openni.android.tools.niviewer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.res.Configuration; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.Toast; import org.openni.Device; import org.openni.DeviceInfo; import org.openni.OpenNI; import org.openni.Recorder; import org.openni.android.OpenNIHelper; import org.openni.android.tools.niviewer.StreamView; public class NiViewerActivity extends Activity implements OpenNIHelper.DeviceOpenListener { private Installation installation; private static final String TAG = "NiViewer"; private OpenNIHelper mOpenNIHelper; private boolean mDeviceOpenPending = false; private Device mDevice; private Recorder mRecorder; private String mRecordingName; private String mRecording; private LinearLayout mStreamsContainer; private int mActiveDeviceID = -1; private void toast(String message) { Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT); toast.show(); } @Override protected void onCreate(Bundle savedInstanceState) { MyToaster.setContext(this); Log.d(TAG, "onCreate"); installation = new Installation(); if (installation.execute()) { Log.d(TAG, "ROOT commands executed."); } else { toast("Not running as ROOT."); Log.d(TAG, "Not running as ROOT."); } MyNetworkManager nm = new MyNetworkManager(this); nm.startup(); mOpenNIHelper = new OpenNIHelper(this); //OpenNI.setLogAndroidOutput(true); //OpenNI.setLogMinSeverity(0); OpenNI.initialize(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_niviewer); mStreamsContainer = (LinearLayout)findViewById(R.id.streams_container); onConfigurationChanged(getResources().getConfiguration()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.niviewer_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.record: toggleRecording(item); return true; case R.id.add_stream: addStream(); return true; case R.id.device: switchDevice(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); mOpenNIHelper.shutdown(); OpenNI.shutdown(); } @Override protected void onStart() { Log.d(TAG, "onStart"); super.onStart(); final android.content.Intent intent = getIntent (); if (intent != null) { final android.net.Uri data = intent.getData (); if (data != null) { mRecording = data.getEncodedPath (); Log.d(TAG, "Will open file " + mRecording); } } } @Override protected void onResume() { Log.d(TAG, "onResume"); super.onResume(); // onResume() is called after the USB permission dialog is closed, in which case, we don't want // to request device permissions again if (mDeviceOpenPending) { return; } // Request opening the first OpenNI-compliant device found String uri; if (mRecording != null) { uri = mRecording; } else { List<DeviceInfo> devices = OpenNI.enumerateDevices(); if (devices.isEmpty()) { showAlertAndExit("No OpenNI-compliant device found."); return; } uri = devices.get(devices.size() - 1).getUri(); } mDeviceOpenPending = true; mOpenNIHelper.requestDeviceOpen(uri, this); } @Override public void onConfigurationChanged(Configuration config) { Log.d(TAG, "onConfigurationChanged"); if (Configuration.ORIENTATION_PORTRAIT == config.orientation) { mStreamsContainer.setOrientation(LinearLayout.VERTICAL); } else { mStreamsContainer.setOrientation(LinearLayout.HORIZONTAL); } //Re-insert each view to force correct display (forceLayout() doesn't work) for (StreamView streamView : getStreamViews()) { mStreamsContainer.removeView(streamView); setStreamViewLayout(streamView, config); mStreamsContainer.addView(streamView); } super.onConfigurationChanged(config); } private void showAlert(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message); builder.show(); } private void showAlertAndExit(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message); builder.setNeutralButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.show(); } @Override public void onDeviceOpened(Device aDevice) { Log.d(TAG, "Permission granted for device " + aDevice.getDeviceInfo().getUri()); mDeviceOpenPending = false; mDevice = aDevice; //Find device ID List<DeviceInfo> devices = OpenNI.enumerateDevices(); for(int i=0; i < devices.size(); i++) { if(devices.get(i).getUri().equals(mDevice.getDeviceInfo().getUri())){ mActiveDeviceID = i; break; } } for (StreamView streamView : getStreamViews()) { streamView.setDevice(mDevice); } mStreamsContainer.requestLayout(); addStream(); } private void setStreamViewLayout(StreamView streamView, Configuration config) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); if (config.orientation == Configuration.ORIENTATION_PORTRAIT) { params.width = LayoutParams.WRAP_CONTENT; params.height = 0; } else { params.width = 0; params.height = LayoutParams.WRAP_CONTENT; } params.weight = 1; params.gravity = Gravity.CENTER; streamView.setLayoutParams(params); } private void addStream() { StreamView streamView = new StreamView(this); setStreamViewLayout(streamView, getResources().getConfiguration()); streamView.setDevice(mDevice); mStreamsContainer.addView(streamView); mStreamsContainer.requestLayout(); } @SuppressLint("SimpleDateFormat") private void toggleRecording(MenuItem item) { if (mRecorder == null) { mRecordingName = Environment.getExternalStorageDirectory().getPath() + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".oni"; try { mRecorder = Recorder.create(mRecordingName); for (StreamView streamView : getStreamViews()) { mRecorder.addStream(streamView.getStream(), true); } mRecorder.start(); } catch (RuntimeException ex) { mRecorder = null; showAlert("Failed to start recording: " + ex.getMessage()); return; } item.setTitle(R.string.stop_record); } else { stopRecording(); item.setTitle(R.string.start_record); } } private void stopRecording() { if (mRecorder != null) { mRecorder.stop(); mRecorder.destroy(); mRecorder = null; showAlert("Recording saved to: " + mRecordingName); mRecordingName = null; } } private void switchDevice() { List<DeviceInfo> devices = OpenNI.enumerateDevices(); if (devices.isEmpty()) { showAlertAndExit("No OpenNI-compliant device found."); return; } new DeviceSelectDialog().showDialog(devices, mActiveDeviceID, this); } public void openDevice(String deviceURI) { if (mDeviceOpenPending) { return; } stopRecording(); for (StreamView streamView : getStreamViews()) { streamView.stop(); mStreamsContainer.removeView(streamView); } if (mDevice != null) { mDevice.close(); } mDeviceOpenPending = true; mOpenNIHelper.requestDeviceOpen(deviceURI, this); } @Override public void onDeviceOpenFailed(String uri) { Log.e(TAG, "Failed to open device " + uri); mDeviceOpenPending = false; showAlertAndExit("Failed to open device"); } @Override protected void onPause() { Log.d(TAG, "onPause"); super.onPause(); // onPause() is called just before the USB permission dialog is opened, in which case, we don't // want to shutdown OpenNI if (mDeviceOpenPending) return; stopRecording(); for (StreamView streamView : getStreamViews()) { streamView.stop(); } if (mDevice != null) { mDevice.close(); mDevice = null; } } private List<StreamView> getStreamViews() { int count = mStreamsContainer.getChildCount(); ArrayList<StreamView> list = new ArrayList<StreamView>(count); for (int i = 0; i < count; ++i) { StreamView view = (StreamView)mStreamsContainer.getChildAt(i); list.add(view); } return list; } }
Windowsfreak/NIStreamer
Android/NiViewer.Android/src/org/openni/android/tools/niviewer/NiViewerActivity.java
Java
mit
10,505
<?php namespace Vision\DependencyInjection; use Psr\Container\NotFoundExceptionInterface; use RuntimeException; class NotFoundException extends RuntimeException implements NotFoundExceptionInterface { }
Trainmaster/Vision
src/DependencyInjection/NotFoundException.php
PHP
mit
206
<?php defined('KOHANASYSPATH') or die('No direct script access.'); /** * UTF8::from_unicode * * @package Kohana * @author Kohana Team * @copyright (c) 2007-2011 Kohana Team * @copyright (c) 2005 Harry Fuecks * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt */ function _from_unicode($arr) { ob_start(); $keys = array_keys($arr); foreach ($keys as $k) { // ASCII range (including control chars) if (($arr[$k] >= 0) AND ($arr[$k] <= 0x007f)) { echo chr($arr[$k]); } // 2 byte sequence elseif ($arr[$k] <= 0x07ff) { echo chr(0xc0 | ($arr[$k] >> 6)); echo chr(0x80 | ($arr[$k] & 0x003f)); } // Byte order mark (skip) elseif ($arr[$k] == 0xFEFF) { // nop -- zap the BOM } // Test for illegal surrogates elseif ($arr[$k] >= 0xD800 AND $arr[$k] <= 0xDFFF) { // Found a surrogate trigger_error('UTF8::from_unicode: Illegal surrogate at index: '.$k.', value: '.$arr[$k], E_USER_WARNING); return FALSE; } // 3 byte sequence elseif ($arr[$k] <= 0xffff) { echo chr(0xe0 | ($arr[$k] >> 12)); echo chr(0x80 | (($arr[$k] >> 6) & 0x003f)); echo chr(0x80 | ($arr[$k] & 0x003f)); } // 4 byte sequence elseif ($arr[$k] <= 0x10ffff) { echo chr(0xf0 | ($arr[$k] >> 18)); echo chr(0x80 | (($arr[$k] >> 12) & 0x3f)); echo chr(0x80 | (($arr[$k] >> 6) & 0x3f)); echo chr(0x80 | ($arr[$k] & 0x3f)); } // Out of range else { trigger_error('UTF8::from_unicode: Codepoint out of Unicode range at index: '.$k.', value: '.$arr[$k], E_USER_WARNING); return FALSE; } } $result = ob_get_contents(); ob_end_clean(); return $result; }
ivantcholakov/codeigniter-utf8
application/third_party/kohana/utf8/from_unicode.php
PHP
mit
1,718
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jms.connection; import java.lang.reflect.Method; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Session; import javax.jms.TransactionInProgressException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.transaction.support.ResourceHolderSupport; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils; /** * JMS resource holder, wrapping a JMS Connection and a JMS Session. * JmsTransactionManager binds instances of this class to the thread, * for a given JMS ConnectionFactory. * * <p>Note: This is an SPI class, not intended to be used by applications. * * @author Juergen Hoeller * @since 1.1 * @see JmsTransactionManager * @see org.springframework.jms.core.JmsTemplate */ public class JmsResourceHolder extends ResourceHolderSupport { private static final Log logger = LogFactory.getLog(JmsResourceHolder.class); private ConnectionFactory connectionFactory; private boolean frozen = false; private final List<Connection> connections = new LinkedList<>(); private final List<Session> sessions = new LinkedList<>(); private final Map<Connection, List<Session>> sessionsPerConnection = new HashMap<>(); /** * Create a new JmsResourceHolder that is open for resources to be added. * @see #addConnection * @see #addSession */ public JmsResourceHolder() { } /** * Create a new JmsResourceHolder that is open for resources to be added. * @param connectionFactory the JMS ConnectionFactory that this * resource holder is associated with (may be {@code null}) */ public JmsResourceHolder(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } /** * Create a new JmsResourceHolder for the given JMS Session. * @param session the JMS Session */ public JmsResourceHolder(Session session) { addSession(session); this.frozen = true; } /** * Create a new JmsResourceHolder for the given JMS resources. * @param connection the JMS Connection * @param session the JMS Session */ public JmsResourceHolder(Connection connection, Session session) { addConnection(connection); addSession(session, connection); this.frozen = true; } /** * Create a new JmsResourceHolder for the given JMS resources. * @param connectionFactory the JMS ConnectionFactory that this * resource holder is associated with (may be {@code null}) * @param connection the JMS Connection * @param session the JMS Session */ public JmsResourceHolder(ConnectionFactory connectionFactory, Connection connection, Session session) { this.connectionFactory = connectionFactory; addConnection(connection); addSession(session, connection); this.frozen = true; } public final boolean isFrozen() { return this.frozen; } public final void addConnection(Connection connection) { Assert.isTrue(!this.frozen, "Cannot add Connection because JmsResourceHolder is frozen"); Assert.notNull(connection, "Connection must not be null"); if (!this.connections.contains(connection)) { this.connections.add(connection); } } public final void addSession(Session session) { addSession(session, null); } public final void addSession(Session session, Connection connection) { Assert.isTrue(!this.frozen, "Cannot add Session because JmsResourceHolder is frozen"); Assert.notNull(session, "Session must not be null"); if (!this.sessions.contains(session)) { this.sessions.add(session); if (connection != null) { List<Session> sessions = this.sessionsPerConnection.get(connection); if (sessions == null) { sessions = new LinkedList<>(); this.sessionsPerConnection.put(connection, sessions); } sessions.add(session); } } } public boolean containsSession(Session session) { return this.sessions.contains(session); } public Connection getConnection() { return (!this.connections.isEmpty() ? this.connections.get(0) : null); } public Connection getConnection(Class<? extends Connection> connectionType) { return CollectionUtils.findValueOfType(this.connections, connectionType); } public Session getSession() { return (!this.sessions.isEmpty() ? this.sessions.get(0) : null); } public Session getSession(Class<? extends Session> sessionType) { return getSession(sessionType, null); } public Session getSession(Class<? extends Session> sessionType, Connection connection) { List<Session> sessions = this.sessions; if (connection != null) { sessions = this.sessionsPerConnection.get(connection); } return CollectionUtils.findValueOfType(sessions, sessionType); } public void commitAll() throws JMSException { for (Session session : this.sessions) { try { session.commit(); } catch (TransactionInProgressException ex) { // Ignore -> can only happen in case of a JTA transaction. } catch (javax.jms.IllegalStateException ex) { if (this.connectionFactory != null) { try { Method getDataSourceMethod = this.connectionFactory.getClass().getMethod("getDataSource"); Object ds = ReflectionUtils.invokeMethod(getDataSourceMethod, this.connectionFactory); while (ds != null) { if (TransactionSynchronizationManager.hasResource(ds)) { // IllegalStateException from sharing the underlying JDBC Connection // which typically gets committed first, e.g. with Oracle AQ --> ignore return; } try { // Check for decorated DataSource a la Spring's DelegatingDataSource Method getTargetDataSourceMethod = ds.getClass().getMethod("getTargetDataSource"); ds = ReflectionUtils.invokeMethod(getTargetDataSourceMethod, ds); } catch (NoSuchMethodException nsme) { ds = null; } } } catch (Throwable ex2) { if (logger.isDebugEnabled()) { logger.debug("No working getDataSource method found on ConnectionFactory: " + ex2); } // No working getDataSource method - cannot perform DataSource transaction check } } throw ex; } } } public void closeAll() { for (Session session : this.sessions) { try { session.close(); } catch (Throwable ex) { logger.debug("Could not close synchronized JMS Session after transaction", ex); } } for (Connection con : this.connections) { ConnectionFactoryUtils.releaseConnection(con, this.connectionFactory, true); } this.connections.clear(); this.sessions.clear(); this.sessionsPerConnection.clear(); } }
boggad/jdk9-sample
sample-catalog/spring-jdk9/src/spring.jms/org/springframework/jms/connection/JmsResourceHolder.java
Java
mit
7,474
<?php namespace GRT\MainBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class GRTMainBundle extends Bundle { }
mwd410/GRT-Interview
src/GRT/MainBundle/GRTMainBundle.php
PHP
mit
122
import { Component, Inject, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AuthService } from './auth.service'; import { IToastr, TOASTR_TOKEN } from '../common/toastr.service'; @Component({ templateUrl: 'app/user/profile.component.html', styles: [ ` em {float:right;color:#e05c65;padding-left:10px;} .error input{background-color:#e3c3c5;} .error ::-webkit-input-placeholder {color:#999;} .error ::-moz-placeholder {color:#999;} .error :-ms-input-placeholder {color:#999;} `, ], }) export class ProfileComponent implements OnInit { profileForm: FormGroup; private firstName: FormControl; private lastName: FormControl; constructor( private authService: AuthService, private router: Router, @Inject(TOASTR_TOKEN) private toastr: IToastr) { } ngOnInit() { this.firstName = new FormControl( this.authService.currentUser.firstName, [Validators.required, Validators.pattern('[a-zA-Z].*')]); this.lastName = new FormControl(this.authService.currentUser.lastName, Validators.required); this.profileForm = new FormGroup({ firstName: this.firstName, lastName: this.lastName, }); } cancel() { this.router.navigate(['events']) } saveProfile(formValues) { if (this.profileForm.valid) { this.authService.updateCurrentUser(formValues.firstName, formValues.lastName) .subscribe(() => { this.toastr.success('Profile saved successfully!'); }); // this.router.navigate(['events']) } } validateFirstName() { return this.firstName.valid || this.firstName.untouched; } validateLastName() { return this.lastName.valid || this.lastName.untouched; } logout(){ this.authService.logout().subscribe(()=> { this.router.navigate(['/user/login']); }); } }
AdamNagy/FrontendTryouts
Angular/EventManager/app/user/profile.component.ts
TypeScript
mit
1,870
require('dotenv').config(); import http from 'http'; import https from 'https'; import Koa from 'koa'; import Io from 'socket.io'; import KoaBody from 'koa-body'; import cors from 'kcors'; import Router from 'koa-router'; import Socket from './socket'; import crypto from 'crypto'; import mailer from './utils/mailer'; import koaStatic from 'koa-static'; import koaSend from 'koa-send'; import { pollForInactiveRooms } from './inactive_rooms'; import getStore from './store'; const env = process.env.NODE_ENV || 'development'; const app = new Koa(); const PORT = process.env.PORT || 3001; const router = new Router(); const koaBody = new KoaBody(); const appName = process.env.HEROKU_APP_NAME; const isReviewApp = /-pr-/.test(appName); const siteURL = process.env.SITE_URL; const store = getStore(); if ((siteURL || env === 'development') && !isReviewApp) { app.use( cors({ origin: env === 'development' ? '*' : siteURL, allowMethods: ['GET', 'HEAD', 'POST'], credentials: true, }), ); } router.post('/abuse/:roomId', koaBody, async ctx => { let { roomId } = ctx.params; roomId = roomId.trim(); if (process.env.ABUSE_FROM_EMAIL_ADDRESS && process.env.ABUSE_TO_EMAIL_ADDRESS) { const abuseForRoomExists = await store.get('abuse', roomId); if (!abuseForRoomExists) { mailer.send({ from: process.env.ABUSE_FROM_EMAIL_ADDRESS, to: process.env.ABUSE_TO_EMAIL_ADDRESS, subject: 'Darkwire Abuse Notification', text: `Room ID: ${roomId}`, }); } } await store.inc('abuse', roomId); ctx.status = 200; }); app.use(router.routes()); const apiHost = process.env.API_HOST; const cspDefaultSrc = `'self'${apiHost ? ` https://${apiHost} wss://${apiHost}` : ''}`; function setStaticFileHeaders(ctx) { ctx.set({ 'strict-transport-security': 'max-age=31536000', 'Content-Security-Policy': `default-src ${cspDefaultSrc} 'unsafe-inline'; img-src 'self' data:;`, 'X-Frame-Options': 'deny', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', 'Feature-Policy': "geolocation 'none'; vr 'none'; payment 'none'; microphone 'none'", }); } const clientDistDirectory = process.env.CLIENT_DIST_DIRECTORY; if (clientDistDirectory) { app.use(async (ctx, next) => { setStaticFileHeaders(ctx); await koaStatic(clientDistDirectory, { maxage: ctx.req.url === '/' ? 60 * 1000 : 365 * 24 * 60 * 60 * 1000, // one minute in ms for html doc, one year for css, js, etc })(ctx, next); }); app.use(async ctx => { setStaticFileHeaders(ctx); await koaSend(ctx, 'index.html', { root: clientDistDirectory }); }); } else { app.use(async ctx => { ctx.body = { ready: true }; }); } const protocol = (process.env.PROTOCOL || 'http') === 'http' ? http : https; const server = protocol.createServer(app.callback()); const io = Io(server, { pingInterval: 20000, pingTimeout: 5000, }); // Only use socket adapter if store has one if (store.hasSocketAdapter) { io.adapter(store.getSocketAdapter()); } const roomHashSecret = process.env.ROOM_HASH_SECRET; const getRoomIdHash = id => { if (env === 'development') { return id; } if (roomHashSecret) { return crypto.createHmac('sha256', roomHashSecret).update(id).digest('hex'); } return crypto.createHash('sha256').update(id).digest('hex'); }; export const getIO = () => io; io.on('connection', async socket => { const roomId = socket.handshake.query.roomId; const roomIdHash = getRoomIdHash(roomId); let room = await store.get('rooms', roomIdHash); room = JSON.parse(room || '{}'); new Socket({ roomIdOriginal: roomId, roomId: roomIdHash, socket, room, }); }); const init = async () => { server.listen(PORT, () => { console.log(`Darkwire is online at port ${PORT}`); }); pollForInactiveRooms(); }; init();
seripap/darkwire.io
server/src/index.js
JavaScript
mit
3,919