source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0007356488.txt" ]
Q: jquery ui autocomplete does't close options menu if there is no focus when ajax returns I'm using jquery ui autocomplete widget with ajax, and on noticed the following problem. Background: In order for the user to be able to focus on the autocomplete and get the options without typing anything, I use the focus event: autoComp.focus(function() { $(this).autocomplete("search", "");} However this produces the following effect: when the user clicks, an ajax request is being sent. While waiting for the response, the user then clicks elsewhere and the autocomplete is blurred. But as soon as the response returns, the options menu pops out, even though the autocomplete has no focus. In order to make it go away the user has to click once inside, and again outside the autocomplete, which is a bit annoying. any ideas how I prevent this? EDIT: I solved this in a very ugly way by building another mediator function that knows the element's ID, and this function calls the ajax function with the ID, which on success check the focus of the element, and returns null if it's not focused. It's pretty ugly and I'm still looking for alternatives. EDIT#2: Tried to do as Wlliam suggested, still doesn't work.. the xhr is undefined when blurring. Some kind of a problem with the this keyword, maybe it has different meanings if I write the getTags function outside of the autocomplete? this.autocomplete = $('.tab#'+this.id+' #tags').autocomplete({ minLength: 0, autoFocus: true, source: getTags, select: function(e, obj) { tab_id = $(this).parents('.tab').attr('id'); tabs[tab_id].addTag(obj.item.label, obj.item.id, false); $(this).blur(); // This is done so that the options menu won't pop up again. return false; // This is done so that the value will not stay in the input box after selection. }, open: function() {}, close: function() {} }); $('.tab#'+this.id+' #tags').focus(function() { $(this).autocomplete("search", ""); }); $('.tab#'+this.id+' #tags').blur(function() { console.log('blurring'); var xhr = $(this).data('xhr'); // This comes out undefined... :( if (xhr) { xhr.abort(); }; $(this).removeClass('ui-autocomplete-loading'); }); and this is the getTags function copied to the source keyword: function getTags(request, response) { console.log('Getting tags.'); $(this).data('xhr', $.ajax({ url: '/rpc', dataType: 'json', data: { action: 'GetLabels', arg0: JSON.stringify(request.term) }, success: function(data) { console.log('Tags arrived:'); tags = []; for (i in data) { a = {} a.id = data[i]['key']; a.label = data[i]['name']; tags.push(a); } response(tags); } })); console.log($(this).data('xhr')); } A: I think you need to use the callback option for the source, in order to abort the AJAX request. Quoting from the overview of the autocomplete widget: The callback gets two arguments: A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo". A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties). It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state. In your case, it'll probably look something like the following: $("#autoComp").autocomplete({ source: function(request, response) { var searchString = request.term; // ajax call to remote server, perhaps filtered with searchString $(this).data('xhr', $.ajax({ ... success: function(data) { ... // pass back the data filtered by searchString response(filteredList); } })); }, minLength: 0, focus: function() { $(this).autocomplete("search"); } }) // cancel the request when user click away from the input box .blur(function() { var xhr = $(this).data('xhr'); if (xhr) xhr.abort(); });
[ "stackoverflow", "0022977339.txt" ]
Q: Using @section inside Razor Helper We are trying to setup Sections of our layout to be Required but configurable based on the individual page. At the moment we do this with a Section. @section FloatingNav { <h1>@Model.Name <span class="release-year">@Model.AverageRating</span></h1> <ul class="sub-nav"> <li class="active"><a href="#episodes">Episodes</a></li> <li><a href="#episodes">Cast</a></li> <li>Reviews</li> <li>Related</li> </ul> } This requires you to setup this block in every new page but i wanted to make this process easier with some defaults and options to configure using a partial view. I was hoping to setup a Razor helper such as this. @using System.Web.Mvc.Html @helper FloatingNav(string name, int rating) { @section FloatingNav { <h1> name <span class="release-year">rating</span></h1> <ul class="sub-nav"> <li class="active"><a href="#episodes">Episodes</a></li> <li><a href="#episodes">Cast</a></li> <li>Reviews</li> <li>Related</li> </ul> } } @helper FloatingNav(System.Web.Mvc.HtmlHelper html, string viewName) { @section FloatingNav { @html.Partial(viewName) } } @helper FloatingNav(System.Web.Mvc.HtmlHelper html, string viewName, object model) { @section FloatingNav { @html.Partial(viewName, model) } } So the syntax to implement would be something like @Layout.FloatingNav(@Model.Name, @Model.AverageRating) or @Layout.FloatingNav("_SimpleNav", @Model) The issue though is that it seems the Razor Helpers do not understand the section syntax. Is there a way to include sections in Razor Helpers? A: I don't think this is possible. The @helper and @section syntax are special directives for compiling pages. A HelperResult (a helper) doesn't know how to define a section. The DefineSection method belongs to a WebPageBase. You might have to come at this from a different direction. Using partial views instead of helpers would probably fix this problem.
[ "stackoverflow", "0006003714.txt" ]
Q: Build XML object on iOS with XCode 4, i.e. with KissXML The official NSXML stuff doesn't work on iOS, according to manual (and trial and error). There are some other projects, but most are just XML parsers. But I want to create XML objects. There is KissXML, but the tutorial on the website only shows how to set up XCode 3 for it. I can't seem to get it to work in XCode 4. There are no positions called "Linking" or "Header search path" in my build settings in XCode 4. I clicked "Add Build Settings" and added "header_search_paths" and "other_ldflags" as seen in the screenshot from XCode 3, but that doesn't work. Are there any other projects to build XML objects on iOS? Or is there a tutorial on how to get KissXML to work in XCode 4? Thanks, MrB A: The "getting started"-section of the original source home page contains the best information to get it up and running. Just follow the steps exactly as they're described there and you should be ready to go in 5 minutes. http://code.google.com/p/kissxml/wiki/GettingStarted
[ "stackoverflow", "0012167363.txt" ]
Q: MVC3 Music Store Tutorial Connection String issue I'm working my way through the MVC Music Store Tutorial and am running into an issue when I try to connect to the database using the entity framework model. I've tried a number of these walkthroughs, and I'm continuing to run into problems when I get to this part. I do not want to use SQL Compact Edition (although I've tried to install it just to get the tutorials to work). Rather, I have SQL Server Developer 2005 Edition as well as a named instance of SQL2008 Express (again, installed just to see if I could get the tutorial to work). Here is my connection string: <connectionStrings> <add name="MusicStoreEntities" connectionString="server=2-BQZ5DP1\DELS2008EXPRESS;Integrated Security=SSPI;database=MvcMusicStore"/> </connectionStrings> The closing tag for the connectionStrings element will not post in the code snippet, so pretend that it is there. What do I need to do differently? 2-BQZ5DP1 is the name of my box, and the SQL Express instance is a named instance. A: You generally need MultipleActiveResultSets=True with Entity Framework when you're using SQL Server editions other than Compact. Depending on what the error you are seeing is, that might be your problem. For more on connection string options, see this blog: http://blogs.msdn.com/b/aspnetue/archive/2012/08/14/sql-server-connection-strings-for-asp-net-web-applications.aspx
[ "stackoverflow", "0024359881.txt" ]
Q: Ms access sub report keeps overlapping, why? I have an access database with a report that contains several subreport. the problem is that the subreport keeps overlapping. I have used the Can Grow = Yes on all report and nothing works. however, when I'm in print preview the report loads fine but report view is where I'm having the problem. what can i do to fix this? thanks PS. im using access 2007 and the database format is .mdb A: I've found the answer on Microsoft's Website. I needed to install Office 2007 suite Service Pack 2 they have an excel sheet with all the changes under the section Downloadable list of issues that the service pack fixes on this page. :)
[ "stackoverflow", "0055652070.txt" ]
Q: Why VS and gcc call different conversion operators here (const vs non-const)? This piece of code is dumb of course, but I only wrote it to illustrate the issue. Here it is: #include <iostream> using namespace std; struct foo { int a = 42; template <typename T> operator T* () { cout << "operator T*()\n"; return reinterpret_cast<T*>(&a); } template <typename T> operator const T* () const { cout << "operator const T*() const\n"; return reinterpret_cast<const T*>(&a); } template <typename T> T get() { cout << "T get()\n"; return this->operator T(); } }; int main() { foo myFoo; cout << *myFoo.get<const int*>() << '\n'; } The output when compiled with Visual Studio 2019 (ISO C++17, /Ox) is: T get() operator const T*() const 42 The output with gcc 8.3 (-std=c++17, -O3) is: T get() operator T*() 42 So I'm wondering why the two compilers opt to call different const-qualified conversions given this code? If I change get() to get() const, then both call the const version of the conversion. But isn't VS violating the standard by calling the const conversion from a method that isn't marked const? EDIT: To clear up some confusion around reinterpret_cast, here's a version without it which still produces the same output on both compilers. A: The method: template <typename T> foo::T get(); is not const. That implies inside its body the object this is a pointer to foo type (and not const foo). Therefore, the statement this->operator T(); is going to call the no-const version because of the overload resolution. As the standard states on [over.match.best], the version no-const is preferred because does not require any cast. Indeed, in order to call the const version, the compiler should have implicitly cast into a const object (i.e. const_cast<const foo*>(this)). Both gcc and clang follow what I have just said. MSVC simply does not follow the standard here.
[ "stackoverflow", "0035607835.txt" ]
Q: Pass variable to resource class in Jersey I'm trying to use a variable that is passed through command line arguments to the main function and that should be somehow visible inside a resource class in jersey. My main function: public class MyApp extends ResourceConfig { public MyApp(String directory) { // I would like the MyResource.class to have access to the // variable that is passed in the main function below, // which is the directory variable register(MyResurce.class); } public void startHttpServer(int port) { ... } // args[0]: a port to start a HTTP server // args[1]: a string that is CONSTANT and UNIQUE throughout the // full execution of the app, and the MyResource.class resource // should be able to read it. How can I pass this variable to the resource? public static void main(String[] args) { final MyApp app = new MyApp(args[1]); int port = Integer.parseInt(args[0]); app.startHttpServer(port); } } The resource class has nothing special, only @GET, @DELETE and @POST methods. What should I do so that the variable given in args[1] is visible not only to the MyResource.class but to all resources registered? A: If you inject, in your resource class, the JAX-RS application you can access the properties Map: @Path(...) public class MyResource { @Context private Application app; @GET @Path(...) public String someMethod() { String directory = app.getProperties().get("directory"); ... } } Then, your main class would be like this: public class MyApp extends ResourceConfig { public MyApp(String directory) { register(MyResource.class); Map<String, Object> properties = new HashMap<>(); properties.put("directory", directory); setProperties(properties); } public void startHttpServer(int port) { ... } public static void main(String[] args) { final MyApp app = new MyApp(args[1]); int port = Integer.parseInt(args[0]); app.startHttpServer(port); } } You can do the above since ResourceConfig extends Application.
[ "math.stackexchange", "0001540298.txt" ]
Q: Proving $\sqrt{2}x-\sqrt{x^{2}+1} \geq \frac{\sqrt{2}}{2}\ln{(x)}$ How can I prove that $$ x\sqrt{2}-\sqrt{x^{2}+1} \geq \frac{\sqrt{2}}{2}\ln{(x)} $$ It's a derivation-based process if I remember correctly, however I was unable to prove it correctly. A: Let's get rid of $\sqrt{2}$ by rewriting the inequality as $$ f(x)=2x-\sqrt{2(x^2+1)}-\ln x\ge0 $$ We have $\lim_{x\to0}f(x)=\infty$. For computing the limit at $\infty$, we do the substitution $t=1/x$, so the limit becomes $$ \lim_{t\to0^+}\frac{2}{t}-\frac{\sqrt{2(t^2+1)}}{t}+\ln t= \lim_{t\to0^+}\frac{2-\sqrt{2(t^2+1)}+t\ln t}{t}=\infty $$ Thus we know that $f$ has at least a point of minimum. Compute the derivative $$ f'(x)=2-\frac{2x}{\sqrt{2(x^2+1)}}-\frac{1}{x} =2-\frac{x\sqrt{2}}{\sqrt{x^2+1}}-\frac{1}{x} $$ Let's go on: $$ f''(x)=-\sqrt{2}\,\frac{\sqrt{x^2+1}-\dfrac{x^2}{\sqrt{x^2+1}}}{x^2+1} +\frac{1}{x^2} =-\sqrt{2}\,\frac{1}{(x^2+1)\sqrt{x^2+1}}+\frac{1}{x^2} $$ and we want to evaluate the sign of $$ (x^2+1)\sqrt{x^2+1}-x^2\sqrt{2} $$ that is, where $(x^2+1)\sqrt{x^2+1}>x^2\sqrt{2}$. We can square getting $$ x^6+3x^4+3x^2+1>2x^4 $$ that is $$ x^6+x^4+3x^2+1>0 $$ which is of course true. Therefore $f''(x)>0$ for all $x>0$ and so $f'(x)$ is increasing. Since $f'(1)=0$, $f'$ vanishes only at $1$, which is thus the unique minimum point for $f$. Since $f(1)=0$, we see that $f(x)\ge0$ for all $x>0$ (equality only at $1$).
[ "mathematica.stackexchange", "0000161027.txt" ]
Q: How can I get Dsolve's output to look like traditional solution? I am still quite new to Mathematica, so please bear with me. I am using Dsolve on a 3D linear differential equation and got what appeared to be an incorrect answer. After some work, it seems that the solution is, in fact, correct, but is not in the typical form of exponentials and sine/cosine I expected from a system with distinct roots and imaginary eigenvalues. It is concerning to see a solution to a linear ODE (without repeated roots) that has $te^{\lambda t}$ and $t^2e^{\lambda t}$ in it. Is there a way to change the output of Dsolve to be more in line with what I expect? Here is the code I use to produce the questionable output. A = {{-10, 0, 75/23}, {2, -10, 77/92}, {0, 8, -1}} SYST = A.{x[t], y[t], z[t]} SOL = DSolve[{ x'[t] == SYST[[1]], y'[t] == SYST[[2]], z'[t] == SYST[[3]], x[0] == x0, y[0] == y0, z[0] == z0 }, {x[t], y[t], z[t]}, t]; A: One way to simplify it could be ClearAll[x,t,y,z,z0,x0,y0] A0 = {{-10,0,75/23},{2,-10,77/92},{0,8,-1}}; syst = A0.{x[t],y[t],z[t]}; ode = {x'[t]==syst[[1]],y'[t]==syst[[2]],z'[t]==syst[[3]]}; ic = {x[0]==x0,y[0]==y0,z[0]==z0}; sol = First@DSolve[{ode,ic},{x[t],y[t],z[t]},t] And now Chop@FullSimplify@ComplexExpand@N@sol
[ "stackoverflow", "0049640183.txt" ]
Q: Telegram URL to send message to specific bot Is it possible to craft a t.me URL that prompts the user to send a specific message to a specific bot. The closest I've found so far is t.me/share/url?url=my%20message, but that doesn't specify a username so the user has to choose one. I don't see the t.me URLs documented anywhere. Note: this is not the same as sending a message via the API. A: You can use deep linking to bot, use following format like this link: https://t.me/username?start=<token> And you will receive /start <token>
[ "stackoverflow", "0027116371.txt" ]
Q: dyld: Library not loaded. Reason : no suitable image found I've looked at a bunch of answers here and none have fixed my issue. I have an Xcode workspace with a custom framework and an iOS app project. The project has been working fine until this morning, now it builds but immediately crashes: dyld: Library not loaded: @rpath/ONCKit.framework/ONCKit Referenced from: /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/atero_t Reason: no suitable image found. Did find: /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit: mmap() error 1 at address=0x100118000, size=0x000B8000 segment=__TEXT in Segment::map() mapping /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit: mmap() error 1 at address=0x100280000, size=0x000B8000 segment=__TEXT in Segment::map() mapping /private/var/mobile/Containers/Bundle/Application/4DF67A3F-6255-4276-8812-8C742A363995/atero_t.app/Frameworks/ONCKit.framework/ONCKit I've been experimenting with build settings all day and I'm just totally lost. A: I came across this issue today and resolved it the same way. Revoke and regenerate code signing solves this issue. But to shed some light on the "why" part of it. Apple went ahead and changed the certificate contents. To be more precise, it added a new "OU" (organizational unit) field under Subject. By revoking and regenerating the code signing, it added the missing field and the problems went away. A: Incase this helps anyone, none of the solutions I kept finding on the web were working for me. Pulled my hair our for 2 days, and tried everything. I revoked in-house cert, new provisioning profile, added files to embedded, etc. Could not for the life of me figure out what was wrong until I noticed that in Keychain access my Apple WWDR and iOS Distributions certs were being set to "Always Trust" instead of "Use Systems Default". Switched my certs back to "Use Systems Defaults" and everything went back to working as it should. I have no idea why and how this works but it did. A: It turns out that Xcode cache some device specific stuff which can get mixed up if you are running your apps on multiple devices. The simple fix is to delete Xcode cache. The following command clean it up for you rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache" rm -rf ~/Library/Developer/Xcode/DerivedData rm -rf ~/Library/Caches/com.apple.dt.Xcode
[ "stackoverflow", "0007058805.txt" ]
Q: "Nothing to be done for makefile" message I have the following files: Child.c , Cookie.c , Cookie.h , CookieMonster.c , Jar.c , Jar.h, Milk.c , Milk.h and the following makefile, named makePractice, which is supposed to create two executables, Child and CookieMonster. makefile: CC = gcc # the compiler CFLAGS = -Wall # the compiler flags ChildObjects = Jar.o # object files for the Child executable CookieMonsterObjects = Jar.o Milk.o #object files for the CookieMonster executable all: Child CookieMonster # the first target. Both executables are created when # 'make' is invoked with no target # general rule for compiling a source and producing an object file .c.o: $(CC) $(CFLAGS) -c $< # linking rule for the Child executable Child: $(ChildObjects) $(CC) $(CFLAGS) $(ChildObjects) -o Child # linking rule for the CookieMonster executable CookieMonster: $(CookieMonsterObjects) $(CC) $(CFLAGS) $(CookieMonsterObjects) -o CookieMonster # dependance rules for the .o files Child.o: Child.c Cookie.h Jar.h CookieMonster.o: CookieMonster.c Cookie.h Jar.h Milk.h Jar.o: Jar.c Jar.h Cookie.h Milk.o: Milk.c Milk.h Cookie.o: Cookie.c Cookie.h # gives the option to delete all the executable, .o and temporary files clean: rm -f *.o *~ When I try to use the makefile to create the executables, by running the following line in the shell make -f makePractice I get the following message: make: Nothing to be done for `makefile'. I don't understand what's wrong... A: If you don't specify a target on the command-line, Make uses the first target defined in the makefile by default. In your case, that is makefile:. But that doesn't do anything. So just remove makefile:. A: Your command line does not tell make what you want to be made, so it defaults to trying to make the first explicitly named target in the makefile. That happens to be makefile, at the very first line. makefile: Since there are no dependencies, there is no reason to do anything to remake that file. Therefore make exits, happy at having obeyed your wish.
[ "stackoverflow", "0056446246.txt" ]
Q: Override Vuetify 2.0 sass variable $heading-font-family In Vuetify 2.0.0-beta.0 I try to override the default variable $heading-font-family. This isn't working. However I can override e.g. $body-font-family, $font-size-root or $btn-border-radius. I've followed the documentation from https://next.vuetifyjs.com/en/framework/theme My main.scss looks like this: // main.scss @import '~vuetify/src/styles/styles.sass'; // The variables I want to modify $font-size-root: 16px; $body-font-family: Arial, sans-serif; $heading-font-family: 'Open Sans', sans-serif; $btn-border-radius: 8px; My .vue file has a template with this HTML: // in my vue Template ... <div class="hello"> <h1 class="display-1">{{ msg }}</h1> <p>Lorem ipsum dolor sit amet...</p> <v-btn color="pink" dark>Click me</v-btn> </div> ... When I inspect the H1 in the console, I expect it to have a font family of 'Open Sans', sans-serif. Instead I see "Roboto", sans-serif. This was the default value of $body-font-family before it was overridden in my custom main.scss As I said, the other overrides from my main.scss are working fine. What am I doing wrong here? A: I've tried all the solutions presented here but nothing worked. What did work was following this https://vuetifyjs.com/en/customization/sass-variables create a directory scss in src (not /src/styles/scss/ or any other variant). And there place your new variables value. // /src/scss/variables.scss $body-font-family: 'Less'; $heading-font-family: $body-font-family; // Required for modifying core defaults @import '~vuetify/src/styles/styles.sass';
[ "stackoverflow", "0001169323.txt" ]
Q: Show ContextMenuStrip at location of StatusBar item I want to show a ContextMenuStrip at the location of a ToolStripStatusLabel in a StatusStrip. Ordinary controls have PointToScreen / PointToClient / etc, but as ToolStripStatusLabel is derived from Component it does not. Any help would be appreciated. A: A very, very late answer, just because I happened to struggle with the same issue and googled up this question. What I found as the best solution adds one nice twist to the answers so far. Here it is: void toolStripItem_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { var label = (ToolStripItem)sender; this.contextMenuStrip1.Show(this.mainStatusStrip, label.Bounds.X + e.X, label.Bounds.Y + e.Y); } } Adding the mouse coordinates relative to the control (e.X, e.Y) to the bounds coordinates makes the menu appear at exactly the right position. Omitting this shows the menu at the top left corner of the ToolStripItem. For the record.
[ "stackoverflow", "0003581434.txt" ]
Q: What are the big web frameworks today? My team at work is going to start working on a website with a medium amount of business logic and a large amount of database. soon. We've got to pick a language and a framework to build it on, but we're not really sure where to start. There are literally a zillion options. All we need is something that hooks into database, something that allows for rapid development and prototyping, and something that scales well. Who are the top 5 or so players in the field today? A: Five very popular ones, in no special order, "one per language": Rails (Ruby), Django (Python), CakePHP (PHP), ASP.NET (all .Net languages), Struts 2 (Java). I'm sure there are many other frameworks for each of these languages (as well, of course, as many more languages;-), but these all have high current popularity, if that's your number one consideration. A: Rails (Ruby), Cake (PHP), Django (Python) and Grails (Groovy) are pretty similar to each other and have the features you mentioned. They are pretty heavy though. I prefer more lightweight frameworks that do less for you, because many of these frameworks like do things their way and if you want to do it your way, you'll have to wrestle with the framework. Then, if you are doing more work than you would normally, why bother using a framework at all? But to each his own. See a list here: http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks
[ "math.stackexchange", "0000562028.txt" ]
Q: Arithmetic sequence of tangent values I have two angles $A_1, A_2 > 0$, and $A_1+A_2 < \pi$, is it possible to find an $A_0$ such that $$\tan(A_0),\ \tan(A_0+A_1),\ \tan(A_0+A_1+A_2)$$ forms an arithmetic sequence on the same continuous range of tangent? I have been looking for a formula for sum of tangents (not tangent of sum), but I have not been successful so far. A: (Resolving my own question) Let the first term $\tan(A_0) = a$, term difference be $d$, then $$\begin{align*} \cot A_1 &= \cot(A_0+A_1-A_0)\\ &= \frac{1+\tan(A_0+A_1)\tan A_0}{\tan(A_0+A_1)-\tan A_0}\\ &= \frac{1+(a+d)a}{d}\\ \cot A_2 &= \cot(A_0+A_1+A_2-A_0-A_1)\\ &= \frac{1+\tan(A_0+A_1+A_2)\tan(A_0+A_1)}{\tan(A_0+A_1+A_2)-\tan(A_0+A_1)}\\ &= \frac{1+(a+2d)(a+d)}{d}\\ \end{align*}$$ then $$\begin{align*} \cot A_2 - \cot A_1 &= \frac{1+(a+2d)(a+d)}d - \frac{1+(a+d)a}d\\ &= \frac{2d(a+d)}d\\ &= 2(a+d)\\ &= 2\tan(A_0+A_1) \end{align*}$$ A value of $A_0$ can be taken as $$A_0 = \arctan \left(\frac{\cot A_2 - \cot A_1}2\right)-A_1$$
[ "stackoverflow", "0053627615.txt" ]
Q: Array.fill() retaining previously selected months' dates I have been looking around in SO and github for an explanation but couldn't find one. There've been many threads floating around with Array.fill() but nothing seems to answer my question. So here it goes, const dates = Array(this.props.totalDays).fill().map((e, i) => moment(this.props.selectedDate).day(i+1).format('DD-MM')). In the above statement this.props.totalDays is a number which is the number of days for the selected month. For example it'll be 31 starting January and 28, 31,30 as we select February, March and April respectively. And this.props.selectedDate is a date in string format(for ex : 2018-01-01 for Jan, 2018-03-01 for March etc) My dates array shows the dates in the required format when i select January as 01-01, 01-02, ......all the way till 01-31. Now when i select February it messes up and i am not getting why? When i select February my dates array will have the array starting from 01-29, 01-30, 01-31, 01-02....all the way till 25-02 And now when i select March the dates array is 26-02, 27-02, 28-02, 01-03,02-03......all the way till 28-03 I've been struggling to understand as to whats happening and have failed. Any help would be much appreciated. Thanks, Vikram A: moment.day() indicates the day of the week starting at 0 for Sunday. I think you want to set set the day of the month, which you get with date(). let totalDays = 28 let selectedDate = '2018-02-01' const dates = Array(totalDays) .fill() .map((e, i) => moment(selectedDate).date(i+1).format('MM-DD')) console.log(dates) <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
[ "workplace.stackexchange", "0000004385.txt" ]
Q: Changing jobs at the end of a year? hiring availability It has become apparent that it is time to change jobs for better personal and career growth opportunities. Are companies hiring people at the end of the year during November and December with all the holidays or would I have better selection after the start of the new year? A: If i leave my current company and forfeit the Christmas bonus can I expect a bonus at a new company that I will have just started working at? Your new employer may be willing to provide some sort of sign-on bonus in order to get you to start at a new job quickly and to forgo a coming bonus. This is fairly common around times when bonuses are paid (end of year and early Feb/Mar). When discussing your compensation with a potential new employer, be sure to mention any bonuses that are expected in the relatively near future (< 6 months) Are companies hiring people at the end of the year during November and December? November and December can be an interesting time to look for work for a variety of reasons. One reason that some give is that during the holiday season (holidays for many), people may be in a more 'giving' spirit. That is debatable, but anecdotal evidence may seem to lead some to believe that is true. A much more tangible and realistic reason to look for work in those months is due to budgets and headcount. If a department has a specific budget for any given year and still has money left in that budget towards the end of the year, they may be more inclined to make a hire in order to be sure they will get the same or more budget for the following year. This is the same for a specific headcount. If a manager is budgeted to have say 8 employees on a team, and there are only 6, that manager has an incentive to bring the team to full capacity in order to keep that headcount for the following year.
[ "stackoverflow", "0002275569.txt" ]
Q: AJAX Toolkit - AsyncFileUpload Control Return Data I am using the AsyncFileUpload control provided by the Ajax Toolkit. I am needing to store the file uploaded in a temporary directory and then return the temporary file name back to the client (or set viewstate) so that on the next post back it can be committed to a database. Does anyone have any ideas as the best approach to do this, if even possible? A: Yes. It is possible. OnClientUploadComplete is fired on the client-side after the upload has completed. Then just use get_fileName() to return the name of the file being uploaded. Example: function uploadCompleted(sender, args) { alert(args.get_fileName()); }
[ "stackoverflow", "0032704004.txt" ]
Q: Python subprocess and running script on directory Im trying to run subprocess. Im running a python file on a directory (to convert each file in the directory.) The convertor works and ive been implementing this into a gui(PYQT4). Here is what I got so far: def selectFile(self): self.listWidget.clear() # In case there are any existing elements in the list directory = QtGui.QFileDialog.getExistingDirectory(self, "Pick a folder") if directory: for file_name in os.listdir(directory): if file_name.endswith(".csv"): self.listWidget.addItem(file_name) print (file_name) def convertfile(self, directory): subprocess.call(['python', 'Createxmlfromcsv.py', directory], shell=True) The error im getting is .. Traceback (most recent call last): File "/Users/eeamesX/PycharmProjects/Workmain/windows.py", line 162, in convertfile subprocess.call(['python', 'Createxmlfromcsv.py', directory], shell=True) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception TypeError: execv() arg 2 must contain only strings Any help for a beginner is appreciated :) A: From the comments to the question, the line: self.convertButton.clicked.connect(self.convertfile) will send False to the convertfile method when the button is clicked, which is why you see that error. You need to add some code to convertfile which gets the directory path from the selected item in the list-widget. Something like: item = self.listWidget.currentItem() if item is not None: directory = unicode(item.text()) subprocess.call(['python', 'Createxmlfromcsv.py', directory]) But note that you are not storing the full directory path in the list-widget, and so the subprocess call may fail. You should really add items to the list-widget like this: self.listWidget.addItem(os.path.join(directory, file_name))
[ "ja.stackoverflow", "0000068754.txt" ]
Q: 複数カラムでGroupした結果をHashでなくActiveRecord::relationで取得したい やりたいこと Userが例えば 生まれた年(=year)と出身の都道府県(:prefecture_id)カラムを持っているとします。 そこから 「同じ生まれ年」かつ「同じ出身都道府県」のユーザーが3人以上いる場合、そのユーザーの一覧を取得したいです。 出力結果がHashであるため期待する結果ではないのですが、集計して多い順に並び替える処理は以下で出来ました。 User.group(:year, :prefecture_id).having("count_all > 3").order("count_all DESC").count この出力結果は {[1990, 13]=>4, [1996,2]=>3} のように、生まれ年と都道府県ID、一致した数になっています。 ここから、この「生まれ年」と「都道府県ID」を持つユーザーを一覧を取得するにはどのような手段がありますでしょうか? 上でのHashにUserIdがあれば、pluckとwhereを用いて取得することも出来るかと思いましたが、Idがあると適切なGroupにならないためそれも出来なかったです。。 試したこと パフォーマンスは悪いですが、以下などが一応期待した動作でした。 しかしデータ数が10万件とかなるとパフォーマンスが非常に悪いため避けたいと思っています。 user_hash = User.all.group_by{ |user| [ user[:year], user[:prefecture_id] ] } @users = user_hash.values.select{ |user| 3 < user.size } A: User.joins(<<~SQL) INNER JOIN ( #{User.select("year, prefecture_id, count(*) as count_all").group(:year, :prefecture_id).having("count_all > ?", 3).to_sql} ) as year_pref ON users.year = year_pref.year AND users.prefecture_id = year_pref.prefecture_id SQL のようにすると、望みの User についての relation が得られるのではないか、と思っていますが、いかがでしょうか? 追記@2020/07/21 「該当件数」でソートしたい場合には、 sort 条件を relation に含めれば良いと思っています。 e.g. User.joins(<<~SQL).order("year_pref.count_all DESC") INNER JOIN ( #{User.select("year, prefecture_id, count(*) as count_all").group(:year, :prefecture_id).having("count_all > ?", 3).to_sql} ) as year_pref ON users.year = year_pref.year AND users.prefecture_id = year_pref.prefecture_id SQL
[ "stackoverflow", "0058736346.txt" ]
Q: Extracting the value from xml that has a given attribute with a value, and then getting the value of the other attribute I have a table with a XML column type. How do I find the value for the car node with name "Ford"? Also, if Ford is not there, it shouldn't throw an error. <cars> <car name="Honda" value="11" /> <car name="Toyota" value="22" /> <car name="Ford" value="3333" /> <car name="Ferarri" value="444" /> </cars> I'm not sure how to set the value of the node attribute and then check the next 'value'? XmlColumn.value('/cars[1]/car[1]/@name["Ford"]/@value', 'nvarchar(max)') I'm trying to do the above, but that is a bad query syntax. A: Here is another version to try. I also added another row to the table with XML without Ford. SQL -- DDL and sample data population, start DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xml_data XML); INSERT INTO @tbl (xml_data) VALUES (N'<cars> <car name="Honda" value="11" /> <car name="Toyota" value="22" /> <car name="Ford" value="3333" /> <car name="Ferarri" value="444" /> </cars>') , (N'<cars> <car name="Honda" value="11" /> <car name="Toyota" value="22" /> <car name="Ferarri" value="444" /> </cars>'); -- DDL and sample data population, end SELECT id, [xml_data].value('(/cars/car[@name="Ford"]/@value)[1]','INT') AS [value] FROM @tbl AS tbl; Output +----+-------+ | id | value | +----+-------+ | 1 | 3333 | | 2 | NULL | +----+-------+
[ "stackoverflow", "0001588992.txt" ]
Q: How can I get CVS to delete a folder I just checked in? I run CVS on my Mac OS X box and access it from a Windows VM. It works great (although the version of CVS that comes with Mac OS X is really old). But I find it annoying that I cannot tell by looking at the project folders if I have checked out the project or not. Is there a way to tell the CVS command to delete a folder it checks in so that I can only edit a project that I have checked out? Since I am the only user I can just as well follow a strict check-in/check-out regime. Also, is there a way for CVS to add new files automatically? I am not sure how I can best remember which new classes I create so I can add them to the project in CVS. I know I should probably cvs add new files when I create them, but then I often create a new class and then delete it again when I decide that I don't need it after all. Adding and removing such files from CVS should best be automatic. Or perhaps I should switch to a different source control system (that is easily installed, runs on Mac OS X, and has a Windows client)? Any answers/comments/ideas welcome! A: You can use "cvs status" to see the status of your working folders, and "cvs release -d" to get CVS to check to see if you've any outstanding changes in your working folders before removing them.
[ "stackoverflow", "0008418982.txt" ]
Q: Unable to INSERT rows into MySQL Database I have a datebase lyrics with a table lyrics1, and with the code below I want to insert a row into lyrics1. But when I go back to the mysql client and do describe lyrics1, it hasn't updated. I get no error, it connects to the database fine. At least I don't get error saying it was unable to. connectToDB(); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { String query = "INSERT INTO lyrics1(name, artist) values(?, ?)"; PreparedStatement statement = connection.prepareStatement(query); statement.setString(1, nameOfSong.getText()); // set input parameter 2 statement.setString(2, artist.getText()); ResultSet rs = statement.executeQuery("SELECT * FROM lyrics1"); while (rs.next()){ System.out.println(rs.getString(1)); } rs.close(); statement.close(); connection.close(); } catch (SQLException insertException) { displaySQLError(insertException); } internalFrame.dispose(); } }); A: you are never actual executing the INSERT statement, you just create it and never actual execute it. You are executing a SELECT but nothing actually sends the INSERT statement to the server. You need to first call statement.executeUpdate() it will return the number of rows affected, most of the time you want to check that this is equal to 1 for INSERT and more than ZERO for UPDATE and DELETE.
[ "stackoverflow", "0055986326.txt" ]
Q: Return a list item from a null value using list comprehension I'm using a list comprehension to get a list of numerical values that are separated by a semicolon, ;, within a string. I need to get a 0 from missing values on either side of the semicolon. Example string without missing values: job_from_serial_st = 'xxxxx\rxxxxxx\rxxxx\rGAX=77.00;85.00\rxxxxx\r' Using my list comprehension I would get the following list of values: [7700, 8500] But how can I get a list of values from strings like 'GAX=77.00;\r' or 'GAX=;85.00\r'? I'm expecting to get the following lists from the example strings with missing values: [7700, 0] or [0, 8500] def get_term(A, B, phrase): n = A.len() start = phrase.find(A) + n end = phrase.find(B, start) term = phrase[start:end] return term # GET GAX NUMBER gax_nums = get_term(r'GAX=', r'\r\x1e\x1d', job_from_serial_st) gax = [int(float(x) * 100) for x in gax_nums.split(';')] print(gax) A: You can add a condition to the list comprehension to return 0 if there is no number before or after the semicolon (also replaced your function with a series of splits to retrieve the numbers from the string). s = 'xxxxx\rxxxxxx\rxxxx\rGAX=77.00;\rxxxxx\r' nums = s.split('GAX=')[1].split('\r')[0].split(';') gax = [int(float(n) * 100) if n else 0 for n in nums] print(gax) # [7700, 0]
[ "stackoverflow", "0058502550.txt" ]
Q: How to keep sub-process running after main process has exited? I have a requirement to use python to start a totally independent process. That means even the main process exited, the sub-process can still run. Just like the shell in Linux: #./a.out & then even if the ssh connection is lost, then a.out can still keep running. I need a similar but unified way across Linux and Windows I have tried the multiprocessing module import multiprocessing import time def fun(): while True: print("Hello") time.sleep(3) if __name__ == '__main__': p = multiprocessing.Process(name="Fun", target=fun) p.daemon = True p.start() time.sleep(6) If I set the p.daemon = True, then the print("Hello") will stop in 6s, just after the main process exited. But if I set the p.daemon = False, the main process won't exit on time, and if I CTRL+C to force quit the main process, the print("Hello") will also be stopped. So, is there any way the keep print this "Hello" even the main process has exited? A: The multiprocessing module is generally used to split a huge task into multiple sub tasks and run them in parallel to improve performance. In this case, you would want to use the subprocess module. You can put your fun function in a seperate file(sub.py): import time while True: print("Hello") time.sleep(3) Then you can call it from the main file(main.py): from subprocess import Popen import time if __name__ == '__main__': Popen(["python", "./sub.py"]) time.sleep(6) print('Parent Exiting')
[ "mythology.stackexchange", "0000000197.txt" ]
Q: What items were made by the dwarves for the Norse gods? On the Wikipage of Mjölnir, it is said to be made by the dwarves Eitri and Brokkr. Wikipedia also states that they created other items for the gods. Those items being: Skidbladnir, the ship of Freyr, Mjölnir, Draupnir and Gungnir. Wiki Quotes: "the Sons of Ivaldi are a group of dwarfs who fashion Skidbladnir, the ship of Freyr, and the Gungnir, the spear of Odin, as well as golden hair for Sif to replace what Loki had cut off." "Eitri succeeded in making the golden boar Gullinbursti, the golden ring Draupnir, and the hammer Mjöllnir." My question being, are there any other items that the dwarves made for the gods of the Norse mythology? A: The objects mentioned in your question were created by Eitri and Brokkr, and the Sons of Ivaldi. However, there are more objects that exist which were crafted by the dwarves. You can find a list of objects belonging to Norse deities here: Viking Mythology Timeless Myth Most of the objects mentioned in the list were created by the Dwarf craftsmen. A: It's not magical, but the Svartálfar is also made Sif's hair. From Faulkes' translation1 (via Wikipedia): In chapter 96, a myth explaining Skíðblaðnir's creation is provided. The chapter details that the god Loki once cut off the goddess's Sif's hair in an act of mischief. Sif's husband, Thor, enraged, found Loki, caught hold of him, and threatened to break every last bone in his body. Loki promises to have the Svartálfar make Sif a new head of hair that will grow just as any other. Loki goes to the dwarfs known as Ivaldi's sons, and they made not only Sif a new head of gold hair but also Skíðblaðnir and the spear Gungnir. 1 Faulkes, Anthony (Trans.) (1995). Edda. Everyman.
[ "stackoverflow", "0031806851.txt" ]
Q: App.config's element values to be used in Connection String Is it possible use App.config's value in Connectionstring. Example is mentioned below. <appsettings><add key="UserName" Value="abc" /></appsettings> <connectionstring><add name="Conn" connectionString="Server=test; Database=test; Uid=UserName; Pwd=test123;" /> So as you can see that I have defined the Username in appsettings and I want to see that into the connection string Any help is appreciated. A: As I know, it's impossible. You can use different App.config files for different configuration (Debug, Release) and set your connection string in them. Look here or here
[ "stackoverflow", "0002610751.txt" ]
Q: Animate and form rows, arrays, AS3 Question How can I animate and form rows together? Explanation One 'for loop' is for animation, the other 'for loop' is for making rows. I want to understand how to use arrays and create a row of sprite animations. I understand how to loop through an Array and create a Sprite for each index of the Array, but I'm having trouble putting my animation in rows. Output I got my number animation to play in a single row. When I add the loop to multiply it across the stage, it just blinks while continuing to animate. 'for loop' for animation //FRAMES ARRAY //THIS SETS UP MY ANIMATION FOR TIMER EVENT var frames:Array = [ new Frame1(), new Frame2(), new Frame3(), new Frame4(), new Frame5(), new Frame6(), new Frame7(), new Frame8(), new Frame9(), new Frame0(), ]; for each (var frame:Sprite in frames) { addChild(frame); } 'for loop' for rows //THIS MAKES A ROW OF DISPLAY OBJECTS var numberOfClips:Number = 11; var xStart:Number = 0; var yStart:Number = 0; var xVal:Number = xStart; var xOffset:Number = 2; for (var $:Number=0; $<numberOfClips; $++) { //DUDE ARRAY var dude:Array = frames; dude.y = yStart +11; dude.x = xVal +55; xVal = dude.x + dude.width + this.xOffset; } timer var timer:Timer = new Timer(100); timer.addEventListener(TimerEvent.TIMER, countdown); function countdown(event:TimerEvent) { var currentFrame:int = timer.currentCount % frames.length; for (var i:int = 0; i < frames.length; ++i) { frames[i].visible = (i == currentFrame); } } timer.start(); counter experiment My new class I'm working on loops through 10 different display objects that are numbers. For those following, I'm trying to make something like NumbersView. INTENT - Single Frames 'individual sprites for each number' - Individual behaviors for Flip, and LED - Flip 'each object is a flip animation with a number' (can't achieve with NumbersView) - LED 'each object is independent, allowing for 7-seg led patterns, or motions staggering walk-in effect' - Odometer 'odometer already achieved, but could achieve the same with tweens for each number' HOPE TO LEARN - arrays 'understand how to use and combine arrays' - for loops 'how to use, and how to follow in a document' - classes 'at what point do I need to extend it as a class' alt text http://www.ashcraftband.com/myspace/videodnd/countlite__.jpg EXAMPLES LED 'same behavior and layout, but vertical increments' http://www.youtube.com/watch?v=__TLrYH8NC4 FLIP NUMBER 'great example of terminal board at airport http://www.youtube.com/watch?v=fH0Aghm1TNE ODOMETER 'towards the end of the clip' http://www.youtube.com/watch?v=DKavhec9fGE alt text http://www.ashcraftband.com/myspace/videodnd/countlite_.jpg A: Your question is a little better now; I've modified the code I gave you for the Odometer slightly, and put in a small Tween inside an object using the Flash IDE. http://dl.dropbox.com/u/3987391/Odometer_Flip.fla Look at how little I changed in the code, from the Odometer example. The main thing I added is inside the flipper MovieClip. Inside it is an object called digitHolder, which animates using CS4's 3D rotation tool. Inside digitHolder is the TextField which displays the number. As for the LED alternative, I imagine you could just use a font which looks like LEDs. Your Youtube link doesn't work, so I can't see what the example is, but I imagine a font would cover you.
[ "gis.stackexchange", "0000210507.txt" ]
Q: Updating Field using Field Calculator Python I am trying to update my Status field as seen below: I want to change the Null and Existing values to Permanently Removed using the Python Parser; however, I am receiving an error. Can someone explain what I am doing wrong? def updateName(sCode): if sCode == Null: status= 'Permanently Removed' elif sCode == 'Existing': status = 'Permanently Removed' else: status = None return status A: You are so close. As mentioned by @mmore, use "is None" to find Null values. sCode is the variable for Status, therefore use that for the final condition. See the link on how to use the field calculator. def updateName(sCode): if sCode is None: return 'Permanently Removed' elif sCode == 'Existing': return 'Permanently Removed' else: return sCode
[ "stackoverflow", "0050065550.txt" ]
Q: Extracting values from Tensorflow Variable I'm new to Python and Tensorflow and i'm facing some difficulties getting values from my NN after training phase. import tensorflow as tf import numpy as np import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot = True) n_nodes_hl1 = 50 n_nodes_hl2 = 50 n_classes = 10 batch_size = 128 x = tf.placeholder('float',[None, 784]) y = tf.placeholder('float') def neural_network_model(data): hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,n_nodes_hl1]),name='weights1'), 'biases': tf.Variable(tf.random_normal([n_nodes_hl1]),name='biases1')} hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2]),name='weights2'), 'biases': tf.Variable(tf.random_normal([n_nodes_hl2]),name='biases2')} output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_classes]),name='weights3'), 'biases': tf.Variable(tf.random_normal([n_classes]),name='biases3')} l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']) , hidden_1_layer['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']) , hidden_2_layer['biases']) l2 = tf.nn.relu(l2) output = tf.add(tf.matmul(l2, output_layer['weights']) , output_layer['biases']) return output def train_neural_network(x): prediction = neural_network_model(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction,labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) hm_epochs = 100 init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer() ) with tf.Session() as sess: sess.run(init) for epoch in range(hm_epochs): epoch_loss = 0 for _ in range(int(mnist.train.num_examples / batch_size)) : ep_x, ep_y = mnist.train.next_batch(batch_size) _, c = sess.run([optimizer, cost], feed_dict = {x: ep_x, y: ep_y}) epoch_loss += c print('Epoch', epoch+1, 'completed out of', hm_epochs, 'loss:',epoch_loss) correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy:', accuracy.eval({x:mnist.test.images, y: mnist.test.labels})) train_neural_network(x) I tried to extract weights from layer 1 using: w = tf.get_variable('weights1',shape=[784,50]) b = tf.get_variable('biases1',shape=[50,]) myWeights, myBiases = sess.run([w,b]) but this throw error Attempting to use uninitialized value weights1_1 is this because my Variables are in a dict type 'hidden_1_layer'? I'm not yet comfortable with Python and Tensorflow data types so i'm in total confusion! A: Use the following code: tensor_1 = tf.get_default_graph().get_tensor_by_name("weights1:0") tesnor_2 = tf.get_default_graph().get_tensor_by_name("biases1:0") sess = tf.Session() np_arrays = sess.run([tensor_1, tensor_2]) Also there are other ways to store the variable for later use or analysis. Please specify your purpose for extracting weights and biases. Comment further if further discussion is needed.
[ "stackoverflow", "0031019434.txt" ]
Q: AWS SNS push notification While creating a platform application when I tried to create application and push notification platform select GCM then add API key I got the following. Invalid parameter: Attributes Reason: Platform credentials are invalid (Service: AmazonSNS; Status Code: 400; Error Code: InvalidParameter; Request ID: 44a04d15-c58b-5bf8-859e-0311947aac6c) What does this mean and how can I fix this? A: I got exactly same error message as yours. It seems google is migrating Firebase Cloud Messaging (FCM) to Google Cloud Messaging, and the API Key created via Credentials in API Manager of Google Cloud Platform is not working. And here is how I get it to work. Go to Firebase Console and import Google Cloud Project. Go to Project settings on Firebase Console and you should see the Web API Key of your project. Go back to your Google Cloud Platform, and go to Credentials of API Manager, you should see there are two API keys have been generated. Browser key (auto created by Google Service) and Server key (auto created by Google Service) The Server key (auto created by Google Service) is what you need to use on the Amazon SNS. Hope it can resolve your problem, and hope it is only a temporary solution that after Google done the migration, we can directly use the API key created in API Manager.
[ "stackoverflow", "0062295654.txt" ]
Q: Finish geolocation in Flutter How can I end the real-time geolocation service when I close the activity and move on to another one, for example MapReceiver to AppHome, since when I do so the GPS is still active and continues to update my database in Firebase realtime until I close the app completely A: You can use dispose method when you leave the page or if you want to close the service. Note that dispose method is only supported inside Stateful widget only. @override void dispose(){ super.dispose(); // write code to close your streams,services, etc. here }
[ "stackoverflow", "0035538891.txt" ]
Q: How do xlrd, xlwt, xlutils work with Excel in the low level? They are all open source Python packages to control Excel (see python-excel). I am still trying to understand their code. If anyone could give a hint, do how they connect in a low lever to Excel? Via xml, Excel API, or some other basic Python packages? A: If we are talking about reading and writing XLS files, basically xlrd and xlwt follow the OpenOffice.org document/specification describing Excel's format and BIFF (Binary Interchange File Format) records to read and write XLS files. If you would inspect the xlwt source code, you would find it manipulates the BIFF records for everything needs to be written: creating workbook, worksheets, writing data, formatting, alignment etc. With XLSX the story is a bit different. To read XLSX xlrd relies on the openxmlformats XML schemas and use built into Python ElementTree XML parsers (cElementTree if available, otherwise ElementTree) to parse the XLSX file which is, to simplify, a zip archive containing XML files inside. Here is a good overview of what is inside the archive: Anatomy of OOXML - xlsx I would also recommend studying the xlsxwriter module - from my point of view, the package is much better documented and the code is much more cleaner and readable than xlwt or xlrd.
[ "stackoverflow", "0026957742.txt" ]
Q: Zeros as missing cases in R I have a csv with millions of cases that look like this: Case_1,11,17481,172,4436,8,4436 Case_2,11,1221,680,55200,1776,55200 Case_3,16,6647,6449,579967,1,579967 Case_4,22,0,0,0,0,0 In this case, Case_4 is missing data, since it has a bunch of zeros in it (there are hundreds of these in the file). I'm very new to R, and I was wondering if there is an efficient way of deleting these kinds of missing data from the file? Thanks. A: Use the na.strings argument when reading in your file. df <- read.csv("filename.csv", na.strings="0")
[ "stackoverflow", "0057632434.txt" ]
Q: Looping through ListBox to enter values into sheet array I would like to find the cells (or Rows) in Column B, Sheet1, who have matching values placed into ListBox2. Then, I'd like to change the value of a cell 4 columns over (using an Offset command). I believe using a For loop is the most efficient way of going thru the values placed into ListBox2. I tried using a Forloop to go thru all values placed into ListBox2.List. Upon calling a value, the code would look for this value in Column B. Once found, it would "remember" the Row in which this value was found. Then, the code would use a Range/Offset command to change the value of a cell 4 columns over in that Row. Private Sub ButtonOK_Click() Dim wb As Workbook Dim ws As Worksheet Dim SerialList As Range Dim SerialRow As Long Dim i As Long Set wb = ActiveWorkbook Set ws = ActiveWorkbook.Worksheets("Sheet1") Dim strFind As Variant With ws For i = 0 To Me.ListBox2.ListCount - 1 Set SerialList = ws.Range("B:B").Find(What:=Me.ListBox2.List(i)) SerialRow = SerialList.Row If Not SerialList Is Nothing Then ws.Range("B", SerialRow).Offset(0, 4).Value = Me.ListBox2.List(i) 'error occurs here! MsgBox (ListBox2.List(i) & " found in row: " & SerialList.Row) Else MsgBox (ListBox2.List(i) & " not found") End If Next i End With End Sub The MsgBoxes do say the correct ListBox2.List(i) value and the correct SerialList.Row, meaning that the program is correctly finding the row in which the list box value is located. However, I get an error saying that my range is not correctly defined at line "ws.Range("B", SerialRow)....." How do I select the cell I'm searching for to correctly set it to =Me.ListBox2.List(i)? A: Couple of fixes: Dim lv '.... For i = 0 To Me.ListBox2.ListCount - 1 lv = Me.ListBox2.List(i) Set SerialList = ws.Range("B:B").Find(What:=lv, LookAt:=xlWhole) '<< be more explicit 'don't try to access SerialList.Row before checking you found a match... If Not SerialList Is Nothing Then ws.Cells(SerialList.Row, "F").Value = lv '<< Cells in place of Range MsgBox (lv & " found in row: " & SerialList.Row) Else MsgBox (lv & " not found") End If Next i
[ "stackoverflow", "0002382943.txt" ]
Q: HasOne vs References Mapping Fluent NHibernate This is the first time I am working with FluentNhibernate Mapping and facing a question of how to reference another table. Any help is appreciated: I have several tables named CD_varname and all these contain two columns - CODE and DESCR. I have one main table called Recipient and it has, say two columns, called ALIVE and SEX, both are of type number, and they reference to the tables CD_ALIVE and CD_SEX. If Alive=1 in the Recipient, then we need to get the code and descr from CD_ALIVE table where Code=1. I have described a Codef class: public Class Codef { int Code { get; set; } string Descr { get; set; } } My Recipient Class assigns these to a component. Recipient class looks like this: public Class IRecepient { int ID { get; set; } Birth Birth {get; set;} Death Death { get; set; } } Where my Birth and Death classes are: public Class Birth { DateTime BDate { get; set; } Codef Sex { get; set; } Codef Ethnicity { get; set; } //CD_ETHNICITy Table Codef Race { get; set; } //CD_RACE Table } and my Death Class: public Class Death { DateTime DeathDate { get; set; } Codef Alive { get; set; } } so, the main column "Alive" in Recipient is actually referencing my Recipient.Death.Alive.Code I Have a codef mapping class: public CodefMapping() { Map(x => x.Code, "CODE"); Map(x => x.Descr, "DESCR"); } I am trying to do the recipient mapping and this is where I am stuck. Can I do something like this: HasOne<CodefMapping>(c => c.Death.Alive) .PropertyRef(c => c.Code) .PropertyRef(c => c.Descr) .WithForeignKey("ALIVE"); It is not working :( Any help is greatly appreciated. Thank you. A: I think you want to use the References mapping HasOne means that the 2 entities that you are mapping together share a "mutually exclusive" identifier http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/
[ "stackoverflow", "0038586338.txt" ]
Q: CSS oblique div few deg with background image I created 3 div's with each 33% width, that I want to oblique a few degrees. The first and last div should not get a oblique, so that it will only work for the inner content. This also because I want to add 4 divs (25% width) in the near future. I also want to make a the div with background wider, on hover. So that other divs will become 30% and the one on hover will become 40%. Note: I do not want to rotate the image itself, only the div. The image should be place without rotation. I can not get it done with CSS. My current code: <div class="divisions"> <div class="col-sm-4 division hosting"> <div class="inner"> </div> </div> <div class="col-sm-4 division shop"> <div class="inner"> </div> </div> <div class="col-sm-4 division solutions"> <div class="inner"> </div> </div> </div> JSFiddle: https://jsfiddle.net/1cwxLw7h/2/ What I want: A: body {margin: 0px;} .divisions .col-xs-4 { padding: 0; } .divisions .division { transition: width 0.25s linear; } .divisions:hover .division { width: 31%; } .divisions:hover .division:hover { width: 38%; } .divisions .solutions .inner { height: 100%; min-height: 750px; background: url(http://67.media.tumblr.com/f3ed524eaf11c7095fc583390eb346be/tumblr_oaj4d1Uh0n1teue7jo1_1280.jpg) center center no-repeat; background-size: cover; } .divisions .shop .inner { height: 100%; min-height: 750px; background: url(http://65.media.tumblr.com/8b638bda48df96a5350d7dd3796e459c/tumblr_oaj43tSwts1teue7jo1_1280.jpg) center center no-repeat; background-size: cover; } .divisions .hosting .inner-holder { transform: skewX(-4deg); position: relative; overflow: hidden; margin: 0 -30px; z-index: 5; } .divisions .hosting .inner { height: 100%; min-height: 750px; background: url(http://67.media.tumblr.com/43a177556b301a8dc5cb45145050853b/tumblr_oaj40xITvh1teue7jo1_1280.jpg) center center no-repeat; background-size: cover; transform: skewX(4deg); margin: 0 -30px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <div class="divisions"> <div class="col-xs-4 division solutions"> <div class="inner"> </div> </div> <div class="col-xs-4 division hosting"> <div class="inner-holder"> <div class="inner"> </div> </div> </div> <div class="col-xs-4 division shop"> <div class="inner"> </div> </div> </div>
[ "stackoverflow", "0038933683.txt" ]
Q: Importing txt without header I did the following import delimited using "input.txt", delimiters("\t") But input.txt does not have a header. I could see that the first row of the data just becomes a header. Numbers become header like v1, v2.. , and characters become header like a,y,.. If data look like 2014 11 A 03 2014 11 B 06 then the data loaded in Stata is header: v1 v2 a v4 1st row: 2014 11 B 06 What can I do to just add an arbitrary header that goes "v1, v2, v3.." without omitting the first row of input.txt? A: The Stata 13 manual indicates that the option you want is varnames import delimited using "input.txt", delimiters("\t") varnames(nonames)
[ "blender.stackexchange", "0000094129.txt" ]
Q: How can I make a chocolate material similar to this one? I would like to make a chocolate material similar to the one seen in the picture. The problem is the slight transparency (you can see the nuts shine through on the surface), which I just can't acchieve. Could somebody help me or tell me which node I have to include? Thank you A: To achieve the transparency you need to combine volumetric scatter into the material - in place of the usual 'diffuse' shader. The key to the transparency is to model the "chocolate" to that it has very thin layers over the "nuts". I started by modelling the nuts : Then added the chocolate (just a cube, rescaled), subdivided and used Sculpt mode to build up the chocolate around the nuts. The material to include surface properties (the bumpiness and glossiness) along with the translucency is as follows : Adjust the Density (the Value node) to vary the opaqueness of the chocolate. This is essentially just the same as a volumetric shader that you would use for a liquid - just with a higher density to make it appear more solid. For best results, take care over the sculpting of the chocolate over the embedded nuts - you need consistently thin layers to get smooth transitions. Blend file included
[ "stackoverflow", "0018425516.txt" ]
Q: updating local branch before git push I work on local branches and push local branches to my forked repo and then do a pull request on origin. Just wanted to learn good Github Practices. When I push my local branch to forked repo on Github. I want to make sure that my local branch is up to date with the remote origin. What is a good way to do this ? DO any of the below two work ? what is the difference between the two ? when the rebase can fail ?Or any better soln? $git branch master *my_branch $git commit -am "committed" $git fetch origin $git rebase origin/master $git push $git commit -am "committed" $git pull --rebase $git push A: I think it is good idea to have your local master branch to be equal to origin/master and when you desire to merge the local master with your local my_branch or to able to see the diffs or some specific files and so on. This way you will have kind of complete control over both the original code and your code. So assuming my_branch is the active one: $git commit -am "committed" $git checkout master $git pull origin master $git checkout my_branch $git merge master Instead of merge at the last step you can do diff or checkout only specific files from the master.
[ "webapps.stackexchange", "0000090614.txt" ]
Q: How can I get a list of albums in Google Photos I have many albums in Google Photos. (Maybe 200). I want to get a list of these albums along with their urls. How can I do this? To put it in context, I want to send an email listing many of these albums to friends. As a workaround I can, in principle, click into each album in the Google Photos web interface. Then click "More options" then click "Sharing options" then click "COPY". Then I can paste this url somewhere. But that's an absolute best case of 5 or 6 clicks times 200. It's probably much higher. Surely there is an API I can use in a hacky one-time sort of way to get a list of all of my albums. No? It seems like this should be simple. Can someone point me to the documentation that I'm not finding? I don't even see where in the world of Google to ask this question. I have found a similar question, but it's unanswered. It seems that today (2016-03-05) the Picasa Web Albums Data API is probably what I need. But I'm not sure. My ideal solution is probably to have a simple script in a Google Sheet to grab a list of all Albums: Names in one column and public url (if it exists) in another column. But I'll settle for ANY way of getting a list of all my albums with their urls. UPDATE: Sally, raised the possibility of screen scraping to get the answer. I love this idea! But I'm unable to use her idea, so I'm adding this angle to the question to provoke a clearer answer. I'm able to list all of my shared albums at this url: https://photos.google.com/shared I would like to obtain the public url for all of these albums. But the public url, which has this form: https://goo.gl/photos/Rw5gpSaD4ikadj6M9, is not found in the source code for the page. I must click into each album and then click "Share" to find the public url. In short: obtaining the complete list of my shared albums with their public urls via API, screen scraping, or any other means would meet my requirement. A: The Google Photos interface is very minimal even for humans, let alone applications. The best way I found to get a list of album names and URLs is to parse the page source using the browser console. The list of all albums Executed on the page https://photos.google.com/albums, this script returns a string that can be copy-pasted to a Google Sheet, creating a table of names and URLs. var links = document.getElementsByTagName('A'); var s = ''; for (var i = 0; i< links.length; i++) { if (/\b(album|share)\b/.test(links[i].href)) { var albumName = links[i].children[3].children[0].innerText; s = s + albumName + '\t' + links[i].href + '\n'; } } The list of shared albums Executed on the page https://photos.google.com/shared, this script returns the list of album names and URLs. var links = document.getElementsByTagName('A'); var s = ''; for (var i = 0; i< links.length; i++) { if (/\b(album|share)\b/.test(links[i].href)) { s = s + links[i].innerText + '\t' + links[i].href + '\n'; } } The URLs are in the long format: https://photos.google.com/share/...?key=..., not in the short format https://goo.gl/photos/... that you would get by clicking the share button. But they are functionally equivalent: the latter redirects to the former after going through Google's URL shortening service goo.gl. If length is a concern, you can shorten them yourself within Google Sheets by using an Apps Script for generating goo.gl URLs.
[ "stackoverflow", "0060118041.txt" ]
Q: 'TypeError: 'datetime.datetime' object is not iterable' when trying to compare a list of dates with a single date I have a nested list like this: nl = [['a', datetime.datetime(2020, 2, 7, 0, 0)], ['b', datetime.datetime(2020, 2, 7, 0, 0)], ['c', datetime.datetime(2020, 2, 5, 0, 0)], ['d', datetime.datetime(2020, 2, 4, 0, 0)] And a single date like this: date_today = datetime.date(2020, 2, 6) I want to remove all sublists which contain an older date than date_today. Like this: date_l = [] for line in nl: if line[1] > date_today: date_l.append[line] However I am getting the error: TypeError: 'datetime.datetime' object is not iterable How can I solve this? A: Use below code nl = [['a', datetime.datetime(2020, 2, 7, 0, 0)], ['b', datetime.datetime(2020, 2, 7, 0, 0)], ['c', datetime.datetime(2020, 2, 5, 0, 0)], ['d', datetime.datetime(2020, 2, 4, 0, 0)]] date_today = datetime.datetime(2020, 2, 6,0,0) date_l = [] for line in nl: if line[1] > date_today: date_l.append(line) print(date_l) Result : [['a', datetime.datetime(2020, 2, 7, 0, 0)], ['b', datetime.datetime(2020, 2, 7, 0, 0)]]
[ "pt.stackoverflow", "0000213301.txt" ]
Q: Diferença de horas entre duas datas com JavaScript? Olá. Tenho essas duas datas: var dtPartida = "20170620 11:20"; var dtChegada = "20170620 16:40"; E preciso descobrir a diferença em horas entre essas datas que no caso e 5 horas e 20 minutos. Preciso que retorne assim: 5h 20m e não assim: 05:20 A: Uma poderosa biblioteca javascript para manipulação de datas Moment.js var dtChegada = "20/06/2017 16:40:00"; var dtPartida = "20/06/2017 11:20:00"; var ms = moment(dtChegada,"DD/MM/YYYY HH:mm:ss").diff(moment(dtPartida,"DD/MM/YYYY HH:mm:ss")); var d = moment.duration(ms); var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss"); console.log(s); <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script> Para retornar no formato pedido no comentario 5h 20m basta agir na variável s var s = Math.floor(d.asHours()) + "h" + moment.utc(ms).format(" mm") +"m"; var dtChegada = "20/06/2017 16:40:00"; var dtPartida = "20/06/2017 11:20:00"; var ms = moment(dtChegada,"DD/MM/YYYY HH:mm:ss").diff(moment(dtPartida,"DD/MM/YYYY HH:mm:ss")); var d = moment.duration(ms); var s = Math.floor(d.asHours()) + "h" + moment.utc(ms).format(" mm") +"m"; console.log(s); <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script> Supondo os horários que mencionou antes da edição da pergunta: var dtChegada = "16:40"; var dtPartida = "11:20"; var ms = moment(dtChegada,"HH:mm").diff(moment(dtPartida,"HH:mm")); var d = moment.duration(ms); var s = Math.floor(d.asHours()) + "h" + moment.utc(ms).format(" mm") +"m"; console.log(s); <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script> Para o caso das datas estarem no formato da resposta do Lucas Costa var dtChegada = "20170620 16:40"; var dtPartida = "20170620 11:20"; var ms = moment(dtChegada,"DD/MM/YYYY HH:mm:ss").diff(moment(dtPartida,"DD/MM/YYYY HH:mm:ss")); var d = moment.duration(ms); var s = Math.floor(d.asHours()) + "h" + moment.utc(ms).format(" mm") +"m"; console.log(s); <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script> A: Manualmente com javascript, da pra criar um date a partir da string, pegando separadamente ano, mês, dia, minuto e segundo, e depois calcular a diferente entre as datas (e minutos e segundos). Exemplo var dtPartida = "20170620 11:20"; var dtChegada = "20170620 16:40"; var date1 = new Date(dtPartida.slice(0,4), dtPartida.slice(4,6),dtPartida.slice(6,8), dtPartida.slice(9,11), dtPartida.slice(12,14)), date2 = new Date(dtChegada.slice(0,4), dtChegada.slice(4,6),dtChegada.slice(6,8), dtChegada.slice(9,11), dtChegada.slice(12,14)); var diffMs = (date2 - date1); var diffHrs = Math.floor((diffMs % 86400000) / 3600000); var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); var diff = diffHrs + 'h ' + diffMins + 'm'; console.log(diff); A: Tu pode testar pelos minutos ou segundos das horas: function verificarDiferencaHorario(inicialMin, finalMin) { var totalMin = Number(finalMin - inicialMin); console.log(Math.trunc(totalMin / 60).toString() + ":" + (totalMin % 60).toString()); } Supondo os horários que mencionou: function verificarHorario() { var inicial = "11:20", final = "16:40"; var splInicial = inicial.split(":"), splFinal = final.split(":"); var inicialMin = (Number(splInicial[0] * 60)) + Number(splInicial[1]); var finalMin = (Number(splFinal[0] * 60)) + Number(splFinal[1]); verificarDiferencaHorario(inicialMin, finalMin); } O mesmo vale para dias: a última conversão em minutos e a função verificarDiferencaHorario retorna em horas e minutos a diferença.
[ "stackoverflow", "0021188564.txt" ]
Q: Synchronized and unsynchronized writers to HashMap - results not as expected I have come across code that does not properly synchronize access to a Map - however I analyzed the impact of the non-synchronized code and it is not as I expected. Essentially the code has multiple writer threads that write to a HashMap perAccountMap_ this code is correctly synchronized. However there is a section of code called by a separate thread which reads the Map and resets it: // Unsynchronized code :( - called from a single thread - reads Map and resets it public static Map<PDKey, PData> copyAndClearPerAccountMap() { Map<PDKey, PData> copyMap = perAccountMap_; perAccountMap_ = new HashMap<PDKey, PData>(); return copyMap; } Now, I was able to independently validate the contents of the Map that was being copied above on some multi-core boxes. Intuitively I would have expected the copyMap above to underestimate the entries in the Map - i.e. because it is not synchronized the other synchronized writer threads inserts to the Map will not necessarily be visible to this single thread that takes a copy of it. However the reverse appears to be the case - the copy above appears to consistently have ca. 1% more entries. I can fix the unsynchronized code, but I don't understand the results I observed. A: The best theory I can offer is that the writer threads are still writing into the original map for a short time after the change is made. This could especially happen if perAccountMap_ is not volatile as the change made by the copyAndClear method would not be seen by the other threads immediately.
[ "stackoverflow", "0017229639.txt" ]
Q: How to show login page based on API response I am consuming a Rails API using a client app written in Rails. If the user is not authenticated then i have to show the login page. I have created a structure of making API calls from only one Ruby class. Now from that Ruby class if the response status is 401 then i have to show login page. Is there any way of redirecting user to login page from my Ruby class? Here is my client code class Client def execute(method, url, params) response = case method when :get HTTParty.get(url, query: params) when :post HTTParty.post(url, body: params) when :put HTTParty.put(url, body: params) when :delete HTTParty.delete(url, body: params) else nil end if response.status == 401 # should redirect to login page else # Send result to caller which will parse it and send back to the controller action who called it end end end A: I solved this problem by raising a custom exception and catching that in ApplicaionController. From there i can redirect to login page easily.
[ "drupal.stackexchange", "0000060772.txt" ]
Q: What are the database tables related to comments in Drupal 7? I received a lot of spam comments in one of my websites running on Drupal 7. I googled for a solution to delete them in bulk and came up on DELETE FROM comment WERE status = 0 The query worked but the database size did not shrink significantly and I realized out that in addition to the 'comment' table there was another table called field_data_comment_body which housed the body of the comment. I would like to know which all tables are related to comments in Drupal 7 A: Run these on your PhpMyAdmin: TRUNCATE TABLE comment; TRUNCATE TABLE field_data_comment_body; UPDATE node_comment_statistics SET comment_count = 0; TRUNCATE TABLE field_revision_comment_body; Take care: all the comments will be deleted!
[ "stackoverflow", "0055594182.txt" ]
Q: Trying to find a transfer function from the discrete system below I'm trying to solve the system below in Matlab. This system is a discrete system. I need to convert to a state space model system, to extract 4 matrices. Then find the transfer function. y(k+2) + 4y(k+1) + 5y(k)= u(k+2)+2u(k+1)+u(k). I solved this by hands and I found the four matrices: A=[0,1:-5,-4] B=[-2;4] C=[1,0,0] D=[1] My problem is when I try to run my below code I got this error: Error using ss2tf (line 26) The A and C matrices must have the same number of columns. Error in no1 (line 5) [N1,D1]=ss2tf(A,B,C,D,1); My Matlab code: A=[0,1;-5,-4]; B=[-2;4]; C=[1,0,0]; D=[1]; [N1,D1]=ss2tf(A,B,C,D,1); H=tf(N1,D1) I expect to get a transfer function A: Don't forget that you are dealing with a discrete-time system (add 1as third argument to ss2tf). If you correct the C matrix as already noticed in the comment, then the following code will do what you want: A = [0,1;-5,-4]; B = [-2;4]; C = [1,0]; D = 1; [N1,D1] = ss2tf(A,B,C,D); H = tf(N1,D1,1) H = z^2 + 2 z + 1 ------------- z^2 + 4 z + 5
[ "meta.stackoverflow", "0000292098.txt" ]
Q: Should an answer be edited to include the correct answer from another's comment? I asked a rather simple C++ question here and got an response that didn't fix my actual problem. However, a comment on that response, from a different user, pointed out that I was making a language mistake, and showed me what my real error was. I didn't mark that response as the answer because it was about a side effect of my real problem, not the problem itself. A different, second commenter requested that I mark that response as the correct answer, I gave my reasons why I didn't feel it was correct, so the commenter edited the answer to include the comment. In the past what I've done is to ask the first commenter to make their own post, and then I'd mark it as the answer. But what I'm wondering is, is that good form to edit someone else's incorrect/less useful answer with someone else's correct answer? Should I accept this edit, request that the first commenter make their own, separate answer, or just leave it all be? The first answer wasn't bad, per-say, it just didn't help me. Update: There's been some confusion in answers I've received. The user who edited the answer is neither the author of the answer, nor the author of the comment that actually made the answer. User 1 made a response with an incorrect answer. User 2 made a comment with the correct answer. User 3 then edited User 1's answer to include User 2's answer. A: If it is correct answer - accept it. There are many reasons why one would be an Answerers who only use comments, or prefer edits over creating own answer. One reason why not to create new answer is original answer is 95% there and creating new complete answer would mean essentially copying whole existing answer and adding one word. This may be reasonable for old/abandoned answers (especially if code change is required), but this case is new and all authors participated. Note that commenter seem to explicitly prefer keeping that answer instead of creating new one, so asking for new separate answer would be strange: added in the edit including that comment. Once accepted by @Peter it should thus be possible to consider it as the answer A: I think ideally, you'd want the person who actually solved your problem to write the answer so you can accept it—or, if he's not going to do so, to put his solution into a Community Wiki answer (as with Question with no answers, but issue solved in the comments) and accept that. If the helpful person has already edited someone else's answer to be correct, what would that change? Clearly, he doesn't mind losing credit for his work. And anyone searching for your question later will be nicely served by the edited answer. So, as long as the person whose answer he edited doesn't mind having his answer improved (and getting more rep), who's being hurt if you just accept the edited answer? Even if it's a third person who did the edit, who's being hurt? It's basically the same case for everyone involved. Unless, of course, you think the commenter was going to come back and write his own answer. In that case, definitely wait for him to do so. I don't think we should be encouraging this kind of third-party edit, but we really aren't encouraging them—the editor isn't the one getting the rep or any other form of credit. So, if you: Suspect that the commenter actually does want to write his own answer and hasn't had time yet, Are seriously worried that the original answerer is going to reject the edit, or Are bothered that the answered doesn't deserve the rep… … then ignore the edit (or even revert it) and write and accept a Community Wiki answer (or, in the first case, wait for the commenter's answer). Otherwise, I'd just accept it.
[ "homebrew.stackexchange", "0000024066.txt" ]
Q: Impact of reboiling wort Long story short, somehow after a chilling my beer after the boil, I've ended up with additional water in the wort (must have a leak in the chiller!). Took me a while to notice, couldn't understand why my OG was 20points off! As a result I need to boil the wort for another hour to get down to my intended volume. What effect will this have on the beer? I guess I'll lose all of those hop aromas from late additions in the first boil? For reference it's an APA with hop additions at 60, 15 & 0min. I intend to do another hop stand to make up for this, but fully expecting the 2nd boil to have a detrimental effect on the beer... A: Just to clarify. You're reboiling wort at this point not beer. Boiling beer is a different issue. In your case the effects will be that your late hop additions will now add to IBU and lose most the aroma and flavor a late addition adds.
[ "stackoverflow", "0018110094.txt" ]
Q: Double pointer of Mat initialization I am trying to make a Mat array using OpenCV. The array is to store a number N of region of interest, and for each region I have to store the information of the last 5 frames. I'm trying to use a double pointer to Mat. The question is how do I initialize it? I'm trying something like this: In the header of the class: Mat *Objs_avgwB[25]; and to initialize in the source file: vseg.Objs_avgwB = new Mat[vseg.avgw][25]; A: Instead of mucking around with pointers and new, a better option is to use the containers provided by the standard library. You don't need to worry about exactly how you'll initialize them, since they can be resized dynamically. For each set of features in a frame, I would create a std::vector of cv::Mat objects, one for each region of interest. Then, use a std::deque to hold the features for each frame. std::deque<std::vector<cv::Mat>> roi_history; On each new frame, you would push_back each ROI onto the std::vector representing all ROIs in that frame: std::vector<cv::Mat> new_rois; new_rois.push_back(roi1); new_rois.push_back(roi2); // Etc... you then pop off the oldest frame and push the new data to keep 5 frames in the queue: roi_history.pop_back(); roi_history.push_front(new_rois); You can then access each ROI in the history by using operator[] For example, to access the fourth ROI found in the previous frame (remember zero-indexing!): cv::Mat my_roi = roi_history[1][3]; // ^ ^ // | Fourth ROI // | // Most recent history (zero is current frame)
[ "stackoverflow", "0050393747.txt" ]
Q: Populate Marker with current location in MapsActivity I have successfully developed a program to update the marker as the user travels, however the text will only say "Current Location" I would also like to populate the marker with Address information to the user when clicked. Below are some snippets of code emphasizing my intention, any help will be greatly appreciated! Thank you Here is my current MapsActivity.java import android.Manifest; import android.content.pm.PackageManager; import android.graphics.Camera; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; import java.util.List; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private GoogleMap mMap; private GoogleApiClient client; private LocationRequest locationRequest; private Location lastLocation; private Marker currentLocationMarker; public static final int REQUEST_LOCATION_CODE = 99; TextView textView; Geocoder geocoder; List<Address> addresses; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ checkLocationPermission(); } // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode) { case REQUEST_LOCATION_CODE: if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //permission is granted if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if(client == null){ buildGoogleApiClient(); } mMap.setMyLocationEnabled(true); } } else { Toast.makeText(this, "Permission Denied!", Toast.LENGTH_LONG).show(); //Permission is denied } return; } } @Override public void onMapReady(GoogleMap googleMap) { Toast.makeText(this, "Click Icon in Top right for Current Location", Toast.LENGTH_LONG).show(); mMap = googleMap; LatLng Phoenix = new LatLng(33.6056711, -112.4052378); mMap.addMarker(new MarkerOptions().position(Phoenix).title("Default Location: Phoenix, AZ")); mMap.moveCamera(CameraUpdateFactory.newLatLng(Phoenix)); if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } protected synchronized void buildGoogleApiClient(){ client = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); client.connect(); } @Override public void onLocationChanged(Location location) { lastLocation = location; if(currentLocationMarker != null){ currentLocationMarker.remove(); } LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)); textView = (TextView) findViewById(R.id.textView); geocoder = new Geocoder(this, Locale.getDefault()); try { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); String address = addresses.get(0).getAddressLine(0); String area = addresses.get(0).getLocality(); String city = addresses.get(0).getAdminArea(); String country = addresses.get(0).getCountryName(); String postalcode = addresses.get(0).getPostalCode(); String fullAddress = address+", "+area+", " +city+", " + country+ "," + postalcode; textView.setText(fullAddress); } catch (IOException e) { e.printStackTrace(); } mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomBy(10)); if(client != null){ LocationServices.FusedLocationApi.removeLocationUpdates(client, this); } } @Override public void onConnected(@Nullable Bundle bundle) { locationRequest = new LocationRequest(); locationRequest.setInterval(1000); locationRequest.setFastestInterval(1000); locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this); } } public boolean checkLocationPermission(){ if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE); } return false; } else return true; } public void onZoom(View view) { if (view.getId() == R.id.zoomIn) { mMap.animateCamera(CameraUpdateFactory.zoomIn()); } if (view.getId() == R.id.zoomOut) { mMap.animateCamera(CameraUpdateFactory.zoomOut()); } } public void ChangeType(View view) { if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) { mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); Toast.makeText(this, "Satellite Map Style", Toast.LENGTH_LONG).show(); } else if (mMap.getMapType() == GoogleMap.MAP_TYPE_SATELLITE) { mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); Toast.makeText(this, "Hybrid Map Style", Toast.LENGTH_LONG).show(); } else if (mMap.getMapType() == GoogleMap.MAP_TYPE_HYBRID) { mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); Toast.makeText(this, "Terrain Map Style", Toast.LENGTH_LONG).show(); } else if (mMap.getMapType() == GoogleMap.MAP_TYPE_TERRAIN) { mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); Toast.makeText(this, "Normal Map Style", Toast.LENGTH_LONG).show(); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } } Here is the corresponding xml file: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/img_header" > <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.SupportMapFragment" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="40dp" android:text="Test" android:layout_centerHorizontal="true" android:textSize="22sp"/> </RelativeLayout> StackTrace 05-17 09:15:49.411 15842-15842/edu.phoenix.mbl402.week3apptt2163 E/AndroidRuntime: FATAL EXCEPTION: main Process: edu.phoenix.mbl402.week3apptt2163, PID: 15842 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java:437) at edu.phoenix.mbl402.week3apptt2163.MapsActivity.onLocationChanged(MapsActivity.java:139) at com.google.android.gms.internal.location.zzay.notifyListener(Unknown Source:4) at com.google.android.gms.common.api.internal.ListenerHolder.notifyListenerInternal(Unknown Source:8) at com.google.android.gms.common.api.internal.ListenerHolder$zza.handleMessage(Unknown Source:16) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) FINAL EDIT: @Override public void onLocationChanged(Location location) { lastLocation = location; if(currentLocationMarker != null){ currentLocationMarker.remove(); } LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title(getAddressForLatLng()); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)); currentLocationMarker = mMap.addMarker((markerOptions)); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); } public static Address getAddressForLatLng(Context context, LatLng location) { final int MAX_RESULTS = 1; final Geocoder geocoder = new Geocoder(context, Locale.getDefault()); Address address = new Address(Locale.getDefault()); try { final List<Address> addresses = geocoder.getFromLocation(location.latitude, location.longitude, MAX_RESULTS); if (addresses != null && addresses.size() != 0) { address = addresses.get(0); } return address; } catch (IOException e) { Log.e("Geocoding", "Geocoding was not possible"); } return address; } A: You don't have to remove marker from map on each location update. reuse existing marker store reference to it. Marker mMarker = mMap.addMarker(new MarkerOptions()......) After creating mMarkerObject refresh its location in OnLocationChanged mMarker.setTitle() mMarker.setPosition(latLng); If for some reason You still want to implement on click action add interface to Your main activity OnMarkerClickListener and override OnMarkerClick and use showInfoWindow or something :) EDIT: for geocrush try following -> public static Address getAddressForLatLng(final Context context, final LatLng location) { final int MAX_RESULTS = 1; final Geocoder geocoder = new Geocoder(context, Locale.getDefault()); Address address = new Address(Locale.getDefault()); try { final List<Address> addresses = geocoder.getFromLocation(location.latitude, location.longitude, MAX_RESULTS); if (addresses != null && addresses.size() != 0) { address = addresses.get(0); } return address; } catch (IOException e) { Log.e("Geocoding", "Geocoding was not possible"); } return address; } Simplified more efficient version of onLocationChanged() @Override public void onLocationChanged(Location location) { lastLocation = location; LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); currentLocationMarker.setPosition(latLng); // make sure following setTitle gets String from getAddressForLatLng currentLocationMarker.setTitle(getAddressForLatLng(latLng)); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); }
[ "stackoverflow", "0017564235.txt" ]
Q: How do you access your DevKit connector in a Functional unit test? I'm trying to verifiy certain properites of my Connector in a test. You can't do this: Object c = registry.lookupConnector("myDevkitCon"); because the connector has a different type from normal connector, ie the internal mule code expects a Connector type but in our case a myDevkitConConnectorConnectionManager is returned. A: DevKit generates classes that wrap your connector in order to add certain properties to it. One is connection pooling. This means that if you want an instance of your connector, you have to: Instiantiate myDevkitConConnectorConnectionManager Call the relevant setters on it to configure it Call initialise() Call acquireConnection() BTW this circles back to your other question Getting functional unit tests to wait until devkit connector is connected Hopefully you now better understand my answer.
[ "stackoverflow", "0003063270.txt" ]
Q: C# Get Events of a Control inside a Custom Control I have a listbox inside a custom control. I use this custom control into a form. I would like to be able to get the listbox index changed event when I am working into the form. How can I do that? A: If you are using WinForms, then you need to wire this event manually. Create event with the same signature on your custom control, create a handler for the even on the original listbox inside your custom control and in this handler fire the newly created event. (ignore all of this if you are using WPF) A: You can add a proxy event to the custom control public event EventHandler<WhatEverEventArgs> IndexChanged { add { listBox.IndexChanged += value; } remove { listBox.IndexChanged -= value; } } A: This can be a disadvantage of a UserControl. You have to re-publish the events and the properties of one or more of its embedded controls. Consider the alternative: if this UserControl only contains a ListBox then you are much better off simply inheriting from ListBox instead of UserControl. Anyhoo, you'll need to re-fire the SelectedIndexChanged event. And surely you'll need to be able to let the client code read the currently selected item. Thus: public partial class UserControl1 : UserControl { public event EventHandler SelectedIndexChanged; public UserControl1() { InitializeComponent(); } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { EventHandler handler = SelectedIndexChanged; if (handler != null) handler(this, e); } public object SelectedItem { get { return listBox1.SelectedItem; } } }
[ "math.meta.stackexchange", "0000013489.txt" ]
Q: What is the etiquette for reposting one's own answer? At one point I wrote a fairly detailed explanation of why equivalence relations on a set and partitions of that set are essentially the same thing. The issue came up in a new question again. The new question is not a duplicate of the old one, so closure as a duplicate is not appropriate. (The original question was specifically about the left cosets of a group, and the new question is more general, just complete bafflement about equivalence relations: What exacly are equivalence classes.) It was tempting to copy most of my previous answer, which I was happy with, into a new answer to the new question. In the past I have not usually done this, and instead have left a comment pointing to the old answer. That is what I did this time. My feeling is that such cases are good opportunities to let other people write their own answers. On the other hand, I think my old answer is pretty good, and might be helpful if reposted. Although the idea of posting the same answer twice makes me uncomfortable, I am not sure why, and I have not been able to identify any specific moral or ethical problem with it. I am interested to hear what other people in the community think about this. A: Ethically speaking, I think it's perfectly fine to repost your own answer to a second question. It's certainly better than answering with a rushed, inferior version of the old answer, or feeling forced to paraphrase a copy of your old answer. A better long-term solution might be to build an indexed list of blog-like in-depth treatments to commonly-asked topics, and point people there. (We have the beginnings of something like this with our "generalization of common questions" list). A: Duplication of content is a problem, even regardless of ethical and moral considerations (and they exist). What if your original answer contains a minor flaw that you overlooked, and someone notices it and correct it? Now there are two slightly different versions of the same answer on the site, one with a flaw and one without. You also deprive the people finding the new or the old question from learning about a different point of view about the same thing, assuming the question weren't already duplicates of each other. At the very least there should be links, preferably in both directions, indicating that the answer was copied. A better option in most cases, IMO, would be to make a whole new answer, explaining why the old answer solves the question and then link to it. Something like this: By theorem XYZ, we can see that your hypothesis A is equivalent to some other hypothesis B, and so by this answer your object satisfies property W which implies what you want to prove for such and such reason. Of course, if you apply this reasoning, you will sometimes be left with an answer that looks like "This older answer solves your problem." In this case, the new question is actually a duplicate of the old one and should be closed, instead of answered. A: Several prominent members of the community expressed support for this behavior, and nobody made any serious argument against it, so I conclude that it is all right to do it. On thing I thought of after I asked the question: When reposting an answer, it may be tempting to paste the text in without re-reading it. But such re-reading is important. Questions do differ, and the old answer might be missing discussion of some point that is important in new context but not in the original, or vice versa. It ill-serves the community to let such copy-pasted answers appear without editing. So one must take care that the answer is really well-suited to its new home, and perhaps do a bit of tailoring to make sure it fits.
[ "pt.stackoverflow", "0000435059.txt" ]
Q: Alinhar Navbar Bootstrap-React Estou tentando alinhar o navbar para a direita, porém, sem sucesso, está assim atualmente: index.js import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import { Nav, Navbar } from 'react-bootstrap'; import Nav_Link from '../../components/index'; import LogoImg from '../../assets/logo.png'; import RetanguloImg from '../../assets/retangulo.png'; import PredioImg from '../../assets/predio.png'; import { Nav_Link_Line, Button, Title, Text, Text2, Button2, Table, } from './styles'; export default class Main extends Component { render() { return ( <div> <Navbar expand="lg" variant="dark"> <Navbar.Brand href="#home"> <img class="logo" src={LogoImg}></img> </Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mr-auto"> <Nav_Link href="">QUESTINÁRIO</Nav_Link> <Nav_Link href="">DÚVIDAS</Nav_Link> <Nav_Link href="">FEEDBACK</Nav_Link> <Nav_Link href="">CONTATO</Nav_Link> <Nav_Link href="">SOBRE</Nav_Link> <Nav_Link_Line href=""> <div class="line"></div> </Nav_Link_Line> <Nav_Link href="">LOGIN</Nav_Link> <Button href="">CADASTRE-SE</Button> </Nav> </Navbar.Collapse> </Navbar> styles.js export const Nav_Link = styled.a` margin-left: 31px; margin-top: 15px; color: white; display: flex !important; justify-content: end !important; &:link { text-decoration: none; } &:hover { color: #748aaa; } `; export const Nav_Link_Line = styled.text` margin-left: 31px; margin-top: 10px; color: white; `; global.js .navbar { background-color: #3D5975; color: #ffff; font-weight: bold; height: 64px; width: 100%; } A: Use Display flex na sua nav, depois use justify-content: flex-end para alinhar o conteúdo no final do seu elemento. Eu fiz um codepen usando div e lista para te mostrar, mas o conceito é o mesmo. https://codepen.io/ianpbh/pen/OJVVbxa
[ "stackoverflow", "0016693463.txt" ]
Q: How to accomplish query notification on SQL Server with python I would like to set up a callback in Python when a table on SQL Server changes, similar to how its done for Oracle here. http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/oow10/python_db/python_db.htm#t11 Is there a library that allows me to do so in Python, an example would be appreciated. A: First, download the ODBC Driver for Linux Then Install pyodbc using pip pip install pyodbc==3.1.1 Create a py file with this code: import pyodbc server = 'yourserver.database.windows.net' database = 'yourdatabase' username = 'yourusername' password = 'yourpassword' driver= '{ODBC Driver 13 for SQL Server}' cnxn = pyodbc.connect('DRIVER='+driver+';PORT=1433;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password) cursor = cnxn.cursor() cursor.execute("select @@VERSION") row = cursor.fetchone() if row: print row That's your basic connection and call. Then follow the procedures from your oracle link, "Using Continuous Query Notification" But... maybe b/c I am a SQL guy and a security wonk, it seems you'd be better off to have SQL Server push change notifications to somewhere python can get to it.
[ "stackoverflow", "0062278713.txt" ]
Q: react-script build giving error while deploying to heroku I am trying to deploy my create-react-app on heroku under my node/express server. I am using the heroku postbuild script but I am getting an error about react-script build. Well I am new to the backend side and not knowledged about heroku deployments. //my npde server scripts "scripts": { "start": "node index.js", "server": "nodemon index.js", "client": "npm run start --prefix client", "dev": "concurrently \"npm run server\" \"npm run client\"", "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client" }, //my client scripts "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, //The error log remote: /tmp/build_9c0331519287501c707a58e785c7cac2/client/node_modules/react-scripts/config/webpack.config.js:306 remote: ...(isEnvProductionProfile && { remote: ^^^ remote: remote: SyntaxError: Unexpected token ... remote: at createScript (vm.js:74:10) remote: at Object.runInThisContext (vm.js:116:10) remote: at Module._compile (module.js:533:28) remote: at Object.Module._extensions..js (module.js:580:10) remote: at Module.load (module.js:503:32) remote: at tryModuleLoad (module.js:466:12) remote: at Function.Module._load (module.js:458:3) remote: at Module.require (module.js:513:17) remote: at require (internal/module.js:11:18) remote: at Object.<anonymous> (/tmp/build_9c0331519287501c707a58e785c7cac2/client/node_modules/react-scripts/scripts/build.js:38:23) remote: npm ERR! code ELIFECYCLE remote: npm ERR! errno 1 remote: npm ERR! [email protected] build: `react-scripts build` remote: npm ERR! Exit status 1 remote: npm ERR! remote: npm ERR! Failed at the [email protected] build script. remote: npm ERR! This is probably not a problem with npm. There is likely additional logging output above. remote: remote: npm ERR! A complete log of this run can be found in: remote: npm ERR! /tmp/npmcache.eaz5f/_logs/2020-06-09T08_25_12_438Z-debug.log remote: npm ERR! code ELIFECYCLE remote: npm ERR! errno 1 remote: npm ERR! [email protected] heroku-postbuild: `NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client` remote: npm ERR! Exit status 1 remote: npm ERR! remote: npm ERR! Failed at the [email protected] heroku-postbuild script. remote: npm ERR! This is probably not a problem with npm. There is likely additional logging output above. remote: remote: npm ERR! A complete log of this run can be found in: remote: npm ERR! /tmp/npmcache.eaz5f/_logs/2020-06-09T08_25_12_454Z-debug.log A: The clue is in this error line: SyntaxError: Unexpected token .... It means Node can't recognise the ... syntax. The spread operator (...) is available from Node.js v8.6 and up. Make sure Heroku is using the right Node version by setting it in your package.json file: { "engines" : { "node" : ">=8.6" } }
[ "stackoverflow", "0057814234.txt" ]
Q: Sorry, your session has expired. Please refresh and try again. - Laravel 5.8 I create a route Route::post('/ddos/store','DdosController@store'); I also have a controller public function store() { dd("HERE"); $ddos = new Ddos; $ddos->ip = $ip; $ddos->details = $details; $ddoss->save(); return $ddos; } I kept getting - when making a TEST post via postman I suppose to see the text "HERE" from my controller. What did I do wrong ? A: Postman is not sending a CSRF token in the request and your route is under the web routes group which applies the VerifyCsrfToken middleware Either move your route to an api group or add it as an exception use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware { /** * Indicates whether the XSRF-TOKEN cookie should be set on the response. * * @var bool */ protected $addHttpCookie = true; /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'ddos/store' ]; } A: There is a middleware executed before dd line executed. It's called CSRF Protection. You can exclude it by adding this line in the app\Http\Middleware\VerifyCsrfToken. protected $except = [ '/ddos/store', ]; If you insist to keep sending csrf token with postman, you can create tests case and save it in environment variable (which i suggest). This link might help you.
[ "stackoverflow", "0027860251.txt" ]
Q: Read string from socket channel Hy, I have the following code: public AppThread(SocketChannel socketChannel){ this.socketChannel=socketChannel; } public void run(){ try{ ByteBuffer bb = ByteBuffer.allocate(11); socketChannel.read(bb); //byte[] b = new byte[bb.capacity()]; // bb.get(b, 0, 11); System.out.println(bb.toString()); byte[] a = new byte[11]; CharBuffer cb = bb.asCharBuffer(); System.out.println(cb); bb.get(a); App app=new App(); // String an = new String(b); //String zodie = Zodie.getZodie(an); //b = new byte[zodie.length()]; //b = zodie.getBytes(); bb.clear(); //bb.put(b); socketChannel.write(bb); socketChannel.close(); } catch(IOException e){ System.err.println("Server comunication error : "+e.getMessage()); } } } and the zodie static method which receive a string and return a string. How can I get the string written into SocketChannel to pass it as argument to zodiac static method. I mention that in the client side I send an array of bytes and I have checked and it's ok. Client side: byte[] a = an.getBytes(); System.out.println(new String(a)); ByteBuffer bb=ByteBuffer.allocate(11); // Varianta 1 bb.put(a); // Varianta 2 // LongBuffer lb=bb.asLongBuffer(); // lb.put(0,m).put(1,n); try{ sc.write(bb); bb.clear(); sc.read(bb); // Varianta 1 //a = new byte[bb.remaining()]; zodie=bb.toString(); // Varianta 2 // r=lb.get(0); System.out.println("Zodia : "+ zodie); sc.close(); Sincerely, I get the server error: Server ready... java.nio.HeapByteBuffer[pos=1 lim=11 cap=11] Exception in thread "pool-1-thread-1" java.nio.BufferUnderflowException at java.nio.HeapByteBuffer.get(Unknown Source) at java.nio.ByteBuffer.get(Unknown Source) at server.AppThread.run(AppThread.java:27) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) A: The issue was on the client side. I have used a charbuffer as a wraper Scanner scanner=new Scanner(System.in); String m; System.out.println("Enter the date (yyyy-mm-dd) :"); m=scanner.next()+" "; CharBuffer c = CharBuffer.wrap(m); System.out.println("Sending date ...: " + c); ByteBuffer b = Charset.forName("ISO-8859-1").encode(c); b.compact(); System.out.println("Bytebuffer has the capacity of "+ b.capacity() + "pointer position on bytebuffer is on: "+ b.position() + " and the limit is:" + b.limit()); b.flip(); On the server side: CharBuffer c; ByteBuffer bb = ByteBuffer.allocate(11); System.out.println("Server allocated a number of 11 octets to ByteBuffer"); socketChannel.read(bb); bb.flip();//sets the Position to 0 and limit to the number of bytes to be read. CharBuffer c = Charset.forName("ISO-8859-1").decode(bb); System.out.println("Got " + c); byte[] byteArray = new byte[11]; bb.get(byteArray); System.out.println("Server got from client the string: " +new String(byteArray)); String an = new String(byteArray); bb.clear();
[ "stats.stackexchange", "0000030665.txt" ]
Q: How to do binary logistic regression on people (couples) clustered within homes? I am looking at the relationship between housing characteristics and a health outcome. To make the example simple, I have data for a continuous predictor (exposure) collected from 1000 homes and health outcomes S (a binary outcome) for 2000 people (1000 couples) living in each of those homes. I would like to look at the relationship between S and E using binary logistic regression. Apart from sharing the same exposure, there is no mechanistic reason to believe that status of partner 1 in the couple can affect the status of partner 2 e.g. its not a transmissible disease etc. Can I do an ordinary logistic regression? Or must I take into account the fact that people are clustered within homes? If so, why? What syntax would be appropriate in Stata, xtlogit with i(house)? or some kind of xtmixed? Many thanks A: For me, this sounds like a (more or less typical) dyadic data set and I would definitely control for dyadic dependencies (i.e. at the houshold level) via multilevel/structural equation modeling. David Kenny owns a great website on Dyadic Analysis. He also is co-author of a book on Dyadic Data Analysis that is highly recommanded. Since you seem to use Stata, I would use the xtmelogit command (see here for more information). A: One assumption of fixed-effects general linear models (e.g. "ordinary" logistic regression) is that observations are independent of each other. However, there is likely some dependency in the observations in your study. For example, two people living in the same household are more likely to have similar diets and similar levels of physical activity than two people living in separate households. I would consider modelling the data using either a logistic or Poisson mixed-effects model. The fixed effects would be your measured exposure covariates. The random effect would be the household. I am not particularly famililar with Stata's mixed effects syntax. In R, for a logistic mixed-effects model, I would call glmer(outcome ~ exposure1 + exposure2 + (1|household), data = study.data, family = binomial). A quick Google search suggests that the equivalent in Stata would be xtmelogit outcome exposure1 exposure2 || household.
[ "stackoverflow", "0009210811.txt" ]
Q: Filtering characters missing from the user’s font in Java I want to build a somewhat simple table with Java (as an exercise) to check for the existence of legal printable Unicode code point in the end-user’s font. Because some fonts cannot print valid code points, I have to know which printable code points the user’s font is nevertheless missing and so cannot print. For example, if a font supports only Latin characters, I cannot print Greek characters using it, let alone Japanese characters. Unicode says they’re all printable, but the user’s font may not be good enough. After a little research I’ve been able to print most of the characters in Eclipse (by adjusing the Encoding). However I still have a bunch of unknown/unprintable characters in my output, in that when I look at the output I see all these empty rectangles for some of my printable characters. I’ve tried filtering them but I can’t find any way to do it. FYI I’m basically just setting a character's value to 50, 100 or 1000, then incremeningt it via a for loop from there to check what characters I can or cannot (or should not?) print. Can anyone give me some hints on where to start here? A: Your task is actually a little more complex than encoding because the font that you are trying to print from makes a big difference in the output. I.e. not all fonts support the same set of characters. In fact, the support of character ranges differs wildly from font to font. That said, your problem now becomes: How do I detect whether a certain font supports a given character? And that question has been asked and answered... See here for the Java doc of the canDisplay function which is a member of the Font class.
[ "physics.stackexchange", "0000481516.txt" ]
Q: Why are atoms not destroyed when dropped? I made the following thought experiment: Dropping a gold ring on a wooden table. It drops, hits the table, bounces off, hits again with less velocity and so on until it finally rests. Now consider an gold atom inside the ring. It will of course be accelerated and there is no problem with the nucleus and shell having a huge mass difference as the gravitational acceleration is independent of the mass. Assume it is a carbon atom that is hit when the ring hits the table. This is reasonable as there are a lot of carbon atoms in wood. Now the only force that can stop our ring is the electromagnetic force, since we only have four forces, there is no anti-gravity and the weak and the strong force do not extend to the outer shell. From the geometry of the two atoms the one shell interacts therefore with the other shell first. The gold atom is a lot heavier than the carbon atom so the carbon atom will start moving and will in turn move other atoms which distributes the force so the counter force starts to increase and in the end will balance forces which brings the gold atom to a halt and then even pushes back so the ring bounces back. The rules are governed by Hooke’s law, the table acts like a spring. But the atom is not a solid sphere, it is like a solar system with all the mass centered in the center. And here I am not understanding how this can actually work. If the electromagnetic force is stopping the atom it can only act on the shell first (because of the speed of light being finite) and therefore the nucleus is simply continuing to follow his trajectory because of the law of inertia. It is thus suddenly pushed out of the center of the atom and even if I ignore that now one side of the shell is pulling harder on the nucleus than the other, the shear difference in mass must just lead to the nucleus crushing through the shells of several atoms. It is like trying to stop a Mercedes by pushing against the star mounted on the bonnet. So what is preventing the atom from being destroyed? How is the force that stops the shell actually put on the nucleus, because obviously the ring does not take any damage when dropped. A: The appropriate intuition here is that small objects operate on faster timescales. You might not be able to stop a Mercedes by pushing on the star instantly, but you certainly can if you gradually push on it for a couple of centuries. In the case of an atom, the appropriate timescales are given by the de Broglie relation $E = \hbar \omega$, so $$t \sim \frac{1}{\omega} \sim \frac{\hbar}{E} \sim \frac{10^{-34} \, \text{J s}}{1 \, \text{eV}} \sim 10^{-15} \, \text{s}.$$ If an impact takes a few milliseconds, then in a classical picture, during the collision the electron can go around the nucleus a trillion times. In our solar system, the equivalent timescale for the Sun and the Earth would be a trillion years. The same intuition holds in the quantum case. The collision is not sudden at all, and there's no reason that impulse can't be gradually transferred from the electron to the nucleus. In fact, for both the classical and quantum cases, this intuition can be formalized by the adiabatic theorem, whose conditions are satisfied extremely well here.
[ "stackoverflow", "0009831239.txt" ]
Q: How to map Zend_Db_Table_Row object to Zend_Form_Element_Select options (optial way) How would You populate Zend_Form_Element_Select with options direct from Zend_Db_Table_Row? For instance: $select = new Zend_Form_Element_Select('user_id', array( 'required' => true )); // fetching users for select $userTable = new User_Model_DbTable_User(); $users = $userTable->fetchAll(); $select->addMultiOptions($users->toArray()); But this will not work to good. Let say I want to have object id as a option value and some object property as an select label. I know I can run foreach thourgh the rowset and construct an array of options but maybe there is some kind of map function? A: Any map function you create would be iterating the rowset so you might as well simply do that, eg foreach ($users as $user) { $select->addMultiOption($user->id, $user->someObjectProperty); }
[ "stackoverflow", "0020704511.txt" ]
Q: how to access a private vector of linked lists [A,0]->[B,3] [B,0]->[A,3] This is the data structure i plan to use where the Y coord is the vector and the x coord is the list. each node in the list will contain a string and a integer (as shown above). lets pretend this is the class that contains the declaration of the vector of linked lists, well call it Graph, since this is a graphing assignment...[Note this code wont compile as i sketched it up to make it look simpler for others to read.] class Graph { public: Graph(){...} ~Graph(){...} private: class Edge { public: Edge(string vertex, int weight) { m_vertex = vertex; m_weight = weight; } ~Edge(){...} string m_vertex; int m_weight; }; vector< list < Edge > > adjacency_list; //the vector of linked lists }; In a completely different .h file I would have this class declared: class Modify_Graph { public: void access_Edge(); //...... private: //...... }; this is contained in the Modify_graph.cpp file void Modify_Graph::access_Edge() { adjacency_list adjList; cout << "The very first vertex is: "; cout << adjList[0].front().m_vertex << endl; } when I compile that it tells me that it cannot find 'adjacency_list' is there a way I could get it? In a more complex program I tried passing it by reference, returning it, and other things but none of them seemed to work. I am completely unsure what to do. A: You need an instance of Graph from which to access adjacency_list, as well as (given that it's private) a method that for accessing the member e.g. something like vector< list < Edge > > Graph::GetAdjacencyList() { return adjacency_list; } Additionally, you also need to make Edge at least public in Graph or declare it outside of Graph. If you kept it as a public inner class, your function prototype would be vector< list < Graph::Edge > > Graph::GetAdjacencyList(). Use of the function would then be something to the effect of void Modify_Graph::access_Edge() { vector< list < Graph::Edge > > adjList = m_graph.GetAdjacencyList(); //m_graph being a member of type Graph cout << "The very first vertex is: "; cout << adjList[0].front().m_vertex << endl; }
[ "stackoverflow", "0013278499.txt" ]
Q: Virtual box vdi Nasm jump I'm doing research on bootloaders. That is, I'm trying to write simple bootloader with Nasm which will run in VB (vdi disk). For now on I did set up a virtualbox environment for testing purposes and successfully load MBR which resides on absolute address (HXD hex editor) 0x2000. But now I want to jump outside MBR (0x2200 big endian) and execute code which resides there (Below snippet doesn't do the job). I use Nasm directive [org 0x7C00], do I have to use this offset when making jumps? [BITS 16] [org 0x7C00] %define location 0x0022 start: mov al, 0x12 mov ah, 0 int 0x10 jmp location:0000 TIMES 510 - ($ - $$) db 0 DW 0xAA55 This is hex view from vdi (2000h is where MBR starts, 2200h is where I want to jump): A: The boot sector will be loaded at address 0x7c00 (which, due to the peculiarities of real mode segments, may be addressed in multiple ways. The two common ones being 0:0x7c00 and 0x7c0:0 - you shouldn't rely on a particular one). The fact that it is at offset 0x2000 in your disk image is probably due to the format of said image, it has no relevance to the memory address. Also, the boot process only loads a single sector of 512 bytes, if you need more you have to load it yourself. Then you can jump to it, using the address that you loaded it to.
[ "stackoverflow", "0022473003.txt" ]
Q: Supress Can't Locate module warning in Perl I was implementing logger in the perl backend service. I am trying to print the content trapped by local $SIG{__DIE__}=. local $SIG{__DIE__}= catches following error:Can't locate xyz.pm in @INC (@INC contains ...............). Whenever I run the script by command line, I can't see the above error message generated on the terminal. Just local $SIG{DIE}= catches this message. Is there any way to supress can't locate warning message? I tried to go through perl doc(Category Hierarchy) http://perldoc.perl.org/perllexwarn.html, but i don't know, can't locate warning belongs to which category? A: That's an error, not a warning. And you should fix this error, because your script will not run until you install the required module. If you just don't want to log that specific message, you could just skip anything that matches some regex of uninteresting messages: my $uninteresting_re = qr{\ACan't locate \w+(?:/\w+)*[.]pm in \@INC [(]you may need to install}; $SIG{__DIE__} = sub { my ($error) = @_; print $log $error unless $error =~ $uninteresting; # let error propagation continue as usual };
[ "superuser", "0000352492.txt" ]
Q: How can I merge two different hard drives for Windows Server? I have two hard disk drives, each of 1TB size. How can I merge them and make them one drive in Windows Server 2008? After doing that, how can I reinstall Windows on those hard drives, keeping the data? A: You are looking for RAID0, also known as striping. Check out this web page for more information. As far as keeping data on both drives? You'll need to transfer it off the drives and recopy it over. I HIGHLY recommend having a backup and restoring it with that method. Although RAID0 is faster then individual disks, you are DOUBLING your risk for data loss on BOTH drives. Make sure all critical data is backed up!!!
[ "math.stackexchange", "0003333007.txt" ]
Q: If $x$ and $y$ are real numbers such that $4x^2 + y^2 = 4x - 2y + 7$, find the maximum value of $5x+6y$. If $x$ and $y$ are real numbers such that $4x^2 + y^2 = 4x - 2y + 7$, find the maximum value of $5x+6y$. I did a little bit of manipulation and got $4(x+1)(x-2) + (y+1)^2=0$. I then got $x=2$ and $y=-1$ which means the maximum must be $4$, but the answer key says it's $16$. How come? A: $$4x^2-4x + 1+y^2 + 2y +1 =9\implies (2x-1)^2+(y+1)^2=9$$ So a pair $(x,y)$ is on elipse: $${(x-{1\over 2})^2\over {9\over 4}}+{(y+1)^2\over 9}=1$$ so you can write $x= {3\over 2}\cos t +{1\over 2}$ and $y= 3\sin t -1$ So your expresion is now $${15\over 2}\cos t +18\sin t -{7\over 2}$$ This you can write as $${39\over 2}\sin (t+\varphi) -{7\over 2}$$ for some phase $\varphi$. So the maximum is when $\sin (t+\varphi)=1$ and it is $16$ and minimum is when $\sin (t+\varphi)=-1$ and it is $-23$.
[ "stackoverflow", "0053633933.txt" ]
Q: Jquery Datatables get absolute index of parent column I have written built-in column filtering plugin for datatables and I have small trouble, I have created text inputs in each column footer and now - on keyup I want to catch them indexes and then use it when filtering. I'm getting parent column index by following line in my code: var visIdx = $(this).parent().index(); It's returning properly index only when ALL columns are visible, but when one of them is hidden, then following columns returning bad indexes. It causes that when some of columns are hidden filtering is applying to bad columns There is my full code on fiddle: http://live.datatables.net/pulewemu/3/edit?js,console,output A: The thing is that DataTable is creating new elements on each draw(). What you see isn't your "original" table with some hidden columns, but a totally new set of elements including only the "visible" columns. So there is no way to get an "absolute" index from there. What I suggest is to add that index in a data attribute in the .each() loop that defines the search inputs: $('#example tfoot th').each(function(i) { var title = $(this).text(); var hate = '<input size="4" class="fder" type="text" id="gte" placeholder="min" data-index="'+i+'" />' hate += '<br><input size="4" class="fder" type="text" id="lov" placeholder="max" data-index="'+i+'" />' $(this).html(hate); }); And then, on keyup, retreive the index like this: var visIdx = $(this).data("index");
[ "stackoverflow", "0059463298.txt" ]
Q: reusing text with multiple components of same type in vuejs Vue.component('home',{ template: '<p>{{homeText}}</p>', data: function(){ return{ homeText:"Welcome" } } }) new Vue ({ el:'#app' }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <home></home> <home></home> <home></home> </div> Currently I am hardcoding the value in the data function. I am trying to reproduce result to be Welcome to this page!! I want to be able to add different text to my home component. In examples and tutorials all i find is how to change numeric values. I want to know how I can pass custom text to these components. My goal is to build a section component and then pass custom text to each component. A: Instead of using data, define a prop named homeText and then pass custom text to the component wherever it's used: Vue.component('home',{ template: '<p>{{homeText}}</p>', props: ['homeText'] }) new Vue ({ el:'#app' }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <home home-text="welcome"></home> <home home-text="to"></home> <home home-text="this page"></home> </div>
[ "serverfault", "0000108508.txt" ]
Q: Failed Backup Job With Backup Exec 12 and AOFO I am backing up a Windows 2003 Small Business Server with SP2. We are running Backup Exec 12 with SP4. Recently the backup job started failing on backing up the system state with the following error: V-79-57344-34110 - AOFO: Initialization failure on: "System?State". Advanced Open File Option used: Microsoft Volume Shadow Copy Service (VSS). Snapshot provider error (0xE000FE7D): Access is denied. To back up or restore System State, administrator privileges are required. Check the Windows Event Viewer for details. Upon review of Symantec's website the error indicates a credential problem. However when I test the credentials they come back with no failures. I have found another forum here referencing a similar error and have tried what has been indicated with no succesful results. I have created new jobs based on new selection lists with no succesful results. I suspect a new update possibly from Microsoft may be causing this but I have no idea which one. I am looking for feedback. Thanks. A: I resolved this issue finally. Symantec changed something is SP4 for BackupExec 12 that requires that you predicate the service account being used for backups to include the domain (i.e. domainname\service account). Changed to this topology and backups function properly
[ "stackoverflow", "0005394163.txt" ]
Q: Zend with existing Propel ORM I'm working on converting a rather large (but somewhat simple) app from Symfony to Zend, large because of the DB. This is also my first Zend project, but it seems to be going well so far. The app is simple, the DB is fairly complex (I foresee many hours of datamapping ahead if done manually). I have all the original source code that was done using the Symfony FW. The original uses propel and works (and has over 200 models mapping the DB, 272 at quick glance). My DB tables have dependent row after row, I am also reusing the original DB structure...straight import of tables/schema, so I imagine that the original propel would still work fine in that respect. My question(s) is/are, would it be time well spent trying to reuse the propel section of the old app w/ my new Zend based version of the app? Should this be straight forward venture? If this could work, it may remove many sleepless nights from my life :) A: I think that you can reuse the Propel sections of the old app, since Propel 1.5 (current stable) and the next 1.6 are backward compatible down to Propel 1.3 (used by Symfony 1.0 if I remember well) and its original "Criteria" syntax. You will then benefit for the Propel 1.5 improvements (among them, the nice "Query" syntax), without losing the existing code. See: http://www.propelorm.org/wiki/Documentation/1.5/WhatsNew http://propel.posterous.com/propel-160-beta-2-released A: The model classes can contain references to Symfony classes, like sfMixer. They are added by extra Propel behaviors in the Symfony distribution. Because sfMixer will probably not exist in your new Zend project, this can lead to errors. However, it should be possible to re-generate your models with a clean Propel installation (in Zend, or in Symfony with the extra behaviors disabled), and then copy your own user-editable class files over the empty generated ones. If you use the same version of Propel in your Zend project as you did in your Symfony project, this should work out of the box (unless you edited the Base classes, but I assume you did not do that). If you are using a newer version of Propel in Zend to generate the models, there might be compatibility issues if you access protected members that since have changed.
[ "stackoverflow", "0015010986.txt" ]
Q: I need to write a shell script to make files executable by default if the file name does not contain system program names like "ls" and "grep" xprog (program name) Checks if this is a suitable name for a program, and if so, launches editor and makes sure file is executable by default. don't allow use of system program names like "ls" use "which" to see if command exists check return code "$?" touch (program) make new prog executable launch editor Testing xprog grep - rejected xprog newprog - ok, created, is executable, editor launched I'm really new to shell scripting and any help would be really appreciated, if I get my entire answer then great but any suggestions would help me out greatly. I've been searching for an answer for about 2 hours now and unfortunately I can't seem to find the place to start. The above are the guidelines for me to follow, I understand the what the description is I just can't seem to find the way to implement it on a shell script. Thanks guys. A: #!/bin/bash for i; do type &>/dev/null "$i" || { chmod +x "$i"; $EDITOR "$i"; } done Homework/noob version : #!/bin/bash for i in $@; do if which &>/dev/null "$i"; then true else chmod +x "$i" $EDITOR fi done Total noob version : #!/bin/bash for i in $@; do which &>/dev/null "$i" if [[ $? == 0 ]]; then chmod +x "$i" $EDITOR fi done
[ "stackoverflow", "0060757779.txt" ]
Q: MySQL: Select query using WHERE IN () with variables on the basis of conditions For my MySQL PROCEDURE, I have a select query statement using WHERE IN (...) clause, for which I need some conditional inputs/variables. example: SELECT * FROM test_table tt WHERE tt.section IN ('A', 'B', 'C'); SELECT * FROM test_table tt WHERE tt.section IN ('A', 'B', 'D'); SELECT * FROM test_table tt WHERE tt.section IN ('A','C'); SELECT * FROM test_table tt WHERE tt.section IN ('A', 'B', 'C', 'D'); How can I achieve this using a single query? Note: This select query statement is inside mySQL PROCEDURE. I'm looking for something like this: SET @ABC = '"A", "B", "C"'; SET @ABCD = '"A", "B", "C", "D"'; SET @AC = '"A", "B", "C", "D"'; SET @IN_CLAOUSE_VARIABLES = NULL; IF (<CONDITION 1>) THEN SET @IN_CLAOUSE_VARIABLES = @ABC; ELSEIF (<CONDITION 2>) THEN SET @IN_CLAOUSE_VARIABLES = @ABCD; ELSE SET @IN_CLAOUSE_VARIABLES = @AC; END IF: SELECT * FROM test_table tt WHERE tt.section IN (@IN_CLAOUSE_VARIABLES); A: SET @ABC = 'A,B,C'; SET @ABCD = 'A,B,C,D'; SET @AC = 'A,C'; SET @IN_CLAOUSE_VARIABLES = NULL; IF (<CONDITION 1>) THEN SET @IN_CLAOUSE_VARIABLES = @ABC; ELSEIF (<CONDITION 2>) THEN SET @IN_CLAOUSE_VARIABLES = @ABCD; ELSE SET @IN_CLAOUSE_VARIABLES = @AC; END IF: SELECT * FROM test_table tt WHERE FIND_IN_SET(tt.section, @IN_CLAOUSE_VARIABLES); tt.section must NOT contain commas and not need to be quoted with ". I.e. it may be 'A' (will be found in all variants), 'D' (only when <CONDITION 1> is false and <CONDITION 2> is true) or 'X' (never).
[ "stackoverflow", "0023164897.txt" ]
Q: calculate odds ratio across factors This is easy at first glance, but I didn't know how to compute it when I started to work on it. The question is to calculate the odds ratio of pass comparing female with male in each school, and the data is constructed like this: set.seed(1000) female = sample(c(0,1),size=20,replace=TRUE) school = factor(sample(c(0:2),size=20,replace=TRUE), labels=c("A school","B school","C school")) school = sort(school) pass = sample(c(0,1),size=20,replace=TRUE) data = data.frame(female,school,pass) Thank you very much! A: You can compute this using split-apply-combine, using the split function to break down your data by school, using lapply to run a function that computes the odds ratio, and using unlist to combine the results: unlist(lapply(split(data, data$school), function(x) { (sum(x$female == 1 & x$pass == 1) / sum(x$female == 1)) / (sum(x$female == 0 & x$pass == 1) / sum(x$female == 0)) })) # A school B school C school # 1.5000000 2.0000000 0.6666667 What I've computed here is actually a risk ratio, since for your dataset the odds ratios are all either infinite or 0.
[ "stackoverflow", "0035801204.txt" ]
Q: jquery get dynamic php value of hidden input type I'm trying to get the value of a hidden input set with php and use it for a jquery progressbar widget, but this code doesn't run. Could you help me? $(document).ready(function () { $("#bar").progressbar({ value: ("#profile_completed").val(); //by id }); }); A: $(document).ready(function () { $("#bar").progressbar({ value: $("#profile_completed").val(); //by id }); });
[ "tex.stackexchange", "0000081687.txt" ]
Q: hyperref generated bookmarks pointing too low I'm using the hyperref package to create a Table of Contents with internal links (bookmarks in Acrobat Reader). However, I don't like the fact that it jumps a little too low when the links are clicked. I'd rather like the links to display the relevant pages directly starting with the top of the page. In other words, I want the same behaviour as with the \bookmark command I'm also using: \usepackage{bookmark} \bookmark[page=10]{Some Page} MWE: \documentclass[oneside,a4paper,11pt,headings=normal,parskip=half,version=first]{scrreprt} \usepackage[pdftex,colorlinks=true]{hyperref} \makeindex \begin{document} \tableofcontents % ------------------------------------------------------------------------- \chapter{Introduction1}\label{chap:Intro1} \section{Abstract1} Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non roident, sunt in culpa qui officia deserunt mollit anim id est laborum. -- Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \section{Introduction1} Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla acilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \subsection{Interviews of the outgoing team members1} Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \chapter{Introduction2}\label{chap:Intro2} \section{Abstract2} Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -- Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait ulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy ibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \section{Introduction2} Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \subsection{Interviews of the outgoing team members2} Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \chapter{Introduction3}\label{chap:Intro3} \section{Abstract3} Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -- Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \section{Introduction3} Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \subsection{Interviews of the outgoing team members3} Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. \end{document} Here is a picture of the situation: A: Yes, the anchor position can be improved by moving it downwards. But I do not see the point in moving the anchor upwards showing lots of white space. For example, \@chapter can be redefined to move \refstepcounter to the position you want: \documentclass[oneside,a4paper,11pt,headings=normal,parskip=half,version=first]{scrreprt} \usepackage{etoolbox} \makeatletter \newcommand*{\chapter@refstepcounter}[1]{% \hbox{% \raisebox{\dimexpr\headsep+\headheight\relax}[0pt]{% \refstepcounter{#1}% }% }% } \patchcmd\@chapter{\refstepcounter}{% \chapter@refstepcounter }{}{} \makeatother \usepackage[pdftex,colorlinks=true]{hyperref} \makeindex \begin{document} ... \end{document}
[ "stackoverflow", "0059114860.txt" ]
Q: I am facing problem while translating spanish into english. But when i translate english into spansih it works. Here is my code I am trying to create a java application that translates spanish into english. I am facing problem while translating spanish into english. But when i translate english into spansih it works. Here is my code. Here is my code. Can you please tell me my error. This code is working right now but when i change the values of fromLang to toLang from en to es it does not work. import java.io.BufferedReader; import java.io.OutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Arrays; public class GuiApp1 { private static final String CLIENT_ID = "FREE_TRIAL_ACCOUNT"; private static final String CLIENT_SECRET = "PUBLIC_SECRET"; private static final String ENDPOINT = "http://api.whatsmate.net/v1/translation/translate"; public static void main(String[] args) throws Exception { GuiApp1 g = new GuiApp1(); JFrame f=new JFrame();//creating instance of JFrame f.setAlwaysOnTop( true ); JButton b=new JButton("Translate");//creating instance of JButton b.setBounds(90,150,100, 40);//x axis, y axis, width, height f.add(b);//adding button in JFrame JTextArea t1,t2; t1=new JTextArea(2,2); String spanish; t1.setBounds(50,100, 200,30); t2=new JTextArea(2,2); t2.setBounds(50,200, 200,30); f.add(t1); f.add(t2); f.setPreferredSize(new Dimension(200, 900)); f.setLayout(null);//using no layout managers f.setVisible(true);//making the frame visible b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ String text = t1.getText(); text = text.trim(); text = text.toLowerCase(); System.out.println(text); String fromLang = "en"; String toLang = "es"; //String text = "Cuál es su nombre"; try{ translate(fromLang, toLang, text); }catch(Exception e){ System.out.println(e); } } }); } /** * Sends out a WhatsApp message via WhatsMate WA Gateway. */ public static void translate(String fromLang, String toLang, String text) throws Exception { // TODO: Should have used a 3rd party library to make a JSON string from an object String jsonPayload = new StringBuilder() .append("{") .append("\"fromLang\":\"") .append(fromLang) .append("\",") .append("\"toLang\":\"") .append(toLang) .append("\",") .append("\"text\":\"") .append(text) .append("\"") .append("}") .toString(); URL url = new URL(ENDPOINT); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID); conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET); conn.setRequestProperty("Content-Type", "application/json"); OutputStream os = conn.getOutputStream(); os.write(jsonPayload.getBytes()); os.flush(); os.close(); int statusCode = conn.getResponseCode(); System.out.println("Status Code: " + statusCode); BufferedReader br = new BufferedReader(new InputStreamReader( (statusCode == 200) ? conn.getInputStream() : conn.getErrorStream() )); String output; while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } } A: Perhaps you've now exceeded the Free Trial usage limit of 10. In any case, the code does work. It will translate from English to Spanish OR Spanish to English. All you need to do is make sure you have a means to select which translation direction you want to go with. Currently you do not have this and are translating via a default of en to es. If you change the fromLang variable contents to "es" and the toLang variable contents to en and enter a Spanish word into the JTextArea t1 then hit the Translate button you will receive the translation into the Console Window (instead of the JTextArea, t2). The received string should be placed into JTextArea, t2. In order to place the returned string into the JTextArea t2 you will want to make the tranlate() method return a String type then in the while loop at the bottom of the method, instead of sending the returned data to console do something like this: public static String translate(String fromLang, String toLang, String text) throws Exception { // ... Most method code here ... String output; StringBuilder sb = new StringBuilder(); while ((output = br.readLine()) != null) { sb.append(output).append(System.lineSeparator()); System.out.println(output); // Optional - For testing } conn.disconnect(); return sb.toString(); } Now, where the translate() method is called, do this instead: try { String translation = translate(fromLang, toLang, text); t2.setText(translation); } catch (Exception e) { System.out.println(e); } Now the returned translation will be placed within the t2 JTextArea. I have taken the above mentioned modifications and applied them to your code provided below: import java.io.BufferedReader; import java.io.OutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.Border; public class Translator { private static final String CLIENT_ID = "FREE_TRIAL_ACCOUNT"; private static final String CLIENT_SECRET = "PUBLIC_SECRET"; private static final String ENDPOINT = "http://api.whatsmate.net/v1/translation/translate"; @SuppressWarnings("Convert2Lambda") public static void main(String[] args) throws Exception { Translator g = new Translator(); JFrame f = new JFrame();//creating instance of JFrame f.setTitle("Translator"); f.setAlwaysOnTop(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setPreferredSize(new Dimension(295, 300)); f.setLayout(null); //using no layout manager (*** BAD IDEA!! ***) String[] transDirection = {"English To Spanish", "Spanish To English"}; JComboBox<String> jc = new JComboBox<>(transDirection); jc.setSelectedIndex(0); jc.setBounds(60, 30, 160, 25); f.add(jc); JButton b = new JButton("Translate");//creating instance of JButton b.setBounds(90, 140, 100, 30);//x axis, y axis, width, height f.add(b);//adding button in JFrame Border border = BorderFactory.createLineBorder(Color.decode("#33acff")); JTextArea t1 = new JTextArea(2, 2); t1.setBounds(40, 80, 200, 50); t1.setBorder(border); t1.setLineWrap(true); t1.setWrapStyleWord(true); JScrollPane sp1 = new JScrollPane(t1); sp1.setBounds(40, 80, 200, 50); // --------------------- JTextArea t2 = new JTextArea(2, 2); t2.setBounds(40, 180, 200, 50); t2.setBorder(border); t2.setLineWrap(true); t2.setWrapStyleWord(true); JScrollPane sp2 = new JScrollPane(t2); sp2.setBounds(40, 180, 200, 50); f.add(sp1, BorderLayout.CENTER); f.add(sp2, BorderLayout.CENTER); f.pack(); f.setVisible(true);//making the frame visible f.setLocationRelativeTo(null); // Must be after setVisible(). t1.requestFocus(); // Set focus on t1 when started // Button Action Listener... b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { String text = t1.getText().trim(); //Make sure there is text to translate... if (text.equals("")) { JOptionPane.showMessageDialog(f, "There is no text supplied to translate!", "Translation Error!", JOptionPane.WARNING_MESSAGE); return; // Get out of this event. } // Get selected language translation direction... String fromLang = ""; String toLang = ""; switch (jc.getSelectedItem().toString().toLowerCase()) { case "english to spanish": fromLang = "en"; toLang = "es"; break; case "spanish to english": fromLang = "es"; toLang = "en"; break; default: fromLang = "en"; toLang = "es"; } try { String translation = translate(fromLang, toLang, text); t2.setText(translation); } catch (Exception e) { System.out.println(e); } } }); } /** * Sends out a WhatsApp message via WhatsMate WA Gateway.<br><br> * @param fromLang * @param toLang * @param text * @return * @throws java.lang.Exception */ public static String translate(String fromLang, String toLang, String text) throws Exception { // TODO: Should have used a 3rd party library to make a JSON string from an object String jsonPayload = new StringBuilder() .append("{") .append("\"fromLang\":\"") .append(fromLang) .append("\",") .append("\"toLang\":\"") .append(toLang) .append("\",") .append("\"text\":\"") .append(text) .append("\"") .append("}") .toString(); URL url = new URL(ENDPOINT); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID); conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET); conn.setRequestProperty("Content-Type", "application/json"); // 'Try With Resources' used here to auto-close stream. try (OutputStream os = conn.getOutputStream()) { os.write(jsonPayload.getBytes()); os.flush(); } int statusCode = conn.getResponseCode(); System.out.println("Status Code: " + statusCode); BufferedReader br = new BufferedReader(new InputStreamReader( (statusCode == 200) ? conn.getInputStream() : conn.getErrorStream() )); String output; StringBuilder sb = new StringBuilder(); while ((output = br.readLine()) != null) { sb.append(output).append(System.lineSeparator()); System.out.println(output); } conn.disconnect(); return sb.toString(); } } On a side note: You use no layout manager (null) in the creation of your Form by choice. This is actually a bad idea, here's why (be sure to read the comments as well).
[ "stackoverflow", "0029759416.txt" ]
Q: search and find several keys in array public function array_searchh($needle, $haystack) { foreach ($haystack as $key => $value) { $current_key = ''; $current_key .= $key; if ($needle === $value OR (is_array($value) && $this->array_searchh($needle, $value) !== false)) { return $current_key; } } return false; } When I search in array return first key, but I want to search and if there same value return all keys. [0] => Array ([id] => 1[value] => payamm) [1] => Array ([id] =>2[value]=>payam) [2] => Array ([id] => 25[value] => payam) [3] => Array ([id] => 3[value] => payam) [4] => Array ([id] => 4[value] => payam) [5] => Array ([id] => 5[value] => 340) In above array, I have several "payam" values. When I use above function, I just return the first (found) key but I want all matching keys. A: public function array_searchh($needle, $haystack) { foreach ($haystack as $key => $value) { $current_key = ''; $current_key .= $key; if ($needle === $value OR (is_array($value) && $this->array_searchh($needle, $value) !== false)) { $foundKeys[] = $current_key; } } if (isset($foundKeys)) { return $foundKeys; } return false; } This should return an array of all the found keys.
[ "stackoverflow", "0003581792.txt" ]
Q: I have created inverted index for a website but where to store that? Database for a search engine? What can be the database for a search engine? I mean after creating inverted index for a site, where one could store it so that program can create indices for other sites and save them too. Later on indexer can query them also. Because indices can range in thousands of billions. Thanksyou A: I would use Lucene. That's what it is made for. You even have your choice of many different languages.
[ "stackoverflow", "0058253767.txt" ]
Q: minikube: failed to start on mac with error E1006 I'm trying to setup k8s locally on my own mac, and after installing all the dependencies, I try to run minikube start, but get the following error message: minikube v1.4.0 on Darwin 10.14.6 Tip: Use 'minikube start -p <name>' to create a new cluster, or 'minikube delete' to delete this one. Using the running virtualbox "minikube" VM ... ⌛ Waiting for the host to be provisioned ... Preparing Kubernetes v1.16.0 on Docker 18.09.9 ... E1006 09:57:30.975647 22071 cache_images.go:79] CacheImage k8s.gcr.io/kube-apiserver:v1.16.0 -> /Users/chrisbao/.minikube/cache/images/k8s.gcr.io/kube-apiserver_v1.16.0 failed: fetching image: Get https://k8s.gcr.io/v2/: dial tcp [2404:6800:4008:c04::52]:443: i/o timeout E1006 09:57:30.976341 22071 cache_images.go:79] CacheImage gcr.io/k8s-minikube/storage-provisioner:v1.8.1 -> /Users/chrisbao/.minikube/cache/images/gcr.io/k8s-minikube/storage-provisioner_v1.8.1 failed: fetching image: Get https://gcr.io/v2/: dial tcp [2404:6800:4008:c00::52]:443: i/o timeout and minikube status command returns the following status info: host: Running kubelet: apiserver: Stopped kubectl: Correctly Configured: pointing to minikube-vm at 192.168.99.100 so how to debug and fix it? what's the potential reason? A: E1006 09:57:30.975647 22071 cache_images.go:79] CacheImage k8s.gcr.io/kube-apiserver:v1.16.0 -> /Users/chrisbao/.minikube/cache/images/k8s.gcr.io/kube-apiserver_v1.16.0 failed: fetching image: Get https://k8s.gcr.io/v2/: dial tcp [2404:6800:4008:c04::52]:443: i/o timeout Looks like you aren't able to pull the k8s api server image from GCR. You can try use one of the available image mirrors by using the --image-repository or --image-mirror-country flags. E.g., if you are based in China, you can start minikube with: minikube start --image-mirror-country=cn
[ "stackoverflow", "0017333837.txt" ]
Q: How to iterate over a map created in MVEL I have created a map in MVEL and I have to iterate over it using foreach. How would I do that? There is a similar question: How to iterate over a map in mvel But in that case the map was created in Java and had a method to return array of keys (entrySet) which is not the case with me. //MVEL map = [ 'a': 'a1', 'b': 'b2', 'c': 'c3' ]; foreach (key: map) { System.out.println(key); } I have tried both map and map.entrySet in the foreach loop but none seems to work. Note: I test it using MVEL command line and using MVEL version 2.2.0.15 A: Although you have accepted an answer, I think it is better to add something as not to mislead other people: ... had a method to return array of keys (entrySet) which is not the case with me First, Map is a Map. Map created in MVEL is simply a "Java" Map. The way to iterate is just the same and they are providing same methods Second, entrySet() is not returning "array of keys". It is returning a Set of Entry (as its name suggests). I am not sure why you cannot use entrySet as it works just fine for me. I suspect you have do foreach (e : map.entrySet). That will not work, because in MVEL, property navigation can mean several thing, like bean properties (which means it will call map.getEntrySet()), or looking up a map (which means it will call map.get('entrySet')), or getting the field (which means 'map.entrySet'). However all these are not valid for your case. You simply want to invoke map.entrySet() method so that you should just do foreach (e : map.entrySet()) The proper way to do is something like this: map = ['a':'a1', 'b':'b1'] ; foreach(entry : map.entrySet()) { System.out.println('key ' + entry.key + ' value ' + entry.value) };
[ "stackoverflow", "0012765231.txt" ]
Q: How do I set the src address dynamically? I am trying to grab information from the page url to set the src for a data file. So, say page url is: page.html?x=data_file_3 (The ideas is I could change the url to access other data files: data_file_4, etc.) I grab the "data_file_3" part of the url and put it in a variable: (the code I use for this works fine -- so result is) folder = "/data_file_3/content.js" -- the content of this file is just an array Then I try this: <script id="url" type="text/javascript"></script> <script language="javascript"> ... var u = document.getElementById('url'); u.src = folder; ... </script> But this doesn't work (the array data does not show up on the page). I put this code right where I used to hard code: <script type="text/javascript" src="/data_file_3/content.js"></script> The hard-coded version works. Any ideas about how I can do this? A: Sounds like you are trying to create script tags dynamically. var scr = document.createElement('script'); scr.src = 'script_path'; document.getElementsByTagName('head')[0].appendChild(scr); You can wrap this in a function where 'script_path' is whatever you're path you're passing in. Note also that 'text/javascript' is not required. All browsers understand that its javascript.
[ "english.stackexchange", "0000224414.txt" ]
Q: Is "fatah" an alternative spelling of "fatwa"? I've occasionally seen "fatah" being used instead of "fatwa" to mean Islamic religious ruling. For example, from Fear and Loathing of Sharks in Western Australia by Paul Watson (in an article which elsewhere complained about halal slaughter): This week, this same premier of Western Australia issued a shark-hating Fatah, calling for their total annihilation. You can find more examples by googling for "issued a fatah" or "a fatah against". When I looked up "fatah" in onelook.com, all the entries referred to the Palestinian militant organisation Fatah. Is "fatah" a valid alternative transliteration of the Arabic word typically transliterated as "fatwa", or is it a mistaken use of the wrong word? A: your hunch is right sir: "Fatah" is a mistaken use of the wrong word.Fatwa is the word for Islamic religious ruling.For more explanation please see: http://www.islamicsupremecouncil.org/understanding-islam/legal-rulings/44-what-is-a-fatwa.html
[ "stackoverflow", "0001167254.txt" ]
Q: Getting a name error when seeding a database in ruby on rails. How do I include app context? I have a seed script called load.rb in the db directory of an application. I just got this app from a client so not sure how to run this script. I get a name error on all of the Model.create(...) statements. I guess this is because the Rails environment is not loaded. There is no indication that this load script was run via a rake task because I see no custom rake tasks in the app. Is this a "Rails thing"? ...in other words, is there a command I am not aware of that will load the app context and execute load.rb in the db directory? If not, how can load the app context in the file so that I can simply type "ruby load.rb" to load the database? The file is literally just a bunch of create statements: Quiz.create(:name=> "1") Quiz.create(:name=> "2") Quiz.create(:name=> "3") Quiz.create(:name=> "4") thanks A: It looks like it's probably just being run from the console. For development, you'd simply start with ./script/console from your Rails root directory. Then inside your console, load the script. >> load "db/load.rb"
[ "stackoverflow", "0052087421.txt" ]
Q: Module build failed (from ./node_modules/babel-loader/lib/index.js): TypeError: Cannot read property 'bindings' of null I've got an error while building a project: Module build failed (from ./node_modules/babel-loader/lib/index.js): TypeError: Cannot read property 'bindings' of null My development environment is as follows: Node: 8.0.0 npm: 5.0.0 devDependencies "devDependencies": { "babel-core": "^6.26.3", "babel-loader": "^8.0.0", "babel-preset-env": "^1.7.0", "webpack": "^4.17.1", "webpack-dev-server": "^3.1.7" } A: [email protected] uses Babel 7.x, which is @babel/core@^7.0.0, and more importantly in your case @babel/preset-env@7 replaces babel-preset-env@^1.7.0. You'll need to make sure to do npm install @babel/core @babel/preset-env and update your Babel config to use @babel/preset-env instead of babel-preset-env with something like "presets": [ "@babel/preset-env" ] Note: For others coming across this, the issue may also be that you're using plugins/preset from Babel 6 on Babel 7. This may be hard to notice if you're using a third-party Babel preset since the versions of the presets may not match the version of Babel itself. A: The error can show with this message too: ERROR in ./resources/js/app.js Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Cannot find module './src/data' I'm fixed it, with: package.json "devDependencies": { "@babel/core": "^7.7.4", "@babel/preset-env": "^7.7.4", or using: npm install -D babel-loader @babel/core @babel/preset-env Obs.: I didn't need to create a .babelrc file, to configure preset.
[ "stackoverflow", "0014860648.txt" ]
Q: bind: Address family not supported by protocol This code works on my other vps, but with linode it doesn't. #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <netdb.h> #include <time.h> #include <string.h> #ifdef STRERROR extern char *sys_errlist[]; extern int sys_nerr; char *undef = "Undefined error"; char *strerror(error) int error; { if (error > sys_nerr) return undef; return sys_errlist[error]; } #endif #define CIAO_PS "bfi_2" main(argc, argv) int argc; char **argv; { int lsock, csock, osock; FILE *cfile; char buf[4096]; struct sockaddr_in laddr, caddr, oaddr; int caddrlen = sizeof(caddr); fd_set fdsr, fdse; struct hostent *h; struct servent *s; int nbyt; unsigned long a; unsigned short oport; int i, j, argvlen; char *bfiargv[argc+1]; char *fintops = CIAO_PS ; if( argc < 4 ) { fprintf(stderr,"Usage: %s localport remoteport remotehost fakeps\n",argv[0]); return 30; } for( i = 0; i < argc; i++ ) { bfiargv[i] = malloc(strlen(argv[i]) + 1); strncpy(bfiargv[i], argv[i], strlen(argv[i]) + 1); } bfiargv[argc] = NULL; argvlen = strlen(argv[0]); if( argvlen < strlen(CIAO_PS) ) { printf("Se vuoi fregare davvero ps vedi di lanciarmi almeno come superFunkyDataPipe !\n") ; abort(); } if(bfiargv[4]) fintops=bfiargv[4] ; strncpy(argv[0], fintops, strlen(fintops)); for( i = strlen(fintops); i < argvlen; i++ ) argv[0][i] = '\0'; for( i = 1; i < argc; i++ ) { argvlen = strlen(argv[i]); for(j=0; j <= argvlen; j++) argv[i][j] = '\0'; } a = inet_addr(argv[3]); if( !(h = gethostbyname(bfiargv[3])) && !(h = gethostbyaddr(&a, 4, AF_INET)) ) { perror(bfiargv[3]); return 25; } oport = atol(bfiargv[2]); laddr.sin_port = htons((unsigned short)(atol(bfiargv[1]))); if( (lsock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1 ) { perror("socket"); return 20; } laddr.sin_family = htons(AF_INET); // laddr.sin_addr.s_addr = htonl(0); laddr.sin_addr.s_addr = inet_addr("ip address here"); if( bind(lsock, &laddr, sizeof(laddr)) ) { perror("bind"); return 20; } if( listen(lsock, 1) ) { perror("listen"); return 20; } if( (nbyt = fork()) == -1 ) { perror("fork"); return 20; } if (nbyt > 0) return 0; setsid(); while( (csock = accept(lsock, &caddr, &caddrlen)) != -1 ) { cfile = fdopen(csock,"r+"); if( (nbyt = fork()) == -1 ) { fprintf(cfile, "500 fork: %s\n", strerror(errno)); shutdown(csock,2); fclose(cfile); continue; } if (nbyt == 0) goto gotsock; fclose(cfile); while (waitpid(-1, NULL, WNOHANG) > 0); } return 20; gotsock: if( (osock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1 ) { fprintf(cfile, "500 socket: %s\n", strerror(errno)); goto quit1; } oaddr.sin_family = h->h_addrtype; oaddr.sin_port = htons(oport); memcpy(&oaddr.sin_addr, h->h_addr, h->h_length); if( connect(osock, &oaddr, sizeof(oaddr)) ) { fprintf(cfile, "500 connect: %s\n", strerror(errno)); goto quit1; } while( 1 ) { FD_ZERO(&fdsr); FD_ZERO(&fdse); FD_SET(csock,&fdsr); FD_SET(csock,&fdse); FD_SET(osock,&fdsr); FD_SET(osock,&fdse); if( select(20, &fdsr, NULL, &fdse, NULL) == -1 ) { fprintf(cfile, "500 select: %s\n", strerror(errno)); goto quit2; } if( FD_ISSET(csock,&fdsr) || FD_ISSET(csock,&fdse) ) { if ((nbyt = read(csock,buf,4096)) <= 0) goto quit2; if ((write(osock,buf,nbyt)) <= 0) goto quit2; } else if( FD_ISSET(osock,&fdsr) || FD_ISSET(osock,&fdse) ) { if ((nbyt = read(osock,buf,4096)) <= 0) goto quit2; if ((write(csock,buf,nbyt)) <= 0) goto quit2; } } quit2: shutdown(osock,2); close(osock); quit1: fflush(cfile); shutdown(csock,2); quit0: fclose(cfile); return 0; } A: Use AF_INET instead of htons(AF_INET) to initialize sin_family.
[ "stackoverflow", "0036645771.txt" ]
Q: nginx reverse proxy stripe domain I trying to stripe part of a domain to pass it in reverse proxy server { server_name *.dr.domain.com; listen X.X.X.; set $headerDR $host; location / { proxy_set_header Accept-Encoding ""; proxy_set_header Host "DOMAIN WITHOUT .dr.domain.com"; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://x.x.x.x; sub_filter "DOMAIN WITHOUT .dr.domain.com" "$headerDR"; sub_filter_once off; } How can do this please ? A: If you use the regular expression version of the server_name directive, you can use a named capture to extract the part of the domain you need. For example: server_name ~^(?<subdomain>.*)\.dr\.domain\.com$; proxy_set_header Host $subdomain; See this document for details.
[ "stackoverflow", "0022271231.txt" ]
Q: Response.Redirect(Request.Url.AbsoluteUri) and MultiView1.SetActiveView I have a submit form. when user click save button it should set active view of multiview1 to view2. I added Response.Redirect(Request.Url.AbsoluteUri); to prohibit users from pressing F5 button and submitting the form again and again, but it causes to multiview1 not set active view to view2 and after submiting the form still shows view1 protected void btnSubmitAd_Click(object sender, EventArgs e) { if (Page.IsValid) { Ads ad = new Ads { Title = txtAdTitle.Text, Dec = txtAdText.Text, Name = txtName.Text, Email = txtEmail.Text }; context.Ads.Add(ad); context.SaveChanges(); MultiView1.SetActiveView(View2); Response.Redirect(Request.Url.AbsoluteUri); } } and this is my pageload event: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { MultiView1.SetActiveView(View1); } } A: The below code will always set the view to View1. if (!Page.IsPostBack) { MultiView1.SetActiveView(View1); } If you want to set the ActiveView to a specific view after the redirect then you have set your view information somewhere. like Session or QueryString Query string code will be like: protected void btnSubmitAd_Click(object sender, EventArgs e) { if (Page.IsValid) { Ads ad = new Ads { Title = txtAdTitle.Text, Dec = txtAdText.Text, Name = txtName.Text, Email = txtEmail.Text }; context.Ads.Add(ad); context.SaveChanges(); //MultiView1.SetActiveView(View2); No need for that as it will be lost after redirect... //Append your ActiveView information in query string with Request.Url.AbsoluteUri Response.Redirect(Request.Url.AbsoluteUri + "?activeView=View2");// } } And on PageLoad protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string activeView = Request.QueryString["activeView"] if(!string.IsNullOrEmpty(activeView) && activeView == "View2") MultiView1.SetActiveView(View2); else MultiView1.SetActiveView(View1); } }
[ "stats.stackexchange", "0000020825.txt" ]
Q: Sidak or Bonferroni? I am using a generalized linear model in SPSS to look at the differences in average number of caterpillars (non-normal, using Tweedie distribution) on 16 different species of plants. I want to run multiple comparisons but I'm not sure if I should use a Sidak or Bonferroni correction test. What is the difference between the two tests? Is one better than the other? A: If you run $k$ independent statistical tests using $\alpha$ as your significance level, and the null obtains in every case, whether or not you will find 'significance' is simply a draw from a random variable. Specifically, it is taken from a binomial distribution with $p=\alpha$ and $n=k$. For example, if you plan to run 3 tests using $\alpha=.05$, and (unbeknownst to you) there is actually no difference in each case, then there is a 5% chance of finding a significant result in each test. In this way, the type I error rate is held to $\alpha$ for the tests individually, but across the set of 3 tests the long-run type I error rate will be higher. If you believe that it is meaningful to group / think of these 3 tests together, then you may want to hold the type I error rate at $\alpha$ for the set as a whole, rather than just individually. How should you go about this? There are two approaches that center on shifting from the original $\alpha$ (i.e., $\alpha_o$) to a new value (i.e., $\alpha_{\rm new}$): Bonferroni: adjust the $\alpha$ used to assess 'significance' such that $$\alpha_{\rm new}=\frac{\alpha_{o}}{k}\qquad\qquad\quad$$ Dunn-Sidak: adjust $\alpha$ using $$\alpha_{\rm new}=1-(1-\alpha_{o})^{1/k}$$ (Note that the Dunn-Sidak assumes all the tests within the set are independent of each other and could yield familywise type I error inflation if that assumption does not hold.) It is important to note that when conducting tests, there are two kinds of errors that you want to avoid, type I (i.e., saying there is a difference when there isn't one) and type II (i.e., saying there isn't a difference when there actually is). Typically, when people discuss this topic, they only discuss—and seem to only be aware of / concerned with—type I errors. In addition, people often neglect to mention that the calculated error rate will only hold if all nulls are true. It is trivially obvious that you cannot make a type I error if the null hypothesis is false, but it is important to hold that fact explicitly in mind when discussing this issue. I bring this up because there are implications of these facts that appear to often go unconsidered. First, if $k>1$, the Dunn-Sidak approach will offer higher power (although the difference can be quite tiny with small $k$) and so should always be preferred (when applicable). Second, a 'step-down' approach should be used. That is, test the biggest effect first; if you are convinced that the null does not obtain in that case, then the maximum possible number of type I errors is $k-1$, so the next test should be adjusted accordingly, and so on. (This often makes people uncomfortable and looks like fishing, but it is not fishing, as the tests are independent, and you intended to conduct them before you ever saw the data. This is just a way of adjusting $\alpha$ optimally.) The above holds no matter how you you value type I relative to type II errors. However, a-priori there is no reason to believe that type I errors are worse than type II (despite the fact that everyone seems to assume so). Instead, this is a decision that must be made by the researcher, and must be specific to that situation. Personally, if I am running theoretically-suggested, a-priori, orthogonal contrasts, I don't usually adjust $\alpha$. (And to state this again, because it's important, all of the above assumes that the tests are independent. If the contrasts are not independent, such as when several treatments are each being compared to the same control, a different approach than $\alpha$ adjustment, such as Dunnett's test, should be used.) A: Denote with $\alpha^*$ the corrected significance level, then Bonferroni works like this: Divide the significance level $\alpha$ by the number $n$ of tests, i.e. $\alpha^*=\alpha/n$. Sidak works like this (if the test are independent): $\alpha^*=1 − (1 − \alpha)^{1/n}$. Because $\alpha/n < 1 − (1 − \alpha)^{1/n}$, the Sidak correction is a bit more powerful (i.e. you get significant results more easily) but Bonferroni is a bit simpler to handle. If you need an even more powerful procedure you might want to use the Bonferroni-Holm procedure. A: The Sidak correction assumes the individual tests are statistically independent. The Bonferroni correction doesn't assume this.
[ "stackoverflow", "0023793690.txt" ]
Q: keyup event not triggered for escape key I have a text input field referred to as $nameEditor. I want to show this text field when a button is pressed, and hide it on blur or when the escape key is pressed. Hiding the field on blur works every time. Hiding the field when pressing the escape key works only the first time. Example sequence of events. 1) Press the button that shows the text input field. 2) Press escape - text input field hides 3) Press the button that shows the text input field again. 4) Press escape - the keyup event is not triggered 5) Press any other key and the keyup event is triggered 6) Press escape - the text input field hides Relevent markup: <button id="renameButton" title="Rename" data-icon="ui-icon-pencil">Rename</button> <span id="assemblyNameView">Assembly Name</span> <input id="assemblyNameEditor" style="display:none" class="ui-corner-all widget"> Relevant script: var $renameButton = $("#renameButton"); var $nameViewer = $('#assemblyNameView'); var $nameEditor = $('#assemblyNameEditor'); function cancelEdit() { $nameEditor.hide(); $nameViewer.show(); } function initEdit() { $nameViewer.hide(); $nameEditor.val($nameViewer.text()).show().select(); } function commitEdit(newName) { // TODO: Update the structure being edited. $nameEditor.hide(); $nameViewer.text(newName); $nameViewer.show(); } $renameButton.click(initEdit); $nameEditor.blur(cancelEdit); $nameEditor.keyup(function(e) { console.log(e); if (e.keyCode === 13) { var newName = val(); if (newName === '') { alert("No name specified."); $nameEditor.val($nameViewer.text()).select(); e.preventDefault(); return false; } commitEdit(newName); } else if (e.keyCode === 27) { cancelEdit(); } }); Why is the escape key not triggering the keyup event after the input box has been hidden then re-shown? A: It's hard to explain what's wrong here. There is a strange effect when both the button and the textbox receive focus? It's impossible in a standard UI interface. In fact when you type keys other than ESC, Enter, Space and maybe more ... the typed characters are shown OK in the textbox and only the textbox receives focus after that. However if you type ESC, Enter, Space... the keystrokes seem to affect on the button and I can even see there is some color effect on the button showing that it's currently focused. This looks like a bug indeed. However to solve this, I tried using focus() explicitly appended after .select() and it works OK. function initEdit() { $nameViewer.hide(); $nameEditor.val($nameViewer.text()).show().select().focus(); } Demo.
[ "stackoverflow", "0005741192.txt" ]
Q: php and chmod does not work Hi I want to write a file by using php, but first I should set permissions. When I try chmod($file,0777); it doesn't work and returns false. What should I do for enable chmod function? A: Hey you can do one thing.....go to console and see the file writes and its user using ll command... if user is not a apache user then its will gives you error even if you are syntactically right..so change the group and owner of file to apache using chgrp and chrown command and then run the code...you can see the output........
[ "es.stackoverflow", "0000241900.txt" ]
Q: source.on is not a function en Node.JS? Estoy tratando de hacer lo siguiente en Node.JS: var file= './elemento1.pdf'; var formData = { 'file': { data: fs.createReadStream(file), filename: 'elemento1', contentType: 'application/pdf' } }; compareAndComply.classifyElements(formData, function(error, response){ if (error) { console.log(error); } else { console.log(JSON.stringify(response, null, 2)); } }); Pero me manda el siguiente error: source.on is not a function ¿Como puedo arreglarlo? Muchas gracias A: Prueba con lo siguiente: var formData = { name: 'file1', file: { value: fs.createReadStream('C:/kristian/Devbeasts-small.png'), options: { filename: 'elemento1.pdf', contentType: 'application/pdf' } } }; Info en el siguiente Link
[ "askubuntu", "0000949645.txt" ]
Q: How do I use the exec command inside a for loop after a find command? I've been trying to get this working for a while now. I want to search for a list of files and then copy them all to a certain path. If I run the command separately, then it works like so: find <path> -name 'file1' -exec cp '{}' <path2> \; But I've been unable to run it inside a for loop. #this works for f in file1 file2 file3...; do find <path> -name "$f" \; done; #none of these work (this code tries to find and copy the files named file and list from the path) for f in file1 file2 file3...; do find <path> -name "$f" -exec cp '{}' <path2> \; done; for f in file1 file2 file3...; do find <path> -name "$f" -exec cp {} <path2> \; done; I've tried a few other stuff that weren't likely to work. The first line in the code quote just gets stuck and the others don't copy anything even though they don't get stuck. I haven't been able to run anything with exec inside a for loop after a search and at this point I'm not sure what to do. I have solved the immediate problem by searching the files and logging the results to another file and then running a copy inside a for loop separately but I'd still like to know how to do this. A: Two issues: for f in some_file does not iterate over the content of some_file, just iterate over or take the literal string some_file. To get over this forget about for looping for iterating over file content, use a properly implemented while construct. Variables won't be expanded when put inside single quotes, '$f' in this case. To get your original idea working, use double quotes. Putting these together, assuming the filenames are newline separated inside file_list file: while IFS= read -r f; do find /path1 -name "$f" -exec cp '{}' /path2 \; done <file_list Or if you know the files would be in the /path1 directory, not under any subdirectory of it, you can just use an array to get the filenames, and use (GNU) cp directly, again assuming newline separated filenames inside file_list: ( IFS=$'\n' files=( $(<file_list) ) cp -t /path2 "${files[@]}" ) In case of huge number of files, you would be better off iterating over and cp individually rather than dumping into an array: while IFS= read -r f; do cp -- "$f" /path2; done <file_list If you have file list like e.g. file1 file2 file3 ... directly in the for construct, then just using double quotes would do: for f in file1 file2 file3; do find /path1 -name "$f" -exec cp '{}' /path2 \; done Now, you can use cp directly here too if all files would not be in any subdirectory: cp -t /path2 file1 file2 file3 Or you can give static absolute or relative paths in case you want to use cp only to deal with any files under any subdirectory. A: You clarified that your file list is not a text file, but a series of filenames you want to find with find. You mentioned that this works for you: for f in file1 file2 file3 ... ; do find <path> -name "$f" \; done; presumably you mean you get the expected list of files from that command. You then say this does not work: for f in file1 file2 file3 ... ; do find <path> -name "$f" -exec cp '{}' <path2> \; done presumably you mean the files listed before aren't copied to <path2>. I'm not sure what error you're getting, but as it's written, I'd expect that command to hang like this: $for f in file1 file2 file3 ... ; do find <path> -name "$f" -exec cp '{}' <path2> \; done > waiting for the missing ;. Assuming you corrected that problem, I can't think of any other obvious reason why your command would definitely fail. You should be able to manage with for f in file1 file2 file3 ... ; do find <path> -name "$f" -exec cp '{}' <path2> \; ; done However I suggest using the -t flag to specify the directory. I have to thank David Foerster for this comment which I think shows the best form for a cp or mv invocation using find. It will refuse to overwrite duplicate files too. for f in file1 file2 file3; do find /path/to/search -name "$f" -exec cp -vt /path/to/destination -- {} + ; done Notes -v be verbose - tell us what is being done -t use the specified directory as destination -- don't accept any further options + if there are multiple matches (in your case this is unlikely since for will run once for each item in the file list, but there may be multiple matching files for each name), then construct an argument list for cp instead of running cp multiple times ; separates commands in the shell. The form of a for loop is for var in things; do command "$var"; done If it doesn't see the ; before done, bash will wait for ; or an interrupt signal. A: While the other answers are correct I want to offer a different approach that doesn't require multiple invocations of find to scan the same directory structure repeatedly. The basic idea is to use find to generate a list of files that match the common criteria, apply a custom filter to that list, and perform some action, e. g. cp, on the entries of the filtered list. Implementation 1 (requires Bash to read null-byte-delimited records) find /some/path -type f -print0 | while read -rd '' f; do case "${f##*/}" in file1|file2|file3) printf '%s\0' "$f";; esac done | xargs -r0 -- cp -vt /some/other/path -- Each pipe corresponds to the beginning of the next step of the three steps described above. The case statement has the advantage of allowing globbing matches. Alternatively you could use Bash's conditional expressions: if [[ "${f##*/}" == file1 || "${f##*/}" == file2 || "${f##*/}" == file3 ]]; then printf '%s\0' "$f" fi Implementation 2 If the list of file names to match is a bit longer and cannot be replaced with a small set of globbing patterns, or if the list of file names to match is not known at the time of writing, you can resort to an array that holds the list of file names of interest: FILE_NAMES=( "file1" "file2" "file3" ... ) find /some/path -type f -print0 | while read -rd '' f; do for needle in "${FILE_NAMES[@]}"; do if [ "${f##*/}" = "$needle" ]; then printf '%s\0' "$f" fi done done | xargs -r0 -- cp -vt /some/other/path -- Implementation 3 As a variation we can use an associative array which hopefully has faster look-up times than plain "list" arrays: declare -A FILE_NAMES=( ["file1"]= ["file2"]= ["file3"]= ... ) # Note the superscripts with []= find /some/path -type f -print0 | while read -rd '' f; do if [ -v FILE_NAMES["${f##*/}"] ]; then printf '%s\0' "$f" fi done | xargs -r0 -- cp -vt /some/other/path --
[ "stackoverflow", "0013783846.txt" ]
Q: edit supporting files location for compiler in Xcode I renamed the folder in which my Xcode project's supporting files are stored, and now I am unable to compile my project. I was able to edit the build settings to reflect the new folder name, but the build phases tab shows that my compiler is still using the old folder name, and I don't see any option for editing the compile sources. I even tried deleting the compile sources and re-adding them, but they still show the old folder name. A: First, in Xcode, delete the problem files. But (important!) when asked, click "just delete" or whatever, not the option that also says "remove the files from the disk". Next, RMB on the folder where you want your classes to occur and click "Add existing files" or whatever. Navigate to where the files actually are and select them, then click "add" or whatever. (Be wary of instinctively double-clicking while navigating through the directories, as that will add the entire directory. If you do this, simply delete the added directory from your project and do the RMB again.) You shouldn't need to do anything else with build settings or whatever (other than to maybe undo some of your prior changes).
[ "rpg.stackexchange", "0000092112.txt" ]
Q: Playing InSpectres with very small groups How small of a group can effectively play InSpectres and still get into the mode of the game, especially if the participants aren't familiar with the system yet? I'm particularly concerned about how confessionals work if there's only two players, but I also suspect that franchise dice as a progression-of-plot mechanic may break down with smaller numbers of players. Is there a hard limit on how small of a group can effectively play InSpectres without being familiar with the system already? Are there strategies, techniques, or simple hacks that can make it work better in these circumstances? A: I've successfully run InSpectres for two before, but that was as more of a demo than a running campaign. An established franchise which needs 20 or 30 dice worth of successes for its average mission might be a little tough for two characters to pull off on their own. Here are some things to consider. Multiple confessionals. Sure, why not? Give them an extra one apiece. Inspectres is a reality TV show game, and in a reality show with a smaller cast, each member can have multiple aside spots per episode. That just makes sense. "And their dog!" If you have two players, they should both be playing normal agents. Weird agents can succeed on skill rolls and help other agents out, but their successes never rack up Franchise Dice for the mission. However, this also means that if you have two players, they can create and share custody of a Weird agent without getting any additional benefit toward racking up Franchise Dice for the mission. Troupe play. At some point, somebody's going to need to recover for long enough that they'll be out of action for a while. At this point, or even before, it's fine to just create a "new character" and keep on going, and pick who you're going to play at the start of the session or maybe when the call comes in. The only mechanical difference between "new characters" and veterans is their Cool score, which is fairly volatile anyway.
[ "stackoverflow", "0009916782.txt" ]
Q: Simple C++ web server with php support im working on a simple C++ HTTP server as a school project and I would like to add php support for it. Post and Get methods should not be a problem, but Im stuck on a cookies. I googled for long and couldnt find, how php handles cookies, where it gives the output for http server such as Apache or how does it work in global. Any ideas how I could print this code: <?php setcookie("cookie[three]","cookiethree"); ?> to console so it can be read by my server and after some parsing(?) sent to a client? Thanks guys EDIT: This is really close example to what I need, but when I execute the script it shows empty array.. http://php.net/manual/en/function.headers-list.php php version: PHP 5.3.6-13ubuntu3.2 with Suhosin-Patch (cli) (built: Oct 13 2011 23:09:42) Copyright (c) 1997-2011 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies A: PHP get its superglobals variables (such as Cookies) from the HTTP server itself. When you parse a client request, you must store every key/value pair in an appropriate container (an HTTPRequest class perhaps). When interfacing your server with PHP you should write a module like apache does (mod_php). To do this, you will have to write your own API for interfacing with the modules. This means for every module you'll have (php, python ...) you will have the same interface for your Inputs/Outputs. When writing such an API, you should define an easy way to pass all the superglobals variables PHP needs from the server. I've written my own HTTP server for the same purpose and the documentation of PHP is a little tricky about this point but you can inspire yourself from PHP-CGI : there is a php.exe or simply php command on Linux/Windows which can take arguments such as variables if my memory is good. Anyway, there are several ways to pass these arguments to php and I used CGI for my server. Hope that'll help you.
[ "stackoverflow", "0021447820.txt" ]
Q: Facebook photos posted through API don't show on page public timeline I thought I'd succeeded in posting photos to my page's timeline with the following VB.NET code: Dim params As Object = New With { .message = Message, .file = New Facebook.FacebookMediaObject() With { .ContentType = "image/jpeg", .FileName = Guid.NewGuid.ToString() & ".jpg" }.SetValue(photoBytes) } ' This is the 'timeline' album for the page. get it at graph explorer at /page-id/albums Dim result = fbClient.Post("/711668238866774/photos", params) If I view the page as the page admin, I can see the photos in the timeline. However, if I view the page publicly, the photos are not visible. If I post a photo to my page using the Facebook UI, it can be seen publicly. If I use the graph explorer to examine '711668238866774/photos', and compare photos posted with the API vs. photos post with the Facebook UI, I can see no difference that would cause one to show publicly and the other to be hidden. Do I need to do anything else to make this work? A: By far the most likely reason that content posted by your app won't be visible to users who aren't admins of the app if is you've forgotten to make the app public - content posted by an app can only be seen by people who can see the app. Go to the Status & Review tab of the app settings and check the value of the toggle at the top You won't be able to make it live without a privacy policy URL and contact email address being in the app details, but otherwise you can just mark it as public
[ "stackoverflow", "0051276024.txt" ]
Q: Multiindex groupby python I have a Multiindex dataframe like this after groupby and sort value descending usage peak = df.groupby(["month_year"]).apply(lambda x: x.sort_values(["Usage"], ascending = False) DateTime Usage month_year 2012-01 2055 2012-01-22 10:00:00 55 351 2012-01-04 16:00:00 52 ..... 2012-12 34545 2012-12-25 20:30:00 22 34505 2012-12-25 10:30:00 21 How can I only keep just the index of first row of each month_year? In other word, I only want to keep '2055' and '34545'? A: One way to do this is to use reset_index and groupby: df1.reset_index(level=1).groupby('month_year').first() Output: level_1 DateTime Usage month_year 2012-01 2055 2012-01-22 10:00:00 55 2012-12 34545 2012-12-25 20:30:00 22