text
stringlengths
175
47.7k
meta
dict
Q: using an image for a button on php I have a php script which creates its own button, as I am using an open source framework. What I want is to use an image to create a button instead of a the link the is created. Here is the line for which I need the button: <td class="main button_marg"><?php echo tep_draw_button(IMAGE_BUTTON_REVIEWS . (($reviews['count'] > 0) ? ' (' . $reviews['count'] . ')' : ''), 'comment', tep_href_link(FILENAME_PRODUCT_REVIEWS, tep_get_all_get_params())); ?></td> That is the script I am using to create the review button, but I would like to insert an image into it. Any ideas would be most appreciative. This is the code for tep_draw_button() function: function tep_draw_button($title = null, $icon = null, $link = null, $priority = null, $params = null) { static $button_counter = 1; $types = array('submit', 'button', 'reset'); if ( !isset($params['type']) ) { $params['type'] = 'submit'; } if ( !in_array($params['type'], $types) ) { $params['type'] = 'submit'; } if ( ($params['type'] == 'submit') && isset($link) ) { $params['type'] = 'button'; } if (!isset($priority)) { $priority = 'secondary'; } $button = '<span class="tdbLink">'; if ( ($params['type'] == 'button') && isset($link) ) { $button .= '<a id="tdb' . $button_counter . '" href="' . $link . '"'; if ( isset($params['newwindow']) ) { $button .= ' target="_blank"'; } } else { $button .= '<button id="tdb' . $button_counter . '" type="' . tep_output_string($params['type']) . '"'; } if ( isset($params['params']) ) { $button .= ' ' . $params['params']; } $button .= '>' . $title; if ( ($params['type'] == 'button') && isset($link) ) { $button .= '</a>'; } else { $button .= '</button>'; } $button .= '</span><script type="text/javascript">$("#tdb' . $button_counter . '").button('; $args = array(); if ( isset($icon) ) { if ( !isset($params['iconpos']) ) { $params['iconpos'] = 'left'; } if ( $params['iconpos'] == 'left' ) { $args[] = 'icons:{primary:"ui-icon-' . $icon . '"}'; } else { $args[] = 'icons:{secondary:"ui-icon-' . $icon . '"}'; } } if (empty($title)) { $args[] = 'text:false'; } if (!empty($args)) { $button .= '{' . implode(',', $args) . '}'; } $button .= ').addClass("ui-priority-' . $priority . '").parent().removeClass("tdbLink");</script>'; $button_counter++; return $button; } ?> A: You can probably override the style by using some css: #your_button_id{ background: url(); height: x; width: x; etc... } .your_button_class{ background: url(); height: x; width: x; etc... }
{ "pile_set_name": "StackExchange" }
Q: How difficult are the plate-based wort chiilers to clean? Do they require filtration before the wort goes through them? I'm considering getting one of those "Therminator" style wort chillers as an upgrade to the coil. I plan on gravity feeding the wort through and pumping back into the kettle until my wort is nice and lukewarm. The specs seem impressive, but it also looks like this thing would be hell to clean, and a bit annoying to sanitize, and I can't help but think bits and pieces of hops would easily clog this thing. Am I being paranoid? A: Unless you're careful with filtering, plate chillers can and do clog up with debris. Any debris that's trapped during transfer needs to be backflushed out by connecting the wort inlet to the water supply. The high pressure usually pushes out most of the debris, but it's still necessary to bake the chiller in the oven every few batches, and maybe run caustic soda through it once a year to clean out any resident crud. Here's a pic of an unused shirron plate chiller cut open The amount of gunk trapped is usually it's not enough to significantly stop the flow, but I've had flow trickle to next to nothing on more than a few batches. For example, I recently tried whirpooling through the plate chiller, and flow ground to a tiny trickle after a few minutes. I was using hop-bags, but still hop pellets and trub can make it into the chiller. A hopback makes a great filter and pretty much stops any trub from reaching the chiller. You can build your own from a canning jar, or buy them ready made for about $125. I'm scaling up to 10 gallon batches and looking to buy a new chiller. I will pass on plate chillers this time round. Also from the same thread: I also pump a lot of water through mine after every brew and blow it out with compressed air (with inline oil filter). Then the day before each brew day I countercirculate caustic beer line cleaning solution with a pump designed for beer line cleaning. The output from the chiller (normally the input) dumps into a bucket and the pump sucks up solution from that bucket through a fine stainless steel strainer. At the end of a few minutes of this the solution has turned dark and the strainer is covered with material. After an hour of circulation the solution is much darker and the strainer has a remarkable amount of crud on it. IOW, there is still plenty of material left in the chiller and it's not soluble even in caustic (the crud on the screen does not dissolve). It's probably bits of hops petals that made their way into the system. I have to disassemble the thing one day and clean it properly but it's not a job I'm looking forward to. No infections so far (touch wood) so I guess my protocol has been successful thus far, at least.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET Development Server I have a solution that contains a number of projects. One is an asp.net project, and is set-up to use the asp.net development server. The other projects have nothing to do with asp.net: for example, some are windows services written in unmanaged c++, others are c# console applications. My problem is that if I start any of the non-asp.net projects in the debugger, Visual Studio still starts the asp.net development server. This causes problems when I am debugging program interactions using multiple instances of visual studio. When I debug the web application I do want the web server to start. I have noticed that when I debug a non-asp.net project, the asp.net development server is started using the port number and virtual directory specified in the asp.net projects properties. There are no project dependencies between these projects. Is there a way to tell visual studio to start the development server only for projects that actually specify that it should be used? Edit 1: To reproduce this behaviour: Using vs2010, create an empty solution. Add a c++ console application accepting all the defaults. Add a call to fgetchar() to the generated main() so that it doesn't immediately exit when it is run. Run the project in the debugger and notice that the asp.net development server does not start. Add an asp.net web application project to the solution, accepting all the defaults. Go to the project properties web tab and verify that it is configured to use the asp.net development server. Set the c++ console application to be the startup project, and then start the c++ project in the debugger. Notice that the asp.net development server now starts, even though the web application project is not running. Edit 2: Clarified that I want the server to start when I debug the web project, but not when I debug the other non-web projects. A: I have a solution that works for me. It appears that web projects have a property that controls whether the asp.net development server is started when the debugger starts, even if the web project is not itself being debugged. To change this property, select the web project in the solution explorer and press F4 to access a property grid. In the grid, under the heading Development Server, is a boolean property named Always Start When Debugging. The default value is true. When I set this property to false the asp.net development server no longer started when I debugged a non-web application project. The property is persisted in <ProjName>.csproj.user, not <ProjName>.csproj.
{ "pile_set_name": "StackExchange" }
Q: Nonconvex optimization problem I have a nonconvex optimization problem with a linear objective function, a set of linear constraints and a set of nonlinear, non-convex constraints. Is this problem NP-hard? If so, how can I prove this? A: In general, you can show that a class of problems is NP-Hard by taking a known NP-hard problem and reducing it to a problem in your class (being careful that size of the problem does not increase too much.) Since some well known NP-hard problems can easily be rewritten as nonlinear optimization problems with non-convex constraints, the class of non-convex nonlinear optimization problems is in general NP-Hard. However, this says nothing about your particular non-convex optimization problem.
{ "pile_set_name": "StackExchange" }
Q: Reloading an iframe in GWT I am currently working on a GWT project where I am displaying an HTML file within an iframe in my application. This HTML file is actually being written to as it is getting displayed, and I am hoping to be able to reload the frame so that the changes made to the HTML file are reflected on screen. I am able to do this two different ways that both work when running in development mode, however neither seem to work when the project is deployed. The first method I tried was setting the frame's URL to itself: frame.setUrl(frame.getUrl()); The second method I tried using JSNI: public native void refresh() /*-{ if($doc.getElementById('__reportFrame') != null) { $doc.getElementById('__reportFrame').src = $doc.getElementById('__reportFrame').src; } }-*/; When deployed, the frame gets displayed in a Window, and when the file is finished being written to, a call to either of these refresh methods is made, and the frame refreshes to contain the finished HTML file. When I am deployed, the call to refresh does not reload the contents of the frame, however if I bring up the frame's context menu (in Firefox), then go into 'This Frame', and click Reload, it successfully reloads the frame to contain the finished HTML file. I have tested this on multiple versions of Firefox without any luck. Does anyone have any suggestions? Why would the behavior be different from one mode to the other? Thanks. A: wow, google is really fast with his search^^ You can use some JSNI to do this. Create a method such as protected native void reloadIFrame(Element iframeEl) /-{ iframeEl.contentWindow.location.reload(true); }-/; Then call it with your iFrame element so your question you posted twice was already answerd here http://groups.google.com/group/google-web-toolkit/browse_thread/thread/64aa7712890652d3
{ "pile_set_name": "StackExchange" }
Q: MS Deploy task failed DeploymentBaseOptions does not contain a definition for UserAgent I am having trouble running a Team Foundation 2013 build with MS Build parameters for deployment and I am getting an error : C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets (4255): Web deployment task failed. ('Microsoft.Web.Deployment.DeploymentBaseOptions' does not contain a definition for 'UserAgent') Development is being done in VS 2013. What is strange is that if I copy the MSBuild folder *..\v11.0\Web* to the *v12.0\Web* The build works and does the deployment. I have already checked the v12.0\Web\Microsoft.Web.Publishing.targets file and there is an entry for UserAgent while in the v11.0\Web\Microsoft.Web.Publishing.targets there is no entry I am able to publish fine using VS Publish on my computer , but on the build server it fails Has anyone managed to build and deploy using MSBuild VS 2013 targets successfully? A: I faced the same issue. For me the solution was to install Web Deploy 3.5 (http://www.iis.net/downloads/microsoft/web-deploy). After that the error disappeared.
{ "pile_set_name": "StackExchange" }
Q: How can I initialize a default value of QComboBox without to click it? How can I initialize a default value of QComboBox without to click it? I tried with ui->combBox->setCurrentIndex(1); but when I read the value at first I get unfortunately a -1 and only after the QComboBox was clicked its value become 1. A: Are you sure there's at least two values in the QComboBox? Counting begins from 0, not 1. If you want to select the first value, you need to: ui->combBox->setCurrentIndex(0); If that's not the problem, and you indeed have two values in the combo box, then make sure that the ui has been set up first. This call needs to execute first: ui->setupUi(this); It's what actually fills the combo box with the values specified in the .ui file. A: I solved the problem. The ui->combBox->setCurrentIndex(1); was in constructor before connect(ui->combBox,SIGNAL(currentIndexChanged(int)).... @Nikos C. thank you very much for a good tip.
{ "pile_set_name": "StackExchange" }
Q: How to pass an additional parameter to CascadingDropDown ServiceMethod? I have two chained CascadingDropDowns. Both are working fine. The thing is that in the underlying web methods which are supplying values for DropDwonList I need read one additional parameter. This parameter is needed for setting up the default item for dropdownlist. I do not know how to pass that parameter or read it. I've read on the Internet about the ContextKey property. But I do not know how to acces it from the WebMethod. I've tried to get to the session through HttpContext.Current.Session (hoping that I could extract some parameter from the session) but it seams that the Session is different for the WebPage and WebMethod. So I am lost here, any ideas? A: You need three things to get the ContextKey to work. Set UseContextKey property on the CascadingDropDown to true Change the method signature of your webmethod to accept the contextKey parameter: public CascadingDropDownNameValue[] GetDropDownContents( string knownCategoryValues, string category, string contextKey) { ... } NOTE: The parameter has to be exact casing. Set the ContextKey using JavaScript. The AJAX CascadingDropDown exposes getter/setter for this property in the DOM: document.getElementById('idOfCDDL').set_contextKey('valueyouwant'); HTH.
{ "pile_set_name": "StackExchange" }
Q: Create Invisible Window in GTK#? I'm looking to create an invisible window for the processing of certain X events (sort of like NativeWindow in Winforms). Is this possible in GTK#? Or do I need to manually create such a window using P/Invoke to the X libraries? A: I'm not quite sure I understand what you're trying to do, but Windows in Gtk are invisible by default. If you never set the visibility to true: window.Visible = true; or if you explicitly set it to false: window.Visible = false; it will remain invisible. Edit: This is the real solution to Zach's problem: I just checked the GTK source code, and you can call Realize() on a GTK Window to make the GTK window create its corresponding GDK Window. The GDK Window is immediately hooked into the X server when it is created.
{ "pile_set_name": "StackExchange" }
Q: Image button inside a Data table I'm facing a scenario that i need to add image button inside a datatable. Is it possible to add an image button control inside a datatable. I'm using Framework 3.5 and C# language. Thanks In Advance! Regards, Ranga A: I think you are trying to work with a user interface control like a DataGrid or DataGridView. DataTable is an ADO.NET class for holding data from a database. It doesn't present data in a user interface, so adding an image button maes no sense. I presume you're working with a grid of some sort, but in order to get a sensible answer you need to tell us which one. Is your user interface WPF, Windows Forms, or ASP.NET? Specifically, which grid class are you trying to use?
{ "pile_set_name": "StackExchange" }
Q: Why can't armrests be raised on window and aisle seats? I noticed that armrests on all the flight's I've taken recently can't be lifted on aisle and window seats (the edges of a row). Last time I flew, I got lucky: I was alone on my row and as such I was able to lay down to sleep. However, it was hard to make myself comfortable as that armrest was pressing on my spine when I tried laying down with my back to the window. Also, it would be much easier to get out of my aisle seat if I could lift the armrest. I'm a pretty tall guy, so I always feel like a contortionist trying to get out of my seat. What's the problem with letting people raise the armrest on window and aisle seats? I'm guessing it's some sort of safety issue, because the mechanism seems to be the exact same one as the other seats, just with an extra locking mechanism added. A: Apparently, it can be done, atleast in some aircraft; even in those cases, the armrests are locked, unless one knows the location of the release button. As for why, it seems that there is a possibility that the upright armrests can be an obstacle (for people in the next seat row) and FAA expects the cabin crew to ensure that the armrests are in forward condition prior to takeoff/landing. According to FAA Volume 3, Chapter 33, Section 3 Instrument and Equipment Requirements, Inspection of the Hardman Model 9500 and other passenger seats installed on several aircraft, disclosed that the armrest in the upright or stowed position can protrude approximately 45 degrees aft the seat back. In the event of an emergency evacuation, protruding armrests could present an obstacle between seat passageways, obstructing emergency exit access. Air Carriers should emphasize to F/As that prior to takeoff and landing they verify that the armrests are in the normal forward/down position in order to ensure that they do not obstruct the passageway between the row of seats leading from the aisle to the emergency exit. As this is a problem in aisle seats (armrests in middle seats cannot go back usually), they have to be fixed forward or atleast locked in position. This is the reason for them to be locked in case of aisle seats. As for window seats, the sets are usually made in a row and you don't really know if the seat will end up in window or aisle i.e. whether the row will get fixed on left or right (or middle, in widebodies). Net result is that both the ends of the row are fixed just to be sure. In other words, the windows armrest is a collateral damage.
{ "pile_set_name": "StackExchange" }
Q: How to find Intersection of Two Collection in monogdb? Let say, I have 2 collection first one :- db.product_main { _id:123121, source_id:"B4456dde1", title:"test Sample", price: 250 quantity: 40 } which consist approx ~10000 objects (Array) and unique field is source_id. Second :- db.product_id { "_id":58745633, "product_id":"B4456dde1" } which consist of ~500 and only have field "product_id" which is equals to "source_id" of db.product_main now, i want to intersect two collection so that i only find those which don't exist in db.product_id. db.product_main.aggregate({any query}) A: Just use the lookup stage to find the products associated with the 'product_main' collection and then match for empty array (i.e. records where no product_id was found) db.product_main.aggregate([ { $lookup: { from: "product_id", localField: "source_id", foreignField: "product_id", as: "products_available" } }, { $match: { products_available: { $size: 0 } } } ])
{ "pile_set_name": "StackExchange" }
Q: H2o with predict_json: "Error: Could not find or load main class water.util.H2OPredictor"? I tried to use the H2o predict_json in R, h2o.predict_json(modelpath, jsondata) and got the error message: Error: Could not find or load main class water.util.H2OPredictor I am using h2o_3.20.0.8. I searched the documentation from H2o but didn't help. > h2o.predict_json(modelpath, jsondata) $error [1] "Error: Could not find or load main class water.util.H2OPredictor" Warning message: In system2(java, args, stdout = TRUE, stderr = TRUE) : running command ''java' -Xmx4g -cp .:/Library/Frameworks/R.framework/Versions/3.5/Resources/library/mylib/Models/h2o-genmodel.jar:/Library/Frameworks/R.framework/Versions/3.5/Resources/library/mylib/Models:genmodel.jar:/ water.util.H2OPredictor /Library/Frameworks/R.framework/Versions/3.5/Resources/library/mylib/Models/mymodel.zip '[{"da1":252,"da2":22,"da3":62,"da4":63,"da5":84.83}]' 2>&1' had status 1 A: It looks like you are missing your h2o-genmodel.jar file - this is what the error message Could not find or load main class water.util.H2OPredictor indicates. You may want to provide all the arguments to checkoff that you have everything: h2o.predict_json(model, json, genmodelpath, labels, classpath, javaoptions) documentation here
{ "pile_set_name": "StackExchange" }
Q: Functions satisfying $g(1 - g(x)) = x$ I need to find all functions with $g(1 - g(x)) = x$ and $x\in \mathbb{R}$. I must also provide a specific example of such function. My first attempt was to invert the expression yielding $g(x) = 1 - g^{-1}(x)$ and inverting again $x = g^{-1}(1 - g^{-1}(x))$. But this doesn´t bring me any further. I am not familiar with this type of problem and appreciate some guidance. A: There is no such continuous function. Notice that if for all $\,x\,$ we have $\, g(1-g(x)) = x, \,$ then the inverse function $\, g^{-1}(x) = 1 - g(x) \,$ implies that $\,g\,$ is a bijection. Since it is defined on the reals this implies that the function is strictly monotone increasing or decreasing. In both cases the composition $\, g(1-g(x)) \,$ is monotone decreasing which contradicts it being equal to $\,x.$ If there are no restrictions on the function $\,g\,$ then it can be very arbitrary. We prove a general result. Suppose $\, t(x) \,$ is any involution and suppose $\, g(t(g(x)) = x \,$ for all $\,x \in \mathbb{R}.\,$ Thus $\,g\,$ is a bijection. Given any $\, a \in \mathbb{R},\,$ then let $\, b := g(a),\, c := t(b),\, \,$ and now, $\, a = g(c). \,$ Thus $\, b = g(g(c)) = t(c), \,$ because $\, t \,$ is an involution. Thus $\, t(x) = g(g(x)) \,$ for all $\, x\in \mathbb{R}.\,$ This is the only restriction on $\,g.$ In other words, this general result uses only elementary group theory. Suppose $\, t,g \in G \,$ a group such that $\, 1 = tt = gtg. \,$ Then $\, t(tg) = (tt)g = g = g(gtg) = (gg)(tg), \,$ and therefore $\, t = gg.\,$ Note that in our original question, if we define $\, f(x) = g(x+\frac12)-\frac12, \,$ then $\, -x = f(f(x)). \,$ Some good solutions to this are in question 312385 "Find a real function f:R->R such that f(f(x))=-x?" If you want concrete examples of functions $\, g \,$ then take a look at the solutions there. A nice solution is given as $\, f(x) = \text{sign}(x) (1 - (-1)^{\lceil x\rceil}) \,$ which is only piecewise continuous.
{ "pile_set_name": "StackExchange" }
Q: ng-include vs. ui-view for static content I'm populating my index.html via angular, as per usual. I have an index that looks something like: <body> <nav ng-include="'app/partials/navbar.html'" ng-controller="NavBarController"></nav> <main> <section ui-view="donate"></section> <section ng-include="'app/partials/about.html'"></section> <section ui-view="stories"></section> <section ng-include="'app/partials/contact.html'"></section> </main> <footer ng-include="'app/partials/footer.html'"/> </body> My nav, about, contact and <footer> all have static content, so I used ng-include. The donate and stories <section>s are dynamic, so I used ui-view. The Question Is there any advantage to using ui-view over ng-include where static content is concerned? The nav might be better with a ui-view I can reference the NavBarController in $stateProvider.state(), but what about the static partials? A: ui-view is useful only when you want to leverage the feature of browser history. For e.g. If you have a HTML as below <div class="searchbar"> <input type="text" ng-model="student.id"> <button type="button" ng-click="getStudent()">Get Student</button> </div> <div class="student-info"> <div class="student" ui-view="studentview"></div> </div> Having a ui-view here will make sense since we can pass different data (like student id etc) as parameter to the same template and display different content. Also the browser history will help us navigate between different students here. For content like about or footer though which are mostly static I would recommend you to use ng-include as you are hardly getting anything extra out of router here. For Contact it can depend on what it contains. If it is something which requires navigation (like one route for contact of each country's office) then go with ui-route otherwise stick with ng-include
{ "pile_set_name": "StackExchange" }
Q: Problem with htaccess redirect (looping) I worked to do this for 2 hours but finally I gave up. I have 2 conditions: 1. If user request a php file redirect cms/index.php?request=$1 2. If user request something different from php (png,css,jpg) redirect cms/website/$1 First rule works but I couldn't apply second rule. When user request /cms/style.css, Apache redirect cms/website/style.css and again redirects cms/website/website/style.css and it loops. My htaccess file is like that: Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*\.php) /cms/index.php?request=$1 [L] RewriteRule (.*\.!(php)) /cms/website/$1 [R,L] Note: I'm not sure that last regex is true, or not. And it returns 500. error_log output is "[Tue Aug 16 16:26:11 2011] [error] [client 127.0.0.1] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace." A: Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !(.*)\.php$ RewriteRule (.*)\.(.*)$ /cms/website/$1 [R,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.*)\.php$ RewriteRule (.*)\.php /cms/index.php?request=$1 [L]
{ "pile_set_name": "StackExchange" }
Q: How to detect when drag input is end in libgdx I don't know how to detect when the user drag event is end or not so I decide to do like this protected class Input extends DragListener{ boolean dragging=false; @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { return true; } @Override public void touchDragged(InputEvent event, float x, float y, int pointer) { if(!dragging)dragging=true; *my game logic* . . . } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { Gdx.app.log("touch up",""); if (dragging) { *my game logic* . . . } } } I try my class by drag and touch up ,nothing happen. I drag again and nothing happen. then I tap and the console is print "touchUp" two time. Is there anything else to detect it A: In the interface GestureListener that resides in GestureDetector there is a method pan and panStop. You should implement that interface, add all the methods from it and use pan for your dragging behaviour and panStop for the solution to your question. The methods register for both touch and mouse as well as multiple finger touches.
{ "pile_set_name": "StackExchange" }
Q: Android - what is the good-practice way of handling button clicks on the header of an app I am working on a header for an app. The header will have 4 buttons. Each button will have a listener and some code to send it to the home of that button. The Java code for the buttons will be the same so I am wondering what I can do so that I can have that code in one place and reuse it in all my screens. How do people typically handle this kind of a scenario? Should/can I make a utility class and just import that? If I do, then how do I handle code like this so it would know which intent I am on? Intent myIntent = new Intent(CurrActivity.this, NextActivity.class); CurrActivity.this.startActivity(myIntent); Thanks! A: A couple of options I can think of:- Have an ActivityBase class or a FragmentBase class that you put all your navigation logic into, all your activities/fragments would subclass from this, therefore share the same nav logic Create a custom view based of LinearLayout or ViewGroup, treat each child view of this custom view as a navigation item, this might be a bit heavy depending on your experience but definetly the way I would do it these days, info here on custom views http://developer.android.com/guide/topics/ui/custom-components.html With both options you should look at the include tag that will allow you to share the xml that defines your navigation across layouts. http://developer.android.com/resources/articles/layout-tricks-reuse.html Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: How to make emacs execute function only a specific dir/file doesn't exist I want Emacs to execute a function if and only if a specific directory or file under .emacs.d doesn't exist. What should I add to init.el? Suppose that the dir or file name is dir, and the function name is fun. A: I am a beginner Lisp programmer but probably something like this: (setq dir "~/.emacs.d") (defun fun() (message "fun called") ) (defun funp(dir fn) (if (not (file-exists-p dir)) (funcall fn)) ) Set dir to what you need. Usage: (funp dir 'fun)
{ "pile_set_name": "StackExchange" }
Q: PHP: Using html_entities correctly. Want all/any characters to be returned in error message I'm having trouble returning certain characters in my error message. The setup is as follows: Whatever the user enters into the textfield (if incorrect), should be returned in the error message. Whether it's a letter, a comma, an ampersand...anything. It seems html_entities or special_chars would be appropriate here. The following block of code is where I think this idea should be set up. The following characters return a blank error message with just the string (is not a valid 4-letter ICAO airport code) attached: + " ' & This is the code in question. The commented out $error_str is what I'm trying to get working. else { //VERIFY ICAO IS IN AIRPORTS.DB $airport_query = "SELECT COUNT(*) AS airport_count, LAT, LONG, IATA, Name FROM airports WHERE ICAO = '$icao'"; $airport_result = $airports_db->queryDB($airport_query); foreach($airport_result as $airport_row) {} if($airport_row["airport_count"] == 0) { $error_str = "$icao is not a valid 4-letter ICAO airport code."; /* $error_str = "html_entities($icao) is not a valid 4-letter ICAO airport code."; */ } $return_array["ICAO"] = $icao; $return_array["IATA"] = $airport_row["IATA"]; $return_array["airport_name"] = $airport_row["Name"]; } $return_array["error"] = $error_str; echo json_encode($return_array); Also notice the echo json_encode at the bottom. I'm not sure if I should be doing the html_entities on the $error_str or the $return_array. Any input is appreciated. A: There are two main issues here. The first is that the PHP function is htmlentities without an underscore in the name, and the second is that the function call can't be in a string. This will work: $error_str = htmlentities($icao) . ' is not a valid 4-letter ICAO airport code.'; htmlentities accepts a string, so running it on $return_array will not work. You could do htmlentities($error_str) before putting it in the $return_array. http://www.php.net/manual/en/function.htmlentities.php
{ "pile_set_name": "StackExchange" }
Q: Library not loaded: @rpath/libmysqlclient.21.dylib Reason: image not found Django migrate error using mysqlclient DB driver and MySQL 8 with macOS While changing to a MySQL database from the default SQLite one that Django uses by default, I ran into this tricky error while trying to run python manage.py migrate --database mysql: Traceback (most recent call last): File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line( sys.argv ) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 217, in all return [self[alias] for alias in self] File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 217, in <listcomp> return [self[alias] for alias in self] File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 202, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 20, in <module> ) from err django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I received this error after having already installed mysqlclient via pip install mysqlclient and its connector through Homebrew with brew install mysql-connector-c, so this is a bit of a puzzling error. Even after following the connector instructions by modifying the mysql_config file in the connector's bin folder, I still ran into this issue. This does appear to be at least somewhat related to that I'm running macOS given the documentation on this connector's known bug. Upon inspecting my stack trace further, I noticed the Library not loaded: @rpath/libmysqlclient.21.dylib error up near the top. Shortly after that is another possible clue I found: Reason: image not found, but I'm not quite sure what that's supposed to mean. I did poke around in /usr/local/Cellar/mysql-connector-c to see if there was anything possibly missing with the connector I installed, and sure enough, the libmysqlclient.21.dylib file was missing. In its place was what I assume is an older version of the file since it was named libmysqlclient.18.dylib. Out of curiosity, I copied the .dylib that my MySQL install came with and moved that copy under the same name to the connector's folder and to /usr/local/lib where I also found another libmysqlclient.18.dylib file. However, my migration still failed, but I did get a slightly different stack trace: Traceback (most recent call last): File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so Reason: no suitable image found. Did find: /usr/local/lib/libmysqlclient.21.dylib: file too short /usr/local/lib/libmysqlclient.21.dylib: file too short The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line( sys.argv ) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 217, in all return [self[alias] for alias in self] File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 217, in <listcomp> return [self[alias] for alias in self] File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 202, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 20, in <module> ) from err django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? This time I get the following error: Reason: no suitable image found. Did find: /usr/local/lib/libmysqlclient.21.dylib: file too short /usr/local/lib/libmysqlclient.21.dylib: file too short With that, I suspect the problem may have something to do with the .dylib version that my MySQL connector installed with, but I'm not sure how to fix this exactly. I do find it curious that simply copying a file over managed to change my stack trace ever so slightly so I guess I ought to look into that more. Thoughts? A: Just create a symbolic link in /usr/local/lib sudo ln -s /usr/local/mysql/lib/libmysqlclient.21.dylib /usr/local/lib/libmysqlclient.21.dylib A: I've recently had this issue when I was trying to install Django and mod_wsgi on my MacBook pro (MacOS Catallina). Setting LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, adding sym link and moving the libmysqlclient.21.dylib to /usr/lib/ didn't work. I had to struggle for a few days but finally I got this solution. The thing is I had to modify the library path in the libmysqlclient.21.dylib. Fortunately we have a tool to do it. The culprit was @rpath/libmysqlclient.21.dylib. It looked like @rpath wasn't working. Ok you can check the paths referred in a .so file using otool. It comes with Xcode. This is what you get when you run it on the mysql .so file (should be in the MySQLdb directory under your site-packages). $ otool -L _mysql.cpython-38-darwin.so _mysql.cpython-38-darwin.so: @rpath/libmysqlclient.21.dylib (compatibility version 21.0.0, current version 21.0.0) libssl.1.1.dylib (compatibility version 1.1.0, current version 1.1.0) libcrypto.1.1.dylib (compatibility version 1.1.0, current version 1.1.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1281.100.1) So we modify the filepath in the _mysql.cpython-38-darwin.so. There is a tool for that. It is install_name_tool. I ran these commands. Basically I changed @rpath to absolute path, and also the libssl and the licrypto paths to absolute path. $ install_name_tool -change @rpath/libmysqlclient.21.dylib /usr/local/mysql/lib/libmysqlclient.21.dylib _mysql.cpython-38-darwin.so $ install_name_tool -change libssl.1.1.dylib /usr/local/mysql/lib/libssl.1.1.dylib _mysql.cpython-38-darwin.so $ install_name_tool -change libcrypto.1.1.dylib /usr/local/mysql/lib/libcrypto.1.1.dylib _mysql.cpython-38-darwin.so My Django worked great after these changes. A: So it turns out that I managed to solve my issue albeit in a bit of an unorthodox manner. If anyone else is using mysqlclient with a version of Python 3 and MySQL 8, give this a try and see if it helps! :) I simply made a copy of the libmysqlclient.21.dylib file located in my installation of MySQL 8.0.13 which is was in /usr/local/mysql/lib and moved that copy under the same name to /usr/lib. You will however need to temporarily disable security integrity protection on your mac to do this since you won't have or be able to change permissions to anything in /usr/lib without disabling it. You can do this by booting up into the recovery system, click Utilities on the menu at the top, and open up the terminal and enter csrutil disable into the terminal. Just remember to turn security integrity protection back on when you're done doing this! The only difference from the above process will be that you run csrutil enable instead. After I did this, I ran my migrations like I did before on the new database and it worked! I honestly don't know how good of a solution this really is, but so far everything's been working perfectly since I changed the copy of .dylib the connector was using. I hope this helps if you also have this issue! You can read more about how to disable and enable macOS's security integrity protection here.
{ "pile_set_name": "StackExchange" }
Q: Error when deploying web app on Glassfish I'm using Eclipse + Glassfish 4.0 When I deploying a simple project, following error appears : cannot Deploy Testmart deploy is failing=Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.RuntimeException: Servlet web service endpoint '' failure. Please see server.log for more details. EDIT : ProductCatalog.java Class : import org.hamed.train.service.ProductServiceImp; @WebService public class ProductCatalog { ProductServiceImp productService = new ProductServiceImp(); @WebMethod public List<String> getProducts() { return productService.getProductCategories(); } public List<String> getProducts(String category) { return productService.getProducts(category); } } system.log content : http://txs.io/B7P A: According to @Silly Freak's comment, I found the answer. These two method should not have the same name : ProductCatalog.java public List<String> getProducts() { return productService.getProductCategories(); } public List<String> getProducts(String category) { return productService.getProducts(category); } Solution: I changed first method name to something else and worked like a charm.
{ "pile_set_name": "StackExchange" }
Q: Remove escape from string c# I have a path in my network who I can use in File Explorer without problems: \\MyNetwork\Projects\16000 Now I want to access it using Directory.Exists as: var normalFolderPath = @"\MyNetwork"; var number = @"\16000" var a = Directory.Exists($@"{normalFolderPath}\{number}"); But this: $@"{normalFolderPath}\{number}" return \\MyNetwork\\16000 but if I try to access it that on File Explorer just can not found, but if I remove \ from subfolder like: \\MyNetwork\16000 it works!, how can I remove one \ from string in c# A: You're complaining that your string has two slashes in the middle of it, but you put two slashes in the middle of it: number is the literal string \16000 You asked c# to concatenate normalfolderpath with number, separated by slash: {normalFolderPath}\{number} Naturally, you'll end up with two slashes; one from number, and one as the separator. To demo what I mean, here is an altered code: var normalFolderPath = @"\MyNetwork"; var number = @"!16000" var a = Directory.Exists($@"{normalFolderPath}={number}"); This will produce the string \MyNetwork=!16000: the = is the separator between the interpolated fields and ! came from the start of number But this: $@"{normalFolderPath}\{number}" return \\MyNetwork\\16000 I disagree: it will definitely return \MyNetwork\\16000 with only one slash at the start and two in the middle. No way will that code you put, return something with two slashes at the start As has been commented, you should use Path.Combine to combine path elements: var normalFolderPath = @"\\MyNetwork"; var number = "16000" var a = Directory.Exists(Path.Combine(normalFolderPath,number));
{ "pile_set_name": "StackExchange" }
Q: Add form to html tabel cell I want to add an input form to an HTML table cell when a checkbox is selected. When I add some form of text field or number field to the table cell to create a form, the text box doesn't show. only the text of my label shows. <td> <label class="collapsible"> <input type="checkbox" /> <span class="collapser">Edit</span> <span class="arrow">&gt;</span> <div class="collapsed"> <form method="post"> <label for="pwd">Hello World</label><br> <input type="number" min="1" step="1" class="form-control" id="pwd" name=min_qty> </form></div></label></td> My Css code as well: .collapsible { display: block; margin-bottom: 1rem; } .collapsible input { position: absolute; left: -9999px; } .collapsible input:focus ~ .collapser { border-color: grey; } .collapsible .collapser { cursor: pointer; border: 1px transparent dotted; } .collapsible .arrow { float: right; margin-left: 0.5em; display: inline-block; transform: rotate(90deg); transition: transform 0.25s ease-out; } .collapsible input:checked ~ .arrow, .collapsible input:checked ~ .collapser .arrow { transform: rotate(270deg); } .collapsible .collapsed { font-size: 0; margin: 0; opacity: 0; padding: 0; /* fade out, then shrink */ transition: opacity 0.25s, margin 0.5s 0.25s, font-size 0.5s 0.25s, padding 0.5s 0.25s; } .collapsible input:checked ~ .collapsed { font-size: 12px; opacity: 1; height: auto; padding: 5px 0; /* grow, then fade in */ transition: margin 0.25s, padding 0.25s, font-size 0.25s, opacity 0.5s 0.25s; } My table output example A: I figured it out. My CSS was affecting all of my inputs, not just my check boxes. Changed this: } .collapsible input { position: absolute; left: -9999px; } to this: .collapsible input[type="checkbox"] { position: absolute; display: none; }
{ "pile_set_name": "StackExchange" }
Q: Did the USS Olympia go forward in time? DS9 "The Sound of her Voice": LISA [OC]: My name's Lisa Cusak. Until a couple of days ago, I was the commanding officer of the Olympia. SISKO: The Olympia. LISA [OC]: We left the Federation over eight years ago for a long range exploration of the Beta Quadrant. SISKO: What happened to your ship, Captain? LISA [OC]: We were finally heading home, if you can believe that, then we picked up some strange energy readings in a nearby star system, and I decided to stop and investigate. We found an energy barrier around the fourth planet that was unlike anything we'd ever seen, and when we probed it with our scanners it triggered a quantum reaction. There was an enormous surge of metrion radiation that disabled our engines. The next thing I knew, we were spiraling in toward the surface. I gave the order to abandon ship and the last thing I remember is a console exploding in my face. I woke up in an escape pod on the surface and I've spent the last day and a half sitting in this cave trying to raise someone on subspace. BASHIR: Captain, Doctor Bashir, Chief Medical Officer. Your message said that you were on a L class planet. Are you sure? LISA [OC]: Positive. And to answer your next question, yes, I've been giving myself fifteen cc's of triox every four hours to compensate for the excess carbon dioxide in the atmosphere. Just like it says in my medical tricorder. BASHIR: How much triox do you have left? LISA [OC]: One hundred and fifty millilitres. BASHIR: Will you to decrease the dosage, Captain, to eight cc's every six hours. We need to stretch your supply as long as possible. KASIDY: What happens when she runs out of the drug? LISA [OC]: That's a good question, Doctor. What happens then? BASHIR: You will begin to experience the effects of hypoxia. But before that happens, the triox compound will have strengthened your cardiopulmonary system, allowing you to better withstand the effects. LISA [OC]: Better withstand the effects. In other words, I'm going to be gasping for air and turning different shades of blue by the time you get here. BASHIR: Yes, I'm afraid so. LISA [OC]: Thanks for brightening my day. KASIDY: Is there anything we can do? LISA [OC]: There is, actually. I can't sleep. I think the injections are keeping me awake and I haven't had anyone to talk to for two days. SISKO: We'll be able to help you with that, Captain. I'll have one of my officers stay on the comm. line with you at all times. So the ship left eight years ago, they were doing long range exploration, Lisa doesn't know anything about the Dominion war, and she's only been on the planet for two days. We learn later that the crew are communicating with her in the past, which is an entirely different issue. Did the ship go forward in time when it hit the metreon radiation in the atmosphere? Is that the explanation that Lisa was giving? I'm confused about the time frame of how this all happened. A: The Metreon radiation caused a temporal lensing effect, sending her communications into her future (the Defiant's present), and their replies back in time (from their perspective) to Captain Cusak's present. There’s no indication that Cusak’s ship travelled in time; just the communications to and from it. Dr. Bashir confirmed she had died 3 years and two months prior to them arriving at the planet in the Rutharian sector. So she would have left on her mission 8 years plus 3 years ago, making that 2363 (the episode takes place in 2374). To put that into perspective, 2363 is one year prior to the first season of Star Trek: The Next Generation
{ "pile_set_name": "StackExchange" }
Q: Нужно чтобы бот правильно отвечал пользователю который вводит число. Я создал список из таких чисел, но бот все равно не отвечает Я поместил в список числа, при вводе которых пользователем, бот понимал, что ответить. Но по какой то причине ничего не получается. Бот ничего не отвечает P.s Я новичок в python #main.py @bot.message_handler(content_types=['text']) def response(message): try: filename = 'UserName.json' rub = message.text if rub == config.scr(): with open(filename, 'w', encoding='utf-8') as f: json.dump(rub, f, ensure_ascii=False) bot.send_message(message.chat.id, 'Вы переводите ' + rub + ' рублей') else: bot.send_message(message.chat.id, 'Введите корректную сумму!') except FileNotFoundError: print('error') #config.py def scr(): n = 100001 ls = [] for i in range(n): ls.append(i) for elem in ls[:1000]: ls.remove(elem) array = [str(i) for i in ls] A: В config.py / scr у вас не возвращается список. Вместо array = [str(i) for i in ls] напишите return [str(i) for i in ls] В config.py / response неправильная проверка наличия числа в списке. У вас проверяется, что введенное значение (строка) равна список. Нужно использовать оператор in: if rub in config.scr(): Мне кажется проверка диапазона суммы выглядит излишней. Предлагаю математически сравнивать. Тут получаемую сумму пытаемся перевести к целому числу через int, если строка не является целым числом, то выбросится исключение ValueError После проверяем что число входит в диапазон от 1 до 1000 (подправьте, если нужен другой диапазон) Пример: @bot.message_handler(content_types=['text']) def response(message): try: rub = int(message.text) if rub <= 0 or rub > 1000: raise ValueError() filename = 'UserName.json' with open(filename, 'w', encoding='utf-8') as f: json.dump(rub, f, ensure_ascii=False) bot.send_message(message.chat.id, f'Вы переводите {rub} рублей') except ValueError: bot.send_message(message.chat.id, 'Введите корректную сумму!') except FileNotFoundError: print('error')
{ "pile_set_name": "StackExchange" }
Q: Tricky for Loop I am bothered by a question of for loop in C language. when i write: #include<conio.h> #include<stdio.h> main() { int i = 0; for( ; i ; ) { printf("In for Loop"); } getch(); } Output: NOTHING PRINT. Code get executed, but printf statement didn't print due to condition. OK, No problem here. But when i write this code: #include<conio.h> #include<stdio.h> main() { for( ; 0 ; ) { printf("In for Loop"); } getch(); } Output: In for Loop. My for loop get executed 1 time, but actually it must not to be executed. I don't know why? can coder/programmer/hacker of stackoverflow help me. explain me please why my for loop giving this output only one time. A: What you wrote shouldn't print anything, but I suspect the actual second-case code (not what you typed in) that causes the problem is: for( ; 0 ; ); // <==== note the trailing semicolon there. { printf("In for Loop"); } In this case the for loop doesn't execute the empty statement, and then the { } code is executed once. EDIT: If this isn't the problem please just paste a complete program that exhibits the problem directly into your question. EDIT2: The following minimal compilable example doesn't print anything: #include <cstdio> int main() { for( ; 0 ; ) { std::printf("In for Loop"); } }
{ "pile_set_name": "StackExchange" }
Q: Perl oneliner might be a runaway multi-line ++ message I am trying to reformat the date for MySQL. This Perl one-liner give me below error message. I would like understand why it's giving this error message. echo 'Dec 2 04:08:40 EST 2012' | perl -lane ' my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); ( $amon, $mday, $hour,$tz, $year) =split('\s+',$_); for (my $i = 0; $i < @abbr; $i++) { next unless $abbr[$i] =~ /^$amon/; $mon=$i; } $mon++; print "$year-$mon-$mday $hour"; ' Error Message syntax error at -e line 3, near ") {" (Might be a runaway multi-line ++ string starting on line 2) syntax error at -e line 9, near ";}" Execution of -e aborted due to compilation errors. A: The problem is that you have tried to embed single quotes within a single-quoted string. You could escape them, but split will split $_ on whitespace by default. Here is a solution, but as Mat says this is a program, not a one-liner. Put it in a file. echo 'Dec 2 04:08:40 EST 2012' | perl -lane ' @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); ($amon, $mday, $hour, $tz, $year) = split; for my $i (0..$#abbr) { next unless $abbr[$i] =~ /^$amon/; $mon=$i; } $mon++; print "$year-$mon-$mday $hour";'
{ "pile_set_name": "StackExchange" }
Q: Не срабатывает псевдокласс :hover Здравствуйте. При наведении на картинку, она затемняется и сверху появляется блок с информацией, в которой есть в том числе и ссылка. Тут проблем не возникло. Но захотел выделить ссылку при наведении, hover почему-то срабатывает, только если навести на ссылку резко. Из за чего это происходит? Заранее спасибо. figure { position: relative; overflow: hidden; ; width: 315px; height: 315px; background: rgba(25, 24, 22, 0.7); } figure img { position: relative; display: block; min-height: 100%; max-width: 100%; } figcaption ul { list-style-image: url("img/marker.png"); margin-left: 40px; font-size: 15px; color: #fff; } figcaption li { padding-bottom: 20px; } figcaption a { width: 156px; background-color: #fff; color: #1c1611; border-radius: 15px; padding: 6px 16px; font-weight: bold; } figure figcaption::before { position: absolute; top: 15px; right: 15px; bottom: 15px; left: 15px; border: 3px dashed #ffda4b; content: ''; } figure h2 { -webkit-transition: -webkit-transform 0.35s; transition: transform 0.35s; -webkit-transform: translate3d(0, 100%, 0); transform: translate3d(0, 100%, 0); color: #ffda4b; font-size: 27px; text-transform: uppercase; } figure figcaption::before, figure ul, figure h2, figure a { opacity: 0; -webkit-transition: opacity 0.35s, -webkit-transform 0.35s; transition: opacity 0.35s, transform 0.35s; -webkit-transform: scale(0); transform: scale(0); } figure figcaption { position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding: 15px 30px; } figure:hover h2 { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); opacity: 1; } figure:hover figcaption::before, figure:hover ul, figure:hover a { opacity: 1; -webkit-transform: scale(1); transform: scale(1); } figcaption a:hover { color: #fff; background-color: #ffda4b; } figure:hover figcaption { background-color: rgba(58, 52, 42, 0); } figure:hover img { opacity: 0.2; } <figure> <img src="img/prewiew.png" alt=""> <figcaption> <h2>Игровой сайт</h2> <ul> <li>CMS с возможностью редактировать сайт</li> <li>Временной таргетинг</li> <li>Интеграция с Яндекс.Касса</li> </ul> <a href="#">Посмотреть</a> </figcaption> </figure> A: Добавьте position: relative на кнопку, чтобы его не перекрывали другие невидимые элементы: figure:hover a { position: relative; } figure{ position: relative; overflow: hidden;; width: 315px; height:315px; background: rgba(25,24,22, 0.7); } figure img { position: relative; display: block; min-height: 100%; max-width: 100%; } figcaption ul{ list-style-image: url("img/marker.png"); margin-left: 40px; font-size: 15px; color: #fff; } figcaption li{ padding-bottom: 20px; } figcaption a{ width: 156px; background-color: #fff; color: #1c1611; border-radius: 15px; padding: 6px 16px; font-weight: bold; } figure figcaption::before{ position: absolute; top: 15px; right: 15px; bottom: 15px; left: 15px; border: 3px dashed #ffda4b; content: ''; } figure h2 { -webkit-transition: -webkit-transform 0.35s; transition: transform 0.35s; -webkit-transform: translate3d(0,100%,0); transform: translate3d(0,100%,0); color: #ffda4b; font-size: 27px; text-transform: uppercase; } figure figcaption::before, figure ul, figure h2, figure a { opacity: 0; -webkit-transition: opacity 0.35s, -webkit-transform 0.35s; transition: opacity 0.35s, transform 0.35s; -webkit-transform: scale(0); transform: scale(0); } figure figcaption { position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding: 15px 30px; } figure:hover h2{ -webkit-transform: translate3d(0,0,0); transform: translate3d(0,0,0); opacity: 1; } figure:hover figcaption::before, figure:hover ul, figure:hover a { opacity: 1; -webkit-transform: scale(1); transform: scale(1); } figcaption a:hover{ color: #fff; background-color:#ffda4b; } figure:hover figcaption { background-color: rgba(58,52,42,0); } figure:hover img { opacity: 0.2; } figure:hover a{ position:relative; } <figure> <img src="img/prewiew.png" alt=""> <figcaption> <h2>Игровой сайт</h2> <ul> <li>CMS с возможностью редактировать сайт</li> <li>Временной таргетинг</li> <li>Интеграция с Яндекс.Касса</li> </ul> <a href="#">Посмотреть</a> </figcaption> </figure> A: Происходит это, потому что прозрачный всплывающий ::before псевдоэлемент перекрывает собой кнопку, и сквозь него клик (и наведение) не проходит. Чтобы исправить, добавьте такой стиль: figure figcaption::before{ pointer-events: none; } Это сделает ::before псевдоэлемент невосприимчивым к кликам и наведениям курсора, и они будут проходить сквозь него, корректно попадая на кнопку. figure { position: relative; overflow: hidden; ; width: 315px; height: 315px; background: rgba(25, 24, 22, 0.7); } figure img { position: relative; display: block; min-height: 100%; max-width: 100%; } figcaption ul { list-style-image: url("img/marker.png"); margin-left: 40px; font-size: 15px; color: #fff; } figcaption li { padding-bottom: 20px; } figcaption a { width: 156px; background-color: #fff; color: #1c1611; border-radius: 15px; padding: 6px 16px; font-weight: bold; } figure figcaption::before { position: absolute; top: 15px; right: 15px; bottom: 15px; left: 15px; border: 3px dashed #ffda4b; content: ''; pointer-events: none; } figure h2 { -webkit-transition: -webkit-transform 0.35s; transition: transform 0.35s; -webkit-transform: translate3d(0, 100%, 0); transform: translate3d(0, 100%, 0); color: #ffda4b; font-size: 27px; text-transform: uppercase; } figure figcaption::before, figure ul, figure h2, figure a { opacity: 0; -webkit-transition: opacity 0.35s, -webkit-transform 0.35s; transition: opacity 0.35s, transform 0.35s; -webkit-transform: scale(0); transform: scale(0); } figure figcaption { position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding: 15px 30px; } figure:hover h2 { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); opacity: 1; } figure:hover figcaption::before, figure:hover ul, figure:hover a { opacity: 1; -webkit-transform: scale(1); transform: scale(1); } figcaption a:hover { color: #fff; background-color: #ffda4b; } figure:hover figcaption { background-color: rgba(58, 52, 42, 0); } figure:hover img { opacity: 0.2; } <figure> <img src="img/prewiew.png" alt=""> <figcaption> <h2>Игровой сайт</h2> <ul> <li>CMS с возможностью редактировать сайт</li> <li>Временной таргетинг</li> <li>Интеграция с Яндекс.Касса</li> </ul> <a href="#">Посмотреть</a> </figcaption> </figure>
{ "pile_set_name": "StackExchange" }
Q: How to count rows efficiently with one pass over the dataframe I have a dataframe made of strings like this: ID_0 ID_1 g k a h c i j e d i i h b b d d i a d h For each pair of strings I can count how many rows have either string in them as follows. import pandas as pd import itertools df = pd.read_csv("test.csv", header=None, prefix="ID_", usecols = [0,1]) alphabet_1 = set(df['ID_0']) alphabet_2 = set(df['ID_1']) # This just makes a set of all the strings in the dataframe. alphabet = alphabet_1 | alphabet_2 #This iterates over all pairs and counts how many rows have either in either column for (x,y) in itertools.combinations(alphabet, 2): print x, y, len(df.loc[df['ID_0'].isin([x,y]) | df['ID_1'].isin([x,y])]) This gives: a c 3 a b 3 a e 3 a d 5 a g 3 a i 5 a h 4 a k 3 a j 3 c b 2 c e 2 c d 4 [...] The problem is that my dataframe is very large and the alphabet is of size 200 and this method does an independent traversal over the whole dataframe for each pair of letters. Is it possible to get the same output by doing a single pass over the dataframe somehow? Timings I created some data with: import numpy as np import pandas as pd from string import ascii_lowercase n = 10**4 data = np.random.choice(list(ascii_lowercase), size=(n,2)) df = pd.DataFrame(data, columns=['ID_0', 'ID_1']) #Testing Parfait's answer def f(row): ser = len(df[(df['ID_0'] == row['ID_0']) | (df['ID_1'] == row['ID_0'])| (df['ID_0'] == row['ID_1']) | (df['ID_1'] == row['ID_1'])]) return(ser) %timeit df.apply(f, axis=1) 1 loops, best of 3: 37.8 s per loop I would like to be able to do this for n = 10**8. Can this be sped up? A: You can get past the row level subiteration by using some clever combinatorics/set theory to do the counting: # Count of individual characters and pairs. char_count = df['ID_0'].append(df.loc[df['ID_0'] != df['ID_1'], 'ID_1']).value_counts().to_dict() pair_count = df.groupby(['ID_0', 'ID_1']).size().to_dict() # Get the counts. df['count'] = [char_count[x] if x == y else char_count[x] + char_count[y] - (pair_count[x,y] + pair_count.get((y,x),0)) for x,y in df[['ID_0', 'ID_1']].values] The resulting output: ID_0 ID_1 count 0 g k 1 1 a h 4 2 c i 4 3 j e 1 4 d i 6 5 i h 6 6 b b 1 7 d d 3 8 i a 5 9 d h 5 I've compared the output of my method to the row level iteration method on a dataset with 5000 rows and all of the counts match. Why does this work? It essentially just relies on the formula for counting the union of two sets: The cardinality of a given element is just the char_count. When the elements are distinct, the cardinality of the intersection is just the count of pairs of the elements in any order. Note that when the two elements are identical, the formula reduces to just the char_count. Timings Using the timing setup in the question, and the following function for my answer: def root(df): char_count = df['ID_0'].append(df.loc[df['ID_0'] != df['ID_1'], 'ID_1']).value_counts().to_dict() pair_count = df.groupby(['ID_0', 'ID_1']).size().to_dict() df['count'] = [char_count[x] if x == y else char_count[x] + char_count[y] - (pair_count[x,y] + pair_count.get((y,x),0)) for x,y in df[['ID_0', 'ID_1']].values] return df I get the following timings for n=10**4: %timeit root(df.copy()) 10 loops, best of 3: 25 ms per loop %timeit df.apply(f, axis=1) 1 loop, best of 3: 49.4 s per loop I get the following timing for n=10**6: %timeit root(df.copy()) 10 loops best of 3: 2.22 s per loop It appears that my solution scales approximately linearly.
{ "pile_set_name": "StackExchange" }
Q: Firebase Google authentication error in ionic3 auth.ts signInWithGoogle(): firebase.Promise<any> { return this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());} login.ts loginGoogle() { this.authData.signInWithGoogle().then(() => { this.navCtrl.push(TabsPage); }, error => { this.presentToast("Invalid user details"); });} Open the google account selector and app working smoothly in mobile when select and account to authenticate from the list it display a message mobile app identifier is not registered for the current project Message showing: Please help me to solve this. Thank you! A: I had the same issue and was able to fix it by updating my widget id (in the config.xml file, to match the app id in the firebase console.
{ "pile_set_name": "StackExchange" }
Q: SAS - Kolmogorov-Smirnov Two Sided Critical Values I am trying to compute the critical values for the two-sided Kolmogorov-Smirnov test (PROC NPAR1WAY doesn't output these!). This is calculated as c(a) * sqrt( (n+m)/(nm) ) where n and m are the number of observations in each dataset and c(a) = 1.36 for for confidence level a = 0.05. Either, A) is there a routine in SAS that will calculate these for me? (I've been searching a while) or, B) what is the best way to compute the statistic myself? My initial approach is to select the number of rows from each data set into macro variables then compute the statistic, but this feel ugly. Thanks in advance A: A) Probably not, if you've searched all the relevant documentation. B) That method sounds fine, but you can use a data step if you prefer, e.g. data example1 example2; set sashelp.class; if _n_ < 6 then output example1; else output example2; run; data _null_; if 0 then set example1 nobs = n; if 0 then set example2 nobs = m; call symput('Kolmogorov_Smirnov_05',1.36 * sqrt((n+m)/(n*m))); run; %put &=Kolmogorov_Smirnov_05;
{ "pile_set_name": "StackExchange" }
Q: ajax json object doesn't update in IE8 I'm working on a project with an heavy use of Ajax & Json and I tend to refresh the data every second. Everything works great, Json Parse works well in Google Chrome, but at IE8 my object does not updates from its initial state, forcing me to clear the browser cache in order to see the changes. With Chrome everything works as expected, changes are seen live. I tried both the native JSON.parse() and jQuery.parseJSON(). Would be glad to have some help with this to make the project run on IE just as good as on Chrome. Here is this section of the code: function get_tables() { $.ajax( { url: 'index.php?a=1', type: 'GET', dataType: 'html', success: function(data){ to_object = JSON.parse( console.log('requested'); }, }); } setInterval(get_tables,1000); Thanks in advance. A: You are making same request all the time, so it caches your request. You can disable caching in two way, This will make cache false for all ajax requests $(document).ready(function() { $.ajaxSetup({ cache: false }); }); or This will disable cache for only this request $.ajax( { url: 'index.php?a=1', type: 'GET', dataType: 'html', success: function(data){ to_object = JSON.parse( console.log('requested'); }, cache: false });
{ "pile_set_name": "StackExchange" }
Q: How to hide/remove a picture in footline on title slide only, as a template using beamer class I am designing a latex template for presentation slides for my company. I use beamer class. I made the following codes to show a footline on every slide. It is a image on the left, and some words on the right, and the words and image are aligned in the center. However, I want to just remove the image in the title slide. I have made the following codes \setbeamertemplate{footline}{% \ifnum\insertframenumber=1 % \else \includegraphics[align=c, height=1.5cm]{sim-ci-logo-2.png}% \fi \hfill% \usebeamercolor[fg]{myfootlinetext} Company confidential. \textcopyright\, 2018 All rights reserved.\hspace*{1em} \insertdate{}\hspace*{2em} \insertframenumber\kern1em } However, it does not work properly. In the title page, the image is gone, but the words moved to the bottom edge. See the two screenshots below: This is the title slide's footline, where the words moved to the bottom edge This is the normal slide's footline. Do you know how to keep the words in the title slide in the same position as other slides? Thanks in advance. Note that I have used \ifnum\insertframenumber=1, assuming title slide is always the first slide. As @samcarter pointed out How to make the end slide use the same background as title page, while the normal slide use different background?, it is usually a bad idea to make such an assumption, but I do not know how to make it. Any suggestion on that is also appreciated. A: In exactly the same way as for the background templates, you can have different footlines: \documentclass{beamer} \usepackage{tikz} \defbeamertemplate{background}{special frames}{% \begin{tikzpicture} \useasboundingbox (0,0) rectangle(\the\paperwidth,\the\paperheight); \fill[color=gray] (0,2) rectangle (\the\paperwidth,\the\paperheight); \end{tikzpicture} } \setbeamertemplate{background}{ \begin{tikzpicture} \fill[white,opacity=1] (0,0) rectangle(\the\paperwidth,\the\paperheight); \end{tikzpicture} } \defbeamertemplate{footline}{special frames}{text for special footline} \setbeamertemplate{footline}{text for normal footline} \newcommand{\insertendpage}{% \setbeamertemplate{background}[special frames] \setbeamertemplate{footline}[special frames] \begin{frame} bla bla \end{frame} } \setbeamertemplate{title page}{% \setbeamertemplate{background}[special frames] \setbeamertemplate{footline}[special frames] \begin{frame} text text \end{frame} } \begin{document} \titlepage \begin{frame} Slide 2 \end{frame} \insertendpage \end{document} Quick hack: If you don't want to worry about the vertical position, replace the image by some invisible element of the same height, e.g. a \rule{0pt}{1.5cm}
{ "pile_set_name": "StackExchange" }
Q: Change Play Dist snapshot number Using Play 2.0 framework, when I run play dist I always get: xyz-1.0-SNAPSHOT.zip How can I increase that number, or specify it manually with each build? End result would be: xyz-1.1-SNAPSHOT.zip A: Change the appVersion and/or appName in project/Build.scala file. It will create dist package with new values next time.
{ "pile_set_name": "StackExchange" }
Q: Random table name generator I am trying to write a script that will randomly generate a "name", and use the variable assigned as the table name. However i am not able to create the table i get the error "table was not created:". I listed my code below. Thanks for any help you can give me. $con = mysqli_connect("localhost","placeholder","placeholder","placeholder"); //or die ('unable to connect'); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //create random database name $alpha = "abcdefghijklmnopqrstuvwxyz"; $alpha_upper = strtoupper($alpha); $numeric = "0123456789"; $special = ".-+=_,!@$#*%<>[]{}"; $chars = ""; if (isset($_POST['length'])){ // if you want a form like above if (isset($_POST['alpha']) && $_POST['alpha'] == 'on') $chars .= $alpha; if (isset($_POST['alpha_upper']) && $_POST['alpha_upper'] == 'on') $chars .= $alpha_upper; if (isset($_POST['numeric']) && $_POST['numeric'] == 'on') $chars .= $numeric; if (isset($_POST['special']) && $_POST['special'] == 'on') $chars .= $special; $length = $_POST['length']; }else{ // default [a-zA-Z0-9]{9} $chars = $alpha . $numeric; $length = 6; } $len = strlen($chars); $pw = ''; for ($i=0;$i<$length;$i++) $pw .= substr($chars, rand(0, $len-1), 1); // the finished table name $pw = str_shuffle($pw); //using the $pw variable for the table name $sql="CREATE TABLE `' . $pw . '` ( PID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(PID), Name CHAR(15))"; if (mysqli_query($con,$sql)) { echo "table created successfully"; } else { echo "table was not created:" . mysqli_error($sql); } //TODO create XML file mysqli_close($con); A: $sql="CREATE TABLE `" . $pw . "` // you were using single quotes.. replace them with double ( PID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(PID), Name CHAR(15))"; It will work now..
{ "pile_set_name": "StackExchange" }
Q: Using PyMC3 to fit a stretched exponential: bad initial energy I am trying to change the very simplest getting started - example of pymc3 (https://docs.pymc.io/notebooks/getting_started.html), the motivating example of linear regression into fitting a stretched exponential. The simplest version of the model I tried is y = exp(-x**beta) import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') # Initialize random number generator np.random.seed(1234) # True parameter values sigma = .1 beta = 1 # Size of dataset size = 1000 # Predictor variable X1 = np.random.randn(size) # Simulate outcome variable Y = np.exp(-X1**beta) + np.random.randn(size)*sigma # specify the model import pymc3 as pm import theano.tensor as tt print('Running on PyMC3 v{}'.format(pm.__version__)) basic_model = pm.Model() with basic_model: # Priors for unknown model parameters beta = pm.HalfNormal('beta', sigma=1) sigma = pm.HalfNormal('sigma', sigma=1) # Expected value of outcome mu = pm.math.exp(-X1**beta) # Likelihood (sampling distribution) of observations Y_obs = pm.Normal('Y_obs', mu=mu, sigma=sigma, observed=Y) with basic_model: # draw 500 posterior samples trace = pm.sample(500) which yields the output Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [sigma, beta] Sampling 4 chains: 0%| | 0/4000 [00:00<?, ?draws/s]/opt/conda/lib/python3.7/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice. out=out, **kwargs) /opt/conda/lib/python3.7/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice. out=out, **kwargs) Bad initial energy, check any log probabilities that are inf or -inf, nan or very small: Y_obs NaN --------------------------------------------------------------------------- RemoteTraceback Traceback (most recent call last) RemoteTraceback: """ Traceback (most recent call last): File "/opt/conda/lib/python3.7/site-packages/pymc3/parallel_sampling.py", line 160, in _start_loop point, stats = self._compute_point() File "/opt/conda/lib/python3.7/site-packages/pymc3/parallel_sampling.py", line 191, in _compute_point point, stats = self._step_method.step(self._point) File "/opt/conda/lib/python3.7/site-packages/pymc3/step_methods/arraystep.py", line 247, in step apoint, stats = self.astep(array) File "/opt/conda/lib/python3.7/site-packages/pymc3/step_methods/hmc/base_hmc.py", line 144, in astep raise SamplingError("Bad initial energy") pymc3.exceptions.SamplingError: Bad initial energy """ The above exception was the direct cause of the following exception: SamplingError Traceback (most recent call last) SamplingError: Bad initial energy The above exception was the direct cause of the following exception: ParallelSamplingError Traceback (most recent call last) <ipython-input-310-782c941fbda8> in <module> 1 with basic_model: 2 # draw 500 posterior samples ----> 3 trace = pm.sample(500) /opt/conda/lib/python3.7/site-packages/pymc3/sampling.py in sample(draws, step, init, n_init, start, trace, chain_idx, chains, cores, tune, progressbar, model, random_seed, discard_tuned_samples, compute_convergence_checks, **kwargs) 435 _print_step_hierarchy(step) 436 try: --> 437 trace = _mp_sample(**sample_args) 438 except pickle.PickleError: 439 _log.warning("Could not pickle model, sampling singlethreaded.") /opt/conda/lib/python3.7/site-packages/pymc3/sampling.py in _mp_sample(draws, tune, step, chains, cores, chain, random_seed, start, progressbar, trace, model, **kwargs) 967 try: 968 with sampler: --> 969 for draw in sampler: 970 trace = traces[draw.chain - chain] 971 if (trace.supports_sampler_stats /opt/conda/lib/python3.7/site-packages/pymc3/parallel_sampling.py in __iter__(self) 391 392 while self._active: --> 393 draw = ProcessAdapter.recv_draw(self._active) 394 proc, is_last, draw, tuning, stats, warns = draw 395 if self._progress is not None: /opt/conda/lib/python3.7/site-packages/pymc3/parallel_sampling.py in recv_draw(processes, timeout) 295 else: 296 error = RuntimeError("Chain %s failed." % proc.chain) --> 297 raise error from old_error 298 elif msg[0] == "writing_done": 299 proc._readable = True ParallelSamplingError: Bad initial energy INFO (theano.gof.compilelock): Waiting for existing lock by process '30255' (I am process '30252') INFO (theano.gof.compilelock): To manually release the lock, delete /home/jovyan/.theano/compiledir_Linux-4.4--generic-x86_64-with-debian-buster-sid-x86_64-3.7.3-64/lock_dir /opt/conda/lib/python3.7/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice. out=out, **kwargs) /opt/conda/lib/python3.7/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice. out=out, **kwargs) Instead of the stretched exponential, I have also tried power laws, and sine functions. It seems to me that the problem arises as soon as my model is not injective. Can this be an issue (as apparent, I am a newbie in this field)? Can I restrict sampling to only positive x values? Are there any tricks to this? A: So the problem here is that X1**beta is only defined when X1 >= 0, or when beta is an integer. When you feed this into your observations, for most places, beta will be a float, and so many of mu = pm.math.exp(-X1**beta) will be nan. I found this out with >>> basic_model.check_test_point() beta_log__ -0.77 sigma_log__ -0.77 Y_obs NaN Name: Log-probability of test_point, dtype: float64 I am not sure what model you are trying to specify! There are ways to require beta to be an integer, and ways to require that X1 be positive, but I would need more details to help you describe the model.
{ "pile_set_name": "StackExchange" }
Q: How to tame the X on the JOptionPane Dialog boxes? Also, right now whenever I click the 'X" button on top right, the dialog boxes behaves as if I clicked OK (on messages) or YES (on questions). When the user clicks the X, I want DO_Nothing. In the code below, when i click on the X on the dialog box, it pops out the 'eat!'. Apparently, the X is acting as 'YES' Option, which it should not. int c =JOptionPane.showConfirmDialog(null, "Are you hungry?", "1", JOptionPane.YES_NO_OPTION); if(c==JOptionPane.YES_OPTION){ JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE); } else {JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);} A: Changed to show how to ignore the cancel button on Dialog box per OP clarification of question: JOptionPane pane = new JOptionPane("Are you hungry?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION); JDialog dialog = pane.createDialog("Title"); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { } }); dialog.setContentPane(pane); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); dialog.pack(); dialog.setVisible(true); int c = ((Integer)pane.getValue()).intValue(); if(c == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE); } else if (c == JOptionPane.NO_OPTION) { JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE); }
{ "pile_set_name": "StackExchange" }
Q: TYPO3 rte didn't render tag in extension output view I have some problem with rte in my extension. In tables I set field text area with rte. In BE TYPO3 generating rte view and when I formatting text everything is ok. The only problem is when I have some paragraphs - in BE I have <p> tag, but in frontend in HTML code the <p> tag didn't "exist". My TCA code looks like this: 'description' => array( 'exclude' => 1, 'label' => 'LLL:EXT:fu_product_table/locallang_db.xml:tx_table_products.description', 'defaultExtras' => 'richtext[*]', 'config' => array( 'type' => 'text', 'cols' => '30', 'rows' => '5', 'wizards' => array( '_PADDING' => 2, 'RTE' => array( 'notNewRecords' => 1, 'RTEonly' => 1, 'type' => 'script', 'title' => 'Full screen Rich Text Editing|Formatteret redigering i hele vinduet', 'icon' => 'wizard_rte2.gif', 'script' => 'wizard_rte.php', ), ), ) ), And then trying to render the field in the class: '<td class="td-1">' . $this->getFieldContent('description') . '</td>'; Any suggestion? A: TYPO3 saves RTE's content little bit 'trimmed' (without full markup) so for 'reverting' it back to the valid HTML you need to wrap it with the dedicated method, ie: $this->pi_RTEcssText($this->getFieldContent('description')) Note: Adrian, next point for Extbase: it has special viewhelper for this, so you can do it easily directly in the template ;)
{ "pile_set_name": "StackExchange" }
Q: Web authentication using desktop ldap Problem: I want users from my corporate client to authenticate with my web server by using their local LDAP credentials. Users have a local desktop client that can authenticate with the local LDAP server. My server and the LDAP server do not talk to each other. I know it is possible to authenticate on a web server using LDAP if the web server relays the LDAP request to a LDAP server. (User/desktop client connects to web server, sends credentials and web server interacts with LDAP server for authentication) But is there a way for a desktop client to authenticate with a local LDAP server and then connect to a web server sending a token that would grant access to the web server? (user auths with ldap, sends ldap response to webserver) I am not talking Oauth, which requires both servers to talk. In this case, the LDAP server is isolated from outside contact. The big problem here is that you should never trust the client, even if you have written it yourself. Something like public/private authentication would (probably) not work as well, since the problem is not the encryption, but making sure the message came as "OK" from the LDAP server. A rogue client could fake the OK and sign it anyway. A: If I understand your problem correctly, you're looking for a way to make your desktop client talk to your web application using the user's domain credentials. This should be easy to do using something like ADFS. If you run ADFS inside your clients Active Directory domain, your desktop client can get a token from it using Kerberos. It can then use this token to authenticate with your web application. You will need to configure your web application to trust tokens issued by the ADFS instance in your clients domain.
{ "pile_set_name": "StackExchange" }
Q: Draw points all over my form i want to draw 1px points allover my form example: 1pxBlack 1pxwhite 1pxBlack 1pxwhite 1pxBlack 1pxwhite 1pxBlack 1pxwhite 1pxBlack 1pxwhite 1pxBlack 1pxwhite 1pxBlack 1pxwhite 1pxBlack 1pxwhite 1pxBlack 1pxwhite A: you can use setPixel example: Dim bmp As New Bitmap(Me.Width, Me.Height) For y = 0 To Me.Height - 1 For x = 0 To Me.Width - 1 If x Mod 2 = 0 And y Mod 2 = 0 Then bmp.SetPixel(x, y, Color.Black) Else bmp.SetPixel(x, y, Color.White) End If Next Next Me.BackgroundImage = bmp
{ "pile_set_name": "StackExchange" }
Q: Can a form submit be disabled if a HTML file input field is empty? In a form which contains only a <input id="fileInput" name="BugReport" type="file" /> input field, I would like to disable the Submit button if the file input is empty (no file was chosen yet). Is there a recommended way to do this? A: Add the required attribute to the input. It'll only work in browsers that support it, so you should have a JavaScript alternative (<form onSubmit="if(document.getElementById('fileinput').value == '') return false;"> or something along those lines).
{ "pile_set_name": "StackExchange" }
Q: Xamarin.Forms Carousel Page Swipe Event Page Changing I'm using the Carousel Page that ships with Xamarin Form (2.5.0) and would like to be able to detect when a page is about to change. Each Page has some validation and if this fails I want to prevent the user from moving to the next page. Currently the only event I can see is PageChanged and this is where I trigger the validation, however the user must swipe back to see the error message. Is there a way to hook into the native swipe event? The App is currently targeting iOS, however it will eventually need to support Android. A: I know it's a bit late, but maybe someone else might also ask, so here's an idea: As you wrote, in protected override void OnCurrentPageChanged() you could find out when a user swiped to the next page. Now if you do the validation for the previous page, you could go back to the previous page in case of error with int index = Children.IndexOf(CurrentPage); this.CurrentPage = this.Children[index-1]; This does not prevent the user from leaving the page (as there is no 'OnSwipingStart' or else), but the user will see the error without having to move back manually. If you are happy to use a different control than CarouselPage: There is a pull request to get CarouselView into native Xamarin Forms. It has a Scrolled-Event which is triggered already on the first percent swiped so you could do your actions there.
{ "pile_set_name": "StackExchange" }
Q: Symfony3 + Assetic : ParameterNotFoundException I'm working on a Symfony 3.4 application. Assetic bundle wasn't installed, so I made : $ composer require symfony/assetic-bundle and add it in the appKernel.php : new Symfony\Bundle\AsseticBundle\AsseticBundle(), It worked perfect. Then, in my app/config/config.yml, I added : # app/config/config.yml assetic: debug: '%kernel.debug%' use_controller: '%kernel.debug%' filters: cssrewrite: ~ # ... and now my front-end is no more available, this is the error displayed with app_dev.php : ParameterNotFoundException You have requested a non-existent parameter "templating.engines". Even if I remove the Assetic configuration out of the config.yml the error is here. I have been searching in all my *.yml files I do not find any property "templating.engines" .... any idea ? A: Try adding the following in the config.yml framework: ... templating: engines: ['twig']
{ "pile_set_name": "StackExchange" }
Q: SSRS 3.0 Report Map + Map Report Part change position when run I have created a simple geographic map using Report Builder 3.0. In order to have a sub-section of the map to zoom in on, I published a report part from a different report and included it on my map like so: However when the report is run it moves the report part outside of the map like this: The print view shows a things back as I would expect. The eventual target for this map will be as a SharePoint PerformancePoint Services Report. Does anyone know why I am experiencing this odd behaviour? A: From the MSDN article about report rendering Overlapping Report Items Overlapping report items are not supported in HTML, MHTML, Word, Excel, in Preview, or the Report Viewer. If overlapping items exist, they are moved. The following rules are applied to overlapping report items: If the vertical overlap of report items is greater, one of the overlapping items is moved to the right. The left-most item remains where it is positioned. If the horizontal overlap of report items is greater, one of the overlapping items is moved down. The top-most item remains where it is positioned. If the vertical and horizontal overlap is equal, one of the overlapping items is moved to the right. The left-most item remains where it is positioned. If an item must be moved to correct overlapping, adjacent report items move down and/or to the right to maintain a minimum amount of spacing between the item and the report items that end above it and/or to the left of it. For example, suppose two report items overlap vertically and a third report item is 2 inches to the right of them. When the overlapping report item is moved to the right, the third report item moves to the right as well in order to maintain the 2 inches between itself and the report item to its left. Overlapping report items are supported in hard page-break formats, including print. See also.
{ "pile_set_name": "StackExchange" }
Q: Can I launch app from my app for google home? I have a problem i want to launch playlist of a music streamming application (spotify, deezer, ...) from my custom app for google-home (I think we call that action) but I doesn't find how to do that. I have already try to play some sound with the tag but with that you can just play 120 second from an audio file. And I need a way to launch app not just play music A: I had some returns from Google and they told me that actually we can't launch other app from our app
{ "pile_set_name": "StackExchange" }
Q: Waterline - Where with sum of fields I've got the following model Test module.exports = { attributes: { a: { type: 'number' }, b: { type: 'number' } } } I would like to build a query that allows me to put sum of fields a and b in where statement. SQL equavilent: SELECT * FROM Test WHERE a + b = myValue I read in sails doc's about Criteria modifiers but there is no word about that. Is there any clever way to do that? Of course I can use native query but I would like to avoid that because I must use the sum along with other modifiers. The reason is I'm generating dynamic queries from separate files and with native queries I will have to also handle already defined functionality like or, and, etc. A: I found a workaround. Maybe it will be useful to someone. It is not stricte sails/node solution, but database one, however, it fits my case perfectly. From MySQL 5.7 there is something like generated columns. Columns are generated because the data in these columns are computed based on predefined expressions. All I had to do was add an extra, auto generated column to my Test model: module.exports = { attributes: { a: { type: 'number', columnType: 'int' }, b: { type: 'number', columnType: 'int' }, c: { type: 'number', columnType: 'int GENERATED ALWAYS AS(a + b) VIRTUAL' } } } Now I'm able to do such query: const result = await Test.find({ c: 2 }) ...and I get the correct result. Waterline treats my column like any other, database does everything instead of me. Of course I can mix it with other modifiers with no problems. I haven't seen any complications so far.
{ "pile_set_name": "StackExchange" }
Q: Is there an inbuilt function to expand ipv6 addresses? I'm working on a project where I need to expand IPv6 addresses. Is there an inbuilt function in Go? What I'm currently doing is ipv6 := "fe80:01::af0" addr := net.ParseIP(ipv6) fmt.Println(addr.String()) but this still prints fe80:01::af0 What I actually need is fe80:0001:0000:0000:0000:0000:0000:0af0 A: There's nothing in the standard library to do this, but it's easy to write your own function. One possible approach (of many): func FullIPv6(ip net.IP) string { dst := make([]byte, hex.EncodedLen(len(ip))) _ = hex.Encode(dst, ip) return string(dst[0:4]) + ":" + string(dst[4:8]) + ":" + string(dst[8:12]) + ":" + string(dst[12:16]) + ":" + string(dst[16:20]) + ":" + string(dst[20:24]) + ":" + string(dst[24:28]) + ":" + string(dst[28:]) } Playground
{ "pile_set_name": "StackExchange" }
Q: How to extract all rows from a large postgres table using python efficiently? I have been able to extract close to 3.5 mil rows from a postgres table using python and write to a file. However the process is extremely slow and I'm sure not the most efficient. Following is my code: import psycopg2, time,csv conn_string = "host='compute-1.amazonaws.com' dbname='re' user='data' password='reck' port=5433" conn = psycopg2.connect(conn_string) cursor = conn.cursor() quert = '''select data from table;''' cursor.execute(quert) def get_data(): while True: recs = cursor.fetchmany(10000) if not recs: break for columns in recs: # do transformation of data here yield(columns) solr_input=get_data() with open('prc_ind.csv','a') as fh: for i in solr_input: count += 1 if count % 1000 == 0: print(count) a,b,c,d = i['Skills'],i['Id'],i['History'],i['Industry'] fh.write("{0}|{1}|{2}|{3}\n".format(a,b,c,d)) The table has about 8 mil rows. I want to ask is there is a better, faster and less memory intensive way to accomplish this. A: I can see four fields, so I'll assume you are selecting only these. But even then, you are still loading 8 mil x 4 x n Bytes of data from what seems to be another server. So yes it'll take some time. Though you are trying to rebuild the wheel, why not use the PostgreSQL client? psql -d dbname -t -A -F"," -c "select * from users" > output.csv
{ "pile_set_name": "StackExchange" }
Q: Android licence for app Please clear up something for me. For my own interest I want to write an Android app to use on my phone, by me alone. Maybe written in Mono, or perhaps something else. It has been suggested to me that I will need to pay a license fee for this. The Android licensing documentation hasn't cleared this up in my mind. Do I need to implement any form of licensing or pay any license for this? I stress, the app will be for use by me alone (and maybe my wife), on my phone alone (or hers). It won't go near Google Play Store or anything like that. A: As long as you don't submit the app to Google Play store, you don't need the licence. You can use the app or even give it to your family and friends. However, you cannot submit to the app store.
{ "pile_set_name": "StackExchange" }
Q: Django Admin :: HTML Input In Django's admin panel: how do I add a form field that users can add unescaped HTML into? A: Use a standard TextField, the data gets saved unescaped. However, by default any data that is outputted in a template is automatically escaped. You can circumvent this by either disable autoescaping (bad idea!) by using the safe filter.
{ "pile_set_name": "StackExchange" }
Q: Logical error: Unable to determine the cause of segmentation fault for (i = (routeVector.size () - 1); i >= 0; i--) { cout << "Connected to -> " << routeVector[i].exitPoint; for (j = (routeVector.size () - 1); j >= 0; j--) { if (routeVector[i].selectedBranchesVector.size() > 0) { cout << "\n: routeVector[i].selectedBranchesVector[0].connectedExitPoint" << routeVector[i].selectedBranchesVector[0].connectedExitPoint; ******cout << "\nrouteVector[j].exitPoint:" << routeVector[j].exitPoint; if (routeVector[i].selectedBranchesVector[0].connectedExitPoint == routeVector[j].exitPoint) { cout << "Connected to -> " << routeVector[i].selectedBranchesVector[0].connectedExitPoint; } } } } The stared line is giving me a segmentation fault, I fail to understand why. If the "routeVector" had nothing in "selectedBranchesVector", it wouldn't have even reached the inside if. What can be the cause of the said problem? EDIT 1: To make the problem more clear, I printed out the two conditions of the statement and the error is shown on the stared line. The structures are: typedef struct branch { unsigned int distance; int connectedExitPoint; } branch; typedef struct route { int exitPoint; vector <branch> selectedBranchesVector; } route; vector <route> routeVector; A: This is dependent on the type of i and j - if i and j are unsigned, the above loops will loop back around quite happily - which is probably what is going on - print the indexes and you'll see...
{ "pile_set_name": "StackExchange" }
Q: Cannot invoke an expression whose type lacks a call signature. Type 'typeof ""' has no compatible call signatures React TypeScript I'm trying to convert three scripts from Javascript to TypeScript. The scripts can be found in this gist. I do however have one error left that I can't get rid of. Please note that this is my first React and TypeScript project so I can easily have missed something obvious. I'm using .tsx files and TypeScript 2.1. In the file: GoogleApiComponent.tsx import * as cache from './ScriptCache' ... componentWillMount() { this.scriptCache = cache({ <--Error TS2349 here google: GoogleApi({ apiKey: apiKey, libraries: libraries }) }); } Gives me this error: Cannot invoke an expression whose type lacks a call signature. Type 'typeof "ScriptCache"' has no compatible call signatures. ScriptCache.tsx looks like this: let counter = 0; let scriptMap = new Map(); export const ScriptCache = (function (global: any) { return function ScriptCache(scripts: any) { const Cache: any = {} ... A: Looks like you're import is not correct :) Please try to import it like this import cache from './ScriptCache'. If you just used the code from the gist the cache is also exported as default. If this does not work, try import { ScriptCache as cache } from './ScriptCache'. You do not need the as syntax. This is just so you don't have to change the variable names.
{ "pile_set_name": "StackExchange" }
Q: Trouble inserting dates into Oracle 11g Database I'm getting a missing comma error message which I can't seem to fix. My code is below. CREATE TABLE Customers ( C_Id int NOT NULL PRIMARY KEY, DOB date Age int, FirstName varchar(255), LastName varchar(255), City varchar(255), MemberSince int ); INSERT INTO Customers VALUES (C_Id.nextval,'TO_DATE( '02-DEC-1977', 'DD-MON-YYYY' )',37,'Joseph','Smith','Minneapolis',2004); A: This looks problematic to me: 'TO_DATE( '02-DEC-1977', 'DD-MON-YYYY' )' Try unquoting the TO_DATE like this: TO_DATE( '02-DEC-1977', 'DD-MON-YYYY' ) You might also need to create the sequence first: CREATE SEQUENCE C_Id MINVALUE 1 MAXVALUE 999999999999999999999999999 START WITH 1 INCREMENT BY 1 CACHE 20; CREATE TABLE Customers ( C_Id int NOT NULL PRIMARY KEY, DOB date, Age int, FirstName varchar(255), LastName varchar(255), City varchar(255), MemberSince int ); INSERT INTO Customers VALUES (C_Id.nextval,TO_DATE( '02-DEC-1977', 'DD-MON-YYYY' ),37,'Joseph','Smith','Minneapolis',2004);
{ "pile_set_name": "StackExchange" }
Q: how to extends and override array methods in typescript now I want to implement an array proxy. here's my code class ArrayProxy<T> extends Array<T> { constructor(data: T[]) { super(...data); } push(...items: T[]): number { var res = super.push(...items); console.log("push invoked!"); // some code to do extra operation. return res; } } var foo = new ArrayProxy(["aa","bb"]); foo.push("cc"); it seems that my override push methods was not invoked. and the foo variable is instance of Array other than ArrayProxy. my typescript version:2.3.2 tsconfig.json { "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true, "moduleResolution": "classic", "target": "es5", "module": "system", "outFile": "js/test.js" } } MyTest i looked for some solution but failed. class MyNewArray<T> extends Array<T> { getFirst() { return this[0]; } } var myArray = new MyNewArray<string>(); myArray.push("First Element"); console.log(myArray.getFirst()); // "First Element" from David Sherret but i got error. Uncaught (in promise) Error: myArray.getFirst is not a function Evaluating http://localhost:8080/application/test/application/ts/bind_test Loading application/ts/bind_test at Object.execute (test.js:1733) at j (system.js:4) at E (system.js:4) at O (system.js:4) at system.js:5 update it works when i add Object.setPrototypeOf(this, ArrayProxy.prototype); after the super call in ArrayProxy's constructor. thanks to @Aluan Haddad. A: Subclassing built-ins is currently broken. It is also extremely dangerous because when the code execute in es2015 compliant environments it will fail for functions like Map. Use composition and avoid these techniques. See here for reference: https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
{ "pile_set_name": "StackExchange" }
Q: can't rebuild solution after entering a pre-build command line I have just upgraded my visual studio to the 2015 edition. I have a solution with just two project. I can rebuild the solution and run the code fine. However I have an issue when I enter a parameter in the Properties > Build Events > Pre-build event command line. I have simply entered the following in the text box, /MTEST When I try to rebuild the solution I get the error message "The command "/MTEST" exited with code 9009". static void Main(string[] args) { if (args.Length == 0) NormalMonring(); else { for (int i = 0; i < args.Length - 1; i++) { switch(args[i].ToUpper()) { case "/AUTO": //code case "/MTEST": // code break; } } } } I have done something similar to this before and not had any issues don't understand what is happening? A: Pre-build event command line is meant for running command line programs before the build. Like if you have something that generates code that you will then build. If you are looking to pass that value to your console application when you debug it then you can set it in Debug->Start Options->Command line arguments.
{ "pile_set_name": "StackExchange" }
Q: How exactly does the Web spell work? A player in my group plays a Wizard who favors terrain controlling spells. One such spell that he uses is Web. Up to this point he would cast Web and it would spread on the ground, with it's effects as normal. Now after reading the spell myslf, I'm not so certain if it's supposed to work that way. The first paragraph states that the webs must be mounted between solid anchors: Web creates a many-layered mass of strong, sticky strands. These strands trap those caught in them. The strands are similar to spiderwebs but far larger and tougher. These masses must be anchored to two or more solid and diametrically opposed points or else the web collapses upon itself and disappears. I read this as two trees, or two pillars, etc, and not just spread on the ground. It says without these anchors the web just collapses and disappears. However, it also says that it effects a range of a 20 ft radius. Having it spread horizontally across the ground to me seems counter to the nature of it having to be anchored. But then does it spread vertically? The wording on this is very confusing and I'd like a second opinion before I do or do not return to my player and inform him he may or may not have been using Web incorrectly. A: All Area of Effect Spells are Three-Dimensional Unless Otherwise Specified Note the use of the phrase many-layered in the Web description. All areas of effect in 3.PF are fully three-dimensional unless, such as in the Blade Barrier spell, a different area is specified. Web does not specify that it isn't three-dimensional and as such takes up the entire space of its area between the two anchor points. As far as that not making physical sense...friend, it's Pathfinder. This is pretty high on the 'making physical sense' scale. Rules don't translate well to physics. A: You are correct, the Web needs to be anchored between walls, pillars, a floor and ceiling, etc. It can't be cast "out in the open" and it doesn't cover the floor like a rug. (It covers the entire radius, so it's effective against flying folks). A: Web does not work in the open, per se. If cast on a group in the open, it will exist between them, but not outside that group, per the description. In an enclosed space, however, it creates a stable mass. In a tunnel, it typically fills the tunnel for the effect diameter's length, in other words, 40' of tunnel up to about 10' wide and tall. in a crevass or ravine, it will create a sphere, chopped at the walls, but may have open space above and below. in a large, but not tall, room, like a 60x90' throne room with a 20' ceiling, it will create a roughly 30' diameter cylinder of web, stretched floor to ceiling. in a collonade more than 40' tall, it will create column width lines of web connecting all pillars within the radius of effect; if the effect is centered at waist height, this happens with a 20' or taller ceiling. If the outer walls are beyond the radius, then no connection to them happens. A generous GM might allow an angled "opposed" position, but that violates the intent.
{ "pile_set_name": "StackExchange" }
Q: What is proper way to stream media with Spring MVC I have a controller method that simply streams bytes for media (images, css, js, etc.) to the client. I first tried something like this: @RequestMapping(value="/path/to/media/**", method=RequestMethod.GET) @ResponseBody public byte[] getMedia(HttpServletRequest request) throws IOException { //logic for getting path to media on server return Files.readAllBytes(Paths.get(serverPathToMedia)); } I originally tested this in Firefox, and it all seemed to work fine. However, I then tried it in Chrome, and then found that none of the images work. So, I then changed it to something like this: @RequestMapping(value="/path/to/media/**", method=RequestMethod.GET) public ResponseEntity<byte[]> getMedia(HttpServletRequest request) throws IOException { //logic for getting path to media on server byte[] bytes = Files.readAllBytes(Paths.get(serverPathToMedia)); //logic for setting some header values like Content-Type and Content-Length return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK); } This gave the same results as before. I saw in the developer tools that my response headers were coming down as expected, but still no image bytes Next I tried something like this: @RequestMapping(value="/path/to/media/**", method=RequestMethod.GET) public void getMedia(HttpServletRequest request, HttpServletResponse response) throws IOException { //logic for getting path to media on server byte[] bytes = Files.readAllBytes(Paths.get(serverPathToMedia)); response.getOutputStream().write(bytes); } Without even setting any response headers, this works in Firefox and Chrome. Now, while I can just do it this last way since it works, this doesn't seem like the correct Spring MVC way. I want to know why the first two things I tried didn't work, as they seem more correct. Also, is there something I didn't try that would actually be the right way to do this? A: Your last approach is pretty much the way to go about it. The only change that I can suggest is to not keep the entire content file to be streamed in memory, instead to stream out the content with buffering - IOUtils from Apache commons can do this for you.
{ "pile_set_name": "StackExchange" }
Q: Linear Interploation using two arrays I have the following arrays: List_CD = [2410.412434205376, 2287.6750893063017, 2199.2602314650626, 2124.4647889960825, 2084.5846633116403, 2031.9053600816167, 1996.2844020790524, 1957.1098650203032, 1938.4110044030583, 1900.0783178367647, 1877.6396548046785, 1868.2902104714337, 1844.9165996383219, 1816.8682911816766] List_Dose = [10.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0] what I am trying to do is to do a simple interpolation using: dsize = numpy.interp(2000., List_CD, List_Dose) the result that expect is between 20.0 and 22.0 but I keep getting a value of 10.0 Can anyone help here please? A: xp : 1-D sequence of floats The x-coordinates of the data points, must be increasing. Your List_CD is not increasing. You can sort it in the following way: d = dict(zip(List_CD, List_Dose)) xp = sorted(d) yp = [d[x] for x in xp] numpy.interp(2000., xp, yp) # returns 21.791381359216665 or: order = numpy.argsort(List_CD) numpy.interp(2000., np.array(List_CD)[order], np.array(List_Dose)[order])
{ "pile_set_name": "StackExchange" }
Q: recursively traverse multidimensional dictionary and export to csv I've have a complex multidimensional dictionary that I want to export some of the the key value pairs to a csv file as a running log file. I've tried the various help with exporting to cvs functions and hacked away at most of the code example in stackoverflow on traversing multidimensional dictionaries but have failed to arrive at a solution. This problem is also unique in that it has only some key values I want to export. Here is the dictionary: cpu_stats = {'time_stamp': {'hour': 22, 'month': 5, 'second': 43, 'year': 2014, 'day': 29, 'minute': 31}, 'cpus': [[{'metric_type': 'CPU_INDEX', 'value': 1}, {'metric_type': 'CPU_TEMPERATURE', 'value': 39}, {'metric_type': 'CPU_FAN_SPEED', 'value': 12000}]]} I need to format the values in time_stamp into a yyyy-mm-dd hh:mm:ss and store it as the first cell of the row. I then need the values in 'cpus' for CPU_INDEX, CPU_TEMPERATURE, and CPU_FAN_SPEED in the same row as the time stamp. The csv file should look like this: time_stamp, cpu_index, cpu_temperature, cpu_fan_speed 2014-05-29, 1, 38, 12000 One example I've been hacking away on is: def walk_dict(seq, level=0): """Recursively traverse a multidimensional dictionary and print all keys and values. """ items = seq.items() items.sort() for v in items: if isinstance(v[1], dict): # Print the key before make a recursive call print "%s%s" % (" " * level, v[0]) nextlevel = level + 1 walk_dict(v[1], nextlevel) else: print "%s%s %s" % (" " * level, v[0], v[1]) I get the following output walk_dict(cpu_stats) cpus [[{'metric_type': 'CPU_INDEX', 'value': 1}, {'metric_type': 'CPU_TEMPERATURE', 'value': 38}, {'metric_type': 'CPU_FAN_SPEED', 'value': 12000}]] time_stamp day 29 hour 22 minute 17 month 5 second 19 year 2014 I have also been hacking away at this function as well hoping I can store the date information into variables that can then be formatted into a single string. Unfortuatly it has recursive calls which loose the local variables on subsequent calls. Using global was futile. def parseDictionary(obj, nested_level=0, output=sys.stdout): spacing = ' ' if type(obj) == dict: print >> output, '%s{' % ((nested_level) * spacing) for k, v in obj.items(): if hasattr(v, '__iter__'): # 1st level, prints time and cpus print >> output, '%s:' % (k) parseDictionary(v, nested_level + 1, output) else: # here is the work if k == "hour": hour = v elif k == "month": month = v elif k == "second": second = v elif k == "year": year = v elif k == "day": day = v elif k == "minute": minute = v print >> output, '%s %s' % (k, v) print >> output, '%s}' % (nested_level * spacing) elif type(obj) == list: print >> output, '%s[' % ((nested_level) * spacing) for v in obj: if hasattr(v, '__iter__'): parseDictionary(v, nested_level + 1, output) else: print >> output, '%s%s' % ((nested_level + 1) * spacing, v) print >> output, '%s]' % ((nested_level) * spacing) else: print >> output, '%s%s' % (nested_level * spacing, obj) if __name__ == "__main__": global year global month global day global hour global minute global second cpu_stats = {'time_stamp': {'hour': 22, 'month': 5, 'second': 43, 'year': 2014, 'day': 29, 'minute': 31}, 'cpus': [[{'metric_type': 'CPU_INDEX', 'value': 1}, {'metric_type': 'CPU_TEMPERATURE', 'value': 39}, {'metric_type': 'CPU_FAN_SPEED', 'value': 12000}]]} parseDictionary(cpu_stats) print '%s-%s-%s %s:%s:%s' % (year, month, day, hour, minute, second) output: { time_stamp: { hour 22 month 5 second 27 year 2014 day 29 minute 57 cpus: [ [ { metric_type CPU_INDEX value 1 { metric_type CPU_TEMPERATURE value 39 { metric_type CPU_FAN_SPEED value 12000 ] ] Traceback (most recent call last): File "./cpu.py", line 135, in <module> print '%s-%s-%s %s:%s:%s' % (year, month, day, hour, minute, second) NameError: global name 'year' is not defined Thanks, I appreciate any help in pointing me in the right direction as I'm currently at a loss. A: I agree with @desired login, however assuming you have no control of the incoming data and had to work with what you showed in your questions... You could just traverse it like so: cpu_stats = {'time_stamp': {'hour': 22, 'month': 5, 'second': 43, 'year': 2014, 'day': 29, 'minute': 31}, 'cpus': [ [{'metric_type': 'CPU_INDEX', 'value': 1}, {'metric_type': 'CPU_TEMPERATURE', 'value': 39}, {'metric_type': 'CPU_FAN_SPEED', 'value': 12000} ] ] } timestamp = '' for stats in cpu_stats.keys(): if stats == 'time_stamp': timestamp = '{year}-{month}-{day}'.format(**cpu_stats[stats]) if stats == 'cpus': for cpu in cpu_stats[stats]: cpu_index = '' cpu_temperature = '' cpu_fan_speed = '' for metric in cpu: if metric['metric_type'] == 'CPU_INDEX': cpu_index = str(metric['value']) elif metric['metric_type'] == 'CPU_TEMPERATURE': cpu_temperature = str(metric['value']) elif metric['metric_type'] == 'CPU_FAN_SPEED': cpu_fan_speed = str(metric['value']) print ','.join([timestamp, cpu_index, cpu_temperature, cpu_fan_speed])
{ "pile_set_name": "StackExchange" }
Q: Can the javascript .bind go up multiple levels? I have a piano Keyboard object in JavaScript and JQuery, like so: function Keyboard(name, size, xPos, yPos, octaves) { this.name = name; this.size = size; this.setDimensions = function (){}; this.highlightKeyboard = function (){}; ... etc. } It's got a bunch of methods to set dimensions, generate the keyboard using divs for the keys, generate major and minor scales referencing the classes of the divs, etc. I wrote 4 methods to highlight a major scale when I press a certain key, a minor scale when I press a different key, major and minor triads with two other keys. They all worked, but after writing them I realized all 4 methods use a lot of the same code so I've been trying to consolidate by bringing out most of the code into separate methods in the main Keyboard object so I can call them repeatedly. The problem I'm having now that I'm consolidating is getting the $(document).keypress objects to play nice with the external code. What I want is something like this (partial code sample—I left out all the code to generate the keyboard and everything else that wasn't relevant because it seems to be working OK other than this one issue): function Keyboard(name, size, xPos, yPos, octaves) { this.getMajorTonic = (function(userNote) { // code to determine myTonic return myTonic; }); this.setMajScale = function(myTonic) { var scale = []; // code to determine scale[]; return scale; }; this.setScaleClasses = function(scale) { // code to determine scale_classes[] return scale_classes; }; this.highlightKeyboard = function (scale, scale_classes){}; // code to add highlighted classes to my divs based // on the values in scale and scale_classes }; this.findMajorScales = function(userNote); var myTonic = this.getMajorTonic(userNote); var scale = this.setMajScale(myTonic); var scale_classes = this.setScaleClasses(scale); var highlightKeyboard = this.highlightKeyboard; $(document).keypress(function (event) { if (event.which === 109) { highlightKeyboard(scale, scale_classes) } }); }; } var keys = new Keyboard("piano", 1, 0, 0, 2); keys.findMajorScales("E"); The desired effect is that when I load the page, it generates a blank keyboard, but when I press the "m" key, it highlights the E Major scale using the this.highlightKeyboard method. So I want to pass the this.findMajorScales method a this.highlightKeyboard method with no arguments, and then have the arguments filled in and the method executed when the "m" key is pressed. Most everything works, including the ($document).keypress object—it executes other code, just not the this.highlightKeyboard method with the right arguments. How do I accomplish this? Does .bind have something to do with it? I can't really figure out if it's applicable here or if I need to do something else. Thanks so much! Jake A: So I want to pass the this.findMajorScales method a this.highlightKeyboard method with no arguments, and then have the arguments filled in and the method executed when the "m" key is pressed. You are listening for M fine, so the only problem you have is invoking highlightKeyboard in the correct context. Consider var foo = {bar: function () {return this}), bar = foo.bar; What will foo.bar() return? (foo) What will bar() return? (window or null or throws an error, etc) You have a lot of options There are several ways around this, you've already mentioned Function.prototype.bind and it may be conceptually easier for you to use Function.prototype.call, Function.prototype.apply or even passing the this variable through using another identifier instead. In either case, the default this in the handler will no longer be an instanceof Keyboard as the event is coming from document Using Function.prototype.bind you have a few options var highlightKeyboard = this.highlightKeyboard.bind(this); $(document).keypress(function (event) { if (event.which === 109) { highlightKeyboard(scale, scale_classes); } }); // or binding args ahead of time too var highlightKeyboard = this.highlightKeyboard.bind(this, scale, scale_classes); $(document).keypress(function (event) { if (event.which === 109) { highlightKeyboard(); } }); // or binding the handler $(document).keypress(function (event) { if (event.which === 109) { this.highlightKeyboard(scale, scale_classes); } }.bind(this)); Using Function.prototype.call or .apply, requires ref to this var highlightKeyboard = this.highlightKeyboard; var me = this; $(document).keypress(function (event) { if (event.which === 109) { highlightKeyboard.call(me, scale, scale_classes); } }); Just using a ref to this var me = this; $(document).keypress(function (event) { if (event.which === 109) { me.highlightKeyboard(scale, scale_classes); } }); Finally, one more solution is to write a function which generates what you want, this is very similar to what .bind is doing but is supported in environments that don't support .bind (read: legacy) $(document).keypress(function (me) { // this function generates the inside one return function (event) { // this is the function used as the handler if (event.which === 109) { me.highlightKeyboard(scale, scale_classes); } }; }(this)); // passing in `this` as param `me`
{ "pile_set_name": "StackExchange" }
Q: image map software for coordinates using magic wand Quick question... there are lots of ways to create an image map (old school, I know!) for a web page, but I have a requirement for one. I want to have an interactive map showing UK counties. I have the map, I have "mapspinner" (also dreamweaver) to do the polymap... but, I was wondering if there was a way to use a magic wand to get the area's coordinates? I have tried using photoshop export to illustrator paths, but the file doesn't contain any coords (as expected really!). Does anyone know a way to do this? (I see that fireworks might do it, but I don't have that software) thanks in advance. A: GIMP can do this. See http://docs.gimp.org/en/plug-in-imagemap.html for a tutorial of exactly the task you are trying to accomplish.
{ "pile_set_name": "StackExchange" }
Q: Force a browser's visibility setting to true I'm trying to set up some specs against a real (not headless) browser but some of the javascript on the target page only runs if the browser is visible (it doesn't need to be the active app). I've been perusing the W3C Page Visibility API docs and [MDN's] too but I can't see a way to manipulate the setting while running Watir. I know there's the option of running the spec on a headless machine but while I'm developing the specs it'd be handy to not have to switch back and forth between browser and terminal to avoid timeouts and failures. I've had a look for Chrome switches that might help and found this very helpful list but it doesn't appear to have the magic bullet either. I've also tried browser.execute_script('document.hidden = false'); but that had no effect. Any help or insight would be much appreciated. A: It's possible to force this status with a Javascript injection via execute_script. To simulate a visible document: Object.defineProperty(document, 'visibilityState', {value: 'visible', writable: true}); Object.defineProperty(document, 'hidden', {value: false, writable: true}); document.dispatchEvent(new Event("visibilitychange")); To simulate an hidden document: Object.defineProperty(document, 'visibilityState', {value: 'hidden', writable: true}); Object.defineProperty(document, 'hidden', {value: true, writable: true}); document.dispatchEvent(new Event("visibilitychange")); Note that you'll have to run it again if the page is reloaded.
{ "pile_set_name": "StackExchange" }
Q: Trying to get a count of labels used in Gmail using Gmail API I am trying to go one level deeper with the demo code that utilises labels to extract the count of each label used within my inbox. e.g label1 = 5, label2 =10 etc and with a date. Any suggestions? Demo code: function listLabels() { var response = Gmail.Users.Labels.list('me'); if (response.labels.length == 0) { Logger.log('No labels found.'); } else { Logger.log('Labels:'); for (var i = 0; i < response.labels.length; i++) { var label = response.labels[i]; Logger.log('- %s', label.name); } } } A: Using the Users.messages:list function call from the GMail API should get you your results. The trick here is to pass label.id to the labelIds argument as a list function listLabels() { var response = Gmail.Users.Labels.list('me'); if (response.labels.length == 0) { Logger.log('No labels found.'); } else { Logger.log('Labels:'); for (var i = 0; i < response.labels.length; i++) { var label = response.labels[i]; // Use the label name to get the messages that match this label var label_messages = Gmail.Users.Messages.list('me', {'labelIds': [label.id]}); Logger.log('%s = %s', label.name, label_messages.resultSizeEstimate); } } }
{ "pile_set_name": "StackExchange" }
Q: How to use HoC with React Native I have an listing app where users can add items for multiple categories, when they want to add new record, there are 3 related screens with this particular feature. All of those screens have <Header/> component, so i thought HoC would be nice here so that i can reuse it across 3 screens. However, i could not accomplish it. Here is what i tried so far: This is my HoC class import React, { Component } from 'react'; import { View, StyleSheet, Text, StatusBar } from 'react-native'; import Header from '../components/Header'; const NewAd = (WrappedComponent) => { class NewAdHoc extends Component { handleBackPress = () => { this.props.navigation.navigate('Home'); StatusBar.setBarStyle('dark-content', true); } render() { const {contentText, children} = this.props return ( <View style={styles.container}> <Header headerText={'Yeni ilan ekle'} onPress={this.handleBackPress} /> <View style={styles.contentContainer}> <Text style={styles.contentHeader}>{contentText}</Text> <WrappedComponent/> </View> </View> ); } } return NewAdHoc; } this is my screen: class NewAdScreen extends Component { render() { const Content = () => { return ( <View style={styles.flatListContainer}> <ListViewItem /> </View> ); } return ( NewAdHoc(Content) ) } } after that i am getting error TypeError: (0 , _NewAdHoc.NewAdHoc) is not a function(…) and i have no idea how can i fix it because this is my first time using hocs on a react-native app. I have looked why this error is popping and they suggest import components in this way: import {NewAdHoc} from '../hocs/NewAdHoc'; but even this is not solved it. any help will be appreciated, thanks. A: The main purpose of a HOC is to encapsulate and reuse stateful logic across components. Since you are just reusing some jsx and injecting nothing in WrappedComponent you should be using a regular component here: const NewAd = ({ contentText, children }) => { handleBackPress = () => { this.props.navigation.navigate('Home'); StatusBar.setBarStyle('dark-content', true); } return ( <View style={styles.container}> <Header headerText={'Yeni ilan ekle'} onPress={this.handleBackPress} /> <View style={styles.contentContainer}> <Text style={styles.contentHeader}>{contentText}</Text> {children} </View> </View> ); } And use it like this return( <> <NewAd> <Screen1 /> </NewAd> <NewAd> <Screen2 /> </NewAd> <NewAd> <Screen3 /> </NewAd> </> )
{ "pile_set_name": "StackExchange" }
Q: IE reading inherited font size from computed style (currentStyle) is incorrect I've put a little test case together here: http://jsfiddle.net/D4sLk/2/ Basically I have the following font sizes set: * (everything): 12px container: 20px test element: inherit The DOM hierarchy is: container > test element. In IE9, the font size is reported as 12px using testEl.currentStyle.fontSize but is displayed as 20px. In Chrome and FF it seems fine. Are there any workarounds to this issue? Or have I done something really stupid? A: Try using font-size: 1em instead of using inherit. The reason for this is because I've found that inherit seems to have issues in IE. It rendered fine when I looked in IE9, however for some reason testEl.currentStyle.fontSize and $(testEl).css('font-size') both returned 12px as well. I've read that to use font-size: inherit in IE8, you would need to specify a !DOCTYPE, however it should be fine in IE9 (http://www.w3schools.com/cssref/pr_font_font-size.asp). For some reason, testEl.currentStyle.fontSize and $(testEl).css('font-size') are not picking up the correct values in IE9. When you set the font-size to 1em, you are sizing it up to 100% of the parent font-size, which in this case results to 20px. From http://www.w3schools.com/cssref/css_units.asp: 1em is equal to the current font size. 2em means 2 times the size of the current font. E.g., if an element is displayed with a font of 12 pt, then '2em' is 24 pt. The 'em' is a very useful unit in CSS, since it can adapt automatically to the font that the reader uses As a result, computedStyle.fontSize and $(testEl).css('font-size'), should both return 20px. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Trouble posting a JavaScript object with an array of Key Value Pairs to Web Api I have an object (mockup below) I've populated client-side with JavaScript and I need to post it to my server. There's a corresponding type of object defined in a class server-side that I'm expecting to receive. When I attempt to post the object, everything posts fine except for a single property. This property is defined server-side as a List<KeyValuePair<Guid,Bar>>. The Bar doesn't seem to be the issue, as I can post that just fine. Client-side, I've attempted to reformat the corresponding property on the JavaScript object in a few ways (as an array of object pairs, as literal properties on the object, etc.), but it's always an empty list when it arrives at the server. I'm guessing this is a syntax issue, but I'm having trouble figuring out what the proper syntax is, and I'm seeing a lot of conflicting examples online. I'm hoping someone can speak from experience as to how this should be posted. //C# Class MockUp public class Foo { public Guid FooId {get;set;} public string Description {get;set;} public bool Inactive {get;set;} public List<KeyValuePair<Guid,Bar>> FooBar {get;set;} //This comes over as null regardless of how I arrange the object client-side. } //TypeScript Class MockUp class Foo { fooId: string; description: string; inactive: boolean; fooBar: Array<KeyValuePair>; } class KeyValuePair { key: string; value: Bar } class Bar { //...Implementation here mathces Bar on the server } A: Will work if you create a dto for foobar public class FooDto { public Guid FooId {get;set;} public string Description {get;set;} public bool Inactive {get;set;} public List<FooBarDto> FooBar {get;set;} } public class FooBarDto { public Guid Key {get;set;} public Bar Value {get;set;} } The reason why KeyValuePair will not work in this case is because the properties in KeyValuePair are read only, take a look here at the msdn docs you can see that the Key and Value proerties only have getters
{ "pile_set_name": "StackExchange" }
Q: @InitBinder in spring boot not working with @RequestBody If I use @InitBinder without limiting it,it is working fine with @RequestBody to validate my objects. @InitBinder private void initBinder(WebDataBinder binder) { binder.setValidator(validator); } @RequestMapping(method=RequestMethod.POST) public CustomerQuickRegisterEntity saveNewCustomer(@Valid @RequestBody CustomerQuickRegisterEntity customerEntity,BindingResult result) { if(result.hasErrors()) { return new CustomerQuickRegisterEntity(); } return customerQuickRegisterRepository.save(customerEntity); } But problem is that when i limit it to just one object by doing it as @InitBinder("customerEntity") it is not validating the object. So I have searched through stackoverflow and found that @InitBinding only works with objects annotated with @ModelAttribute. Then my question is that it is working fine with @RequestBody when I use it as @InitBinder but does not work well when I use it as @InitBinder("customerEntity") ...why is it so? Is there any other way to validate Objects(Not properties of object Individually) associated with @RequestBody A: This is an old question, but I've managed to get the @InitBinder annotation to bind my custom Validator to a @Valid @RequestBody parameter like this: @InitBinder private void bindMyCustomValidator(WebDataBinder binder) { if ("entityList".equals(binder.getObjectName())) { binder.addValidators(new MyCustomValidator()); } } If you try to filter the bound argument by setting the value of the annotation, then it won't work for a @RequestBody argument. So here I check the object name instead. My method parameter is actually called entities, but Spring had decided to call it entityList. I had to debug it to discover this. A: From the docs, Default is to apply to all command/form attributes and all request parameters processed by the annotated handler class. Specifying model attribute names or request parameter names here restricts the init-binder method to those specific attributes/parameters, with different init-binder methods typically applying to different groups of attributes or parameters. Please have a look here
{ "pile_set_name": "StackExchange" }
Q: How to split a page in six equally sized sectors? I'd like to split an A4 page into six equally sized sectors. I want that page to be in landscape. Each sector has a body of text and a caption. I don't really have an idea where to start. I know I can split a page in to columns, but I need like six minipages, all equally arranged on one paper. The only idea I could come up with, is to use a0poster and then size it down for print. I think however, this is overkill; isn't there a better way to do that? I'm preferably using XeLaTeX, if that is of any importance. A: You can use six minipages; I defined a \Block command using a minipage of the desired width and length with two arguments: the text and the caption (make the necessary formatting adjustments). I added some frames just for visualization purposes (and they will produce some overfull boxes); please delete the lines marked with %delete: \documentclass{article} \usepackage[landscape]{geometry} \newcommand\Block[2]{% \setlength\fboxsep{0pt}\setlength\fboxrule{0.1pt}% delete \fbox{% delete \begin{minipage}[c][.5\textheight][t]{0.333333\textwidth} #1\par #2 \end{minipage}% }% delete } \begin{document} \noindent \Block{text}{caption}% \Block{text}{caption}% \Block{text}{caption}% \par\nointerlineskip\noindent \Block{text}{caption}% \Block{text}{caption}% \Block{text}{caption} \end{document} To meet the requirements in the comment: \documentclass{article} \usepackage[margin=3cm,centering,landscape]{geometry} \newcommand\Block[2]{% \setlength\fboxsep{0pt}\setlength\fboxrule{0.1pt}% delete \fbox{% delete \begin{minipage}[c][\dimexpr.5\textheight-2pt\relax][c]{\dimexpr0.3333333\textwidth-3pt\relax} \centering #1\par #2 \end{minipage}% }% delete } \begin{document} \thispagestyle{empty}% optional: suppress page numbering \noindent \Block{text}{caption}\hfill% \Block{text}{caption}\hfill% \Block{text}{caption}% \vfill \noindent\Block{text}{caption}\hfill% \Block{text}{caption}\hfill% \Block{text}{caption} \end{document} Using some of the options for the geometry package, the text area layout can be modified at will. A: Here's a solution using the pdfpages package. It consists of two steps: First you produce a document with a small paper size, and then you produce another document that combines these small pages onto one A4 landscape page. This is your actual document, where you put all of your text etc. You might have to adapt the margins, page numbers, etc. to your needs. % This file is called sixpages-doc.tex \documentclass{article} \usepackage[paperwidth=9.9cm,paperheight=10.5cm]{geometry} % paperwidth is A4/3, paperheight is A4/2 \usepackage{lipsum}% just for filler text \begin{document} \lipsum[1-6] \end{document} This is the document that puts the six pages on one page: \documentclass{article} \usepackage[landscape,a4paper]{geometry} \usepackage{pdfpages} \begin{document} \includepdf[pages=-,nup=3x2]{sixpages-doc.pdf} % pages=- means all pages % nup "Puts multiple logical pages onto each sheet of paper. The syntax of % this option is: nup=⟨xnup⟩x⟨ynup⟩." (from the manual) % If you want this layout: % 1 3 5 % 2 4 6 % use the option "column". \end{document} This is the output of the second document: A: I know that you want to use minipages. But here is a version using \parbox. You can't have certain things like footnotes here. This answer is given just to complete the list. We ride on Gonzalo's code (thanks @Gonzalo) and modify a bit: \documentclass{article} \usepackage[landscape]{geometry} \newcommand\Block[2]{% \setlength\fboxsep{0pt}\setlength\fboxrule{0.1pt}% delete \fbox{% delete \parbox[c][.5\textheight][t]{0.3\textwidth} {#1\par #2} % }% delete } \begin{document} \noindent \Block{text}{caption}\hfill \Block{text}{caption}\hfill \Block{text}{caption}% \vfill\noindent \Block{text}{caption}\hfill \Block{text}{caption}\hfill \Block{text}{caption} \end{document}
{ "pile_set_name": "StackExchange" }
Q: VB.NET [Cross-thread operation not valid: Control 'txtIncomingText' accessed from a thread........] I'm a beginner in VB.NET, please bear with me. I've downloaded a multiclient TCP-IP Socket Server-Client application in VB.NET. The Server listens pretty well, but the Client encounters below exception: "Cross-thread operation not valid: Control 'txtIncomingText' accessed from a thread other than the thread it was created on." I'll be greateful if you guys could help me with corrected version of the code. Thank you. ' ------- CLIENT CODE ------- Imports System.Windows.Forms Imports System.Collections.Generic Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Linq Imports System.Net Imports System.Net.Sockets Imports System.Text Imports System.Threading Public Class frmClient Inherits Form Private Sub frmClient_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load End Sub Private _clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) Public Sub New() InitializeComponent() End Sub Private receivedBuf As Byte() = New Byte(1023) {} Private thr As Thread Private Sub ReceiveData(ar As IAsyncResult) Dim socket As Socket = DirectCast(ar.AsyncState, Socket) Dim received As Integer = socket.EndReceive(ar) Dim dataBuf As Byte() = New Byte(received - 1) {} Array.Copy(receivedBuf, dataBuf, received) ' These two lines encounter an error ->>>>> txtIncomingText.Text = (Encoding.ASCII.GetString(dataBuf)) rbChat.Text = "\nServer: " + txtIncomingText.Text _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), _clientSocket) End Sub Private Sub SendLoop() While True 'Console.WriteLine("Enter a request: "); 'string req = Console.ReadLine(); 'byte[] buffer = Encoding.ASCII.GetBytes(req); '_clientSocket.Send(buffer); Dim receivedBuf As Byte() = New Byte(1023) {} Dim rev As Integer = _clientSocket.Receive(receivedBuf) If rev <> 0 Then Dim data As Byte() = New Byte(rev - 1) {} Array.Copy(receivedBuf, data, rev) lbStt.Text = ("Received: " + Encoding.ASCII.GetString(data)) rbChat.AppendText(vbLf & "Server: " + Encoding.ASCII.GetString(data)) Else _clientSocket.Close() End If End While End Sub Private Sub LoopConnect() Dim attempts As Integer = 0 While Not _clientSocket.Connected Try attempts += 1 _clientSocket.Connect(IPAddress.Loopback, 420) Catch generatedExceptionName As SocketException 'Console.Clear(); lbStt.Text = ("Connection attempts: " + attempts.ToString()) End Try End While lbStt.Text = ("Connected!") End Sub Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click If _clientSocket.Connected Then Dim buffer As Byte() = Encoding.ASCII.GetBytes(txtText.Text) _clientSocket.Send(buffer) rbChat.AppendText("Client: " + txtText.Text) End If End Sub Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click LoopConnect() ' SendLoop(); _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), _clientSocket) Dim buffer As Byte() = Encoding.ASCII.GetBytes("@@" + txtName.Text) _clientSocket.Send(buffer) End Sub End Class A: Well, you should invoke the calls on the control's thread. This is a quick and dirty solution Dim message = Encoding.ASCII.GetString(dataBuf) txtIncomingText.Invoke(Sub() txtIncomingText.Text = message) rbChat.Invoke(Sub() rbChat.Text = Environment.NewLine & "Server: " & message) But you should check if invocation is required first. See https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx Also, "\n" is not how you make a new line in vb.net (did you copy this code from c#?). And + is not how you concatenate strings in vb.net (see above parenthesis).
{ "pile_set_name": "StackExchange" }
Q: Mediawiki: how to allow users to edit their User pages (but not other pages) Is there a permission in Mediawiki that allows a user with username A-User to create and edit pages A-User, A-User/A-new-page etc but not to edit other pages? A: Not by default. You can find the list of permissions here, and the permissions each user group on a wiki has at Special:ListGroupRights. There is editmyusercss/editmyuserjs which allows users to edit user subpages ending in .css/.js, but probably even that requires the normal edit right. It would be pretty simple to write an extension granting that right, though. See UserPageEditProtection for a similar example (which does the opposite: instead of granting the right to edit own subpages, it takes away the right to edit others' subpages). You could make it do what you want by tweaking the return values in the userCan hook a bit.
{ "pile_set_name": "StackExchange" }
Q: Gallerific .selected Element I'm having a problem with the selected element in Galleriffic. When an image is selected it is not highlighting the correct thumb, it's highlighting the previous one. Edited to remove a soon to be dead link of the website. JS: <script type="text/javascript"> jQuery(document).ready(function($) { // We only want these styles applied when javascript is enabled $('div.navigation').css({'width' : '100%', 'clear' : 'both'}); $('div.content').css('display', 'block'); // Initially set opacity on thumbs and add // additional styling for hover effect on thumbs var onMouseOutOpacity = .7; $('#thumbs ul.thumbs li').opacityrollover({ mouseOutOpacity: onMouseOutOpacity, mouseOverOpacity: 1.0, fadeSpeed: 'fast', exemptionSelector: '.selected' }); // Initialize Advanced Galleriffic Gallery var gallery = $('#thumbs').galleriffic({ delay: 2500, preloadAhead: 10, enableTopPager: true, enableBottomPager: true, maxPagesToShow: 7, imageContainerSel: '#slideshow', controlsContainerSel: '#controls', captionContainerSel: '#caption', loadingContainerSel: '#loading', renderSSControls: false, renderNavControls: false, playLinkText: 'Play Slideshow', pauseLinkText: 'Pause Slideshow', prevLinkText: '&lsaquo; Previous Photo', nextLinkText: 'Next Photo &rsaquo;', nextPageLinkText: 'Next &rsaquo;', prevPageLinkText: '&lsaquo; Prev', enableHistory: false, autoStart: false, syncTransitions: true, defaultTransitionDuration: 900, onSlideChange: function(prevIndex, nextIndex) { // 'this' refers to the gallery, which is an extension of $('#thumbs') this.find('ul.thumbs').children() .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end() .eq(nextIndex).fadeTo('fast', 1.0); }, onPageTransitionOut: function(callback) { this.fadeTo('fast', 0.0, callback); }, onPageTransitionIn: function() { this.fadeTo('fast', 1.0); } }); }); </script> CSS div.slideshow a.advance-link { display: block; width: 820px; height: 388px; /* This should be set to be at least the height of the largest image in the slideshow */ line-height: 0px; /* This should be set to be at least the height of the largest image in the slideshow */ text-align: center; } div.slideshow a.advance-link:hover, div.slideshow a.advance-link:active, div.slideshow a.advance-link:visited { text-decoration: none; } div.download { float: right; } div.image-title { font-weight: bold; font-size: 1.4em; } div.image-desc { } div.navigation { /* The navigation style is set using jQuery so that the javascript specific styles won't be applied unless javascript is enabled. */ text-align: left; } ul.thumbs { clear: both; margin: 0; padding: 0; background-color: #FFF; } ul.thumbs li { display:inline; margin-right: 10px; padding: 0; list-style: none; } a.thumb { display:inline-block; text-decoration: none; } ul.thumbs li.selected a.thumb { color: #0C3 } a.thumb:focus { outline: none; text-decoration: none; } ul.thumbs img { border: none; display: block; } div.pagination { clear: both; } div.navigation div.top { padding-top: 10px; margin-top: 10px; text-align: center; background-color: #fff; } div.navigation div.bottom { text-align: center; } div.pagination a, div.pagination span.current, div.pagination span.ellipsis { display: block; float: left; } div.pagination a:hover { background-color: #eee; text-decoration: none; } div.pagination span.current { font-weight: bold; background-color: #000; border-color: #000; color: #fff; } div.pagination span.ellipsis { border: none; } A: There was an indexing problem, the was considered like an index which was causing it to start off at the wrong place. Solved it! :)
{ "pile_set_name": "StackExchange" }
Q: Keeping XML in Memory between Webservice Calls First, I don't want to use a database or a local file. Is it possible to store variables in memory so they don't have to be created each time the webservice is called? The problem is that FullCompanyListCreateXML(); takes about 1 Minute to create the XDocument. So is there any way to prevent that the xml variable is dropped after the webservice call is finished? [WebMethod(CacheDuration = 120)] public String FullCooperationListChunkGet(int part, int chunksize) { StringBuilder output_xml = new StringBuilder(); XDocument xml = FullCompanyListCreateXML(); IEnumerable<XElement> xml_query = xml.Root.Elements("Cooperation").Skip(part * chunksize).Take(chunksize); foreach (XElement x in xml_query) { output_xml.Append(x.ToString()); } output_xml.Insert(0, "<Cooperations>"); output_xml.Append("</Cooperations>"); return output_xml.ToString().Zip(); } Thanks, Henrik A: 2 ways: 1) You can add a global.asax class to the web service which will get created when the web application is first started, and will persist for as long as the worker process keeps it in memory. Override the 2) create a static class to hold the values See this blog entry, or this post on the topic of adding the global.asax class to web services. You can create things when the session starts, or when the application starts by overriding the Session_Start or Application_Start methods
{ "pile_set_name": "StackExchange" }
Q: Set limits for add content in text file with PHP I need to create a list of last logged members in my website, but i don't wanna user MySQL. i did some search in stackoverflow and Google and wrote this code: ////////////CHECK LIMIT $storage = "engine/data/write.txt"; $readz = file_get_contents($storage); $listz = explode('|||',$readz); $counter = count( $listz ); if($counter > "3"){ $stop = "1"; }else{ $stop = "0"; } if($stop == "0"){ ///REMOVE MEMBER IF AVAILABLE if ( preg_match("<!-- UserID: {$member_id} -->", $readz)){ $content = file_get_contents($storage); $content = str_replace("<!-- UserID: {$member_id} -->".$user."|||", '', $content); file_put_contents($storage, $content); } //ADD MEMBER AGAIN if ( !preg_match("<!-- UserID: {$member_id} -->", $readz)){ $beonline_file = fopen($storage, "a+"); fwrite($beonline_file, "<!-- UserID: {$member_id} -->".$user."|||"); fclose($beonline_file); } } Problem is i can't set limit! how i can edit this code to set limit to add only 20 users in text file? A: Maybe you can do this? if ( !preg_match("<!-- UserID: {$member_id} -->", $readz)){ $nlistz = explode('|||',$readz); if(count( $nlistz ) == 20){ array_shift($nlistz); $newlistz = implode("|||",$nlistz); $beonline_file = fopen($storage, "w+"); fwrite($beonline_file, $newlistz."|||<!-- UserID: {$member_id} -->".$user."|||"); fclose($beonline_file); }else{ $beonline_file = fopen($storage, "a+"); fwrite($beonline_file, "<!-- UserID: {$member_id} -->".$user."|||"); fclose($beonline_file); } }
{ "pile_set_name": "StackExchange" }
Q: Value not showing for input field using one way binding angular2 Objective: Get a collection of values based on the dropdown selection and place them in hidden input fields to be included in my model; The relative html: <select class="selectFoo" (change)="onSelect($event.target.value)" name="FooName" ngModel> <option selected="selected">--Select--</option> <option *ngFor="let foo of foos" [value]="foo.ID">{{foo.Name}} </option> </select> <input type="hidden" [value]="fooAddress" name="FooAddress" ngModel/> In the code above I called a function named OnSelect to get the data about the selected foo. The foos are populated using a webservice call. Here is the snippet from my ts file. import { Component, OnInit } from '@angular/core'; import { Foo } from './model'; import { DataService } from './data.service'; @Component({ moduleId: module.id, selector: 'add-on', templateUrl: './app.component.html' }) export class AppComponent implements OnInit { foos : Foo[]; selectedFoo: Foo; fooAddress: string; onSelect(fooID){ this.selectedFoo = null; for(var i = 0; i < this.foos.length; i++) { console.log(this.foos[i].ID); if(this.foos[i].ID == fooID){ this.selectedFoo = this.foos[i]; this.fooAddress = this.selectedFoo.Address.toString(); } } } } I originally tried one way binding my value to the selectedFoo but I was getting an error indicating my Address value wasn't defined. I noticed I could set the value equal to selectedFoo and it didn't error. So i created a new variable that was set to the fooAddress based on the selected foo. I get no value even though while stepping through the code I see it has a value. How can I get my value to populate so I can use it in my model? Let me know if I need to provide anything else. Thanks! A: If I am correctly understanding what you are after then something like this would work: <select name="FooName" [(ngModel)]="selectedFoo"> <option>--Select--</option> <option *ngFor="let foo of foos" [ngValue]="foo" >{{foo.Name}}</option> </select> <input type="hidden" [value]="selectedFoo?.Address" name="FooAddress" /> //Assuming your 'foo' items are e.g. { ID: 1, Name: 'Hello', Address: '123 Hello St'} Here you can bind the Address property of the selectedFoo directly to your hidden input field, rather than needing to handle the (change) event.
{ "pile_set_name": "StackExchange" }
Q: Switch flooding when bonding interfaces in Linux +--------+ | Host A | +----+---+ | eth0 (AA:AA:AA:AA:AA:AA) | | +----+-----+ | Switch 1 | (layer2/3) +----+-----+ | +----+-----+ | Switch 2 | +----+-----+ | +----------+----------+ +-------------------------+ Switch 3 +-------------------------+ | +----+-----------+----+ | | | | | | | | | | eth0 (B0:B0:B0:B0:B0:B0) | | eth4 (B4:B4:B4:B4:B4:B4) | | +----+-----------+----+ | | | Host B | | | +----+-----------+----+ | | eth1 (B1:B1:B1:B1:B1:B1) | | eth5 (B5:B5:B5:B5:B5:B5) | | | | | | | | | +------------------------------+ +------------------------------+ Topology overview Host A has a single NIC. Host B has four NICs which are bonded using the balance-alb mode. Both hosts run RHEL 6.0, and both are on the same IPv4 subnet. Traffic analysis Host A is sending data to Host B using some SQL database application. Traffic from Host A to Host B: The source int/MAC is eth0/AA:AA:AA:AA:AA:AA, the destination int/MAC is eth5/B5:B5:B5:B5:B5:B5. Traffic from Host B to Host A: The source int/MAC is eth0/B0:B0:B0:B0:B0:B0, the destination int/MAC is eth0/AA:AA:AA:AA:AA:AA. Once the TCP connection has been established, Host B sends no further frames out eth5. The MAC address of eth5 expires from the bridge tables of both Switch 1 & Switch 2. Switch 1 continues to receive frames from Host A which are destined for B5:B5:B5:B5:B5:B5. Because Switch 1 and Switch 2 no longer have bridge table entries for B5:B5:B5:B5:B5:B5, they flood the frames out all ports on the same VLAN (except for the one it came in on, of course). Reproduce If you ping Host B from a workstation which is connected to either Switch 1 or 2, B5:B5:B5:B5:B5:B5 re-enters the bridge tables and the flooding stops. After five minutes (the default bridge table timeout), flooding resumes. Question It is clear that on Host B, frames arrive on eth5 and exit out eth0. This seems ok as that's what the Linux bonding algorithm is designed to do - balance incoming and outgoing traffic. But since the switch stops receiving frames with the source MAC of eth5, it gets timed out of the bridge table, resulting in flooding. Is this normal? Why aren't any more frames originating from eth5? Is it because there is simply no other traffic going on (the only connection is a single large data transfer from Host A)? I've researched this for a long time and haven't found an answer. Documentation states that no switch changes are necessary when using mode 6 of the Linux interface bonding (balance-alb). Is this behavior occurring because Host B doesn't send any further packets out of eth5, whereas in normal circumstances it's expected that it would? One solution is to setup a cron job which pings Host B to keep the bridge table entries from timing out, but that seems like a dirty hack. A: Yes - this is expected. You've hit a fairly common issue with NIC bonding to hosts, unicast flooding. As you've noted, the timers on your switch for the hardware addresses in question as no frames sourced from these addresses are being observed. Here are the general options- 1.) Longer address table timeouts. On a mixed L2/L3 switch the ARP and CAM timers should be close to one another (with the CAM timer running a few seconds longer). This recommendation stands regardless of the rest of the configuration. On the L2 switch the timers can generally be set longer without too many problems. That said, unless you disable the timers altogether you'll be back in the same situation eventually if there isn't some kind of traffic sourcing from those other addresses. 2.) You could hard-code the MAC addresses on the switches in question (all of the switches in the diagram, unfortunately). This is obviously not optimal for a number of reasons. 3.) Change the bonding mode on the Linux side to one that uses a common source MAC (i.e. 802.3ad / LACP). This has a lot of operational advantages if your switch supports it. 4.) Generate gratuitous arps via a cron job from each interface. You may need some dummy IP's on the various interfaces to prevent an oscillation condition (i.e. the host's IP cycles through the various hardware addresses). 5.) If it's a traffic issue, just go to 10GE! (sorry - had to throw that in there) The LACP route is probably the most common and supportable and the switches can likely be configured to balance inbound traffic to the server fairly evenly across the various links. Failing that I think the gratuitous arp option is going to be the easiest to integrate.
{ "pile_set_name": "StackExchange" }
Q: Compile PHP on Linux or use apt-get / yum? I have been compiling PHP for years with the configuration options I want. I compile extensions I use from source. Is there an advantage to doing this versus installing it from a package manager like apt-get or yum. I assumed it would also give me a leaner binary. I noticed that their are PHP modules in the repos such as "php53-gd". What if there wasn't a package available for something I wanted such as cURL for PHP? I understand the disadvantages of compiling such as needing to download/install dependencies based on my configuration options. I'm not really concerned with that. So the question is: Compile PHP on Linux or just use apt-get / yum? Can I get all the things I need from the repos? Does anyone out there still compile it from source? Any insight is appreciated! Thanks. A: I compile from source every time. It's not hard to corral the mentioned issues with regards to compiling manually. For example, my ./configure settings are saved to a file which is version controlled, so when a new version of PHP is stable and I am ready to make the switch, I download and extract the file, then run this command: ./configure `sh /path/to/my/configure/php.sh` Not too difficult. And because it's in version control, I can add notes as to why a module was added or removed. Another benefit of manual compilation is it allows me to keep the PHP footprint as minimal as possible. I pass the --disable-all flag, then add the modules I need. However, there is a downside to this minimalist approach, recently I needed to install Magento, so I had to recompile with --enable-hash and --with-mcyrpt flags. Even though I needed to add new flags, it wasn't difficult to add to the configure file and recompile.
{ "pile_set_name": "StackExchange" }
Q: How to stop sending $_FILES['name'] if nobody provides thefile? I Have a multipart/form-data form but I not require from users to send me the picture. I am changing the name of the file to random number and the put the path to MySQL. Whenever somebody doesn't put the file, in my database a new recor is beeing created without an extension(obviesly). How to stop this from happening? Sorry for my english. Here is a a part from the code: case 'Sleep Aid': { ?> <section class="summarySection"> <div class="summaryHeadingDIV"> <h1 class="summaryH1">Please check the details below</h1> </div> <article class="summaryPage"> <p class="boldSummaryDescr">Brand:</p><p class="paraSummary"><?php echo $brand; ?></p><br> <p class="boldSummaryDescr">Model:</p><p class="paraSummary"><?php echo $model; ?></p><br> <p class="boldSummaryDescr">Colour:</p><p class="paraSummary"><?php echo $colour; ?></p><br> <p class="boldSummaryDescr">Material:</p><p class="paraSummary"><?php echo $material; ?></p><br> <p class="boldSummaryDescr">Suitable Age:</p><p class="paraSummary"><?php echo $suitable; ?></p><br> <p class="boldSummaryDescr">Purchase date:</p><p class="paraSummary"><?php echo $month . '/' . $year; ?></p><br> <p class="boldSummaryDescr">Condition:</p><p class="paraSummary"><?php echo $condition; ?></p><br> <p class="boldSummaryDescr">Dimesions:</p><p class="paraSummary"><?php echo $width . ' cm <span class="smallcaps">x</span> ' . $height . ' cm <span class="smallcaps">x</span> ' . $depth . ' cm'; ?></p><br> <p class="boldSummaryDescr">Weight:</p><p class="paraSummary"><?php echo $weight . ' kg'; ?></p> </article> <div class="imageg_container"> <figure class="img_figure_show"> <?php if(empty($picture)) { ?> <img src="/_images/no-picture.png" alt="no picture added"> <?php } else { $random_id = rand_img_id(); add_file(db_user_connect(), $email, $random_id); $arry = show_picture(db_user_connect(), $email, $random_id); print "<img src=".$arry["sciezka"]." alt='product picture'>"; } ?> </figure> </div> <div class="clear-left"></div> <div class="summaryButtonContainer"> <a href="javascript:goBack();" class="summaryLinks" title="Go Back">Edit details</a> <a href="/_pages/transaction/quotation.php?location=sleepaid&brand=<?php echo urlencode($brand);?>&model=<?php echo urlencode($model)?>&month=<?php echo urlencode($month);?>&year=<?php echo urlencode($year);?>&condition=<?php echo urlencode($condition);?>" class="summaryLinks">Proced to Quote</a> </div> </section> <?php break; } A: You need to check the $_FILES['error'] value: if ($_FILES['name']['error'] === UPLOAD_ERR_OK) ... The manual lists all possible values, which you could use to display different messages/do different things: https://secure.php.net/manual/en/features.file-upload.errors.php
{ "pile_set_name": "StackExchange" }
Q: Can I make my desktop background active? I want my desktop background to look like the Chrome extension, Currently. How would I accomplish this? A: I can give you similar conky script but no 100%. You need to change the font, alignment and icon set. Result Step 1. Install conky sudo apt-get install conky Step 2. Install conky forecast sudo add-apt-repository ppa:conky-companions/ppa sudo apt-get update && sudo apt-get install conkyforecast Step 3. Save at home folder .conky1 .conky2 .weather-ob .conkyForecast.config Step 4. Open .conky2 and locate --location=MYXX0006 Replace MYXX0006 with you location code. You can find your code here Step 5. Run your conky By terminal: conky -c ~/.conky1 conky -c ~/.conky2 Make startup application Open startup application Name : Conky1 Command : conky -p 20 -c ~/.conky1 Name : Conky2 Command : conky -p 20 -c ~/.conky2
{ "pile_set_name": "StackExchange" }
Q: Woo Commerce - Offer to register at checkout (don't force) As the title says, is there anyway I can allow a customer to register at checkout. The ideal situation would be to get their shipping and billing address included in the registration at the same time they enter it for the actual purchase. However, I don't want to force the customer to register if they don't really want to. A: I don't know which version of woocommerce you have, but certainly the latest vesion let's you set if customer's can create an account at checkout, or if they can check out without account (guest checkout). These settings are all in: woocommerce/settings/accounts & privacy tab
{ "pile_set_name": "StackExchange" }
Q: ms-access: query (concat multiple records into one) here's a glimpse of the original table: Occurrence Number Occurrence Date 1 0 Preanalytical (Before Testing) Cup Type 2 0 Analytical (Testing Phase) 2 0 Area 3 0 Postanalytical ( After Testing) 4 0 Other Practice Code Comments 1477 2/5/2010 1.1 Specimen Mislabeled PURSLEY 1476 2/5/2010 1.1 Specimen Mislabeled HPMR 1475 2/5/2010 1.1 Specimen Mislabeled ACCIM N008710 1474 2/5/2010 1.1 Specimen Mislabeled ACCIM N008636 1473 2/5/2010 1.3 QNS-Quantity Not Sufficient SAPMC 1472 2/5/2010 1.3 QNS-Quantity Not Sufficient RMG 1471 2/5/2010 1.1 Specimen Mislabeled NMED 1470 2/5/2010 1.9 QNS- Specimen Spilled in transit MRPS 1469 2/5/2010 1.9 QNS- Specimen Spilled in transit ANESPC 1468 2/5/2010 2.22 Instrument Problem-reinject LAB 1525 2/8/2010 2.5 Other - False (+) Blanks Tecan 2 LAB 1524 2/8/2010 2.5 Other - False (+) Blanks Tecan #1 LAB Blank 019 1523 2/8/2010 2.22 Instrument Problem, 2.5 Other Tecan LAB 1519 2/8/2010 3.3A Reporting Error 4.1 LIS Problem? (see LOM 1418,1520) LAB/SJC F356028 1518 2/8/2010 1.4 Tests Missed/Wrong Test Ordered SDPTC F316628 1516 2/8/2010 1.6 Test Requisition Missing TPMCF 2 specimens both unlabeled 1515 2/8/2010 1.1 Specimen Mislabeled PALMETTO 1514 2/8/2010 1.1 Specimen Mislabeled THWR 1513 2/8/2010 1.1 Specimen Mislabeled THWR i am getting information from this table using the following statement: select mid(Lom1,1,4) as LOM, sum([Count1]) as [Count] from ( SELECT [Lab Occurrence Form].[1 0 Preanalytical (Before Testing)] as Lom1,Count([Lab Occurrence Form].[1 0 Preanalytical (Before Testing)]) AS [Count1] FROM [Lab Occurrence Form] WHERE ((([Lab Occurrence Form].[Occurrence Date]) Between [Forms]![Meeting_Reasons_Frequency]![Text4] And [Forms]![Meeting_Reasons_Frequency]![Text2])) GROUP BY [Lab Occurrence Form].[1 0 Preanalytical (Before Testing)] HAVING Count([Lab Occurrence Form].[1 0 Preanalytical (Before Testing)])<>0 UNION SELECT [Lab Occurrence Form].[2 0 Analytical (Testing Phase)], Count([Lab Occurrence Form].[2 0 Analytical (Testing Phase)]) AS [CountOf2 0 Analytical (Testing Phase)] FROM [Lab Occurrence Form] WHERE ((([Lab Occurrence Form].[Occurrence Date]) Between [Forms]![Meeting_Reasons_Frequency]![Text4] And [Forms]![Meeting_Reasons_Frequency]![Text2])) GROUP BY [Lab Occurrence Form].[2 0 Analytical (Testing Phase)] HAVING Count([Lab Occurrence Form].[2 0 Analytical (Testing Phase)])<>0 union SELECT [Lab Occurrence Form].[3 0 Postanalytical ( After Testing)], Count([Lab Occurrence Form].[3 0 Postanalytical ( After Testing)]) AS [CountOf3 0 Postanalytical ( After Testing)] FROM [Lab Occurrence Form] WHERE ((([Lab Occurrence Form].[Occurrence Date]) Between [Forms]![Meeting_Reasons_Frequency]![Text4] And [Forms]![Meeting_Reasons_Frequency]![Text2])) GROUP BY [Lab Occurrence Form].[3 0 Postanalytical ( After Testing)] HAVING Count([Lab Occurrence Form].[3 0 Postanalytical ( After Testing)])<>0 UNION SELECT [Lab Occurrence Form].[4 0 Other], Count([Lab Occurrence Form].[4 0 Other]) AS [CountOf4 0 Other] FROM [Lab Occurrence Form] WHERE ((([Lab Occurrence Form].[Occurrence Date]) Between [Forms]![Meeting_Reasons_Frequency]![Text4] And [Forms]![Meeting_Reasons_Frequency]![Text2])) GROUP BY [Lab Occurrence Form].[4 0 Other] HAVING Count([Lab Occurrence Form].[4 0 Other])<>0 ORDER BY 1, 2) group by mid(Lom1,1,4); this is what the query returns: LOM Count 1.1 231 1.11 21 1.3 103 1.4 6 1.5 1 1.6 25 1.8 2 1.9 88 2.1 8 2.22 5 2.24 1 2.3 1 2.4 1 2.5 29 3.2 13 3.3 8 3.3A 4 4.1 2 4.6 1 4.8 7 i need to add another column here. let's say it is column3 this is the output that need: LOM Count column3 1.1 231 everything from original table where LOM LIKE *1.1* separated by "," 1.11 21 everything from original table where LOM=1.11 separated by "," 1.3 103 everything from original table where LOM=1.3 separated by "," 1.4 6 everything from original table where LOM=1.4 separated by "," 1.5 1 everything from original table where LOM=1.5 separated by "," 1.6 25 1.8 2 1.9 88 2.1 8 2.22 5 2.24 1 2.3 1 2.4 1 2.5 29 3.2 13 3.3 8 3.3A 4 4.1 2 4.6 1 4.8 7 prac 1 that would mean the first element in column 3 would be "something1, something2, etc...somethingelse231" i apologize if this explanation is horrible, please let me know if i can clarify anything A: Here's one solution I found: http://www.access-programmers.co.uk/forums/showpost.php?p=272455&postcount=2 It requires writing a VBA function. I don't know of a way to do it with straight SQL in Access. Public Function Conc(Fieldx, Identity, Value, Source) As Variant Dim cnn As ADODB.Connection Dim rs As ADODB.Recordset Dim SQL As String Dim vFld As Variant Set cnn = CurrentProject.Connection Set rs = New ADODB.Recordset vFld = Null SQL = "SELECT [" & Fieldx & "] as Fld" & _ " FROM [" & Source & "]" & _ " WHERE [" & Identity & "]=" & Value ' open recordset. rs.Open SQL, cnn, adOpenForwardOnly, adLockReadOnly ' concatenate the field. Do While Not rs.EOF If Not IsNull(rs!Fld) Then vFld = vFld & ", " & rs!Fld End If rs.MoveNext Loop ' remove leading comma and space. vFld = Mid(vFld, 3) Set cnn = Nothing Set rs = Nothing ' return concatenated string. Conc = vFld End Function You can then use it in a query like this: SELECT [tblData].[ID], Conc("Field1","ID",[ID],"tblData") AS Field1, Conc("Field2","ID",[ID],"tblData") AS Field2 FROM tblData GROUP BY [tblData].[ID]; Edit So your first query would look something like this: SELECT [Lab Occurrence Form].[1 0 Preanalytical (Before Testing)] as Lom1, Conc("NameOfTheFieldToConcatenate", "[Lab Occurrence Form].[1 0 Preanalytical (Before Testing)]", [Lab Occurrence Form].[1 0 Preanalytical (Before Testing)], "[Lab Occurrence Form]"), Count([Lab Occurrence Form].[1 0 Preanalytical (Before Testing)]) AS [Count1] FROM [Lab Occurrence Form] WHERE ((([Lab Occurrence Form].[Occurrence Date]) Between [Forms]![Meeting_Reasons_Frequency]![Text4] And [Forms]![Meeting_Reasons_Frequency]![Text2])) GROUP BY [Lab Occurrence Form].[1 0 Preanalytical (Before Testing)] HAVING Count([Lab Occurrence Form].[1 0 Preanalytical (Before Testing)])<>0 Note that you may have to tweak the Conc() function a little to get the wildard compare you want instead of an exact match on the LOM field.
{ "pile_set_name": "StackExchange" }
Q: Infinite word size abstraction I was reading the java doc of BigInteger, they mentioned "infinite word size abstraction" more than one places. what are they referring to? https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html A: They are referring to word as processing unit for a computer processor. https://en.wikipedia.org/wiki/Word_(computer_architecture) The word size is normally a small number like 32 or 64 bits for a given processor, but BigInteger provides an abstraction for infinite word size.
{ "pile_set_name": "StackExchange" }
Q: sed command to be used to modify the file name I am able to use the sed command for a simple things but I have a question which for me is complex to find the solution by my own, so if some one can help me it would be a great favour. example: how shall I modify the following file as following? orig_file_name = OBIEE_S99_TT_PLV_BI0026.rpd target_file_name = OBIEE_S99_TT_PLV.rpd so in my bash script, I will be doing following. 1. check the latest file in a directory. 2. pickup that file and modify its name, similar as above. situations: I do not know always what would be the file name is, but i know the part of pattern, file names always ends as "something_is_name_xxxx.rpd" so then I would want to modify the file name as "something_is_name.rpd" A: I would do something like this, but i don't doubt there are better solutions. for f in $(ls -1t OBIEE_S99_TT_PLV* | head -1) do mv $f $(echo $f | sed 's/_BI[0-9]*//g') done
{ "pile_set_name": "StackExchange" }
Q: UltraDateTimeEditor - MinDate set to future date results in odd behavior If you set the MinDate on an UltraDateTimeEditor to a date that is today or in the past and then type in a date that is before the MinDate, the control clears the date (desired outcome). If you set a MinDate that is in the future and type in a date that is before the MinDate value, the control acts oddly. Example MinDate = 1/29/2014 Type in = 1/1/2014 Tab out of the control Date control shows 1/1/2020 After some trial and error, it appears that the control is taking the first two spaces in the year (2014) and treating it like a 2-digit version of the year (20). If you type in 1/1/1500, you get 1/1/2015. If you type in 1/1/1900 you get 1/1/2019. Is this a known issue (I couldn't find anything on it)? Is there a workaround that allows both the limiting of the dates on the dropdown, but also won't result in the odd behavior when a user tries to type a date in? A: I made a quick test using version 12.1 with the latest available service release - 12.1.20121.2135 and I could confirm that the issue is fixed. Please try to upgrade to latest available service release of version 12.1 or to one of latest versions (for example 13.1 or 13.2) where the issue is fixed. Let me know if you have any questions
{ "pile_set_name": "StackExchange" }
Q: insert duplicate keys to hash map I have created hash map and when I debug it I saw that I have duplicte keys. I didnt override the hashCode() & equals(Object obj) in the key - Object1 and i wonder how will it affect the performance of the map search? private HashMap<Object1,Object2> map = new HashMap<Object1,Object2>(); A: It is not possible to have duplicate keys in a Map, you have different keys that "appear" the same (Maybe based on their toString()? )because you have not overridden equals() and hashCode(), but in reality the keys are different. This means that in order to get all values from your Map you need to keep every key you created and store it somewhere, which to me defeats the purpose of the Map. Summary: Override equals() and hashCode(), then put your key/value pairs into the Map.
{ "pile_set_name": "StackExchange" }
Q: Printf waiting for enter int kr=0; int ss =0; while ((kr=getchar()) != EOF){ if(kr != '\n') { ss++; } printf("%d\n",ss); } With this code , printf is waiting until i press enter then printing all the sequential ss values at the same time like in this . Can somebody explain this behavior ? A: printf is not waiting it is getchar instead. getchar uses a buffer behind the scene. When that buffer is empty, getchar will read 1 line from stdin and then return the first caracter. If it is not empty, it will return the next caracter from the buffer immediatly. That means that the getchar will wait the first time you call it. And thus your printf is never executed until you press enter
{ "pile_set_name": "StackExchange" }
Q: How to pass record id from row to Test method? I delete 1 record from table. How to pass into test method selectedMR(this record Id) and cover in test method from controller below? VF PAGE: <apex:repeat value={!mrItems} var="mrItem"> <apex:column> <apex:facet name="header">Deleting</apex:facet> <apex:commandButton value="Del" action="{!deleteMR}" reRender="form"> <apex:param name="mritemId" value="{!mrItem.id}" assignTo="{!selectedMR}"/> </apex:commandButton> </apex:column> </apex:repeat> CONTROLLER public void deleteMR() { if (selectedMR == null) { return; } TERF_MR__c tobeDeleted = null; for (TERF_MR__c mr : mrList) if (mr.Id == selectedMR) { if (mr.TERF_MR_Status__c != 'Approved') { tobeDeleted = mr; break; } else { ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Info,'You can\'t delete approved month report')); } } if (tobeDeleted != null) { delete tobeDeleted; loadData(); } } TEST static testMethod void test1() { test.startTest(); TERF_MR__c MR = new TERF_MR__c(); Insert MR ; System.assert([SELECT Name FROM TERF_MR__c WHERE Id = :MR.Id].Name != null); PageReference testpage = new pageReference('/apex/TERF_Home'); testpage.getParameters().put('selectedMR', mr.Id); ApexPages.currentPage().getParameters().put('id', MR.id); TERF_Controller_Home contr = new TERF_Controller_Home(); contr.gotoTERF_CreateNew(); contr.deleteMR(); contr.goToSystem(); contr.save(); test.stopTest(); } A: For your test, set it directly on the controller: TERF_Controller_Home contr = new TERF_Controller_Home(); contr.selectedMR = mr.Id; ... contr.deleteMR(); Not sure, but you can probably also do it by naming the parameter to match this: <apex:param name="mritemId" value="{!mrItem.id}" assignTo="{!selectedMR}"/> i.e.: testpage.getParameters().put('mritemId', mr.Id);
{ "pile_set_name": "StackExchange" }
Q: HTML5 - Can it do this? Today? In HTML 5 is there any support for things which are really easy to do in Silverlight? For example, ripping a file (chosen by the user) into an array of bytes that can be base64 encoded and passed up to a web service? Or, creation/reading of an image and being able to manipulate the pixels and display this on screen? Or even save it to disk (location chosen by the user)? If so, which browsers would support this and are the APIs consistent? Thanks A: In HTML 5 is there any support for things which are really easy to do in Silverlight? See this For example, ripping a file (chosen by the user) into an array of bytes Yes. See this that can be base64 encoded Google and passed up to a web service? XMLHttpRequest still works. Or, creation/reading of an image and being able to manipulate the pixels and display this on screen? Yes. Combine FileReader with canvas. Or even save it to disk (location chosen by the user)? Sorry, not possible. No longer the case! See this. If so, which browsers would support this I know Firefox does, but try this on other browsers. See what works and what doesn't. and are the APIs consistent? Yes. These are called standards for a reason.
{ "pile_set_name": "StackExchange" }
Q: memory leak discovered MKMapView I have NSAutoreleasePool leaked object on a MKMapView. should I be concerned about this? I can't seem to get rid of it. I also noticed that the same leak occurs in apple's CurrentAddress sample code app link text A: If it depends from Apple's library do not be worried about it (plus it is just 32 byte : D)
{ "pile_set_name": "StackExchange" }
Q: Count multiple values with jquery I am trying to create counting function with jquery. I have multiple sets of inputs with numbers determined, something like: <input class="price" type="hidden" name="price" value="4"> <input class="count" type="text" name="count" maxlength="4"> I want to create script that will count all inputs, eg. (price * count) + (price * count) etc.. So far i came up with this script, which multiplies and displays only one input $('.count').blur(function() { var amount = parseFloat($(this).val()); var price = $(this).closest('tr').find('.price'); var result = parseFloat((price).val()); var money = (amount * result) $('.money').text(money); }); A: You need to use a loop inside your blur handler like var $counts = $('.count').blur(function () { var money = 0; $counts.each(function () { money += (+this.value * $(this).closest('tr').find('.price').val()) || 0 }); $('.money').text(money); }); Demo: Fiddle
{ "pile_set_name": "StackExchange" }
Q: Replace string in a database file with an input file list - Terminal I'd like to replace some file extension in an SQL file when I match strings from an input file using terminal. I have an input.txt containing a list of file paths. /2014/02/haru-sushi_copertina_apdesign-300x300.png /2014/02/haru-sushi_copertina_apdesign.png /2014/02/harusushi_01_apdesign-300x208.png ect ect Then I have a WordPress.sql file What I'd like to do, whenever I find a match between the 2 files, is to replace the extension from .png to .jpg in the database file of that matching. I hope I've made myself clear. Should I use sed with regular expressions? Something like cat input.txt | while read -r a; do sed -i 's/$a/.jpg/g' wordpress.sql; done Any suggestions? Even for the RegEx. A: sed is for simple substitutions on individual lines, that is all, and you should never write a shell loop just to manipulate text, see http://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice. Try this (uses GNU awk which I assume you have since you were using GNU sed): awk -i inplace 'NR==FNR { paths[$0]; next } { for (path in paths) { gsub(path,gensub(/png$/,"jpg",1,path)) } print } ' input.txt wordpress.sql It has some caveats related to partial matching but no worse than if you were trying to use sed and easily fixable if there's a problem (unlike with sed).
{ "pile_set_name": "StackExchange" }
Q: Generic of type RawRepresentable is misinterpreted as self it seems To use NSCoding with Swift's Enum type I made an extension on NSCoder: extension NSCoder { func encodeEnum<Enum: RawRepresentable where Enum.RawValue == String>(value: Enum, forKey key: String) { self.encodeObject(value.rawValue, forKey: key) } func decodeEnumForKey<Enum: RawRepresentable where Enum.RawValue == String>(key: String) -> Enum? { guard let returnValue = self.decodeObjectForKey(key) as? String else { return nil } return Enum(rawValue: returnValue) } } The encodeEnum method works fine for a String-backed Enum, but when I try to decode the prior encoded Enum like so: enum MyEnum: String { case Something, Other } class MyEnumClass: NSObject, NSCoding { let myEnum: MyEnum init(myEnum: MyEnum) { self.myEnum = myEnum } required convenience init?(coder aDecoder: NSCoder) { guard let tmp = aDecoder.decodeEnumForKey("myKey") as? MyEnum else { return nil } self.init(myEnum: tmp) } } I get an error on aDecoder.decodeEnumForKey("myKey"): Value of type `NSCoder` has no member `RawValue` I'm pretty sure it has something to do with the generic and the condition that Enum.RawValue == String. But I do not understand while it's not working, but works for encodeEnum(). A: The problem is that in guard let tmp = aDecoder.decodeEnumForKey("myKey") as? MyEnum else { return nil } the compiler cannot infer the generic placeholder of func decodeEnumForKey<Enum: ...>(key: String) -> Enum? to be MyEnum, you have to cast the result to MyEnum? instead: guard let tmp = aDecoder.decodeEnumForKey("myKey") as MyEnum? else { return nil } so that the return type is inferred as MyEnum? from the calling context.
{ "pile_set_name": "StackExchange" }
Q: Does Vow of Peace's calming aura affect the caster? Are you affected by your own calming aura? I would think the answer is "no" since you cannot re-enter the area (so maybe you were affected by it initially, but that only lasted until someone took a swing at you). A: Technically yes, but only once upon taking the feat, so basically no. The effect of the aura is described (BoED p. 48) as: ...you are constantly surrounded by a calming aura to a radius of 20 feet. Creatures within the aura must make a successful Will save (DC 10 + one-half your character level + your Cha modifier) or be affected as by the calm emotions spell. Creatures who leave the aura and reenter it receive new saving throws. A creature that makes a successful saving throw and remains in the aura is unaffected until it leaves the aura and reenters. The aura is a mind-affecting, supernatural compulsion. "Creatures within the aura" doesn't make an exception for the character who took the feat, so they're affected the same as anyone else inside the aura (including the clause about ignoring it if they make their saving throw). However, the effect of the aura works as the calm emotions spell, which says: Any aggressive action against or damage dealt to a calmed creature immediately breaks the spell on all calmed creatures. So, even if they fail their save, the first time anything takes an aggressive action against the vow-taker, the calm emotions effect will end. Since, as the question points out, there's no way for a creature to leave the effect of its own aura (which would refresh the effect)...it will probably just never be affected again. In most D&D campaigns, even a character devoted to peace is going to be the target of at least one aggressive action pretty early on. So, this isn't likely to be a concern for very long.
{ "pile_set_name": "StackExchange" }
Q: What's the simplest way to extend a numpy array in 2 dimensions? I have a 2d array that looks like this: XX xx What's the most efficient way to add an extra row and column: xxy xxy yyy For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible: xxaxx xxaxx aaaaa xxaxx xxaxx A: The shortest in terms of lines of code i can think of is for the first question. >>> import numpy as np >>> p = np.array([[1,2],[3,4]]) >>> p = np.append(p, [[5,6]], 0) >>> p = np.append(p, [[7],[8],[9]],1) >>> p array([[1, 2, 7], [3, 4, 8], [5, 6, 9]]) And the for the second question p = np.array(range(20)) >>> p.shape = (4,5) >>> p array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) >>> n = 2 >>> p = np.append(p[:n],p[n+1:],0) >>> p = np.append(p[...,:n],p[...,n+1:],1) >>> p array([[ 0, 1, 3, 4], [ 5, 6, 8, 9], [15, 16, 18, 19]]) A: A useful alternative answer to the first question, using the examples from tomeedee’s answer, would be to use numpy’s vstack and column_stack methods: Given a matrix p, >>> import numpy as np >>> p = np.array([ [1,2] , [3,4] ]) an augmented matrix can be generated by: >>> p = np.vstack( [ p , [5 , 6] ] ) >>> p = np.column_stack( [ p , [ 7 , 8 , 9 ] ] ) >>> p array([[1, 2, 7], [3, 4, 8], [5, 6, 9]]) These methods may be convenient in practice than np.append() as they allow 1D arrays to be appended to a matrix without any modification, in contrast to the following scenario: >>> p = np.array([ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] ) >>> p = np.append( p , [ 7 , 8 , 9 ] , 1 ) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/dist-packages/numpy/lib/function_base.py", line 3234, in append return concatenate((arr, values), axis=axis) ValueError: arrays must have same number of dimensions In answer to the second question, a nice way to remove rows and columns is to use logical array indexing as follows: Given a matrix p, >>> p = np.arange( 20 ).reshape( ( 4 , 5 ) ) suppose we want to remove row 1 and column 2: >>> r , c = 1 , 2 >>> p = p [ np.arange( p.shape[0] ) != r , : ] >>> p = p [ : , np.arange( p.shape[1] ) != c ] >>> p array([[ 0, 1, 3, 4], [10, 11, 13, 14], [15, 16, 18, 19]]) Note - for reformed Matlab users - if you wanted to do these in a one-liner you need to index twice: >>> p = np.arange( 20 ).reshape( ( 4 , 5 ) ) >>> p = p [ np.arange( p.shape[0] ) != r , : ] [ : , np.arange( p.shape[1] ) != c ] This technique can also be extended to remove sets of rows and columns, so if we wanted to remove rows 0 & 2 and columns 1, 2 & 3 we could use numpy's setdiff1d function to generate the desired logical index: >>> p = np.arange( 20 ).reshape( ( 4 , 5 ) ) >>> r = [ 0 , 2 ] >>> c = [ 1 , 2 , 3 ] >>> p = p [ np.setdiff1d( np.arange( p.shape[0] ), r ) , : ] >>> p = p [ : , np.setdiff1d( np.arange( p.shape[1] ) , c ) ] >>> p array([[ 5, 9], [15, 19]]) A: Another elegant solution to the first question may be the insert command: p = np.array([[1,2],[3,4]]) p = np.insert(p, 2, values=0, axis=1) # insert values before column 2 Leads to: array([[1, 2, 0], [3, 4, 0]]) insert may be slower than append but allows you to fill the whole row/column with one value easily. As for the second question, delete has been suggested before: p = np.delete(p, 2, axis=1) Which restores the original array again: array([[1, 2], [3, 4]])
{ "pile_set_name": "StackExchange" }
Q: How can you quickly check if you package.json file has modules that could be updated to newer versions? How can you quickly check if you package.json file has modules that could be updated to newer versions? For example, a quick way to check if either express or nodemailer has an available update? { "name": "some_module_name" , "description": "" , "version": "0.0.3" , "dependencies": { "express": "3.1" , "nodemailer" : "0.4.0" } } I read over the FAQs, but didn't see anything: https://npmjs.org/doc/faq.html Thanks. A: Yes there is an option : npm outdated This will list modules, with available updates. It supports syntax for specifying the module name. According to the Documentation, the syntax is npm outdated [<name> [<name> ...]] This gives you to specify the module name you wish to check exclusively, like $ npm outdated mongoose Note To use this properly, you'll have to add a version number of the target module(s) with range greater than or greater than or equal. You can check node-semver, which is integrated into npm to check the syntax. Example { "dependencies": { "express": "3.2.0", "mongoose": ">= 3.5.6", }, } Will give the following result ( since today the latest mongoose version is 3.6.9 ) $ npm outdated ... [email protected] node_modules/mongoose current=3.6.7 $ While if you place { "dependencies": { "express": ">= 3.2.0", "mongoose": ">= 3.5.6", }, } The result will be : $ npm outdated ... [email protected] node_modules/mongoose current=3.6.7 [email protected] node_modules/express current=3.2.0 $ A: there's a service like travis that checks it automatically: https://gemnasium.com
{ "pile_set_name": "StackExchange" }
Q: Configure apache for system passwords? I know I can use htpasswd to create a password file for apache, but how do I configure it to use valid users or groups from the system? A: You'll need to use an appropriate authentication module. Here's an example with mod_authnz_external: http://blog.innerewut.de/2007/6/26/apache-2-2-authentication-with-mod_authnz_external
{ "pile_set_name": "StackExchange" }
Q: Attach debugger (using eclipse) to play framework failed I am using Scala to write a web on top of Play framework with eclipse IDE. I am trying to debug my app but hit debug attach failure. I tried to switch using Java instead of Scala,but I got same error. This is what I do. Create a project and run play clean compile run play debug run in Eclipse, set 'debug configration' ->remote java application -> host: localhost, port:9999 and common: debug in browser type in URL and enter: localhost:9999. Then get the following failure in play framework command line: Debugger failed to attach: handshake failed - received >GET / HTTP/1.1< - expected >JDWP-Handshake< Any idea what is wrong? A: localhost:9999 is what Eclipse is going to use to communicate with your application. On your browser, you still access your application on localhost:9000 (default) or however you would access your application had you just done play run. Basically, you've configured your debugging correctly in Eclipse. Now, with your configuration selected from the Debug Configuration, click Debug (or selected your configuration from the Debug As toolbar button). Eclipse will attach to localhost:9999. Browse to localhost:9000 like you normally would to access your application. That's it. Eclipse will pause on any breakpoints you have set, etc.
{ "pile_set_name": "StackExchange" }
Q: Linux bash thing I try to create a little bash script, with which I have no experience. I try to do something like: #!/bin/bash statut="na" if [ $proc = 0 ]; then statut = "closed" else statut = "opened" fi but I receive: ./test.sh: line 4: statut: command not found Can you give me a hint? On Google I couldn't find something similar. All if examples are with echo not with variable assignation. Thank you! A: That's because you're not following a syntax for assignment operator - you should remove spaces around '=' (and quote $proc): #!/bin/bash statut="na" if [ "$proc" = 0 ]; then statut="closed" else statut="opened" fi
{ "pile_set_name": "StackExchange" }
Q: Achieving dark matte background in studio I've been trying to achieve a dark matte background (maybe with some texture on it) in a studio, but i have a limited experience with backdrops and so far i haven't been able to produce satisfying results. Here's what i do: i hang a black seamless paper backdrop i put a very dim strobe on it (just for a little gradient) i put my model a few meters from the background In this situation the results are pretty good, but only for headshots. And since i have limited space, i can't shoot full-length portraits with the model so far away from the background. So ... as soon as i get the model closer to the background and as soon as more light starts hitting it ... the results are terrible: the background looks very uneven, and obviously, there's this terrible line of light where the background curves near the ground. It takes huge amounts of post-processing to fix it and even then it looks horrible. So my question is ... how do i get a matte look even when a model is close to the background? Below is an example of what i'm talking about (WARNING: slightly NSFW). It looks to me as if the background in the sample image was simply done in post, but i believe there are some backdrop materials that could achieve a decent result as well. What are your thoughts on this? Sample image (slightly NSFW): https://500px.com/photo/83383151/catia-by-paulo-latães (as you can see, instead of a white highlighted horizontal area we have a beautiful dark shadow where the background curves on the ground) Thanks for your input A: Black seamless is not what you want to be using to get a midnight grey background in a small space; it takes quite a bit of light to lift the values, and there's no way to sneak enough light in without making the paper seem glossy in spots. (With a lot more room, you can control the angles to avoid shine or use softer light without worrying about spill.) Seamless is pretty heavily sized and calandered as matte papers go; it's glossier than most people think it is. A more truly matte paper, like a good pastel paper with a lot of "tooth", would need to be much heavier to avoid easy tearing in sheets/rolls that size. You'll probably find that a charcoal grey or "black tie-dye" fabric (muslin) will give you fewer problems, provided that you steam or press it and hang it carefully. Canvas would be better, except that the fabric will be coarse enough to show texture with your subject so close to the background. That may or may not be a problem, depending on your tastes. A good muslin isn't especially cheap, but you can test the concept using a small remnant (about a linear metre) from a fabric store. You want something dark enough that it's easy to let it fall to black when unlit (or not well-lit), but that will be near enough your desired grey value when lit as the model is lit.
{ "pile_set_name": "StackExchange" }
Q: How to build rpm package correctly? I'm trying to install the new version from ganglia, which provides a tar.gz. My procedure was uncompress the tar.gz file, enter in the folder and then makes rpmbuild -ba ganglia.spec, a warning message is given saying about the dependencies libraries missing, then I install them via yum, then gives the rpmbuild again, which generates some .rpm files at /usr/src/RPM/ I did this in a centOS 5 and centOS 6. Then install it in some servers. I wonder if what I'm doing is correct ? (I read some tutorials over the internet only) A friend of mine said that this is wrong, that this .rpm that I generate is like compile and will work only for servers with exactly hardware only, is that right ? What is the correct way to build an .rpm package from .tar.gz file ? A: That's the correct way. It's the responsibility of the persons releasing the .tar.gz to have the proper rpm spec file, if it's meant to be built as an rpm. And that's how you build the rpm from the spec file. The rpm files you generate that way can be installed on all matching servers, provided you have not deliberately done things that prevent them from working (like installing weird versions of the "dependencies", but if you have installed packages only from the centos base repositories, the packages will be good). But "matching" here means both centos/rhel version AND architecture. Architecture usually means just 32-bit or 64-bit x86, but there are also arm, powerpc and other architectures. For example, the Fedora project supports these architectures: https://fedoraproject.org/wiki/Architectures . Anyway some rpms (architecture specific) can be installed on a certain architecture because they contain compiled code. Other rpms can be "noarch", which means the generated rpm can be installed on any architecture. This kind of rpms don't have compiled binaries in them, only data or interpreted language programs (shell, perl, python etc).
{ "pile_set_name": "StackExchange" }