text
stringlengths
175
47.7k
meta
dict
Q: Calling JavaScript function from [WebMethod] I need to call a JavaScript function that shows a Bootstrap modal. I have the following code: [System.Web.Services.WebMethod()] [System.Web.Script.Services.ScriptMethod()] public static void execModal(string groupname, int zw) { //need to generate the data first StringBuilder sb = new StringBuilder(); Generate gen = new Generate(); sb = gen.generateDeeperTable(zw, groupname); //insert into my placeholder //Append the HTML string to Placeholder. fillPH(sb); //run javascript function <showModel> to show the modal } Here is how I call the execModal method form JS: <script type="text/javascript> function callGenDeeperTable(zw, groupname) { PageMethods.execModal(groupname, zw); } </script> The function execModal is called from a javascript function in the .aspx site. How can I call the javascript function showModal? A: Your execModal method is on the server. You have not specified where you want to invoke (call) it from, but since you've decorated it (added attributes to the method defining it...) as a WebMethod, chances are you're trying to invoke it from a (HTML) page running in a client's browser. To make this call you need a line of communication between the client that wants to run the method, and the server that holds the method. You will also notice that execModal is defined as a static method. That means that when it is invoked it will not have the instance members of the Page class, including things like fillPH (unless fillPH is static). I don't know if you're working with ASP.NET WebForms (trying to make the call from an .aspx page), or this is a service consumed by some application (method resides in an .asmx), or I guess this could even be ASP.NET MVC. Assuming ASP.NET WebForms Let's deal with the simplest case since there have been almost no details provided. If we assume that this method, execModal, lives in an .aspx.cs file, and you're trying to call it from the corresponding .aspx page, and this is part of an ASP.NET WebForms application... You need to initiate the call to execModal. This requires an AJAX call from your client to your server. You can create your own AJAX framework, but there are many open source frameworks available. I will give an example below using jQuery. You need to do the work on the server statically, or you need to use the HttpCurrent.Context to get the instance of the Page, Session, etc. The Page can be retrieved via the HttpCurrent.Context.Handler as Page. Once the method finishes on the server, the result (success or failure), and optionally any data you want to return to the client, is sent back to the client's browser. The client portion of the application should be able to process this response with an event handler. The event handler should be associated with the XMLHttpRequest object's onreadystatechange event and process the response when the state changes to 4 (done). Frameworks, like jQuery, take care of this overhead by providing parameters in your AJAX call to specify the success/failure callbacks. Do not confuse the result (sucess/failure) of this communication process with the result of your application's processes (actual work of execModal). Your client side (success) callback function would then just call your desired js function showModal. Your client side AJAX call (if you were to use jQuery) would look something like this... $.ajax({ type: "POST", url: "Default.aspx/execModal", data: '{groupname: "' + groupname + '", zw: ' + zw + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { showModal(); }, failure: function(response) { alert("AJAX request failed"); } }); This is a very basic example. You might want the server to decide what happens on success, but returning a JSON data, or a string with the name of a js function that can be executed on the client - these are just examples to get your thinking about what is possible. Edit - account for OP's addition of PageMethods.execModal() to question You say you're calling your server code from this... <script type="text/javascript> function callGenDeeperTable(zw, groupname) { PageMethods.execModal(groupname, zw); } That implies that you're using ASP.NET's ScriptManager with EnablePageMethods=true. Is that correct? That would inject the script with the PageMethods type, and define functions for each of your WebMethods. So you are using an AJAX framework - the one provided by MS. All that work of making the AJAX call is being hidden from you with PageMethods.execModal(groupname, zw). However, each of the functions generated for you (on the PageMethod object) take additional parameters for OnSuccess and OnFailure callbacks. Here is a SO answer detailing how to use the ScriptManager's PageMethod object. The signature for any function generated on the PageMethod object corresponding to a WebMethod is... function foo(param1, param2, param3, etc., OnSuccess, OnFailure) In your case, you have two parameters being passed to the WebMethod, so after those two parameters you would want to supply callback functions for success and failure. showModal would be your success handler probably... PageMethods.execModal(groupname, zw, showModal, function() { alert('failed!') });
{ "pile_set_name": "StackExchange" }
Q: DataTables YajraBox Laravel extension with Eloquent Query String Filtering im newbie Laravel, im trying to create a data table with YajraBox extension. Im stuck on ajax controller: public function indexData(LotFilters $filters) { $lots = Lot::filter($filters)->get(); return Datatables::of($lots)->make(true); } This is my route: Route::get('data', 'LotController@indexData'); When i go: http://127.0.0.1:8000/data it gives me an error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 140673944 bytes) It think i need to set up a pagination, but i didn't find a example how to do it, maybe you guys can help me? A: Actually i find a solution just now. i just need to remove ->get(); from the end.
{ "pile_set_name": "StackExchange" }
Q: Exclude element from zooming using SvgPanZoom I have an SVG and in it a lot of elements. I also have a popup element which is shown on an element click. When I zoom the SVG the popup should not be zoomed. How can I prevent this popup from being zoomed with the SVG? A: See this demo. Basically you can zoom only one SVG group while keeping others static.
{ "pile_set_name": "StackExchange" }
Q: Creating an object of an inherited class in c# This should be a pretty straight-forward question. I only ask for a simple easy to understand answer. No, I don't want a textbook definition or a link to documentation, please, if possible answer this as simply as possible. Consider the following: class Monster { public int Hp { get; protected set; } public string Name { get; protected set; } public virtual void Attack() { Console.WriteLine("Monster attacking!"); } } class Skeleton : Monster { public Skeleton() { Hp = 20; Name = "Skeleton"; } public override void Attack() { Console.WriteLine("Skeleton attacking!"); } } Now imagine I create a new Skeleton object with the type Monster as so. Monster skeleton = new Skeleton(); I would like to know the difference between creating a Skeleton object with a Monster Type vs creating a Skeleton Object with a Skeleton type. Skeleton skeleton = new Skeleton(); I don't understand if there's a difference between the two or really how this works. Any and all help appreciated! Thank you! A: The benefits to creating a Skeleton object with a Monster type becomes more apparent when you have multiple monsters that you want to hold in a single collection. For example, you might have a list defined as follows: List<Monster> EncounterMonsters = new List<Monster>(); Declaring your Skeleton object as Monster allows you to add it to this list, along with any other Monster classes you create. So, you might have another monster class: class Ogre : Monster { public Ogre() { Hp = 50; Name = "Ogre"; } public override void Attack() { Console.WriteLine("Ogre attacking!"); } } You could then do the following: Monster skeleton = new Skeleton(); Monster ogre = new Ogre(); EncounterMonsters.Add(skeleton); EncounterMonsters.Add(ogre); This would then allow you to loop through the EncounterMonsters collection and attack with each using the overridden Attack method for each.
{ "pile_set_name": "StackExchange" }
Q: Extracting different length of numbers (latitude and longitude) from unstructured text file with R I want to extract differents latitudes and longitudes from from unstructured text file. The coordinates can take these forms : "0.41566" ; "-0.41566" ; "21.36584785" ; "100.2457 This syntax works only for numbers like that 120.564874 library(stringr) lat <- c("([0-9]{3}) [.] ([0-9]{6})") essailat<-str_extract_all(essai,lat, simplify=F) But As I said, I would like to extract all the other formats presented above. library(stringr) lat <- c("([0-9]{1}) [.] ([0-9]{4})", "([0-9]{3}) [.] ([0-9]{6})") essailat<-str_extract_all(essai,lat, simplify=F) But it does not seems to work. Plus sometimes, my lat is a negative number (-0.41567) so I would like to specify that it extract as well the negative sign Thank you in advance for your help. PS: this is what I meant to specify a unstructured file and as lon and lat works by pair I can extract first all the lat with a certain type of format but all of them at once respecting the order. THANK YOU in advance for your help ! Sample input: cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"900.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"-0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"-0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"-0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac"latitude":"0.252578";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca"longitude":"0.997754"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacac A: You may use the following fix: > library(stringr) > lat <- "-?[0-9]+\\.[0-9]+" > s <- "cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"900.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"0.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"-0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"0.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"0.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"-0.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"0.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"-0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"0.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"0.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacacac\"latitude\":\"0.252578\";cacacacacacacacacacacacacacacaccacacacacacacacacacacacacacacacaccccacacacacaca\"longitude\":\"0.997754\"cacacacacacaacacacacacaacacacacacacacacacacacacacacacacacacacac" > essailat<-str_extract_all(s,lat) > essailat [[1]] [1] "900.252578" "0.997754" "0.252578" "-0.997754" "0.252578" "0.997754" "0.252578" "0.997754" [9] "-0.252578" "0.997754" "0.252578" "-0.997754" "0.252578" "0.997754" "0.252578" "0.997754" [17] "0.252578" "0.997754" The -?[0-9]+\\.[0-9]+ regex will match an optional -, then 1+ digits, a literal ., and again 1+ digits. See the regex demo online.
{ "pile_set_name": "StackExchange" }
Q: How to create a file in shell script I need to write a shell script where I read a variable from environment. If the file pointed by it doesn't exist, I want to create it. This file path could contain some intermediate non-existent directories, so these also need to be created. So neither mkdir -p works here nor simple touch works here. What is the workaround? Thanks! A: mkdir -p "`dirname $foo`" touch "$foo" dirname works on arbitrary paths; it doesn't check whether the path is in use (whether the file pointed to exists).
{ "pile_set_name": "StackExchange" }
Q: Merge Elements Of int array C# I've been looking around on MSDN and Stack overflow for a while now, but i can't seem to find anything, i want to merge elements of an int array. I've looked at string.join but can't seem to find an equivalent for int int[] myArray = new int[] {1,4}; int myArray[0] + myArray[1] would equal 14, Note that i want to merge them together not mathematically add them. The whole program: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Exercise2 { /** Create a reference type called Person. Populate the Person class with the following properties to store the following information: First name Last name Email address Date of birth **/ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string DOB = tbDOB.Text; DOB.Replace("\\"," "); int[] iDOB = DOB.Select(n => Convert.ToInt32(n)).ToArray(); int day = } } } Would it be better to change it to a char array? A: You can use string.Concat and then parse the result to integer: int result = int.Parse(string.Concat(myArray)); Also strings are immutable, you need to assign DOB back, and you need to replace non-digit chars with string.Empty not with a white-space otherwise you will get a FormatException. DOB = DOB.Replace("\\", "");
{ "pile_set_name": "StackExchange" }
Q: Why does bodies move after an perfect inelastic collision? This might be a very basic concept but I have never been able to understand it. Lets say a object with speed $v$ collides with another of same mass at rest in an perfectly inelastic collision in which the momentum. Why does then the both object join and move with speed $v/2$ ? If all the kinetic energy is lost then where does the energy to move the two blocks come from ? Also if I throw wet clay at my bedroom wall it does not move with the clay ? I understand, plugging values in conservation of momentum equation gives this result. A: In a perfectly inelastic collision, all the kinetic energy in the center of mass frame is lost. This is the key fact you are missing. Problem 1: If you compute the problem of 2 equal masses, one a rest and the other moving to collision at speed $v$, in the center of mass frame, those 2 masses are moving at $v/2$ and $-v/2$ towards each other. The final state the 2 masses are "stuck" together and there's no kinetic energy. All the initial kinetic energy of $${1 \over 2} m ({v \over 2})^2+ {1 \over 2} m ({v \over 2})^2$$ is lost in the CM frame. You were analyzing the collision in a non-CM frame! Problem 2 In the wet clay problem, you can model your wall as an infinite mass (ok, technically, the wall is glued to the earth, and so you could use the earth as the 2nd mass). Then for all intents and purpose, the center of mass frame is the earth, coz, well the earth is pretty heavy and dominates the CM. All the kinetic energy is lost in the frame of the wall/earth as you observe!
{ "pile_set_name": "StackExchange" }
Q: Create a QDockWidget that resizes to it's contents I have an application where fixed-size child widgets need to be added programatically to a dock widget at run time based on user input. I want to add these widgets to a dock on the Qt::RightDockArea, from top to bottom until it runs out of space, then create a new column and repeat (essentially just the reverse of the flow layout example here, which I call a fluidGridLayout) I can get the dock widget to resize itself properly using an event filter, but the resized dock's geometry doesn't change, and some of the widgets are drawn outside of the main window. Interestingly, resizing the main window, or floating and unfloating the dock cause it to 'pop' back into the right place (I haven't been able to find a way to replicate this programatically however) I can't use any of the built-in QT layouts because with the widgets in my real program, they end up also getting drawn off screen. Is there some way that I can get the dock to update it's top left coordinate to the proper position once it has been resized? I think this may be of general interest as getting intuitive layout management behavior for dock widgets in QT is possibly the hardest thing known to man. VISUAL EXMAPLE: The code to replicate this is example given below. Add 4 widgets to the program using the button Resize the green bottom dock until only two widgets are shown. Notice that the 3 remaining widgets are getting painted outside the main window, however the dock is the right size, as evidenced by the fact that you can't see the close button anymore Undock the blue dock widget. Notice it snaps to it's proper size. Re-dock the blue dock to the right dock area. Notice it appears to be behaving properly now. Now resize the green dock to it's minimum size. Notice the dock is now IN THE MIDDLE OF THE GUI. WTf, how is this possible?? THE CODE Below I give the code to replicate the GUI from the screenshots. main.cpp: #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); }; #endif // MAINWINDOW_H mainwindow.cpp #include "mainwindow.h" #include "QFluidGridLayout.h" #include "QDockResizeEventFilter.h" #include <QDockWidget> #include <QGroupBox> #include <QPushButton> #include <QWidget> #include <QDial> class QTestWidget : public QGroupBox { public: QTestWidget() : QGroupBox() { setFixedSize(50,50); setStyleSheet("background-color: red;"); QDial* dial = new QDial; dial->setFixedSize(40,40); QLayout* testLayout = new QVBoxLayout; testLayout->addWidget(dial); //testLayout->setSizeConstraint(QLayout::SetMaximumSize); setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); setLayout(testLayout); } QSize sizeHint() { return minimumSize(); } QDial* dial; }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QDockWidget* rightDock = new QDockWidget(); QDockWidget* bottomDock = new QDockWidget(); QGroupBox* central = new QGroupBox(); QGroupBox* widgetHolder = new QGroupBox(); QGroupBox* placeHolder = new QGroupBox(); placeHolder->setStyleSheet("background-color: green;"); placeHolder->setMinimumHeight(50); widgetHolder->setStyleSheet("background-color: blue;"); widgetHolder->setMinimumWidth(50); widgetHolder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); widgetHolder->setLayout(new QFluidGridLayout); widgetHolder->layout()->addWidget(new QTestWidget); QPushButton* addWidgetButton = new QPushButton("Add another widget"); connect(addWidgetButton, &QPushButton::pressed, [=]() { widgetHolder->layout()->addWidget(new QTestWidget); }); central->setLayout(new QVBoxLayout()); central->layout()->addWidget(addWidgetButton); rightDock->setWidget(widgetHolder); rightDock->installEventFilter(new QDockResizeEventFilter(widgetHolder,dynamic_cast<QFluidGridLayout*>(widgetHolder->layout()))); bottomDock->setWidget(placeHolder); this->addDockWidget(Qt::RightDockWidgetArea, rightDock); this->addDockWidget(Qt::BottomDockWidgetArea, bottomDock); this->setCentralWidget(central); central->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); this->setMinimumSize(500,500); } }; QFluidGirdLayout.h #ifndef QFluidGridLayout_h__ #define QFluidGridLayout_h__ #include <QLayout> #include <QGridLayout> #include <QRect> #include <QStyle> #include <QWidgetItem> class QFluidGridLayout : public QLayout { public: enum Direction { LeftToRight, TopToBottom}; QFluidGridLayout(QWidget *parent = 0) : QLayout(parent) { setContentsMargins(8,8,8,8); setSizeConstraint(QLayout::SetMinAndMaxSize); } ~QFluidGridLayout() { QLayoutItem *item; while ((item = takeAt(0))) delete item; } void addItem(QLayoutItem *item) { itemList.append(item); } Qt::Orientations expandingDirections() const { return 0; } bool hasHeightForWidth() const { return false; } int heightForWidth(int width) const { int height = doLayout(QRect(0, 0, width, 0), true, true); return height; } bool hasWidthForHeight() const { return true; } int widthForHeight(int height) const { int width = doLayout(QRect(0, 0, 0, height), true, false); return width; } int count() const { return itemList.size(); } QLayoutItem *itemAt(int index) const { return itemList.value(index); } QSize minimumSize() const { QSize size; QLayoutItem *item; foreach (item, itemList) size = size.expandedTo(item->minimumSize()); size += QSize(2*margin(), 2*margin()); return size; } void setGeometry(const QRect &rect) { QLayout::setGeometry(rect); doLayout(rect); } QSize sizeHint() const { return minimumSize(); } QLayoutItem *takeAt(int index) { if (index >= 0 && index < itemList.size()) return itemList.takeAt(index); else return 0; } private: int doLayout(const QRect &rect, bool testOnly = false, bool width = false) const { int left, top, right, bottom; getContentsMargins(&left, &top, &right, &bottom); QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); int x = effectiveRect.x(); int y = effectiveRect.y(); int lineHeight = 0; int lineWidth = 0; QLayoutItem* item; foreach(item,itemList) { QWidget* widget = item->widget(); if (y + item->sizeHint().height() > effectiveRect.bottom() && lineWidth > 0) { y = effectiveRect.y(); x += lineWidth + right; lineWidth = 0; } if (!testOnly) { item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); } y += item->sizeHint().height() + top; lineHeight = qMax(lineHeight, item->sizeHint().height()); lineWidth = qMax(lineWidth, item->sizeHint().width()); } if (width) { return y + lineHeight - rect.y() + bottom; } else { return x + lineWidth - rect.x() + right; } } QList<QLayoutItem *> itemList; Direction dir; }; #endif // QFluidGridLayout_h__ QDockResizeEventFilter.h #ifndef QDockResizeEventFilter_h__ #define QDockResizeEventFilter_h__ #include <QObject> #include <QLayout> #include <QEvent> #include <QDockWidget> #include <QResizeEvent> #include "QFluidGridLayout.h" class QDockResizeEventFilter : public QObject { public: QDockResizeEventFilter(QWidget* dockChild, QFluidGridLayout* layout, QObject* parent = 0) : QObject(parent), m_dockChild(dockChild), m_layout(layout) { } protected: bool eventFilter(QObject *p_obj, QEvent *p_event) { if (p_event->type() == QEvent::Resize) { QResizeEvent* resizeEvent = static_cast<QResizeEvent*>(p_event); QMainWindow* mainWindow = static_cast<QMainWindow*>(p_obj->parent()); QDockWidget* dock = static_cast<QDockWidget*>(p_obj); // determine resize direction if (resizeEvent->oldSize().height() != resizeEvent->size().height()) { // vertical expansion QSize fixedSize(m_layout->widthForHeight(m_dockChild->size().height()), m_dockChild->size().height()); if (dock->size().width() != fixedSize.width()) { m_dockChild->resize(fixedSize); m_dockChild->setFixedWidth(fixedSize.width()); dock->setFixedWidth(fixedSize.width()); mainWindow->repaint(); //dock->setGeometry(mainWindow->rect().right()-fixedSize.width(),dock->geometry().y(),fixedSize.width(), fixedSize.height()); } } if (resizeEvent->oldSize().width() != resizeEvent->size().width()) { // horizontal expansion m_dockChild->resize(m_layout->sizeHint().width(), m_dockChild->height()); } } return false; } private: QWidget* m_dockChild; QFluidGridLayout* m_layout; }; #endif // QDockResizeEventFilter_h__ A: The problem is, nothing in the code above actually causes the QMainWindowLayout to recalculate itself. That function is buried within the QMainWindowLayout private class, but can be stimulated by adding and removing a dummy QDockWidget, which causes the layout to invalidate and recalcualte the dock widget positions QDockWidget* dummy = new QDockWidget; mainWindow->addDockWidget(Qt::TopDockWidgetArea, dummy); mainWindow->removeDockWidget(dummy); The only problem with this is that if you dig into the QT source code, you'll see that adding a dock widget causes the dock separator to be released, which causes unintuitive and choppy behavior as the user tries to resize the dock, and the mouse unexpectedly 'lets go'. void QMainWindowLayout::addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget, Qt::Orientation orientation) { addChildWidget(dockwidget); // If we are currently moving a separator, then we need to abort the move, since each // time we move the mouse layoutState is replaced by savedState modified by the move. if (!movingSeparator.isEmpty()) endSeparatorMove(movingSeparatorPos); layoutState.dockAreaLayout.addDockWidget(toDockPos(area), dockwidget, orientation); emit dockwidget->dockLocationChanged(area); invalidate(); } That can be corrected by moving the cursor back onto the separator and simulating a mouse press, basically undoing the endSeparatorMove callafter the docks have been repositioned. It's important to post the event, rather than send it, so thatit occurs after the resize event. The code for doing so looks like: QPoint mousePos = mainWindow->mapFromGlobal(QCursor::pos()); mousePos.setY(dock->rect().bottom()+2); QCursor::setPos(mainWindow->mapToGlobal(mousePos)); QMouseEvent* grabSeparatorEvent = new QMouseEvent(QMouseEvent::MouseButtonPress,mousePos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier); qApp->postEvent(mainWindow, grabSeparatorEvent); Where 2 is a magic number that accounts for the group box border. Put that all together, and here is the event filter than gives the desired behavior: Corrected Event Filter #ifndef QDockResizeEventFilter_h__ #define QDockResizeEventFilter_h__ #include <QObject> #include <QLayout> #include <QEvent> #include <QDockWidget> #include <QResizeEvent> #include <QCoreApplication> #include <QMouseEvent> #include "QFluidGridLayout.h" class QDockResizeEventFilter : public QObject { public: friend QMainWindow; friend QLayoutPrivate; QDockResizeEventFilter(QWidget* dockChild, QFluidGridLayout* layout, QObject* parent = 0) : QObject(parent), m_dockChild(dockChild), m_layout(layout) { } protected: bool eventFilter(QObject *p_obj, QEvent *p_event) { if (p_event->type() == QEvent::Resize) { QResizeEvent* resizeEvent = static_cast<QResizeEvent*>(p_event); QMainWindow* mainWindow = dynamic_cast<QMainWindow*>(p_obj->parent()); QDockWidget* dock = static_cast<QDockWidget*>(p_obj); // determine resize direction if (resizeEvent->oldSize().height() != resizeEvent->size().height()) { // vertical expansion QSize fixedSize(m_layout->widthForHeight(m_dockChild->size().height()), m_dockChild->size().height()); if (dock->size().width() != fixedSize.width()) { m_dockChild->setFixedWidth(fixedSize.width()); dock->setFixedWidth(fixedSize.width()); // cause mainWindow dock layout recalculation QDockWidget* dummy = new QDockWidget; mainWindow->addDockWidget(Qt::TopDockWidgetArea, dummy); mainWindow->removeDockWidget(dummy); // adding dock widgets causes the separator move event to end // restart it by synthesizing a mouse press event QPoint mousePos = mainWindow->mapFromGlobal(QCursor::pos()); mousePos.setY(dock->rect().bottom()+2); QCursor::setPos(mainWindow->mapToGlobal(mousePos)); QMouseEvent* grabSeparatorEvent = new QMouseEvent(QMouseEvent::MouseButtonPress,mousePos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier); qApp->postEvent(mainWindow, grabSeparatorEvent); } } if (resizeEvent->oldSize().width() != resizeEvent->size().width()) { // horizontal expansion // ... } } return false; } private: QWidget* m_dockChild; QFluidGridLayout* m_layout; }; #endif // QDockResizeEventFilter_h__
{ "pile_set_name": "StackExchange" }
Q: Laravel Route URI: Add or condition I have written a route with uri, which accepts /app/12/password Route::get('app/{id}/password', 'AppController@pwd')->name('apwd'); Now i want to extend it to also accept /app/12/pwd. What is standard way to do this, since i can't write different route. I tried. Route::get('app/{id}/(pwd|password)', 'AppController@pwd')->name('apwd'); Any help is appreciated. A: You may try this: Route::get('app/{id}/{param}', 'AppController@pwd') ->where('param', 'pwd|password') // param will accept either 'pwd' or 'password' ->name('apwd');
{ "pile_set_name": "StackExchange" }
Q: Is it safe to recycle DatagramPacket objects? The Question: Assuming you are transferring up to 10 MB/s, is it a good idea to recycle DatagramPacket objects, instead of creating a new one every time a packet is to be sent? The Story: I'm creating a LAN file-sync application that deals with files over 30 GB at times. The file sync application will transfer the files over 100Mbit wired LAN. I already have an anti-packet-loss system in place (which works flawlessly). The program works fine but takes around 10% CPU usage, and since this is a background application, this is too much for me. Ideally it will be around 3% tops. When profiling I discovered the garbage collector was going mental, activating every few seconds. I know object creation (when done in large quantities) gets heavy for Java, so now I'm trying to recycle as many objects and arrays as I can. Each packet containing file data has a size of 1450 bytes, meaning that transferring at 10 MB/s will be around 7,200 packets per second. I decided to start recycling these packets (i.e. when a packet is sent, the DatagramPacket object will added to a list, and after 5 seconds the DatagramPacket can be re-used). When a DatagramPacket is re-used, the method DatagramPacket.setData() is used to assign the data it is going to send. Apart from sending packets containing file data, I also send small packets roughly every second to try and determine the ping of the connection. These ping packets have a size of 10 bytes. The Error: After testing my application with the DatagramPacket recycle feature for roughly 30 minutes, strange errors start to pop up. One time the file being transferred got corrupted, and other times I get something I can't wrap my head around... Below is some of the code of my class. The integer length is only set through the applyData() method. public class PacketToSend { private int length; private DatagramPacket packet; ... public void applyData(byte[] newData) { try { length = newData.length; packet.setData(newData, 0, length); } catch(java.lang.IllegalArgumentException e) { System.out.println("Arraylength = "+newData.length); System.out.println("length value = "+length); } } ... } After about 20-40 minutes testing each time, I get an IllegalArgumentException, telling me that newData's size is 10, and the value of length is 1450, thus saying the length is illegal. How is this even possible? The variable length is not modified anywhere else but in this method and is set right before setData() is called! It's as though the DatagramPacket randomly switches to sending the ping data... These errors only occurs when I enable my DatagramPacket recycling feature. Mind you, after a packet is sent, it is placed on a list and will wait for 5 full seconds before it is re-used again. I'm wondering if the OS somehow has its finger in these packets, or perhaps some native code is manipulating the data. There is only one thread in my program that sends packets, so this is not a threading or synchronization issue. Hence my question: is it a good idea to recycle DatagramPacket objects, instead of creating a new one every time a packet is to be sent? Or am I playing with fire and things I should really leave alone? Attempted Fixes: I've placed length = newData.length; after calling setData(newData, 0, newData.length);, which prevented the IllegalArgumentException but I still encountered other errors, such as connection loss. Regardless, the error mentioned above, according to my knowledge of Java, simply should never occur, so I think something else is at work here. A: Is it safe to recycle DatagramPacket objects? As far as I am aware or can determine, there is nothing inherently unsafe about reusing DatagramPacket instances. On the other hand, the errors you describe only make sense if instances are shared between two or more threads, and accessing shared objects from multiple threads without proper synchronization is definitely unsafe. No amount of waiting substitutes for synchronization, so the strategy of imposing a 5-second delay before reuse is probably counterproductive -- it does not guarantee correct operation, yet it may cause your program to maintain more live objects than it really needs. Without details of your program's architecture, we can speak only in generalities about what you can do to resolve the situation. At the most general level, the alternatives are to avoid sharing objects between threads and to access the shared objects in a thread-safe manner. However, any mechanism for thread-safe object sharing carries relatively significant overhead, and I'm inclined to think that performing 20 million thread-safe operations in the course of one file transfer will be far too costly to be acceptable. Your best bet, therefore, is to avoid sharing objects. Creating new DatagramPackets at every need and not allowing them to escape the threads in which they were created is one way to achieve that. Since that's causing too much GC for you, the next logical step might be to maintain per-thread queues of reusable packets. You might use a ThreadLocal for that, but if each file transfer is managed by a single thread then you could also consider using per-file queues. Either way, be careful also about other sharing, such as of the data buffer arrays carried by the DatagramPackets (which might well be something else you could reuse). Also, if you are careful not to share data between threads, then you should be able to do so without a reuse delay. Indeed, you might not need more than one DatagramPacket and one buffer array per thread. That could make your code not only more efficient but also simpler.
{ "pile_set_name": "StackExchange" }
Q: C: program prints garbage text even after structs are freed I have a program with the following structs: typedef struct slide { int number; int maxX; int y; int r, g, b; struct line *first; } slide; typedef struct line { char content[256]; // number subject to change int r, g, b; struct line *prev; struct line *next; } line; Creating instances of these structs is done with the following code: slide* createSlideArray(int s) { slide* slides = malloc(sizeof(struct slide)*s); return slides; } line *nextLine(line *prev) { line *n = malloc(sizeof(line)); n->prev = prev; prev->next = n; return n; } And finally here is the code to free the structs after the program loop finishes, and before a new file is opened: void freeLines(line *l) { line *next; while(l) { next = l->next; free(l); l = next; } } in main: int i; for (i=0;i<slideCount;i++) { freeLines(slides[i].first); // works through next till NULL } free(slides); As you can see, an instance of the slide struct holds a "first" line struct, the line struct is a doubly linked list. The line's content is read to the screen (using ncurses) While in the program loop the user can type a command :open filename to open a new file, this is where my issue lies. This slides and lines should be freed. When the loop starts again it'll open a new file, create the slides and lines, and use them as the content. The content, however, is partially filled with garbage text. I'm pretty sure this issue is in the lines struct and how it is being free. I'm not seeing that I'm doing wrong however. Edit: I should make it clear that on the first iteration of the program the text is perfect, it is only when I try to parse a new file that the garbage text appears, and it is very homogeneous (appears at the front of each line, same characters) I'm on Ubuntu if that makes a difference. Here is a link to the project: DSS A: There are some clear issues that I can spot from reading the code in your post. I can't definitively say if these are responsible for your problem as the code in your post is not a compilable example and I didn't go delving into your linked project. Your nextLine function: You have neglected to set n->next. You have also neglected setting the prev pointer of the following node if there is one. ( prev->next->prev if prev->next != NULL ). You current design precludes you from using this function to setup the first node in the list. It also does not show how you intend to create that node. This function does not allow you to add a node to the begining of the list. Your createSlideArray function: This function does not initialize the slides it creates. These slide instances must be initialized. It seems sensible to do it here, but you might have a good reason to do it elsewhere. In either case, initializing the slideObject.first member is critical. Without this you will not be able to tell if the slide has a list of lines or not and your freeLines function will fail as it will be passed garbage as its parameter. Note: A different way of implementing doubly linked lists is using a "head node" which is always present and links to the first and last node in the list. This simplifies some issues, but changes others. You can research this if you are interested.
{ "pile_set_name": "StackExchange" }
Q: How to Make ZURB Foundation Top-Bar Dropdown Menu 100% Width? Did some searching but only found info for the megaBar. Would like to have 100% width dropdown widths and implement it with as little css/js on top of Foundation as possible. I'd like to do a sub menu (ul > li.has-dropdown -> ul.dropdown) that is 100% window width similar to the one on Mashable and shows on hover. The Foundation megaBar is outside of the nested nav structure but that's not what I'd like for my Wordpress template (want to stay in the nested walker type menu tree). If you hover over any of the top menu links on Mashable, you'll see the dropdown submenu I'd like to copy (just the structure, not the content). I'm using Foundation 3.2 and have the <div class="contain-to-grid fixed"><nav class="top-bar"> setup so that it is fixed to the top and always 100% window width while the top-bar has a max-width: 1440px, just like the Mashable site. Now I just need the dropdown (sub menu) part sussed out. A: This will reset your top bar submenu to be 100% of your top bar's width and will organise your submenu items in responsive columns, just as a flyout content but still preserving the navigation behavior on the small screen size @media only screen and (min-width: $screenSmall) { nav.top-bar > section > ul > li.has-dropdown{ position: static; & > .dropdown{ @include outerRow(); & > li.has-dropdown{ @include column(3); min-width: auto; .dropdown{ @include outerRow(); position: static; visibility: inherit; top: auto !important; left: auto !important; padding: 0; min-width: auto; li{ @include column(12); min-width: auto; } } } } } }
{ "pile_set_name": "StackExchange" }
Q: Spring Integration - how to send POST parameters with http outbound-gateway I'm trying to put together a really simple HTTP POST example using Spring Integration and a http outbound-gateway. I need to be able to send a HTTP POST message with some POST parameters, as I would with curl: $ curl -d 'fName=Fred&sName=Bloggs' http://localhost I can get it working (without the POST parameters) if I send a simple String as the argument to the interface method, but I need to send a pojo, where each property of the pojo becomes a POST parameter. I have the following SI config: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration" xmlns:int-http="http://www.springframework.org/schema/integration/http" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd"> <int:gateway id="requestGateway" service-interface="RequestGateway" default-request-channel="requestChannel"/> <int:channel id="requestChannel"/> <int-http:outbound-gateway request-channel="requestChannel" url="http://localhost" http-method="POST" expected-response-type="java.lang.String"/> </beans> My RequestGateway interface looks like this: public interface RequestGateway { String echo(Pojo request); } My Pojo class looks like this: public class Pojo { private String fName; private String sName; public Pojo(String fName, String sName) { this.fName = fName; this.sName = sName; } .... getters and setters } And my class to kick it all off looks like this: public class HttpClientDemo { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("/si-email-context.xml"); RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class); Pojo pojo = new Pojo("Fred", "Bloggs"); String reply = requestGateway.echo(pojo); System.out.println("Replied with: " + reply); } } When I run the above, I get: org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [Pojo] and content type [application/x-java-serialized-object] I've googled a lot for this, but cannot find any examples of sending HTTP POST parameters with an outbound-gateway (I can find lots about setting HTTP Headers, but that's not what I'm trying to do here) The only thing I did find was spring-integration: how to pass post request parameters to http-outbound but it's a slightly different use case as the OP was trying to send a JSON representation of his pojo which I am not, and the answer talks about setting headers, not POST parameters. Any help with this would be very much appreciated; Thanks Nathan A: Thanks to the pointers from @jra077 regarding Content-Type, this is how I solved it. My SI config now looks like this - the important bit was adding the Content-Type header: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration" xmlns:int-http="http://www.springframework.org/schema/integration/http" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd"> <int:gateway id="requestGateway" service-interface="RequestGateway" default-request-channel="requestChannel"> <int:method name="sendConfirmationEmail"> <int:header name="Content-Type" value="application/x-www-form-urlencoded"/> </int:method> </int:gateway> <int:channel id="requestChannel"/> <int-http:outbound-gateway request-channel="requestChannel" url="http://localhost" http-method="POST" expected-response-type="java.lang.String"/> </beans> Then I changed my interface to take a Map as it's argument rather than the pojo: public interface RequestGateway { String echo(Map<String, String> request); } The pojo itself remains as before; and the class that invokes the service is changed so that it creates a Map and passes it: public class HttpClientDemo { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("/si-email-context.xml"); RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class); Pojo pojo = new Pojo("Fred", "Bloggs"); Map<String, String> requestMap = new HashMap<String, String>(); requestMap.put("fName", pojo.getFName()); requestMap.put("sName", pojo.getSName()); String reply = requestGateway.echo(requestMap); System.out.println("Replied with: " + reply); } } I'm sure there are several more elegant ways of transforming the pojo into a Map, but for the time being this answers my question. To send POST parameters with a http outbound-gateway you need to set the Content-Type to application/x-www-form-urlencoded and you need to pass a Map of key/values pairs.
{ "pile_set_name": "StackExchange" }
Q: What properties are allowed in comprehension axiom of ZFC? I am trying to understand the axioms of ZFC. The axiom schema of specification or the comprehension axioms says: If A is a set and $\phi(x)$ formalizes a property of sets then there exists a set C whose elements are the elements of A with this property. I read Is the Subset Axiom Schema in ZF necessary? and understand that ZFC axioms are defined in the language first-order logic. I do not understand the part 'phi(x) formalizes a property of sets'. If we allowed any property, e.g. $\phi(x) = x \notin x$, then we would get a Russell's paradox. But saying any property except $\phi(x) = x \notin x$ would not eliminate all the paradoxes. Thus we have to have some way to say which properties $\phi(x)$ do not make ZFC inconsistent. Is my understanding correct? What does it mean to 'formalize a property of a set'? How do we know that a property $\phi(x)$ does not make ZFC inconsistent? A: To formalize a property of a set simply means to give a formula in the language of set theory. That is $\phi(x)$ is nothing but a formula in the language. Now, for each such property of sets $\phi(x)$ there is an axiom that says that given any set $A$ the set $\{x\in A\mid \phi(x)\}$ exists. This is the axiom schema of specification. Russele's Paradox does not creep in here since you still can't form the set $\{x\mid x\notin x\}$ not since you can't formulate the property $\phi(x)=x\notin x$ (you certainly can) but simply since using the axiom schema of specification will only allow you to create such sets as $\{x\in A\mid x\notin x \}$. By the axiom of foundation this set is just $A$. A: As mentioned above, by "$\varphi(u)$ formalizes a property of sets" we just mean that $\varphi(u)$ is a formula in the language of set theory. Fortunately, virtually all of mathematics can be formalised within the language of set theory, and so as long as you stick with mathematically meaningful properties, you can use Comprehension to construct subsets of any given set. Unfortunately, Comprehension could not allow you to construct the set of all happy horses (until you have given a mathematically meaningful definition of a happy horse). The ZFC axiomatization side-steps the issue of Russell's paradoxical set (as opposed to simply outlawing its formation as was done in the Russell theory of types, and Quine's New Foundations). It is done in the following manner: Naive set theory may be thought of as essentially axiomatizaed by the Axiom Schema of Unrestricted Comprehension: For any formula $\varphi (u)$ (with no free occurrences of the variable $y$), the universal closure of $$( \exists y ) ( \forall u ) ( u \in y \leftrightarrow \varphi (u) )$$ is an instance of Unrestricted Comprehension. (We disallow free occurrences of $y$ in $\varphi (x)$ so that this new set isn't defined as the collection of all objects in some relation to this heretofore undetermined set; otherwise we could take $\varphi (x) \equiv x \notin y$, and get a different paradoxical set: $y = \{ x : x \notin y \}$.) That is, for any set theoretic property $\varphi(u)$ that you can think of, there is a set whose elements are precisely all those objects $u$ satisfying $\varphi (u)$. As an example, there is a universal set, given by taking $\varphi(u) \equiv u = u$: $$V = \{ u : u = u \}.$$ Russell's paradoxical set is given by the formula $\varphi (u) \equiv u \notin u$: $$R = \{ u : u \notin u \}.$$ ZF(C) takes the stance that we cannot use Comprehension to demonstrate the existence of inherently new sets, but only the existence of sets which are definable subsets of already given sets: For any formula $\varphi (u)$ (with no free occurrences of the variable $y$), the universal closure of $$( \forall x ) ( \exists y ) ( \forall u ) ( u \in y \leftrightarrow ( u \in x \wedge \varphi (u) ))$$ is an instance of Comprehension. Let us naively try to use Comprehension to get Russell's paradoxical set. Given any set $X$ we may form the set $$X^\prime = \{ u \in X : u \notin u \}.$$ However, if it happens that $X \notin X$, then $X \notin X^\prime$ (since $X^\prime$ only contains elements of $X$), but $X$ itself is a set which would be an element of Russell's paradoxical set $R$. So for any set $X$ which does not contain itself as an element, the associated $X^\prime$ cannot be Russell's paradoxical set. As luck would happen, another axiom of ZFC (the Axiom of Regularity) immediately implies that no set contains itself as an element, which then implies that we cannot use the Axiom of Comprehension with the formula $\varphi(u) \equiv u \notin u$ to prove the existence of Russell's paradoxical set. Note that because of Regularity under ZF(C) we have $R = V$, and it can easily be shown that ZF(C) proves that $V$ is not a set: if $V$ were a set, then by definition $V \in V$, contradicting Regularity! Of course, ZF(C) could turn out to be inconsistent, and would then prove the existence of Russell's paradoxical set (and still also disprove its existence). Life would be easier if we could determine exactly which formulas are unproblematic in applications of Comprehension (or Replacement), but life isn't always easy.
{ "pile_set_name": "StackExchange" }
Q: how to populate input type tesxt with ajax I want to know how can i populate a value of input type text with ajax. Thanks. A: By, AJAX I assume you mean JavaScript. Well, you could use something like this: <html> <head> <title>Form Example</title> <script type="text/javascript"> window.onload = function() { document.myform.mytext.value = "TEXTBOX"; } </script> </head> <body> <form name="myform" method="get"> <input type="text" name="mytext" /> </form> </body> </html> Explanation: Once the document has finished loading the script looks for the form named "myform". Then it looks for an element named "mytext" inside this form and you can then set/change the value property to what you desire.
{ "pile_set_name": "StackExchange" }
Q: Collections.shuffle only working once I checked a previous answer but it didn't work for me. I have the following code public static void createPopulation(ArrayList<City> city) { for (int i = 0; i<gen.getSize(); i++) { ArrayList<City> copy = new ArrayList<City> (city); //added from previous question Collections.shuffle(copy, new Random(seed)); gen.add(copy); } } It shuffles once, with or without the line with the comment on it, but doesn't shuffle again. It's a GP algorithim (well, the start of it) where I have to shuffle the members of a population. A: That's because you recreate the Random object. Do this : Random r = new Random(seed); for (int i = 0; i<gen.getSize(); i++) { ArrayList<City> copy = new ArrayList<City> (city); //added from previous question Collections.shuffle(copy, r); gen.add(copy); } From the javadoc : If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. An instance of Random is a generator whose state is changed each time you call a random function on it. Here you don't want to reset this state to the initial seed based one, because that would lead to the same sequence of returned numbers. That's why you don't want to recreate a new instance for each shuffling.
{ "pile_set_name": "StackExchange" }
Q: Avoiding race conditions in Python 3's multiprocessing Queues I'm trying to find the maximum weight of about 6.1 billion (custom) items and I would like to do this with parallel processing. For my particular application there are better algorithms that don't require my iterating over 6.1 billion items, but the textbook that explains them is over my head and my boss wants this done in 4 days. I figured I have a better shot with my company's fancy server and parallel processing. However, everything I know about parallel processing comes from reading the Python documentation. Which is to say I'm pretty lost... My current theory is to set up a feeder process, an input queue, a whole bunch (say, 30) of worker processes, and an output queue (finding the maximum element in the output queue will be trivial). What I don't understand is how the feeder process can tell the worker processes when to stop waiting for items to come through the input queue. I had thought about using multiprocessing.Pool.map_async on my iterable of 6.1E9 items, but it takes nearly 10 minutes just to iterate through the items without doing anything to them. Unless I'm misunderstanding something..., having map_async iterate through them to assign them to processes could be done while the processes begin their work. (Pool also provides imap but the documentation says it's similar to map, which doesn't appear to work asynchronously. I want asynchronous, right?) Related questions: Do I want to use concurrent.futures instead of multiprocessing? I couldn't be the first person to implement a two-queue system (that's exactly how the lines at every deli in America work...) so is there a more Pythonic/built-in way to do this? Here's a skeleton of what I'm trying to do. See the comment block in the middle. import multiprocessing as mp import queue def faucet(items, bathtub): """Fill bathtub, a process-safe queue, with 6.1e9 items""" for item in items: bathtub.put(item) bathtub.close() def drain_filter(bathtub, drain): """Put maximal item from bathtub into drain. Bathtub and drain are process-safe queues. """ max_weight = 0 max_item = None while True: try: current_item = bathtub.get() # The following line three lines are the ones that I can't # quite figure out how to trigger without a race condition. # What I would love is to trigger them AFTER faucet calls # bathtub.close and the bathtub queue is empty. except queue.Empty: drain.put((max_weight, max_item)) return else: bathtub.task_done() if not item.is_relevant(): continue current_weight = item.weight if current_weight > max_weight: max_weight = current_weight max_item = current_item def parallel_max(items, nprocs=30): """The elements of items should have a method `is_relevant` and an attribute `weight`. `items` itself is an immutable iterator object. """ bathtub_q = mp.JoinableQueue() drain_q = mp.Queue() faucet_proc = mp.Process(target=faucet, args=(items, bathtub_q)) worker_procs = mp.Pool(processes=nprocs) faucet_proc.start() worker_procs.apply_async(drain_filter, bathtub_q, drain_q) finalists = [] for i in range(nprocs): finalists.append(drain_q.get()) return max(finalists) HERE'S THE ANSWER I found a very thorough answer to my question, and a gentle introduction to multitasking from Python Foundation communications director Doug Hellman. What I wanted was the "poison pill" pattern. Check it out here: http://www.doughellmann.com/PyMOTW/multiprocessing/communication.html Props to @MRAB for posting the kernel of that concept. A: You could put a special terminating item, such as None, into the queue. When a worker sees it, it can put it back for the other workers to see, and then terminate. Alternatively, you could put one special terminating item per worker into the queue.
{ "pile_set_name": "StackExchange" }
Q: Сохранение данных из запроса в Redux хранилище необходимо получить информацию запросом (готово при помощи Axios) и сохранить её в Redux хранилище для дальнейшего использования в разных компонентах, как это сделать? Где правильно разместить функцию с запросом и как передать результат в хранилище? Может у кого то есть гайд или пример кода? О приложении, это простой калькулятор криптовалют, а также система для постоянного мониторинга той же криптовалюты и отрисовки графика изменений курса. A: Можешь попробовать миделвер Redux-Thunk https://github.com/reduxjs/redux-thunk он дает возможность работать с промисами, и довольно легкий в понимании import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; // добавляешь мидлевар const store = createStore(rootReducer, applyMiddleware(thunk)); экшены: export const fetchSomething = (someData) => { return dispatch => axios.get(url, someData).then(response => { dispatch({ type: 'SOME_TYPE', payload: response.data }); }); } и передаешь экшен в компонент const mapDispatchToProps = { fetchSomething, } export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent);
{ "pile_set_name": "StackExchange" }
Q: django DEBUG=False still runs in debug mode I'm having issues setting my DEBUG = False on my deployed server (on heroku). I don't believe I've seen this before, but setting debug to false is not getting rid of debug mode for my project. This means that when there are 500 errors it shows the error, and 404 errors are showing all my urls. What's strange is that when i log into the server and run get the setting value from django.conf import settings settings.DEBUG it shows as False, which is what I set it to for the production server. TEMPLATE_DEBUG is also set to False. I don't know I've ever seen this before where DEBUG = False but it's still acting in debug mode. Any ideas? EDIT: Thought I'd put this little note too because it's very common for people to be getting 500 or 400 errors when switching debug to False. I am not getting any errors, my project is just acting like it's in DEBUG mode. # settings/dev.py from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG if not DEBUG: ALLOWED_HOSTS = ['localhost'] SECRET_KEY = 'localsecret1234123412341234' # settings/prod.py from .base import * import dj_database_url, os DEBUG = os.environ.get("DEBUG", False) TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ['mydomain.com'] SECRET_KEY = os.environ["DJANGO_SECRET_KEY"] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') DATABASES = {} DATABASES['default'] = dj_database_url.config() A: The root cause of issue - False translated to 'False' string not bool. Used next solution (settings.py): DEBUG = os.getenv('DEBUG', False) == 'True' i.e.: in this case DEBUG will set to (bool) True, only if the environment variable is explicitly set to True or 'True'. Good luck configuring! :) A: As a note for others: I had the same problem; I configured my production website on a VM with gunicorn and nginx, following the tutorial for ubuntu 16.04 from the digital ocean documentation. I wasn't able to turn off the debug mode, even when restarting the nginx systemd's service: the solution was to restart also the gunicorn service: # systemctl restart nginx gunicorn A: This ended up being an issue with the config variable being "False" instead of False, and so debug wasn't properly set to the boolean value. Shoutout to @WithNail for helping get to the answer
{ "pile_set_name": "StackExchange" }
Q: setting the NR to 1 does not work (awk) I have the following script in bash. awk -F ":" '{if($1 ~ "^fall") { NR==1 {{printf "\t<course id=\"%s\">\n",$1} } } }' file1.txt > container.xml So what I have a small file. If ANY line starts with fall, then I want the first field of the VERY first line. So I did that in the code and set NR==1. However, it does not do the job!!! A: Try this: awk -F: 'NR==1 {id=$1} $1~/^fall/ {printf "\t<course id=\"%s\">\n",id}' file1.txt > container.xml Notes: NR==1 {id=$1} This saves the course ID from the first line $1~/^fall/ {printf "\t<course id=\"%s\">\n",id} If any line begins with fall, then the course ID is printed. The above code illustrates that awk commands can be preceded by conditions. Thus, id=$1 is executed only if we are on the first line: NR==1. If this way, it is often unnecessary to have explicit if statements. In awk, assignment with done with = while tests for equality are done with ==. If this doesn't do what you want, then please add sample input and corresponding desired output to the question.
{ "pile_set_name": "StackExchange" }
Q: What are the largest Technic-compatible tires on the market? I am looking for the largest LEGO wheels with tires available to build a nice-sized RC LEGO car. Of course I will start with the simplest prototype, but I would like to achieve a design which will embed an automatic gear box and quite a large propulsion system. So the size of the wheels will be important. Edit: The "Wheel 81.6x15" 2903 @Pubby8 found seem to be the biggest. But they are thin... Are there any other larger ones? Even 3rd party would be good. Edit: @Joubarc & @Pubby8 found the biggest wheels but without tires I am still looking for 3rd party solutions before accepting an answer. A: The largest wheels I know are these (I measured 110x63 mm, including tyres), but they are quite rare (only available in one single set): Weels: 22969 "Wheel Technic Racing" Tyres: 32298 "Tyre Power Puller" The wheels itself are not that big, but if you include the tyres, they are really huge: They would probably work really well for an RC car. A: The largest wheels I've seen are "Wheel 81.6x15" 2903 To show scale: There are larger ones on the Hailfire Droid but these probably aren't good for your needs: A: An alternative is the 94.8x44 balloon tires. While they are not as big as the ones elusive suggested, I imagine they are easier to get as they have been in some recent sets. Comparison: Left: 81.6x15 Middle: 94.8x44 balloon Right: 81.6x38 balloon
{ "pile_set_name": "StackExchange" }
Q: Resolve container name in extra_hosts option in docker-compose I need to curl my API from another container. Container 1 is called nginx Container 2 is called fpm I need to by able to bash into my FPM container and curl the nginx container. Config: services: nginx: build: context: . dockerfile: ./docker/nginx/Dockerfile volumes: - ./docker/nginx/conf/dev/api.conf:/etc/nginx/conf.d/default.conf ports: - 8080:80 links: - fpm fpm: build: context: . dockerfile: ./docker/fpm/Dockerfile volumes: - .:/var/www/html - ./docker/fpm/conf/dev/xdebug.ini:/usr/local/etc/php/conf.d/xdebug.ini - ./docker/fpm/conf/dev/api.ini:/usr/local/etc/php/conf.d/api.ini env_file: - ./docker/mysql/mysql.env - ./docker/fpm/conf/dev/fpm.env links: - mysql shm_size: 256M extra_hosts: - myapi.docker:nginx My initial thought was to slap it in the extra_hosts option like: extra_hosts: - myapi.docker:nginx But docker-compose up fails with: ERROR: for apiwip_fpm_1 Cannot create container for service fpm: invalid IP address in add-host: "nginx" I have seen some examples of people using docker's network configuration but it seems over the top to just resolve an address. How can I resolve/eval the IP address of the container rather than just passing it literally? A: I solved this kind of issue by using links instead of extra_hosts. In that case, just set link alias can do your favor. service fpm setting links - nginx:myapi.docker See docker-compose links documentation, The alias name can be the domain which appears in your code. A: Add network aliases in the default network. version: "3.7" services: nginx: # ... networks: default: aliases: - example.local browser-sync: # ... depends_on: - nginx command: "browser-sync start --proxy http://example.local" A: services: nginx: build: context: . dockerfile: ./docker/nginx/Dockerfile volumes: - ./docker/nginx/conf/dev/api.conf:/etc/nginx/conf.d/default.conf ports: - 8080:80 networks: my_network: aliases: - myapi.docker - docker_my_network fpm: build: context: . dockerfile: ./docker/fpm/Dockerfile volumes: - .:/var/www/html - ./docker/fpm/conf/dev/xdebug.ini:/usr/local/etc/php/conf.d/xdebug.ini - ./docker/fpm/conf/dev/api.ini:/usr/local/etc/php/conf.d/api.ini env_file: - ./docker/mysql/mysql.env - ./docker/fpm/conf/dev/fpm.env links: - mysql shm_size: 256M networks: - my_network networks: my_network: driver: bridge add custom network and add container to that network by default if you curl nginx container from fpm you will curl localhost, so we need to add alias to be the same as your servername in the nginx configuration with this solution you can curl myapi.docker from the fpm container @edward let me know if this solution worked for you Edit: Jack_Hu is right, I removed extra_hosts. Network alias is enough.
{ "pile_set_name": "StackExchange" }
Q: How to sort an array given a range? First of all I am using java and my first objective is to use bubble sort to sort an array in descending order given the range lowindex..highindex (inclusive). So my question is how to sort an array given a range? An example would be greatly appreciated to get me started on doing this. A: That wheel has already been invented: Arrays.sort(array, lowIndex, highIndex + 1); See doc.
{ "pile_set_name": "StackExchange" }
Q: Lookup exchanged data between PHP and Flash I'ld like to see the data that is exchanged between a Flash based web app and PHP. What is the tool of choice for that? A: Fiddler is a great tool for sniffing HTTP requests. You can download it here. Also, Google Chrome's Developer section (shortcut : ctrl + shift + j) has a Network Tab, which gives you info about time and http request. It is not as detailed as fiddler though!
{ "pile_set_name": "StackExchange" }
Q: Matchmaking program in C? The problem I am given is the following: Write a program to discover the answer to this puzzle:"Let's say men and women are paid equally (from the same uniform distribution). If women date randomly and marry the first man with a higher salary, what fraction of the population will get married?" From this site My issue is that it seems that the percent married figure I am getting is wrong. Another poster asked this same question on the programmers exchange before, and the percentage getting married should be ~68%. However, I am getting closer to 75% (with a lot of variance). If anyone can take a look and let me know where I went wrong, I would be very grateful. I realize, looking at the other question that was on the programmers exchange, that this is not the most efficient way to solve the problem. However, I would like to solve the problem in this manner before using more efficient approaches. My code is below, the bulk of the problem is "solved" in the test function: #include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define ARRAY_SIZE 100 #define MARRIED 1 #define SINGLE 0 #define MAX_SALARY 1000000 bool arrayContains(int* array, int val); int test(); int main() { printf("Trial count: "); int trials = GetInt(); int sum = 0; for(int i = 0; i < trials; i++) { sum += test(); } int average = (sum/trials) * 100; printf("Approximately %d %% of the population will get married\n", average / ARRAY_SIZE); } int test() { srand(time(NULL)); int femArray[ARRAY_SIZE][2]; int maleArray[ARRAY_SIZE][2]; // load up random numbers for (int i = 0; i < ARRAY_SIZE; i++) { femArray[i][0] = (rand() % MAX_SALARY); femArray[i][1] = SINGLE; maleArray[i][0] = (rand() % MAX_SALARY); maleArray[i][1] = SINGLE; } srand(time(NULL)); int singleFemales = 0; for (int k = 0; k < ARRAY_SIZE; k++) { int searches = 0; // count the unsuccessful matches int checkedMates[ARRAY_SIZE] = {[0 ... ARRAY_SIZE - 1] = ARRAY_SIZE + 1}; while(true) { // ARRAY_SIZE - k is number of available people, subtract searches for people left // checked all possible mates if(((ARRAY_SIZE - k) - searches) == 0) { singleFemales++; break; } int randMale = rand() % ARRAY_SIZE; // find a random male while(arrayContains(checkedMates, randMale)) // ensure that the male was not checked earlier { randMale = rand() % ARRAY_SIZE; } checkedMates[searches] = randMale; // male has a greater income and is single if((femArray[k][0] < maleArray[randMale][0]) && (maleArray[randMale][1] == SINGLE)) { femArray[k][1] = MARRIED; maleArray[randMale][1] = MARRIED; break; } else { searches++; continue; } } } return ARRAY_SIZE - singleFemales; } bool arrayContains(int* array, int val) { for(int i = 0; i < ARRAY_SIZE; i++) { if (array[i] == val) return true; } return false; } A: In the first place, there is some ambiguity in the problem as to what it means for the women to "date randomly". There are at least two plausible interpretations: You cycle through the unmarried women, with each one randomly drawing one of the unmarried men and deciding, based on salary, whether to marry. On each pass through the available women, this probably results in some available men being dated by multiple women, and others being dated by none. You divide each trial into rounds. In each round, you randomly shuffle the unmarried men among the unmarried women, so that each unmarried man dates exactly one unmarried woman. In either case, you must repeat the matching until there are no more matches possible, which occurs when the maximum salary among eligible men is less than or equal to the minimum salary among eligible women. In my tests, the two interpretations produced slightly different statistics: about 69.5% married using interpretation 1, and about 67.6% using interpretation 2. 100 trials of 100 potential couples each was enough to produce fairly low variance between runs. In the common (non-statistical) sense of the term, for example, the results from one set of 10 runs varied between 67.13% and 68.27%. You appear not to take either of those interpretations, however. If I'm reading your code correctly, you go through the women exactly once, and for each one you keep drawing random men until either you find one that that woman can marry or you have tested every one. It should be clear that this yields a greater chance for women early in the list to be married, and that order-based bias will at minimum increase the variance of your results. I find it plausible that it also exerts a net bias toward more marriages, but I don't have a good argument in support. Additionally, as I wrote in comments, you introduce some bias through the way you select random integers. The rand() function returns an int between 0 and RAND_MAX, inclusive, for RAND_MAX + 1 possible values. For the sake of argument, let's suppose those values are uniformly distributed over that range. If you use the % operator to shrink the range of the result to N possible values, then that result is still uniformly distributed only if N evenly divides RAND_MAX + 1, because otherwise more rand() results map to some values than map to others. In fact, this applies to any strictly mathematical transformation you might think of to narrow the range of the rand() results. For the salaries, I don't see why you even bother to map them to a restricted range. RAND_MAX is as good a maximum salary as any other; the statistics gleaned from the simulation don't depend on the range of salaries; but only on their uniform distribution. For selecting random indices into your arrays, however, either for drawing men or for shuffling, you do need a restricted range, so you do need to take care. The best way to reduce bias in this case is to force the random numbers drawn to come from a range that is evenly divisible by the number of options by re-drawing as many times as necessary to ensure it: /* * Returns a random `int` in the half-open interval [0, upper_bound). * upper_bound must be positive, and should not exceed RAND_MAX + 1. */ int random_draw(int upper_bound) { /* integer division truncates the remainder: */ int rand_bound = (RAND_MAX / upper_bound) * upper_bound; for (;;) { int r = rand(); if (r < rand_bound) { return r % upper_bound; } } }
{ "pile_set_name": "StackExchange" }
Q: .HTACCESS RewriteRule force default page to HTTP I did a lot of searching on this, and just couldn't quite find the right answer. A lot of things got me close, but nothing worked like I wanted it to. I'm working on a site where, because of an external JQuery add-on library, I need to force certain pages to be HTTP. Certain other pages (for shopping, etc) need to be HTTPS. So far in my .HTACCESS file I have: RewriteCond %{SERVER_PORT} !^80$ RewriteRule ^(index|event)\.php$ http://www.example.com%{REQUEST_URI} [R=301,L] This works perfectly when the user goes to https://www.example.com/index.php But doesn't redirect when they go to https://www.example.com/ Any suggestions on how to catch that last instance? Thank you in advance! A: To match landing page tweak your regex to match empty URI also like this: RewriteCond %{SERVER_PORT} !^80$ RewriteRule ^((index|event)\.php)?$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC,NE]
{ "pile_set_name": "StackExchange" }
Q: Controlling multiple pointers with Xlib or xinput in ubuntu/linux I'm creating a system that uses multiple cursors (pointers) in multiple xsessions. My computer has multiple video cards in it for controlling different monitors. I want to have a different cursor on each screen and control each. Each monitor is a different session. I started using the xlib library in C to control the single cursor I have using the following command: XWarpPointer(display,None,window,0,0,0,0,x,y); This works perfectly for one cursor. Then I created a second cursor using xinput in the terminal: >>xinput create-master second and then I have two cursors on screen. I can go and control each with a separate mouse by using the reattach command: >>xinput reattach MOUSEID POINTERID The last step is to control each cursor separately using xlib. When I use the xWarpPointer command it just moves the original cursor around and I can't find a way to designate which cursor to control. I have also been unable to find a way to set the default pointer. You can see a list of all the pointers using "xinput list" in terminal. Does anyone know how I can Thanks for the help! A: You need to use XIWarpPointer request from XInput2 extension, it takes deviceid as parameter Bool XIWarpPointer( Display* display, int deviceid, Window src_win, Window dst_win, double src_x, double src_y, unsigned int src_width, unsigned int src_height, double dst_x, double dst_y );
{ "pile_set_name": "StackExchange" }
Q: Fermat's proof for $x^3-y^2=2$ Fermat proved that $x^3-y^2=2$ has only one solution $(x,y)=(3,5)$. After some search,i found only proofs using factorization over the ring $Z[\sqrt{-2}]$. My question is: Is this Fermat's original proof?If not where can i find it? Thank you for viewing Note: I am not expecting to find Fermat's handwritings because this may not exist. I was hoping to find a proof that would look more ''Fermatian'' A: Fermat never gave a proof, only announced he had one (sounds familiar?). Euler did give a proof, which was flawed, see Franz Lemmermeyer's lecture notes, or see page 4 of David Cox's introduction. For a discussion why a proof along the lines set out by Fermat is unlikely to work, see this MO posting. ---- trivia ---- As a curiosity, I looked up Fermat's original text (reproduced below from his collected works), written in the margin of the Arithmetica of Diophantus: Can one find in whole numbers a square different from 25 that, when increased by 2, becomes a cube? This would seem at first to be difficult to discuss; and yet, I can proof by a rigorous demonstration that 25 is the only integer square that is less than a cube by two units. For rationals, the method of Bachet would provide an infinity of such squares, but the theory of integer numbers, which is very beautiful and subtle, was not known previously, neither by Bachet, nor by any author whose work I have read. A: Fermat did not prove this result; he claimed that the only solution is the obvious one and conjectured (in words that seem to suggest he knew how to prove it, but without explicitly saying so) that this can be proved by descent. I am sure that Fermat, if he really believed to have a proof (in my opinion he did not), was mistaken. I am not aware of any proofs based on Fermat's techniques alone, and I have often tried to find one myself - so far without success.
{ "pile_set_name": "StackExchange" }
Q: How should I handle total freeze upon launching iPhone simulator? I updated Xcode (11.4.1) this afternoon and noticed the new iPhone SE 2 simulator option. Cool! My iOS app was running fine on my physical device and all simulator before this update, but now when I launch the simulator, it freezes my MBP (2019 16", Catalina 10.15.4) while attempting to run. I can still move the mouse, but nothing else responds, and I'm forced to do a hard reset. Anyone else having this issue? Any suggestions on how to approach fixing this? I don't particularly want to keep trying it, only to repeatedly force reset my Mac. A: Turned out this was a pretty fundamental hardware issue related to the graphics card with new 16" MBP. Not sure how many machines are affected, but it's easy enough to find threads and forums with owners discussing this issue. I met with a Mac technician at an Apple store and fortunately, she had seen the issue and immediately agreed to replace the machine. The new machine they gave me has also had a handful of kernel panics, but of a different sort, and they seem to have stopped suddenly after a few days of use. Keeping Apple on speed dial though if more issues arise.
{ "pile_set_name": "StackExchange" }
Q: I need jquery UI auto complete source from mysql database I create auto complete but its source coming from javascript, now i want to get source from mysql database using php language.Below is my script, Please help me <SCRIPT language="javascript"> $(document).ready(function() { $("input#autocomplete").autocomplete({ source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] }); }); </SCRIPT> A: Hope this helps, this is an example i made using php and mysql, you can download it from here: http://dl.dropbox.com/u/15208254/trickylearning/examples/autocomplete/autocomplete-php.zip Than main idea of this example is to have something with this structure in your db: id: 1 / tag_column: jeans, jackets, shoes id: 2 / tag_column: kfc, burger king, pizza hut And the final result will split everything from db and look like this: Regards.
{ "pile_set_name": "StackExchange" }
Q: How to loop over array of hashes and remove a hash where a key has a specific value? I'm trying to loop over an array of hashes containing a set of keys and values, in this loop I want to check whether any key (or a set of specific keys, whatever that is most simple) has a certain value. This is what I've got so far, but it doesn't work as the hashes containing a key with the value dollar is still present within the array: remove_currency = [{a: 'fruit', b: 'dollar'}, {a: 'fruit', b: 'yen'}] currency = 'dollar' remove_currency.delete_if { |_, v| v == currency } Hope I made myself clear enough! A: things = [{foo: 3, bar: 42}, {baz: 5, quiz: 3.14}] things.reject { |thing| thing.values.include? 42 } # => [{:baz=>5, :quiz=>3.14}]
{ "pile_set_name": "StackExchange" }
Q: Oracle Java - Add optional date parameter to Prepared statement I want to add optional "todate" parameter to Prepared statement One way is to add a placeholder for optional parameter(s) and replace it before execute where id=? OPTIONAL_SECTION For example OPTIONAL_SECTION will be set to TO_DATE <=sysdate -1 A better and correct way is to bind optional parameter with handling null where id=? and TO_DATE <= nvl(?, TO_DATE) Is there a better way to handle optional date parameter? Specially because condition can be without equal ( TO_DATE < ?) This is a minimal example, Id isn't a primary key (actually it's a foreign key), SQL return multiple records  A: The first decision for a query with an optional parameter is as follows: 1) is it accepatable to use one statement for both / all options 2) it is prefered to use a separate statament for each option In your case you have two parameter options: id id and date_parameter From the naming, I'd argue, that ID is a primary key of the table, so it returns one row only and will be the driver in the execution plan - simple index access. The date_parameter could only cause that the query return optionally no row In this case you may safely use the decision 1) - one query for both option will be fine But in other interpretation, the ID is a foreign key with tons of rows and the date_parameter is used to return only a small number of recent rows. In this case the decision 1) aka OR query will fail badly. The execution plan is optimized on the case returning mass data, so you will wait ages to get few rows. So in this case only decision 2) provides a performant solution. The short answer is to dynamically generate two queries based on the parameter passed where id=? where id=? and data_parameter <= ? The technical problem with this approach is, that the queries have a different number of bind variables which makes the setXXX complicated. To avoid this problem you can use the 1=1 or trick, that a) makes the number of the bind variable equal in all queries* and b) eliminates the not necessary onces. Query for ID only is generated as where id=? and 1=1 or data_parameter <= ? Query with IDand DATE_PARAM remains the same where id=? and data_parameter <= ? Some more examples and credit for popularizing this approach can be foud here and there
{ "pile_set_name": "StackExchange" }
Q: Use JetBrains Toolbox to get Early Access versions I am using the Jetbrains Toolbox tool to auto-install updates to IntelliJ IDE. This works well for regular releases. But how do I use this tool to obtain an Early Access pre-release? I see a hexagon-shape icon that displays a menu. But the menu items there say nothing about skipping ahead to a pre-release. The items there are only Settings, Roll back to…, and Uninstall. I checked the Settings display, but no options there to enroll in the Early Access program. A: Redundant product listing Scroll down to the item at the bottom that redundantly lists your licensed product, IntelliJ IDEA Ultimate. Click the Install Again pop-up menu. Choose the pre-release version you want. After download completes, you will see another product listing at the top of the app list.
{ "pile_set_name": "StackExchange" }
Q: Select Values While Sum I have a table with a date and an integer value. I want to sort the table by the date and pick the top n rows until the integer values sum up to 12 or more. A: You can use a cumulative sum: select t.* from (select t.*, sum(val) over (order by date) as sum_val from t ) t where sum_val - val < 12 order by date
{ "pile_set_name": "StackExchange" }
Q: PostgreSQL: How to differentiate stored procedures and table-valued functions? Question: In Microsoft SQL Server, there are stored procedures, and there are table-valued functions. The difference is, from a stored procedure, I cannot do further selects, while from a table-valued function, I can. e.g. SELECT * FROM sp_whatever WHERE xxx is illegal while SELECT * FROM TVF_whatever WHERE xxx is perfectly legal Now my question: In PostgreSQL, when I look at information_schema.routines, how can I differentiate table valued functions, and procedures ? Is there a difference at all ? And in general, how can I differentiate functions and procedures in PostgreSQL? I mean theoretically, on SQL-server, one can differentiate them like this: Table valued function: information_schema.data_type = 'table' stored procedures: information_schema.data_type IS NULL functions: information_schema.data_type != 'table' AND information_schema.data_type IS NOT NULL How is this done in Postgres? Theoretically, a stored procedure has return type void, but since a stored procedure can also return a table, there is no way to differentiate between tvf and stored precedure - assuming there is a difference. So my question could also be formulated: In PostGreSQL, how do I create a table-valued function, and how do I create a stored procedure (1 example each). I'm interested in the difference in the return type between the two, if there is any. A: PostgreSQL doesn't have real stored procedures, just user defined functions: CREATE FUNCTION foo() RETURNS TABLE(bar INT, baz TEXT) ... CREATE FUNCTION bar() RETURNS BOOLEAN ... Check for datatype "record": SELECT * FROM information_schema.routines WHERE data_type = 'record';
{ "pile_set_name": "StackExchange" }
Q: Convert column of strings representing variously formatted dates into a column of dates I'm looking for an efficient way to convert a column of strings in a data table into a column of dates with the proviso that the strings may be in one of three date formats -- number, %Y-%m-%d, %m/%d/%Y. The following illustrates how a hypothetical function datefun would behave: library(data.table) dt <- data.table( my_dates = c('42292.7894','2014-06-22','11/25/2011','33661', NA)) datefun(dt$my_dates) [1] "2015-10-15" "2014-06-22" "2011-11-25" "1992-02-27" NA which would be the same as applying as.Date to each string with knowledge of the format of that string. l <- dt$my_dates c( as.Date(as.numeric(l[1]), origin = "1899-12-30"), as.Date(l[2],'%Y-%m-%d'), as.Date(l[3],'%m/%d/%Y'), as.Date(as.numeric(l[4]), origin = "1899-12-30"), as.Date(l[5])) [1] "2015-10-15" "2014-06-22" "2011-11-25" "1992-02-27" NA I'm attempting to read data directly from excel which has not been formatted consistently. A: lubridate is handy for this. I think the other questions on this topic don't explicitly handle decimal days since origin, so here goes: library(lubridate) d <- parse_date_time(l, c('%Y-%m-%d', '%m/%d/%Y')) d[is.na(d)] <- (ymd_hms("1899-12-30 00:00:00") + as.numeric(l) * 3600 * 24)[is.na(d] d ## [1] "2015-10-15 18:56:44 UTC" "2014-06-22 00:00:00 UTC" "2011-11-25 00:00:00 UTC" ## [4] "1992-02-27 00:00:00 UTC" NA This assumes that any elements of l that are coercible to numeric are in the decimal days since origin format (with a consistent origin).
{ "pile_set_name": "StackExchange" }
Q: How to get the index of the element by class that is clicked I have this code: <button class="remove" value="1" /> <button class="remove" value="2" /> <button class="remove" value="3" /> $(document).on('click', ".remove", function(e) { alert($(this).index()); }); It is always alerting 0. If the user clicked the button that has a value of 2, it must alert 1 but in my code it alerts 0. A: depending on what you want to finally achieve and assuming that: <button class="remove" value="34" data-myval="a"/> <button class="remove" value="33" data-myval="b"/> <button class="remove" value="32" data-myval="c"/> if you want to get the value of 'value': $(document).on('click', ".remove", function(e) { alert($(this).val()); }); if you want to get the index of what was clicked: $(document).on('click', ".remove", function(e) { alert($(this).index()); }); if you want to get a custom value: $(document).on('click', ".remove", function(e) { alert($(this).data('myval')); });
{ "pile_set_name": "StackExchange" }
Q: Does Flask-Login not support roles? If not, are there any projects that have added this feature to Flask-Login? Otherwise, it appears to be a bit daunting to migrate from Flask-Login to Flask-User. Otherwise, is there any sort of direction out there for migrating from Flask-Login to Flask-User? A: Again, answering my own question here for anyone else curious how you can add the feature of handling multiple roles while still using Flask-Login. I created the below decorator which just checks the current_user.role to see if it is "Admin". You should also check the same thing when letting the user log in, depending on if they are logging in to the admin or the user panel. from functools import wraps def admin_required(f): @wraps(f) def wrap(*args, **kwargs): if current_user.role == "Admin": return f(*args, **kwargs) else: flash("You need to be an admin to view this page.") return redirect(url_for('index')) return wrap
{ "pile_set_name": "StackExchange" }
Q: Boolean coding for date class Date { private int day; private int month; private int year; public Date() { } public Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public int getDay() { return this.day; } public int getMonth() { return this.month; } public int getYear() { return this.year; } public void setDay(int day) { day = enteredDay; } public void setMonth(int month) { month = enteredMonth; } public void setYear(int year) { year = enteredYear; } public String toString() { return getDay() + "/" + getMonth() + "/" + getYear(); } public boolean isEarlier(Date) { if (enteredDay.getDay() < day) { return true; } else { return false; } } } I'm having trouble getting the last method to work. It must be boolean and return true if a date is earlier than it. My problem (at least as far as I know) is figuring out what to write either side of the '<' operator. Any feedback on the rest of the code would be greatly appreciated. A: I'd go over the year, month, and day and compare each in turn until you find a pair that's strictly earlier or later. Using a Comparator, especially in Java 8's neat syntax, could save you a lot of boilerplate code here: public boolean isEarlier(Date other) { return Comparator.comparingInt(Date::getYear) .thenComparingInt(Date::getMoth) .thenComparingInt(Date::getDay) .compare(this, other) < 0; } EDIT: To answer the question in the comments, you can of course manually compare each field: public boolean isEarlier(Date other) { if (getYear() < other.getYear()) { return true; } else if (getYear() > other.getYear()) { return false; } // If we reached here, both dates' years are equal if (getMonth() < other.getMonth()) { return true; } else if (getMonth() > other.getMonth()) { return false; } // If we reached here, both dates' years and months are equal return getDay() < other.getDay(); } This of course could be compacted to a single boolean statement, although whether it's more elegant or less elegant is somewhat in the eye of the beholder (the parenthesis aren't strictly needed, but IMHO they make the code clearer): public boolean isEarlier(Date other) { return (getYear() < other.getYear()) || (getYear() == other.getYear() && getMonth() < other.getMonth()) || (getYear() == other.getYear() && getMonth() == other.getMonth() && getDay() < other.getDay()); } A: If you don't want to use any other libraries, try this: public boolean isEarlier(Date date) { if (this.getYear() < date.getYear()) { return true; } else if (getYear() == date.getYear() && this.getMonth() < date.getMonth()) { return true; } else if (getYear() == date.getYear() && this.getMonth() == date.getMonth() && this.getDay() < date.getDay()) { return true; } return false; }
{ "pile_set_name": "StackExchange" }
Q: self referencing generic with inheritence I have a class AnimalQueue which is a queue of Animals. Each queue will only store a certain type of Animal, and I want to make sure that only Animals that match the type of the queue are added to it: Public Class AnimalQueue(Of T As Animal) Public Sub Add(pA As T) End Sub End Class When an Animal in the queue is processed, I want to pass the queue that is processing it to the Animal in case the Animal wants to add another Animal to the same queue: Public MustInherit Class Animal Public MustOverride Sub Process(Of T As Animal)(pAQ As AnimalQueue(Of T)) End Class The problem is that when I add a concrete class I get a compile error at the call to Add: Public Class Horse Inherits Animal Public Overrides Sub Process(Of T As Animal)(pAQ As AnimalQueue(Of T)) pAQ.Add(New Horse()) End Sub End Class It says Horse can't be converted to T, but the constraint says that T is an Animal and Horse is an Animal... A: The problem is that T might be any class that is derived from animal. Assume the following class hierarchy: Horse -> Animal Dog -> Animal In your code, the generic parameter T of Process is constrained to be any animal. So even if you implement it on the Horse class, the following call would be perfectly valid: Dim dogQ As New AnimalQueue(Of Dog)() Dim h As New Horse() h.Process(Of Dog)(dogQ) In this case, your implementation of Process would try to add a Horse to a queue of Dogs. As Horse is not derived from Dog, you cannot do this. I assume that you want to create a method so that the Process method of Horse only accepts a queue of Horses and the Process method of Dog only accepts a queue of Dogs. There are several ways to accomplish this: Do not create a generic Process method on the level of the base class, but only Process methods on the level of the children (e.g. for Horse: Public Sub Process(horseQ As AnimalQueue(Of Horse))). Use a New constraint and implement the method on the level of Animal. In your comments, you mention that your animals need constructor parameters, so this is not an option. If you want to have a base class that defines the generic method, you could create the following structure: Public Class AnimalQueue(Of T As Animal) Public Sub Add(animal As T) ' ... End Sub End Class Public MustInherit Class Animal End Class Public MustInherit Class ProcessableAnimal(Of T As Animal) Inherits Animal Public MustOverride Sub Process(q As AnimalQueue(Of T)) End Class Public Class Horse Inherits ProcessableAnimal(Of Horse) Public Overrides Sub Process(q As AnimalQueue(Of Horse)) q.Add(New Horse()) End Sub End Class Public Class Dog Inherits ProcessableAnimal(Of Dog) Public Overrides Sub Process(q As AnimalQueue(Of Dog)) q.Add(New Dog()) End Sub End Class In this approach, there is a new level of inheritance. But the significant change is that you set the generic type parameter on class level. So the decision is made when deriving from ProcessableAninmal and is not left to the caller of Process. Dim h As New Horse() Dim hQ As New AnimalQueue(Of Horse)() Dim dQ As New AnimalQueue(Of Dog)() h.Process(hQ) ' Valid h.Process(dQ) ' NOT VALID ANYMORE
{ "pile_set_name": "StackExchange" }
Q: swipes are not getting detected In the below posted code, I am trying to detect swipes using onDown and onFling but when I run the App, nothing appears. I expected to see output coming from onFling when I hold touching the screen and drag my finger across it quickly, but i received nothing. Also, I expected to see the output coming from onDown when I press on the screen, but as well, nothing showed up. please let me know what I am missing Or I misundersatnd the functionalities of onFling on onDown?! JavaCode: super.onCreate(savedInstanceState); setContentView(R.layout.swipe_gesture_activivty); mGestureDetector = new GestureDetector(getApplicationContext(), new MySwipeGestureDetector()); mViewGestureDetector = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return mGestureDetector.onTouchEvent(event); } }; final TextView view = (TextView) findViewById(R.id.accXLabel); } private class MySwipeGestureDetector extends SimpleOnGestureListener implements OnTouchListener { @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "onDown", Toast.LENGTH_LONG).show(); return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(getApplicationContext(), "Left Swipe", Toast.LENGTH_SHORT).show(); } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(getApplicationContext(), "Right Swipe", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // nothing } return false; @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return mGestureDetector.onTouchEvent(event); } } } A: First, I assume for an example that, all your views in the layout.xml file are wrapped inside a framelayout and you want your swipes to be detectable across the entire framelayout. If so, register your framelayout to the object of the type GestureDetector as shown in the following code: FrameLayout mFL = (FrameLayout) findViewById(R.id.framelayoutID); mGestureDetector = new GestureDetector(getApplicationContext(), new MySwipeGestureDetector()); mFL.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return mGestureDetector.onTouchEvent(event); } }); Regarding the simpleOnGestureListener, here is how to implement onFling. it works for me.: //define these variables globally: /* private static final int MIN_DIST = 100; private static final int MAX_OFF_PATH = 200; private static final int THRESHOLD_VELOC = 200;*/ ... ... ... @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Log.i("SwipeGesture", "Left Swipe"); } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Log.i("SwipeGesture", "Right Swipe"); } } catch (Exception e) { // nothing } return false; } }
{ "pile_set_name": "StackExchange" }
Q: SQL Server Trigger not Working i have this 2 triggers and no one is working, but i dont know why, can´t everyone help me: Insert: CREATE TRIGGER [dbo].[afterInsert] ON [dbo].[LinhasVenda] FOR INSERT AS BEGIN DECLARE @IdVenda INT, @PrecoTotalSIva MONEY, @PrecoTotalCIva MONEY SELECT @PrecoTotalSIva = PrecoTotalSIva, @PrecoTotalCIva = PrecoTotalCIva FROM INSERTED UPDATE Vendas SET ValorSIva = ValorSIva + @PrecoTotalSIva, ValorCIva = ValorCIva + @PrecoTotalCIva WHERE IdVenda = @IdVenda END Delete: CREATE TRIGGER afterDelete ON LinhasVenda FOR DELETE AS BEGIN DECLARE @IdVenda INT, @IdArtifo INT, @PrecoTotalSIva MONEY, @PrecoTotalCIva MONEY SELECT @PrecoTotalSIva = PrecoTotalSIva, @PrecoTotalCIva = PrecoTotalCIva FROM DELETED UPDATE Vendas SET ValorSIva = ValorSIva - @PrecoTotalSIva, ValorCIva = ValorCIva - @PrecoTotalCIva WHERE IdVenda = @IdVenda END A: Both triggers have 2 flaws. The @IdVenda value used in the WHERE clause is not being assigned by the SELECT statements. Also, these triggers will not work with multi-row INSERT/UPDATE statements. I suggest you JOIN to INSERTED/DELETED, which will address both these problems. Below is an example, assuming the column name in the LinhasVenda table is also named IdVenda. CREATE TRIGGER [dbo].[afterInsert] ON [dbo].[LinhasVenda] FOR INSERT AS BEGIN UPDATE v SET ValorSIva = v.ValorSIva + i.PrecoTotalSIva , ValorCIva = v.ValorCIva + i.PrecoTotalCIva FROM Vendas AS v JOIN INSERTED AS i ON i.IdVenda = v.IdVenda; END; GO CREATE TRIGGER afterDelete ON LinhasVenda FOR DELETE AS BEGIN UPDATE v SET ValorSIva = v.ValorSIva - d.PrecoTotalSIva , ValorCIva = v.ValorCIva - d.PrecoTotalCIva FROM Vendas AS v JOIN DELETED AS d ON d.IdVenda = v.IdVenda; END; GO
{ "pile_set_name": "StackExchange" }
Q: Revision control -- Title Color Overlap I am looking at the rev control for this question and on my screen in Chrome 13.0.7 it looks like this: This should be remedied because it can get hard to read if the title is more than one line. It might just be a minor css issue. The same happens if you click on the second option for side by side diffs: This was an issue in July (on profile pages): Problem displaying title revisions on profile activity tab, and it was marked as status-completed -- so it is probably the same issue, and just as easy to fix. A: The too low line-height for the headers was fixed for the Stack Exchange 2.0 sites, but was never pulled over to the Trilogy sites. Fixed in the next build. Note that depending on a site's font settings, there may still be a slight overlap in the highlights, but it won't touch the actual letters (and thus hurt readability).
{ "pile_set_name": "StackExchange" }
Q: Determine the region bounded by the inequalities Determine the region bounded by the inequalities: $$ 0 \leq x + y \leq 1 \\ 0 \leq x - y \leq x + y $$ I don't know what to solve for first, so I just added them: $$ 0 \leq x \leq 1 + x + y \\ $$ I guess I can subtract $x$: $$ -x \leq 0 \leq 1 + y \\ $$ Or: $$ -y - 1 \leq 0 \leq x \\ $$ So from this inequality, it looks like some area in the 4th quadrant because $x \geq 0$ means everything to the right of the $y$-axis, and $-y - 1 \leq 0$ means $- 1 \leq y$ which is above the line $y = -1$. However, it looks like I'm analyzing incorrectly as the answer says that it is some area above $y = 0$. I'm not sure what I'm doing wrong. A: The inequalities are: $$y\le 1-x$$ $$y\ge -x$$ $$y\ge 0$$ $$y\le x$$ You should graph these and determine the region where all the inequalities hold. Here is a picture of what it should look like
{ "pile_set_name": "StackExchange" }
Q: Parsing charts from a series of webpages Maybe there is something regarding this subject but I haven t found it, yet. I have parsed a list of webpages and I am extracting the lists I need from the https://tradingeconomics.com/ website. In any page appears a list of countries with an hyperlink for any country to have info on that particular nation. Now, in any of these pages there is a chart I would like to extract and store as .pdf or .doc (or any other format available). Here's my code. trading_ec <- read_html("https://tradingeconomics.com/indicators") ## 01. Formatting the link tr_ec_tabs_39 <- tr_ec_tabs[39] tr_ec_tabs_lo_39 <- tolower(tr_ec_tabs_39) tr_ec_nospace_39 <- gsub(" ", "-", tr_ec_tabs_lo_39) ## 02. Choosing dataset (in the ex. : dataset 39, ' food inflation') json.indicators_39 <- json.indicators[39] ## 03. Scraping the variables names table_39 <- list() for(i in seq_along(json.indicators_39)) { table_39[[1]] <- html_table(read_html(json.indicators_39[1]))[[1]] } ## 04. Turning the list into a dataframe table_39_df <- as.data.frame(table_39) ## 05. Building up the links table_39_df$Country <- tolower(table_39_df$Country) table_39_df$Country <- gsub(" ", "-", table_39_df$Country) json.indicators_39_p <- paste0("https://tradingeconomics.com/" , table_39_df$Country, "/food-inflation") ## 06. Function to choose the tables one is interested in each page table_39_tables <- list() for(i in seq_along(json.indicators_39_p)) { table_39_tables[[i]] <- html_table(read_html(json.indicators_39_p[i]), fill=TRUE)[[1]] cat("Page", i, "of", length(json.indicators_39_p), "obtained.\n") } Any hint? A: You can grab each chart quite easily as a PNG image. I will show you the steps you might use. Firstly load in the necessary libraries, then get a vector containing all the indicators we might want to see by using xpath and html_attr to scrape the links from the page: library(rvest) library(tidyverse) site <- "https://tradingeconomics.com" trading_ec <- read_html(paste0(site, "/indicators")) link_xpath <- "//ul/li/a[contains(@id, 'ctl00_ContentPlaceHolder1')]" link_nodes <- html_nodes(trading_ec, xpath = link_xpath) link_names <- grep("country-list", html_attr(link_nodes, "href"), value = T) indicators <- unlist(lapply(strsplit(link_names, "/"), function(x) x[3])) These can now be viewed and stored, etc. print(head(indicators)) # [1] "employed-persons" "employment-change" "employment-rate" # [4] "full-time-employment" "initial-jobless-claims" "job-vacancies" Next we can define a function that will give us a list of all countries available to examine for any given indicator list_countries <- function(indicator) { url <- paste0("https://tradingeconomics.com/country-list/", indicator) indicator_page <- read_html(url) country_nodes <- html_nodes(indicator_page, xpath = "//td/a") relative_links <- html_attr(country_nodes, "href") countries <- unlist(lapply(strsplit(relative_links, "/"), function(x) x[2])) tibble(country = countries, link = paste0("https://tradingeconomics.com", relative_links)) } This allows us to see all the available countries for any indicator, and the link to that country's page. link_df <- list_countries("food-inflation") print(link_df) #> # A tibble: 171 x 2 #> country link #> <chr> <chr> #> 1 afghanistan https://tradingeconomics.com/afghanistan/food-inflation #> 2 albania https://tradingeconomics.com/albania/food-inflation #> 3 algeria https://tradingeconomics.com/algeria/food-inflation #> 4 argentina https://tradingeconomics.com/argentina/food-inflation #> 5 armenia https://tradingeconomics.com/armenia/food-inflation #> 6 aruba https://tradingeconomics.com/aruba/food-inflation #> 7 australia https://tradingeconomics.com/australia/food-inflation #> 8 austria https://tradingeconomics.com/austria/food-inflation #> 9 azerbaijan https://tradingeconomics.com/azerbaijan/food-inflation #> 10 bahrain https://tradingeconomics.com/bahrain/food-inflation #> # ... with 161 more rows Finally, we define a function to make it easier to get the chart from our target page. We will save this directly to local disk by passing in the desired file name to the function: get_chart <- function(url, save_to) { page <- read_html(url) image_node <- html_nodes(page, xpath = "//img[@id='ImageChart']") image_url <- html_attr(image_node, "src") download.file(image_url, destfile = save_to, mode = "wb") } Now we can save the image directly to local disk. This can be added to a pdf or html as needed. get_chart(as.character(link_df[1, 2]), path.expand("~/food_chart.png")) In my R home directory I now have the following file save as food_chart.png: Of course, you can string the functions together so that you only have to give the country and indicator, etc.
{ "pile_set_name": "StackExchange" }
Q: Negation of verb/gerund I made up the following sentences. Which version is correct? I prefer being by myself and not depend on others. I prefer being by myself and don't depend on others. I prefer being by myself and not depending on others. The first version looks to me a nice version to hear it. But negation of the verb seems to me wrong. The senond one looks pretty grammatical.Due to we negate a verb with auxiliary verb do The third one uses gerund. It doesn't nice to hear. But it make sense because it combines the sentence in a good structure: Subject+Verb(Gerund + Gerund) A: The first sentence is wrong because "not" can't modify the following "depend". The second and third sentences are grammatically correct but have slightly different meaning. Sentence 2 describes what I do (I don't depend on others) while sentence 3 describes what I prefer (I prefer not depending on others).
{ "pile_set_name": "StackExchange" }
Q: (ibm_db) ImportError: DLL load failed while importing ibm_db: The specified module could not be found I have installed Python 3.8.1 and have installed the ibm_db 3.0.1 API for IBM DB2. When I try to 'import ibm_db' in debug mode I get "ImportError: DLL load failed while importing ibm_db: The specified module could not be found." I tried uninstalling and re-installing Python and the API, installing prior versions of Python but nothing worked. I also tried to see if adding the path prior to the import ibm_db would make a difference: sys.path.append( "C:\\Users\\<userid>\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\ibm_db") It should not be that hard so please feel free to suggest what might be considered obvious. A: Update: 16/June/2020, the ibm_db module versions 3.0.2 and higher now supports Python 3.8 on Microsoft Windows platform. The ibm_db module versions lower than v3.0.2 do not support Python 3.8 on Microsoft-Windows. You can see this mentioned on the related github issue github. ibm_db v3.0.1 will install and work correctly with Python 3.7.x on Microsoft Windows.
{ "pile_set_name": "StackExchange" }
Q: Errors with configuring Propel ORM in Symfony2 I'm trying to configure propel ORM in Symfony2 project, but I keep getting this error message when ever I run symfony command lin tool: [Symfony\Component\Config\Exception\FileLoaderLoadException] There is no extension able to load the configuration for "propel" (in C:\Program Files (x86)\Zend\Apache2\htdocs\se\app/config\config.yml). Looked for namespace "propel", found " framework", "security", "twig", "monolog", "swiftmailer", "assetic", "doctrine", "sensio_framework_extra", "acme_demo", "debug", "web_profiler", "sensio_distribution" in C:\Progr am Files (x86)\Zend\Apache2\htdocs\se\app/config\config.yml (which is being imported from "C:\Program Files (x86)\Zend\Apache2\htdocs\se\app/config/config_dev.yml"). I configured according to the official documentation: #Propel Configuration propel: dbal: driver: "%database_driver%" user: "%database_user%" password: "%database_password%" dsn: "%database_driver%:host=%database_host%;dbname=%database_name%;charset=%database_charset%" And I installed the propel package properly trough composer. The propel command line works fine. A: Did you add PropelBundle to AppKernel? Looks like you didn't. AppKernel.php public function registerBundles() { $bundles = array( // ... new Propel\PropelBundle\PropelBundle(), ); // ... } http://propelorm.org/Propel/cookbook/symfony2/working-with-symfony2.html
{ "pile_set_name": "StackExchange" }
Q: Modular exponentiation fails for large mod in C++ This is the code I'm using for calculating (n^p)%mod. Unfortunately, it fails for large values of mod (in my case mod = 10000000000ULL) when I call it from main() method. Any idea; why? ull powMod(ull n, ull p, ull mod) { ull ans = 1; n = n%mod; while(p) { if(p%2 == 1) { ans = (ans*n)%mod; } n = (n*n)%mod; p /= 2; } return ans; } Here, ull is a typedef for unsigned long long. A: Yes you can do it in C++. As others pointed out you cannot do it directly. Using a little drop of number theory it is possible to decompose the problem into two manageable sub problems. First consider that 10^10 = 2^10 * 5^10. Both factors are coprime, so you can use the Chinese remainder theorem to find the power modulo 10^10 using the powers modulo 2^10 and modulo 5^10. Note that in the following code the magic values u2 and u5 were found using the Extended Euclidean Algorithm. You don't need to program this algorithm yourself because these values are constants. I use maxima and its gcdex function, to compute them. Here is the modified version: typedef unsigned long long ull; ull const M = 10000000000ull; ull pow_mod10_10(ull n, ull p) { ull const m2 = 1024; // 2^10 ull const m5 = 9765625; // 5^10 ull const M2 = 9765625; // 5^10 = M / m2 ull const M5 = 1024; // 2^10 = M / m5 ull const u2 = 841; // u2*M2 = 1 mod m2 ull const u5 = 1745224; // u5*M5 = 1 mod m5 ull b2 = 1; ull b5 = 1; ull n2 = n % m2; ull n5 = n % m5; while(p) { if(p%2 == 1) { b2 = (b2*n2)%m2; b5 = (b5*n5)%m5; } n2 = (n2*n2)%m2; n5 = (n5*n5)%m5; p /= 2; } ull np = (((b2*u2)%M)*M2)%M; np += (((b5*u5)%M)*M5)%M; np %= M; return np; }
{ "pile_set_name": "StackExchange" }
Q: Encryption & Decryption Question Greetings all i want to know how to make good encryption and decryption for something in java and is is possible for anyone to decrypt something encrypted ? A: It's always possible. Encryption/decryption is only as good as the underlying algorithm. Given enough time and computing power, anything can be done. Try http://www.jasypt.org/ A: Edited to be more technically correct ... is possible for anyone to decrypt something encrypted ? The encryption algorithm will dictate how long it will take for someone to decrypt your encrypted data, like duffymo said. WEP for wireless routers would be a good example of an security algorithm that does not take much time to break. The underlying encryption algorithm (RC4) is easily exploitable due to it used in the wrong context. RC4 is not broken, the designers used RC4 for the wrong application. http://en.wikipedia.org/wiki/Wired_Equivalent_Privacy#Flaws If you use an encryption algorithm in the wrong context, then you may be building false sense of security. A: Cryptography is a big subject with a long history, but the basic idea is that you're using a "secret" to prevent someone else from seeing something (data, a message, etc). There are many ways to hide information, but the best ones are based on time-tested, mathematically sound algorithms. For that reason, it's uncommon for a layperson (i.e. not a mathematician or advanced computer science guru) to write a successful encryption algorithm from scratch. Instead, most people use one of the existing set of algorithms, some of which (like AES) are international standards. These combine a publicly-known "scrambling" algorithm with a small "secret" key that only you (or a small group) know; without the key, you can't get the data. There are cases where "brute force" can be used to get the data--for example, trying every possible key. This, of course, takes time and computing power, and for a sufficiently large key size, is effectively impossible (i.e. there are more possible keys than the number of atoms in the universe). So, if you use a well known, well tested algorithm, with a large key, you can be pretty assured that your data can't be gotten by force. (Of course, there are other ways to skin a cat--like calling you pretending to be someone who should know the key, and getting you to tell them ...) There are java libraries for every major encryption algorithm that you can simply include in your project and use (as @duffymo said, http://www.jasypt.org/ is a good place to start).
{ "pile_set_name": "StackExchange" }
Q: How to use "due to" for two clauses I am wondering which of the following sentences is properly written: This is due to {First Clause} and to {Second Clause}. or This is due to {First Clause} and {Second Clause}. The question is how we should distribute "to" between clauses? This question also remains for other phrases which have "to" at the end of. A: There's nothing syntactically wrong with due to X and Y; but in any given context it may be desirable to repeat either to or due to to avoid ambiguity and keep your structure apparent to your readers. Generally, you will want to repeat one or both of these if X is 'heavy': very long or very complex. When you've taken your readers down a long path in one direction and then suddenly return to the head of the path and start off in a different direction, you want to carry them with you to the point where the two paths diverge. And in some instances you need to make clear that you're not still on the first path. Look at your example: This is due to the abundance of controller and observer design techniques available for ODEs and also mathematical complexities of dealing with an infinite dimensional space As it stands, many readers will assume at first glance that and also mathematical complexities is conjoined with ODEs, that ODEs and complexities are two classes of things for which techniques are available. And inserting to before mathematical complexities merely pushes the misunderstanding back a step and leaves them wondering why techniques are available for ODEs but available to mathematical complexities. Acute readers, of course, will eventually figure out what you mean. But they will be at least a little annoyed and impatient; and your incoherence may lead them to doubt your intellectual acumen. Your job as a writer is to make it as easy as possible for your readers to understand what you mean—to assure that they do not misunderstand, to hold their rapt attention, and not least as a courtesy you owe them for condescending to spend their valuable time on your work. At the very least you need to repeat both due and to: This is due to the abundance of controller and observer design techniques available for ODEs, and due also to the mathematical complexities of dealing with an infinite dimensional space. Me, I'd be even more explicit: This is due on the one hand to the abundance of controller and observer design techniques available for ODEs, and on the other to the mathematical complexities of dealing with an infinite dimensional space. It's eight words longer, to be sure; but the microseconds it takes to read the two fixed phrases on the one hand and on the other is I think more than offset by the reduced parsing time required.
{ "pile_set_name": "StackExchange" }
Q: Critique my SMPS buck design I'm using an LM2734 buck regulator to get +3.3V at 400mA. The datasheet is unclear on how to lay out the supply, so I tried to follow some common sense, keeping all power traces short where possible. The power supply has to be very small, which is why it uses ceramic caps and the LM2734, which operates at 3 MHz and thus requires a smaller inductor (it's still pretty massive!) L1: 3.3uH 2A inductor C1: 4.7uF 50V ceramic cap C2: 4.7uF 50V ceramic cap C3: 0.01uF 16V ceramic cap C4: 22uF 10V ceramic cap D1: RB160M (input protection) D2: RB160M D3: (mislabeled D1, the SOT-23) any small signal silicon diode R1: 10k R2: 31.6k R3: 1k LED1: any small LED U1: LM2734, SOT-23-6 I'm generating the boost voltage from the output. A: Good first stab, just some thoughts: 1) The R1 / R2 feedback voltage divider has some really long traces and paths to ground. Anything you can do to keep the FB traces short will improve regulation stability and the ground used should be tightly coupled to the IC ground. I'd put R1 and R2 directly next to each other and put em where the small signal diode is, moving the diode over to where R1 is now. Ground R2 to the IC ground via (its low current). The LED can go pretty much anywhere and trace length doesn't matter so just move it to fit. 2) The input caps, C1/C2 and the catch diode D2 should be very tightly coupled, their ground references need to be very very close to each other. I'd flip D2 90 degrees and move it over next to C2, ground them all right there, you should use more than 1 via for this ground. What i normally do for this is a little copper pour on the surface that connects to all 3 pads (D2/C1/C2) and extends out enough to plop 3 decently sized vias in it. 3) the output filter cap C4 is in a really odd place It should also be quite tightly coupled to the ground of D2/C1/C2, move L1 over and you can probably put it right next to D2 and included it in the little ground pour I was talking about in 2). 4) With the above re-organization you can move C3 over just above/to the right a touch of the IC which will get rid of the problem you have with the input supply trace having to fit between C3's pads, as drawn right now that will short out, the trace is way too close to the pads. Keep in mind that your critical path in this circuit, that is the loop where there will be high current AC and DC spike is from the input -> D1 -> C1+ -> C2+ -> ICin -> ICsw -> D2+ -> L1 -> C4+ -> C4- -> through other grounds back to C1- Your goal is to minimize the loop area and the resistance in that loop, which moving C1,C2,D2,C4 as close as possible to each other and the IC will help with as well as tightly coupling their grounds through a small pour on the surface with multiple vias to the ground plane. A: From the details below: At 400mA and 20V in, you're running in continuous mode with a duty cycle of around 18%, with a peak inductor current of around 0.7A. At 4.8V, it's also CCM with a duty cycle near 70% and a peak inductor current of around 0.5A. You may want to consider having a footprint on the PCB for the feed-forward capacitor Cff, just in case the internal compensation needs a speed-up. (You could also add a resistor in series with Cff, making what's referred to as type-3 compensation when combined with the ICs internal feedback). Bucks can be tricky to stabilize, especially with ceramic output capacitors (and with most of the compensation inside the chip!) If you can afford some copper, add some around the SW and/or Vin pins. Copper here can pull some of the heat out of the internal MOSFET and improve reliability. The 2% reference may cause a setpoint error of up to +/- 66mV, not including the tolerance of the resistors used in the feedback divider. You may want to add another footprint in parallel with the bottom resistor in the divider or add a trim pot if the setpoint is critical for your application. Don't expect great efficiency at 20V in - the duty cycle is very small. It'll be much better than a linear regulator of course, but not great.
{ "pile_set_name": "StackExchange" }
Q: Oracle Procedure create or replace function gen.sample_func(owner varchar2) return varchar2 as data_t varchar2(10); cursor cur is select data_type from SYS.DBA_TAB_COLUMNS; begin open cur; dbms_output.put_line('Done'); close cur; return data_t; end sample_func; On compiling the above function i get the following error Warning: compiled but with compilation errors Errors for FUNCTION sample_func LINE/COL -------------------------------------------------------------------------------- ERROR -------------------------------------------------------------------------------- 4/8 PLS-00201: identifier 'DBA_TAB_COLUMNS' must be declared 4/8 PL/SQL: Item ignored 7/15 PLS-00320: the declaration of the type of this expression is incomplete or malfo rmed 7/8 PL/SQL: Statement ignored I'm not getting this error when i execute the select statement alone in the cursor. Please help me to resolve this issue. A: Your user needs to be granted SELECT ON DBA_TAB_COLUMNS. Note that granting through a role will not work - it needs to be a direct grant to the user for you to create a function/procedure. A: In a definer's rights stored procedure such as the one you are creating, only privileges that are granted directly to the owner of the procedure are considered when resolving object names. Privileges granted through roles are not considered. I would wager that the owner of your procedure has been granted access to the DBA_TAB_COLUMNS view via a role rather than via a direct grant. You would need to ask the DBA to grant access to DBA_TAB_COLUMNS directly to the user that owns your procedure. You can quickly test whether this is actually the problem you're experiencing. In SQL*Plus, enter the command SQL> set role none; and then run your SELECT statement. If you get the same permissions error, then the rpoblem is that you have the grant via a role. Disabling roles means that your interactive session is running with the same privileges that your stored procedure would run with.
{ "pile_set_name": "StackExchange" }
Q: YAML $ref is not control-clickable (hyperlink) in IntelliJ IDEA We have a .yml file defining the REST API, with many entries like this /projects/{projectId}/jobs/{jobId}: parameters: - $ref: '#/parameters/projectId' - $ref: '#/parameters/jobId' get: summary: Get Job responses: 200: description: Information retrieved successfully. schema: $ref: '#/definitions/Job' The $ref items are not control-clickable in IDEA although they can be. The YAML and YAML/Ansible support plugins are installed and enabled. A: I've discovered, with the help of @Frederik here, that the Swagger Plugin does the trick. I chose the one by "Zalando" for editing and not for code generation as it has the highest rate.
{ "pile_set_name": "StackExchange" }
Q: Pushing data from one workbook to another I have an Excel workbook book1.xlsm and another one as book2.xls. I want to push values from book1 to book2 via a macro running in book1. Is there a way in which even if the workbook book2 is closed the value is pushed to it? The main reason for asking this is that it will skip the problem of saving book2 again and again after a new value is inserted. A: The short answer is No The longer answer is ... ... whatever technology you use to get updates into a file (patching on the O/S byte level, using application programmes, etc. ...), it always means to open / update / save / close the file (allthough on the lowest level a "file" may be a sector on the hard drive). Some techno's are faster than others, though ... So don't waste time ... if you can't do by creating formulas in Book2 that retrieve data from Book1- as suggested in the comments to your question - write code in Book1 to open / update / close Book1 By carefull and intelligent use of events like Workbook_Open() and Workbook_BeforeClose(...) you can care for synchronisation and hence minimizing the number of openings / savings /closings of Book2
{ "pile_set_name": "StackExchange" }
Q: How to work with Dropbox Paper TODOs via API? I have gone through the API documentation on the Dropbox website, and have found the section that relates to Paper, however I don't see a way to work with the TODO's for a document or a user. Is this something that is not yet supported or have I missed it ? A: The Dropbox API doesn't offer a way to interact with Paper to-do items unfortunately, but I'll pass this along as a feature request.
{ "pile_set_name": "StackExchange" }
Q: Custom Compare function for std::binary_search Is there any problem with this code? bool Spellcheck::smart_comp(string value, string key){ return true; } void func(){ std::string aprox_key = "hello"; if(std::binary_search(this->words.begin(), this->words.end(), aprox_key, smart_comp)){ std::cout << "Found" << std::endl; } } I am trying to write my own compare function for comparing strings in binarysearch I am getting following error: xyz.cpp:40:85: error: no matching function for call to ‘binary_search(std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, std::string&, <unresolved overloaded function type>)’ xyz.cpp:40:85: note: candidates are: /usr/include/c++/4.6/bits/stl_algo.h:2665:5: note: template<class _FIter, class _Tp> bool std::binary_search(_FIter, _FIter, const _Tp&) /usr/include/c++/4.6/bits/stl_algo.h:2698:5: note: bool std::binary_search(_FIter, _FIter, const _Tp&, _Compare) [with _FIter = __gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >, _Tp = std::basic_string<char>, _Compare = bool (Spellcheck::*)(std::basic_string<char>, std::basic_string<char>)] /usr/include/c++/4.6/bits/stl_algo.h:2698:5: note: no known conversion for argument 4 from ‘<unresolved overloaded function type>’ to ‘bool (Spellcheck::*)(std::basic_string<char>, std::basic_string<char>)’ Any help is appreciated... A: Is there any problem with this code? bool Spellcheck::smart_comp(string const value, string const key){ return true; } Other than it always returns true? Yes, the basic problem is that a member function has an implicit parameter this, so the signature does not match that of the expected predicate. You should be doing this function static or even a free function (friended if needed). Also you are copying the strings each time, it would be best if you take the arguments by const reference to avoid unneeded copies. In case the real result of the predicate depends on the state of the Spellcheck object, you will have to bind that state to the member function in order to create a function object with the appropiate signature: std::binary_search( this->words.begin(), this->words.end() , std::bind( &Spellcheck::smart_comp, this ) );
{ "pile_set_name": "StackExchange" }
Q: Can I use a deep fryer instead of a pot with oil? I got a deep fryer for Christmas, and that made me think of all the donut recipes I have seen floating about, like this one for crullers or this one for chocolate dipped donuts. These are just two examples, but I noticed they all call for a pot filled with about 2 inches of oil heated to a certain temperature. My deep fryer does have adjustable temperature settings, so that would be fine, but I am not sure if using the deep fryer instead of the pot of oil would work. Is a deep fryer an okay substitute? I really want to get some good use out of it, and this sounded somewhat plausible. Am I completely off-track? A: You can definitely cook donuts in a deep fryer. Most, if not all, donuts shops cook them in that manner. Just make sure your temperature is good and use something like chopsticks to flip them.
{ "pile_set_name": "StackExchange" }
Q: Storing a word with double quotes into a char array How do I store the following into a char array: AT+CIPSTART="TCP","103.6.157.239","8085" When I do the following : char L []="AT+CIPSTART="TCP","103.6.157.239","8085""; I get an error : ../GPRS.c:48: error: expected ',' or ';' before 'TCP' A: Try this char c[]="AT+CIPSTART=\"TCP\",\"103.6.157.239\",\"8085\""; Micro controller escape sequences : \? for ? \\ for \ \' for ' \" for " \b for backspace \n for new line \ooo for octal number \t for horizontal tab \v for vertical tab \xxx for hexadecimal number
{ "pile_set_name": "StackExchange" }
Q: Is there an acceptable cross-platform method for displaying a numeric keypad in standard web forms on a touch-based device? The goal: To find a cross-platform solution for displaying numeric keyboards on mobile touch-based devices, with a minimum of hacks. The problem: I have a regular web application using data input forms, containing primarily numeric data. When a user interacts with my site on a mobile device, I would like to display a numeric virtual keypad as most standard keyboards require a second press to switch from alphas to numbers. I know that i can trigger different keyboard by setting the "type" attribute of input element: type=number: This works great under iOS/Safari. I am unsure about other browsers on the platform. On Android, this does not consistently raise the correct keyboard on various browsers and often results in unwanted elevator buttons on the input. I have yet to find a clean way to turn these off in CSS. type=tel: This almost works on iOS/Safari, but the telephone keyboard lacks a decimal button. Seems to work great across multiple android browsers, without any extraneous UI elements added to the page. My current solution is hacky and simplistic. Based on a class that I'm already using for numeric validation, I replace each text element that should contain a number with a new input that is either a number or a tel type based on the detected OS/browser. var isAndroid = navigator.userAgent.match(/android/i) ? true : false; var isIOS = navigator.userAgent.match(/(ipod|ipad|iphone)/i) ? true : false; if (isAndroid || isIOS) { var useNumberType = (isIOS ? true : false); //iOS uses type=number, everyone else uses type=tel jQuery("input.num").each(function () { var type = (useNumberType ? "number" : "tel"); var html = this.outerHTML; html = html.replace(/(type=\"?)text(\"?)/, "$1" + type + "$2"); this.outerHTML = html; }); } I would prefer to not use browser detection and to not change out the inputs on the fly at run time. I could possibly introduce an http module on the server side that did basically the same thing, but that is not substantially better. I'm shocked that there isn't a CSS call for this. Is there a better way to get a numeric keyboard with a decimal button, that works on all or most touch-based mobile devices without adding weird UI elements to the page? -------------- update I don't think there is a way to do what I really want to do, which is to setup a single input style or type that will work well across desktop browsers and all major mobile touch-based platforms. I settled on changing the type of the input through a direct DOM call rather through jQuery instead of rewriting the entire input via outerHTML. I suspect there isn't much difference in effect, but the code is a little cleaner. Since I'm not changing input types on the desktop, I shouldn't have to worry about IE's read only restriction on the attribute. Ideally, I'd probably handle this on the server side so everything got sent to the browser in the format desired for the device making the request. But for now the new code looks more like this: var isAndroid = navigator.userAgent.match(/android/i) || navigator.platform.match(/android/i) ? true : false; var isIOS = navigator.userAgent.match(/(ipod|ipad|iphone)/i) ? true : false; if (isAndroid || isIOS) { var useNumberType = (isIOS ? true : false); //iOS uses type=number, everyone else uses type=tel jQuery("input.num").each(function () { var type = (useNumberType ? "number" : "tel"); if (this.type == "text") { this.type = type; } }); } A: Protip: when working with mobile, do NOT interfere with the user experience. This means keeping the built-in keypads as they are. Some users may even have Javascript disabled on their mobile devices/browsers! What you should do here is include an HTML hint to the browser. This way, mobile browsers should know what kind of content they are interacting with. HTML5 includes several new <input> content types that should be supported on all modern mobile devices (and most modern browsers) You can find the full list here. What you want specifically is the following: Old code: Phone number: <input type="text" name="phone" /> New code: Phone number: <input type="tel" name="phone" /> I don't know that any browsers currently support "tel", so you could use something like the following: Phone number: <input type="number" name="phone" min="1000000000" max="9999999999" /> This is a bit of a hack, but is another option for you. This is a MUCH simpler and more maintainable way of doing things, and better for the user. Please let me know if you have any questions. I know this isn't directly answering the question, but it is a better way of doing things for now, in my opinion. :) EDIT: A possible way to get around this for each browser is by checking the user agent using JS/Jquery. I'm not sure exactly how to do this, but here is a tutorial on how to do so in .NET and changing the CSS for each element using JQuery. EDIT EDIT!: Try just modifying your code as such: var isAndroid = navigator.userAgent.match(/android/i) ? true : false; var isIOS = navigator.userAgent.match(/(ipod|ipad|iphone)/i) ? true : false; if(isIOS) $(.phoneInput).attr("type", "tel"); if(isAndroid) { $(.phoneInput).attr("type", "number"); $(.phoneInput).attr("min", "1000000000"); $(.phoneInput).attr("max", "9999999999"); } I hope this out of everything works! You might have to switch the two if statements, depending on how your testing turns out.
{ "pile_set_name": "StackExchange" }
Q: Setting Privacy Settings using the Facebook API I am working with the Facebook API for C#. I am unable to find any reference to changing privacy settings using the API. I've looked at a lot of different places, with no success. Could anyone guide me in the right direction? Thanks! A: You can't. Only through the official channels can users change their privacy settings.
{ "pile_set_name": "StackExchange" }
Q: Eilenberg-MacLane Spaces of "large" groups It is well-known that if $G$ is a discrete group, then $BG=K(G,1)$. I'm interested in comparing classifying spaces of topological groups with the classifying spaces of the same groups but equipped with the discrete topology. They will be quite different in general, that much is clear. For instance, $S^1$ can be thought of as a topological group (the usual way) and as a discrete group, denoted by, say, $S^1_d$. On one hand we have that $BS^1=\mathbb{C}P^∞(=K(\mathbb{Z},2))$, and on the other we should have $K(S^1_d,1)$, which I guess we could construct by hand (as in Hatcher's book, for example), but other than that I can't really say anything about it. Perhaps they usually are quite messy. What is known about this space? Or, more generally, about $K(G,1)$ where $G$ is infinite and discrete (and not $\mathbb{Z}$)? Are there any references about this? Any thoughts on the relation between the classifying spaces of top. groups vs E-M spaces of the same (discrete) groups (if any) would be greatly appreciated. Thanks! On another matter: this is a cross-post of https://math.stackexchange.com/questions/480437/what-is-k-s1-1, which I asked quite some time ago, and didn't get any answers there. Should I delete that question? A: Let me just point out that if you're interested in, say, homology, then discrete $S^{1}$ is not as complicated as it might seem. The resulting invariants will be huge, of course, but one should be able to compute them explicitly. The point is that $S^{1} = \mathbb{R} / \mathbb{Z}$ and $\mathbb{R} \simeq \bigoplus \mathbb{Q}$ (as an abelian group), thus $S^{1} \simeq (\mathbb{Q} / \mathbb{Z}) \bigoplus (\oplus \mathbb{Q})$. Any direct sum of groups can be written as a filtered colimit of its finite subsums and finite direct sums coincide with finite products. Taking classifying spaces commutes with both filtered colimits and finite products and so the classifying space of discrete $S^{1}$ can be described in terms of classifying spaces of $\mathbb{Q} / \mathbb{Z}$ and $\mathbb{Q}$. You can use this to compute homology (it commutes with filtered colimits) by using Künneth formula to deal with products. I imagine classifying spaces of $\mathbb{Q} / \mathbb{Z}$ and $\mathbb{Q}$ are not difficult to describe, as $\mathbb{Q} / \mathbb{Z}$ falls apart into a direct sum of $p$-torsion parts (which I imagine are limits of finite cyclic $p$-groups?) and $\mathbb{Q} = colim (\mathbb{Z} \rightarrow \mathbb{Z} \rightarrow \ldots)$. A: One place to start might be: Milnor, J. On the homology of Lie groups made discrete. Comment. Math. Helv. 58 (1983), no. 1, 72–85. http://www.ams.org/mathscinet-getitem?mr=699007
{ "pile_set_name": "StackExchange" }
Q: Rejected gated check-in (old vb.net Website) I have an old vb.net Website that targets .NET Framework 2.0. When I build and run the project locally, everything works fine. When I queue a build on the tfs I get the following error: ~\Website.metaproj: .NET Framework v3.5 Service Pack 1 was not found. In order to target ".NETFramework,Version=v2.0", .NET Framework v3.5 Service Pack 1 or later must be installed. When I change the target framework to 4 or 4.5 I get the following error: ASPNETCOMPILER: Object reference not set to an instance of an object. How do I proceed? A: Install .net 3.5 on your build server.
{ "pile_set_name": "StackExchange" }
Q: What is Android CameraX? What is Android CameraX? There is a session about CameraX planned in Google I/O 2019. What is it? Is it a new framework API? Is it a new library? https://events.google.com/io/schedule/events/8d400240-f31f-4ac2-bfab-f8347ef3ab3e Does it mean that Camera2 API is deprecated? https://github.com/googlesamples/android-Camera2Basic A: What is Android CameraX? CameraX is a new Jetpack library that lets developers control a device's camera and focuses on compatibility across devices going back to API level 21 (Lollipop). It was announced at Google I/O 2019 and has a dedicated documentation page alongside an official sample. Does it mean that Camera2 API is deprecated? Camera2 API is not deprecated; in fact, it is the foundation that CameraX is built on. CameraX also provides a Camera2 interop API that lets developers extend their CameraX implementation with Camera2 code. For more information, the official documentation is available at https://developer.android.com/camerax A: In Google IO 2019, Google added another powerful tool for camera development in Android development called CameraX as part of Jetpack Few Features of CameraX It is backwards compatible till Android 5.0 / Lollipop (API 21) and it works with at least 90% devices in the market. Under the hood, it uses and leverages the Camera 2 APIs. It basically, provide the same consistency as Camera 1 API via Camera 2 Legacy layer and it fixed a lot of issues across the device. It also has a lot of awesome advanced features like Portrait, HDR, Night mode etc (Provided your Device supports that). CameraX has also introduced use cases which allow you to focus on the the task you need to get it done and not waste your time with specific devices. Few of them are Preview, Image Analysis, Image Capture. CameraX doesn't have specific call/stop methods in onResume() and onPause() but it binds to the lifecycle of the View with the help of CameraX.bindToLifecycle() The following is the few lists of known issues fixed with CameraX, what more you can do with CameraX You can also create Video Recorder App using CameraX Add multiple extensions like Portrait Mode, HDR etc. We can also use Image Analysis to perform Computer Vision, ML. So it implements Analyzer method to run on each and every frame. To read more about CameraX refer here for Getting Started with CameraX
{ "pile_set_name": "StackExchange" }
Q: Creating A Sign Up Activity using Parse In my application I am creating a sign up activity using parse database and I used the signUpInBackground() but when I run the code on the emulator the parse is giving me a message that says "unauthorised. Join.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final ProgressDialog dialog = new ProgressDialog(SignUp.this); dialog.setTitle("Please Wait"); dialog.setMessage("Please Wait While Signing Up"); dialog.show(); final ParseUser user =new ParseUser(); user.setUsername(Username.getText().toString().trim()); user.setPassword(Password.getText().toString().trim()); user.setEmail(Email.getText().toString().trim()); user.put("firstName", FirstName.getText().toString().trim()); user.put("lastName", LastName.getText().toString().trim()); user.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { dialog.dismiss(); if(e!=null){ Toast.makeText(SignUp.this,e.getMessage(),Toast.LENGTH_LONG).show(); }else { Intent i = new Intent(SignUp.this,LogIn.class); startActivity(i); } } }); } }); A: When you initialise Parse in your Application class, are you setting your ACL? Also are your keys correct when you initialise? Make sure you follow the Quick Start Guide.
{ "pile_set_name": "StackExchange" }
Q: photo gallery php echo pic on submit I got an assignment to build a photo gallery that works without JS, and you have a working navigation where you can go to next or previous photo. I did a counter that counted from 1-6 (number of pics) then I made if statsment. That is if $spaceship = 1,2,3,4,5,6 echo "that img". It did not work. When I put on the echo my counter failed to count and ALL img display same time after refresh!! god damn. First part of code is sessions <?php //$start = $_GET['value']; //echo $start; //$test = hej; //echo $test; session_start(); $_SESSION['ship'] = ((isset($_SESSION['ship'])) ? $_SESSION['ship'] : 0); if(isset($_GET['add'])){ $_SESSION['ship']++; } if(isset($_GET['sub'])){ $_SESSION['ship']--; } ?> And here is the code so I cycle through the 6 numbers <?php if ($_SESSION['ship'] > 6) { $_SESSION['ship'] = 1; } if ($_SESSION['ship'] < 1) { $_SESSION['ship'] = 6; } echo $_SESSION['ship'] ?> And here is my failure, where I tried to attach each number to diffrent pics and echo them out. if ( $_SESSION['ship'] = 1 ) { echo "<img src=\"img/space/battlestar.jpg\"/>"; } if ( $_SESSION['ship'] = 2 ) { echo "<img src=\"img/space/enterprise.jpg\"/>"; } if ( $_SESSION['ship'] = 3 ) { echo "<img src=\"img/space/integrity.jpg\"/>"; } if ( $_SESSION['ship'] = 4 ) { echo "<img src=\"img/space/millenium.jpg\"/>"; } if ( $_SESSION['ship'] = 5 ) { echo "<img src=\"img/space/planetes.jpg\"/>"; } if ( $_SESSION['ship'] = 6 ) { echo "<img src=\"img/space/serenity.jpg\"/>"; } A: instead of checking equality your if statements are setting the value of ship. so to fix it use this: if ( $_SESSION['ship'] === 1 ) { echo "<img src=\"img/space/battlestar.jpg\"/>"; } if ( $_SESSION['ship'] === 2 ) { echo "<img src=\"img/space/enterprise.jpg\"/>"; } if ( $_SESSION['ship'] === 3 ) { echo "<img src=\"img/space/integrity.jpg\"/>"; } if ( $_SESSION['ship'] === 4 ) { echo "<img src=\"img/space/millenium.jpg\"/>"; } if ( $_SESSION['ship'] === 5 ) { echo "<img src=\"img/space/planetes.jpg\"/>"; } if ( $_SESSION['ship'] === 6 ) { echo "<img src=\"img/space/serenity.jpg\"/>"; } edit: be better to use elseif as well so instead use: if ( $_SESSION['ship'] === 1 ) { echo "<img src=\"img/space/battlestar.jpg\"/>"; } elseif ( $_SESSION['ship'] === 2 ) { echo "<img src=\"img/space/enterprise.jpg\"/>"; } elseif ( $_SESSION['ship'] === 3 ) { echo "<img src=\"img/space/integrity.jpg\"/>"; } elseif ( $_SESSION['ship'] === 4 ) { echo "<img src=\"img/space/millenium.jpg\"/>"; } elseif ( $_SESSION['ship'] === 5 ) { echo "<img src=\"img/space/planetes.jpg\"/>"; } elseif ( $_SESSION['ship'] === 6 ) { echo "<img src=\"img/space/serenity.jpg\"/>"; } HTH; Nick (ps. go Firefly!)
{ "pile_set_name": "StackExchange" }
Q: problems with ordering dates in r I am trying to order dates in R. I have some strings which look like this jnk <- c("2016-01-12T10:54:41Z", "2016-01-12T12:40:30Z", "2016-01-12T14:59:22Z", "2016-01-12T15:55:10Z", "2015-03-29T02:56:42Z", "2015-03-29T02:40:56Z") So I format them with strptime jnk2 <- strptime(jnk, "%Y-%m-%dT%H:%M:%SZ") When I now try to order them, the two 2015 dates will always be at the end... order(jnk2) [1] 1 2 3 4 5 6 Am I missing something? I would expect the order to be 6, 5, 1, 2, 3, 4 A: I had the same issue until I defined a time zone (e.g. tz="GMT"): jnk <- c("2016-01-12T10:54:41Z", "2016-01-12T12:40:30Z", "2016-01-12T14:59:22Z", "2016-01-12T15:55:10Z", "2015-03-29T02:56:42Z", "2015-03-29T02:40:56Z") jnk2 <- strptime(jnk, "%Y-%m-%dT%H:%M:%SZ", tz="GMT") order(jnk2) [1] 6 5 1 2 3 4
{ "pile_set_name": "StackExchange" }
Q: Check if dropdown's selected option is not the first with JavaScript Below are the options that i have in my HTML code: <label id="subn"> <select name="subs" id="subs"> <option value="nothing">Choose a Subject</option> <option value="General Question">General Question</option> <option value="MemberShip Area">MemberShip Area</option> <option value="Others">Others</option> </select> </label> I want to create JavaScript code that will check if the user selected an option other than the first. Here is what I tried: if (document.getElementsByTagName('option') == "nothing"){ document.getElementById("subn").innerHTML = "Subject is Required!"; document.getElementById("subs").focus(); return false; } A: You can check like this if nothing is going to be first (usually the case in my experience): if (document.getElementById('subs').selectedIndex == 0){ To still compare based on the value, do this: var sel = document.getElementById('subs'); if (sel.options[sel.selectedIndex].value == 'nothing') { You may wand to change your markup so the label is beside, like this: <select name="subs" id="subs"></select><label id="subn" for="subs"></label> Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)
{ "pile_set_name": "StackExchange" }
Q: Is there a publicly available instance of ArcGIS Server Are there any publicly available instances of ArcGIS Server for learning? I have searched Amazon EC2 but I don't see any public instances available (unless you already have an ArcGIS Server license). A: When you say instances, I am assuming you mean to hook into and actually play with the back-end as opposed to work against the actual services that ArcGIS Server dishes out? There are some Esri AMI templates available for you to spawn your own AWS instances up to play around with. Assuming you have an Amazon account setup, you will need to request access to the Esri AMIs from their Customer Service team. See their quick start guide for more info. If you are on maintenance or on their EDN programme, this will allow you access to these templates. You will need to bring your own ArcGIS Server license to the instance as well. There may well be some custom AMI templates with ArcGIS Server on, and provided by 3rd parties, and searchable on the AWS AMI catalog. However, same applies, you will still need to bring your own license. If it is just the services you need to work against, check out their sampleservers.
{ "pile_set_name": "StackExchange" }
Q: How do i send enum string values to client I have defined an enum as following. public enum Month { January, February, March, April, May, June, July, August, September, October, November, December } I am getting and sending it back to client. public List<Month> GetMonths() { return Enum.GetValues(typeof(Month)).Cast<Month>().ToList(); } However, I am receiving 0,1,2,3,....11 values at client end instead of actual string values i.e. month names. How i can send actual month name as values? A: You can use the GetNames method on Enum: public string[] GetMonths() { return Enum.GetNames(typeof(Month)); }
{ "pile_set_name": "StackExchange" }
Q: Typing a question ID in the search box doesn't "work" If I type question or answer ID into the search box, I would expect that to shortcut me to that question or at least a search results page with that answer/question. But it doesn't. A: uhh.. it already does that? https://meta.stackoverflow.com/search?q=33155
{ "pile_set_name": "StackExchange" }
Q: Are there surahs in the quran which state that the moon is lit by reflected sunlight? When I look up at the moon at night, it looks like a source of its own light just like the sun. surah 71:16 expresses this observation as: And made the moon therein a [reflected] light and made the sun a burning lamp? The [reflected] has been added and isn't part of the surah, so I'm looking for a surah that contains the word reflected or something similar to it. A: The Quran does not explicitly say that the moon is lit by reflected sunlight. Also see related answer.
{ "pile_set_name": "StackExchange" }
Q: Install python-glpk I want to install python-glpk I followed the instructions here: https://en.wikibooks.org/wiki/GLPK/Python But when I tried to do this: import glpk print glpk.glp_version() I have these errors Thank you A: Bug For Ubuntu 16.04 LTS it is known issue - it was reported to LaunchPad.net on 2016-10-02 as bug 1629672. Fix We can fix this bug by installation of previous version of python-ply component with pip into your home folder: #sudo apt-get install python-glpk # you did this before in question sudo apt-get install python-pip pip install ply==3.4 --user And then test it with simple script (name it glpk_test.py) with contents: #!/usr/bin/python2 import glpk print glpk.glp_version() then make it executable with chmod +x glpk_test.py and execute with ./glpk_test.py. The output on Ubuntu 16.04 LTS will be: 4.57
{ "pile_set_name": "StackExchange" }
Q: jQuery Json and Each There is my code: $.ajax({ url: "?module=gestionApplication&action=importScenario&fichierconf="+$fichierconf, dataType: "json", success: function( data ) { $( "#dialog-scenario input#fichierxml" ).val( data.FICHIERXML ); $( "#dialog-scenario input#fichierproxy" ).val( data.FICHIERPROXY ); $( "#dialog-scenario select#portail" ).val( data.PORTAIL ); $( "#dialog-scenario select#typemaj" ).val( data.MONITORING ); $( "#dialog-scenario input#periodemaintenance" ).val( data.MAINT ); $( "#dialog-scenario input#nomdns" ).val( data.DNSATESTER ); It works well, but i got like 40 lines of the same type is it possible to do the same action without knowing the string after data. ? I would do something like data.each( function(dataName) { $( "#dialog-scenario inputORselect#"+dataName ).val( data.dataname ); }); Thx for your help A: Create a map between the name of the element and the data property: var map, prop; map = { "typemaj" : "MONITORING", "periodemaintenance" : "MAINT" } Then you can loop through the properties to set their values. for( prop in map ) { $( "#dialog-scenario inputORselect#" + prop ).val( data[ map[prop] ] ); }
{ "pile_set_name": "StackExchange" }
Q: Meaning of the Poynting vector In a book I am studying, the Poynting vector is defined as: $$ \mathcal{P} = \mathbb{E} \times\mathbb{H} $$ and it is described the Poynting's theorem, that states that the flux through a surface wrapping a volume is the energy balance on that volume. In another part of the book, it says that the only thing that has a physical meaning is the flux of the Poynting vector, while the vector by itself hasn't it. This is because, if you add to the Poynting vector the curl of another vector, it will gave the same flux. $$ \mathcal{P}' = \mathbb{E} \times\mathbb{H} + \operatorname{curl}( \mathbb{F}) $$ $$ \Rightarrow\iint_Σ \mathcal{P}' \cdot n \, dS = \iint_Σ \mathbb{E} \times\mathbb{H} \cdot n\, dS = \iint_Σ \mathcal{P} \cdot n \, dS $$ Looking on the web, I found on the Wikipedia page about Poynting vector, in the section "Adding the curl of a vector field" that (for some reason I cannot fully understand since I have never had a course about special relativity) that the expression for the Poynting vector is unique. To me, this seems to give the Poynting vector a local meaning, not only to its flux through a surface. Is it true? What is this local meaning (if present)? Where can I look to start comprehend it better and more mathematically? $\mathbb{E} $: electric field $\mathbb{H} $: magnetic field $Σ$: generic closed surface $\mathcal{P} $: Poynting vector A: The Poynting vector itself represents the energy flux density of an electromagnetic field. In other words, its magnitude is the energy per unit area per unit time carried by the field at a particular location. Therefore, it has units of W/m^2. If you integrate its divergence over a surface, you obtain the total power radiated through that surface, which of course has units of W. As for the issue of adding the curl, note that it is a basic vector-calculus identity that the curl of any vector field has zero divergence. Therefore, it must contribute nothing to the integral of the divergence of the Poynting vector. However, we must be very careful in reading your Wikipedia article. The article says that adding a field to [the Poynting vector] which has zero divergence will result in a field which satisfies this required property of a Poynting vector field according to Poynting's theorem. It does not, however, say that the field that you get when adding the curl is still the energy flux density as computed with $\vec{E}\times\vec{H}$. If you add some weird random field, it will not represent the local energy flux density anymore, but it will still satisfy Poynting's theorem. In summary, adding a curl of some random field destroys the local meaning of the Poynting vector, but preserves the meaning of the surface integral of its divergence.
{ "pile_set_name": "StackExchange" }
Q: Is using __PACKAGE__ inside my methods bad for inheritance? If inside my code I'll have calls like: __PACKAGE__->method; will this limit the usability of this module, if this module is inherited? A: It depends on what you want to do: #!/usr/bin/perl package A; use strict; use warnings; sub new { bless {} => $_[0] } sub method1 { printf "Hello from: %s\n", __PACKAGE__; } sub method2 { my $self = shift; printf "Hello from: %s\n", ref($self); } package B; use strict; use warnings; use parent 'A'; package main; my $b = B->new; $b->method1; $b->method2; Output: Hello from: A Hello from: B A: If you intend to inherit that method, call it on the referent and don't rely on the package you find it in. If you intend to call a method internal to the package that no other package should be able to see, then it might be okay. There's a fuller explanation in Intermediate Perl, and probably in perlboot (which is an extract of the book). In general, I try not to ever use __PACKAGE__ unless I'm writing a modulino. Why are you trying to use __PACKAGE__? A: That depends. Sometimes __PACKAGE__->method() is exactly what you need. Otherwise it's better to use ref($self)->class_method() or $self->method().
{ "pile_set_name": "StackExchange" }
Q: how to change constants of class in Magento\Framwork? I'm newbie. My boss want to increase value of this const: const MAX_NUM_COOKIES = 50; path: vendor/magento/framework/Stdlib/Cookie/PhpCookieManager.php is it possible? if yes, which's the best way to do that? A: First, your boss should be aware of the implications: incompatibility with several more or less outdated browsers, depending on much you increase it. Especially IE 11 and lower have the 50 Cookie per domain limit and still a relevant market share. See: http://browsercookielimits.squawky.net/ Also from that site: If you want to support most browsers, then don't exceed 50 cookies per domain, and don't exceed 4093** bytes per domain (i.e. total size of all cookies <= 4093 bytes). How to change a constant Now, for the question: you cannot change constants themselves, you will have to find where they are used and find a way to change the usage. Most of the time, this will work with a plugin/interceptor (see: http://devdocs.magento.com/guides/v2.1/extension-dev-guide/plugins.html) Your case In your case, there's only one usage of the constant and it's in the PhpCookieManager class itself, in checkAbilityToSendCookie(). Unfortunately this is a private method which cannot be pluginized, so let's see where it is used: deleteCookie() setCookie() setCookie() is protected, so again, you cannot write a plugin for it. It's used in all remaining public methods and I don't see a way to change the checkAbilityToSendCookie() call without replacing the methods altogether. That means it is easier and more sensible to replace the whole class. You can do that with preferences (see: http://devdocs.magento.com/guides/v2.1/extension-dev-guide/build/di-xml-file.html) <preference for="Magento\Framework\Stdlib\Cookie\CookieManagerInterface" type="YourNamespace\YourModule\PhpCookieManager" /> Your own PhpCookieManager then should be a full copy of the original one, but with the constant changed. Note that this only works because the constant is used in the class itself. Constants are referred by the exaxt class name and the DI system of Magento cannot change anything about it.
{ "pile_set_name": "StackExchange" }
Q: Naming global variables in a structured way My current project has global constants that define certain rows and columns in workbooks that this project will be searching through. I have defined them as such: Public Const headRow As Integer = 1 Public Const descRow As Integer = 2 Public Const pnumCol As Integer = 1 Public Const teamCol As Integer = 2 Public Const dateCol As Integer = 3 Public Const hourCol As Integer = 4 Public Const typeCol As Integer = 5 Public Const taskCol As Integer = 6 Public Const noteCol As Integer = 7 I'm wondering if there is a cleaner way to define these that would allow me to write these in a way such as: ColumnNums.team ColumnNums.task ColumnNums.note 'etc I think something similar to this could be done by defining my own type, but that would probably not be worthwhile. I'm basically wanting this to be an easy way to remember the variable names as I write more code, as well as to be able to count how many items I have in each group. Would a Type or Collection be useful in this case? A: For mixed variable types, you can put it in a class module, name the class module ColumnNumbers and put the following code in: Public Property Get Team() As Long Team = 1 End Property Public Property Get TeamName() As String TeamName = "Team One! :-)" End Property Then you can use it in any module like this: Dim colNums As New ColumnNumbers Sub foo() MsgBox colNums.Team End Sub If you only want to return long values, put it in an enum: Enum ColumnNumbers Team = 1 Description = 2 End Enum Sub foo() MsgBox ColumnNumbers.Team End Sub Chip pearson has already done a fantastic job of describing enums here it's worth a read if you have yet to discover them.
{ "pile_set_name": "StackExchange" }
Q: Using AngularJS 1.2.16, unique issue with data escaping for href links having issues with ng-href i can use target="_blank" using AngularJS 1.2 ,old post but found what is going on leading me to another question,I have a page that has a table inside an accordian, in the JS file i have my angular functions and i have this: var CapitalRequestMultiMillInquiryController = function ($scope, $rootScope, $modal, $window, CapitalRequestService, PlantService) { $rootScope.title = 'Capital Request Multi Mill Inquiry'; $scope.allMills = []; $scope.selectedMill = ''; $scope.jobNumber = ''; $scope.description = ''; $scope.amount = ''; $scope.amountOperator = ''; $scope.openOnly = ''; $scope.projectManager = ''; //$scope.allUsers = []; //UsersService.getUsersWithId().then(function(objectTypes) { // $scope.allUsers = objectTypes //}); //$scope.openurl = function() { // $scope.openurl = function(url) { // $location.path(url, '_blank') // } //} PlantService.getPlantId().then(function (mills) { $scope.allMills = mills }); $scope.search = function() { //for each mill CapitalRequestService.searchMulti("http://coucmmsweb.pca.com/CapitalRequest/Search", authenticatedUser.userName.toUpperCase(), $scope.selectedMill, $scope.jobNumber, $scope.description, $scope.amount, $scope.amountOperator, $scope.openOnly, $scope.projectManager).then(function (results) { $scope.counce = results; }); CapitalRequestService.searchMulti("http://filcmmsweb.pca.com/CapitalRequest/Search", authenticatedUser.userName.toUpperCase(), $scope.selectedMill, $scope.jobNumber, $scope.description, $scope.amount, $scope.amountOperator, $scope.openOnly, $scope.projectManager).then(function (results) { $scope.filer = results; }); CapitalRequestService.searchMulti("http://tomcmmsweb.pca.com/CapitalRequest/Search", authenticatedUser.userName.toUpperCase(), $scope.selectedMill, $scope.jobNumber, $scope.description, $scope.amount, $scope.amountOperator, $scope.openOnly, $scope.projectManager).then(function (results) { $scope.tomahawk= results; }); CapitalRequestService.searchMulti("http://tridentval.pca.com/api/Inquiry/Inquiry/CapitalRequestMultiMillInquiry/Search", authenticatedUser.userName.toUpperCase(), $scope.selectedMill, $scope.jobNumber, $scope.description, $scope.amount, $scope.amountOperator, $scope.openOnly, $scope.projectManager).then(function (results) { $scope.valdosta = results; }); CapitalRequestService.searchMulti("http://tridentder.pca.com/api/Inquiry/Inquiry/CapitalRequestMultiMillInquiry/Search", authenticatedUser.userName.toUpperCase(), $scope.selectedMill, $scope.jobNumber, $scope.description, $scope.amount, $scope.amountOperator, $scope.openOnly, $scope.projectManager).then(function (results) { $scope.deridder = results; }); } }; and my HTML page i have this: <tbody> <tr ng-repeat="item in tomahawk"> <td>{{item.projectManager}}</td> <td>{{item.jobNumber}}</td> <td>{{item.description}}</td> <td>{{item.totalAmount*1000 | currency}}</td> </tr> </tbody> </table> and i still have this in my view which leads me to believe that the URL that this is getting information from has an anchor tag that isnt displaying the data correctly because i am using angular on this end. how would i escape the angular contraints for href's such that my data will display normally and be clickable to download a picture on next page? i posted another post earlier and thought that something was up with this end. but i remover everything and saw that it was still returning the anchor tag in my display which means its where the source is and its pushing that to me. the picture below is an older picture they are not clickable when i take everything out of my app on my end, leaving just a table pulling in the data. A: You'll need to let Angular know that the data you have is trusted HTML, and bind it to the td elements. In your controller, you'll need to use $sce to replace the HTML with trusted HTML: CapitalRequestService.searchMulti("http://tomcmmsweb.pca.com/CapitalRequest/Search", authenticatedUser.userName.toUpperCase(), $scope.selectedMill, $scope.jobNumber, $scope.description, $scope.amount, $scope.amountOperator, $scope.openOnly, $scope.projectManager).then(function (results) { $scope.tomahawk = results; $scope.tomahawk.forEach(function(item){ item.jobNumber = $sce.trustAsHtml(item.jobNumber); item.description = $sce.trustAsHtml(item.description); }); }); And in your view <tbody> <tr ng-repeat="item in tomahawk"> <td>{{item.projectManager}}</td> <td ng-bind-html="item.jobNumber"></td> <td ng-bind-html="item.description"></td> <td>{{item.totalAmount*1000 | currency}}</td> </tr> </tbody> </table> Edit: I changed the for-loop to a forEach iteration, simply because it seems a little cleaner. Check my edit history if you want the way it was before.
{ "pile_set_name": "StackExchange" }
Q: useless pin_ptr while copying array I have some legacy code, which copy a native array into a managed one: float* nativeValues = new float[NumberOfSamples]; array<double>^ managedValues = gcnew array<double>(NumberOfSamples); pin_ptr<double> pinnedValues = &managedValues[0]; for (int i = 0; i < managedValues->Length; i++) { nativeValues[i] = (float) pinnedValues[i]; } I can't refactor it with Runtime::InteropServices::Marshal::Copy because the original array is double and the target one is float. My problem is I don't get why the pin_ptr. I dont' think is needed but its a critical piece of code and I'd like to be sure before removing it. Do you think is it safe to remove it? A: The pin_ptr would be needed if you were going to pass the pin_ptr directly to an unmanaged API as a double*. void SomeUnmanagedAPI(double* data, int length); // Example of where pin_ptr would be needed. pin_ptr<double> pinnedValues = &managedValues[0]; SomeUnmanagedAPI(pinnedValues, managedValues->Length); For either the manual copy, or the Marshal::Copy, it's not needed. Go ahead and remove it, and just iterate over managedValues.
{ "pile_set_name": "StackExchange" }
Q: Trying to add a column of logicals by looping over time in a tibble in R I started replicating the value factor used by Fama and French in r to build a portfolio strategy for my final dissertation. I have a dataset of monthly market caps from the S&P 500 over the years. I created a loop to determine whether the variable (mkt cap) of a determined observation at a certain date is higher or lower than a certain threshold computed cross-sectionally at the same time (across all the observations of the variable mkt cap at time t). To achieve this, I thought the appropriate technique to be a for loop. In this way for each date I calculate the threshold and check the criteria. Unfortunately I am not able to store the logical during the loop. When I print the results I can see what I would like to store but when I try to store I get only the results related to the last step of the loop. for(d in dates$date){ month <- data_tbk %>% filter(date==d) up <- quantile(month$mktcap, 0.8, na.rm=TRUE) low <- quantile(month$mktcap, 0.2, na.rm=TRUE) data_tbk %>% filter(date==d) %>% mutate(ptf=ifelse(mktcap>=up,1,ifelse(mktcap<=low,0,NA))) %>% print } Another way I tried to pursue is the following but I got even less: data_tbk$ptf <- NA for(d in dates$date){ month <- data_tbk %>% filter(date==d) up <- quantile(month$mktcap, 0.8, na.rm=TRUE) low <- quantile(month$mktcap, 0.2, na.rm=TRUE) data_tbk %>% filter(date==d) %>% filter(mktcap>=up) %>% ptf=1 filter(data_tbk, date==d) %>% filter(mktcap<=low) %>% ptf=0 } How should I change the codes to get a column containing the logical 1 or 0 according to the criteria? A: You won't need a loop. Assuming your dataframe is data_tbk, this code will create new variable is_higher. 1 if mktcap more then Q80%, 0 if less than Q20%, and NA for the rest. library(dplyr) data_tbk <- data_tbk %>% mutate(is_higher = case_when( mktcap > quantile(mktcap,0.8) ~ 1, mktcap <= quantile(mktcap,0.2) ~ 0, TRUE ~ NA) ) If you expect to calculate quantile per date, then add group_by clause. data_tbk <- data_tbk %>% group_by(date) %>% mutate(is_higher = case_when( mktcap > quantile(mktcap,0.8) ~ 1, mktcap <= quantile(mktcap,0.2) ~ 0, TRUE ~ NA) ) PS. You need to install package dplyr install.package("dplyr")
{ "pile_set_name": "StackExchange" }
Q: How can I change serenity-bdd log settings I use Serenity BDD for test automation on my project, IntelliJ IDEA as IDE. I would like to change format and debug level of the logs I can see everytime I run tests. For example, I want to see logs only from [main] thread: [main] INFO net.thucydides.core.reports.junit.JUnitXMLOutcomeReport [pool-3-thread-1] INFO net.thucydides.core.reports.ReportService - I know how to do it for logback, but I can't find any info on how and where one should change log settings for Serenity. A: The output is produced by code you are testing not by Serenity BDD. So in order to modify output you should be changing logging properties of the logger you use. slf4j is a logging facade, it finds proper logger and redirect output to it. So you need to add a logger to your application and then configure it the way you like. For example, adding logback to your configuration. Add it logback as dependency to a project <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.3</version> </dependency> add src/test/resources/logback-test.xml to guide what logback should be logging. <?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern> %-5level %logger{36} - %msg%n </Pattern> </layout> </appender> <!-- set DEBUG logging level for a package --> <logger name="com.my.package" level="debug"> <!-- log warnings and errors by default --> <root level="warn"> <appender-ref ref="STDOUT" /> </root> </configuration> This configuration will log warnings and error to console. And will log also debug and info messages for package com.my.package. If you don't like logback, use log4j2 or any other logger of your choice.
{ "pile_set_name": "StackExchange" }
Q: Project Euler 22: Names scores by Loki 2 Alternative to Project Euler 22 solution. Project Euler 22 Slightly more brittle than the original. This code depends on the input stream being exactly as specified. But on the other side of the coin it's slightly easier to read because you don't have to wonder about std::locale and code that uses facets like std::ctype<> (which few people understand how to use). Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? #include <iostream> #include <fstream> #include <iterator> #include <string> #include <set> #include <numeric> long scoreName(std::string const& name) { return std::accumulate(std::begin(name), std::end(name), 0L, [](long v1, char x){return v1 + x - 'A' + 1;}); } struct FirstName { // Read a name from a stream. // Each name is quoted and separated with comma. // There are no extra spaces on the stream. // Sample: "DEBBIE","APRIL","LESLIE","CLARA","LUCILLE","JAMIE" std::string name; // Read the next name from the input. // Note does not remove quotes. friend std::istream& operator>>(std::istream& s, FirstName& data) { return std::getline(s, data.name, ','); } // When we convert this object to a std::string // we remove the quotes around the name. In the code // below this happens as the iterator is de-reference into the set. operator std::string() const { return name.substr(1, name.size() - 2); } }; Thus leaving a very simple main. int main() { std::ifstream data("euler/e22.data"); std::set<std::string> names{std::istream_iterator<FirstName>(data), std::istream_iterator<FirstName>()}; long score = 0; long loop = 1; for(auto name: names) { score += (loop * scoreName(name)); ++loop; } std::cout << score << "\n"; } A: std::accumulate with a lambda is quite a bit more complicated than writing out the range-for-loop manually, and it isn't even more concise: long result = 0; for(char c : name) result += c - 'A' + 1; return result; Using a std::set instead of a std::vector and sorting it once manually after reading everything in is possibly a bit less efficient. The really interesting part though is that duplicates are silently discarded, and the problem-statement doesn't seem to allow that. Your range-for-loop in main needlessly copies every string. Better go for references even though that's slightly longer: for(const auto& name: names) Inserting a single char instead of a length-1 string is probably slightly more efficient.
{ "pile_set_name": "StackExchange" }
Q: Is there a good javascript WYSIWYG tool that uses absolute positioning? I'm building a site where users (with no knowledge of html/css) will custom-design simple static HTML pages. Years ago, I used a CMS that used absolute positioning with drag and drop for designing static pages, and it was a fantastically easy UI for anyone to grasp. I'm wondering if there's a javascript solution for this that I could implement in my new site. It would need the basic bold, italic, font size, image uploads available in something like TinyMCE, but I'd also like for elements to be positioned absolutely by the user. Anyone know of such a solution? JQuery solutions are fine, since I'm using JQuery anyway on the site. I'd prefer not to have to load in a second framework. A: I know of no specific solutions. I wonder if you implement a jquery drag and drop plugin, on the drop you could get the dropped coordinates and dynamically create a CSS file for the dropped element containing those absolute coordinates.
{ "pile_set_name": "StackExchange" }
Q: Is the coefficient of restitution frame independent and energy conservation? In this question I am ignoring relativistic effects. The following statements I think are true: change in Kinetic energy is not invariant under change of frame Force is invariant under change in frame Change in velocity and relative velocity between two particles is invariant under change of frame The coefficient of restitution is given by $e=|\frac{v_1-v_2}{u_1-u_2}|=\sqrt{1-\frac{\Delta E}{T'}}$ where $\Delta E$ is the change in kinetic energy in the frame we are in and $T'$ is the initial kinetic energy in the centre of mass frame. So here is my problem. If 2. is correct work done is invariant and therefore from the work energy theorem 1. must be wrong (since w.d=change in kinetic energy). If both 1 and 3 are right then 4. must be wrong as the first equation for e would stay the same under change of frame whilst the second would change. Please can you explain which of these expressions is wrong, thanks. A: The first statement is wrong. The total energy of a body changes with frame but the change in kinetic energy does not. It is constant. This statement can also be viewed as the fact that conservation of energy is valid on all inertial frames.
{ "pile_set_name": "StackExchange" }
Q: Why SmtpClient SendAsync throws Exceptions with combinations of UseDefaultCredentials and EnableSsl, while Send works fine I'm using the System.Net.Mail. There are some topics around this area, but they are ASP.NET and often VB related. I'm isolating the code into a desktop skeleton code, I use .NET 3.5 and C#. So Send works in all scenario what I tried (EnableSsl false/true, UseDefaultCredentials false/true). But SendAsync only works if UseDefaultCredentials is not set to true (turns out that it can even matter if you explicitly set it to false, it's false by default), EnableSsl is true (OK, that can be server settings too), and hard-code my credentials. I want to be able to SendAsync using UseDefaultCredentials. Code: void sendmail() { MailMessage email = new MailMessage(); email.From = new MailAddress("tcs@software.com"); email.To.Add("tcs@software.com"); email.Subject = "Simple test email subject"; email.Body = "Simple test email body"; string mHost = "mail.software.com"; string mUsername = @"DOMAIN\tcs"; string mPassword = "myfreakinpassword?Really???"; SmtpClient smtpCli = new SmtpClient(mHost); //smtpCli.UseDefaultCredentials = true; smtpCli.Credentials = new NetworkCredential(mUsername, mPassword); smtpCli.EnableSsl = true; smtpCli.SendCompleted += smtpCli_SendCompleted; try { //smtpCli.Send(email); smtpCli.SendAsync(email, null); // This mofo only works in this combination } catch (Exception ex) { Console.WriteLine(ex); } } void smtpCli_SendCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Error != null) Console.WriteLine(e.Error); } A: Use messaging pattern like Prism's EventAggregator (specifying ThreadOption.BackgroundThread). This way the caller sends a message (the message would contain From, To, Subject, Body), and it is asynchronous from the sender's point of view. Then use the synchronous Send function of System.Net.Mail in the consumer/handler of the message. This probably works because the executing background thread has more proper privileges than the one spawns the SendAsync.
{ "pile_set_name": "StackExchange" }
Q: ggplot2: plot all attributes per id I have a survey where each line represents a person and each column represents how long they took to complete the survey I would like to plot a dot per timing per person so that if for example a person they completed the first part x1 in 10 minutes and the second part x2 in 12 minutes, the third part in 15 minutes x3 and the fourth part in 45 minutes x4 for ID 1 they would have these 4 dots on the y axis where the ID is the X Axis point id <- sample(1:12) x1 <- sample(1:250, 12, replace=F) x2 <- sample(1:250, 12, replace=F) x3 <- sample(1:250, 12, replace=F) x4 <- sample(1:250, 12, replace=F) mydf <- data.frame(id,x1,x2,x3,x4) I tried using ggplot where i specified the x axis as the ID but im not sure how to represent all the other columns as different counts Does anyone know if this is possible Any help would be great A: I believe we need to melt your data.frame first and then construct your desired plot. library(reshape2) melted <- melt(mydf, id.vars = "id") # Melt data # Generate plot library(ggplot2) ggplot(melted, aes(factor(id), value, colour = variable)) + geom_point()
{ "pile_set_name": "StackExchange" }
Q: Print lines from one file that are not contained in another file I wish to print lines that are in one file but not in another file. However, neither files are sorted, and I need to retain the original order in both files. contents of file1: string2 string1 string3 contents of file2: string3 string1 Output: string2 Is there a simple script that I can accomplish this in? A: fgrep -x -f file2 -v file1 -x match whole line -f FILE takes patterns from FILE -v inverts results (show non-matching) A: In Perl, load file2 into a hash, then read through file1, outputing only lines that weren't in file2: use strict; use warnings; my %file2; open my $file2, '<', 'file2' or die "Couldn't open file2: $!"; while ( my $line = <$file2> ) { ++$file2{$line}; } open my $file1, '<', 'file1' or die "Couldn't open file1: $!"; while ( my $line = <$file1> ) { print $line unless $file2{$line}; } A: awk 'FNR==NR{a[$0];next} (!($0 in a))' file2 file1
{ "pile_set_name": "StackExchange" }
Q: How can I create an empty sql.Rows instance? I have a function that returns (*sql.Rows, error) in Go. Under some circumstances, there's nothing to return, but also no error. The choices seems to be: if (...) { return nil, nil } and then, in the caller: rows, err := fn() if err != nil { return nil, err } if rows == nil { ... } else { for rows.Next() { ... } } or else returning a special error which I then check for. I think it would be a lot more elegant if I could return a valid Rows instance, but that does nothing but return false when its Next() method is called, like this: if (...) { return EmptyRows(), nil } and, in the caller: rows, err := fn() if err != nil { return nil, err } for rows.Next() { ... } I could do something like: if (...) { return db.QueryRows("select * from something where true=false"), nil } but that seems pretty goofy. Any recommendations? A: I would handle this a little differently, and just pass in the handler to your function. So if your function is currently: func YourFunc() (*sql.Rows, error) { // ... if (...) { return nil, nil } return rows, nil } It would have it be: func yourFunc() (*sql.Rows, error) { // ... if (...) { return nil, sql.ErrNoRows } return rows, nil } func YourFunc(cb func(*sql.Rows)) error { rows, err := yourFunc() if err == sql.ErrNoRows { return nil } if err != nil { return err } cb(rows) return nil } And then in your caller: err := YourFunc(func(row *sql.Rows) { for rows.Next() { // ... } }) This will have the function you pass only get called if there are rows, you get the error if it's one you care about, and the caller's syntax is pretty clean.
{ "pile_set_name": "StackExchange" }
Q: get all table names with the primary key row count I have a scenario, where I need to compare data between two servers. Long story short, I need a result set which gives the output like SchemaName|TableName|RowCount_PrimaryKey Whenever a new student joins a unique schema is created say Stu1200 and this schema has 5 tables like stu1200.class stu1200.sub stu1200.avg stu1200.work stu1200.blabla There are 500 students in our database. So 500 schema. I need to compare all the tables of work of 500 students. In order to do so I need to get the counts of the primary key, say StuID. So I need to get all the 500 schemas with the table like work. Something like SchemaName TableName StuID_Count stu1200 Work 70 Stu1201 Work 112 Stu1202 Work 9 How can this be done? I have a script which does row counts of the table but its of useless, I need the row counts based only on the primary key. Note: using SQL Server 2000 :( Thanks in advance for sharing your suggestions/experience. A: Your design is highly questionable but here is a way to get a relatively up-to-date count in an efficient manner. In SQL Server 2005+: DECLARE @tablename SYSNAME; SET @tablename = N'Work'; SELECT SchemaName = OBJECT_SCHEMA_NAME([object_id]), TableName = @tablename, RowCount_PrimaryKey = SUM([rows]) FROM sys.partitions WHERE OBJECT_NAME([object_id]) = @tablename AND index_id IN (0,1) GROUP BY OBJECT_SCHEMA_NAME([object_id]) ORDER BY SchemaName; Just noticed SQL Server 2000. DECLARE @tablename SYSNAME; SET @tablename = N'Work'; SELECT SchemaName = u.name, TableName = @tablename, i.rows FROM sys.sysindexes AS i INNER JOIN sys.sysobjects AS o ON i.id = o.id INNER JOIN sys.sysusers AS u ON o.uid = u.uid WHERE i.indid IN (0,1) AND o.name = @tablename;
{ "pile_set_name": "StackExchange" }
Q: Cordova/Android: change app banner color (NOT status bar) I am currently using Apache Cordova to experiment with all of it's capabilities. I can't seem to find out how to change the banner that appears when you tap the "view open application" option on android. How do I change the color of the banner seen here? A: I didn't seem to have any of the files needed to change the banner, so I opted to use a plugin to do this: https://github.com/tomloprod/cordova-plugin-headercolor (and it works)
{ "pile_set_name": "StackExchange" }
Q: How to get jquery append to only append at the bottom of the element and not multiple times When using append the element that I add is added several times to my page. From what I understand append adds to all appended elements which is why it is appending several times. I tried using clone, but had no success. What is the workaround. Here is my code Script <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#Test').click(function(){ //this is the method that call append $('#Get_Id').submit(function(event){ event.preventDefault(); var $form = $( this ); url = $form.attr( "action" ); $.get( url, function(data){ console.log(data); user_data = data; var html = `<div class="note"> <p>${data[0].note}</p> <form action="/delete/${data[0].id}" method="post" id="delete_note"> <input type="submit" name="submit" value="Delete" class='delete'/> </form> <form action="/AddDescription/${data[0].id}" method="post" class="update_note"> <label asp-for="Description" >Description</label> <textarea name="Description" id="" cols="30" rows="10" class="Description">${data[0].description}</textarea> <input type="submit" name="submit" class="update" value="Update"/> </form> </div>` $('.added_notes').append(html); }); }); }); }); }); </script> Html @model ajaxNotes.Models.Home <div class = "notes"> @{ if(ViewBag.Notes != null) { foreach(var note in ViewBag.Notes ) { <div class = "note"> <p>@note.Note</p> <form action="/delete/@note.Id" method="post" id="delete_note"> <input type="submit" name="submit" value="Delete" class='delete'/> </form> <form action="/AddDescription/@note.Id" method="post" class="update_note"> <label asp-for="Description" ></label> <textarea name="Description" id="" cols="30" rows="10" class="Description">@note.Description</textarea> <input type="submit" name="submit" class="update" value="Update"/> </form> </div> } } } </div> <div class="added_notes"> </div> <form asp-controller="Home" asp-action="AddNote" method="post" id="New_Note"> <label asp-for="Note" ></label> <p><input asp-for="Note" class = "Note" name="Note"/> </p> @{ if(ViewData["error"] != null) { <p>Please enter data for Notes</p> } } <button type="submit">Add Note</button> </form> <form asp-controller="Home" asp-action="GetLastEntry" method="post" id="Get_Id"> <label asp-for="Note" ></label> <p><input asp-for="Note" class = "Note" name="Note"/> </p> @{ if(ViewData["error"] != null) { <p>Please enter data for Notes</p> } } <button type="submit" id = "Test">Add Note</button> </form> A: Your use of "click" and "submit" is redundant here. The button acts as a submit trigger so choose one. The problem is created when you do $("button").on("click", function(e) { // this creates a new binding on click $("form").on("submit", function(e) { }); }); You are creating duplicate binding for "submit" and this multiplies on each click. Hence the duplicate appending.
{ "pile_set_name": "StackExchange" }
Q: js/css add multiple backgrounds i have seen several usages of the .css() function or simply setting element.style.background in js what i want is to stack multiple backgrounds, ie add another background over the 1st one. i tried input.style.background.add("white url('http://cssdeck.com/uploads/media/items/5/5JuDgOa.png') no-repeat 30px 6px;"); but the add function is not recognized : TypeError: input.style.background.add is not a function i guess i could set the css after onload with "background1", then reset it as "background1, background2" and back to "background1" when i need to but i would prefer an add() / remove() approach A: why not create a few classes : .bg-1{bg-img ...1} .bg-2{bg-img ...2} and use .addClass('bg-1'); and .removeClass('bg-x'); etc... with a js function with the wanted delay Warning : Jquery functions apply to jquery objects, for you : $(input).addClass('some-class');
{ "pile_set_name": "StackExchange" }
Q: Full width mega menu on desktop within a Bootstrap Container I'm trying to create a mega menu that lives within the navigation list element but at the same time the mega menu needs to span the full width of the page. I'm stuck in that the mega menu is relative to where it's parent resides. The mega menu is aligned to the first nav item, where I want it flush to the left edge of the whole page. Is there a non JS solution to this? The attached image shows what I currently have. Link to a quick fiddle: <div class="header"> <div class="container"> <div class="row"> <div class="col-xs-3 logo">Logo</div> <div class="col-xs-6 nav"> <ul> <li> <a href="#">Link 1</a> <div class="mega-menu"> This needs to be full width. </div> </li> <li><a href="#">Link 1</a></li> <li><a href="#">Link 1</a></li> </ul> </div> <div class="col-xs-3 secondary-nav">Other links</div> </div> </div> </div> .header { width: 100%; } .container { background-color: #ccc; max-width: 500px; margin-left: auto; margin-right: auto; } .nav ul { display: inline-block; } .nav ul li { display: block; float: left; margin-right: 20px; } .nav ul li a { background-color: #888; color: #fff; } .nav .mega-menu { background-color: #aaa; display: block; height: 500px; position: absolute; top: 35px; width: 100vw; } A: add these two lines to your .nav .mega-menu's css: .nav .mega-menu { position: fixed; left: 0px; } jsfiddle: https://jsfiddle.net/n2oodnrz/23/
{ "pile_set_name": "StackExchange" }
Q: Error: Objects are not valid as a React child, prop not returning in React Hook I am receiving an error when trying to return ( <div id="info_side">{info}</div> ) below. I have a _onClick function that works and I can console log info if I do not include {info} anywhere in the return. How can I fix this? Here is the error: Error: Objects are not valid as a React child (found: object with keys {type, _vectorTileFeature, properties, layer, source, state}). If you meant to render a collection of children, use an array instead. Update Had to convert the object to an array and then map the key values and it now works. const _onClick = event => { const display = event.features; if (display.length > 0) { setInfo(display[0].properties) } } var list = Object.entries(info).map(([key,value]) => { return ( <div><span className="bold">{key}</span>: <span>{value.toString()}</span></div> ) }); return ( <div id="info_side">{list}</div> ) Original Post const App = () => { const [viewport, setViewport] = useState({longitude: -98.58, latitude: 39.83, zoom: 3.5}) const [locations, setLocations] = useState([]) const [geojson, setGeojson] = useState(null) const [size, setSize] = useState({value: "All"}) const [info, setInfo] = useState([]) useEffect(() => { setLocations(geodata) _updateLocationData(size.value) }, [locations]); useEffect(() => { setInfo(info); }, [info]); const _updateViewport = viewport => { setViewport(viewport) } const _updateData = event => { setSize({value: event.target.value}) _updateLocationData(event.target.value) } const _updateLocationData = (sizeValue) => { var tempLocations = []; locations.forEach(function(res) { if (sizeValue === "All") { tempLocations.push(res); } else if (res.Size === sizeValue) { tempLocations.push(res); } }); var data = { type: "FeatureCollection", features: tempLocations.map(item => { return { id: ..., type: "Feature", properties: { Company: item.Company, Address: item.Address, Phone: item.Phone, Long: item.Long, Lat: item.Lat, Size: item.Size, }, geometry: { type: "Point", coordinates: [item.Long, item.Lat] } }; }) }; setGeojson(data); } const _onClick = event => { const { features } = event; const info = features && features.find(f => f.layer.id === 'icon'); setInfo(info); // Error: Objects are not valid as a React child (found: object with keys {type, _vectorTileFeature, properties, layer, source, state}). If you meant to render a collection of children, use an array instead. console.log(info) // I can see the object with no error here if I do not add {info} in return ( <div id="info_side">{info}</div> ) } return ( <div className="App"> <div className="inner-left map-container"> <ReactMapGL {...viewport} onViewportChange={_updateViewport} width="100%" height="100%" mapStyle={mapStyle} mapboxApiAccessToken={TOKEN} onClick={_onClick}> <Source id="my-data" type="geojson" data={geojson}> <Layer {...icon} /> </Source> <div style={navStyle}> <NavigationControl onViewportChange={_updateViewport} /> <select onChange={_updateData} defaultValue={size.value}> <option value="All">All</option> <option value="Large">Large</option> <option value="Medium">Medium</option> <option value="Small">Small</option> <option value="Very Small">Very Small</option> </select> </div> </ReactMapGL> </div> <div className="inner-right info-container"> <Nav /> <Search /> <div id="info_side"> // where is error is thrown if I have {info} below <div className="company">{info.properties.Company}</div> <div className="address">{info.properties.Address}</div> <div className="phone">{info.properties.Phone}</div> </div> </div> </div> ); } export default App; A: Info is an object, so you can't do this: <div id="info_side">{info}</div> Every time you use {} inside a DOM elemnet in React, the variable inside {} must a string, number or boolean. So you have to make sure you are using a primitive inside brackets. Try {JSON.stringify(info)} or any variable you want and you'll see what is the string represtabntion of that value.
{ "pile_set_name": "StackExchange" }
Q: How can I use lodash to filter value between two date? created_at is the value I Want to compare with the beginDate and the endDate. var newARRA = chain(this.props.transferts.transfertAccount) .filter({ 'officeSender': this.props.users.user.office,officeReceiver:this.state.selectedOffice, 'created_at':(this.state.beginDate,this.state.endDate)}) .groupBy("currency") .map((v, k) => ({ currency: k, amount: sumBy(v, 'fee') })) .value(); A: You'll need to use the filter's predicate function. Example (not tested): var newARRA = chain(this.props.transferts.transfertAccount) .filter(({ officeSender, officeReceiver, created_at }) => { return _.eq(officeSender, this.props.users.user.office) && _.eq(officeReceiver, this.state.selectedOffice) && _.gte(created_at, this.state.beginDate) && _.lte(created_at, this.state.endDate) && }) .groupBy("currency") .map((v, k) => ({ currency: k, amount: sumBy(v, 'fee') })) .value();
{ "pile_set_name": "StackExchange" }
Q: Get latest version in Chart.yaml I got the following Chart.yaml file for kubernetes: apiVersion: v1 description: Chart for installing myapp name: myapp version: 1.5.0 namespace: my-app How do I get the latest version without updating manually every new version? A: helm install myapp will always install latest available version of your chart from your chart repository. From documentation --version string specify the exact chart version to install. If this is not specified, the latest version is installed
{ "pile_set_name": "StackExchange" }
Q: Each array need an unique key in React JS I'm using React-Slick slider component for React JS, but I'm getting a warning that each array has to have an unique key. I have an array inside of settings for the slider component. Settings are : const settings = { dots: false, arrows: false, autoplay: true, autoplaySpeed: 4000, responsive: [ {breakpoint: 310, settings: {slidesToShow: 1, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000}}, {breakpoint: 468, settings: {slidesToShow: 1, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000}}, {breakpoint: 750, settings: {slidesToShow: 2, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000}}, {breakpoint: 800, settings: {slidesToShow: 2, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000}}, {breakpoint: 1200, settings: {slidesToShow: 3, slidesToScroll: 2, autoplay: true, autoplaySpeed: 4000}}, {breakpoint: 1800, settings: {slidesToShow: 4, slidesToScroll: 2, autoplay: true, autoplaySpeed: 4000}}, {breakpoint: 2600, settings: {slidesToShow: 5, slidesToScroll: 2, autoplay: true, autoplaySpeed: 4000}}, {breakpoint: 100000, settings: 'unslick'} ] }; And the slider component where I use those settings is : <Slider {...settings}> {this.cars()} </Slider> How can I map through those settings to give them an key? A: I think this is what you might need: ... render(){ var Cars = settings.responsive.map.function(car, index){ return(<div key={index}>YOUR CONTENT</div>); } return( <Slider {...settings}> {Cars} </Slider> ) } I want to add that the second parameter of the map function can be used as a unique index which suits the reacts requested key attribute perfectly Dirty solution: ... render(){ var counter = 0; var Cars = settings.responsive.map.function(car, index){ counter++; return(<div key={counter}>YOUR CONTENT</div>); } return( <Slider {...settings}> {Cars} </Slider> ) }
{ "pile_set_name": "StackExchange" }
Q: How to StartEdit in EditingPlugin in grid? I know row index and column name. But EditingPlugin need startEdit( Ext.data.Model record, Ext.data.Model columnHeader )</code>. How I can take it and give it back? A: For the record you can do record = grid.getStore().getAt(recordIndex); but for the column header, I dont' think you needed it since startedit requeres the column not its header. In the CellEditing plugin doc it says column header but it describes it as the column object. columnHeader : Ext.data.Model The Column object defining the column to be edited Provide a more detailed example giving the available local variables and I will try to gieve a solution for the column also.
{ "pile_set_name": "StackExchange" }