content
stringlengths
10
4.9M
// Check that mallopt does not return invalid values (ex. -1). // RUN: %clangxx -O2 %s -o %t && %run %t #include <assert.h> #include <malloc.h> int main() { // Try a random mallopt option, possibly invalid. int res = mallopt(-42, 0); assert(res == 0 || res == 1); }
<reponame>Ozcry/PythonExercicio '''Faça um programa que leia três números e mostre qual é o maior e qual é o menor.''' n1 = float(input('\033[30mDigite o primeiro número:\033[m ')) n2 = float(input('\033[31mDigite o segundo número:\033[m ')) n3 = float(input('\033[32mDigite o terceiro número:\033[m ')) if n1 > n2 and n1 > n3: print('\033[33mMaior número\033[m {}{:.1f}{}'.format('\033[31m', n1, '\033[m')) if n2 > n1 and n2 > n3: print('\033[34mMaior número\033[m {}{:.1f}{}'.format('\033[32m', n2, '\033[m')) if n3 > n1 and n3 > n2: print('\033[35mMaior número\033[m {}{:.1f}{}'.format('\033[33m', n3, '\033[m')) if n1 < n2 and n1 < n3: print('\033[36mMenor número\033[m {}{:.1f}{}'.format('\033[34m', n1, '\033[m')) if n2 < n1 and n2 < n3: print('\033[37mMenor número\033[m {}{:.1f}{}'.format('\033[35m', n2, '\033[m')) if n3 < n1 and n3 < n2: print('\033[30mMenor número\033[m {}{:.1f}{}'.format('\033[36m', n3, '\033[m')) print('\033[33m----------\033[m')
After leaving the president's office vacant for 18 months, the Montreal Alouettes opted to hire from within. The Canadian Football League club announced Tuesday that Mark Weightman, the former Chief Operating Officer, will be the new president and CEO. Weightman, 41, had been filling the president's duties anyway since Ray Lalonde stepped down in May 2012 after only 14 months on the job. "We asked Mark to lead our franchise," said Andrew Wetenhall, the son of owner Bob Wetenhall who was unable to attend the announcement due to a flu. "He's proven himself time and again." Weightman has been with the franchise since 1995 when he worked for the defunct Baltimore Stallions. The native of St. Andre d'Argenteuil, Que., moved with them to Montreal the following year and stayed on when Wetenhall bought the team from Jim Spiros in 1997. His first priority will be to fill Percival Molson Stadium, which has had empty seats since it was expanded from 20,202 seats to 25,012 in 2010. The Alouettes used to sell out the smaller stadium every game, but have generally drawn about 23,000 since the expansion. "It's a pretty high priority," said Wetenhall, a New York investment banker who is a CFL governor. "It's a marker of our commercial success and our on-field and community success to secure that support. "At the same time, we're not in an at-all-costs type of mentality. We need to correctly approach the marketplace and put a winning team on the field to enable people to say 'I've got to go to that event."' The Alouettes went 8-10 this season and lost the East Division semifinal to the Hamilton Tiger-Cats. They have not won a playoff game since winning back to back Grey Cups in 2009 and 2010. The empty seats suggest the Alouettes' popularity is waning, but Weightman said the future looks bright. The season ticket base has remained at about 17,000, but they hope to increase sales through partial season tickets, family packs and other offers. "We're still going through a transition where we have a bigger stadium and people think we're not doing as well because the stadium's not full," said Weightman. "We had 23,000 where we had 20,000 for 10 years. "If you look at TV ratings and how much we're followed on social media, you'll see our fan base is as strong and healthy as ever. But we need to do a better job of reaching out to all our fans." He also hopes to boost the team's community involvement and its support for minor football in Quebec, which are priorities for the Wetenhall family. "In reality, we didn't have a president, so I can't say my role will change a lot, other than that I'll have to get some new business cards," added Weighman. "The important thing is the transition we've done over the last year or so. "We've refocused on the things we've done well over the last 15 years — winning on the field, the great experience in the stadium, and being involved in the community. Now we have to bring that to the next level." A large media contingent turned out to the news conference expecting an announcement on whether general manager Jim Popp will remain as head coach after taking over from the fired Dan Hawkins five games into the season, or on whether 41-year-old quarterback Anthony Calvillo will retire. Instead, it was a day for the men in suits. Weightman said there is no timeline for a decision on the coach, although they would prefer to make one soon so that preparations can start for the 2014 season. The future of veterans like Calvillo, who suffered a season-ending concussion in August, all-star guard Scott Flory or defensive end Anwar Stewart are not expected to be decided until after the CFL expansion draft on Dec. 16. Flory lauded Weightman's appointment. "There's a lot of stuff going on around the league," said Flory. "It's not just our team. "The thing is, to have leadership from the top, you have to have the right people in place. The Alouettes have got it right so many times over the years. I've been here 15 years and played in eight Grey Cups, so we're doing something right." The experiment with Hawkins, who joined the team without any pro coaching experience, was a setback. Another may have been Lalonde's one-season tenure as president and CEO. He left citing personal reasons, but there were reports the former Montreal Canadiens marketing guru was feuding with Popp and former coach Marc Trestman. Lalonde had replaced popular former Alouettes player Larry Smith, who left after the stadium expansion was completed in 2010 to try his hand at politics. Andrew Wetenhall said his family's commitment to the Alouettes and the CFL is as strong as ever. "I certainly am," he said. "We make decisions like this one in a family format. We're very committed to this league and it's success. We've invested 20 years almost in Montreal and we're hopeful there will be another 20 or 50 to come."
// AddressUnspentTransactionDetails this endpoint retrieves transaction details for a given address // Use max transactions to filter if there are more UTXOs returned than needed by the user // // For more information: (custom request for this go package) func (c *Client) AddressUnspentTransactionDetails(address string, maxTransactions int) (history AddressHistory, err error) { var utxos AddressHistory if utxos, err = c.AddressUnspentTransactions(address); err != nil { return } else if len(utxos) == 0 { return } if maxTransactions > 0 { total := len(utxos) if total > maxTransactions { utxos = utxos[:total-(total-maxTransactions)] } } var batches []AddressHistory chunkSize := MaxTransactionsUTXO for i := 0; i < len(utxos); i += chunkSize { end := i + chunkSize if end > len(utxos) { end = len(utxos) } batches = append(batches, utxos[i:end]) } for _, batch := range batches { txHashes := new(TxHashes) for _, utxo := range batch { txHashes.TxIDs = append(txHashes.TxIDs, utxo.TxHash) history = append(history, utxo) } var txList TxList if txList, err = c.BulkTransactionDetails(txHashes); err != nil { return } for index, tx := range txList { for _, utxo := range history { if utxo.TxHash == tx.TxID { utxo.Info = txList[index] continue } } } } return }
/** * Inserts the status updates passed as parameter into the database. It is * synchronous to avoid more than one method trying to insert new updates * into the database. * * Then broadcasts intend RECEIVE_TIMELINE_NOTIFICATIONS if new message was * received. * * @param posts * @param newposts */ @Checkpoint(value = "storeInDB", threadName = "RSSUpdaterThread") public synchronized void storeStatusUpdates(List<ContentValues> posts, long newposts) { Log.d(TAG, "Storing status updates"); for (ContentValues value : posts) { database.insertFeedItems(value); } Log.d(TAG, "We have a new RSSFeed updates"); }
/** * Formats a given number in a default format (3 decimals, padded left to 10 characters). * * @param nr a number * @return a string version of the number */ public static String format(Double nr) { if (nr == null) { return PLACEHOLDER_NULL; } return String.format(FORMAT_NUMBER, nr); }
Produced by The Online Distributed Proofreading Team at http://www.pgdp.net (This file was produced from images generously made available by The Internet Archive) A FLORAL FANTASY IN AN OLD ENGLISH GARDEN BY WALTER CRANE NEW YORK & LONDON HARPER AND BROTHERS [Illustration] [Illustration] [Illustration] [Illustration] A FLORAL FANTASY IN AN OLD ENGLISH GARDEN [Illustration] SET FORTH IN VERSES & COLOURED DESIGNS BY WALTER CRANE LONDON: AT THE HOUSE OF HARPER AND BROTHERS: 1899 [Illustration] THE OLD ENGLISH GARDEN A FLORAL PHANTASY [Illustration] In an old world garden dreaming, Where the flowers had human names, Methought, in fantastic seeming, They disported as squires and dames. [Illustration] Of old in Rosamond's Bower, With it's peacock hedges of yew, One could never find the flower Unless one was given the clue; So take the key of the wicket, Who would follow my fancy free, By formal knot and clipt thicket, And smooth greensward so fair to see [Illustration] And while Time his scythe is whetting, Ere the dew from the grass has gone, [Illustration] The Four Seasons' flight forgetting, As they dance round the dial stone; [Illustration] With a leaf from an old English book, A Jonquil will serve for a pen. [Illustration] Let us note from the green arbour's nook, Flowers masking like women and men. [Illustration] FIRST in VENUS'S LOOKING GLASS, You may see where LOVE LIES BLEEDING, [Illustration] While PRETTY MAIDS all of them pass With careless hearts quite unheeding. [Illustration] Next, a knight with his flaming targe See the DENT-DE-LION so bold With his feathery crest at large, On a field of the cloth of gold. [Illustration] Simple honesty shows in vain A fashion few seek to robe in, While the poor SHEPHERD'S-PURSE is ta'en By rascally RAGGED-ROBIN. [Illustration] COLTSFOOT and LARKSPUR SPEEDWELL [Illustration] In the race of the flowers that's run due, [Illustration] As the HARTSTONGUE pants at the well [Illustration] And the HOUNDSTONGUE laps the SUNDEW. [Illustration] Here's VENUS'-COMBE for MAIDENHAIR: While KING-CUPS drink BELLA-DONNA, [Illustration] Glad in purple and gold so fair, Though the DEADLY NIGHTSHADE'S upon her. [Illustration] Behold LONDON PRIDE robed & crowned, Ushered in by the GOLDEN ROD, While a floral crowd press around, Just to win from her crest a nod. [Illustration] The FOXGLOVES are already on. Not only in pairs but dozens; They've come out to see all the fun, With sisters and aunts and cousins. [Illustration] The STITCHWORK looked up with a sigh At BATCHELOR'S BUTTONS unsewn: [Illustration] Single Daisies were not in her eye, For the grass was just newly mown. [Illustration] The HORSE-TAIL, 'scaped from WOLFE'S CLAW, Rides off with a LADIES' LAGES. [Illustration] The FRIAR'S-COWL hides a doctor of law, And the BISHOP'S-WEED covers his grace's [Illustration] The SNAPDRAGON opened his jaw, But, at sight of Scotch THISTLE, turned pale: [Illustration] He'd too many points of the law For a dragon without a scale. [Illustration] Little JENNY-CREEPER lay low, Till happy thoughts made her gladder; How to rise in the world she'd know, So she climbed up JACOB'S LADDER [Illustration] SWEET WILLIAM with MARYGOLD Seek HEARTSEASE in the close box-border. Where, starched in their ruff's stiff fold, DUTCH DAHLIAS prim, keep order. [Illustration] NARCISSUS bends over the brook, Intent upon DAFFA-DOWN-DILLY: [Illustration] While EYEBRIGHT observes from her nook, And wonders he could be so silly. [Illustration] A LANCE FOR A LAD 'gainst KING'S SPEAR. When the BUGLE sounds for the play [Illustration] A LADIES MANTLE flaunting there Is the banner that leads the fray. [Illustration] KNIGHT'S SPUR to the LADIES BOWER To seek for the LADIES SLIPPER. [Illustration] 'Twas lost in the wood in a summer shower When the CLOWN'S WORT tried to trip her. [Illustration] TOAD-FLAX is spun for BUTTER-AND-EGGS [Illustration] On a LADIES' CUSHION sits THRIFT She never wastes, or steals, or begs, But she can't give poor RAGWORT a lift. [Illustration] QUEEN OF THE MEADS is MEADOWSWEET, In the realm of grasses wide: [Illustration] But not in all her court you meet The turbaned TURK'S HEAD in his pride. [Illustration] Fair BETHLEHEM' STAR shineth bright, In a lowly place, as of old, [Illustration] And through the green gloom glows the light Of ST. JOHN'S-WORT--a nimbus of gold. [Illustration] But the hours of the sun swift glide, And the flowers with them are speeding. [Illustration] Though LOVE-IN-A-MIST may hide. When Time's in the garden weeding. [Illustration] There's TRAVELLER'S JOY To entwine, At our journey's end for greeting, [Illustration] We can talk over SOPS-IN-WINE, And drink to our next merry meeting. [Illustration] PRINTED BY EDMUND EVANS BOUND BY LEIGHTON SON & HODGE [Illustration] [Illustration] [Illustration: A FLORAL FANTASY] End of the Project Gutenberg EBook of A Floral Fantasy in an Old English Garden, by Walter Crane ***
// AttrScaleNew is a wrapper around the C function pango_attr_scale_new. func AttrScaleNew(scaleFactor float64) *Attribute { c_scale_factor := (C.double)(scaleFactor) retC := C.pango_attr_scale_new(c_scale_factor) retGo := AttributeNewFromC(unsafe.Pointer(retC)) return retGo }
First, it was a WhatsApp message saying that the National Aeronautics and Space Administration (NASA) had stated there would be heavy rainfall and a cyclone on November 21 and 22 in Chennai that caused panic in the city. That message effectively turned out to be a hoax. Then came the message that more than 40 crocodiles had escaped the Madras Crocodile Bank on East Coast Road that started doing the rounds. Some local TV channels thought it true and even flashed it as news. This caused panic among the residents in that area who began to expect a crocodile to enter their homes at any minute! But again, it turned out to be a hoax. Zai Whitaker of the Madras Crocodile Bank tells dna, “We got several calls from the media. Perhaps people are learning, from experience, that not all news is true. The 'crocodiles have escaped' rumour has happened before as well including during the 1985 cyclone. Many media persons came over and it was good to meet several who have been well-wishers of the Crocodile Bank for a long time.” The security measures in place are quite extensive so it’s really not possible for crocodiles to just crawl out of the bank so easily. “We watch special news portals very carefully every time there's a build-up of weather in the region. Regarding security measures, this would mean writing a small book because there are many things we consider. In brief, there are four major areas here: Pen construction, the height, breadth of walls, the slope of ponds, ratio of land and water, and other factors are important, and the fact that the Crocodile Bank advises and helps other crocodile facilities in India and abroad, means that after 40 years of being in this field, we have cracked it! There is a secure wall all the way around the crocodile farm,” explains Whitaker. The staff is trained in what to look out for in case of a storm surge or any other natural or human-made disaster as well. “The most difficult one is groups of drunken tourists who start throwing things at the animals, and fight with and abuse our staff when told to stop. Natural disasters are easier to deal with than irresponsible humans,” adds Whitaker.
def plot_evo(self, runs, iters, title='', anno=''): tqdm.write('Plotting variance over time...') assert self.savehist, 'ERROR: No history to calculate metrics per step.' assert len(runs) == 1 or len(iters) == 1, 'ERROR: One run or one iter' runits = [i for i in product(runs, iters)] cmap = np.vectorize(lambda x : cm.plasma(x)) colors = np.array(cmap(np.linspace(0, 0.9, len(runits)))).T fig, ax = plt.subplots() for i, runit in enumerate(tqdm(runits, desc='Calculating variance')): y = self.variances(runit[0], runit[1]) ax.plot(np.arange(len(y)), y, color=colors[i]) ax.set(title=title, xlabel='# Steps', ylabel='Variance') ax.grid() plt.tight_layout() fig.savefig('figs/' + self.fname + anno + '.png', dpi=300) plt.close()
#include "stdafx.h" #include "TrayIcon.h" #include "RecentMessagesAlert.h" #include "../MainWindow.h" #include "../MainPage.h" #include "../contact_list/ContactListModel.h" #include "../containers/FriendlyContainer.h" #include "../contact_list/RecentItemDelegate.h" #include "../contact_list/RecentsModel.h" #include "../contact_list/UnknownsModel.h" #include "../sounds/SoundsManager.h" #include "../../core_dispatcher.h" #include "../../gui_settings.h" #include "../../url_config.h" #include "../../my_info.h" #include "../../controls/ContextMenu.h" #include "../../utils/gui_coll_helper.h" #include "../../utils/InterConnector.h" #include "../../utils/utils.h" #include "../../utils/features.h" #include "../../utils/log/log.h" #include "../history_control/history/MessageBuilder.h" #include "utils/gui_metrics.h" #include "main_window/LocalPIN.h" #include "styles/ThemeParameters.h" #include "../common.shared/config/config.h" #include "../common.shared/string_utils.h" #if defined(_WIN32) //# include "toast_notifications/win32/ToastManager.h" typedef HRESULT (__stdcall *QueryUserNotificationState)(QUERY_USER_NOTIFICATION_STATE *pquns); typedef BOOL (__stdcall *QuerySystemParametersInfo)(__in UINT uiAction, __in UINT uiParam, __inout_opt PVOID pvParam, __in UINT fWinIni); #elif defined(__APPLE__) #include "notification_center/macos/NotificationCenterManager.h" #include "../../utils/macos/mac_support.h" #endif #ifdef _WIN32 #include <Shobjidl.h> extern HICON qt_pixmapToWinHICON(const QPixmap &p); const QString pinPath = qsl("\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\\ICQ.lnk"); #endif // _WIN32 namespace { constexpr std::chrono::milliseconds init_mail_timeout = std::chrono::seconds(5); #ifdef _WIN32 enum class hIconSize { small, big }; HICON createHIconFromQIcon(const QIcon& _icon, const hIconSize _size) { if (!_icon.isNull()) { const int xSize = GetSystemMetrics(_size == hIconSize::small ? SM_CXSMICON : SM_CXICON); const int ySize = GetSystemMetrics(_size == hIconSize::small ? SM_CYSMICON : SM_CYICON); const QPixmap pm = _icon.pixmap(_icon.actualSize(QSize(xSize, ySize))); if (!pm.isNull()) return qt_pixmapToWinHICON(pm); } return nullptr; } bool isTaskbarIconsSmall() { QSettings s(qsl("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced"), QSettings::NativeFormat); return s.value(qsl("TaskbarSmallIcons"), 0).toInt() == 1; } #endif //_WIN32 #ifdef __linux__ quint32 djbStringHash(const QString& string) { quint32 hash = 5381; const auto chars = string.toLatin1(); for (auto c : chars) hash = (hash << 5) + hash + c; return hash; } #endif } namespace Ui { TrayIcon::TrayIcon(MainWindow* parent) : QObject(parent) , systemTrayIcon_(new QSystemTrayIcon(this)) , emailSystemTrayIcon_(nullptr) , Menu_(nullptr) , MessageAlert_(new RecentMessagesAlert(AlertType::alertTypeMessage)) , MentionAlert_(new RecentMessagesAlert(AlertType::alertTypeMentionMe)) , MailAlert_(new RecentMessagesAlert(AlertType::alertTypeEmail)) , MainWindow_(parent) , Base_(qsl(":/logo/ico")) , Unreads_(qsl(":/logo/ico_unread")) #ifdef _WIN32 , TrayBase_(qsl(":/logo/ico_tray")) , TrayUnreads_(qsl(":/logo/ico_unread_tray")) #else , TrayBase_(qsl(":/logo/ico")) , TrayUnreads_(qsl(":/logo/ico_unread")) #endif //_WIN32 , InitMailStatusTimer_(nullptr) , UnreadsCount_(0) , MailCount_(0) #ifdef _WIN32 , ptbl(nullptr) , flashing_(false) #endif //_WIN32 { #ifdef _WIN32 HRESULT hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ptbl)); if (FAILED(hr)) ptbl = nullptr; for (auto& icon : winIcons_) icon = nullptr; #endif //_WIN32 init(); InitMailStatusTimer_ = new QTimer(this); InitMailStatusTimer_->setInterval(init_mail_timeout); InitMailStatusTimer_->setSingleShot(true); connect(MessageAlert_, &RecentMessagesAlert::messageClicked, this, &TrayIcon::messageClicked, Qt::QueuedConnection); connect(MailAlert_, &RecentMessagesAlert::messageClicked, this, &TrayIcon::messageClicked, Qt::QueuedConnection); connect(MentionAlert_, &RecentMessagesAlert::messageClicked, this, &TrayIcon::messageClicked, Qt::QueuedConnection); connect(MessageAlert_, &RecentMessagesAlert::changed, this, &TrayIcon::updateAlertsPosition, Qt::QueuedConnection); connect(MailAlert_, &RecentMessagesAlert::changed, this, &TrayIcon::updateAlertsPosition, Qt::QueuedConnection); connect(MentionAlert_, &RecentMessagesAlert::changed, this, &TrayIcon::updateAlertsPosition, Qt::QueuedConnection); connect(Ui::GetDispatcher(), &core_dispatcher::im_created, this, &TrayIcon::loggedIn, Qt::QueuedConnection); connect(Ui::GetDispatcher(), &core_dispatcher::myInfo, this, &TrayIcon::forceUpdateIcon); connect(Ui::GetDispatcher(), &core_dispatcher::needLogin, this, &TrayIcon::loggedOut, Qt::QueuedConnection); connect(Ui::GetDispatcher(), &core_dispatcher::activeDialogHide, this, &TrayIcon::clearNotifications, Qt::QueuedConnection); connect(Ui::GetDispatcher(), &core_dispatcher::mailStatus, this, &TrayIcon::mailStatus, Qt::QueuedConnection); connect(Ui::GetDispatcher(), &core_dispatcher::newMail, this, &TrayIcon::newMail, Qt::QueuedConnection); connect(Ui::GetDispatcher(), &core_dispatcher::mentionMe, this, &TrayIcon::mentionMe, Qt::QueuedConnection); connect(&Utils::InterConnector::instance(), &Utils::InterConnector::historyControlPageFocusIn, this, &TrayIcon::clearNotifications, Qt::QueuedConnection); connect(&Utils::InterConnector::instance(), &Utils::InterConnector::mailBoxOpened, this, &TrayIcon::mailBoxOpened, Qt::QueuedConnection); connect(&Utils::InterConnector::instance(), &Utils::InterConnector::logout, this, &TrayIcon::resetState, Qt::QueuedConnection); if constexpr (platform::is_apple()) { connect(&Utils::InterConnector::instance(), &Utils::InterConnector::mailBoxOpened, this, [this]() { clearNotifications(qsl("mail")); }); setVisible(get_gui_settings()->get_value(settings_show_in_menubar, false)); } } TrayIcon::~TrayIcon() { cleanupWinIcons(); clearAllNotifications(); } void TrayIcon::cleanupWinIcons() { #ifdef _WIN32 for (auto& icon : winIcons_) { DestroyIcon(icon); icon = nullptr; } #endif } void TrayIcon::openMailBox(const QString& _mailId) { Ui::gui_coll_helper collection(Ui::GetDispatcher()->create_collection(), true); collection.set_value_as_qstring("email", Email_); Ui::GetDispatcher()->post_message_to_core("mrim/get_key", collection.get(), this, [this, _mailId](core::icollection* _collection) { Utils::openMailBox(Email_, QString::fromUtf8(Ui::gui_coll_helper(_collection, false).get_value_as_string("key")), _mailId); }); } void TrayIcon::hideAlerts() { MessageAlert_->hide(); MessageAlert_->markShowed(); updateIcon(); } void TrayIcon::forceUpdateIcon() { updateUnreadsCounter(); updateIcon(); } void TrayIcon::resetState() { UnreadsCount_ = 0; MailCount_ = 0; Email_.clear(); forceUpdateIcon(); updateEmailIcon(); clearAllNotifications(); } void TrayIcon::setVisible(bool visible) { systemTrayIcon_->setVisible(visible); if (emailSystemTrayIcon_) emailSystemTrayIcon_->setVisible(visible); } void TrayIcon::updateEmailIcon() { if (MailCount_ && canShowNotifications(NotificationType::email)) showEmailIcon(); else hideEmailIcon(); } void TrayIcon::setMacIcon() { #ifdef __APPLE__ NotificationCenterManager::updateBadgeIcon(UnreadsCount_); QString state = MyInfo()->state().toLower(); if (state != u"offline") state = qsl("online"); const auto curTheme = MacSupport::currentTheme(); QString iconResource(qsl(":/menubar/%1_%2%3_100"). arg(state, curTheme, UnreadsCount_ > 0 ? qsl("_unread") : QString()) ); QIcon icon(Utils::parse_image_name(iconResource)); systemTrayIcon_->setIcon(icon); emailIcon_ = QIcon(Utils::parse_image_name(qsl(":/menubar/mail_%1_100")).arg(curTheme)); if (emailSystemTrayIcon_) emailSystemTrayIcon_->setIcon(emailIcon_); #endif } void TrayIcon::updateAlertsPosition() { TrayPosition pos = getTrayPosition(); QRect availableGeometry = QDesktopWidget().availableGeometry(); int screenMarginX = Utils::scale_value(20) - Ui::get_gui_settings()->get_shadow_width(); int screenMarginY = screenMarginX; int screenMarginYMention = screenMarginY; int screenMarginYMail = screenMarginY; if (MessageAlert_->isVisible()) { screenMarginYMention += (MessageAlert_->height() - Utils::scale_value(12)); screenMarginYMail = screenMarginYMention; } if (MentionAlert_->isVisible()) { screenMarginYMail += (MentionAlert_->height() - Utils::scale_value(12)); } switch (pos) { case TrayPosition::TOP_RIGHT: MessageAlert_->move(availableGeometry.topRight().x() - MessageAlert_->width() - screenMarginX, availableGeometry.topRight().y() + screenMarginY); MentionAlert_->move(availableGeometry.topRight().x() - MentionAlert_->width() - screenMarginX, availableGeometry.topRight().y() + screenMarginYMention); MailAlert_->move(availableGeometry.topRight().x() - MailAlert_->width() - screenMarginX, availableGeometry.topRight().y() + screenMarginYMail); break; case TrayPosition::BOTTOM_LEFT: MessageAlert_->move(availableGeometry.bottomLeft().x() + screenMarginX, availableGeometry.bottomLeft().y() - MessageAlert_->height() - screenMarginY); MentionAlert_->move(availableGeometry.bottomLeft().x() + screenMarginX, availableGeometry.bottomLeft().y() - MentionAlert_->height() - screenMarginYMention); MailAlert_->move(availableGeometry.bottomLeft().x() + screenMarginX, availableGeometry.bottomLeft().y() - MailAlert_->height() - screenMarginYMail); break; case TrayPosition::BOTOOM_RIGHT: MessageAlert_->move(availableGeometry.bottomRight().x() - MessageAlert_->width() - screenMarginX, availableGeometry.bottomRight().y() - MessageAlert_->height() - screenMarginY); MentionAlert_->move(availableGeometry.bottomRight().x() - MentionAlert_->width() - screenMarginX, availableGeometry.bottomRight().y() - MentionAlert_->height() - screenMarginYMention); MailAlert_->move(availableGeometry.bottomRight().x() - MailAlert_->width() - screenMarginX, availableGeometry.bottomRight().y() - MailAlert_->height() - screenMarginYMail); break; case TrayPosition::TOP_LEFT: default: MessageAlert_->move(availableGeometry.topLeft().x() + screenMarginX, availableGeometry.topLeft().y() + screenMarginY); MentionAlert_->move(availableGeometry.topLeft().x() + screenMarginX, availableGeometry.topLeft().y() + screenMarginYMention); MailAlert_->move(availableGeometry.topLeft().x() + screenMarginX, availableGeometry.topLeft().y() + screenMarginYMail); break; } } QIcon TrayIcon::createIcon(const bool _withBase) { auto createPixmap = [this](const int _size, const int _count, const bool _withBase) { QImage baseImage = _withBase ? TrayBase_.pixmap(QSize(_size, _size)).toImage() : QImage(); return QPixmap::fromImage(Utils::iconWithCounter(_size, _count, Styling::getParameters().getColor(Styling::StyleVariable::SECONDARY_ATTENTION), Styling::getParameters().getColor(Styling::StyleVariable::TEXT_SOLID_PERMANENT), std::move(baseImage))); }; QIcon iconOverlay; if (UnreadsCount_ > 0) { iconOverlay.addPixmap(createPixmap(16, UnreadsCount_, _withBase)); iconOverlay.addPixmap(createPixmap(32, UnreadsCount_, _withBase)); } return iconOverlay; } bool TrayIcon::updateUnreadsCounter() { const auto prevCount = UnreadsCount_; UnreadsCount_ = Logic::getRecentsModel()->totalUnreads() + Logic::getUnknownsModel()->totalUnreads(); return UnreadsCount_ != prevCount; } void TrayIcon::updateIcon(const bool _updateOverlay) { #if defined(_WIN32) if (_updateOverlay) { const auto hwnd = reinterpret_cast<HWND>(MainWindow_->winId()); const auto resetIcons = [this, hwnd](const QIcon& _icon) { cleanupWinIcons(); winIcons_[IconType::small] = createHIconFromQIcon(_icon, hIconSize::small); winIcons_[IconType::big] = createHIconFromQIcon(_icon, hIconSize::big); winIcons_[IconType::overlay] = UnreadsCount_ > 0 ? createHIconFromQIcon(createIcon(), hIconSize::small) : nullptr; SendMessage(hwnd, WM_SETICON, ICON_SMALL, LPARAM(winIcons_[IconType::small])); SendMessage(hwnd, WM_SETICON, ICON_BIG, LPARAM(winIcons_[IconType::big])); }; if (ptbl && !isTaskbarIconsSmall()) { resetIcons(Base_); ptbl->SetOverlayIcon(hwnd, winIcons_[IconType::overlay], L""); } else { resetIcons(UnreadsCount_ > 0 ? Unreads_ : Base_); } } #elif defined(__linux__) static const auto hasUnity = QDBusInterface(qsl("com.canonical.Unity"), qsl("/")).isValid(); if (hasUnity) { static const auto launcherUrl = []() -> QString { const auto executableInfo = QFileInfo(QCoreApplication::applicationFilePath()); const QString desktopFileName = executableInfo.fileName() % u"desktop.desktop"; return u"application://" % desktopFileName; }(); QVariantMap unityProperties; unityProperties.insert(qsl("count-visible"), UnreadsCount_ > 0); if (UnreadsCount_ > 0) unityProperties.insert(qsl("count"), (qint64)(UnreadsCount_ > 9999 ? 9999 : UnreadsCount_)); QDBusMessage signal = QDBusMessage::createSignal( qsl("/com/canonical/unity/launcherentry/") % QString::number(djbStringHash(launcherUrl)), qsl("com.canonical.Unity.LauncherEntry"), qsl("Update")); signal << launcherUrl; signal << unityProperties; QDBusConnection::sessionBus().send(signal); } #endif if constexpr (platform::is_apple()) setMacIcon(); else systemTrayIcon_->setIcon(UnreadsCount_ > 0 ? createIcon(true): TrayBase_); animateTaskbarIcon(); } void TrayIcon::updateIconIfNeeded() { if (updateUnreadsCounter()) updateIcon(); } void TrayIcon::animateTaskbarIcon() { bool nowFlashing = false; #ifdef _WIN32 nowFlashing = flashing_; const auto flash = [this](const auto _flag, const auto _count, const auto _to) { FLASHWINFO fi; fi.cbSize = sizeof(FLASHWINFO); fi.hwnd = reinterpret_cast<HWND>(MainWindow_->winId()); fi.uCount = _count; fi.dwTimeout = _to; fi.dwFlags = _flag; FlashWindowEx(&fi); flashing_ = _flag != FLASHW_STOP; }; if (UnreadsCount_ == 0) flash(FLASHW_STOP, 0, 0); #endif static int prevCount = UnreadsCount_; const auto canAnimate = (UnreadsCount_ > prevCount || nowFlashing) && UnreadsCount_ > 0 && get_gui_settings()->get_value<bool>(settings_alert_tray_icon, false) && !MainWindow_->isActive(); prevCount = UnreadsCount_; if (canAnimate) { #if defined(__APPLE__) if (ncSupported()) NotificationCenterManager_->animateDockIcon(); #elif defined(_WIN32) UINT timeOutMs = GetCaretBlinkTime(); if (!timeOutMs || timeOutMs == INFINITE) timeOutMs = 250; flash(FLASHW_TRAY | FLASHW_TIMERNOFG, 10, timeOutMs); #else qApp->alert(MainWindow_, 1000); #endif } } void TrayIcon::clearNotifications(const QString& aimId) { // We can remove notifications pushed by a previous application run if constexpr (!platform::is_apple()) { if (aimId.isEmpty() || !Notifications_.contains(aimId)) { updateIconIfNeeded(); return; } } Notifications_.removeAll(aimId); #if defined (_WIN32) // if (toastSupported()) // ToastManager_->HideNotifications(aimId); #elif defined (__APPLE__) if (ncSupported()) NotificationCenterManager_->HideNotifications(aimId); #endif //_WIN32 updateIconIfNeeded(); } void TrayIcon::clearAllNotifications() { if constexpr (!platform::is_apple()) { if (Notifications_.isEmpty()) { updateIconIfNeeded(); return; } } Notifications_.clear(); #if defined (__APPLE__) if (ncSupported()) NotificationCenterManager_->removeAllNotifications(); #endif //__APPLE__ updateIconIfNeeded(); } void TrayIcon::dlgStates(const QVector<Data::DlgState>& _states) { std::set<QString> showedArray; bool playNotification = false; for (const auto& _state : _states) { const bool canNotify = _state.Visible_ && !_state.Outgoing_ && _state.UnreadCount_ != 0 && !_state.hasMentionMe_ && !_state.isSuspicious_ && (!ShowedMessages_.contains(_state.AimId_) || (_state.LastMsgId_ != -1 && ShowedMessages_[_state.AimId_] < _state.LastMsgId_)) && !_state.GetText().isEmpty() && !Logic::getUnknownsModel()->contains(_state.AimId_) && !Logic::getContactListModel()->isMuted(_state.AimId_); if (canNotify) { ShowedMessages_[_state.AimId_] = _state.LastMsgId_; const auto notifType = _state.AimId_ == u"mail" ? NotificationType::email : NotificationType::messages; if (canShowNotifications(notifType)) showMessage(_state, AlertType::alertTypeMessage); playNotification = true; } if (_state.Visible_) showedArray.insert(_state.AimId_); } if (playNotification) { #ifdef __APPLE__ if (!MainWindow_->isUIActive() || MacSupport::previewIsShown()) #else if (!MainWindow_->isUIActive()) #endif //__APPLE__ GetSoundsManager()->playSound(SoundsManager::Sound::IncomingMessage); } if (!showedArray.empty()) markShowed(showedArray); updateIconIfNeeded(); } void TrayIcon::mentionMe(const QString& _contact, Data::MessageBuddySptr _mention) { if (canShowNotifications(NotificationType::messages)) { if (auto state = Logic::getRecentsModel()->getDlgState(_contact); state.YoursLastRead_ >= _mention->Id_ || state.LastReadMention_ >= _mention->Id_) return; Data::DlgState state; state.header_ = QChar(0xD83D) % QChar(0xDC4B) % ql1c(' ') % QT_TRANSLATE_NOOP("notifications", "You have been mentioned"); state.AimId_ = _contact; state.mentionMsgId_ = _mention->Id_; state.mentionAlert_ = true; state.senderAimId_ = _mention->GetChatSender(); state.Official_ = Logic::getContactListModel()->isOfficial(_contact); state.SetText(hist::MessageBuilder::formatRecentsText(*_mention).text_); showMessage(state, AlertType::alertTypeMentionMe); GetSoundsManager()->playSound(SoundsManager::Sound::IncomingMessage); } } void TrayIcon::newMail(const QString& email, const QString& from, const QString& subj, const QString& id) { Email_ = email; if (canShowNotifications(NotificationType::email)) { Data::DlgState state; auto i1 = from.indexOf(ql1c('<')); auto i2 = from.indexOf(ql1c('>')); if (i1 != -1 && i2 != -1) { state.senderAimId_ = from.mid(i1 + 1, from.length() - i1 - (from.length() - i2 + 1)); state.senderNick_ = from.mid(0, i1).trimmed(); } else { state.senderAimId_ = from; state.senderNick_ = from; } state.AimId_ = qsl("mail"); state.Friendly_ = from; state.header_ = Email_; state.MailId_ = id; state.SetText(subj); if constexpr (platform::is_apple()) // Hide previous mail notifications clearNotifications(qsl("mail")); showMessage(state, AlertType::alertTypeEmail); GetSoundsManager()->playSound(SoundsManager::Sound::IncomingMail); } showEmailIcon(); } void TrayIcon::mailStatus(const QString& email, unsigned count, bool init) { Email_ = email; MailCount_ = count; updateEmailIcon(); if (!canShowNotifications(NotificationType::email)) return; if (!init && !InitMailStatusTimer_->isActive() && !MailAlert_->isVisible()) return; if (count == 0 && init) { InitMailStatusTimer_->start(); return; } Data::DlgState state; state.AimId_ = qsl("mail"); state.header_ = Email_; state.Friendly_ = QT_TRANSLATE_NOOP("tray_menu", "New email"); state.SetText(QString::number(count) % Utils::GetTranslator()->getNumberString(count, QT_TRANSLATE_NOOP3("tray_menu", " new email", "1"), QT_TRANSLATE_NOOP3("tray_menu", " new emails", "2"), QT_TRANSLATE_NOOP3("tray_menu", " new emails", "5"), QT_TRANSLATE_NOOP3("tray_menu", " new emails", "21") )); MailAlert_->updateMailStatusAlert(state); if (count == 0) { hideMailAlerts(); return; } else if (MailAlert_->isVisible()) { return; } showMessage(state, AlertType::alertTypeEmail); } void TrayIcon::messageClicked(const QString& _aimId, const QString& mailId, const qint64 mentionId, const AlertType _alertType) { statistic::getGuiMetrics().eventNotificationClicked(); MainWindow::ActivateReason reason = MainWindow::ActivateReason::ByNotificationClick; if (!_aimId.isEmpty()) { bool notificationCenterSupported = false; DeferredCallback action; #if defined (_WIN32) if (!toastSupported()) #elif defined (__APPLE__) notificationCenterSupported = ncSupported(); #endif //_WIN32 { switch (_alertType) { case AlertType::alertTypeEmail: { if (!notificationCenterSupported) { MailAlert_->hide(); MailAlert_->markShowed(); } action = [this, mailId]() { GetDispatcher()->post_stats_to_core(mailId.isEmpty() ? core::stats::stats_event_names::alert_mail_common : core::stats::stats_event_names::alert_mail_letter); openMailBox(mailId); }; reason = MainWindow::ActivateReason::ByMailClick; break; } case AlertType::alertTypeMessage: { if (!notificationCenterSupported) { MessageAlert_->hide(); MessageAlert_->markShowed(); } action = [_aimId]() { if (_aimId != Logic::getContactListModel()->selectedContact()) Utils::InterConnector::instance().getMainWindow()->skipRead(); Logic::getContactListModel()->setCurrent(_aimId, -1, true); }; break; } case AlertType::alertTypeMentionMe: { if (!notificationCenterSupported) { MentionAlert_->hide(); MentionAlert_->markShowed(); } action = [_aimId, mentionId]() { Q_EMIT Logic::getContactListModel()->select(_aimId, mentionId); }; break; } default: { assert(false); return; } } if (action) { if (!LocalPIN::instance()->locked()) action(); else LocalPIN::instance()->setDeferredAction(new DeferredAction(std::move(action), this)); } } } MainWindow_->activateFromEventLoop(reason); Q_EMIT Utils::InterConnector::instance().closeAnyPopupMenu(); Q_EMIT Utils::InterConnector::instance().closeAnyPopupWindow(Utils::CloseWindowInfo()); GetDispatcher()->post_stats_to_core(core::stats::stats_event_names::alert_click); } QString alertType2String(const AlertType _alertType) { switch (_alertType) { case AlertType::alertTypeMessage: return qsl("message"); case AlertType::alertTypeEmail: return qsl("mail"); case AlertType::alertTypeMentionMe: return qsl("mention"); default: assert(false); return qsl("unknown"); } } void TrayIcon::showMessage(const Data::DlgState& state, const AlertType _alertType) { Notifications_.push_back(state.AimId_); const auto isMail = (_alertType == AlertType::alertTypeEmail); #if defined (_WIN32) // if (toastSupported()) // { // ToastManager_->DisplayToastMessage(state.AimId_, state.GetText()); // return; // } #elif defined (__APPLE__) if (ncSupported()) { auto displayName = isMail ? state.Friendly_ : Logic::GetFriendlyContainer()->getFriendly(state.AimId_); if (_alertType == AlertType::alertTypeMentionMe) { displayName = QChar(0xD83D) % QChar(0xDC4B) % ql1c(' ') % QT_TRANSLATE_NOOP("notifications", "You have been mentioned in %1").arg(displayName); } const bool isShowMessage = Features::showNotificationsText() && !Ui::LocalPIN::instance()->locked(); const QString messageText = isShowMessage ? state.GetText() : QT_TRANSLATE_NOOP("notifications", "New message"); NotificationCenterManager_->DisplayNotification( alertType2String(_alertType), state.AimId_, Logic::getContactListModel()->isChannel(state.AimId_) ? QString() : state.senderNick_, messageText, state.MailId_, displayName, QString::number(state.mentionMsgId_)); return; } #endif //_WIN32 RecentMessagesAlert* alert = nullptr; switch (_alertType) { case AlertType::alertTypeMessage: alert = MessageAlert_; break; case AlertType::alertTypeEmail: alert = MailAlert_; break; case AlertType::alertTypeMentionMe: alert = MentionAlert_; break; default: assert(false); return; } alert->addAlert(state); TrayPosition pos = getTrayPosition(); QRect availableGeometry = QDesktopWidget().availableGeometry(); int screenMarginX = Utils::scale_value(20) - Ui::get_gui_settings()->get_shadow_width(); int screenMarginY = Utils::scale_value(20) - Ui::get_gui_settings()->get_shadow_width(); if (isMail && MessageAlert_->isVisible()) screenMarginY += (MessageAlert_->height() - Utils::scale_value(12)); switch (pos) { case TrayPosition::TOP_RIGHT: alert->move(availableGeometry.topRight().x() - alert->width() - screenMarginX, availableGeometry.topRight().y() + screenMarginY); break; case TrayPosition::BOTTOM_LEFT: alert->move(availableGeometry.bottomLeft().x() + screenMarginX, availableGeometry.bottomLeft().y() - alert->height() - screenMarginY); break; case TrayPosition::BOTOOM_RIGHT: alert->move(availableGeometry.bottomRight().x() - alert->width() - screenMarginX, availableGeometry.bottomRight().y() - alert->height() - screenMarginY); break; case TrayPosition::TOP_LEFT: default: alert->move(availableGeometry.topLeft().x() + screenMarginX, availableGeometry.topLeft().y() + screenMarginY); break; } alert->show(); if (Menu_ && Menu_->isVisible()) Menu_->raise(); } TrayPosition TrayIcon::getTrayPosition() const { QRect availableGeometry = QDesktopWidget().availableGeometry(); QRect iconGeometry = systemTrayIcon_->geometry(); QString ag = qsl("availableGeometry x: %1, y: %2, w: %3, h: %4 ").arg(availableGeometry.x()).arg(availableGeometry.y()).arg(availableGeometry.width()).arg(availableGeometry.height()); QString ig = qsl("iconGeometry x: %1, y: %2, w: %3, h: %4").arg(iconGeometry.x()).arg(iconGeometry.y()).arg(iconGeometry.width()).arg(iconGeometry.height()); Log::trace(u"tray", ag + ig); if (platform::is_linux() && iconGeometry.isEmpty()) return TrayPosition::TOP_RIGHT; bool top = abs(iconGeometry.y() - availableGeometry.topLeft().y()) < abs(iconGeometry.y() - availableGeometry.bottomLeft().y()); if (abs(iconGeometry.x() - availableGeometry.topLeft().x()) < abs(iconGeometry.x() - availableGeometry.topRight().x())) return top ? TrayPosition::TOP_LEFT : TrayPosition::BOTTOM_LEFT; else return top ? TrayPosition::TOP_RIGHT : TrayPosition::BOTOOM_RIGHT; } void TrayIcon::initEMailIcon() { #ifdef __APPLE__ emailIcon_ = QIcon(Utils::parse_image_name(qsl(":/menubar/mail_%1_100")).arg(MacSupport::currentTheme())); #else emailIcon_ = QIcon(qsl(":/resources/main_window/tray_email.ico")); #endif //__APPLE__ } void TrayIcon::showEmailIcon() { if (emailSystemTrayIcon_ || !canShowNotifications(NotificationType::email)) return; emailSystemTrayIcon_ = new QSystemTrayIcon(this); emailSystemTrayIcon_->setIcon(emailIcon_); emailSystemTrayIcon_->setVisible(true); connect(emailSystemTrayIcon_, &QSystemTrayIcon::activated, this, &TrayIcon::onEmailIconClick, Qt::QueuedConnection); #ifdef __APPLE__ if (ncSupported()) NotificationCenterManager_->reinstallDelegate(); #endif //__APPLE__ } void TrayIcon::hideEmailIcon() { if (!emailSystemTrayIcon_) return; emailSystemTrayIcon_->setVisible(false); delete emailSystemTrayIcon_; emailSystemTrayIcon_ = nullptr; #ifdef __APPLE__ if (ncSupported()) NotificationCenterManager_->reinstallDelegate(); #endif //__APPLE__ } void TrayIcon::hideMailAlerts() { if constexpr (platform::is_apple()) clearNotifications(qsl("mail")); else MailAlert_->hide(); } void TrayIcon::init() { MessageAlert_->hide(); MailAlert_->hide(); MainWindow_->setWindowIcon(Base_); updateUnreadsCounter(); updateIcon(false); systemTrayIcon_->setToolTip(Utils::getAppTitle()); initEMailIcon(); if constexpr (!platform::is_apple()) { Menu_ = new ContextMenu(MainWindow_); auto parentWindow = qobject_cast<MainWindow*>(parent()); if constexpr (platform::is_linux()) Menu_->addActionWithIcon(QIcon(), QT_TRANSLATE_NOOP("tray_menu", "Open"), parentWindow, [parentWindow]() { parentWindow->activateFromEventLoop(); }); const auto iconPath = platform::is_windows() ? qsl(":/context_menu/quit") : QString(); Menu_->addActionWithIcon(iconPath, QT_TRANSLATE_NOOP("tray_menu", "Quit"), parentWindow, &Ui::MainWindow::exit); systemTrayIcon_->setContextMenu(Menu_); } connect(systemTrayIcon_, &QSystemTrayIcon::activated, this, &TrayIcon::activated, Qt::QueuedConnection); systemTrayIcon_->show(); } void TrayIcon::markShowed(const std::set<QString>& _aimIds) { Ui::gui_coll_helper collection(Ui::GetDispatcher()->create_collection(), true); core::ifptr<core::iarray> contacts_array(collection->create_array()); contacts_array->reserve(_aimIds.size()); for (const auto& aimid : _aimIds) contacts_array->push_back(collection.create_qstring_value(aimid).get()); collection.set_value_as_array("contacts", contacts_array.get()); Ui::GetDispatcher()->post_message_to_core("dlg_states/hide", collection.get()); } bool TrayIcon::canShowNotificationsWin() const { #ifdef _WIN32 QUERY_USER_NOTIFICATION_STATE state; if (SHQueryUserNotificationState(&state) == S_OK && state != QUNS_ACCEPTS_NOTIFICATIONS) { Log::write_network_log(su::concat("QueryUserNotificationState returned ", std::to_string((int)state))); return false; } #endif //_WIN32 return true; } void TrayIcon::mailBoxOpened() { hideEmailIcon(); } void TrayIcon::onEmailIconClick(QSystemTrayIcon::ActivationReason) { GetDispatcher()->post_stats_to_core(core::stats::stats_event_names::tray_mail); openMailBox(QString()); } bool TrayIcon::canShowNotifications(const NotificationType _notifType) const { const auto isMail = _notifType == NotificationType::email; const auto paramName = isMail ? settings_notify_new_mail_messages : settings_notify_new_messages; if (!get_gui_settings()->get_value<bool>(paramName, true)) return false; if (isMail && !getUrlConfig().isMailConfigPresent()) return false; #ifdef __linux__ static const bool trayCanShowMessages = systemTrayIcon_->isSystemTrayAvailable() && systemTrayIcon_->supportsMessages(); #else const bool trayCanShowMessages = systemTrayIcon_->isSystemTrayAvailable() && systemTrayIcon_->supportsMessages(); #endif const bool uiActive = isMail ? false : MainWindow_->isUIActive(); #ifdef __APPLE__ if (isMail) return get_gui_settings()->get_value<bool>(settings_notify_new_mail_messages, true); return trayCanShowMessages && (!uiActive || MacSupport::previewIsShown()); #else if (platform::is_windows() && !canShowNotificationsWin()) return false; return trayCanShowMessages && !uiActive; #endif } void TrayIcon::activated(QSystemTrayIcon::ActivationReason reason) { bool validReason = reason == QSystemTrayIcon::Trigger; if constexpr (platform::is_linux()) validReason |= (reason == QSystemTrayIcon::MiddleClick); if (validReason) MainWindow_->activate(); } void TrayIcon::loggedIn() { connect(Logic::getRecentsModel(), &Logic::RecentsModel::dlgStatesHandled, this, &TrayIcon::dlgStates); connect(Logic::getRecentsModel(), &Logic::RecentsModel::updated, this, &TrayIcon::updateIconIfNeeded, Qt::QueuedConnection); connect(Logic::getRecentsModel(), &Logic::RecentsModel::readStateChanged, this, &TrayIcon::clearNotifications, Qt::QueuedConnection); connect(Logic::getUnknownsModel(), &Logic::UnknownsModel::dlgStatesHandled, this, &TrayIcon::dlgStates); connect(Logic::getUnknownsModel(), &Logic::UnknownsModel::updatedMessages, this, &TrayIcon::updateIconIfNeeded, Qt::QueuedConnection); connect(Logic::getUnknownsModel(), &Logic::UnknownsModel::readStateChanged, this, &TrayIcon::clearNotifications, Qt::QueuedConnection); connect(Logic::getContactListModel(), &Logic::ContactListModel::contactChanged, this, &TrayIcon::updateIconIfNeeded, Qt::QueuedConnection); connect(Logic::getContactListModel(), &Logic::ContactListModel::selectedContactChanged, this, &TrayIcon::clearNotifications, Qt::QueuedConnection); connect(Logic::getContactListModel(), &Logic::ContactListModel::contact_removed, this, &TrayIcon::clearNotifications, Qt::QueuedConnection); forceUpdateIcon(); } void TrayIcon::loggedOut() { resetState(); } #if defined (_WIN32) bool TrayIcon::toastSupported() { return false; /* if (QSysInfo().windowsVersion() > QSysInfo::WV_WINDOWS8_1) { if (!ToastManager_) { ToastManager_ = std::make_unique<ToastManager>(); connect(ToastManager_.get(), SIGNAL(messageClicked(QString)), this, SLOT(messageClicked(QString)), Qt::QueuedConnection); } return true; } return false; */ } #elif defined (__APPLE__) bool TrayIcon::ncSupported() { if (QSysInfo().macVersion() > QSysInfo::MV_10_7) { if (!NotificationCenterManager_) { NotificationCenterManager_ = std::make_unique<NotificationCenterManager>(); connect(NotificationCenterManager_.get(), &NotificationCenterManager::messageClicked, this, &TrayIcon::messageClicked, Qt::QueuedConnection); connect(NotificationCenterManager_.get(), &NotificationCenterManager::osxThemeChanged, this, &TrayIcon::setMacIcon, Qt::QueuedConnection); } return true; } return false; } #endif //_WIN32 }
<gh_stars>0 package com.github.bsideup.jabel; import com.sun.source.util.JavacTask; import com.sun.source.util.Plugin; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.code.Source; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JavacMessages; import net.bytebuddy.ByteBuddy; import net.bytebuddy.agent.ByteBuddyAgent; import net.bytebuddy.asm.Advice; import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.asm.MemberSubstitution; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.loading.ClassInjector; import net.bytebuddy.dynamic.loading.ClassReloadingStrategy; import net.bytebuddy.implementation.bytecode.Removal; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.implementation.bytecode.constant.IntegerConstant; import net.bytebuddy.pool.TypePool; import net.bytebuddy.utility.JavaModule; import java.lang.instrument.Instrumentation; import java.util.*; import static net.bytebuddy.matcher.ElementMatchers.*; public class JabelCompilerPlugin implements Plugin { @Override public void init(JavacTask task, String... args) { Map<String, AsmVisitorWrapper> visitors = new HashMap<String, AsmVisitorWrapper>() {{ // Disable the preview feature check AsmVisitorWrapper checkSourceLevelAdvice = Advice.to(CheckSourceLevelAdvice.class) .on(named("checkSourceLevel").and(takesArguments(2))); // Allow features that were introduced together with Records (local enums, static inner members, ...) AsmVisitorWrapper allowRecordsEraFeaturesAdvice = MemberSubstitution.relaxed() .field(named("allowRecords")) .onRead() .replaceWith( (instrumentedType, instrumentedMethod, typePool) -> { return (targetType, target, parameters, result, freeOffset) -> { return new StackManipulation.Compound( // remove aload_0 Removal.of(targetType), IntegerConstant.forValue(true) ); }; } ) .on(any()); put("com.sun.tools.javac.parser.JavacParser", new AsmVisitorWrapper.Compound( checkSourceLevelAdvice, allowRecordsEraFeaturesAdvice ) ); put("com.sun.tools.javac.parser.JavaTokenizer", checkSourceLevelAdvice); put("com.sun.tools.javac.comp.Check", allowRecordsEraFeaturesAdvice); put("com.sun.tools.javac.comp.Attr", allowRecordsEraFeaturesAdvice); put("com.sun.tools.javac.comp.Resolve", allowRecordsEraFeaturesAdvice); // Lower the source requirement for supported features put( "com.sun.tools.javac.code.Source$Feature", Advice.to(AllowedInSourceAdvice.class) .on(named("allowedInSource").and(takesArguments(1))) ); }}; try { ByteBuddyAgent.install(); } catch (Exception e) { ByteBuddyAgent.install( new ByteBuddyAgent.AttachmentProvider.Compound( ByteBuddyAgent.AttachmentProvider.ForJ9Vm.INSTANCE, ByteBuddyAgent.AttachmentProvider.ForStandardToolsJarVm.JVM_ROOT, ByteBuddyAgent.AttachmentProvider.ForStandardToolsJarVm.JDK_ROOT, ByteBuddyAgent.AttachmentProvider.ForStandardToolsJarVm.MACINTOSH, ByteBuddyAgent.AttachmentProvider.ForUserDefinedToolsJar.INSTANCE, ByteBuddyAgent.AttachmentProvider.ForEmulatedAttachment.INSTANCE ) ); } ByteBuddy byteBuddy = new ByteBuddy(); ClassLoader classLoader = JavacTask.class.getClassLoader(); ClassFileLocator classFileLocator = ClassFileLocator.ForClassLoader.of(classLoader); TypePool typePool = TypePool.ClassLoading.of(classLoader); visitors.forEach((className, visitor) -> { byteBuddy .redefine( typePool.describe(className).resolve(), classFileLocator ) .visit(visitor) .make() .load(classLoader, ClassReloadingStrategy.fromInstalledAgent()); }); JavaModule jabelModule = JavaModule.ofType(JabelCompilerPlugin.class); ClassInjector.UsingInstrumentation.redefineModule( ByteBuddyAgent.getInstrumentation(), JavaModule.ofType(JavacTask.class), Collections.emptySet(), Collections.emptyMap(), new HashMap<String, java.util.Set<JavaModule>>() {{ put("com.sun.tools.javac.api", Collections.singleton(jabelModule)); put("com.sun.tools.javac.tree", Collections.singleton(jabelModule)); put("com.sun.tools.javac.code", Collections.singleton(jabelModule)); put("com.sun.tools.javac.util", Collections.singleton(jabelModule)); }}, Collections.emptySet(), Collections.emptyMap() ); Context context = ((JavacTaskImpl) task).getContext(); JavacMessages.instance(context).add(locale -> new ResourceBundle() { @Override protected Object handleGetObject(String key) { return "{0}"; } @Override public Enumeration<String> getKeys() { return Collections.enumeration(Arrays.asList("missing.desugar.on.record")); } }); task.addTaskListener(new RecordsRetrofittingTaskListener(context)); System.out.println("Jabel: initialized"); } @Override public String getName() { return "jabel"; } // Make it auto start on Java 14+ public boolean autoStart() { return true; } static class AllowedInSourceAdvice { @Advice.OnMethodEnter static void allowedInSource( @Advice.This Source.Feature feature, @Advice.Argument(value = 0, readOnly = false) Source source ) { switch (feature.name()) { case "PRIVATE_SAFE_VARARGS": case "SWITCH_EXPRESSION": case "SWITCH_RULE": case "SWITCH_MULTIPLE_CASE_LABELS": case "LOCAL_VARIABLE_TYPE_INFERENCE": case "VAR_SYNTAX_IMPLICIT_LAMBDAS": case "DIAMOND_WITH_ANONYMOUS_CLASS_CREATION": case "EFFECTIVELY_FINAL_VARIABLES_IN_TRY_WITH_RESOURCES": case "TEXT_BLOCKS": case "PATTERN_MATCHING_IN_INSTANCEOF": case "REIFIABLE_TYPES_INSTANCEOF": case "RECORDS": //noinspection UnusedAssignment source = Source.DEFAULT; break; } } } static class CheckSourceLevelAdvice { @Advice.OnMethodEnter static void checkSourceLevel( @Advice.Argument(value = 1, readOnly = false) Source.Feature feature ) { if (feature.allowedInSource(Source.JDK8)) { //noinspection UnusedAssignment feature = Source.Feature.LAMBDA; } } } }
<filename>tests/test_b_extension.rs pub mod machine_build; #[test] pub fn test_clzw_bug() { let mut machine = machine_build::int_v1_imcb("tests/programs/clzw_bug"); let ret = machine.run(); assert!(ret.is_ok()); assert_eq!(ret.unwrap(), 0); #[cfg(has_asm)] { let mut machine_asm = machine_build::asm_v1_imcb("tests/programs/clzw_bug"); let ret_asm = machine_asm.run(); assert!(ret_asm.is_ok()); assert_eq!(ret_asm.unwrap(), 0); } #[cfg(has_aot)] { let code = machine_build::aot_v1_imcb_code("tests/programs/clzw_bug"); let mut machine_aot = machine_build::aot_v1_imcb("tests/programs/clzw_bug", &code); let ret_aot = machine_aot.run(); assert!(ret_aot.is_ok()); assert_eq!(ret_aot.unwrap(), 0); } } #[test] pub fn test_sbinvi_aot_load_imm_bug() { let mut machine = machine_build::int_v1_imcb("tests/programs/sbinvi_aot_load_imm_bug"); let ret = machine.run(); assert!(ret.is_ok()); assert_eq!(ret.unwrap(), 0); #[cfg(has_asm)] { let mut machine_asm = machine_build::asm_v1_imcb("tests/programs/sbinvi_aot_load_imm_bug"); let ret_asm = machine_asm.run(); assert!(ret_asm.is_ok()); assert_eq!(ret_asm.unwrap(), 0); } #[cfg(has_aot)] { let code = machine_build::aot_v1_imcb_code("tests/programs/sbinvi_aot_load_imm_bug"); let mut machine_aot = machine_build::aot_v1_imcb("tests/programs/sbinvi_aot_load_imm_bug", &code); let ret_aot = machine_aot.run(); assert!(ret_aot.is_ok()); assert_eq!(ret_aot.unwrap(), 0); } } #[test] pub fn test_rorw_in_end_of_aot_block() { // The 1024th instruction will use one more temporary register than normal. let mut machine = machine_build::int_v1_imcb("tests/programs/rorw_in_end_of_aot_block"); let ret = machine.run(); assert!(ret.is_ok()); assert_eq!(ret.unwrap(), 0); #[cfg(has_asm)] { let mut machine_asm = machine_build::asm_v1_imcb("tests/programs/rorw_in_end_of_aot_block"); let ret_asm = machine_asm.run(); assert!(ret_asm.is_ok()); assert_eq!(ret_asm.unwrap(), 0); } #[cfg(has_aot)] { let code = machine_build::aot_v1_imcb_code("tests/programs/rorw_in_end_of_aot_block"); let mut machine_aot = machine_build::aot_v1_imcb("tests/programs/rorw_in_end_of_aot_block", &code); let ret_aot = machine_aot.run(); assert!(ret_aot.is_ok()); assert_eq!(ret_aot.unwrap(), 0); } } #[test] pub fn test_pcnt() { let mut machine = machine_build::int_v1_imcb("tests/programs/pcnt"); let ret = machine.run(); assert!(ret.is_ok()); assert_eq!(ret.unwrap(), 0); #[cfg(has_asm)] { let mut machine_asm = machine_build::asm_v1_imcb("tests/programs/pcnt"); let ret_asm = machine_asm.run(); assert!(ret_asm.is_ok()); assert_eq!(ret_asm.unwrap(), 0); } #[cfg(has_aot)] { let code = machine_build::aot_v1_imcb_code("tests/programs/pcnt"); let mut machine_aot = machine_build::aot_v1_imcb("tests/programs/pcnt", &code); let ret_aot = machine_aot.run(); assert!(ret_aot.is_ok()); assert_eq!(ret_aot.unwrap(), 0); } } #[test] pub fn test_clmul_bug() { let mut machine = machine_build::int_v1_imcb("tests/programs/clmul_bug"); let ret = machine.run(); assert!(ret.is_ok()); assert_eq!(ret.unwrap(), 0); #[cfg(has_asm)] { let mut machine_asm = machine_build::asm_v1_imcb("tests/programs/clmul_bug"); let ret_asm = machine_asm.run(); assert!(ret_asm.is_ok()); assert_eq!(ret_asm.unwrap(), 0); } #[cfg(has_aot)] { let code = machine_build::aot_v1_imcb_code("tests/programs/clmul_bug"); let mut machine_aot = machine_build::aot_v1_imcb("tests/programs/clmul_bug", &code); let ret_aot = machine_aot.run(); assert!(ret_aot.is_ok()); assert_eq!(ret_aot.unwrap(), 0); } } #[test] pub fn test_orc_bug() { let mut machine = machine_build::int_v1_imcb("tests/programs/orc_bug"); let ret = machine.run(); assert!(ret.is_ok()); assert_eq!(ret.unwrap(), 0); #[cfg(has_asm)] { let mut machine_asm = machine_build::asm_v1_imcb("tests/programs/orc_bug"); let ret_asm = machine_asm.run(); assert!(ret_asm.is_ok()); assert_eq!(ret_asm.unwrap(), 0); } #[cfg(has_aot)] { let code = machine_build::aot_v1_imcb_code("tests/programs/orc_bug"); let mut machine_aot = machine_build::aot_v1_imcb("tests/programs/orc_bug", &code); let ret_aot = machine_aot.run(); assert!(ret_aot.is_ok()); assert_eq!(ret_aot.unwrap(), 0); } }
#ifndef __CERBERUS_SLOT_MAP_HPP__ #define __CERBERUS_SLOT_MAP_HPP__ #include <set> #include <string> #include "common.hpp" #include "utils/address.hpp" namespace cerb { class Server; class Proxy; struct RedisNode { util::Address addr; std::string node_id; std::string master_id; std::set<std::pair<slot, slot>> slot_ranges; RedisNode(util::Address a, std::string nid) : addr(std::move(a)) , node_id(std::move(nid)) {} RedisNode(util::Address a, std::string nid, std::string mid) : addr(std::move(a)) , node_id(std::move(nid)) , master_id(std::move(mid)) {} RedisNode(RedisNode&& rhs) : addr(std::move(rhs.addr)) , node_id(std::move(rhs.node_id)) , master_id(std::move(rhs.master_id)) , slot_ranges(std::move(rhs.slot_ranges)) {} RedisNode(RedisNode const& rhs) : addr(rhs.addr) , node_id(rhs.node_id) , master_id(rhs.master_id) , slot_ranges(rhs.slot_ranges) {} bool is_master() const { return master_id.empty(); } }; class SlotMap { Server* _servers[CLUSTER_SLOT_COUNT]; public: SlotMap(); SlotMap(SlotMap const&) = delete; Server** begin() { return _servers; } Server** end() { return _servers + CLUSTER_SLOT_COUNT; } Server* const* begin() const { return _servers; } Server* const* end() const { return _servers + CLUSTER_SLOT_COUNT; } Server* get_by_slot(slot s) { return _servers[s]; } void replace_map(std::vector<RedisNode> const& nodes, Proxy* proxy); void clear(); Server* random_addr() const; static void select_slave_if_possible(std::string host_beginning); }; std::vector<RedisNode> parse_slot_map(std::string const& nodes_info, std::string const& default_host); void write_slot_map_cmd_to(int fd); } #endif /* __CERBERUS_SLOT_MAP_HPP__ */
<reponame>bitjjj/vue3-component-library-template<gh_stars>0 export { default as useFocus } from './use-focus' export * from './use-locale'
FORTH-ICS / TR-106 December 1993 Rehabilitation ( Assistive ) Technology product taxonomy : A conceptual tool for analysing products and extracting demand determinants This paper proposes and describes a conceptual tool, namely the Rehabilitation (Assistive) Technology (RT) product taxonomy, as a framework for analysing Rehabilitation Technology products and extracting demand determinants. The ultimate objective of this work is to provide demand and supply related actors with a meaningful tool for identifying and focusing on specific aspects, which may be directly or indirectly related to existing or new products, so that demand and consumption allocation decisions can be targeted, evaluated and/or predicted.
// CreateWalletFile creates a new wallet file on disk func CreateWalletFile(file *os.File, passphrase string, privateKey []byte) error { hasher := sha256.New() bytesWritten, err := hasher.Write([]byte(passphrase)) if err != nil { return err } if bytesWritten <= 0 { return ErrEmptyPassphrase } passwordHash := hasher.Sum(nil) if len(passwordHash) != 32 { return ErrUnexpectedHashLength } source := bytes.NewReader(privateKey) _, err = sio.Encrypt(file, source, walletConfig(passwordHash)) return err }
import { tplEngineNew } from '@omni-door/utils'; const tpl = `\`import { Component, Vue, Prop } from 'vue-property-decorator'; import classnames from '@utils/classnames'; \${ts ? \`/* import types */ import type { CreateElement, VNode } from 'vue'; \` : ''} @Component export default class \${componentName} extends Vue { @Prop({ type: String, default: '\${componentName.toLowerCase()}' }) \${ts ? \`private prefixCls!: string;\` : 'prefixCls;'} \${ts ? \`protected render(h: CreateElement): VNode\` : 'render(h)'} { const content = this.$slots.default; const classes = classnames(this.prefixCls); return h( 'div', { staticClass: classes() }, content ); } }\``; export const tpl_new_component_h_class = { tpl }; export default tplEngineNew(tpl_new_component_h_class, 'tpl');
<reponame>ranineha003/nrs import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators, AbstractControl } from '@angular/forms'; import { LoginService } from "../services"; import { Router } from "@angular/router"; import { BroadcastSubject } from "../services"; @Component({ selector: 'app-login', templateUrl: './login.component.html' }) export class LoginComponent { loginInfo: FormGroup; constructor(private loginService: LoginService, private router: Router, public broadcastSubject: BroadcastSubject) { this.loginInfo = new FormGroup({ email: new FormControl('', [Validators.required, Validators.minLength(5), Validators.email, this.customValidator()]), password: new FormControl() }) } customValidator() { return (control: AbstractControl): { [key: string]: any } | null => { if (control.value.indexOf('gmail') !== -1) { return true ? { 'notvalidmail': true } : null; } else return null; }; } get email() { return this.loginInfo.get('email') } get password() { return this.loginInfo.get('password') } login() { if (this.loginInfo.valid) { this.loginService.login(this.loginInfo.value).subscribe((data: any) => { if (data.login) { localStorage.setItem("token", data.token); this.broadcastSubject.sendMessage(data); this.router.navigate(["/home"]); } }); } } }
<filename>src/java/mail/AuthCode.java<gh_stars>10-100 package mail; import java.security.SecureRandom; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AuthCode { private static final Random RANDOM = new SecureRandom(); /** Length of password. @see #generateRandomPassword() */ public static final int PASSWORD_LENGTH = 12; /** * Generate a random String suitable for use as a temporary password. * * @return String suitable for use as a temporary password * @since 2.4 */ public String generateCode() { // Pick from some letters that won't be easily mistaken for each // other. So, for example, omit o O and 0, 1 l and L. String letters = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789"; String pw = ""; for (int i=0; i<PASSWORD_LENGTH; i++) { int index = (int)(RANDOM.nextDouble()*letters.length()); pw += letters.substring(index, index+1); } return pw; } public static void main(String ar[]) { // AuthCode ac=new AuthCode(); //String cd =ac.generateCode(); } //response.sendRenderParameter("Password", pw); }
American musician and sports businessman For the Major League Baseball first baseman, see Jimmy Hart (baseball) James Ray Hart[2] (born January 1, 1943) is an American professional wrestling manager, executive, composer, and musician currently signed with WWE in a Legends deal.[1] He is best known for his work in the World Wrestling Federation and World Championship Wrestling, where he used the nickname "The Mouth of the South". He has managed many professional wrestlers, including Hulk Hogan, Bret Hart (no relation) and Jim Neidhart (The Hart Foundation), Greg "The Hammer" Valentine, Jerry "The King" Lawler, "The Million Dollar Man" Ted DiBiase, Irwin R. Schyster, The Mountie, Earthquake, Typhoon, Dino Bravo, the Nasty Boys, The Giant, and The Honky Tonk Man. He was at one time AWA Southern Heavyweight Champion. Before becoming involved with professional wrestling, Hart was a member of rock band The Gentrys, best known for their 1965 top five Billboard Hot 100 hit, "Keep on Dancing". Professional wrestling career [ edit ] Memphis Wrestling (1978 - 1984) [ edit ] Jimmy Hart was born in Jackson, Mississippi. He was brought into wrestling by Jerry "The King" Lawler, with whom he had attended Memphis Treadwell High School. Having been asked to sing back-up with Lawler, Hart later became Lawler's manager. After splitting from Lawler, Hart created a stable known as Hart's First Family of Wrestling to attack Lawler, which among others included King Kong Bundy, "Ravishing" Rick Rude, Lanny Poffo, Jim "The Anvil" Neidhart, Ox Baker, Kamala, Randy Savage, "Hot Stuff" Eddie Gilbert, The Iron Sheik and Kevin Sullivan. In 1982, Hart earned national headlines doing a program with comedian and television star Andy Kaufman. Hart, Lawler and Kaufman would continue this feud for over a year. Around this time, Hart became known as "The Wimp", a nickname given to him by Lawler and chanted by fans, and was the subject of the song "Wimpbusters," which was sung by Lawler to the tune of "Ghostbusters" by Ray Parker, Jr.; a music video was also made featuring Lawler, announcer Lance Russell, and wrestlers such as Randy Savage, Jimmy Valiant, Dutch Mantel, Tommy Rich, and Rufus R. Jones, along with footage of Lawler beating Hart and his "First Family". In 1981 through 1984, Hart led Austin Idol, Masao Ito, and Gilbert to NWA/AWA International titles. World Wrestling Federation (1985–1993) [ edit ] In 1985, Hart's friend Hillbilly Jim recommended him to WWF owner Vince McMahon, who hired him. He was nicknamed "The Mouth of the South" due to his loose-lipped style, often augmented by his trademark megaphone, which he used to instruct and encourage his protégés, to discourage and annoy opponents and announcers (especially Gorilla Monsoon) and also as a weapon. Hart's first acquisition in the WWF was Greg "The Hammer" Valentine, then the Intercontinental Heavyweight Champion, whom Hart managed at WrestleMania. After Valentine lost the Intercontinental Heavyweight Title to Tito Santana, Hart briefly co-managed the Dream Team (Valentine and Beefcake), until he was phased out and gave full control to "Luscious Johnny" Valiant. At WrestleMania, Hart also managed King Kong Bundy as he defeated S.D. Jones. Hart later traded Bundy's contract to Bobby "The Brain" Heenan for The Missing Link and Adrian Adonis. He helped the latter to establish his "Adorable Adrian" gimmick. In 1985, Hart took the Funk Family under his wing. The Funks included Terry and Hoss Funk, as well as their kayfabe brother Jimmy Jack Funk. Hart also managed Jim "The Anvil" Neidhart. 1985 also marked the appearance of Bret "Hitman" Hart. Jimmy Hart teamed him up with Jim "The Anvil" Neidhart to form The Hart Foundation. On January 26, 1987, Hart guided the Hart Foundation to the WWF World Tag Team Title, which they won from the British Bulldogs. Disgraced-referee-turned-wrestler Danny Davis also was managed by Jimmy Hart. When The Honky Tonk Man turned heel, Hart became his manager. In this position, Hart was nicknamed "The Colonel" in a reference to Colonel Tom Parker, the manager of Elvis Presley. With Hart in his corner, the Honky Tonk Man captured the Intercontinental Heavyweight Title from Ricky "The Dragon" Steamboat on June 2, 1987 and held it until August 1988. "The Colonel" moniker stuck with him for years, even after the Honky Tonk Man departed the company in early 1991. At WrestleMania III, Hart was involved in three matches and took some incredible bumps during the show. His first appearance was with "Adorable Adrian" Adonis who fought Rowdy Roddy Piper. Then came the six-man tag match, pitting the Hart Foundation and Danny Davis against the Bulldogs and Tito Santana. Jimmy Hart's third appearance on the show was when The Honky Tonk Man fought Jake "The Snake" Roberts who had rock legend Alice Cooper in his corner. Following that match, Hart was left alone in the ring where Roberts and Cooper teamed up to terrorise him with Roberts' pet snake Damien. Also in 1987, Hart managed the WWF Women's Tag Team champions Judy Martin and Leilani Kai, known as The Glamour Girls. Martin and Kai mostly feuded with Japanese team the Jumping Bomb Angels (Noriyo Tateno and Itsuki Yamazaki). Hart was named Pro Wrestling Illustrated's Manager of the Year in 1987, an award he won again in 1994. At WrestleMania IV, Hart received a haircut from Brutus "The Barber" Beefcake, after interfering in the Intercontinental Heavyweight Championship match between Beefcake and the Honky Tonk Man, helping Honky Tonk Man retain the title by getting disqualified. When the Hart Foundation fired Hart as manager (and turned face) in 1988, Hart managed The Fabulous Rougeau Brothers to feud with his former team; the angle was that Hart still retained the managerial rights to his former team and gave a portion of it to the Rougeaus, giving them the right to appear at ringside whenever the Hart Foundation wrestled. At SummerSlam 1988, Hart accompanied Demolition and Mr. Fuji to help retain their WWF Tag Team title against the Hart Foundation. Ax used Hart's megaphone as a foreign object to strike Bret in the head and secure the victory. In 1989, Hart brought Dino Bravo into his stable after the departure of Frenchy Martin. Then at a push-up contest between the Ultimate Warrior and Bravo, Hart and Bravo invited a large 460 pound man from the audience – later known as Earthquake – into the ring to sit on the contestants' backs. Predictably the large man was planted in the audience by Hart and Bravo and they eventually teamed up against the Warrior. In 1990, Hart groomed Earthquake to be the man to beat Hulk Hogan. Hart continued his war with his former tag team, the Hart Foundation. In 1990, he combined his protégés Honky Tonk Man and Greg Valentine into the short-lived team of Rhythm and Blues, though they had teamed previously as themselves when facing the Hart Foundation at WrestleMania V. In 1991, he managed The Nasty Boys to defeat the Hart Foundation for the WWF World Tag Team title at WrestleMania VII, this time using a motorbike helmet as a weapon. When the Nasty Boys lost the title to the Legion of Doom at SummerSlam 1991, Hart sent The Natural Disasters, a team formed out of Earthquake and his former opponent Typhoon (formerly known as Tugboat), to dispose the new champions. When the Disasters failed, Hart formed a new team in early 1992: Money Inc., composed of Hart's protégé I.R.S. and "The Million Dollar Man" Ted DiBiase. Money, Inc. defeated the L.O.D. Their title win led to the split between Hart and the Natural Disasters, who as faces feuded with Money Inc. and exchanged the tag team titles twice in 1992. Their biggest match came at WrestleMania VIII when Money Inc. retained their titles by leaving the ring and forcing a count-out. In 1991, Hart had also brought in The Mountie, who had a short reign as Intercontinental Heavyweight Champion in early 1992 after defeating Bret Hart on January 17, then losing it just two days later to Rowdy Roddy Piper at the Royal Rumble. The Mountie then went on to feud with the Big Boss Man over who was the "law and order" in the WWF. Their feud culminated in a match at SummerSlam where the loser (in this case The Mountie) had to spend the night in a New York jail. Late in 1992, Money Inc. regaining the tag team titles from the Natural Disasters led to the Nasty Boys turning on their manager, as he had repeatedly substituted them for Money Inc. in title matches. Hart broke with Money Inc. early in 1993 and turned face when the team attacked Brutus "The Barber" Beefcake. In the storyline, Hart, conscious of Beefcake's extensive facial injuries from a real-life parasailing accident three years prior which required extensive re-constructive surgery to Beefcake's face and all but ended his full-time career, felt that his team went too far, and tried to stop them. Hart even went so far as to cover an unconscious Beefcake with his own body to stop them from doing more harm. Beefcake's long time friend Hulk Hogan came out the following week and expressed gratitude to Hart for his uncharacteristically heroic actions. He managed both Beefcake and Hogan who at WrestleMania IX lost to Money Inc by disqualification. Later in the show, Hart for the first time would be the manager of the WWF World Heavyweight Champion when Hogan accepted an impromptu challenge by Mr. Fuji, the manager of the new champion Yokozuna who had just defeated Bret Hart for the belt. Hogan would defeat the 505 lb (229 kg) new champion in a short match. At King of the Ring, Hart was in Hogan's corner as he lost the WWF World Heavyweight Title back to Yokozuna. This appearance was Hart's last in the WWF, as both he and Hogan departed the company. World Championship Wrestling (1994–2001) [ edit ] Following their departure from the WWF, Hogan and Hart briefly toured Mexico. After their return, Hart wrote music and occasionally appeared on Hogan's television show, Thunder in Paradise. Hogan then had Hart manage him when they went to World Championship Wrestling (WCW). At Bash at the Beach in 1994, Hart managed Hogan to win his first WCW World Heavyweight Title by defeating "The Nature Boy" Ric Flair. At Halloween Havoc in 1995, Hart turned on Hogan to help The Giant. Hart also became the manager of the evil faction, the Dungeon of Doom, created by Kevin Sullivan. During that era, he managed Ric Flair to a 12th world title victory over Macho Man Randy Savage. After the demise of the Dungeon of Doom, Hart recreated The First Family. After the demise of the First Family, Hart was placed in charge of booking TBS's WCW Saturday Night show prior to the program's cancellation. Jimmy Hart was also the first Strapmaster for the Yapapi Indian strap match in which Hulk Hogan defeated Ric Flair on March 19, 2000, at the Uncensored PPV. At Spring Stampede in 2000, Hart faced radio personality Mancow. The two had a rematch later in the year at Mayhem. In February 2001, Hart joined WCW's booking committee. Independent circuit; Wrestlicious (2002–present) [ edit ] After the sale of WCW to the then rival WWF, Hart and a close consortium of wrestlers and investors decided to create a wrestling organization—the Xcitement Wrestling Federation (XWF)—that would replace WCW as well as take wrestling back to early 1990s style of fun, family-oriented entertainment with minimal story lines and more solid wrestling. In 2002, Hart restarted his feud with Jerry Lawler by buying, for the XWF, part of the upstart Memphis Wrestling promotion. In 2007, Hart appeared at the PMG Clash of Legends. On November 7, 2008, Hart appeared at the Jerry "The King" Lawler 35th anniversary event. He also made a few appearances with Florida Championship Wrestling, WWE's developmental territory, as a color commentator in 2008. He made multiple appearances for WrestleMania Axxess during the week leading up to The 25th Anniversary of WrestleMania. In May 2006, Hart traveled to The Funking Conservatory, owned by Dory Funk Jr and Marti Funk, to shoot promos with the students. His most notable ones being with Studio Sar Ah when he discusses his move from World Wrestling Entertainment to TNA Wrestling and as well as Wrestlicious. Both promos can be found on the Studio Sar Ah fan page on Facebook and as well as YouTube. Hart continues to work at the school and shoot promos. On January 19, 2010, Hart announced that his all-female wrestling promotion Wrestlicious would be premiering on MavTV and BiteTV on March 1, 2010.[3] Hart currently appears at various professional wrestling conventions and autograph signings around the United States. He is a staple at all of the Wrestlereunion shows, and also does various appearances as part of the VOC Nation wrestling radio program in Philadelphia on 1360 WNJC. Hart is a regular guest on the VOC Wrestling Nation radio program on WNJC. Total Nonstop Action Wrestling (2003–2011) [ edit ] In October 2003 Hart made his debut for Total Nonstop Action Wrestling (TNA), hyping a match between Hulk Hogan and Jeff Jarrett, which was eventually scrapped as Hogan decided to return to WWE instead.[1] On June 19, 2005, at Slammiversary pay-per-view, The Naturals were assisted in a title defense against Team Canada by Hart, who ran to ringside and threw his megaphone to Chase Stevens, who hit Petey Williams with it and pinned him.[1] Hart acted as the manager of The Naturals until October 3, 2005. On February 14, 2010, at Against All Odds, Hart made his return to TNA as a heel by helping The Nasty Boys defeat Team 3D in a tag team match.[4] The alliance, however, was short lived as on March 29, 2010, news broke that the Nasty Boys had been released by TNA following an incident at a TNA function with Spike executives present.[5][6] Hart stayed with the company following the incident, but his role was unknown. Hart was seen on the January 20, 2011, edition of Impact!, when Kurt Angle yelled at him to play his entrance music upon entering the Impact! Zone.[7] Return to WWE (2011–present) [ edit ] Hart, with his signature megaphone, in April 2014 On March 1, 2011, it was reported that Jimmy Hart had left Total Nonstop Action Wrestling and re-signed with WWE to work on WrestleMania-related projects.[8] Hart has since hosted various house shows. On August 14, 2011, Hart made an appearance at SummerSlam, teasing a managerial position with R-Truth during a backstage segment.[9] On April 10, 2012, Hart made an appearance on SmackDown: Blast from the Past, where he managed the team of Heath Slater and Tyson Kidd, but ended up getting the mandible claw from Mick Foley. As of April 30, 2014, Hart was part-owner of "Hogan's Beach", a wrestling-themed tiki-bar in Tampa, Florida. As of April 2014, Hart was a regular cast member on the WWE Network original reality show Legends' House. Hart appeared on the August 11 edition of Raw for Hogan's birthday celebration. In April 2017, Hart purchased a beachfront property in Daytona Beach, Florida, and opened “Jimmy Hart’s Hall of Fame Bar and Tiki Deck“, which is a beach bar featuring an abundance of autographed pictures, wrestling paraphernalia, and at times an intercontinental championship belt. Other media [ edit ] His book, The Mouth of the South, was released on November 18, 2004. Music [ edit ] Before wrestling, Hart, as a teenager, was a vocalist in the 60s band The Gentrys, who had a million selling record with 1965's "Keep on Dancing". Before becoming The Gentrys, they were known as just "The Gents." Their production manager told them that if they did not change their name, then they would not succeed in the music industry. Later, after the leader of the group Larry Raspberry left, Hart took over and they had a few minor hits, most notably "Why Should I Cry" and a cover of Neil Young's "Cinnamon Girl", but were never able to match the success of "Keep on Dancing." Hart and the band were successful in the Memphis area nightclub circuit. The group was under contract to Stax Records at the time of its bankruptcy, and Stax could not properly promote them. During his years in the professional wrestling business, Hart composed many theme songs for wrestlers in the WWF and WCW. Some of the wrestlers for whom he composed music were Honky Tonk Man, Jimmy Snuka, Brutus "The Barber" Beefcake, The Rockers, The Hart Foundation, Crush, the Fabulous Rougeau Brothers, Dusty Rhodes, the Legion of Doom, the Nasty Boys, Ted DiBiase, the Mountie, Hulk Hogan, Sting, the nWo Wolfpac, and 3 Count. He also composed the themes for SummerSlam '88 (which was later reused as the theme for many early Royal Rumble events) and WrestleMania VI (which was later used for the seventh, eighth, ninth, and tenth events). One of Hart's most notable compositions is Shawn Michaels's entrance theme, "Sexy Boy."[10] In the late 1980s, Hart released a music album (also available on cassette tape) titled Outrageous Conduct. The release consisted of comical songs done in character; such as "Barbra Streisand's Nose" and "Eat Your Heart Out Rick Springfield." In 1995, Hulk Hogan released the album "Hulk Rules."[11] Hart, as well as Hogan's then wife Linda, were a part of the band The Wrestling Boot Band and helped write and sing many of the album's songs.[11] Television appearances [ edit ] In September 2007, Hart appeared on an episode of The People's Court as a witness for a defendant. Hart is a close friend of Hulk Hogan and is featured on many episodes of Hogan's VH1 reality series, Hogan Knows Best. Hart was also a judge on Hulk Hogan's Celebrity Championship Wrestling. Hart also appears in hair restoration advertisements for Medical Hair Restoration, as a client. He also does a comedic women's wrestling show called Wrestlicious, which can be viewed at Wrestlicious.com. Hart appeared on the WWE Legends' House. Hart has appeared a few times in Hulk Hogan's TV-show Thunder in Paradise. He also sang the intro music for the episode "Deadly Lessons, Pt. 1". Movie appearances [ edit ] In 1967, Hart appeared in the film It's a Bikini World as a member of The Gentrys.[12] In 2010, Hart appeared Insane Clown Posse's film Big Money Rustlas. In 2011, Hart appeared as himself in the Canadian movie Monster Brawl. Hart played the announcer to a wrestling tournament of eight classic monsters that fight to the death.[13] Championships and accomplishments [ edit ] Hart at a signing in Toronto in December 2009 Notes [ edit ] References [ edit ]
/** * Contains global actions and configurations. * @since 0.0.1 * @author Oleg Nenashev <[email protected]> */ public class OwnershipPlugin extends Plugin { public static final String LOG_PREFIX="[OwnershipPlugin] - "; public static final String FAST_RESOLVER_ID="Fast resolver for UI (recommended)"; private static final PermissionGroup PERMISSIONS = new PermissionGroup(OwnershipPlugin.class, Messages._OwnershipPlugin_ManagePermissions_Title()); public static final Permission MANAGE_ITEMS_OWNERSHIP = new Permission(PERMISSIONS, "Jobs", Messages._OwnershipPlugin_ManagePermissions_JobDescription(), Permission.CONFIGURE, PermissionScope.ITEM); public static final Permission MANAGE_SLAVES_OWNERSHIP = new Permission(PERMISSIONS, "Nodes", Messages._OwnershipPlugin_ManagePermissions_SlaveDescription(), Permission.CONFIGURE, PermissionScope.COMPUTER); private boolean requiresConfigureRights; private boolean assignOnCreate; private List<OwnershipAction> pluginActions = new ArrayList<OwnershipAction>(); public String mailResolverClassName; private ItemSpecificSecurity defaultJobsSecurity; public static OwnershipPlugin Instance() { Plugin plugin = Jenkins.getInstance().getPlugin(OwnershipPlugin.class); return plugin != null ? (OwnershipPlugin)plugin : null; } @Override public void start() throws Exception { super.load(); ReinitActionsList(); Hudson.getInstance().getActions().addAll(pluginActions); } public boolean isRequiresConfigureRights() { return requiresConfigureRights; } public boolean isAssignOnCreate() { return assignOnCreate; } public ItemSpecificSecurity getDefaultJobsSecurity() { return defaultJobsSecurity; } /** * Gets descriptor of ItemSpecificProperty. * Required for jelly. * @return Descriptor */ public ItemSpecificSecurity.ItemSpecificDescriptor getItemSpecificDescriptor() { return ItemSpecificSecurity.DESCRIPTOR; } @Override public void configure(StaplerRequest req, JSONObject formData) throws IOException, ServletException, Descriptor.FormException { Hudson.getInstance().getActions().removeAll(pluginActions); requiresConfigureRights = formData.getBoolean("requiresConfigureRights"); assignOnCreate=formData.getBoolean("assignOnCreate"); if (formData.containsKey("enableResolverRestrictions")) { JSONObject mailResolversConf = formData.getJSONObject("enableResolverRestrictions"); mailResolverClassName = hudson.Util.fixEmptyAndTrim(mailResolversConf.getString("mailResolverClassName")); } else { mailResolverClassName = null; } if (formData.containsKey("defaultJobsSecurity")) { this.defaultJobsSecurity = getItemSpecificDescriptor().newInstance(req, formData.getJSONObject("defaultJobsSecurity")); } ReinitActionsList(); save(); Hudson.getInstance().getActions().addAll(pluginActions); } public void ReinitActionsList() { pluginActions.clear(); } public static String getDefaultOwner() { User current = User.current(); return current !=null ? current.getId() : ""; } public boolean hasMailResolverRestriction() { return mailResolverClassName != null; } public String getMailResolverClassName() { return mailResolverClassName; } public FormValidation doCheckUser(@QueryParameter String userId) { userId = Util.fixEmptyAndTrim(userId); if (userId == null) { return FormValidation.error("Field is empty. Field will be ignored"); } User usr = User.get(userId, false, null); if (usr == null) { return FormValidation.warning("User " + userId + " is not registered in Jenkins"); } return FormValidation.ok(); } /** * Resolves e-mail using resolvers and global configuration. * @param user * @return */ public String resolveEmail(User user) { try { if (hasMailResolverRestriction()) { if (mailResolverClassName.equals(FAST_RESOLVER_ID)) { return FastEmailResolver.resolveFast(user); } else { Class<MailAddressResolver> resolverClass = (Class<MailAddressResolver>)Class.forName(mailResolverClassName); MailAddressResolver res = MailAddressResolver.all().get(resolverClass); return res.findMailAddressFor(user); } } } catch (ClassNotFoundException ex) { // Do nothing - fallback do default handler } return MailAddressResolver.resolve(user); } public Collection<String> getPossibleMailResolvers() { ExtensionList<MailAddressResolver> extensions = MailAddressResolver.all(); List<String> items =new ArrayList<String>(extensions.size()); items.add(FAST_RESOLVER_ID); for (MailAddressResolver resolver : extensions) { items.add(resolver.getClass().getCanonicalName()); } return items; } /** * Implements e-mail resolution by suffix. * @deprecated Class duplicates functionality of the Mailer 1.5 plugin. Will be removed in the new versions * @author Kohsuke Kawaguchi, Oliver Gondža, Alex Earl */ private static class FastEmailResolver { /** * Try to resolve user email address fast enough to be used from UI * <p> * This implementation does not trigger {@link MailAddressResolver} * extension point. * * @return User address or null if resolution failed */ public static String resolveFast(User u) { String extractedAddress = extractAddressFromId(u.getFullName()); if (extractedAddress != null) { return extractedAddress; } if (u.getFullName().contains("@")) // this already looks like an e-mail ID { return u.getFullName(); } String ds = Mailer.descriptor().getDefaultSuffix(); if (ds != null) { // another common pattern is "DOMAIN\person" in Windows. Only // do this when this full name is not manually set. see HUDSON-5164 Matcher m = WINDOWS_DOMAIN_REGEXP.matcher(u.getFullName()); if (m.matches() && u.getFullName().replace('\\', '_').equals(u.getId())) { return m.group(1) + ds; // user+defaultSuffix } return u.getId() + ds; } return null; } /** * Tries to extract an email address from the user id, or returns null */ private static String extractAddressFromId(String id) { Matcher m = EMAIL_ADDRESS_REGEXP.matcher(id); if (m.matches()) { return m.group(1); } return null; } /** * Matches strings like "Kohsuke Kawaguchi * &lt;[email protected]>" * @see #extractAddressFromId(String) */ private static final Pattern EMAIL_ADDRESS_REGEXP = Pattern.compile("^.*<([^>]+)>.*$"); /** * Matches something like "DOMAIN\person" */ private static final Pattern WINDOWS_DOMAIN_REGEXP = Pattern.compile("[^\\\\ ]+\\\\([^\\\\ ]+)"); } }
<reponame>devpcat/pribankcustmgt<filename>src/main/java/com/thyme/pribankcustmgt/mapper/PbcmCustExtpropAdminItemMapper.java package com.thyme.pribankcustmgt.mapper; import com.thyme.pribankcustmgt.entity.PbcmCustExtpropAdminItem; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author yuchao925 * @since 2020-04-04 */ public interface PbcmCustExtpropAdminItemMapper extends BaseMapper<PbcmCustExtpropAdminItem> { }
NEW YORK, May 6 -- Gay rights advocates celebrated swift and unexpected twin victories in New England on Wednesday when Maine became the fifth state to legalize same-sex marriage and New Hampshire's legislature shortly afterward sent a marriage equality bill to the governor. If Gov. John Lynch (D) signs the New Hampshire bill or allows it to become law without his signature, New Hampshire will become the sixth state to legalize marriages of same-sex couples, leaving Rhode Island as the only New England holdout. The movement in Maine and New Hampshire came faster than even gay rights advocates had expected and with bipartisan support in both places, suggesting that the question of same-sex marriage is losing some of its resonance as a divisive societal and political issue, at least in the Northeast. "There is no doubt there is a shift in attitudes and opinions," said Jennifer Chrisler, executive director of the Massachusetts-based Family Equality Council, which advocates legalization of gay marriage. "We're seeing it in poll after poll. We're seeing it at lunch counters and over kitchen tables." Massachusetts, Connecticut, Vermont and Iowa now allow gay men and lesbians to marry their partners. California briefly allowed such unions before a voter-backed referendum last year made same-sex marriage illegal -- and left in limbo the thousands of couples who had wed in the interim. The California Supreme Court is set to rule imminently on whether that referendum was constitutional. The Maine law came after a 21 to 13 vote in the state Senate, following an earlier state House vote, which sent the bill to Gov. John E. Baldacci (D), who has spoken against same-sex marriage. But Wednesday morning, according to some involved in the issue, Baldacci told legislative leaders that if the bill passed, he wanted it on his desk within two hours. In a statement, Baldacci said that although he was not raised to believe in same-sex marriage, he has come to see it as a civil rights issue. "I have come to believe that this is a question of fairness and of equal protection under the law," he said. Betsy Smith, executive director of Equality Maine, which had been pushing the issue, said: "We were not expecting it. What was not a surprise was he heard the thousands and thousands of Maine voters who raised their voices." The Maine law now faces the likely prospect of a referendum challenge much like California's. In Maine, citizens who collect 55,000 signatures can file a "people's veto" to have a law passed by the legislature overturned, and opponents of same-sex marriage have said they plan to do so. The law would not be enforced until the challenges were exhausted, and the first possible date for a referendum would be November. Smith predicted the gay rights advocates could prevail in tiny Maine, since they would need about 200,000 supporters in a referendum to keep same-sex marriage legal. "We can talk one-on-one to 200,000 voters," she said.
Brain Capillary Networks Across Species: A few Simple Organizational Requirements Are Sufficient to Reproduce Both Structure and Function Despite the key role of the capillaries in neurovascular function, a thorough characterization of cerebral capillary network properties is currently lacking. Here, we define a range of metrics (geometrical, topological, flow, mass transfer, and robustness) for quantification of structural differences between brain areas, organs, species, or patient populations and, in parallel, digitally generate synthetic networks that replicate the key organizational features of anatomical networks (isotropy, connectedness, space-filling nature, convexity of tissue domains, characteristic size). To reach these objectives, we first construct a database of the defined metrics for healthy capillary networks obtained from imaging of mouse and human brains. Results show that anatomical networks are topologically equivalent between the two species and that geometrical metrics only differ in scaling. Based on these results, we then devise a method which employs constrained Voronoi diagrams to generate 3D model synthetic cerebral capillary networks that are locally randomized but homogeneous at the network-scale. With appropriate choice of scaling, these networks have equivalent properties to the anatomical data, demonstrated by comparison of the defined metrics. The ability to synthetically replicate cerebral capillary networks opens a broad range of applications, ranging from systematic computational studies of structure-function relationships in healthy capillary networks to detailed analysis of pathological structural degeneration, or even to the development of templates for fabrication of 3D biomimetic vascular networks embedded in tissue-engineered constructs. S1.1 Generation of Voronoi diagram Each cell of length L C was divided into 16 × 16 × 16 pixels, and one seed was placed at a random pixel. The 3D Voronoi diagram was extracted using the MATLAB function voronoin, which returns the coordinates of vertices and the list of vertices belonging to each polyhedron, from which the network connectivity matrix was constructed. S1.2 Pruning the network Very small or narrow polyhedral faces (with area < 75 pixels or with any interior angle < 30°) were merged with the neighboring face sharing the longest edge of the current face ie. this edge was deleted. Similarly, neighbouring faces lying almost in a plane (solid angle < 15°) were merged. If any triangles with area < 75 pixels remained, the longest edge was removed. Final networks were not very sensitive to the choice of face area or angle criteria. Vertices were then removed or merged in two stages: 1. Boundary vertices. If two boundary vertices v b, 1 and v b,2 were located within some minimum distance D min of each other, v b,1 was arbitrarily deleted, but only if it was connected to an interior (i.e. non-boundary) vertex v i,1 which had more than three connections. If both boundary vertices were connected to the same interior vertex v i,1 , which itself only had three connections (v b,1 and v b,2 plus one other interior vertex v i,2 ), then v b,1 and v i,1 were deleted, and v b,2 was instead connected to v i,2 . If neither of these cases applied, v b,1 was moved a distance D min along the boundary away from v b,2 in the direction of the vector between the two vertices. 2. Interior vertices. To minimize the computationally heavy task of calculating the distance between all vertices, the domain was divided into sub-cubes of size L C × L C × L C (solid lines in 2D in Figure S1a). These cubes were shifted by 0.5L C in each direction yielding an off-set grid, to avoid missing vertex pairs spanning neighboring cubes (dashed lines in Figure S1a). Running through cubes in randomized order, the distance between each pair of vertices within the same cube was calculated. If a pair of vertices (v 1 and v 2 ) lay < D min from each other, as in Figure S1b, v 1 was arbitrarily deleted and its connections were re-attached to v 2 ( Figure S1c), but only if v 2 still had at least three connections. Otherwise, v 1 was moved a distance D min away from v 2 in the direction of the vector between the two vertices. Final networks were not very sensitive to the choice of D min , and thus its value was fixed at 2.5 pixels (for L C = 75µm, D min = 11.7µm). Next, excess edges between internal vertices were removed in random order according to the following criteria. An interior vertex could not have more than one connecting edge with a boundary vertex, except if it only had one internal connection, in which case it may be connected to two boundary vertices. If an internal vertex was not connected to any boundary vertices, it should have three connections to internal vertices. S1.3 Splitting multiply-connected vertices Vertices with more than 3 connections were treated in random order. For each multiply-connected vertex, the shortest connected edge was kept, as well as the edge with smallest solid angle relative to that Figure S1: a) Schematic diagram illustrating the division of the domain into a grid of length L C (solid lines) and an off-set grid shifted by 0.5L C (dashed lines), for efficient detection of vertices (black dots) less than distance D min apart. b) Illustration of two vertices v 1 and v 2 separated by less than D min ; c) vertex v 1 and its connections are merged into vertex v 2 ; d) -g) Sequence of schematic diagrams illustrating the division of a multiply-connected vertex with five connections into three bifurcations. See text for further details. edge (see e.g. the two edges in bold in Figure S1d). The center of mass of the remaining vertices was calculated (the cross in blue in Figure S1e), and a new vertex was placed on the vector between the initial vertex and the center of mass, at a distance of half the shortest length of the remaining edges, or D min , whichever is smaller (see the blue arrow in Figure S1e). This process was repeated until all interior vertices had only three connections (Figure S1f and g). This step introduced more short vessel lengths, but since there were typically only a small percentage of multiply-connected vertices, this did not have an important effect on overall network properties. S1.4 Domain size To avoid any boundary effects associated with the generation of these synthetic networks, for a desired domain size of L x × L y × L z , a larger network was initially generated in a domain of 2(L x + 2L C ) × 2(L y + 2L C ) × 2(L z + 2L C ) (with L i rounded up to the nearest multiple of L C ). At the end of the process, the desired sub-network in a domain of size L x × L y × L z was extracted from the center of the large domain. S2 Results in lattice networks Results for the two ordered, regular lattice networks introduced in Section 2.2.2 and shown in Figure 1Dare presented. These networks are referred to respectively as the CLN (with 6-connectivity) and the PLN (with 3-connectivity). After a study of the scaling properties of these networks, we present the results of metrics for chosen domain size and scaling. S2.1 Scaling of lattice networks We first present an analytical investigation into the scaling of these networks with domain size or with mean length L. Recall that in both lattice networks, the length of the elementary cubes, L C , is linearly proportional to L (L C = L in the CLN and L C = 3L in the PLN). The Voronoi-like synthetic networks, despite exhibiting greater randomness, also follow a similar semi-ordered structure controlled by the characteristic length L C . Thus we make the hypothesis that these metrics scale with L C in the same way, and use this to inform the scaling studies in Section 3.2. S2.1.1 Morphometrical metrics The mean vessel length was L for both lattice networks. The length density was 3L/L 3 for the CLN and 30L/(3L) 3 for the PLN. Obviously, none of these metrics depended on domain size, in contrast to the loop metrics studied below. S2.1.2 Topological metrics The scaling of topological metrics with domain size was derived analytically. Loop metrics computed for lattice networks generated for the range of domain sizes shown in Figure S2 agreed perfectly with the analytical expressions derived in this section. For both networks, we suppose that i, j and k are the number of unit cells in the x, y, and z directions respectively. Both lattice networks had two modes of loops, α = 1, 2, with m α edges per loop. We then define the mean number of edges per loop, N edge/loop (i, j, k), as the total number of loop edges, divided by the total number of loops, i.e.: where N α loop (i, j, k) are the number of loops corresponding to mode α. Similarly the mean loop length, L loop , was given by: and thus converged with domain size in the same way as N edge/loop (i, j, k), but also scaled with L. The mean number of loops per edge, N loop/edge (i, j, k), is the total number of loop edges divided by the number of interior (i.e. non-boundary) edges, N edge,int (i, j, k): These metrics were derived for the specific geometries of the CLNs and PLNs as follows. Cubic lattice network The CLN had two modes of loops with 4 and 6 edges respectively (m = {4, 6}). The number of loops with 4 edges, N 1 loop (i, j, k), followed: Similarly, the number of loops with 6 edges, N 2 loop (i, j, k), obeyed: where R(x) is the ramp function, defined as: Using Equation S1, the mean number of edges per loop for a cube of side length n = i = j = k and n ≥ 2 was given by: The mean number of edges per loop converged to within 5% of the converged value for networks of 4 3 unit cubes ( Figure S2a). Convergence was slow: this metric was only converged to within 5% of this value for networks of 36 3 unit cubes or greater ( Figure S2b). N edge/loop quickly converged to within 5% of this value for networks of 2 3 unit cubes ( Figure S2a). N loop/edge converged more quickly for the PLN than the CLN, and was within 5% of its converged value for networks of 11 3 unit cubes or more ( Figure S2b). Thus, in both lattice networks the number of loops per edge was especially sensitive to finite-size effects. Nonetheless, none of the loop metrics except the mean loop length depended on the choice of L (or equivalently L C ), and thus are purely topological metrics. S2.1.3 Permeability Cubic lattice network In the CLN, imposing a pressure gradient in the x-direction yields zero flow in vessels orientated parallel to the y-or z-axis: the network is reduced to an array of tubes of length L x S4 where L x is the ROI size in the x-direction. The global flowrate Q x is: where µ is the effective viscosity, d is the diameter (which here is uniform), and ∆P is the pressure drop. N is the number of boundary vessels on the face x = 0, expressed in terms of L, the edge length: From Equation (1), this yields: Rearranging and using the definition for the domain area perpendicular to the x-axis, A x = L y L z , gives: Figure S3: Flow distribution in an elementary motif of the PLN with a pressure gradient from left to right. The magnitude of the flow in the green vessels was half of that in the red vessels, and zero in the dark blue vessels. Periodic lattice network In the PLN, imposing a pressure gradient in the x-direction with uniform diameters also yields a simple flow distribution (Figure S3 and legend). The global flowrate obeys the same law in Equation S4, but N follows: In the minimal example shown in Figure S3, L y = 3L and L z = 3L giving N = 2. Substituting this expression into Equation (1) yields: Thus, to obtain the same permeability in both lattice networks, L in the PLN would have to be √ 2/3 = 0.47 times that of the CLN. Finally, for both lattice networks, the permeability scaled with d 4 and 1 /L 2 (or equivalently 1 /L 2 C )and did not depend on domain size (assuming uniform diameters). S2.2 Lattice networks scaled to match mouse ROIs In the CLN, L = 67µm was chosen to match the length density in mice. A network of 4 × 4 × 4 unit cubes was generated with dimensions 268 × 268 × 268µm 3 , to be as close as possible to the size of the mouse ROIs will containing whole unit cubes. In the PLN L = 41µm; with the unit cube side length being L C = 3L, a network of 2 × 2 × 2 unit cubes was generated with dimension 246 × 246 × 246µm 3 . Results in these networks are given in Table 1. Space-filling metrics In the box-counting analysis, the cut-off lengths for both lattice networks were of a similar order of magnitude to the other networks, but in contrast, both had linear regimes at small scales. The mean EVD was very close to the mouse data for both lattice networks, while the maximum EVD was lowest in the CLN, and highest in the PLN. The mean local maxima of EVDs were 22% and 61% higher in the PLNs and CLNs respectively. Morphometrical metrics The PLN had a similar mean length to that in mice, while that in the CLN was almost 50% higher. By construction, the length distributions in these networks were drastically different to the mouse and synthetic networks, with only one mode for each network, and hence zero SD. Due to the choice of L as described above, the mean length density in both networks was very close to that in mice. As a result, in the PLN both the edge density and vertex density were close to those in mice, whereas the CLN had a much lower edge and vertex density. Both lattice networks had a much lower density of boundary vertices (36% and 62% respectively). Topological metrics By construction the PLN had no multiply connected vertices, while all junctions in the CLN had 6 connections. The distri-S5 bution of loops was very different for the lattice networks, with fewer edges per loop (9 and 5.14 respectively) on average, with values restricted to two modes per network, as described above in Section S2.1.2. The mean loop length was also lower in both lattice networks than in mice. Flow metrics The mean velocity was 45% higher in both the lattice networks. Similarly, the mean permeability in the PLNs and especially the CLNs was much higher than in mice (almost 30% and 120% higher respectively), and completely isotropic due to their regular construction. Mass transfer metrics Unsurprisingly, the distribution of capillary transit times for lattice networks were very different to those in the synthetic and mouse ROIs ( Figure 8E). The exchange coefficient h was 26.5% and 32.9% higher in the PLNs and CLNs respectively compared mice. Robustness metrics For the PLN, the histogram of pre-to post-occlusion flow ratios was very different to the distributions for the mice and synthetic networks, due to its highly organized architecture ( Figure 8F), and was restricted to 3 modes. The mean flow ratio was approximately 10% lower than in mice. The CLN was not included because none of its vertices were converging bifurcations. In conclusion, while some simple morphometrical metrics in the lattice networks aligned well with those in mice, their highly organised structure meant that the distribution of metrics was completely different, and topological and functional metrics also differed greatly from the more randomized networks. Thus, such simple networks cannot be used to make accurate predictions of functional properties in the cerebral capillaries. 0.77 ± 0.03 0.76 ± 0.01 Post-occlusion flow ratio (diverging; branch A) 0.28 ± 0.05 0.28 ± 0.04 Table S1: The geometrical, topological and functional metrics calculated here, for human and synthetic with L C = 90µm ('S90') networks. Results are presented as mean ± S.D. over the N ROIs studied for each network type. Permeabilities, velocities and transit times were calculated with uniform diameters of 5µm. Table S2: In the synthetic networks, results of a standard linear regression on a range of metrics as a function of L C to the appropriate power, i.e. following the expression: αL n C + β, where n is the power appropriate for each metric. The coefficient of determination, R 2 , was very good for all fits.
package remoterepo import ( "testing" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/client" "gitlab.com/gitlab-org/gitaly/internal/git" "gitlab.com/gitlab-org/gitaly/internal/gitaly/config" "gitlab.com/gitlab-org/gitaly/internal/helper" "gitlab.com/gitlab-org/gitaly/internal/testhelper" "gitlab.com/gitlab-org/gitaly/internal/testhelper/testserver" "gitlab.com/gitlab-org/gitaly/proto/go/gitalypb" ) func TestRepository(t *testing.T) { _, serverSocketPath, cleanup := testserver.RunInternalGitalyServer(t, config.Config.GitalyInternalSocketPath(), config.Config.Storages, config.Config.Auth.Token) defer cleanup() ctx, cancel := testhelper.Context() defer cancel() ctx, err := helper.InjectGitalyServers(ctx, "default", serverSocketPath, config.Config.Auth.Token) require.NoError(t, err) pool := client.NewPool() defer pool.Close() git.TestRepository(t, func(t testing.TB, pbRepo *gitalypb.Repository) git.Repository { t.Helper() r, err := New(helper.OutgoingToIncoming(ctx), pbRepo, pool) require.NoError(t, err) return r }) }
Operation Bodenplatte – disaster for the Luftwaffe To support the German offensive through the Ardennes the Luftwaffe had planned a co-ordinated operation to try to neutralise the Allied fighter bombers. The heavily outnumbered Luftwaffe had made little impact on the battle so far. Rather than directly confronting the Allied fighters in the air, Operation Bodenplatte aimed to destroy as many Allied fighters on the ground as possible. News Year’s Day was the first day that the weather would be favourable from early morning. Luftwaffe pilot Willi Heilman of III Gruppe recalled the early morning excitement: We were awoken at 3 o’clock in the morning and half an hour later all the pilots of JG 26 and III/JG54 were assembled in the mess room. Hptm. Worner came in with the ominous envelope already open in his hand. ‘To make it brief boys, we’re taking off with more than a thousand fighters at the crack of dawn to prang various airfields on the Dutch-Belgian border’ Then followed the details of the take-off, flying order, targets and return flights. Brussels was the target of III/JG 54. The whole mission was to be carried out at less than 600 feet until we reached the targets so that the enemy ground stations could not pick us up. To this end, radio silence was the order until we reached the target. We were given a magnificent breakfast, cutlets, roast beef and a glass of wine. For sweets there were patries and several cups of fragrant coffee. The last minutes before we were airborne seemed an eternity. Nervous fingers stubbed out half smoked cigarettes. In the scarlet glow the sun slowly appeared above the horizon to the east. It was 8.25am. And the armada took off … This account, together with many more, appears in To Win the Winter Sky: The Air War over the Ardennes 1944-1945 Despite the careful planning Operation Bodenplatte did not achieve the level of surprise hoped for, only a minority of attacks were to hit undefended airfields. The Allied fighters were soon in the air and the large numbers of very inexperienced German pilots who had been pressed into service paid the price. To make matters worse the secrecy surrounding the operation meant that German anti-aircraft units had not been warned about it and more low flying planes fell to ‘friendly fire’. The Luftwaffe lost 143 pilots killed and missing, while 70 were captured and 21 wounded – it was the worst single day’s losses for the Luftwaffe. These pilots were irreplaceable. Although the Allies are estimated to have lost almost 300 aircraft destroyed and about 180 damaged on the ground, these were empty aircraft and such was the Allied supply situation most planes were replaced within a week. Contemporary film of aerial combat and ground strafing by planes of the 8th Air Force during this period: The Luftwaffe were now irreparably weakened as the Allied continued with not just the widespread fight bomber attacks, in support of the Army, but the heavy bombers’ assault on German cities. These continued at the same intensity that they had reached in 1944 – in the remaining months of the war 470,000 tons of bombs would fall on Germany, more than twice the tonnage that had fallen in the whole of 1943. Amongst the targets for the RAF on 1st January 1945 was the familiar site of the Dortmund-Ems Canal, a key route in German industrial supply. In 1940 a raid on the canal had led to the first Victoria Cross for Bomber Command. Now another member of Bomber Command was similarly recognised:
// NewAccountWarehouse creates a new AccountWarehouse using the provided client // and options. func NewWarehouse(store storage.Store) (*AccountWarehouse, error) { wh := &AccountWarehouse{ store: store, tmp: make(map[string]iam.AccessKey), } return wh, nil }
// AS creates new PgTsDictTable with assigned alias func (a *PgTsDictTable) AS(alias string) *PgTsDictTable { aliasTable := newPgTsDictTable() aliasTable.Table.AS(alias) return aliasTable }
A female sex worker and blogger has been exposed as a middle-aged man — which might not be such a big deal if he hadn't used his fake identity to solicit sex partners and naked photos of minors. According to a Metafilter post by Asparagirl, "Alexa di Carlo" said she was a sex worker and a student in San Francisco State University's sexuality studies program. She also ran a sex advice website for teenagers, and mentored other sex workers via email. But then the anonymous blog Expose a Bro outed Alexa as Thomas "Pat" Bohannan, a computer technician in Delaware. Simply maintaining a blog under a pseudonym might not have been a problem — says sex educator and blogger Charlie Glickman, "Personally, I don't care if someone wants to create an online fantasy personna. I don't think it's necessarily bad or unhealthy to explore the different facets of our psyches by writing stories." But Glickman and others are angry that Bohannon pretended to have credentials he didn't really possess — and added to the misrepresentation of sex work by non-sex workers. Advertisement That's not all, though: as Alexa, Bohannon reportedly referred new sex workers to a star client named Matt ... who turned out to be Bohannon himself (if you're not easily creeped out, here's an email in which Alexa describes "Matt"). Worse, he (in another persona known as "Caitlain" or "Cathy") allegedly encouraged minors to post seminude pictures of themselves on his teen sex website. One blogger describes her use of "Cathy's" site: On the forum, there was a specific few threads for posting pictures of your breasts and ass and more general ones for just pictures of yourself. Complete nudity was NOT permitted but this basically meant that if you posted a picture of your breasts with just your hand covering your nipples, you were fine. Even if you were a minor. She would encourage me when I expressed nervousness about posting a photograph of myself in just that position – I was 17. I posted the picture, and was extremely flattered by the response especially from Cathy. Most of the other members were as far as I know, under 18 or under 21 at least. The case isn't without its complexities — Sex and the 405 argues that the outing of an anonymous blogger sets "a dangerous precedent": "what's to stop well-meaning members of another community from coming together to expose a sex-worker, who is, by many state laws, engaging in criminal activity (i.e., prostitution)?" And outing has indeed had disturbing consequences for other sex bloggers' lives. But there's a big difference between maintaining anonymity or a pseudonym to protect yourself and constructing a false persona for the express purpose of deceiving people. The teen who wrote about "Cathy's" site offers this example of how damaging the latter can be: I once felt that Cathy's forums was a huge part of my understanding of my own sexuality, and Cathy herself an orchestrator of how I felt about myself. I was confident and happy and felt safe about showing my body to my friends on this forum. Now I know that the one person I thought of as the safest of all was the one lying about everything – well, I no longer feel very happy with myself. I feel sick and ashamed and terrified that these incredibly intimate, private photos are out there somewhere. I will never again have the confidence in my own sexuality that I once had because of this man, and my trust in people is shattered. I used to want to be like Cathy and tried to feel as sexually liberated as she did. Well now I feel the least interested in sex I have ever felt, because I've lost my own understanding of how I felt about it. Advertisement As many have pointed out both in relation to this story and elsewhere, sex work and sex blogging are misunderstood and stigmatized. That's one reason people who write about sex don't always write under their real names. But if everything bloggers are saying about Bohannon is true, then he used his pseudonym to fool and hurt people. He harmed sex workers by adding more misinformation to the conversation about their lives, he harmed sex bloggers by misusing the anonymity some of them need to write safely, and he harmed teens, who already have too few trustworthy resources to turn to when it comes to sexuality. It's unclear whether Bohannon will face any criminal investigation — Expose a Bro's information, while it seems convincing, might not hold up in court. But what is clear is if Bohannon was using a fake identity to act out the deceptions Expose a Bro describes, that identity does not deserve protection. Oh No, #Fauxho [Metafilter] Expose A Bro [Blogspot] Caitlain [Blogspot] Faux Ho! A Dangerous Crusade [Sex and the 405] The Downfall Of Alexa Di Carlo [Charlie Glickman] Image via Valeriy Lebedev/Shutterstock.com
import numpy as np import tensorflow as tf from typing import Dict from utils.sth import sth from Algorithms.tf2algos.base.policy import Policy from utils.on_policy_buffer import DataBuffer class On_Policy(Policy): def __init__(self, s_dim, visual_sources, visual_resolution, a_dim_or_list, is_continuous, **kwargs): super().__init__( s_dim=s_dim, visual_sources=visual_sources, visual_resolution=visual_resolution, a_dim_or_list=a_dim_or_list, is_continuous=is_continuous, **kwargs) def initialize_data_buffer(self, data_name_list=['s', 'visual_s', 'a', 'r', 's_', 'visual_s_', 'done']): self.data = DataBuffer(dict_keys=data_name_list) def store_data(self, s, visual_s, a, r, s_, visual_s_, done): """ for on-policy training, use this function to store <s, a, r, s_, done> into DataBuffer. """ assert isinstance(a, np.ndarray), "store need action type is np.ndarray" assert isinstance(r, np.ndarray), "store need reward type is np.ndarray" assert isinstance(done, np.ndarray), "store need done type is np.ndarray" self.data.add(s, visual_s, a, r, s_, visual_s_, done) def no_op_store(self, *args, **kwargs): pass def clear(self): """ clear the DataFrame. """ self.data.clear() def _learn(self, function_dict: Dict): ''' TODO: Annotation ''' _cal_stics = function_dict.get('calculate_statistics', lambda *args: None) _train = function_dict.get('train_function', lambda *args: None) # 训练过程 _train_data_list = function_dict.get('train_data_list', ['s', 'visual_s', 'a', 'discounted_reward', 'log_prob', 'gae_adv']) _summary = function_dict.get('summary_dict', {}) # 记录输出到tensorboard的词典 self.intermediate_variable_reset() if not self.is_continuous: self.data.convert_action2one_hot(self.a_counts) if self.use_curiosity: s, visual_s, a, r, s_, visual_s_ = self.data.get_curiosity_data() crsty_r, crsty_loss, crsty_summaries = self.curiosity_model(s, visual_s, a, s_, visual_s_) self.data.r = r.reshape([self.data.eps_len, -1]) self.summaries.update(crsty_summaries) else: crsty_loss = tf.constant(value=0., dtype=self._data_type) _cal_stics() all_data = self.data.sample_generater(self.batch_size, _train_data_list) for data in all_data: if self.use_rnn and self.burn_in_time_step: raise NotImplementedError # _s, _visual_s = self.data.get_burn_in_states() # cell_state = self.get_burn_in_feature(_s, _visual_s) else: cell_state = None data = list(map(self.data_convert, data)) summaries = _train(data, crsty_loss, cell_state) self.summaries.update(summaries) self.summaries.update(_summary) self.write_training_summaries(self.episode, self.summaries) self.clear()
/** * Puts the cache server record into the shared {@link CacheServerBlackboard} * map. */ private static Record putRecord(String name, HostDescription hd, int pid) { Record record = new Record(hd, pid); CacheServerBlackboard.getInstance().getSharedMap().put(name, record); return record; }
def a_slice(i_slice, max_index): return np.arange(*i_slice.indices(max_index), dtype = U32)
/** * This is the first <i>ScenarioSimulation</i> specific abstract class - i.e. it is bound to a specific use case. Not every implementation * would need this. Menu initialization may be done in other different ways. It is provided to avoid code duplication in concrete implementations */ public abstract class AbstractHeaderMenuPresenter extends BaseMenu implements HeaderMenuPresenter { protected ScenarioSimulationEditorConstants constants = ScenarioSimulationEditorConstants.INSTANCE; protected ScenarioGridModel model; protected String HEADERCONTEXTMENU_GRID_TITLE; protected String HEADERCONTEXTMENU_PREPEND_ROW; /** * The <b>Insert row below</b> menu element in the <b>header</b> contextual menu */ protected LIElement insertRowBelowElement; protected LIElement gridTitleElement; public void setEventBus(EventBus eventBus) { this.executableMenuItemPresenter.setEventBus(eventBus); } /** * This method set common <b>SCENARIO</b> menu items */ public void initMenu() { // SCENARIO gridTitleElement = addMenuItem(HEADERCONTEXTMENU_GRID_TITLE, constants.scenario(), "scenario"); insertRowBelowElement = addExecutableMenuItem(HEADERCONTEXTMENU_PREPEND_ROW, constants.insertRowBelow(), "insertRowBelow"); } public void show(final GridWidget gridWidget, final int mx, final int my) { super.show(mx, my); mapEvent(insertRowBelowElement, new PrependRowEvent(gridWidget)); } }
Please enable Javascript to watch this video A rookie LAPD officer who allegedly shot a 23-year-old man to death following a fight in Pomona fled to Texas with the help of his father, according to an FBI agent’s affidavit released Thursday. Henry Solis, 27, is suspected of killing Salome Rodriguez Jr. early March 13 after a physical altercation near a nightclub. While authorities continued to search for him, Solis was fired by Los Angeles Police Department Chief Charlie Beck on Tuesday, a day after Pomona police named the police officer as a suspect. An affidavit signed Thursday by FBI Special Agent Scott Garriola stated that Solis was charged with murder Tuesday in an arrest warrant issued by the Los Angeles Superior Court. Items left by Solis at the crime scene allowed Pomona detectives to identify him as the gunman, according to the affidavit. Soon after the shooting, Solis made statements that incriminated himself and said that he would never been seen again, Garriola wrote, citing interviews with family members, friends and witnesses. On the day of the shooting, Henry Solis called his father, Victor Solis, in Lancaster, and then the older man left the home in a hurry, Garriola wrote. The next day, Saturday, Victor Solis’ truck was spotted at relatives’ home in El Paso, Texas, and FBI agents interviewed him there two days later. Victor Solis told the FBI he drove his son to the bus station in El Paso and dropped him off. He did not know where his son had gone, he told agents. On Wednesday, the Los Angeles County District Attorney’s Officer asked for the FBI’s help finding and returning Solis to L.A. About noon Thursday, in response to Garriola's affidavit, a U.S. District Court magistrate issued a federal arrest warrant charging Henry Solis with fleeing to avoid prosecution for murder. Solis was a U.S. Marine before joining the LAPD in June, the Los Angeles Times reported. He worked for the Devonshire Division in Northridge. His actions were "most likely fueled by alcohol," Beck said Tuesday.
HealthZette To Replace Obamacare, Enforce Laws Already on the Books How costs can come down and choices for health care can go up On Tuesday night, like many Americans, I watched President Donald Trump’s address to Congress. Some watch President Trump for the same reasons others watch a NASCAR race — the exciting and unpredictable moments that might be forthcoming. Many of my Washingtonian patients watched because they wanted to know how he will affect their jobs in the federal bureaucracy or in D.C. lobbying firms. As a practicing physician, I share the same concerns. Advertisement [lz_ndn video=32056747] Our worsening federal deficit is essentially due to Medicare and Medicaid. Our elected leaders’ inability to explain in any detail how they might solve this problem (years in the making) and work in a bipartisan and productive way is frankly depressing. Trump outlined five points for a plan to replace what he called “this imploding Obamacare disaster,” all of which sound great, but none of which were any surprise. The first two points — access to coverage for those with pre-existing conditions, and allowing Americans to buy the plan they want, not one forced on them by the government — he promised throughout his campaign. Block grants for states for Medicaid was again, nothing new, nor was the ability to purchase health care plans across state lines. Related: Keeping Drug Costs Low — It’s About Time The final point, legal reforms that protect patients and doctors from unnecessary costs and to bring down the artificially high price of drugs immediately, aren’t necessary. We have laws in place to do this already, they just need to be enforced. On Tuesday night I didn’t get much insight into what “better, cheaper plan” President Trump might have. And one thing actually disturbed me. These people voted Trump into office and they aren’t happy with the lack of progress in health care reform. Advertisement One of President Trump’s special guests was Megan Crowley. At 15 months old, Megan was diagnosed with Pompe Disease and not expected to live more than a few years. To look for a cure, her father left his job with Big Pharma and eventually founded Novazyme Pharmaceuticals, a five person start-up that he built into a 100 person company. This company makes the orphan drug that has saved Megan’s life and treats a disease that affects about one in 40,000 to 300,000 live births and manifests itself in a variable fashion. Her presence was heart-rending and should help garner bipartisan support. But for what, exactly? While we heard during the campaign — promises to effectively address drug costs, we’ve seen little real action to date. Candidate Obama made similar promises and eight years later American drug costs are much worse. A few weeks ago when President Trump met with Pharmaceutical CEOs, there were no tough words, just promises of support. The result: Drug stocks spiked upward and drug prices remain unchanged or rising. [lz_third_party align=center width=630 includes=https://portal.aolonnetwork.com/o2/search/v/5898945ac4d21f4e4860ce1a#Basic%20Information] Rowdy town hall meetings are no doubt in part paid Democrat disruption, but there is clearly a group of dissatisfied Americans whose patience is wearing thinner by the day. These people voted Trump into office and they aren’t happy with the lack of progress in health care reform. I admit I’m one of them. Advertisement When I see Megan Crowley, I see more than the above. Megan Crowley’s presence can only be a signal to Big Pharma — it’s business as usual. The American consumer will continue to pay to support worldwide drug innovation as they increasingly they can’t afford to buy drugs available today that could keep them alive and well and out of the hospital. Related: Out-of-Pocket Costs for Out-of-Shape Patients If you can’t pay the exorbitant costs of modern health care like Crowley or Steve Jobs, you don’t contribute more to society than you “cost” — you’re out of luck. Health care “costs” don’t need to be so inflated except to transfer wealth from the American middle class to the medical monopolies. Perhaps my 93-year-old mother is right. Perhaps it’s time to let people live out their lives without all the medical intervention. Let people die when they get sick if they haven’t put away enough money to pay their health care bills. Or perhaps the president, who has said little about any of the Republican plans presented so far, has something far more rational and effective yet to bring forth. “A better health care plan for all Americans,” as he said in his speech. Advertisement America is still watching, and waiting. Dr. Ramin Oskoui, a cardiologist in the Washington, D.C., area, is CEO of Foxhall Cardiology PC and a regular contributor to LifeZette.
<reponame>by-student-2017/skpar-0.2.4_Ubuntu18.04LTS """Test plotting functions.""" import unittest import logging import os import numpy as np from numpy.random import random from skpar.dftbutils.queryDFTB import get_bandstructure from skpar.dftbutils.plot import plot_bs, magic_plot_bs from skpar.core.database import Database from skpar.core.plot import skparplot np.set_printoptions(precision=2, suppress=True) logging.basicConfig(level=logging.DEBUG) logging.basicConfig(format='%(message)s') LOGGER = logging.getLogger(__name__) def init_test_plot_bs(basename): """Some common initialisation for the test_plot_bs_*""" twd = '_workdir/test_plot' filename = os.path.join(twd, basename) if os.path.exists(filename): os.remove(filename) else: os.makedirs(twd, exist_ok=True) bsdata = np.loadtxt("reference_data/fakebands.dat", unpack=True) return filename, bsdata class BandstructurePlotTest(unittest.TestCase): """Test bandstructure plotting back-end and magic""" def test_plot_bs_1(self): """Can we plot a bandsturcture, given as a x, and y array?""" filename, bsdata = init_test_plot_bs('test_plot_bs_1.pdf') xx1 = bsdata[0] yy1 = bsdata[1:] xtl = None fig, _ax = plot_bs(xx1, yy1, ylim=(-2.5, 2.5), xticklabels=xtl, linelabels=['ref', 'model'], title='Test 1 array', xlabel=None) fig.savefig(filename) self.assertTrue(os.path.exists(filename)) def test_plot_bs_2(self): """Can we plot a two bandsturctures with shared k-points?""" filename, bsdata = init_test_plot_bs('test_plot_bs_2.pdf') xx1 = bsdata[0] yy1 = bsdata[1:] jitter = .1 * (0.5 - random(yy1.shape)) yy2 = yy1 + jitter xtl = [(1, 'X'), (6, 'Gamma'), (10, 'L')] plot_bs(xx1, [yy1, yy2], ylim=(-2.5, 2.5), xticklabels=xtl, linelabels=['ref', 'model'], title='Test 2 array common X', xlabel=None, filename=filename) self.assertTrue(os.path.exists(filename)) def test_plot_bs_3(self): """Can we plot a two bandsturctures with 2 sets of k-points?""" filename, bsdata = init_test_plot_bs('test_plot_bs_3.pdf') xx1 = bsdata[0] yy1 = bsdata[1:] jitter = .1 * (0.5 - random(yy1.shape)) yy2 = yy1 + jitter xtl = [(1, 'X'), (6, 'Gamma'), (11, 'L')] plot_bs([xx1, xx1], [yy1, yy2], ylim=(-2.5, 2.5), xticklabels=xtl, linelabels=['ref', 'model'], title='Test 2 bands 2 kpts', xlabel=None, filename=filename) self.assertTrue(os.path.exists(filename)) def test_plot_bs_4(self): """Can we plot a two bandsturctures with 2 different of k-points?""" filename, bsdata = init_test_plot_bs('test_plot_bs_4.pdf') xx1 = bsdata[0] yy1 = bsdata[1:] j = 6 jitter = .1 * (0.5 - random(yy1[:j, :8].shape)) yy2 = yy1[:j, :8] + jitter xx2 = xx1[:8] xtl = [(1, 'X'), (6, 'Gamma'), (8, 'K'), (11, 'L')] plot_bs([xx1, xx2], [yy1, yy2], ylim=(-2.5, 2.5), xticklabels=xtl, linelabels=['ref', 'model'], title='Test 2 bands 2 (different) kpts', xlabel=None, filename=filename) self.assertTrue(os.path.exists(filename)) def test_magic_plot_bs_1(self): """Can we call the magic without the need for magic?""" filename, bsdata = init_test_plot_bs('test_magic_plot_bs_1.pdf') xx1 = bsdata[0] yy1 = bsdata[1:] jitter = .1 * (0.5 - random(yy1.shape)) yy2 = yy1 + jitter xx2 = xx1 xtl = [(1, 'X'), (6, 'Gamma'), (8, 'K'), (11, 'L')] magic_plot_bs([xx1, xx2], [yy1, yy2], filename=filename, ylim=(-2.5, 2.5), xticklabels=xtl, linelabels=['ref', 'model'], title='Test magic without gap', xlabel=None) self.assertTrue(os.path.exists(filename)) def test_magic_plot_bs_2(self): """Can we call the magic with gap?""" filename, bsdata = init_test_plot_bs('test_magic_plot_bs_2.pdf') xx1 = bsdata[0] yy1 = bsdata[1:] jitter = .1 * (0.5 - random(yy1.shape)) yy2 = yy1 + jitter xx2 = xx1 xtl = [(1, 'X'), (6, 'Gamma'), (8, 'K'), (11, 'L')] eg1 = np.atleast_1d(0.3) eg2 = np.atleast_1d(0.4) magic_plot_bs([xx1, xx2, xx1, xx2], [eg1, eg2, yy1[:4], yy2[:4], yy1[4:], yy2[4:]], filename=filename, ylim=(-2.5, 2.5), colors=['b', 'darkred', 'b', 'darkred'], xticklabels=xtl, linelabels=['ref', 'model'], title='Test magic 2 Eg Eg VB VB CB CB', xlabel=None) self.assertTrue(os.path.exists(filename)) def test_magic_plot_bs_3(self): """Can we call the magic with gap (alternative yval order)?""" filename, bsdata = init_test_plot_bs('test_magic_plot_bs_3.pdf') xx1 = bsdata[0] yy1 = bsdata[1:] jitter = .1 * (0.5 - random(yy1.shape)) yy2 = yy1 + jitter xx2 = xx1 xtl = [(1, 'X'), (6, 'Gamma'), (8, 'K'), (11, 'L')] eg1 = np.atleast_1d(0.3) eg2 = np.atleast_1d(0.4) magic_plot_bs([xx1, xx1, xx2, xx2], [eg1, yy1[:4], yy1[4:], eg2, yy2[:4], yy2[4:]], filename=filename, ylim=(-2.5, 2.5), colors=['b', 'b', 'r', 'r'], xticklabels=xtl, linelabels=['ref', None, 'model', None], title='Test magic 3 Eg VB CB Eg VB CB', xlabel=None) self.assertTrue(os.path.exists(filename)) class GenericPlotTaskTest(unittest.TestCase): """Test generic plot-task from tasksdict for 1D and 2D plots""" def test_skparplot(self): """Can we plot a band-structure objectives?""" env = {} database = Database() latticeinfo = {'type': 'FCC', 'param': 5.4315} model = 'Si.bs' filename = '_workdir/test_plot/bs1.pdf' get_bandstructure(env, database, 'test_dftbutils/Si/bs/', model, latticeinfo=latticeinfo) modeldb = database.get(model) bands = modeldb['bands'] eps = 0.25 jitter = eps * (0.5 - random(bands.shape)) altbands = bands + jitter if os.path.exists(filename): os.remove(filename) else: os.makedirs('_workdir/test_plot', exist_ok=True) skparplot(modeldb['kvector'], [altbands, bands], filename=filename, xticklabels=modeldb['kticklabels'], xlabel='wave-vector', ylabel='Energy, eV', linelabels=['ref', 'model'], ylim=(-13, 6)) self.assertTrue(os.path.exists(filename)) if __name__ == '__main__': unittest.main()
/** * Verify that malformed float content throws a properly formed * JiBXParseException. */ public void testParseElementDouble() { UnmarshallingContext uctx = new UnmarshallingContext(); uctx.setDocument(new TestDocument(new int [] {IXMLReader.START_TAG, IXMLReader.TEXT, IXMLReader.END_TAG}, "namespace", "tag", "abc")); try { uctx.parseElementDouble("namespace", "tag", 1.0); fail("Expected JiBXParseException to be thrown"); } catch (JiBXException e) { assertEquals(e, new JiBXParseException(null, "abc", "namespace", "tag", null)); } }
<reponame>SaveTheRbtz/toolbox<gh_stars>10-100 package nw_retry import ( "github.com/watermint/toolbox/essentials/http/es_response" "github.com/watermint/toolbox/essentials/http/es_response_impl" "github.com/watermint/toolbox/essentials/log/esl" "github.com/watermint/toolbox/essentials/network/nw_client" "github.com/watermint/toolbox/essentials/network/nw_congestion" "github.com/watermint/toolbox/infra/api/api_context" "net/http" "time" ) func NewRatelimit(client nw_client.Rest) nw_client.Rest { return &RateLimit{ client: client, } } type RateLimit struct { client nw_client.Rest } const ( exitReasonSuccess = iota exitReasonTransportError exitReasonRateLimit ) func (z RateLimit) Call(ctx api_context.Context, req nw_client.RequestBuilder) (res es_response.Response) { var errRateLimit *ErrorRateLimit exitReason := exitReasonTransportError l := esl.Default() defer func() { switch exitReason { case exitReasonSuccess: nw_congestion.EndSuccess(ctx.ClientHash(), req.Endpoint()) case exitReasonRateLimit: reset := time.Now() if errRateLimit != nil { reset = errRateLimit.Reset } nw_congestion.EndRateLimit(ctx.ClientHash(), req.Endpoint(), reset) default: nw_congestion.EndTransportError(ctx.ClientHash(), req.Endpoint()) } }() nw_congestion.Start(ctx.ClientHash(), req.Endpoint()) res = z.client.Call(ctx, req) if res.IsSuccess() || res.TransportError() == nil { if res.IsSuccess() { exitReason = exitReasonSuccess } return res } switch res.Code() { case http.StatusTooManyRequests: l.Debug("Ratelimit", esl.Int("code", res.Code())) exitReason = exitReasonRateLimit errRateLimit = NewErrorRateLimitFromHeadersFallback(res.Headers()) return es_response_impl.NewTransportErrorResponse(errRateLimit, res) } return res }
/* * __slvg_col_range -- * Figure out the leaf pages we need and free the leaf pages we don't. */ static int __slvg_col_range(WT_SESSION_IMPL *session, WT_STUFF *ss) { WT_TRACK *jtrk; uint32_t i, j; for (i = 0; i < ss->pages_next; ++i) { if (ss->pages[i] == NULL) continue; for (j = i + 1; j < ss->pages_next; ++j) { if (ss->pages[j] == NULL) continue; if (ss->pages[j]->col_start > ss->pages[i]->col_stop) break; jtrk = ss->pages[j]; WT_RET(__slvg_col_range_overlap(session, i, j, ss)); if (ss->pages[j] != NULL && jtrk != ss->pages[j]) --j; } } return (0); }
// New returns an error with the provided message. func New(msg string) error { return &Error{ Message: msg, Stack: callers(), } }
/** Checks to see if the given config contains valid MySQL details. * @param config The config that you wish to check. * @return Whether the config has valid MySQL details. */ public static boolean isValidSql(YamlConfig config) { ConfigurationSection mySql = config.getConfigurationSection("mysql"); if (!exists(mySql.getString("hostname"), mySql.getString("port"), mySql.getString("username"), mySql.getString("password"), mySql.getString("database"))) { return false; } if (isValidHostname(mySql.getString("hostname")) == false) { return false; } if (isValidPort(mySql.getString("port")) == false) { return false; } return true; }
Designing and Implementing Health Concerns Caused by the COVID-19 Pandemic: Explorative Study Background Coronavirus and its psychological impacts on people have been taken into attention by scholars due to the psychosocial crisis. Fear, worry, and psychological agitation are common experiences due to uncertainties in the context of the COVID-19 pandemic. This study is a comprehensive research for finding the methods of intervention to these psychological health issues based on presumable concerns.Method a multi-stage mixed study conducted in 3 stages. Stage one was a qualitative study to prioritizing and determining concerns about coronavirus with an in-depth semi-structured interview. Stage two was another qualitative study to design an appropriate intervention through the Nominal group technique (NGT) by collecting the brainstorming’s health specialists or expert panel. Stage three was a quantitative study to determine the effect of BETTER therapy; the counseling method as a clinical intervention for high-risk populations who were randomly assigned to experimental or intervention and control groups. Results In stage one, participants expressed five main concerns about COVID-19. In stage two, the health concern like inaccurate information and unpredictable disease were identified as the priority concerns preceded in designing the intervention. In stage three, a significant difference between the two groups presents the clinical intervention was effective in improving performance, marital intimacy, and reducing the subjects’ distress.
-- module texture module Texture.Texture where import Math3D.Vector import Color.ColorInterface -- base types and enums import Utility.BaseEnum class Texture a where -- object -> u -> v -> hit point -> wave length -> Color information color :: a -> Double -> Double -> Vector -> WaveVal -> ColorRecord
/** * DTO container with formatting for a table row. */ @ApiModel(description = "DTO container with formatting for a table row.") public class TableRowFormat extends LinkElement { /** * Gets or sets the rule for determining the height of the table row. */ @JsonAdapter(HeightRuleEnum.Adapter.class) public enum HeightRuleEnum { ATLEAST("AtLeast"), EXACTLY("Exactly"), AUTO("Auto"); private String value; HeightRuleEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static HeightRuleEnum fromValue(String text) { for (HeightRuleEnum b : HeightRuleEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter< HeightRuleEnum > { @Override public void write(final JsonWriter jsonWriter, final HeightRuleEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public HeightRuleEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return HeightRuleEnum.fromValue(String.valueOf(value)); } } } @SerializedName("AllowBreakAcrossPages") private Boolean allowBreakAcrossPages = null; @SerializedName("HeadingFormat") private Boolean headingFormat = null; @SerializedName("Height") private Double height = null; @SerializedName("HeightRule") private HeightRuleEnum heightRule = null; public TableRowFormat allowBreakAcrossPages(Boolean allowBreakAcrossPages) { this.allowBreakAcrossPages = allowBreakAcrossPages; return this; } /** * Gets or sets a value indicating whether the text in a table row is allowed to split across a page break. * @return allowBreakAcrossPages **/ @ApiModelProperty(value = "Gets or sets a value indicating whether the text in a table row is allowed to split across a page break.") public Boolean getAllowBreakAcrossPages() { return allowBreakAcrossPages; } public void setAllowBreakAcrossPages(Boolean allowBreakAcrossPages) { this.allowBreakAcrossPages = allowBreakAcrossPages; } public TableRowFormat headingFormat(Boolean headingFormat) { this.headingFormat = headingFormat; return this; } /** * Gets or sets a value indicating whether the row is repeated as a table heading on every page when the table spans more than one page. * @return headingFormat **/ @ApiModelProperty(value = "Gets or sets a value indicating whether the row is repeated as a table heading on every page when the table spans more than one page.") public Boolean getHeadingFormat() { return headingFormat; } public void setHeadingFormat(Boolean headingFormat) { this.headingFormat = headingFormat; } public TableRowFormat height(Double height) { this.height = height; return this; } /** * Gets or sets the height of the table row in points. * @return height **/ @ApiModelProperty(value = "Gets or sets the height of the table row in points.") public Double getHeight() { return height; } public void setHeight(Double height) { this.height = height; } public TableRowFormat heightRule(HeightRuleEnum heightRule) { this.heightRule = heightRule; return this; } /** * Gets or sets the rule for determining the height of the table row. * @return heightRule **/ @ApiModelProperty(value = "Gets or sets the rule for determining the height of the table row.") public HeightRuleEnum getHeightRule() { return heightRule; } public void setHeightRule(HeightRuleEnum heightRule) { this.heightRule = heightRule; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TableRowFormat tableRowFormat = (TableRowFormat) o; return Objects.equals(this.allowBreakAcrossPages, tableRowFormat.allowBreakAcrossPages) && Objects.equals(this.headingFormat, tableRowFormat.headingFormat) && Objects.equals(this.height, tableRowFormat.height) && Objects.equals(this.heightRule, tableRowFormat.heightRule) && super.equals(o); } @Override public int hashCode() { return Objects.hash(allowBreakAcrossPages, headingFormat, height, heightRule, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TableRowFormat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" allowBreakAcrossPages: ").append(toIndentedString(allowBreakAcrossPages)).append("\n"); sb.append(" headingFormat: ").append(toIndentedString(headingFormat)).append("\n"); sb.append(" height: ").append(toIndentedString(height)).append("\n"); sb.append(" heightRule: ").append(toIndentedString(heightRule)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
def nyu(): A,B,C,X,Y = map(int,input().split()) return A,B,C,X,Y def kansu(A,B,C,X,Y): sum = 0 #(A+B)<=2C AとBの単品で終わらせる if A+B<=2*C: sum += A*X + B*Y return sum #(A+B)>2C xかyの大きいほうだけ2c分買う。AとBの単品に置き換えて値段をみる else: kosu_sa =0 if X>Y: sum = X * 2 * C if A < 2*C: sum = (sum - 2*C*(X-Y))+A*(X-Y) else: sum = Y * 2 * C if B < 2*C: sum = (sum - 2*C*(Y-X))+B*(Y-X) return sum A,B,C,X,Y = nyu() print(kansu(A,B,C,X,Y))
def assert_task_managers(params, task_dir): if "managers" not in params: return managers = params["managers"] Validator.assert_value(managers, "files_list", "managers", base_dir=task_dir) for manager in managers: _, ext = os.path.splitext(manager) if ext not in Constants.source_exts: raise Exception("Unknown manager extension: %s" % ext)
#include <iostream> using namespace std; string line[3]; int x, o; bool win(char c) { if (line[0][0]==line[1][1] && line[1][1]==line[2][2] && line[2][2]==c) return 1; if (line[0][2]==line[1][1] && line[1][1]==line[2][0] && line[2][0]==c) return 1; for (int i=0; i<3; i++) { int ok=1; for (int j=0; j<3; j++) if (line[i][j]!=c) ok=0; if (ok) return 1; } for (int j=0; j<3; j++) { int ok=1; for (int i=0; i<3; i++) if (line[i][j]!=c) ok=0; if (ok) return 1; } return 0; } int main() { for (int i=0; i<3; i++) cin>>line[i]; for (int i=0; i<3; i++) for (int j=0; j<3; j++) if (line[i][j]=='X') x++; else if (line[i][j]=='0') o++; if ((win('0') && x!=o)||(win('X') && x!=o+1)||(x!=o+1 && x!=o)) { cout<<"illegal"; return 0; } if (win('X') && x==o+1) { cout<<"the first player won"; return 0; } if (win('0') && x==o) //Att { cout<<"the second player won"; return 0; } if (x==5 && o==4 && !win('X') && !win('0')) { cout<<"draw"; return 0; } if (x==o) cout<<"first"; else cout<<"second"; return 0; }
// GetEuConfig returns the EuConfig field value if set, zero value otherwise. func (o *LinkTokenCreateRequest) GetEuConfig() LinkTokenEUConfig { if o == nil || o.EuConfig == nil { var ret LinkTokenEUConfig return ret } return *o.EuConfig }
n,k,d = map(int,input().split(" ")) def fsum(n,k): tab = [[0 for i in range(k+1)] for i in range(n+1)] for i in range(n+1): for j in range(k+1): if i == 0 or j == 0: tab[i][j] = 0 elif i == 1 or j == 1: tab[i][j] = 1 elif i == j: tab[i][j] = tab[i][j-1] + 1 elif j > i: tab[i][j] = tab[i][i] else: paths = 0 for j1 in range(1,j+1): if i-j1 > 0: paths += tab[i-j1][j] tab[i][j] = paths # print(tab) return tab[n][k] # print(fsum(3,3)) # print(fsum(3,0)) # print(fsum(n,k)) # b = fsum (n,d-1) # print(n,k,d ,f"{a}-{b}={a-b}") print((fsum(n,k) - fsum(n,d-1))% 1000000007)
def add_node_write(self, write): t = rospy.Time.now() delta_t = (t - self.last_write_update).to_sec() write_rate = float(write) / delta_t self.__node_write.append(write_rate) self.last_write_update = t
<gh_stars>0 print('Confederação Nacional de Natação') print('-' * 30) idade = int(input('Qual a sua idade: ')) if idade < 10: print('Categoria Mirim') elif idade < 15: print('Categoria Infantil') elif idade < 20: print('Categoria Junior') elif idade == 20: print('Categoria Senior') else: print('Categoria Master')
package is import ( "fmt" "github.com/corbym/gocrest" ) func describe(conjunction string, matchers []*gocrest.Matcher) string { var description string for x := 0; x < len(matchers); x++ { description += matchers[x].Describe if x+1 < len(matchers) { description += fmt.Sprintf(" %s ", conjunction) } } return description }
<gh_stars>100-1000 #![cfg(feature = "test")] use std::fmt::{self, Debug, Display, Formatter}; use std::fs::read_to_string; use std::result; use glob::glob; use serde::Deserialize; use std::error::Error; use yarte_lexer::error::{ErrorMessage, KiError, Result}; use yarte_lexer::pipes::{ _false, _true, and_then, debug, important, is_empty, is_len, map, map_err, not, then, }; use yarte_lexer::{ _while, alt, ascii, asciis, do_parse, is_ws, path, pipes, tac, tag, ws, Ascii, Cursor, Ki, Kinder, LexError, LexResult, Lexer, SArm, SExpr, SLocal, SStr, SVExpr, Sink, Span, Ws, S, }; #[derive(Debug, Clone, PartialEq, Deserialize)] pub enum Token<'a, Kind> where Kind: Kinder<'a>, { Arm(Ws, SArm), ArmKind(Ws, Kind, SArm), Comment(#[serde(borrow)] &'a str), Safe(Ws, SExpr), Local(Ws, SLocal), Expr(Ws, SVExpr), ExprKind(Ws, Kind, SVExpr), Lit( #[serde(borrow)] &'a str, #[serde(borrow)] SStr<'a>, #[serde(borrow)] &'a str, ), Block(Ws, SVExpr), BlockKind(Ws, Kind, SVExpr), } struct VecSink<'a, K: Ki<'a>>(Vec<S<Token<'a, K>>>); impl<'a, K: Ki<'a>> Sink<'a, K> for VecSink<'a, K> { fn arm(&mut self, ws: Ws, arm: SArm, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::Arm(ws, arm), span)); Ok(()) } fn arm_kind(&mut self, ws: Ws, kind: K, arm: SArm, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::ArmKind(ws, kind, arm), span)); Ok(()) } fn block(&mut self, ws: Ws, expr: SVExpr, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::Block(ws, expr), span)); Ok(()) } fn block_kind(&mut self, ws: Ws, kind: K, expr: SVExpr, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::BlockKind(ws, kind, expr), span)); Ok(()) } fn comment(&mut self, src: &'a str, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::Comment(src), span)); Ok(()) } fn expr(&mut self, ws: Ws, expr: SVExpr, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::Expr(ws, expr), span)); Ok(()) } fn expr_kind(&mut self, ws: Ws, kind: K, expr: SVExpr, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::ExprKind(ws, kind, expr), span)); Ok(()) } fn lit(&mut self, left: &'a str, src: SStr<'a>, right: &'a str, span: Span) { self.0.push(S(Token::Lit(left, src, right), span)); } fn local(&mut self, ws: Ws, local: SLocal, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::Local(ws, local), span)); Ok(()) } fn safe(&mut self, ws: Ws, expr: SExpr, span: Span) -> LexResult<K::Error> { self.0.push(S(Token::Safe(ws, expr), span)); Ok(()) } fn end(&mut self) -> LexResult<K::Error> { Ok(()) } } pub fn parse<'a, K: Ki<'a>>( i: Cursor<'a>, ) -> result::Result<Vec<S<Token<'a, K>>>, ErrorMessage<K::Error>> { Ok(Lexer::<K, VecSink<'a, K>>::new(VecSink(vec![])).feed(i)?.0) } #[derive(Debug, Deserialize)] struct Fixture<'a, Kind: Ki<'a>> { #[serde(borrow)] src: &'a str, #[serde(borrow)] exp: Vec<S<Token<'a, Kind>>>, } #[derive(Debug, Deserialize)] struct FixturePanic<'a>(#[serde(borrow)] &'a str); fn comment<'a, K: Ki<'a>>(i: Cursor<'a>) -> Result<&'a str, K::Error> { const E: Ascii = ascii!('!'); const B: &[Ascii] = asciis!("--"); const END_B: &[Ascii] = asciis!("--}}"); const END_A: &[Ascii] = asciis!("}}"); let (c, _) = tac(i, E)?; let (c, expected) = if c.starts_with(B) { (c.adv_ascii(B), END_B) } else { (c, END_A) }; let mut at = 0; loop { if c.adv_starts_with(at, expected) { break Ok((c.adv(at + expected.len()), &c.rest[..at])); } else { at += 1; if at >= c.len() { break Err(LexError::Next( K::Error::UNCOMPLETED, Span::from_cursor(i, c), )); } } } } #[derive(Debug, Clone, PartialEq, Deserialize)] enum MyKindAfter<'a> { Partial(&'a str), Some, Str(&'a str), } impl<'a> Kinder<'a> for MyKindAfter<'a> { type Error = MyError; const OPEN: Ascii = ascii!('{'); const CLOSE: Ascii = ascii!('}'); const OPEN_EXPR: Ascii = ascii!('{'); const CLOSE_EXPR: Ascii = ascii!('}'); const OPEN_BLOCK: Ascii = ascii!('{'); const CLOSE_BLOCK: Ascii = ascii!('}'); const WS: Ascii = ascii!('~'); const WS_AFTER: bool = true; fn parse(i: Cursor<'a>) -> Result<Self, Self::Error> { const PARTIAL: Ascii = ascii!('>'); let ws = |i| pipes!(i, ws: is_empty: _false); do_parse!(i, tac[PARTIAL] => ws => p= path => ws => (MyKindAfter::Partial(p)) ) } fn comment(i: Cursor<'a>) -> Result<&'a str, Self::Error> { comment::<Self>(i) } } #[derive(Debug, Clone, PartialEq, Deserialize)] enum MyKind<'a> { Partial(&'a str), Some, Str(&'a str), } impl<'a> Kinder<'a> for MyKind<'a> { type Error = MyError; const OPEN: Ascii = ascii!('{'); const CLOSE: Ascii = ascii!('}'); const OPEN_EXPR: Ascii = ascii!('{'); const CLOSE_EXPR: Ascii = ascii!('}'); const OPEN_BLOCK: Ascii = ascii!('{'); const CLOSE_BLOCK: Ascii = ascii!('}'); const WS: Ascii = ascii!('~'); const WS_AFTER: bool = false; fn parse(i: Cursor<'a>) -> Result<Self, Self::Error> { alt!(i, some | partial) } fn comment(i: Cursor<'a>) -> Result<&'a str, Self::Error> { comment::<Self>(i) } } fn partial(i: Cursor) -> Result<MyKind, MyError> { const PARTIAL: Ascii = ascii!('>'); let ws = |i| pipes!(i, ws: _true); do_parse!(i, tac[PARTIAL] => ws => p= path => ws:important => (MyKind::Partial(p)) ) } fn some(i: Cursor) -> Result<MyKind, MyError> { const SOME: &[Ascii] = asciis!("some"); let tag = |i| { pipes!(i, tag[SOME]: map_err::<_, MyError, _>[|_| MyError::Some]: then::<_, _, MyKind, _>[|_| Err(MyError::Some)]: and_then[|_| Ok(MyKind::Some)] ) }; let ws = |i| pipes!(i, ws:is_empty:_false:map[|_| MyKind::Some]); do_parse!(i, tag => ws => (MyKind::Some)) } #[derive(Debug, Clone, PartialEq, Deserialize)] enum MyKindBlock<'a> { Partial(&'a str), Some, Str(&'a str), } impl<'a> Kinder<'a> for MyKindBlock<'a> { type Error = MyError; const OPEN: Ascii = ascii!('{'); const CLOSE: Ascii = ascii!('}'); const OPEN_EXPR: Ascii = ascii!('{'); const CLOSE_EXPR: Ascii = ascii!('}'); const OPEN_BLOCK: Ascii = ascii!('%'); const CLOSE_BLOCK: Ascii = ascii!('%'); const WS: Ascii = ascii!('~'); const WS_AFTER: bool = true; fn parse(i: Cursor<'a>) -> Result<Self, Self::Error> { const PARTIAL: Ascii = ascii!('>'); let ws_not_empty = |i| pipes!(i, ws: is_empty: _false); let ws_0 = |i| pipes!(i, _while[is_ws]:is_len[0]:debug["Len"]:_false:is_empty:_true:not:_false); // TODO: remove unnecessary [] do_parse!(i, tac[PARTIAL] => ws_not_empty => p= path => ws_not_empty[]:debug["after"] => ws_0[]:debug["ws_0"] => (MyKindBlock::Partial(p)) ) } fn comment(i: Cursor<'a>) -> Result<&'a str, Self::Error> { comment::<Self>(i) } } #[derive(Debug, Clone, PartialEq)] enum MyError { Some, Str(&'static str), StrO(String), } impl Display for MyError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Debug::fmt(self, f) } } impl Error for MyError {} impl KiError for MyError { const EMPTY: Self = MyError::Some; const UNCOMPLETED: Self = MyError::Some; const PATH: Self = MyError::Some; const WHITESPACE: Self = MyError::Some; fn str(s: &'static str) -> Self { MyError::Str(s) } fn char(_: char) -> Self { MyError::Some } fn string(s: String) -> Self { MyError::StrO(s) } } macro_rules! features { ($name:ident: $path:literal $kind:ty) => { #[test] fn $name() { for entry in glob($path).expect("Failed to read glob pattern") { let name = entry.expect("File name"); eprintln!("\n{:?}\n", name); let src = read_to_string(name).expect("Valid file"); let fixtures: Vec<Fixture<'_, $kind>> = ron::from_str(&src).expect("Valid Fixtures"); for (i, Fixture { src, exp }) in fixtures.into_iter().enumerate() { let res = parse::<$kind>(unsafe { Cursor::new(src, 0) }).expect("Valid parse"); eprintln!("{:2}:\nBASE {:?} \nEXPR {:?}", i, exp, res); assert_eq!(res, exp); } } } }; ($name:ident: $path:literal $kind:ty, $($t:tt)*) => { features!($name: $path $kind); features!($($t)*); }; () => {} } features!( test_after_same_features: "./tests/fixtures/features/**/*.ron" MyKindAfter, test_after_same_features_a: "./tests/fixtures/features_a/**/*.ron" MyKindAfter, test_same_features: "./tests/fixtures/features/**/*.ron" MyKind, test_same_features_b: "./tests/fixtures/features_b/**/*.ron" MyKind, test_after_block_features: "./tests/fixtures/features/**/*.ron" MyKindBlock, test_after_block_features_a: "./tests/fixtures/features_a/**/*.ron" MyKindBlock, test_after_block: "./tests/fixtures/block/**/*.ron" MyKindBlock, ); #[test] fn test_panic() { for entry in glob("./tests/fixtures/panic/**/*.ron").expect("Failed to read glob pattern") { let name = entry.expect("File name"); let src = read_to_string(name).expect("Valid file"); let fixtures: Vec<FixturePanic> = ron::from_str(&src) .map_err(|e| eprintln!("{:?}", e)) .expect("Valid Fixtures"); for FixturePanic(src) in fixtures { assert!(parse::<MyKind>(unsafe { Cursor::new(src, 0) }).is_err()); } } }
<filename>src/Network/Nats/Protocol/Message.hs {-| Module : Network.Nats.Protocol.Message Description: Message definitions and utilities for the NATS protocol -} {-# LANGUAGE OverloadedStrings #-} module Network.Nats.Protocol.Message ( Message(..) , PartialMessage , parseMessage , parseServerBanner , parseSubject ) where import Control.Applicative ((<|>)) import Data.Aeson (eitherDecodeStrict) import Network.Nats.Protocol.Types import qualified Data.Attoparsec.ByteString.Char8 as A import qualified Data.ByteString.Char8 as BS -- | Messages received from the NATS server data Message = Message BS.ByteString -- ^ A published message, containing a payload | OKMsg -- ^ Acknowledgment from server after a client request | ErrorMsg BS.ByteString -- ^ Error message from server after a client request | Banner BS.ByteString -- ^ Server "banner" received via an INFO message | Ping -- ^ Server ping challenge deriving Show -- | Parser function for incrementally parsing a message. type PartialMessage = BS.ByteString -> A.Result Message -- | Specialized parsed to return a NatsServerInfo parseServerBanner :: BS.ByteString -> Either String NatsServerInfo parseServerBanner bannerBytes = do case A.parseOnly bannerParser bannerBytes of Left err -> Left err Right (Banner b) -> eitherDecodeStrict b Right a -> Left $ "Expected server banner, got " ++ (show a) -- | Parses a Message from a ByteString parseMessage :: BS.ByteString -> A.Result Message parseMessage = A.parse messageParser bannerParser :: A.Parser Message bannerParser = do _ <- A.string "INFO" banner <- A.skipSpace >> A.takeTill (== '\r') _ <- A.string "\r\n" return $ Banner banner -- | Parse a 'BS.ByteString' into a 'Subject' or return an error message. See <http://nats.io/documentation/internals/nats-protocol/> parseSubject :: BS.ByteString -> Either String Subject parseSubject = A.parseOnly $ subjectParser <* A.endOfInput -- | The actual parser is quite dumb, it doesn't try to validate silly subjects. subjectParser :: A.Parser Subject subjectParser = do tokens <- A.takeWhile1 (not . A.isSpace) `A.sepBy` A.char '.' return $ makeSubject $ BS.intercalate "." tokens msgParser :: A.Parser Message msgParser = do _ <- A.string "MSG" A.skipSpace (_subject, _subscriptionId, _replyTo, msgLength) <- msgMetadataParser1 <|> msgMetadataParser2 payload <- A.take msgLength _ <- A.string "\r\n" return $ Message payload msgMetadataParser1 :: A.Parser (Subject, BS.ByteString, Maybe BS.ByteString, Int) msgMetadataParser1 = do subject <- subjectParser subscriptionId <- A.skipSpace >> A.takeTill A.isSpace replyTo <- A.skipSpace >> A.takeTill A.isSpace msgLength <- A.skipSpace >> A.decimal _ <- A.string "\r\n" return (subject, subscriptionId, Just replyTo, msgLength) msgMetadataParser2 :: A.Parser (Subject, BS.ByteString, Maybe BS.ByteString, Int) msgMetadataParser2 = do subject <- subjectParser subscriptionId <- A.skipSpace >> A.takeTill A.isSpace msgLength <- A.skipSpace >> A.decimal _ <- A.string "\r\n" return (subject, subscriptionId, Nothing, msgLength) okParser :: A.Parser Message okParser = do _ <- A.string "+OK" _ <- A.string "\r\n" return OKMsg singleQuoted :: A.Parser BS.ByteString singleQuoted = do _ <- A.char '\'' str <- A.takeWhile $ \c -> c /= '\'' _ <- A.char '\'' return str errorParser :: A.Parser Message errorParser = do _ <- A.string "-ERR" A.skipSpace err <- singleQuoted _ <- A.string "\r\n" return $ ErrorMsg err pingParser :: A.Parser Message pingParser = do _ <- A.string "PING" *> A.string "\r\n" return Ping messageParser :: A.Parser Message messageParser = bannerParser <|> msgParser <|> okParser <|> errorParser <|> pingParser
#[doc = "Writer for register SRACT"] pub type W = crate::W<u32, super::SRACT>; #[doc = "Register SRACT `reset()`'s with value 0"] impl crate::ResetValue for super::SRACT { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Activate Group Service Request Node 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum AGSR0_AW { #[doc = "0: No action"] VALUE1 = 0, #[doc = "1: Activate the associated service request line"] VALUE2 = 1, } impl From<AGSR0_AW> for bool { #[inline(always)] fn from(variant: AGSR0_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `AGSR0`"] pub struct AGSR0_W<'a> { w: &'a mut W, } impl<'a> AGSR0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AGSR0_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(AGSR0_AW::VALUE1) } #[doc = "Activate the associated service request line"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(AGSR0_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Activate Group Service Request Node 1\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum AGSR1_AW { #[doc = "0: No action"] VALUE1 = 0, #[doc = "1: Activate the associated service request line"] VALUE2 = 1, } impl From<AGSR1_AW> for bool { #[inline(always)] fn from(variant: AGSR1_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `AGSR1`"] pub struct AGSR1_W<'a> { w: &'a mut W, } impl<'a> AGSR1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AGSR1_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(AGSR1_AW::VALUE1) } #[doc = "Activate the associated service request line"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(AGSR1_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Activate Group Service Request Node 2\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum AGSR2_AW { #[doc = "0: No action"] VALUE1 = 0, #[doc = "1: Activate the associated service request line"] VALUE2 = 1, } impl From<AGSR2_AW> for bool { #[inline(always)] fn from(variant: AGSR2_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `AGSR2`"] pub struct AGSR2_W<'a> { w: &'a mut W, } impl<'a> AGSR2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AGSR2_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(AGSR2_AW::VALUE1) } #[doc = "Activate the associated service request line"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(AGSR2_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Activate Group Service Request Node 3\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum AGSR3_AW { #[doc = "0: No action"] VALUE1 = 0, #[doc = "1: Activate the associated service request line"] VALUE2 = 1, } impl From<AGSR3_AW> for bool { #[inline(always)] fn from(variant: AGSR3_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `AGSR3`"] pub struct AGSR3_W<'a> { w: &'a mut W, } impl<'a> AGSR3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AGSR3_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(AGSR3_AW::VALUE1) } #[doc = "Activate the associated service request line"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(AGSR3_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Activate Shared Service Request Node 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ASSR0_AW { #[doc = "0: No action"] VALUE1 = 0, #[doc = "1: Activate the associated service request line"] VALUE2 = 1, } impl From<ASSR0_AW> for bool { #[inline(always)] fn from(variant: ASSR0_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `ASSR0`"] pub struct ASSR0_W<'a> { w: &'a mut W, } impl<'a> ASSR0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ASSR0_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(ASSR0_AW::VALUE1) } #[doc = "Activate the associated service request line"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(ASSR0_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Activate Shared Service Request Node 1\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ASSR1_AW { #[doc = "0: No action"] VALUE1 = 0, #[doc = "1: Activate the associated service request line"] VALUE2 = 1, } impl From<ASSR1_AW> for bool { #[inline(always)] fn from(variant: ASSR1_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `ASSR1`"] pub struct ASSR1_W<'a> { w: &'a mut W, } impl<'a> ASSR1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ASSR1_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(ASSR1_AW::VALUE1) } #[doc = "Activate the associated service request line"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(ASSR1_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Activate Shared Service Request Node 2\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ASSR2_AW { #[doc = "0: No action"] VALUE1 = 0, #[doc = "1: Activate the associated service request line"] VALUE2 = 1, } impl From<ASSR2_AW> for bool { #[inline(always)] fn from(variant: ASSR2_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `ASSR2`"] pub struct ASSR2_W<'a> { w: &'a mut W, } impl<'a> ASSR2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ASSR2_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(ASSR2_AW::VALUE1) } #[doc = "Activate the associated service request line"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(ASSR2_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Activate Shared Service Request Node 3\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ASSR3_AW { #[doc = "0: No action"] VALUE1 = 0, #[doc = "1: Activate the associated service request line"] VALUE2 = 1, } impl From<ASSR3_AW> for bool { #[inline(always)] fn from(variant: ASSR3_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `ASSR3`"] pub struct ASSR3_W<'a> { w: &'a mut W, } impl<'a> ASSR3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ASSR3_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No action"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(ASSR3_AW::VALUE1) } #[doc = "Activate the associated service request line"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(ASSR3_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } impl W { #[doc = "Bit 0 - Activate Group Service Request Node 0"] #[inline(always)] pub fn agsr0(&mut self) -> AGSR0_W { AGSR0_W { w: self } } #[doc = "Bit 1 - Activate Group Service Request Node 1"] #[inline(always)] pub fn agsr1(&mut self) -> AGSR1_W { AGSR1_W { w: self } } #[doc = "Bit 2 - Activate Group Service Request Node 2"] #[inline(always)] pub fn agsr2(&mut self) -> AGSR2_W { AGSR2_W { w: self } } #[doc = "Bit 3 - Activate Group Service Request Node 3"] #[inline(always)] pub fn agsr3(&mut self) -> AGSR3_W { AGSR3_W { w: self } } #[doc = "Bit 8 - Activate Shared Service Request Node 0"] #[inline(always)] pub fn assr0(&mut self) -> ASSR0_W { ASSR0_W { w: self } } #[doc = "Bit 9 - Activate Shared Service Request Node 1"] #[inline(always)] pub fn assr1(&mut self) -> ASSR1_W { ASSR1_W { w: self } } #[doc = "Bit 10 - Activate Shared Service Request Node 2"] #[inline(always)] pub fn assr2(&mut self) -> ASSR2_W { ASSR2_W { w: self } } #[doc = "Bit 11 - Activate Shared Service Request Node 3"] #[inline(always)] pub fn assr3(&mut self) -> ASSR3_W { ASSR3_W { w: self } } }
/** * Initialize game display with starting positions/values */ public void init() { Log.v("GAME DISPLAY","Initializing..."); this.board.init(); this.toolBox.init(); Log.v("GAME DISPLAY","Initialization complete."); }
Neighborhoods remain the crucible of social life, even in the internet age. Children do not stream lectures — they go to school. They play together in parks and homes, not over Skype. Crime and fear of crime are experienced locally, as is the police response to it. But wide income gaps and America’s legacy of racial segregation result in wide differences between neighborhoods on a range of measures. Two major new studies from Harvard economists Raj Chetty and Nathaniel Hendren show that neighborhoods matter not only for daily life, but for the life chances of the children raised there. Drawing on a unique data set based on the tax records of 44 million households, the first study shows that locality matters a great deal for the future income of children. The second study of roughly 13,000 children is smaller but packs a big policy punch, since it directly contradicts recent evaluations of a major policy initiative — Moving to Opportunity (MTO) — carried out by leading social scientists. In short: MTO seems to work, after all. MTO, Act I: Ideals MTO was started in 1994 by the Department of Housing and Urban Development. In a handful of large cities, a few thousand public-housing residents were randomly assigned to one of three programs: An experimental group that received a rental subsidy (voucher) but had to move to a low-poverty neighborhood for at least one year A Section-8 group that received a voucher but no restriction on movement A control group that received no voucher. Economists love random assignment, because it helps overcome one of the biggest problems in social science: isolating causation from correlation. It’s like a social science pharmaceutical trial. Around half the experimental group “took their medicine” and moved to less poor areas; that is, the proportion living in neighborhood poverty fell by roughly half, from 40 percent to 20 percent. There were limits, however: the voucher didn’t allow them to buy their way into affluent neighborhoods with great schools, so much as somewhat less poor neighborhoods with schools that were slightly better. Teams of economists and other social scientists published analyses of MTO data in leading academic journals (see the table at the end of the piece). MTO, Act II: Disappointment These studies were disappointing, especially for those, like myself, who believe that harmful neighborhood qualities have impeded the social progress of the poor. The key findings were that: Neighborhood poverty has no effect on adult earnings or employment. Neighborhood poverty has no consistent positive effects on the behavior of children or their academic performance. Neighborhood poverty improves some aspects of adult mental and physical health. MTO Act III: Reflection These findings, especially the second, contradicted a large body of social science theory and non-experimental evidence, mostly from sociologists, like William Julius Wilson and Douglas Massey. They and other sociologists suggested that the limitations of the study explained the absence of observable effects. In a very recent example, Massey and I found that neighborhood income during childhood strongly predicts adult incomes. Our evidence suggested a causal effect, too, since neighborhood income even explained differences in sibling incomes. Author Jonathan Rothwell Former Brookings Expert Senior Economist - Gallup Less noticed, the first wave of MTO findings also contradicted a powerful body of experimental evidence from school lottery and voucher programs. These studies had consistently found that attending better schools—measured in various ways—boosted the academic performance (and eventual earnings) of children, especially those from poor families. MTO Act IV: Vindication With their new study, Chetty and Hendren (along with Lawrence Katz, an author of many of the previous studies) provide very strong evidence for the positive impact of MTO. Specifically, moving to a less poor neighborhood in childhood (i.e., before the age of 13): Increased future annual income by the mid-twenties by roughly $3,500 (31%) Boosted marriage rates (by 2 percentage points) Raised both college attendance rates (by 2.5 percentage points) and quality of college attended The age of the child moved was a critical factor: moving to a less poor neighborhood in the teenage years had no significant impact on later earnings or other adult outcomes. Lessons from MTO evaluation There was nothing wrong with the earlier round of MTO evaluations in themselves: the main problem was that the positive effects of leaving poor neighborhoods as a child could not be observed until the children were old enough to finish college and enter the adult labor market. In measuring adult outcomes, scholars of MTO thought creatively about capturing alternative outcomes, like mental health, that had not previously been studied in this context. Still, some of the scholars who conducted earlier studies were too quick to write off MTO specifically and, more importantly, neighborhood effects more generally. As Chetty and his colleagues show, even a few extra years of data can make all the difference. Now we can be even more confident that when it comes to equality and opportunity, place matters.
class GLM: """Generalized Linear Model. Parameters: optimizer (optim.Optimizer): The sequential optimizer used to find the best weights. loss (optim.Loss): The loss function to optimize for. intercept (float): Initial intercept value. intercept_lr (float): Learning rate used for updating the intercept. Setting this to 0 means that no intercept will be used, which sometimes helps. l2 (float): Amount of L2 regularization used to push weights towards 0. Attributes: weights (collections.defaultdict) """ def __init__(self, optimizer, loss, l2, intercept, intercept_lr): self.optimizer = optimizer self.loss = loss self.l2 = l2 self.intercept = intercept self.intercept_lr = intercept_lr self.weights = collections.defaultdict(float) def raw_dot(self, x): return utils.dot(self.weights, x) + self.intercept def fit_one(self, x, y): # Some optimizers need to do something before a prediction is made self.weights = self.optimizer.update_before_pred(w=self.weights) # Obtain the gradient of the loss with respect to the raw output g_loss = self.loss.gradient(y_true=y, y_pred=self.raw_dot(x)) # Clip the gradient of the loss to avoid numerical instabilities g_loss = utils.clamp(g_loss, -1e12, 1e12) # Calculate the gradient gradient = { i: xi * g_loss + 2. * self.l2 * self.weights.get(i, 0) for i, xi in x.items() } # Update the weights self.weights = self.optimizer.update_after_pred(w=self.weights, g=gradient) # Update the intercept self.intercept -= g_loss * self.intercept_lr return self
Evaluation of routine radiation boost following breast conservation therapy in young patient. 709 Background: A recent trial compared local radiation boost (RB) to no local boost (NB) following breast conservation therapy. Fewer local recurrences (LR) occurred in the RB group, most pronounced in patients ≤ 40 years old. The current study evaluates LR in young patients at an institution where RB is not routine. METHODS A retrospective review was performed on patients ≤ 40 years with primary breast cancer who underwent adjuvant breast radiation from 1980-1999. RB was added to patients at high risk for LR (close margins, multifocal tumors). RESULTS Seventy-five patients with a median age of 37 years (range 24-40) were followed for a median 7.6 years (range 0.5-17.7). Twenty-six patients received a RB while 49 patients were treated with uniform breast radiation only. Multifocal tumors, were more prevalent in the RB group (19% vs. 2%, p=0.03). LR occurred in 8 of 75 patients (11%). There was no difference in LR between NB group (3/49, 6.1%) and RB group (5/26, 19.2%)(p=0.18). LR in the same quadrant as the primary tumor was found in 2 patients in the NB group (4%) and 3 patients in the RB group (n=12%)(p=0.23). There were no significant differences in overall survival, disease-free survival, and same quadrant disease-free survival between the two groups. The addition of a radiation boost was not predictive of local recurrence by univariate and multivariate analyses. CONCLUSIONS Uniform breast irradiation resulted in low ipsilateral and same quadrant recurrence rates. Routine RB does not appear to be justified in young patients. No significant financial relationships to disclose.
<reponame>Eshanatnight/College class ThreadClass extends Thread { private int number; public ThreadClass(int number) { this.number = number; } @Override public void run() { int counter = 0; int numInt = 0; // prints the number till specified number is reached, starting from 10 do { numInt = (int) (counter); System.out.println(this.getName() + " prints Hello World " + numInt); counter++; } while(numInt != number); System.out.println("## SUCCESSFUL! " + this.getName() + " printed " + counter + " times. ##"); } } public class Assignment2 { public static void main(String [] args) { System.out.println("Starting thread_1..."); //create a thread class instance Thread thread_1 = new ThreadClass(4); //start the thread thread_1 thread_1.start(); try { //wait for thread_1 to join to main thread thread_1.join(); } catch (InterruptedException e) { System.out.println("Thread interrupted."); } System.out.println("Starting thread_2..."); Thread thread_2 = new ThreadClass(6); //start thread_2 thread_2.start(); System.out.println("main() is ending..."); } }
Theoretical Control and Experimental Verification of Carded Web Density Part I: Dynamic System Analysis and Controller Design Control of uniform carded fiber webs becomes very important when one wants to push the state of the art with faster and more accurate textile spinning. Four steps are necessary for controlling the carded web and its uniformity. First, a good design-based model of the plant needs to be considered. Second, a good actuator, sensor and, con troller that are also realizable must exist. Third, input to the controller must be con structed using knowledge of the system's dynamic response to improve system performance. Finally, all the effort of the design is meaningful only when tested by experiment. This paper presents a complete strategy for a uniform carded fiber web control system. Part I illustrates the system dynamics, stability, controllability, and observability by application to feedback control of one worker-stripper group, and uses the root-locus design technique for the controller design. At the same time, a comple mentary control scheme for precise system control is presented. This composite control method gives the corresponding closed-loop system not only a time-optimal operation, but also the most efficient, precise control properties.
WATCH ABOVE: The full interview with Sam Sotiropoulos TORONTO – Toronto School Board trustee Sam Sotiropoulos has come under fire after saying in a tweet he “reserves the right not to believe” in transgendered people. He’s waiting for “scientific proof” being transgendered isn’t “simply a mental illness,” he wrote Aug. 29. Until I see scientific proof that transgenderism exists and is not simply a mental illness, I reserve the right not to believe in it. #TDSB — Sam Sotiropoulos (@TrusteeSam) August 30, 2014 He refused to say in an interview Friday whether he thinks transgendered people actually suffer from a mental illness. “I have not formed an opinion, but I reserve the right to form an opinion.” Sotiropoulos also suggested anyone offended by the tweet would be “casting a stigma on mental illness … by believing it’s offensive to be mentally ill.” But Egale Canada President Robert Leckey said people have historically cast aspersions on gay, lesbian and transgendered people by saying their orientation was a mental illness in need of treatment. “There’s a long connection between sexual minority – sexual orientation minorities and gender identity minorities – and mental illness, so gay people used to be locked up and sent to therapists. Now some people think transgendered people are sick,” he said. READ MORE: 16×9: Two transgender children struggle to be themselves “It doesn’t take seriously the dignity and experience of people who are transgendered.” The Diagnostic and Statistical Manual of Mental Disorders (DSM) – a tome of recognized psychiatric diagnoses – does list transgendered people under “Gender Dysphoria” but notes “gender noncomformity is not in itself a mental disorder.” WATCH: TDSB trustee reserves ‘right not to believe’ in trans people. Trans-rights activist Susan Gapka said she’s glad Sotiropoulos isn’t the only decision maker at the Toronto District School Board. “It’s very concerning that people elected to public office don’t follow or take the time to learn about our codes of conduct, about our society, this person is disconnected,” she said. “I hope he doesn’t win again.” She pointed out the Ontario Human Rights Code and the World Health Organization recognizes trans people. This isn’t the first time Sotiropoulos has said expressed views dismissive of lesbian, gay, bisexual, queer or transgendered people: He suggested on Newstalk 1010 in April there might be nude pedophiles at the Pride Parade and said at one point the parade “openly flouted” the country’s laws against public nudity. Dozens of people criticized Sotiropoulos’ tweet about trans persons. Gapka suggested that outrage points to how far society as come in recent years. “The terrific thing is that there are non-trans people, allies and supporters, leaping to the defense, there was a flurry on twitter, and social media, the news has covered it, that shows you how far we’ve come in the last five or ten years.”
def error_callback(messages: tuple) -> None: global ERROR_MESSAGES ERROR_MESSAGES = messages
/** * We will create a brand new RecordManager file, containing nothing, but the RecordManager header, * a B-tree to manage the old revisions we want to keep and * a B-tree used to manage pages associated with old versions. * <br/> * The RecordManager header contains the following details : * <pre> * +--------------------------+ * | PageSize | 4 bytes : The size of a physical page (default to 4096) * +--------------------------+ * | NbTree | 4 bytes : The number of managed B-trees (zero or more) * +--------------------------+ * | FirstFree | 8 bytes : The offset of the first free page * +--------------------------+ * | current BoB offset | 8 bytes : The offset of the current BoB * +--------------------------+ * | previous BoB offset | 8 bytes : The offset of the previous BoB * +--------------------------+ * | current CP btree offset | 8 bytes : The offset of the current BoB * +--------------------------+ * | previous CP btree offset | 8 bytes : The offset of the previous BoB * +--------------------------+ * </pre> * * We then store the B-tree managing the pages that have been copied when we have added * or deleted an element in the B-tree. They are associated with a version. * * Last, we add the bTree that keep a track on each revision we can have access to. */ private void initRecordManager() throws IOException { nbBtree = 0; firstFreePage = NO_PAGE; currentBtreeOfBtreesOffset = NO_PAGE; updateRecordManagerHeader(); endOfFileOffset = fileChannel.size(); createBtreeOfBtrees(); createCopiedPagesBtree(); try { manageSubBtree( btreeOfBtrees ); currentBtreeOfBtreesOffset = ( ( PersistedBTree<NameRevision, Long> ) btreeOfBtrees ).getBtreeHeader() .getBTreeHeaderOffset(); updateRecordManagerHeader(); currentBTreeHeaders.put( BTREE_OF_BTREES_NAME, ( ( PersistedBTree<NameRevision, Long> ) btreeOfBtrees ).getBtreeHeader() ); newBTreeHeaders.put( BTREE_OF_BTREES_NAME, ( ( PersistedBTree<NameRevision, Long> ) btreeOfBtrees ).getBtreeHeader() ); manageSubBtree( copiedPageBtree ); currentCopiedPagesBtreeOffset = ( ( PersistedBTree<RevisionName, long[]> ) copiedPageBtree ) .getBtreeHeader().getBTreeHeaderOffset(); updateRecordManagerHeader(); currentBTreeHeaders.put( COPIED_PAGE_BTREE_NAME, ( ( PersistedBTree<RevisionName, long[]> ) copiedPageBtree ).getBtreeHeader() ); newBTreeHeaders.put( COPIED_PAGE_BTREE_NAME, ( ( PersistedBTree<RevisionName, long[]> ) copiedPageBtree ).getBtreeHeader() ); } catch ( BTreeAlreadyManagedException btame ) { } if ( LOG_CHECK.isDebugEnabled() ) { MavibotInspector.check( this ); } }
/// Opens file at given filepath and process it by finding all its TODOs. pub fn open_todos<F>(&mut self, filepath: F) -> Result<(), Error> where F: AsRef<Path>, { // using _p just to let the compiler know the correct type for open_option_filtered_todos() let mut _p = Some(|_t: &Todo| true); _p = None; self.open_option_filtered_todos(filepath, &_p) }
import * as util from 'util'; import { BaseView } from './baseview'; import {WebviewPanel} from 'vscode'; import {Utility} from '../misc/utility'; //import { Utility } from './utility'; /** * A Webview that just shows some static text. * Is e.g. used to run an Emulator command and display it's output. */ export class TextView extends BaseView { /** * Creates the text view. * @param title The title to use for this view. * @param text The static text to show. */ constructor(title: string, text: string) { super(); // Title Utility.assert(this.vscodePanel); (this.vscodePanel as WebviewPanel).title = title; // Use the text this.setHtml(text); } /** * Sets the html code to display the text. * @param text Text to display. */ protected setHtml(text: string) { if (!this.vscodePanel) return; const format = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dump</title> </head> <body style="font-family: Courier"> <div style="word-wrap:break-word"> %s </div> </body> </html>`; // Exchange each newline into <br> const brText = text.replace(/\n/g, '<br>'); // Add html body const html = util.format(format, brText); this.vscodePanel.webview.html = html; } }
//***************************************************************************** // split cmdline to tkn array and return nmb of token static int split(microrl_t* pThis, int limit, char const ** tkn_array) { microl_decode_state_t decode_state; int cmdline_index = 0; int nb_token; nb_token = 0; decode_state = IDLE; cmdline_index = 0; #ifdef _USE_QUOTING char current_quote; #endif while (cmdline_index < limit) { switch(decode_state) { case IDLE: switch(pThis->cmdline [cmdline_index]) { case ' ': case '\0': break; #ifdef _USE_QUOTING case '"': case '\'': decode_state = WORD_WITH_QUOTE_BEGIN; current_quote = pThis->cmdline [cmdline_index]; break; #endif default: decode_state = WORD; tkn_array[nb_token++] = &pThis->cmdline [cmdline_index]; if (nb_token >= _COMMAND_TOKEN_NMB) goto split_in_error; break; } break; case WORD: switch (pThis->cmdline [cmdline_index]) { case ' ': case '\0': pThis->cmdline [cmdline_index] = '\0'; decode_state = IDLE; break; case '"': case '\'': goto split_in_error; break; default: break; } break; #ifdef _USE_QUOTING case WORD_WITH_QUOTE_BEGIN: if (pThis->cmdline [cmdline_index] == current_quote) goto split_in_error; else { decode_state = WORD_WITH_QUOTE_WORD; tkn_array[nb_token++] = &pThis->cmdline [cmdline_index]; if (nb_token >= _COMMAND_TOKEN_NMB) goto split_in_error; } break; case WORD_WITH_QUOTE_WORD: if (pThis->cmdline [cmdline_index] == current_quote) { pThis->cmdline [cmdline_index] = '\0'; decode_state = IDLE; } break; #endif default: goto split_in_error; break; } cmdline_index++; } pThis->cmdline [cmdline_index] = '\0'; #ifdef _USE_QUOTING if ((decode_state == WORD_WITH_QUOTE_BEGIN) || (decode_state == WORD_WITH_QUOTE_WORD)) goto split_in_error; #endif return nb_token; split_in_error: return -1; }
t=int(input()) for i in range(t): n=input() if(len(n)==1): print(n) else: n=int(n) p=9 if(n>9 and n<=17): print(n-9,end="") print("9") elif(n>=18 and n<=24): print(n-17,end="") print("89") elif(n>=25 and n<=30): print(n-24,end="") print("789") elif(n>=31 and n<=35): print(n-30,end="") print("6789") elif(n>=36 and n<=39): print(n-35,end="") print("56789") elif(n>=40 and n<=42): print(n-39,end="") print("456789") elif(n>=43 and n<=44): print(n-42,end="") print("3456789") elif(n==45): print("123456789") else: print("-1")
<filename>tools/gen_debug_info.py #!/usr/bin/env python3 ''' Convert debug info for C interpreter debugger. Usage: tools/gen_debug_info.py src/game/game_debuginfo.h ''' import sys import sundog_info out = sys.stdout def gen(out): proclist = sundog_info.load_metadata() info = [] for k,v in proclist._map.items(): if v.name is not None: info.append((k, v)) info.sort() out.write('// clang-format off\n') for k,v in info: if v.name is None: continue # get name without arguments name = v.name if '(' in name: name = name[0:name.find('(')] # output out.write('{ { { { "%s" } }, 0x%x }, "%s" },' % (k[0].decode(), k[1], name)) out.write('\n') out.write(' // clang-format on\n') if __name__ == '__main__': with open(sys.argv[1], 'w') as f: gen(f)
<filename>test/test_api_file_state.py """Test units for the file_state rest apis.""" import json from http import HTTPStatus from unittest.mock import MagicMock import pytest import apis from core.eeadm.file_state import LtfseeFile def test_api_file_state_post(client, monkeypatch, valid_auth_headers): """Check that file_state returns expected behavior.""" data = {"path": "/my/test/path/file.sh"} # "P 2 JD0099JD@POOL_JD@ts4500 MB0355JE@POOL_JE@ts4500 - -- /gpfs/gpfs0/sample_file", # "M 1 MB0355JE@POOL_JE@ts4500 - - -- /gpfs/gpfs0/sample_file2", # "R 0 - - - -- /gpfs/gpfs0/sample_file3", eeadm_mock = MagicMock(name="EEADM") mock = MagicMock() files = [ LtfseeFile( state="P", replicas=2, tapes=["-", "-", "-"], path="/gpfs/gpfs0/sample_file" ), LtfseeFile( state="M", replicas=1, tapes=["-", "-", "-"], path="/gpfs/gpfs0/sample_file2", ), LtfseeFile( state="R", replicas=0, tapes=["-", "-", "-"], path="/gpfs/gpfs0/sample_file3", ), ] mock.files = files eeadm_mock.return_value = mock monkeypatch.setattr(apis.file_state, "EEADM_File_State", eeadm_mock) # monkeypatch.setattr(core.eeadm.file_state, "EEADM_File_State", mock) response = client.post( "/api/v0.5/file_state/file_state", data=json.dumps(data), content_type="application/json", headers=valid_auth_headers, # valid login creds ) assert response.status_code == HTTPStatus.CREATED # nosec
/** Tries to find "private" JRadioButton in this dialog. * @return JRadioButtonOperator */ public JRadioButtonOperator rbPrivate() { if (_rbPrivate==null) { _rbPrivate = new JRadioButtonOperator(this, "private"); } return _rbPrivate; }
/// WSC Technical Specification v2.0.7, Section 12, Table 28 impl Id { pub const AP_SETUP_LOCKED: Self = Self([0x10, 0x57]); pub const CONFIG_METHODS: Self = Self([0x10, 0x08]); pub const DEVICE_NAME: Self = Self([0x10, 0x11]); pub const DEVICE_PASSWORD_ID: Self = Self([0x10, 0x12]); pub const MANUFACTURER: Self = Self([0x10, 0x21]); pub const MODEL_NAME: Self = Self([0x10, 0x23]); pub const MODEL_NUMBER: Self = Self([0x10, 0x24]); pub const PRIMARY_DEVICE_TYPE: Self = Self([0x10, 0x54]); pub const RESPONSE_TYPE: Self = Self([0x10, 0x3B]); pub const RF_BANDS: Self = Self([0x10, 0x3C]); pub const SELECTED_REG: Self = Self([0x10, 0x41]); pub const SELECTED_REG_CONFIG_METHODS: Self = Self([0x10, 0x53]); pub const SERIAL_NUMBER: Self = Self([0x10, 0x42]); pub const UUID_E: Self = Self([0x10, 0x47]); pub const VENDOR_EXT: Self = Self([0x10, 0x49]); pub const VERSION: Self = Self([0x10, 0x4A]); pub const WPS_STATE: Self = Self([0x10, 0x44]); }
package src.DatConRecs.Created4V3; import src.DatConRecs.Payload; import src.Files.ConvertDat; public class RecMag6_2257 extends MagGroup { public RecMag6_2257(ConvertDat convertDat) { super(convertDat, 2257, 6, 1); } public void process(Payload _payload) { super.process(_payload); } }
/** * Return response as JSON from the resource path if the request is ... * <pre> * e.g. returns response as the json if the request is /harbor/ * response.asJson("/mock/harbor/product.json", request -&gt; request.getUrl().contains("/harbor/")); * * e.g. returns response as the json at all requests * response.asJson("/mock/harbor/product.json", request -&gt; true); * </pre> * @param responseFilePath The resource path to JSON resource file for mock response. (NotNull) * @param requestLambda The callback for determination of corresponding request. (NotNull) * @return The resource to create mock HTTP response. (NotNull) */ public MockHttpResponseResource asJson(String responseFilePath, MockRequestDeterminer requestLambda) { assertArgumentNotNull("responseFilePath", responseFilePath); assertArgumentNotNull("requestLambda", requestLambda); return registerProvider(request -> { return requestLambda.determine(request) ? responseJson(responseFilePath) : null; }); }
import itertools res = 100000000000000000000000000 a = raw_input().split() z = raw_input().split() for c in itertools.permutations(a): res = min(res,eval('(('+c[0]+z[0]+c[1]+')'+z[1]+c[2]+')'+z[2]+c[3])) res = min(res,eval('('+c[0]+z[0]+c[1]+')'+z[2]+'('+c[2]+z[1]+c[3]+')')) print(res)
/** * Counts the records from the tables. */ private void countRecords() { this.lblStudentCount.setText(GraduatedStudentModel.getTotalRecords()); this.lblProfileCount.setText(CompanyProfileModel.getTotalRecords()); this.lbl_inquiry_count.setText(InquiryModel.getTotalRecords()); }
/** * Handles all SQL based databases * * @author TOTHTOMI * @version 1.0.0 * @since 1.3.0-SNAPSHOT" */ public abstract class SQLDatabase extends Storage { private final String databaseName; protected Connection connection = null; /** * @param databaseName the databaseName * @param type the {@link StorageType} * @param logger the {@link Logger} to use */ public SQLDatabase(String databaseName, StorageType type, Logger logger) { super(type, logger); this.databaseName = databaseName; } /** * Documented in {@link Storage} */ @Override protected abstract boolean init() throws StorageException; /** * Documented in {@link Storage} */ @Override protected abstract boolean openConnection() throws StorageException; /** * Documented in {@link Storage} */ @Override protected boolean closeConnection() { if (connection != null) { try { connection.close(); connection = null; return true; } catch (SQLException sqlException) { sqlException.printStackTrace(); } return false; } return true; } /** * Closes the previous and returns a new fresh {@link Connection} * * @return the {@link Connection} */ @SneakyThrows private Connection getConnection() { closeConnection(); openConnection(); return connection; } /** * Documented in {@link Storage} * Customized to fit the SQL database types */ @Override public void deleteData(String key, Object value, String containerName) { String query; if (databaseName != null) query = String.format("DELETE FROM %s.%s WHERE ? = ?", databaseName, containerName); else query = String.format("DELETE FROM %s WHERE ? = ?", containerName); try { PreparedStatement preparedStatement = getConnection().prepareStatement(query); preparedStatement.setString(0, key); preparedStatement.setObject(1, value); preparedStatement.executeUpdate(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } } /** * Documented in {@link Storage} * Customized to fit the SQL database types */ @Override public List<ContainerData> getData(Container container) { String containerName = container.getContainerName(); List<ContainerData> containerData = new ArrayList<>(); try { String query; if (databaseName != null) query = String.format("SELECT * FROM %s.%s WHERE 1", databaseName, containerName); else query = String.format("SELECT * FROM %s WHERE 1", containerName); PreparedStatement preparedStatement = getConnection().prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { long id = resultSet.getLong("id"); DataType[] dataTypes = container.getDataKeyTypes(); Object[] values = new Object[dataTypes.length]; for (int i = 0; i < dataTypes.length; i++) { values[i] = resultSet.getObject(i + 2); } containerData.add(new ContainerData(dataTypes, container.getDataKeyNames(), values, id)); } getConnection().close(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } return containerData; } private void applyInsertion(String query, List<ContainerData> insertList) { insertList.forEach(queueData -> { //looping through the insertMap try { PreparedStatement preparedStatement = getConnection().prepareStatement(query); preparedStatement.setLong(1, queueData.getId()); DataType[] dataTypes = queueData.getDataTypes(); //Datatypes for the rows' columns' Object[] values = queueData.getValues(); //Values for the rows' columns' for (int i = 0; i < dataTypes.length; i++) { DataType dataType = dataTypes[i]; Object value = values[i]; Object toEnter = dataType.getJavaRepresentation().cast(value); //System.out.println(toEnter); int toSet = i + 2; insert(dataType, toEnter, preparedStatement, toSet); } preparedStatement.executeUpdate(); getConnection().close(); } catch (SQLException sqlException) { sqlException.printStackTrace(); } }); } /** * Inserts data to the given {@link PreparedStatement} * * @param dataType the {@link DataType} * @param toEnter the value to insert * @param preparedStatement the {@link PreparedStatement} * @param toSet parameter indexs * @throws SQLException */ private void insert(DataType dataType, Object toEnter, PreparedStatement preparedStatement, int toSet) throws SQLException { switch (dataType) { case STRING: preparedStatement.setString(toSet, (String) toEnter); break; case BOOLEAN: preparedStatement.setBoolean(toSet, (Boolean) toEnter); break; case INTEGER: preparedStatement.setInt(toSet, (Integer) toEnter); break; case LONG: preparedStatement.setLong(toSet, (Long) toEnter); break; default: break; } } /** * Documented in {@link Storage} * Customized to fit the SQL database types */ @Override public void applyChanges() { lastUpdated = System.currentTimeMillis(); String startSchema; if (databaseName != null) startSchema = "REPLACE INTO %s.%s(id, %s) VALUES (?,%s)"; else startSchema = "REPLACE INTO %s(id, %s) VALUES (?,%s)"; containerMap.forEach((tableName, container) -> { //looping through our queue if (!container.getQueue().isEmpty()) { List<ContainerData> queue = container.getQueue(); createTableIfNotExists(tableName, queue); //creating table StringBuilder valuesBuilder = new StringBuilder(); StringBuilder columnBuilder = new StringBuilder(); List<ContainerData> insertList = new ArrayList<>(); //Map used to keep track of what we need to insert later on, first we create the query List<String> blacklist = new ArrayList<>(); //To prevent duplication queue.forEach(queueData -> { //looping through the data for a table to create query and to add to insertmap String[] columns = queueData.getKeys(); for (String column : columns) { //looping through the columns if (!blacklist.contains(column)) { //making sure we're not making duplicates columnBuilder.append(column).append(", "); valuesBuilder.append("?, "); blacklist.add(column); } } insertList.add(queueData); //ading to insertMap }); String columns = columnBuilder.substring(0, columnBuilder.length() - 2); String values = valuesBuilder.substring(0, valuesBuilder.length() - 2); String query; if (databaseName != null) query = String.format(startSchema, databaseName, tableName, columns, values); //creating query else query = String.format(startSchema, tableName, columns, values); //creating query info("Running query " + query); applyInsertion(query, insertList); //handling insertion container.getQueue().clear(); } }); } /** * Creates tables if they're not exist from the given data list * * @param name the containerName * @param data the container's data */ private void createTableIfNotExists(String name, List<ContainerData> data) { StringBuilder stringBuilder = new StringBuilder(); List<String> blackList = new ArrayList<>(); //we need to keep track which key we have already put in to prevent Duplicate column names data.forEach(queueData -> { //looping through our data DataType[] dataTypes = queueData.getDataTypes(); //dataTypes for each data String[] keys = queueData.getKeys(); //columns for each data for (int i = 0; i < dataTypes.length; i++) { DataType dataType = dataTypes[i]; //dataType for a column String key = keys[i]; //column name if (!blackList.contains(key)) { //making sure not to have duplicate columns stringBuilder.append(key).append(" ").append(dataType.getMysqlParameter()).append(", "); blackList.add(key); } } }); String values = stringBuilder.substring(0, stringBuilder.length() - 2); //Removing the last comma and space String query; if (databaseName != null) query = String.format("CREATE TABLE IF NOT EXISTS %s.%s (id BIGINT PRIMARY KEY, %s)", databaseName, name, values); //Creating query else query = String.format("CREATE TABLE IF NOT EXISTS %s (id BIGINT PRIMARY KEY, %s)", name, values); //Creating query info("Running query " + query); try { PreparedStatement preparedStatement = getConnection().prepareStatement(query); //Creating prepared statement preparedStatement.executeUpdate(); //Running prepared statement getConnection().close(); } catch (Exception e) { e.printStackTrace(); } } }
// filterSubnetsByZone - find all of the subnets in the requested zone func (c *CloudVpc) filterSubnetsByZone(subnets []*VpcSubnet, zone string) []*VpcSubnet { matchingSubnets := []*VpcSubnet{} for _, subnet := range subnets { if subnet.Zone == zone { matchingSubnets = append(matchingSubnets, subnet) } } return matchingSubnets }
def remove_objective(request, teacher_email, teacher_class_id, date, objective): teacher = Teacher.objects.get(email=teacher_email) if teacher.user != request.user: return redirect('top.index') if request.POST: date_of_objective = datetime.datetime.strptime(date, '%Y-%m-%d') Entry.objects.filter(teacher=teacher, teacher_class__id=teacher_class_id, date=date_of_objective, objective=objective).delete() start_of_week_datetime = date_of_objective - datetime.timedelta(days=date_of_objective.weekday()) start_of_week = datetime.date(start_of_week_datetime.year, start_of_week_datetime.month, start_of_week_datetime.day) return redirect('teachers.views.dashboard', teacher_email=teacher_email, teacher_class_id=teacher_class_id, start_of_week=start_of_week) args = {'teacher_email': teacher_email, 'teacher_class_id': teacher_class_id, 'date': date, 'objective': objective, 'dashboard_emails': get_dashboard_emails(request)} args.update(csrf(request)) return render(request, 'teachers/remove_objective.html', args)
package e4m.ui.swt; import org.eclipse.swt.SWT; import e4m.ref.CGA; class ColorMap { static int color(int index) { switch (index) { default: return -1; case CGA.BACKGROUND: return SWT.COLOR_BLACK; case CGA.BLUE: return SWT.COLOR_BLUE; case CGA.RED: return SWT.COLOR_RED; case CGA.PINK: return SWT.COLOR_MAGENTA; case CGA.GREEN: return SWT.COLOR_GREEN; case CGA.TURQUOISE: return SWT.COLOR_CYAN; case CGA.YELLOW: return SWT.COLOR_YELLOW; case CGA.FOREGROUND: return SWT.COLOR_WHITE; case CGA.BLACK: return SWT.COLOR_DARK_GRAY; case CGA.DEEP_BLUE: return SWT.COLOR_DARK_BLUE; case CGA.ORANGE: return SWT.COLOR_DARK_RED; case CGA.PURPLE: return SWT.COLOR_DARK_MAGENTA; case CGA.PALE_GREEN: return SWT.COLOR_DARK_GREEN; case CGA.PALE_TURQUOISE: return SWT.COLOR_DARK_CYAN; case CGA.GREY: return SWT.COLOR_DARK_YELLOW; case CGA.WHITE: return SWT.COLOR_GRAY; } } }
package test; import java.util.Map; import java.util.HashMap; import java.util.Random; import umicollapse.util.BitSet; import umicollapse.util.Utils; import umicollapse.util.Read; import umicollapse.util.ReadFreq; import umicollapse.algo.*; import umicollapse.data.*; public class ParallelBenchmarkTime{ public static void main(String[] args){ int numRand = 1000; int numDup = 20; int numIter = 5; int umiLength = 100; int k = 1; int threadCount = 2; float percentage = 0.5f; ParallelAlgorithm algo = new ParallelConnectedComponents(); ParallelDataStructure data = new ParallelFenwickBKTree(); Random rand = new Random(1234); // fixed seed System.out.println("Parallel algorithm\t" + algo.getClass().getName()); System.out.println("Parallel data structure\t" + data.getClass().getName()); System.out.println("Number of random iterations\t" + numRand); System.out.println("Number of duplicates\t" + numDup); System.out.println("Number of testing iterations\t" + numIter); System.out.println("UMI length\t" + umiLength); System.out.println("Max number of edits\t" + k); System.out.println("Thread count\t" + threadCount); System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", (threadCount - 1) + ""); Map<BitSet, ReadFreq> umiFreq = TestUtils.generateData(numRand, numDup, umiLength, k, percentage, rand); System.out.println("Actual number of UMIs\t" + umiFreq.size()); long avgTime = 0L; for(int i = 0; i < numIter + 1; i++){ System.gc(); long time = runTest(algo, data, umiFreq, umiLength, k, percentage); if(i > 0) // first time is warm-up avgTime += time; } avgTime /= numIter; System.out.println("Average time (ms)\t" + avgTime); } private static long runTest(ParallelAlgorithm algo, ParallelDataStructure data, Map<BitSet, ReadFreq> umiFreq, int umiLength, int k, float percentage){ long start = System.currentTimeMillis(); algo.apply(umiFreq, data, umiLength, k, percentage); return System.currentTimeMillis() - start; } }
// lit element import { css, CSSResult } from 'lit'; // memberdashboard import { primaryBlue, primaryRed } from './colors'; export const coreStyle: CSSResult = css` .center-text { text-align: center; } .destructive-button { --mdc-theme-primary: ${primaryRed}; } a { color: ${primaryBlue}; } .margin-r-24 { margin-right: 24px; } /* ANIMATION */ @keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } `;
/** * The factory which builds the PHP54Translator. * <p/> * It loads a StringTemplate which is used by the PHP54Translator. */ public class HardCodedTSPHPTranslatorInitialiser implements ITranslatorInitialiser { private final ITranslatorController controller; private final IInferenceEngineInitialiser inferenceEngineInitialiser; private StringTemplateGroup templateGroup; private Exception loadingTemplateException; public HardCodedTSPHPTranslatorInitialiser( ITSPHPAstAdaptor astAdaptor, ISymbolsInitialiser theSymbolsInitialiser, ICoreInitialiser theCoreInitialiser, IInferenceEngineInitialiser theInferenceEngineInitialiser) { inferenceEngineInitialiser = theInferenceEngineInitialiser; IPrecedenceHelper precedenceHelper = new PrecedenceHelper(); ITempVariableHelper tempVariableHelper = new TempVariableHelper(astAdaptor); Map<String, ITypeSymbol> primitiveTypes = theCoreInitialiser.getCore().getPrimitiveTypes(); ITypeHelper typeHelper = theSymbolsInitialiser.getTypeHelper(); ISymbolFactory symbolFactory = theSymbolsInitialiser.getSymbolFactory(); IUnionTypeSymbol unionTypeSymbol = (IUnionTypeSymbol) primitiveTypes.get(PrimitiveTypeNames.BOOL); ITypeSymbol tsphpBoolTypeSymbol = new TsphpUnionTypeSymbol("bool", unionTypeSymbol); unionTypeSymbol = (IUnionTypeSymbol) primitiveTypes.get(PrimitiveTypeNames.NUM); ITypeSymbol tsphpNumTypeSymbol = new TsphpUnionTypeSymbol("num", unionTypeSymbol); unionTypeSymbol = (IUnionTypeSymbol) primitiveTypes.get(PrimitiveTypeNames.SCALAR); ITypeSymbol tsphpScalarTypeSymbol = new TsphpUnionTypeSymbol("scalar", unionTypeSymbol); ITypeTransformer typeTransformer = new TSPHPTypeTransformer( symbolFactory, typeHelper, primitiveTypes, tsphpBoolTypeSymbol, tsphpNumTypeSymbol, tsphpScalarTypeSymbol); IOutputIssueMessageProvider outputIssueMessageProvider = new HardCodedOutputIssueMessageProvider(); IRuntimeCheckProvider runtimeCheckProvider = new TSPHPRuntimeCheckProvider( typeHelper, typeTransformer, tempVariableHelper, outputIssueMessageProvider, tsphpBoolTypeSymbol); IOperatorHelper operatorHelper = new TSPHPOperatorHelper( symbolFactory, typeHelper, primitiveTypes, runtimeCheckProvider, typeTransformer); ITypeVariableTransformer typeVariableMapper = new TsphpTypeVariableTransformer( symbolFactory, typeHelper, typeTransformer); IDtoCreator dtoCreator = new DtoCreator( tempVariableHelper, typeTransformer, typeVariableMapper, runtimeCheckProvider ); controller = new TranslatorController( astAdaptor, symbolFactory, precedenceHelper, tempVariableHelper, operatorHelper, dtoCreator, runtimeCheckProvider, outputIssueMessageProvider, typeTransformer); loadStringTemplate(); } private void loadStringTemplate() { InputStreamReader streamReader = null; try { // LOAD TEMPLATES (via classpath) ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final InputStream inputStream = classLoader.getResourceAsStream("TSPHP.stg"); if (inputStream != null) { streamReader = new InputStreamReader(inputStream); templateGroup = new StringTemplateGroup(streamReader); streamReader.close(); } else { loadingTemplateException = new TSPHPException("TSPHP.stg could not be resolved"); } } catch (IOException ex) { loadingTemplateException = ex; } finally { try { if (streamReader != null) { streamReader.close(); } } catch (IOException ex) { //no further exception handling needed } } } @Override public ITranslator build() { return new TSPHPTranslator( templateGroup, controller, inferenceEngineInitialiser, loadingTemplateException); } @Override public void reset() { //nothing to reset } }
// // Copyright © 2017 IronSource. All rights reserved. // #ifndef IRONSOURCE_REWARDEDVIDEO_DELEGATE_H #define IRONSOURCE_REWARDEDVIDEO_DELEGATE_H #import <Foundation/Foundation.h> @class ISPlacementInfo; @protocol ISRewardedVideoDelegate <NSObject> @required /** Called after a rewarded video has changed its availability. @param available The new rewarded video availability. YES if available and ready to be shown, NO otherwise. */ - (void)rewardedVideoHasChangedAvailability:(BOOL)available; /** Called after a rewarded video has been viewed completely and the user is eligible for reward. @param placementInfo An object that contains the placement's reward name and amount. */ - (void)didReceiveRewardForPlacement:(ISPlacementInfo *)placementInfo; /** Called after a rewarded video has attempted to show but failed. @param error The reason for the error */ - (void)rewardedVideoDidFailToShowWithError:(NSError *)error; /** Called after a rewarded video has been opened. */ - (void)rewardedVideoDidOpen; /** Called after a rewarded video has been dismissed. */ - (void)rewardedVideoDidClose; /** * Note: the events below are not available for all supported rewarded video ad networks. * Check which events are available per ad network you choose to include in your build. * We recommend only using events which register to ALL ad networks you include in your build. */ /** Called after a rewarded video has started playing. */ - (void)rewardedVideoDidStart; /** Called after a rewarded video has finished playing. */ - (void)rewardedVideoDidEnd; /** Called after a video has been clicked. */ - (void)didClickRewardedVideo:(ISPlacementInfo *)placementInfo; @end #endif
<reponame>caibirdme/leetforfun<filename>leetcode/leet_889/source.go package leet_889 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func constructFromPrePost(pre []int, post []int) *TreeNode { length := len(pre) if length == 0 { return nil } node := &TreeNode{ Val: pre[0], } if length == 1 { return node } pre = pre[1:] post = post[:length-1] leftVal := pre[0] idx := findVal(post, leftVal) node.Left = constructFromPrePost(pre[:idx+1], post[:idx+1]) node.Right = constructFromPrePost(pre[idx+1:], post[idx+1:]) return node } func findVal(post []int, val int) int { for idx, v := range post { if v == val { return idx } } return -1 }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.apache.eagle.alert.engine.evaluator.impl; import com.google.common.base.Preconditions; import org.apache.commons.lang3.StringUtils; import org.apache.eagle.alert.engine.coordinator.PolicyDefinition; import org.apache.eagle.alert.engine.coordinator.StreamColumn; import org.apache.eagle.alert.engine.coordinator.StreamDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.siddhi.query.api.definition.AbstractDefinition; import io.siddhi.query.api.definition.Attribute; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SiddhiDefinitionAdapter { private static final Logger LOG = LoggerFactory.getLogger(SiddhiDefinitionAdapter.class); public static final String DEFINE_STREAM_TEMPLATE = "define stream %s ( %s );"; public static String buildStreamDefinition(StreamDefinition streamDefinition) { List<String> columns = new ArrayList<>(); Preconditions.checkNotNull(streamDefinition, "StreamDefinition is null"); if (streamDefinition.getColumns() != null) { for (StreamColumn column : streamDefinition.getColumns()) { columns.add(String.format("%s %s", column.getName(), convertToSiddhiAttributeType(column.getType()).toString().toLowerCase())); } } else { LOG.warn("No columns found for stream {}" + streamDefinition.getStreamId()); } return String.format(DEFINE_STREAM_TEMPLATE, streamDefinition.getStreamId(), StringUtils.join(columns, ",")); } public static Attribute.Type convertToSiddhiAttributeType(StreamColumn.Type type) { if (_EAGLE_SIDDHI_TYPE_MAPPING.containsKey(type)) { return _EAGLE_SIDDHI_TYPE_MAPPING.get(type); } throw new IllegalArgumentException("Unknown stream type: " + type); } public static Class<?> convertToJavaAttributeType(StreamColumn.Type type) { if (_EAGLE_JAVA_TYPE_MAPPING.containsKey(type)) { return _EAGLE_JAVA_TYPE_MAPPING.get(type); } throw new IllegalArgumentException("Unknown stream type: " + type); } public static StreamColumn.Type convertFromJavaAttributeType(Class<?> type) { if (_JAVA_EAGLE_TYPE_MAPPING.containsKey(type)) { return _JAVA_EAGLE_TYPE_MAPPING.get(type); } throw new IllegalArgumentException("Unknown stream type: " + type); } public static StreamColumn.Type convertFromSiddhiAttributeType(Attribute.Type type) { if (_SIDDHI_EAGLE_TYPE_MAPPING.containsKey(type)) { return _SIDDHI_EAGLE_TYPE_MAPPING.get(type); } throw new IllegalArgumentException("Unknown siddhi type: " + type); } public static String buildSiddhiExecutionPlan(PolicyDefinition policyDefinition, Map<String, StreamDefinition> sds) { StringBuilder builder = new StringBuilder(); PolicyDefinition.Definition coreDefinition = policyDefinition.getDefinition(); // init if not present List<String> inputStreams = coreDefinition.getInputStreams(); if (inputStreams == null || inputStreams.isEmpty()) { inputStreams = policyDefinition.getInputStreams(); } for (String inputStream : inputStreams) { builder.append(SiddhiDefinitionAdapter.buildStreamDefinition(sds.get(inputStream))); builder.append("\n"); } builder.append(coreDefinition.value); if (LOG.isDebugEnabled()) { LOG.debug("Generated siddhi execution plan: {} from definition: {}", builder.toString(), coreDefinition); } return builder.toString(); } public static String buildSiddhiExecutionPlan(String policyDefinition, Map<String, StreamDefinition> inputStreamDefinitions) { StringBuilder builder = new StringBuilder(); for (Map.Entry<String,StreamDefinition> entry: inputStreamDefinitions.entrySet()) { builder.append(SiddhiDefinitionAdapter.buildStreamDefinition(entry.getValue())); builder.append("\n"); } builder.append(policyDefinition); if (LOG.isDebugEnabled()) { LOG.debug("Generated siddhi execution plan: {}", builder.toString()); } return builder.toString(); } /** * public enum Type { * STRING, INT, LONG, FLOAT, DOUBLE, BOOL, OBJECT * }. */ private static final Map<StreamColumn.Type, Attribute.Type> _EAGLE_SIDDHI_TYPE_MAPPING = new HashMap<>(); private static final Map<StreamColumn.Type, Class<?>> _EAGLE_JAVA_TYPE_MAPPING = new HashMap<>(); private static final Map<Class<?>, StreamColumn.Type> _JAVA_EAGLE_TYPE_MAPPING = new HashMap<>(); private static final Map<Attribute.Type, StreamColumn.Type> _SIDDHI_EAGLE_TYPE_MAPPING = new HashMap<>(); static { _EAGLE_SIDDHI_TYPE_MAPPING.put(StreamColumn.Type.STRING, Attribute.Type.STRING); _EAGLE_SIDDHI_TYPE_MAPPING.put(StreamColumn.Type.INT, Attribute.Type.INT); _EAGLE_SIDDHI_TYPE_MAPPING.put(StreamColumn.Type.LONG, Attribute.Type.LONG); _EAGLE_SIDDHI_TYPE_MAPPING.put(StreamColumn.Type.FLOAT, Attribute.Type.FLOAT); _EAGLE_SIDDHI_TYPE_MAPPING.put(StreamColumn.Type.DOUBLE, Attribute.Type.DOUBLE); _EAGLE_SIDDHI_TYPE_MAPPING.put(StreamColumn.Type.BOOL, Attribute.Type.BOOL); _EAGLE_SIDDHI_TYPE_MAPPING.put(StreamColumn.Type.OBJECT, Attribute.Type.OBJECT); _EAGLE_JAVA_TYPE_MAPPING.put(StreamColumn.Type.STRING, String.class); _EAGLE_JAVA_TYPE_MAPPING.put(StreamColumn.Type.INT, Integer.class); _EAGLE_JAVA_TYPE_MAPPING.put(StreamColumn.Type.LONG, Long.class); _EAGLE_JAVA_TYPE_MAPPING.put(StreamColumn.Type.FLOAT, Float.class); _EAGLE_JAVA_TYPE_MAPPING.put(StreamColumn.Type.DOUBLE, Double.class); _EAGLE_JAVA_TYPE_MAPPING.put(StreamColumn.Type.BOOL, Boolean.class); _EAGLE_JAVA_TYPE_MAPPING.put(StreamColumn.Type.OBJECT, Object.class); _JAVA_EAGLE_TYPE_MAPPING.put(String.class, StreamColumn.Type.STRING); _JAVA_EAGLE_TYPE_MAPPING.put(Integer.class, StreamColumn.Type.INT); _JAVA_EAGLE_TYPE_MAPPING.put(Long.class, StreamColumn.Type.LONG); _JAVA_EAGLE_TYPE_MAPPING.put(Float.class, StreamColumn.Type.FLOAT); _JAVA_EAGLE_TYPE_MAPPING.put(Double.class, StreamColumn.Type.DOUBLE); _JAVA_EAGLE_TYPE_MAPPING.put(Boolean.class, StreamColumn.Type.BOOL); _JAVA_EAGLE_TYPE_MAPPING.put(Object.class, StreamColumn.Type.OBJECT); _SIDDHI_EAGLE_TYPE_MAPPING.put(Attribute.Type.STRING, StreamColumn.Type.STRING); _SIDDHI_EAGLE_TYPE_MAPPING.put(Attribute.Type.INT, StreamColumn.Type.INT); _SIDDHI_EAGLE_TYPE_MAPPING.put(Attribute.Type.LONG, StreamColumn.Type.LONG); _SIDDHI_EAGLE_TYPE_MAPPING.put(Attribute.Type.FLOAT, StreamColumn.Type.FLOAT); _SIDDHI_EAGLE_TYPE_MAPPING.put(Attribute.Type.DOUBLE, StreamColumn.Type.DOUBLE); _SIDDHI_EAGLE_TYPE_MAPPING.put(Attribute.Type.BOOL, StreamColumn.Type.BOOL); _SIDDHI_EAGLE_TYPE_MAPPING.put(Attribute.Type.OBJECT, StreamColumn.Type.OBJECT); } public static StreamDefinition convertFromSiddiDefinition(AbstractDefinition siddhiDefinition) { StreamDefinition streamDefinition = new StreamDefinition(); streamDefinition.setStreamId(siddhiDefinition.getId()); List<StreamColumn> columns = new ArrayList<>(siddhiDefinition.getAttributeNameArray().length); for (Attribute attribute : siddhiDefinition.getAttributeList()) { StreamColumn column = new StreamColumn(); column.setType(convertFromSiddhiAttributeType(attribute.getType())); column.setName(attribute.getName()); columns.add(column); } streamDefinition.setColumns(columns); streamDefinition.setTimeseries(true); streamDefinition.setDescription("Auto-generated stream schema from siddhi for " + siddhiDefinition.getId()); return streamDefinition; } }
package nl.uu.cs.aplib.mainConcepts; import java.util.*; import org.junit.jupiter.api.Test; import nl.uu.cs.aplib.mainConcepts.Environment; import nl.uu.cs.aplib.mainConcepts.Environment.EnvironmentInstrumenter; import static org.junit.jupiter.api.Assertions.*; public class Test_Environment { class MyEnv extends Environment { int x = 0; int y = 0; @Override public MyEnv observe(String agentId) { return (MyEnv) this.sendCommand(agentId, null, "observe",null) ; } @Override protected Object sendCommand_(EnvOperation opr) { switch (opr.command) { case "incrx": x++; break; case "incry": y++; break ; case "observe" : break ; } return this; } MyEnv clone_() { MyEnv o = new MyEnv(); o.x = x; o.y = y; return o; } } class MyInstrumenter implements EnvironmentInstrumenter { List<MyEnv> history = new LinkedList<>(); @Override public void update(Environment env) { history.add(((MyEnv) env).clone_()); } @Override public void reset() { history.clear(); } MyEnv last() { return history.get(history.size() - 1); } } @Test public void test_debugmode() { var env = new MyEnv(); assertFalse(env.debugmode); env.turnOnDebugInstrumentation(); assertTrue(env.debugmode); env.turnOffDebugInstrumentation(); assertFalse(env.debugmode); } @Test public void test_register_remove_instrumenter() { var env = new MyEnv(); var instrumenter = new MyInstrumenter(); env.registerInstrumenter(instrumenter); assertTrue(env.instrumenters.contains(instrumenter)); env.removeInstrumenter(instrumenter); assertFalse(env.instrumenters.contains(instrumenter)); } @Test public void test_instrumentation() { var env = new MyEnv(); var instrumenter = new MyInstrumenter(); env.registerInstrumenter(instrumenter); env.turnOnDebugInstrumentation(); assertTrue(env.getLastOperation() == null); env.observe("bla"); assertTrue(env.getLastOperation().command.equals("observe")); assertTrue(instrumenter.history.size() == 1); assertTrue(instrumenter.last().x == 0 && instrumenter.last().y == 0); env.observe("bla"); assertTrue(env.getLastOperation().command.equals("observe")); assertTrue(instrumenter.history.size() == 2); assertTrue(instrumenter.last().x == 0 && instrumenter.last().y == 0); env.sendCommand("originId", "targetId", "incrx", null); assertTrue(env.getLastOperation().command.equals("incrx")); assertTrue(instrumenter.history.size() == 3); assertTrue(instrumenter.last().x == 1 && instrumenter.last().y == 0); env.sendCommand("originId", "targetId", "incry", null); assertTrue(env.getLastOperation().command.equals("incry")); assertTrue(instrumenter.history.size() == 4); assertTrue(instrumenter.last().x == 1 && instrumenter.last().y == 1); env.resetAndInstrument(); assertTrue(env.getLastOperation() == null); assertTrue(instrumenter.history.size() == 0); } }
package co.com.gs.proteccionpdf; import java.awt.Desktop; import java.net.URL; import javax.swing.UIManager; /** * * @author <NAME>. * @version 1.1 - 2021 */ public class AboutMeUI extends javax.swing.JFrame { public AboutMeUI() { initComponents(); setLocationRelativeTo(null); setIconImage(new javax.swing.ImageIcon(getClass().getResource("/icono3.png")).getImage()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { iconLogo = new javax.swing.JLabel(); lTitulo = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); txtInfo = new javax.swing.JTextArea(); lMe = new javax.swing.JLabel(); iconTwitter = new javax.swing.JLabel(); lLibraries = new javax.swing.JLabel(); iconLicence = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Acerca de Proyecto Protección PDF"); setAlwaysOnTop(true); setResizable(false); iconLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icono3.png"))); // NOI18N lTitulo.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N lTitulo.setText("Protección PDF - Versión 1.1"); txtInfo.setEditable(false); txtInfo.setColumns(20); txtInfo.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N txtInfo.setLineWrap(true); txtInfo.setRows(5); txtInfo.setText("Esta aplicación convierte el contenido de un PDF a PDF con imágenes con lo que genera una capa de seguridad que evita que el contenido sea editado directamente. Esto puede llegar a ser útil cuando necesitamos garantizar que la información que enviamos a través de un archivo PDF no sea alterada."); txtInfo.setWrapStyleWord(true); jScrollPane1.setViewportView(txtInfo); lMe.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N lMe.setText("<NAME>"); iconTwitter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitter.png"))); // NOI18N iconTwitter.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { iconTwitterMouseClicked(evt); } }); lLibraries.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N lLibraries.setText("Librería Utilizada: Apache Pdfbox| Imágenes de Iconfinder"); iconLicence.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N iconLicence.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cc.png"))); // NOI18N iconLicence.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { iconLicenceMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(lMe) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(iconTwitter) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(iconLogo) .addGap(74, 74, 74) .addComponent(lTitulo) .addGap(0, 207, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(lLibraries) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(iconLicence))) .addContainerGap()))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(iconLogo) .addGroup(layout.createSequentialGroup() .addGap(62, 62, 62) .addComponent(lTitulo))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lMe) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lLibraries)) .addGroup(layout.createSequentialGroup() .addComponent(iconTwitter) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(iconLicence))) .addGap(12, 12, 12)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void iconLicenceMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_iconLicenceMouseClicked openWebPage("http://creativecommons.org/licenses/by-sa/4.0/"); }//GEN-LAST:event_iconLicenceMouseClicked private void iconTwitterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_iconTwitterMouseClicked openWebPage("https://twitter.com/edgaso"); }//GEN-LAST:event_iconTwitterMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { try { UIManager.setLookAndFeel("org.netbeans.swing.laf.dark.DarkMetalLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PDFimageUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AboutMeUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel iconLicence; private javax.swing.JLabel iconLogo; private javax.swing.JLabel iconTwitter; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lLibraries; private javax.swing.JLabel lMe; private javax.swing.JLabel lTitulo; private javax.swing.JTextArea txtInfo; // End of variables declaration//GEN-END:variables public static void openWebPage(String urlString) { try { Desktop.getDesktop().browse(new URL(urlString).toURI()); } catch (Exception e) { e.printStackTrace(); } } }
<gh_stars>1-10 // // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @class CKRecordZone, CKServerChangeToken, NSArray, NSMutableArray, NSString; @protocol ADCloudKitDataStoreProtocol, OS_dispatch_source; @interface ADCloudKitRecordZoneInfo : NSObject { _Bool _fetchInProgress; // 8 = 0x8 _Bool _simulatedError; // 9 = 0x9 NSString *_zoneName; // 16 = 0x10 NSString *_subscriptionName; // 24 = 0x18 NSArray *_subscriptionNames; // 32 = 0x20 CKRecordZone *_zone; // 40 = 0x28 NSObject<OS_dispatch_source> *_zoneSetupTimer; // 48 = 0x30 NSMutableArray *_subscriptionList; // 56 = 0x38 NSObject<OS_dispatch_source> *_subscriptionSetupTimer; // 64 = 0x40 NSObject<ADCloudKitDataStoreProtocol> *_dataStore; // 72 = 0x48 NSObject<OS_dispatch_source> *_rateLimitTimer; // 80 = 0x50 NSObject<OS_dispatch_source> *_syncRetryTimer; // 88 = 0x58 NSObject<OS_dispatch_source> *_shareCreationTimer; // 96 = 0x60 unsigned long long _shareCreationRetryCount; // 104 = 0x68 long long _retryState; // 112 = 0x70 double _currentRetryInterval; // 120 = 0x78 NSString *_zoneId; // 128 = 0x80 NSString *_subscriptionId; // 136 = 0x88 } - (void).cxx_destruct; // IMP=0x000000010012f10c @property(copy, nonatomic) NSString *subscriptionId; // @synthesize subscriptionId=_subscriptionId; @property(copy, nonatomic) NSString *zoneId; // @synthesize zoneId=_zoneId; @property(nonatomic) _Bool simulatedError; // @synthesize simulatedError=_simulatedError; @property(nonatomic) double currentRetryInterval; // @synthesize currentRetryInterval=_currentRetryInterval; @property(nonatomic) long long retryState; // @synthesize retryState=_retryState; @property(nonatomic) _Bool fetchInProgress; // @synthesize fetchInProgress=_fetchInProgress; @property(nonatomic) unsigned long long shareCreationRetryCount; // @synthesize shareCreationRetryCount=_shareCreationRetryCount; @property(retain, nonatomic) NSObject<OS_dispatch_source> *shareCreationTimer; // @synthesize shareCreationTimer=_shareCreationTimer; @property(retain, nonatomic) NSObject<OS_dispatch_source> *syncRetryTimer; // @synthesize syncRetryTimer=_syncRetryTimer; @property(retain, nonatomic) NSObject<OS_dispatch_source> *rateLimitTimer; // @synthesize rateLimitTimer=_rateLimitTimer; @property(retain, nonatomic) NSObject<ADCloudKitDataStoreProtocol> *dataStore; // @synthesize dataStore=_dataStore; @property(retain, nonatomic) NSObject<OS_dispatch_source> *subscriptionSetupTimer; // @synthesize subscriptionSetupTimer=_subscriptionSetupTimer; @property(retain, nonatomic) NSMutableArray *subscriptionList; // @synthesize subscriptionList=_subscriptionList; @property(retain, nonatomic) NSObject<OS_dispatch_source> *zoneSetupTimer; // @synthesize zoneSetupTimer=_zoneSetupTimer; @property(retain, nonatomic, setter=setZone:) CKRecordZone *zone; // @synthesize zone=_zone; @property(readonly, copy, nonatomic) NSArray *subscriptionNames; // @synthesize subscriptionNames=_subscriptionNames; @property(readonly, copy, nonatomic) NSString *subscriptionName; // @synthesize subscriptionName=_subscriptionName; @property(readonly, copy, nonatomic) NSString *zoneName; // @synthesize zoneName=_zoneName; - (void)reset; // IMP=0x000000010012ed7c @property(nonatomic) _Bool hasSetUpRecordZoneSubscription; // @dynamic hasSetUpRecordZoneSubscription; @property(retain, nonatomic) CKServerChangeToken *serverChangeToken; - (id)initWithZone:(id)arg1 dataStore:(id)arg2 subscriptionNames:(id)arg3; // IMP=0x000000010012eb4c - (id)initWithZoneName:(id)arg1 subscriptionNames:(id)arg2; // IMP=0x000000010012ea70 - (id)initWithZoneName:(id)arg1 subscriptionName:(id)arg2; // IMP=0x000000010012e98c @end
<gh_stars>1-10 #ifndef TEMOTO_CORE__RESOURCE_SERVER_H #define TEMOTO_CORE__RESOURCE_SERVER_H #include "ros/ros.h" #include "ros/callback_queue.h" #include "temoto_core/common/temoto_id.h" #include "temoto_core/common/tools.h" #include "temoto_core/trr/base_resource_server.h" #include "temoto_core/trr/server_query.h" #include "temoto_core/trr/resource_registrar_services.h" #include <mutex> namespace temoto_core { namespace trr { template <class ServiceType, class Owner> class ResourceServer : public BaseResourceServer<Owner> { public: typedef void (Owner::*LoadCbFuncType)(typename ServiceType::Request&, typename ServiceType::Response&); typedef void (Owner::*UnloadCbFuncType)(typename ServiceType::Request&, typename ServiceType::Response&); ResourceServer( std::string name , LoadCbFuncType load_cb , UnloadCbFuncType unload_cb , Owner* owner , ResourceRegistrar<Owner>& resource_registrar) : BaseResourceServer<Owner>(name, __func__, resource_registrar) , load_callback_(load_cb) , unload_callback_(unload_cb) , owner_(owner) , load_spinner_(2, &load_cb_queue_) { std::string rm_name = this->resource_registrar_.getName(); std::string server_srv_name = rm_name + "/" + this->name_; ros::AdvertiseServiceOptions load_service_opts = ros::AdvertiseServiceOptions::create<ServiceType>( server_srv_name, boost::bind(&ResourceServer<ServiceType, Owner>::wrappedLoadCallback, this, _1, _2), ros::VoidPtr(), &this->load_cb_queue_); load_server_ = nh_.advertiseService(load_service_opts); load_spinner_.start(); TEMOTO_DEBUG("ResourceServer constructed, listening on '%s'.", this->load_server_.getService().c_str()); } ~ResourceServer() { load_spinner_.stop(); TEMOTO_DEBUG("ResourceServer destroyed."); } void linkInternalResource(temoto_id::ID internal_resource_id) { TEMOTO_DEBUG("Trying to register client side id in resource query %d.", internal_resource_id); if (!queries_.size()) { TEMOTO_ERROR("Failed because queries_ is empty."); return; } queries_.back().linkResource(internal_resource_id); } void unlinkInternalResource(temoto_id::ID internal_resource_id) { TEMOTO_DEBUG("Trying to unlink resource '%d'.", internal_resource_id); try { const auto found_query_it = std::find_if(queries_.begin(), queries_.end(), [internal_resource_id](const ServerQuery<ServiceType>& query) -> bool { return query.isLinkedTo(internal_resource_id); }); if (found_query_it != queries_.end()) { found_query_it->unlinkResource(internal_resource_id); //if(found_query_it->getInternalResources().size()==0) } else { throw CREATE_ERROR(error::Code::RMP_FAIL, "Resource id '%ld' was not found from any queries.", internal_resource_id); } } catch (error::ErrorStack& error_stack) { throw FORWARD_ERROR(error_stack); } } bool wrappedLoadCallback(typename ServiceType::Request& req, typename ServiceType::Response& res) { #ifdef enable_tracing /* * Propagate the context of the span to the invoked subroutines */ temoto_core::StringMap parent_tracer_span_context = temoto_core::keyValuesToUnorderedMap(req.trr.tracer_context); TextMapCarrier carrier(parent_tracer_span_context); auto span_context_maybe = TRACER->Extract(carrier); //assert(span_context_maybe); auto tracing_span = TRACER->StartSpan(this->class_name_ + "::" + __func__, {opentracing::ChildOf(span_context_maybe->get())}); #endif TEMOTO_TRACED_DEBUG("Got query with status_topic: '%s'.", req.trr.status_topic.c_str()); if (!owner_) { res.trr.code = status_codes::FAILED; res.trr.error_stack = CREATE_ERROR(error::Code::RMP_FAIL, "ResourceServer Owner is NULL. Query aborted."); return true; } // generate new external id for the resource temoto_id::ID ext_resource_id = this->resource_registrar_.generateID(); TEMOTO_TRACED_DEBUG("Generated external id: '%d'.", ext_resource_id); // lock the queries waitForLock(queries_mutex_); // New or existing query? Check it out with this hi-tec lambda function :) auto found_query = std::find_if(queries_.begin(), queries_.end(), [&req](const ServerQuery<ServiceType>& query) -> bool { return query.getMsg().request == req && !query.failed_; }); if (found_query == queries_.end()) { // generate new internal id, and give it to owners callback. // with this id, owner can send status messages later when necessary temoto_id::ID int_resource_id = this->resource_registrar_.generateID(); res.trr.resource_id = int_resource_id; TEMOTO_TRACED_DEBUG("New query, server generated new internal id: '%d'.", int_resource_id); // equal message not found from queries_, add new query try { queries_.emplace_back(req, int_resource_id, *owner_); queries_.back().addExternalResource(ext_resource_id, req.trr.status_topic); } catch(error::ErrorStack& error_stack) { queries_.pop_back(); //remove the failed query queries_mutex_.unlock(); res.trr.code = status_codes::FAILED; res.trr.error_stack = FORWARD_ERROR(error_stack); return true; } // set this server active in resource manager // when a client call is made from callback, the binding between active server // and the new loaded resources can be made automatically waitForLock(active_server_mutex_); try { this->activateServer(); #ifdef enable_tracing temoto_core::StringMap current_span_context; TextMapCarrier carrier(current_span_context); auto err = TRACER->Inject(tracing_span->context(), carrier); if(!err) { TEMOTO_WARN_STREAM("Failed to get the context of a tracing span"); } else { this->active_tracer_context_ = current_span_context; } #endif } catch(error::ErrorStack& error_stack) { queries_.pop_back(); //remove the failed query queries_mutex_.unlock(); active_server_mutex_.unlock(); res.trr.code = status_codes::FAILED; res.trr.error_stack = FORWARD_ERROR(error_stack); return true; } queries_mutex_.unlock(); // call owner's registered callback and release the lock during the callback so that owner is // able to use trr inside the callback try { (owner_->*load_callback_)(req, res); } catch(error::ErrorStack& error_stack) { // callback threw an exeption, try to clean up and return. try { waitForLock(queries_mutex_); auto q_it = getQueryByExternalId(ext_resource_id); if(q_it->failed_) { res.trr.error_stack += q_it->getMsg().response.trr.error_stack; } queries_.erase(q_it); queries_mutex_.unlock(); } catch(error::ErrorStack& query_error) { // just send the error when trying to and continue queries_mutex_.unlock(); SEND_ERROR(FORWARD_ERROR(query_error)); } this->deactivateServer(); active_server_mutex_.unlock(); res.trr.code = status_codes::FAILED; res.trr.error_stack = FORWARD_ERROR(error_stack); return true; } catch(...) { // callback threw an unknown exeption, prevent this for reaching ros callback. // try to clean up and report. try { waitForLock(queries_mutex_); auto q_it = getQueryByExternalId(ext_resource_id); if(q_it->failed_) { res.trr.error_stack += q_it->getMsg().response.trr.error_stack; } queries_.erase(q_it); queries_mutex_.unlock(); } catch(error::ErrorStack& query_error) { // just send the error when trying to and continue queries_mutex_.unlock(); SEND_ERROR(FORWARD_ERROR(query_error)); } this->deactivateServer(); active_server_mutex_.unlock(); res.trr.code = status_codes::FAILED; res.trr.error_stack = CREATE_ERROR(error::Code::RMP_FAIL, "Unexpected error was thrown from " "owner's load callback."); return true; } // restore active server to NULL in resource manager this->deactivateServer(); active_server_mutex_.unlock(); waitForLock(queries_mutex_); try { // verify that our query is still on the list auto q_it = std::find_if(queries_.begin(), queries_.end(), [&](const ServerQuery<ServiceType>& q) -> bool { return q.hasExternalResource(ext_resource_id); }); if (q_it != queries_.end()) { // First, make sure the internal_resource_id for that query is not changed. res.trr.resource_id = int_resource_id; // check if the query has not been marked as failed while we were dealing with the owner's callback // if it failed, remove the query. if(q_it->failed_) { // TODO Potentially some resources were sucessfully loaded, SEND UNLOAD REQUEST TO ALL // LINKED CLIENTS res.trr.error_stack += q_it->getMsg().response.trr.error_stack; queries_.erase(q_it); queries_mutex_.unlock(); res.trr.code = status_codes::FAILED; return true; } // update the query with the response message filled in the callback q_it->setMsgResponse(res); // prepare the response for the client res.trr.resource_id = ext_resource_id; //res.trr.code = status_codes::OK; //res.trr.message = "New resource sucessfully loaded."; } else { queries_mutex_.unlock(); res.trr.code = status_codes::FAILED; res.trr.error_stack = CREATE_ERROR(error::Code::RMP_FAIL, "Query got missing during owners callback, oh well..."); return true; } } catch(error::ErrorStack& error_stack) { queries_mutex_.unlock(); res.trr.code = status_codes::FAILED; res.trr.error_stack = FORWARD_ERROR(error_stack); return true; } } else { try { // found equal request, simply reqister this in the query // and respond with previous data and a unique resoure_id. TEMOTO_TRACED_DEBUG("Existing query, linking to the found query."); queries_.back().addExternalResource(ext_resource_id, req.trr.status_topic); res = found_query->getMsg().response; res.trr.resource_id = ext_resource_id; //res.trr.code = status_codes::OK; //res.trr.message = "Sucessfully sharing existing resource."; } catch(error::ErrorStack& error_stack) { queries_mutex_.unlock(); res.trr.code = status_codes::FAILED; res.trr.error_stack = FORWARD_ERROR(error_stack); return true; } } // release the queries lock queries_mutex_.unlock(); return true; } // This function is called from resource manager when /unload request arrives // (e.g. when some external client is being destroyed) // We look up the query that contains given external resource id and send unload to all internal // clients in the same query void unloadResource(temoto_core::UnloadResource::Request& req, temoto_core::UnloadResource::Response& res) { // find first query that contains resource that should be unloaded const temoto_id::ID ext_rid = req.resource_id; waitForLock(queries_mutex_); const auto found_query_it = std::find_if(queries_.begin(), queries_.end(), [ext_rid](const ServerQuery<ServiceType>& query) -> bool { return query.hasExternalResource(ext_rid); }); if (found_query_it != queries_.end()) { TEMOTO_DEBUG("Query with ext id %d was found", ext_rid); TEMOTO_DEBUG("internal resource count: %lu", found_query_it->getLinkedResources().size()); // Query found, try to remove external client from it. size_t resources_left = found_query_it->removeExternalResource(ext_rid); if (resources_left == 0) { // last resource removed, execute owner's unload callback and remove the query from our list typename ServiceType::Request orig_req = found_query_it->getMsg().request; typename ServiceType::Response orig_res = found_query_it->getMsg().response; error::ErrorStack unload_errs; // buffer for all unload-related errors try { (owner_->*unload_callback_)(orig_req, orig_res); } catch(error::ErrorStack& error_stack) { unload_errs += error_stack; } // Send unload command to all linked internal clients... for (auto& set_el : found_query_it->getLinkedResources()) { try { this->resource_registrar_.unloadClientResource(set_el); } catch (error::ErrorStack& es) { unload_errs += es; //append error to the unload error stack } } // forward the stack if any error occured if (unload_errs.size()) { res.code = status_codes::FAILED; res.error_stack += FORWARD_ERROR(unload_errs); } // Finally, remove the found query, even when some of the unload calls failed. // \TODO: The next line potentially causes zombie resources. How to manage these? queries_.erase(found_query_it); } } queries_mutex_.unlock(); } // go over queries_ and look for the linked resource_id bool hasInternalResource(temoto_id::ID resource_id) const { auto found_q = find_if(queries_.begin(), queries_.end(), [&](const ServerQuery<ServiceType>& q) -> bool { return q.hasInternalResource(resource_id); }); return found_q != queries_.end(); } bool isLinkedTo(temoto_id::ID resource_id) const { auto found_q = find_if(queries_.begin(), queries_.end(), [&](const ServerQuery<ServiceType>& q) -> bool { return q.isLinkedTo(resource_id); }); return found_q != queries_.end(); } bool hasExternalResource(temoto_id::ID external_resource_id) const { auto found_q = find_if(queries_.begin(), queries_.end(), [&](const ServerQuery<ServiceType>& q) -> bool { return q.hasExternalResource(external_resource_id); }); return found_q != queries_.end(); } // concatenate pairs of <external_resource_id, status_topic> of the query where internal id is found. std::vector<std::pair<temoto_id::ID, std::string>> getExternalResourcesByInternalId(temoto_id::ID internal_resource_id) { waitForLock(queries_mutex_); std::vector<std::pair<temoto_id::ID, std::string>> ext_resources; for (const auto& q : queries_) { if (q.hasInternalResource(internal_resource_id)) { for (auto resource : q.getExternalResources()) { ext_resources.push_back(resource); } break; // no need to look any further } } queries_mutex_.unlock(); return ext_resources; } // concatenate pairs of <external_resource_id, status_topic> of the query where external id is found. std::vector<std::pair<temoto_id::ID, std::string>> getExternalResourcesByExternalId(temoto_id::ID external_resource_id) { waitForLock(queries_mutex_); std::vector<std::pair<temoto_id::ID, std::string>> ext_resources; for (const auto& q : queries_) { if (q.hasExternalResource(external_resource_id)) { for (auto resource : q.getExternalResources()) { ext_resources.push_back(resource); } break; // no need to look any further } } queries_mutex_.unlock(); return ext_resources; } typename std::vector<ServerQuery<ServiceType>>::iterator getQueryByExternalId(temoto_id::ID ext_id) { auto q_it =std::find_if(queries_.begin(), queries_.end(), [&](const ServerQuery<ServiceType>& q) -> bool { return q.hasExternalResource(ext_id); }); if (q_it == queries_.end()) { throw CREATE_ERROR(error::Code::RMP_FAIL, "External id not found from any queries."); } return q_it; } void waitForLock(std::mutex& m) { while (!m.try_lock()) { TEMOTO_DEBUG("Waiting for lock()"); ros::Duration(0.01).sleep(); // sleep for few ms } } void setFailedFlag(temoto_id::ID internal_resource_id, error::ErrorStack& error_stack) { waitForLock(queries_mutex_); const auto found_query_it = std::find_if(queries_.begin(), queries_.end(), [internal_resource_id](const ServerQuery<ServiceType>& query) -> bool { return query.hasInternalResource(internal_resource_id); }); if (found_query_it != queries_.end()) { // Query found, mark query as failed and append why did it fail. found_query_it->setFailed(error_stack); } queries_mutex_.unlock(); } private: Owner* owner_; LoadCbFuncType load_callback_; UnloadCbFuncType unload_callback_; ros::NodeHandle nh_; ros::ServiceServer load_server_; ros::CallbackQueue load_cb_queue_; ros::AsyncSpinner load_spinner_; std::vector<ServerQuery<ServiceType>> queries_; // mutexes std::mutex queries_mutex_; std::mutex active_server_mutex_; }; } // trr namespace } // temoto_core namespace #endif
/// reorder weights, flatten the 2-dimensional vector into a single dimension /// data by metric and edge_id is found at index `metric * num_edges + edge_id` fn reorder_weights(weights: &Vec<Vec<Weight>>, num_metrics: usize, scale_upper_bound: bool) -> Vec<Weight> { let mut ret = vec![0; weights.len() * num_metrics]; weights.iter().enumerate().for_each(|(edge_id, edge_weights)| { edge_weights.iter().enumerate().for_each(|(metric_id, &val)| { ret[metric_id * weights.len() + edge_id] = val; }); }); if scale_upper_bound { for edge_id in 0..weights.len() { ret[UPPERBOUND_METRIC * weights.len() + edge_id] = min(INFINITY, max((ret[UPPERBOUND_METRIC * weights.len() + edge_id] / 2) * 3, 1)); } } ret }
While doubts remain that Tottenham have enough creativity to bother the top six, Eric Dier’s move into central midfield has been inspired… “We were aggressive,” said Hugo Lloris, who was best placed to judge exactly how traditionally tip-toeing Tottenham contrived to out-tackle a Sunderland side containing Yann M’Vila. Lloris did not namecheck Eric Dier but the statistics tell the story: Eight tackles, two interceptions, five clearances and four blocked shots from a position we should probably cease to call ‘unfamiliar’. Midfielder Dier is Tottenham’s success story of this nascent season. “I made the decision from the start of pre-season that we needed to give the option to Eric Dier to play,” said Mauricio Pochettino, who saw enough promise in the 21-year-old to allow French international Etienne Capoue to leave along with Benjamin Stambouli. The Argentine can now allow himself a smug smile; while Tottenham are still struggling to justify a lack of investment in strikers, his left-field decision to trust the stubbornly black-booted Dier looks inspired rather than desperate. Let’s face it, something had to be done. Despite finishing in fifth last season, Tottenham contrived to concede more goals than relegated Hull. The purchase of Toby Alderweireld provided the no-brainer upgrade on Vlad Chiriches, Younes Kaboul and Fazio as Jan Vertonghen’s partner, but moving Dier into midfield was very much the brainer part of the transition from soft underbelly to hard abdominals. Nobody saw it coming. While no Tottenham fan could be ecstatic with six points from their first five matches, the ‘goals against’ column makes for unusually pleasant reading. With just four goals conceded, only the Premier League’s top three can boast a more miserly record. Dier deserves a large dollop of the credit. Comparing his tackling statistics with Francis Coquelin illustrates the might of Dier. The Frenchman has been successful with 21 of his 26 tackles while Dier has won the ball with 19 of his 23 attempts – there is a barely a cigarette paper between the pair. And although Coquelin’s passing accuracy is marginally better, it’s safe to say that Dier offers a greater attacking threat. It would be foolish to declare Dier a finished product on the back of clean sheets against Everton and Sunderland, but there is enough evidence to suggest that Pochettino and Tottenham got one thing – if not many more – right this summer. Dier was not alone in his aggression against Sunderland, who suffered the ignominy of being out-tackled 25-22 by a Tottenham side who could boast the youngest average age (24 years and 135 days) in the Premier League, but it was his discipline that caught the eye. On a weekend when Roy Hodgson admitted that he was monitoring Liverpool’s 19-year-old winger Jordon Ibe, it surely cannot be long before he glances towards White Hart Lane in his quest to find an Englishman to play at the base of his midfield. “I would look down the line at Dier at Tottenham. He’s a player who could ultimately be the replacement for these two,” said Martin Keown earlier this year. At that juncture he was talking about Gary Cahill and Phil Jagielka, but perhaps Scott Parker would be a more apt comparison. Tottenham fans might be naturally disinclined to worship a tough-tackling midfielder, but in the absence of last season’s Harry Kane or a winger worthy of the name, Dier aggressively but fairly plugs that gap. Man of Match Eric Dier: 56 touches, 8 tackles, 81% passing accuracy, 11.34km covered. pic.twitter.com/J4o6HNgyw5 — Sky Sports Statto (@SkySportsStatto) September 13, 2015 Sarah Winterburn
import './set_public_path'; import singleSpa from 'single-spa-vue'; import Vue from 'vue'; import VueMeta from 'vue-meta'; import VueRouter from 'vue-router'; import app from './App.vue'; import router from './router'; import '@/assets/styles/index.css'; Vue.config.productionTip = false; Vue.use(VueRouter); Vue.use(VueMeta); export const { bootstrap, mount, unmount } = singleSpa({ Vue, appOptions: { router, render: (h: any) => h(app), }, });
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (c) 2021 HERE Europe B.V. # # SPDX-License-Identifier: MIT # License-Filename: LICENSE # ############################################################################### # from PyQt5.QtWebEngineWidgets import QWebEngineView # import error import json from typing import Optional from qgis.PyQt.QtCore import QUrl, QObject from qgis.PyQt.QtNetwork import QNetworkAccessManager from qgis.PyQt.QtWebKit import QWebSettings from qgis.PyQt.QtWebKitWidgets import QWebPage, QWebView, QWebInspector from qgis.PyQt.QtWidgets import QDialog, QGridLayout from qgis.PyQt.QtCore import Qt from .net_handler import IMLNetworkHandler from ...common.signal import BasicSignal from ...models import API_TYPES, SpaceConnectionInfo from ...network.net_handler import NetworkError from ...network.net_utils import ( CookieUtils, make_payload, make_conn_request, set_qt_property, ) class WebPage(QWebPage): def __init__(self, parent, *a, **kw): super().__init__(*a, **kw) self.parent_widget = parent settings = self.settings() settings.setAttribute(QWebSettings.JavascriptEnabled, True) settings.setAttribute(QWebSettings.LocalStorageEnabled, True) settings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True) settings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True) # settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, True) settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) settings.setAttribute(QWebSettings.WebGLEnabled, True) settings.setAttribute(QWebSettings.PluginsEnabled, True) settings.setThirdPartyCookiePolicy(settings.AlwaysAllowThirdPartyCookies) def createWindow(self, window_type): # WindowDialog is just a simple QDialog with a QWebView parent = self.parent_widget dialog = QDialog(parent) page = self.new_page(dialog, self.networkAccessManager()) dialog.show() return page @classmethod def new_page(cls, dialog: QDialog, network: QNetworkAccessManager): parent = dialog dialog.setAttribute(Qt.WA_DeleteOnClose, True) dialog.raise_() # dialog.setWindowModality(Qt.WindowModal) page = WebPage(parent) page.setNetworkAccessManager(network) view = QWebView(parent) view.setPage(page) mainLayout = QGridLayout(parent) mainLayout.addWidget(view, 0, 0) dialog.resize(600, 600) dialog.setLayout(mainLayout) # cls.attach_inspector(dialog, page) return page @classmethod def attach_inspector(cls, dialog: QDialog, page: "WebPage"): parent = page.parent_widget inspector = QWebInspector(parent) inspector.setPage(page) inspector.setMinimumHeight(400) dialog.layout().addWidget(inspector, 1, 0) dialog.resize(800, 600) class PlatformUserAuthentication: API_SIT = "SIT" API_PRD = "PRD" PLATFORM_URL_SIT = "platform.in.here.com" PLATFORM_URL_PRD = "platform.here.com" HERE_URL_SIT = "st.p.account.here.com" PLATFORM_LOGIN_URL_SIT = ( "https://st.p.account.here.com/sign-in?version=4&oidc=true" "&client-id=TlZSbQzENfNkUFrOXh8Oag&no-sign-up=true" "&realm-input=true&sign-in-template=olp&self-certify-age=true" "&theme=brand&authorizeUri=%2Fauthorize%3Fresponse_type%3Dcode" "%26client_id%3DTlZSbQzENfNkUFrOXh8Oag%26scope%3Dopenid%2520email" "%2520phone%2520profile%2520readwrite%253Aha%26redirect_uri" "%3Dhttps%253A%252F%252Fplatform.in.here.com%252FauthHandler" "%26state%3D%257B%2522redirectUri%2522%253A%2522https" "%253A%252F%252Fplatform.in.here.com%252FauthHandler" "%2522%252C%2522redirect%2522%253A%2522https%25253A%25252F" "%25252Fplatform.in.here.com%25252F%2522%257D%26nonce" "%3D1628073689817%26prompt%3D&sign-in-screen-config=password" ) PLATFORM_LOGIN_URL_PRD = ( "https://account.here.com/sign-in?version=4&oidc=true" "&client-id=YQijV3hAPdxySAVtE6ZT&no-sign-up=true" "&realm-input=true&sign-in-template=olp&self-certify-age=true" "&theme=brand&authorizeUri=%2Fauthorize%3Fresponse_type%3Dcode" "%26client_id%3DYQijV3hAPdxySAVtE6ZT%26scope%3Dopenid%2520email" "%2520phone%2520profile%2520readwrite%253Aha%26redirect_uri" "%3Dhttps%253A%252F%252Fplatform.here.com%252FauthHandler" "%26state%3D%257B%2522redirectUri%2522%253A%2522https" "%253A%252F%252Fplatform.here.com%252FauthHandler" "%2522%252C%2522redirect%2522%253A%2522https%25253A%25252F" "%25252Fplatform.here.com%25252F%2522%257D%26nonce" "%3D1628073704030%26prompt%3D&sign-in-screen-config=password" ) ENDPOINT_ACCESS_TOKEN = "/api/portal/accessToken" ENDPOINT_TOKEN_EXCHANGE = "/api/portal/authTokenExchange" ENDPOINT_SCOPED_TOKEN = "/api/portal/scopedTokenExchange" def __init__(self, network: QNetworkAccessManager): self.signal = BasicSignal() self.network = network self.dialog: QDialog = None self.page: WebPage = None # public def auth_project(self, conn_info): reply_tag = "oauth" project_hrn = conn_info.get_("project_hrn") platform_server = ( self.PLATFORM_URL_SIT if conn_info.is_platform_sit() else self.PLATFORM_URL_PRD ) url = "https://{platform_server}{endpoint}".format( platform_server=platform_server, endpoint=self.ENDPOINT_SCOPED_TOKEN ) payload = {"scope": project_hrn} kw_prop = dict(reply_tag=reply_tag, req_payload=payload) # token = self.get_access_token() token, _ = conn_info.get_xyz_space() reply = self.network.post( make_conn_request(url, token=token, req_type="json"), make_payload(payload) ) set_qt_property(reply, conn_info=conn_info, **kw_prop) return reply def auth(self, conn_info: SpaceConnectionInfo): reply_tag = "oauth" kw_prop = dict(reply_tag=reply_tag) # parent = self.network parent = None api_env = self.API_SIT if conn_info.is_platform_sit() else self.API_PRD CookieUtils.load_from_settings(self.network, API_TYPES.PLATFORM, api_env) token = self.get_access_token() if token: conn_info.set_(token=token) else: email = conn_info.get_("user_login") dialog = self.open_login_dialog(api_env, email=email) dialog.exec_() token = self.get_access_token() if token: conn_info.set_(token=token) else: self.reset_auth(conn_info) return self.make_dummy_reply(parent, conn_info, **kw_prop) def reset_auth(self, conn_info): api_env = self.API_SIT if conn_info.is_platform_sit() else self.API_PRD self._reset_auth(api_env) conn_info.set_(token=None) def _reset_auth(self, api_env): CookieUtils.remove_cookies_from_settings(API_TYPES.PLATFORM, api_env) # private def make_dummy_reply(self, parent, conn_info, **kw_prop): qobj = QObject(parent) set_qt_property(qobj, conn_info=conn_info, **kw_prop) return qobj def cb_dialog_closed(self, api_env: str, *a): self.dialog = None if self.get_access_token(): CookieUtils.save_to_settings(self.network, API_TYPES.PLATFORM, api_env) def cb_url_changed(self, url: QUrl): if "/authHandler" in url.toString(): self.auth_handler(url) elif "/sdk-callback-page" in url.toString(): # "action=already signed in" in url.toString() self.dialog.close() api_env = self.API_SIT if url.host() == self.HERE_URL_SIT else self.API_PRD self._reset_auth(api_env) def cb_auth_handler(self, reply): try: IMLNetworkHandler.on_received(reply) except NetworkError as e: self.signal.error.emit(e) self.dialog.close() def get_access_token(self) -> Optional[str]: cookie = CookieUtils.get_cookie(self.network, "olp_portal_access") if not cookie: return val = QUrl.fromPercentEncoding(cookie.value()) obj = json.loads(val) return obj.get("accessToken") def auth_handler(self, url: QUrl): """ Handle auth handler url to get cookies with access token :param url: :return: Example: QUrl('https://platform.here.com/authHandler?code=bfO-Yz6l3ZDPK0VIyC4tPkBH9K05-d8JQHP869q8MmA&state=%7B%22redirectUri%22%3A%22https%3A%2F%2Fplatform.here.com%2FauthHandler%22%2C%22redirect%22%3A%22https%253A%252F%252Fplatform.here.com%252F%22%7D')) """ query_kv = dict(s.split("=", 1) for s in url.query().split("&")) for k, v in query_kv.items(): query_kv[k] = url.fromPercentEncoding(v.encode("utf-8")) platform_server = url.host() url = "https://{platform_server}{endpoint}".format( platform_server=platform_server, endpoint=self.ENDPOINT_TOKEN_EXCHANGE ) reply = self.network.post( make_conn_request(url, token=None, req_type="json"), make_payload(query_kv), ) reply.finished.connect(lambda: self.cb_auth_handler(reply)) # reply.waitForReadyRead(1000) # self.cb_auth_handler(reply) def open_login_dialog(self, api_env: str, email: str = None, parent=None): if not self.dialog: dialog = QDialog(parent) page = WebPage.new_page(dialog, self.network) self.page = page self.dialog = dialog view = page.view() # url = "https://platform.here.com/" url = ( self.PLATFORM_LOGIN_URL_PRD if api_env == self.API_PRD else self.PLATFORM_LOGIN_URL_SIT ) if email: url = "&".join([url, "prefill-email-addr={email}".format(email=email)]) page.currentFrame().urlChanged.connect(self.cb_url_changed) dialog.finished.connect(lambda *a: self.cb_dialog_closed(api_env, *a)) dialog.open() view.load(QUrl(url)) else: dialog = self.dialog dialog.show() return dialog
def save_pack(obj: 'SERIALIZABLE', fp: TextIO, meta: Dict[str, 'JSONABLE'] = None, include_timestamp: bool = False) -> NoReturn: return json.dump(pack(obj, meta=meta, include_timestamp=include_timestamp), fp)
package com.jamasoftware.services.restclient.jamadomain.lazyresources; import com.jamasoftware.services.restclient.exception.RestClientException; import com.jamasoftware.services.restclient.jamadomain.core.JamaDomainObject; import java.util.List; public abstract class LazyCollection extends LazyBase { @Override public void forceFetch() throws RestClientException { markFetch(); copyContentFrom(jamaInstance.getResourceCollection(getCollectionUrl())); } public abstract String getCollectionUrl(); public abstract void copyContentFrom(List<JamaDomainObject> objectList); }
<gh_stars>1-10 // Container for application level data. #ifndef __CGAMEOBJECTMANAGER_H__ #define __CGAMEOBJECTMANAGER_H__ #include <iostream> #include "Defines.h" #include "PlayerEnums.h" namespace Core { class CPlayer; class CBuilding; class CGameObject; class CPluginManager; namespace Physics { class IPhysicsStrategy; } namespace SceneLoader { class CSerializer; } namespace AI { class CFpsVehicle; class Obstacle; class SphereObstacle; class BoxObstacle; class Wall; } namespace Plugin { class IGameObjectFactory; } class CORE_EXPORT CGameObjectManager { friend SceneLoader::CSerializer; public: typedef Map<CGameObject*, AI::Obstacle*> ObstacleList; static CGameObjectManager* Instance(); ~CGameObjectManager(); // Game Objects CGameObject* CreateObject(const char* GameObjectType); // Objects from plugins CGameObject* CreateObject(const char* GameObjectType, const char* Name, Vector3& Pos); CGameObject* CreateCustomObject(const char* MeshName); // Objects without plugins CGameObject* CreateCustomObject(const char* MeshName, const char* Name, Vector3& Pos); CGameObject* GetGameObject(Entity* entity); // Search by entity pointer CGameObject* GetGameObject(const char* Name); // Search by game object name CGameObject* GetGameObjectByEntityName(const char* Name); // Search by entity name, used when doing a scene query, and all you get back is a movable object void SetGameObjectUpdatable(CGameObject* GameObject, bool Value); void GetGameObjects(Vector<CGameObject*>& GameObjects); void GetAllObjectTypes(Vector<const char*>& ObjectTypes); void RemoveGameObject(CGameObject* GameObject); // Player methods CPlayer* CreatePlayer(const char* Type, E_PLAYER_TEAM Team, const char* LabelName = "", Physics::IPhysicsStrategy* PhysicsStrategy = nullptr, bool isPlayer = false); bool CreateCustomPlayer(CPlayer* Player, E_PLAYER_TEAM Team, const char* LabelName = "", Physics::IPhysicsStrategy* PhysicsStrategy = nullptr, bool isPlayer = false); bool AddCustomPlayer(CPlayer* Player, E_PLAYER_TEAM Team, bool isPlayer = false); void RemovePlayer(CPlayer* Player); void RemoveAllPlayers(); void GetTeam(E_PLAYER_TEAM Team, std::vector<CPlayer*>& List); void GetAllPlayers(Vector<CPlayer*>& Players); void GetPlayerTypes(Vector<const char*>& PlayerType); CPlayer* GetHumanPlayer() { return m_HumanPlayer; } CPlayer* GetPlayerByName(const char* Name); CPlayer* GetPlayerByEntityName(const char* EntityName); CPlayer* GetClosestVisibleEnemy(CPlayer* Player); CPlayer* GetClosestEnemy(CPlayer* Player); void SetHumanPlayer(CPlayer* Player); void ChangePlayerTeam(CPlayer* Player, E_PLAYER_TEAM Team); // Building methods CBuilding* CreateBuilding(const char* Type, E_PLAYER_TEAM Team, const char* LabelName, Physics::IPhysicsStrategy* PhysicsStrategy); CBuilding* GetBuildingByEntityName(const char* EntityName); void RemoveBuilding(CBuilding* Building); void RemoveAddBuildings(); void GetAllBuildingTypes(Vector<const char*>& ObjectTypes); Vector<CBuilding*>& GetAllBuildings(); // Events void Update(const f32& elapsedTime); void Shutdown(); // Destroy all objects, players and obstacles void Restart(); // Ensure the manager is ready to do its job again. // Obstacles void AddSphereObstacle(CGameObject* GameObject); void AddBoxObstacle(CGameObject* GameObject); void GetObstacles(Vector<AI::Obstacle*>& list); void GetSphereObstacles(Vector<AI::Obstacle*>& list); // Only sphere obstacles, temp fix for opensteer not working on all types of obstacles void RemoveObstacle(CGameObject* GameObject); // Walls void AddWall(const Vector3& From, const Vector3& To, bool LeftNormal = false); void GetWalls(Vector<AI::Wall*>& Walls); void RemoveWalls(); private: CGameObjectManager(); // Creates an internal unquie name for ogre String CreateName(const char* Name); // Player Methods void RemoveFromPlayerList(CPlayer* Player); // Removes the player from the players list // Obstacle Methods AI::SphereObstacle* FindClosestSphereObstacle(CPlayer* Player, f32& Max); AI::BoxObstacle* FindClosestBoxObstacle(CPlayer* Player, f32& Max); // Game Objects Vector<CGameObject*> m_GameObjects; // All game objects including objects that are NOT updated every frame Vector<CGameObject*> m_UpdatableGameObjects; // All game objects that need to be updated every frame // Players CPlayer* m_HumanPlayer; // Current human player Vector<CPlayer*> m_Players; // Used to run updates on all players including the human player Vector<CPlayer*> m_Teams[NUM_TEAMS]; // Used to do queries based on the teams for each player // Buildings Vector<CBuilding*> m_Buildings; // All buildings Vector<CBuilding*> m_UpdatableBuildings; // All updatable buildings ObstacleList m_ObsObj; // Map objects to obstacles Vector<AI::Wall*> m_Walls; static CGameObjectManager* GameObjectManager; Core::CPluginManager* m_PluginManager; u32 m_GameObjectCounter; // Number of game objects that have been created u32 m_PlayerCounter; // Number of players that have been created u32 m_BuildingCounter; // Number of buildings that have been created }; } #endif // __CGAMEOBJECTMANAGER_H__
""" A converter class, able to verify, extract and submit important tumor diagnostic information from a ZIP archive to CentraXX. """ import os import sys import uuid import shutil from zipfile import ZipFile from mtbparser.snv_utils import * from .mtbfiletype import MtbFileType from .mtbconverter_exceptions import MtbUnknownFileType from .mtbconverter_exceptions import MtbIncompleteArchive from .mtbconverter_exceptions import MtbUnknownBarcode from .datasetinstance import DataSetInstance from .patientdataset import PatientDataSet from .cx_profiles import * from mtbparser.snv_parser import SnvParser from mtbparser.snv_utils import SSnvHeader from datetime import datetime TEMP_BASE_PATH = "/tmp" FILETYPE_HEADER = { MtbFileType.GERM_SNV: GSnvHeader, MtbFileType.SOM_SNV: SSnvHeader, MtbFileType.GERM_CNV: CnvHeader, MtbFileType.SOM_CNV: CnvHeader, MtbFileType.SOM_SV: SsvHeader, MtbFileType.META: MetaData } VERSIONS = { MtbFileType.GERM_SNV: 'QBIC_GERMLINE_SNV_V{}'.format(GERMLINE_SNV_VERSION) , MtbFileType.SOM_SNV: 'QBIC_SOMATIC_SNV_V{}'.format(SOMATIC_SNV_VERSION), MtbFileType.GERM_CNV: 'QBIC_GERMLINE_CNV_V{}'.format(GERMLINE_CNV_VERSION), MtbFileType.SOM_CNV: 'QBIC_SOMATIC_CNV_V{}'.format(SOMATIC_CNV_VERSION), MtbFileType.SOM_SV: 'QBIC_SOMATIC_SV_V{}'.format(SOMATIC_SV_VERSION), MtbFileType.META: 'QBIC_METADATA_V{}'.format(METADATA_VERSION) } class MtbConverter(): def __init__(self, zip_file, sample_code, patient_code): pyxb.utils.domutils.BindingDOMSupport.DeclareNamespace(cx.Namespace, 'cxx') self._root = cx.CentraXXDataExchange() self._zip_file = zip_file self._sample_code = sample_code self._patient_code = patient_code self._filelist = {} self._snvlists = {} self._tmp_dir = TEMP_BASE_PATH + os.path.sep + "tmp_uktdiagnostics_" + uuid.uuid4().hex os.mkdir(self._tmp_dir) self._verify() self._extract() def _extract(self): try: self._zip_file.extractall(path=self._tmp_dir) except Exception as exc: print(exc) self._cleanup() sys.exit(1) def convert(self): print("Conversion started") flex_ds_instances = [] date_time = datetime.isoformat(datetime.now()) counter = 1 # First, we have to build a flexible data type # for EVERY variant entry! for variant_file, mtb_filetype in self._filelist.items(): # Skip germline data atm if mtb_filetype == mtb_filetype.GERM_SNV or mtb_filetype == mtb_filetype.GERM_CNV: continue file_path = self._tmp_dir + os.path.sep + variant_file print('Sample {}: Processing of file {}'.format(self._sample_code, variant_file)) snv_list = SnvParser(file_path, FILETYPE_HEADER[mtb_filetype]).getSNVs() version = VERSIONS[mtb_filetype] for snv_item in snv_list: ds_instance = DataSetInstance( header_type=FILETYPE_HEADER[mtb_filetype], snv_item=snv_item, date=date_time, version=version, instance=counter ) flex_ds_instances.append(ds_instance) counter += 1 # Second, we have to build a patient data set # that consumes the references from the flexible # data set instances patient_ds = PatientDataSet( qbic_pat_id=self._patient_code, qbic_sample_id=self._sample_code, datetime=date_time, datasetinstance_list=flex_ds_instances ) # Third, build the complete CentraXXDataExchange XML # object, that can be consumed by CentraXX flex_data_sets = [ds.datasetinstance() for ds in flex_ds_instances] self._root.Source = 'XMLIMPORT' effect_data = cx.EffectDataType(PatientDataSet=[patient_ds.patientdataset()]) effect_data.FlexibleDataSetInstance = flex_data_sets self._root.EffectData = effect_data root_dom = self._root.toDOM() root_dom.documentElement.setAttributeNS( xsi.uri(), 'xsi:schemaLocation', 'http://www.kairos-med.de ../CentraXXExchange.xsd') root_dom.documentElement.setAttributeNS( xmlns.uri(), 'xmlns:xsi', xsi.uri()) # Clean up the temp extraction files from the archive self._cleanup() return root_dom.toprettyxml(encoding='utf-8') def _verify(self): for zipinfo in self._zip_file.infolist(): filename = zipinfo.filename assigned_type = self._getfiletype(filename) if self._sample_code not in filename: raise MtbUnknownBarcode("Could not find sample_code {} in file '{}'. All" " files need to contain the same " "sample_code as the zip archive.".format(self._sample_code, filename)) if not assigned_type: raise MtbUnknownFileType("Could not determine filetype " "according to the naming convention." " {} was probably not defined.".format(filename)) self._filelist[filename] = assigned_type if len(self._filelist) != len(MtbFileType): raise MtbIncompleteArchive("The archive did not contain all necessary files." " Only found: {}".format(self._filelist.values())) def _cleanup(self): print(self._tmp_dir) shutil.rmtree(self._tmp_dir) def _getfiletype(self, filename): for filetype in MtbFileType: if filetype.value in filename: return filetype return ""
def read_resource_task(self,task,roles): filtered_list = list(filter(lambda x: x['task']==task, self.data)) role_assignment = list() for task in filtered_list: for role in roles: for member in role['members']: if task['user']==member: role_assignment.append(role['role']) return max(role_assignment)