INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Can't assign text value to a variable from JQuery element in event handler This is some event handling for a list of items in my dom. Using event delegation, the click handler is on the parent container $( "#list" ).on( "click", "a", (event) => { event.preventDefault(); event.stopImmediatePropagation(); let text = $(this).parent().children().last().text(); // The following HAS content (seen in the dev tools debugger !!!!) // $(this).parent().children().last().text() // But the text variable gets No content - WHY ? // "" is printed.... console.log(text); }); Any ideas? Any help is appreciated.
Because you use arrow function and `this` in arrow function is `window` in browser. $( "#list" ).on( "click", "a", function (event) { event.preventDefault(); event.stopImmediatePropagation(); let text = $(this).parent().children().last().text(); debugger console.log(text); });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "javascript, jquery, dom, onclick, jquery events" }
AngularJS use constant in directive I have defined a constant like this: app.constant('ngSettings', { apiBaseUrl: ' }); how can I reference now this constant in a directive? Where the directive is something like this: angular.module('my.directive', []).directive(...................
You can inject the constant anywhere that is injectable including the directive definition itself, the controller of a directive, the link function, et. al. angular.module('my.directive', []).directive('name', ['ngSettings', function (ngSettings) { // do things with ngSettings return {}; }]); By the way I wouldn't name anything you define yourself as `ng` \-- that should be preserved for things in the `ng` module or that Angular itself created.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 4, "tags": "angularjs, angularjs directive" }
Prolog Find All Predicate I am trying to find all the brothers of a person.. I have created the following rule.. find_all_brothers(Z):- findall(X,brother(X,Z),X0),write(X0). This works however, if a person has more then one brother then it will only find a single brother.. I'm assuming I have to use recursion somehow but I'm a little stuck!
If you have relationships such as: brother(sam, bill). brother(bill, fred). And you want to find all of bill's brothers, you'll need to do a little more: find_all_brothers(Z) :- findall(X, (brother(X, Z) ; brother(Z, X)), X0), write(X0). To avoid any redundant members of the list, `setof` will sort and provide only unique members: find_all_brothers(Z) :- setof(X, (brother(X, Z) ; brother(Z, X)), X0), write(X0).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "recursion, prolog, artificial intelligence, prolog setof" }
Mutually excluding properties in swagger How do I indicate that in my_object you can have property_1 or property_2, but not both? my_object: type: object properties: property_1: type: string property_2: type: string
You may want to switch to OpenAPI 3.0, which supports oneOf keyword to define mutually exclusive conditions: here is an example : my_object: type: object properties: property_1: type: string property_2: type: integer oneOf: - required: [property_1] - required: [property_2]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "swagger, openapi" }
Executing bash script from C++ and read its output ubuntu sdk I have a ubuntu application and I'm trying to execute bash scripts from it but it doesn't seem to be working. I tried doing this with system() #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]) { // tried both system("./script.sh"); // system ("script.sh") } Also, i've tried researching this but did not find a solution; is it possible to also read the output and display in textbox.
Use `popen()`. FILE *script; char line[LINESIZE]; script = popen("./script.sh", "r"); while (fgets(line, sizeof(line), script)) { ... } pclose(script); It's not relevant that you're running a script. This will work with any shell command.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c++, linux, bash, ubuntu, qml" }
Costa Rican empanada-like food? So I went to Costa Rica and tried a a savoury pastry that is similar to empanadas but it is not empanadas. The pastry had a yellowy-orange colour, the shape of it was rectangular and it was stuffed with some sort of flavourful meat. I really want to know what the name of this food is.
What you describe sounds like a **Jamaican Patty.** From Explore Costa Rica.com : > A Jamaican patty or pattie is a pastry that contains various fillings and spices baked inside a flaky shell. Technically, it is a beef filled turnover. As its name suggests, it is commonly found in Jamaica, and is also eaten in other areas of Costa Rica, especially on the Caribbean coast. It is traditionally filled with ground beef, however, fillings now include chicken, vegetables, shrimp, lobster, soy and cheese. ![enter image description here]( ![enter image description here]( ![enter image description here]( They are quite tasty!
stackexchange-cooking
{ "answer_score": 3, "question_score": 2, "tags": "pastry" }
Import issue with MySQL Workbench I am trying to import a .csv (or .txt it doesn't matter) with MySQL Workbench and I am actually using the following command : LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv' INTO TABLE test.dummy FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'; My .csv file is placed in the mysql/data folder of the server where my database is placed (on localhost). MySQL Workbench tells me "Query interrupted". I previously tried to put the full path but the query was running successfully without results. My database was still empty... Thanks for your help.
Okay so... Problem solved. It just seems that MySQLWorbench accepts this request with a direct path (no errors, script executed) but doesn't refresh his table view... So my table have been fullfilled around 3 times before I restarted MySQLWorkbench to discover that my table was full. So... Problem solved. Sorry for the time loss.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, import, workbench" }
Special Issue with div displacement upon zooming out EDIT: On the above site whenever I zoom out in firefox the main content div is displaced to the right. This issue only exists in firefox, not in internet explorer, opera or chrome. Could someone help me fix this? EDIT 2: I do NOT want the div to displace in firefox. Sorry about the first question, I was in a hurry but should be clear now :)
If you give float:left; to the .wrapper element and the ul.menu everything will be ok :)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css, html" }
netrw `Ex` sometimes creates a split I'm usually in 2 vertical splits, in each one I jump in an out of files using `:Ex`. When a split shows a file and I type `:Ex` I expect this split to show me the netrw UI, where I can choose another file. But sometimes instead of replacing the split, `:Ex` will create a horizontal split inside this split and show me both the netrw UI and the file I was previously viewing. I haven't identified when and how, was wondering if you could help me understand if I'm using it wrong.
This is directly explained under `:help :Explore`: > `:Explore` will open the local-directory browser on the current file's directory (or on directory `[dir]` if specified). **The window will be split only if the file has been modified and`'hidden'` is not set**, otherwise the browsing window will take over that window. Normally the splitting is taken horizontally. You might want to consider adding `set hidden` to your vimrc to ensure `:Explore` will not create a new split. See `:help 'hidden'` for details. I generally recommend enabling this option, I think it's quite useful behavior and it's not really counterintuitive, it doesn't take much to get used to its behavior. * * * As a general advice, when you have questions about a specific command or setting or behavior in Vim, start looking at `:help` (+ whatever command you're running.) Vim's help system is _very_ good and in the vast majority of cases will have very direct answers to the questions you might have.
stackexchange-vi
{ "answer_score": 3, "question_score": 1, "tags": "netrw" }
Adding checkbox values using Jquery I am trying to add the checkbox values on button click using Jquery. Please help. I want to display the result in the paragraph. <div class="container"> <input type="checkbox" classname="check" id="one" value="1"> 1 <br> <input type="checkbox" classname="check" id="two" value="2"> 2 <br> <input type="checkbox" classname="check" id="three" value="3"> 3 <br> <input type="checkbox" classname="check" id="four" value="4"> 4 <br> <input type="checkbox" classname="check" id="five" value="5"> 5 <br> <button type="button" id="button"> Add </button><br> <p id="total"></p> </div> Clicking on the ADD button the output should be printed below. Link to Example
Please try this code. here is jsfiddle < var addButton = document.getElementById("button"); var totalP = document.getElementById("total"); addButton.onclick = function(){ var total =0; $.each($("input[classname='check']:checked"), function(){ total = total + Number($(this).val()); }); totalP.innerText = "total value "+ total; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery" }
Obtaining a screen shot of an Applet? Given an Applet object, is it possible to programatically obtain a "screen shot" of the applet window (represented as say a BufferedImage)? JApplet applet = this; // ... code here ... BufferedImage screenshotOfApplet = ...;
You could use `Robot.createScreenCapture(Rectangle bounds)` \- however, the applet would have to be signed to allow this to work once deployed. After comments - If you just want the applet component - You can create a BufferedImage and paint to it - something like this: public static BufferedImage imageFor(Component component) { BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); component.paint(g); return image; } I'm not sure if this would require the applet to be signed or not...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, swing, applet, awt, bufferedimage" }
how can I permanently change db path in Mongodb? I tried `mongod --dbpath=/data` option to change the data directory location, by executing this command **_continously running in forground waiting for connection_** it works on mongo CLI, But after I stop the `mongod --dbpath=/data` by CTRL +C, mongo CLI refuse to Connect Then After restarting mongod service, it's just normally use by default path in root directory. Then I edited in /etc/mongodb.conf db path parameter, after mongob serive can't start Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: Active: **failed** (Result: exit-code) since Mon 2019-07-15 19:36:47 IST; 5s ago Docs: Process: 5355 ExecStart=/usr/bin/mongod --config /etc/mongod.conf **(code=exited** Main PID: 5355 (code=exited, status=2) How do I make this permanent **I change that new directory ownership to mongodb user **I am using Ubuntu
Finally fixed that problem, I am actually put **small case P in dbPath option**. Then I properly give **ownership that directory to mongodb** user account, It works perfect!
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "nodejs, mongodb" }
Как задать UILabel.text цвет текста и размер строки? у меня есть NSString _abc к примеру, и есть UILabel_ labtxt - к которому я хочу прикрутить цвет и размер. [UIColor redColor]//цвет font//Размер только как прикрутить это всё не знаю. Хотел бы задать ещё несколько попутных вопросов: 1.Сам же стринг цвета не может иметь? только нужно выставить компонент с нужным цветом? 2.Как текст сделать жирным?
self.labtxt.textColor = [UIColor redColor]; self.labtxt.font = [UIFont boldSystemFontOfSize:14]; self.labtxt.text = abc; Как то так)
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "xcode" }
Add an ImageGallery under Article I have for same Article a ImageGallery. How can I add the gallery to an article by Schmea.org? What is the best property to declare a gallery to an article? Gallery is "Thing > CreativeWork > WebPage > CollectionPage > ImageGallery". Is the property `hasPart` (`CreativeWork`) the best one?
The `ImageGallery` type is for image gallery _pages_ (as it inherits from `WebPage`), not for any kind of image gallery. So `ImageGallery` doesn’t seem to be a suitable type for image galleries that are part of an `Article`. There doesn’t seem to be a good alternative to model these for `Article`. A simple way is to use the `hasPart` property for each `ImageObject`, but this doesn’t allow you to state something about the whole gallery.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "image gallery, schema.org" }
PCL Save Image File to local File System I am looking for a way to store image files in my local filesystem using the **PCL Storage** plugin in my core Project for `Windows Phone`, `Xamarin.Android` and `Xamarin.iOS`. However, the plugin does just provide methods for writing Text. Nothing about bytes. Is there a way to save byte arrays?
How about something like this: IFile file = await FileSystem.Current.GetFileFromPathAsync(fs.filepath); byte[] buffer = new byte[100]; using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite)) { stream.Write(buffer, 0, 100); } Edit: Some code taken from < IFile file = await folder.CreateFileAsync("myfile.abc", CreationCollisionOption.ReplaceExisting); Once you've got the IFile object you should then be able to use this in the same way: IFile file = await folder.CreateFileAsync("myfile.abc", CreationCollisionOption.ReplaceExisting); byte[] buffer = new byte[100]; using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite)) { stream.Write(buffer, 0, 100); }
stackexchange-stackoverflow
{ "answer_score": 22, "question_score": 9, "tags": "cross platform, xamarin, storage, portable class library" }
akka http remote address I'm using Akka HTTP 10.0.9, but struggling to get my unit tests to have a working Remote Address. eg unit test: Get("/").withHeaders( RawHeader("Remote-Address", "192.168.1.1"), RawHeader("X-Forwarded-For", "192.168.1.1") ) ~> route ~> check { status must_== StatusCodes.OK } And in the web server code: extractClientIP{ clientAddr => complete(s"$clientAddr") } When running the app via the command line, the client address is returned correctly. But when run via unit tests, the client address always comes back as "Unknown" What am I doing wrong?
This is caused by **akka http** can't handle the `RawHeader` in **test**. You can solve it by use the `Remote-Address` object for set the **IP** for test: import akka.http.scaladsl.model.headers.`Remote-Address` Get().withHeaders( `Remote-Address`(RemoteAddress(new InetSocketAddress("192.168.1.1", 23))) )
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "scala, unit testing, http, akka" }
ng-model in select box is not working correctly I am using angular js to draw select boxes. <select ng-model="selected"> <option value="{{obj.id}}" ng-repeat="obj in values">{{obj.name}} </option> </select> selected id - {{selected}} Here the default selected is not initialized according to value `selected`. Have made a fiddle for the problem.
You should use `ngOptions` directive to render selectbox options: <select ng-model="selected" ng-options="obj.id as obj.name for obj in values"></select> **Fixed demo:** <
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "javascript, angularjs, angular ngmodel" }
How can get the number of likes shown in app store I want to know if exist a way to get the number of likes shown in App Store or Game Center. In this way I can check if a user really likes my application on Facebook. Thanks!
You should be using the iTunes lookup API to get back the info you need in JSON formatted results: < The link you should use for Angry Birds Rio would look like this: < { "resultCount":1, "results":[ { "artistId":298910979, "artistName":"Rovio Entertainment Ltd", ... "averageUserRating":4.5, "averageUserRatingForCurrentVersion":4.5, ...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, facebook, ios6" }
i want to get preview of my files in popup box I want to display my content (pdf, txt, images, videos) in pop up box..... as we can see an example in facebook! How to do that? For videos we can play our video in pop-up box. can we achieve this task through **JS** ? Please help if any tag we use in jsp.
This might help you < how to popup jquery window to play vimeo/youtube video?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, javascript, liferay" }
Is there a way to hide the keyboard without losing the focus of the EditText When you click the back button, the keyboard hides itself but the focus on the edittext remains. How can I reproduce this behaviour?
You can use this code to hide the keyboard: getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN ); Or this one : View view = this.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } If the EditText loses the focus, simple write a simple command editText.requestFocus();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android, android edittext, keyboard, focus" }
Does garlic repel mosquitoes? I have heard claims that garlic repels mosquitoes. Specifically, this site claims that > Eating a diet heavy in onions and garlic can make you unattractive to mosquitoes. Is there any evidence supporting that claim?
My answer is that it is a myth. To quote this study: > Most alternatives to topically applied repellents have proved to be ineffective. No ingested compound, including garlic and thiamine (vitamin B1), has been found to be capable of repelling biting arthropods.26-28 Small, wearable devices that emit sounds that are purported to be abhorrent to biting mosquitoes have also been proved to be ineffective.29 In our study, wristbands impregnated with either DEET or citronella similarly provided no protection from bites, consistent with the known inability of repellents to protect beyond 4 cm from the site of application. The above comes from: Comparative Efficacy of Insect Repellents against Mosquito Bites Mark S. Fradin, M.D., and John F. Day, Ph.D. N Engl J Med 2002; 347:13-18July 4, 2002
stackexchange-skeptics
{ "answer_score": 18, "question_score": 18, "tags": "natural remedies, entomology" }
Should GD need so much memory when resizing? I have a resize script i made in PHP that uses GD (my VPS doesn't have imagemagick installed) to resize an image, I have recently started getting memory errors so i have increased the memory_limit up to 50Mb and still get memory error. The image I am trying to resize is only 2Mb, is this correct for PHP image stuff, something sounds a bit wrong to me.
To resize the image GD has to work on the **uncompressed** image, which is significantly larger than 2MB, I assume. Imagemagick needs to store the entire image data (pixels * bit_depth) and quite some more for the actual work in memory. 50 Megabytes is not much for working with images. For example, Drupal warns you if you have less than 96MB memory limit, if you have the image resizing, etc.. enabled. For reasonably sized images 64MB are enough in my experience, but if you put full size images from a digital camera you'll run into problems with that memory limit.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "php" }
Scala's "This" and MapLike Say I wanted to extend Scala's MapLike trait with a concrete implementation, IntIntMap. In order to do so, I need to implement the following methods, def get(key: A): Option[B] def iterator: Iterator[(A, B)] def + B1 >: B): This def -(key: A): This What is the `This` type? Should my overriding method signature be, override def +=(kv: (Int, Int)): IntIntMap = { // logic } Or just `scala.reflect.This`? What about the class definition? Should it be, class IntIntMap(...) extends MapLike[Int,Int,This] { ... } or something else entirely?
You should extend `MapLike[Int, Int, IntIntMap]`, and `This` becomes `IntIntMap`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "scala, dictionary, this, scala collections" }
Convert base64 string to jpg/file I am struggling to find a way to convert a base 64 string to a jpeg or a file without using the Image class. Is it possible to create the file and not save it locally and upload to Azure blob storage? var bytes = Convert.FromBase64String(base64String);
To keep it completely clean and simple, use something like this: using (var img = new MemoryStream(bytes)) { cloudBlockBlob.UploadFromStream(img); } This creates a MemoryStream that you can use to call CloudBlockBlob.UploadFromStream(). **Edit** Or, like @mike-z said in the comment below, you can use CloudBlockBlob.UploadFromByteArray() directly.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, .net core, encoding" }
Trying to make `Solve` and `ReplaceAll` work together I have \[ScriptCapitalX][x_] := \[ScriptCapitalC][1] Cos[Sqrt[λ] x] + \[ScriptCapitalC][2] Sin[Sqrt[λ] x] Now, using the `Replace` function on `\[ScriptCapitalX][x_]`, I get > > BC1tospatialode = \[ScriptCapitalX][x] /. \[ScriptCapitalC][1] -> \[ScriptCapitalC][2] Sqrt[λ] > Again, applying the `Replace` function on `BC1tospatialode`, I get BC1tospatialode /. x -> L Here is where things gets slightly tricky in terms of the syntax: Ideally, I would like to set BC1tospatialode /. x -> L to zero and solve for `λ` with `Solve`, but I am unable to circumvent the syntax. I've tried BC2BC1tospatialode = Solve[ \[ScriptCapitalC][2] Sin[Sqrt[λ] L] + \[ScriptCapitalC][2] Sqrt[λ] Cos[Sqrt[λ] L] == 0, λ] to no avail. Would anyone be willing to help?
You can't solve the equations analytically, since it is transcendental of the form `Sqrt[Lambda] == -Tan[L Sqrt[Lambda]]` Restrict the `Lambda`values to lambdamax to get results with BC2BC1tospatialode[L_,lambdamax_] := NSolve[(Sqrt[lambda] Cos[L Sqrt[lambda]] \[ScriptCapitalC][2] + Sin[L Sqrt[lambda]] \[ScriptCapitalC][2] /. C[2] -> 1) == 0 && 0 < lambda < lambdamax, lambda] BC2BC1tospatialode[4, 50] // N (* {{lambda -> 0.412945}, {lambda -> 1.7916}, {lambda -> 4.30866}, {lambda -> 8.02989}, {lambda -> 12.9744}, {lambda -> 19.1481}, {lambda -> 26.5535}, {lambda -> 35.1914}, {lambda -> 45.0624}} *) C[2] is set to 1, since it has no influence on roots.
stackexchange-mathematica
{ "answer_score": 3, "question_score": 1, "tags": "equation solving, replacement" }
Preposition with спросить I'm puzzled by the use of the preposition _у_ with the verb спросить: > Я спрошу у мамы смогу ли взять машину In this example, the preposition is used. But: > Журналист спросил президента о его планах на будущее In this example, the preposition is not used. Is the meaning the same in these two sentences? As far as I know, in both instances the meaning is "to ask someone (about) something".
Both forms "спросить у кого-то" and "спросить кого-то" are equally valid \- the difference is very, very subtle and you can find a lot of answers in internet that are nothing but wrong. It wouldn't be oversimplification to say - those form a virtually equivalent. The only difference I'm aware of - and it's only a statistical observation, I can not provide any grammar rule or other evidence - when it comes to inanimate objects, the "у"-form is more likely. For instance, there's a famous song which contains following lyrics: "Я спросил у ясеня, где моя любимая". One can not say "я спросил ясень" but "у ясеня" sounds more natural. I'm leaving behind the brackets here the fact that it's strange to communicate with inanimate objects but I can imagine following phrases: * "Я спросил у тополя" (and less likely "я спросил тополь"). * "Я спросил у талисмана" (but less likely "талисман").
stackexchange-russian
{ "answer_score": 4, "question_score": 3, "tags": "глаголы, предлоги" }
Get the X-API-KEY value from header in Phil Sturgeon REST API I have made an API using Phil Sturgeon REST Api which uses the codeignitor framework. Every request made to my api should have X-API-KEY:{api key} in the request header. Is there anyway I can get the api key of a request so that the api can identify the user who has generated the api key in my system.Is there anyway I get get the X-API-KEY value from the header?
@piya I am not sure this could help you out or not.. but give it a try.. <?php $headers = apache_request_headers(); foreach ($headers as $header => $value) { echo "$header: $value <br />\n"; } ?>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, api, codeigniter, codeigniter restserver" }
Prove that the sum of derivatives of a non-negative function is non-negative Let $f(x)$ be a polynomial of degree $n$ with real coefficients such that $f(x)$ is non-negative for all real $x$. Let $g(x)=f(x)+f'(x)+f''(x)+\dots$ be the sum of $f(x)$ and the first $n$ derivatives of $f(x)$. Show that $g(x)$ is non-negative for all real $x$. Thanks for any comments/answers in advance!
Note that $f(x) $ must have even degree and a positive leading coefficient (unless it is zero, in which case it's trivial) and thus so must $g(x)$. Thus, $g$ has a global minimum, say at $y$. From the definition of $g$, $g'(y)=0$ then implies that $g(y) = f(y) \ge 0$.
stackexchange-math
{ "answer_score": 4, "question_score": 4, "tags": "derivatives, polynomials" }
Freeform: sending Composer form submission notification to a dynamic email address I have a Contact Us form that is being generated in Composer and being assigned to my template via the Freeform Fieldtype. The template code simply uses the custom_field name: i.e. {modal_form} The form has a select statement that allows the user to select a location. Depending on the user's selection I would like that location to be notified via email of the form submission. Currently the site administrator has to manually forward the email to the correct location. Is this possible? Thanks.
Have you tried a Dynamic Recipients field on Composer? It allows you to set a select drop-down which impacts the recipients of the email.
stackexchange-expressionengine
{ "answer_score": 0, "question_score": 0, "tags": "solspace freeform" }
Add option for editors through `register_setting` I want to add some options in wordpress admin panel which editors also can update through a form. I have used `register_setting()` function to add those options. For administrator this works fine, but for editors i get message `Sorry, you are not allowed to manage these options.`. Is there a way so editors can also edit these new options?
To allow users with capabilities other than `manage_options` to save a setting you can use the `option_page_capability_{$option_page}` hook. Despite the name, `{$option_page}` is the option _group_ , which is what you set for the first argument of `register_setting()` and `settings_fields()` on your options page. So if you registered a setting: register_setting( 'wpse_310606_setting_group', 'wpse_310606_setting' ); You can allow other capabilities to save it with: function wpse_310606_setting_capability( $capability ) { return 'edit_pages'; } add_filter( 'option_page_capability_wpse_310606_setting_group', 'wpse_310606_setting_capability' ); Editors and Administrators both have the `edit_pages` capability, so this would allow both roles to save this settings group.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "editor, options" }
Windows 8 metro apps offline download Is their any sites available to download windows 8 metro apps for offline installation. Alternative to windows store.Because i don't have internet connection in home. Please tell me any sites ?
You have to be connected to install Windows 8 Store apps. You cannot sideload an app that has been downloaded from the Windows Store. Alternatively, you can get your app directly from the developer without involving the Store, in which case, installation can be offline. Apps that aren't signed by Windows Store can only be installed on sideloading-enabled devices.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 6, "tags": "windows 8, download, microsoft metro, windows store apps, windows 8.1" }
Solving $ \lim_{x\to0}{\frac{1}{x^2}-\cot^2(x)}$ Evaluate: $$ \lim_{x\to0}{\frac{1}{x^2}-\cot^2(x)}$$ My approach : $$\lim_{x\to0}{\frac{1}{x^2}-\frac{\cos^2(x)}{\sin^2(x)}}$$ $$ \lim_{x\to0}\frac{\sin^2(x)-x^2\cos^2(x)}{x^2\sin^2(x)} $$ Using $$\lim_{x\to0}\frac{\sin^2(x)}{x^2}=1 $$ $$ \lim_{x\to0}\frac{\sin^2(x)-x^2\cos^2(x)}{x^4} $$ $$ \lim_{x\to0}\frac{\sin^2(x)}{x^2}\cdot\frac{1}{x^2}-\frac{\cos^2(x)}{x^2} $$ $$ \lim_{x\to0}\frac{1}{x^2}-\frac{\cos^2(x)}{x^2} $$ Applying L Hopital, $$\lim_{x\to0}\frac{2\sin(x)\cos(x)}{2x}=1$$ But the actual answer is $\frac{2}{3}$. What am I doing wrong here?
The following steps are not allowed $$ \lim_{x\to0}\frac{\sin^2(x)-x^2\cos^2(x)}{x^2\sin^2(x)} \color{red}{=\lim_{x\to0}\frac{\sin^2(x)-x^2\cos^2(x)}{x^4} }= \lim_{x\to0}\frac{\sin^2(x)}{x^2}\cdot\frac{1}{x^2}-\frac{\cos^2(x)}{x^2} =\\\ \color{red}{= \lim_{x\to0}\frac{1}{x^2}-\frac{\cos^2(x)}{x^2} }$$ since $\lim_{x\to0}\frac{\sin^2(x)}{x^2}=1 $ doesn't mean that $\frac{\sin^2(x)}{x^2}=1$. We need to solve by l'Hopital or by Taylor's expansion starting from the first expression.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "limits, trigonometry" }
Expose C++ buffer as Python 3 bytes Using Boost::Python, is there a way to make a raw C++ buffer accessible to **Python 3.2** as a `bytes` object? There is a Python 2 answer to a very similar question, but the `PyBuffer_FromReadWriteMemory` function described there no longer exist in Python 3. **Edit** : thanks to user2167433's answer, what I actually want is a read only memoryview object, not a `bytes` object (using a `memoryview` avoids copying the buffer I believe).
## Python > 3 and Python <= 3.2: Py_buffer buffer; int res = PyBuffer_FillInfo(&buffer, 0, data, dataSize, true, PyBUF_CONTIG_RO); if (res == -1) { PyErr_Print(); exit(EXIT_FAILURE); } boost::python::object memoryView(boost::python::handle<>(PyMemoryView_FromBuffer(&buffer))) ## Python >= 3.3: The best way I know how is to use PyMemoryView_FromMemory: boost::python::object memoryView(boost::python::handle<>(PyMemoryView_FromMemory(data, dataSize, PyBUF_READ))); memoryview is the Python way to access objects that support the buffer interface. C API memoryview memoryview class
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 7, "tags": "c++, python 3.x, boost python, python 3.2" }
Convert wifi to wired using wireless router I have a TP-Link WR740N, a Raspberry Pi (With only an ethernet port for Network), and a Wifi connection. Is it possible to use the wireless router to bridge the Pi with the Wifi connection?
Yes you can, you need to set the TP Link up as a client to your WIFI this creates a WIFI bridge. To do that you need to access it's admin page via your browser, log in, find client or ethernet bridge mode. It will ask for an SSID, this is your wifi network name. It will also need your wifi password and may ask for the encryption type your wifi is set to. When it comes to it's IP address, you will have 2 choices, dynamic or static, dyanmic will get an IP from your home network. But finding it again after it's been asigned an IP can be tricky. Or set it as static, you need to match your homes Subnet mask and choose an IP thats inside your home networks but not used by any other devices. Once it's connected you will want to make sure the TPLinks DHCP is turned off as your home network more than likely has a DHCP ( gives out IP address ). I've done this for my development boards that only have Ethernet using this device.
stackexchange-serverfault
{ "answer_score": 2, "question_score": -1, "tags": "wifi, bridge, wireless bridge, bridge router, tp link" }
what is nonce in the api client I have a API client to make a PHP call. But as a matter of fact the documentation given with the API is very limited, so I don't really know how to use it. This a part of the API code: $name = readline("Name: "); $id = readline("ID: "); $data = $name.$id; $test = new PoW(sha1($name.$id)); echo "Original data: " . $data . "\n"; echo "data: " . $test->data . "\n"; echo "nonce: " . $test->nonce . "\n"; echo "hash: " . $test->hash . "\n"; $result = file_get_contents(" echo "\n" . $result . "\n"; I don't know what is nonce and how does it works.
The NIST glossary defines a _nonce_ as follows: > _" A time-varying value that has at most a negligible chance of repeating, for example, a random value that is generated anew for each use, a timestamp, a sequence number, or some combination of these."_ Source: < See also: * How to create and use nonces Nonce values are typically used in security related use-cases to help defend against replay attacks. * * * It is not obvious (to me) how the nonce should be generated and used for your particular use-case. However, for it to be effective, it needs to be part of the message that is being hashed.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, api" }
Beautifulsoup doesn't work properly with all urls The error says: > AttributeError: 'NoneType' object has no attribute 'get_text' I was following a web scraping tutorial and everything worked fine just with this url, when I wanted to change it to this url the error that I already mentioned appeared. The crawler function: def product_crawler(): page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') title = soup.find(id="productTitle").get_text() print(title) I checked all the answers on stackoverflow such as changing html.parser to lxml , but non of them worked.
Try to add `Accept-Language` HTTP header: import requests from bs4 import BeautifulSoup url = " headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0", "Accept-Language": "en-US,en;q=0.5", } page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, "html.parser") title = soup.find(id="productTitle").get_text(strip=True) print(title) Prints: GoPro HERO9 Black - Waterproof Action Camera with Front LCD and Touch Rear Screens, 5K Ultra HD Video, 20MP Photos, 1080p Live Streaming, Webcam, Stabilization
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "python 3.x, web scraping, beautifulsoup, attributeerror" }
Give certain values specific color in matrix with imagesc Lets say I have a matrix A A = [1 1 1 1 1 1 1; 1 0 0 1 0 0 1; 1 0 0 0 0 1 1; 1 0 1 0 1 0 0; 1 0 0 0 0 0 1; 1 1 1 1 1 1 1]; And I want to give the 1's at the edges a specific color, and the 1's that are not at the boundaries a specific color and the 0's a specific color, How do I go about this? Currently I just have `imagesc(A)`, I have been reading up on `colormap` and I do not understand it. To me it seems they just have set color scheme. On the website I see `winter`, `summer`, `hot`, `jet` etc. I would like to know how to modify, and how and where colors are displayed, and what colors are to be displayed.
Colormap in matlab allows you to set a color for an indexed image (in your case you only have 2 indexes - 0,1 which is usually interperted as black and white). MATLAB has some predefine settings as you mentioned `winter`,`summer`, `hot`, `jet` etc. You can define your own colormaps.In order to do that you need to first build a matrix of nX3 where n is the number of colors you need and the 3 is attributed to the RGB color space. In your example above imagesc(A) Gives a blue and yellow image (since the default is `parula`). If you define the new colormap matrix as follows Cmap = [1 1 1; 0 0 0]; colormap(Cmap); You will get the image in black and white (because of the values in Cmap). You can change the `Cmap` matrix values for different colors.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "matlab" }
Build GNU Guile stable on Ubuntu 16.04 The Ubuntu repositories only contain the old `2.0` version of GNU Guile. I want to build the current stable `2.2` on my machine. I cloned the repository: git clone git://git.sv.gnu.org/guile.git and checked out stable: git checkout stable-2.2 The `README` file says that install instructions are in the `INSTALL` file. That one does not exist, so I searched the web and the only instructions I found are on < They mention to run the typical configure, make, make install process with parameters and other things. However, next problem: There is no `configure` file in the repository I cloned. How to build GNU Guile?
Apparently there is a not mentioned difference between what you can pull with `git` and versions one can download from < for example. I have no idea why it would make sense to leave the important parts for installing out of the repository, since they are only some scripts, but it seems they only get added for releases downloadable in other ways. The downloaded release versions can be built and installed using the usual `./configure`, `make`, `make install`, process.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "linux, ubuntu, git, build" }
2015 AIME #3: Where did I go wrong? This is a question conerning 2015 AIME #3. The problem goes as follows: 3. There is a prime number $p$ such that $\displaystyle 16p+1$ is the cube of a positive integer. Find $p$. Here is my current working: By the problem statement: $16p+1=a^3$ Therefore, $16p+1 ≡ a^3 \mod 3$ And by Fermat's Little Theorem and the transitive property, $16p+1 ≡ a \mod 3$ This can be re-arranged by subtracting $1 \mod 3$ from both sides. $16p ≡ a-1 \mod 3$ The modular multiplicative inverse of $16$ is $1\mod 3$ because: $x≡16^{-1} \mod 3$ $16x ≡ 1 \mod 3$ Which is true for $x={1,4,7,...}$ Multiplying both sides by the inverse $16^{-1} \mod 3$, you get: $p≡a-1 \mod 3$ Which appears to be incorrect? Any suggestions/hints? Is this just the plain wrong approach to the problem? (It very likely might be)
Hint: Try $a^3-1=(a-1)(a^2+a+1)=(17-1)(17^2+17+1)$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "modular arithmetic, contest math" }
Git accept all changes from Pull Request I have a project that we just rewrote which completely changed the file structure of the application, and upgraded many parts of it. I no longer care what's in the master branch; I want the PR I created to replace everything in master with what's in the version-2 branch. I'm just not sure what command to use. I created the PR in GitHub, but it can't automatically merge for me (obviously) but running `git merge dev` on the version-2 branch isn't working either, because I can't exactly tell if it's prioritizing the version-2 changes over anything in dev. Hopefully this makes sense...which git command is the one I'm looking for? Again, when version-2 merges into master, I want version-2 to overwrite master in any potential merge conflict.
You can create a "fake merge" by specifying a merge strategy `ours` dedicated for your case: git checkout version-2 git merge -s our master -m "This is a brand new version 2" git update-ref -m "Promote master to version-2" master refs/heads/version-2 git checkout master git branch -D version-2 # if nobody needs version-2 anymore This way is slightly longer than renaming branches, but it allows to keep the whole history of your project. All the users of the master branch will receive the major change without any additional effort.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "git" }
Java - Read a string of numbers into columns by rows I have a grid in this form: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 and I will be receiving it in a string form: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 this is just an example of a 5 by 5 grid. But in actual, I have 20 columns by 15 rows. The values in the grid will not be only in zeroes. However, I would like to know how to read a string of numbers like this into columns by rows. I am depending on this string to check the grid with colours in android's GUI using onDraw method. Where my method reads in column by row. Any help is appreciated!
Thanks for giving me the opportunity to learn and think on my own. Of course, thank you @xgeorgekx for the codes that gave me my own idea of solving my own problem using your codes as reference. I did it in this way though, I know it is not fully optimised. I welcome any suggestions! Firstly, I get rid of all the spaces in the string. then using numColumns as 15 and numRows as 20, i used 2 loops and stored the values of the string parsed to int as i needed the element of the array as the cellType so as to set the colour. String spaceFilter = map.replaceAll(" ", ""); for (int i = 0; i < numColumns; i++) { for (int j = 0; j < numRows; j++) { if (spaceFilter.length() != 0) { cellType[i][j] = Integer.parseInt(spaceFilter.substring(0,1)); spaceFilter = spaceFilter.substring(1); } } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, ondraw" }
Must an automorphism on the group of real numbers under multiplication maintain sign? Suppose we have an automorphism $\phi$ under the group $(\mathbb{R}^{\\#},\,\cdot)$. I need to show that $\phi$ preserves the sign of the numbers, or that $\phi(\mathbb{R}^+)=\mathbb{R}^+$ and $\phi(\mathbb{R}^-)=\mathbb{R}^-$. I've had a bit of success. I determined fairly painlessly that $\phi(r)>0\iff\phi(r^{-1})>0$ for any $r\in\mathbb{R}^\\#$. But I'm having difficulty making any other sort of progress. My guess is that there's something trivial that I'm missing that I'm currently just too blind to see, but either way, I'm a bit frustrated with my stagnancy here. Any help or hints or suggestions would really help. For reference, the only thing I really know about automorphisms is the fact that they're bijective and that it preserves the identity (in this case) $\phi(a) \cdot \phi(b)=\phi(a \cdot b)$ for all $a,b\in\mathbb{R}^\\#$.
**Hint:** Use that $\phi(a^2)=(\phi(a))^2$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "abstract algebra, group theory, real numbers" }
Is there a topologically mixing and minimal homeomorphism on the circle (or on $\mathbb S^2$)? The irrational rotation on the circle is both a homeomorphism and minimal but is not topologically mixing. The argument-doubling transformation on the circle is topologically mixing but is neither a homeomorphism nor is it minimal. Is there a topologically mixing and minimal homeomorphism on the circle (or on $\mathbb S^2$)?
There's no topologically mixing self-homeomorphism of the circle. Indeed, pick 3 points, so that the complement of these 3 points consists of 3 intervals $A,B,C$. If $g$ is a self-homeomorphism such that $g(A)$ meets all of $A,B,C$, then it has to contain entirely one of $A,B,C$. Therefore it is not possible that all the intersections $g(A)\cap A$, $g(A)\cap B$, $g(A)\cap C$, $g(B)\cap A$, $g(B)\cap B$, $g(B)\cap C$ be simultaneously nonempty. (If $f$ were a topologically mixing self-homeomorphism, $f^n$ for large $n$ would have to satisfy this property.) On $S^2$ it's completely another question.
stackexchange-mathoverflow_net_7z
{ "answer_score": 11, "question_score": 6, "tags": "gn.general topology, ds.dynamical systems, topological dynamics" }
Attach an event handler to an object literal I have an object literal to open a websocket connection. this is a simplified version of it: const ws = { conn : null, start : function(){ this.conn = new WebSocket('wss://.....'); this.conn.onopen = (e) => {}; this.conn.onmessage = (e) => {}; this.conn.onclose = (e) => {}; } } i can initialize the connection with: var websocket = ws.start(); now i want to attach an eventhandler to _websocket_ , which is called when _onmessage_ is fired. like this: websocket.on('message', function (e) { console.log('this.conn.onmessage in ws was fired'); }); is there a way to achieve this?
Just return the connection at the end of the `start` function. const ws = { conn : null, start : function(){ this.conn = new WebSocket('wss://.....'); this.conn.onopen = (e) => {}; this.conn.onmessage = (e) => {}; this.conn.onclose = (e) => {}; return this.conn; } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
How to disable autocomplete code statements in code editor? Every time I type `if` and press the space bar, Delphi completes it with `if True then` and a new empty line above. Is there a way to remove **this** "autocomplete" feature or at least edit it to not create the new line?
That's called a _live template_ , and you can edit the list of live templates in the template window, from the View menu. Find the template you don't like, select it, and click the "remove template code" button.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "delphi, delphi xe3" }
How to remove "Field" text from every property name in web api response I have ASP.NET web api which is returning response with property names appended with text "Field" like below { "idField":"12345", "activeField":true } The web api method returns an object created from a proxy class which is generated in Visual Studio by adding a service reference so I can't modify the class properties with attributes. How can I remove the "Field" text from property names? I am also having issues with the POST method where I send JSON data without "Field" text appended to the property names and I am not getting data in the method but if I append the "Field" text, it's working as expected.
It might be a one of case and applicable only for me but here is what worked for me. I added the below code in WebApiConfig class --> Register method and I get the response as expected. ( ( Newtonsoft.Json.Serialization.DefaultContractResolver ) ( config.Formatters.JsonFormatter.SerializerSettings.ContractResolver ) ).IgnoreSerializableAttribute = true;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "json, asp.net web api" }
Mysql: Sum by current date + 30 days Table structure: id int revenue float date date I would like to SUM the revenue and group the result by date +30 days starting from a specific date until current date. So i have data starting from 2015-01-05 so i would like to get the sum of the revenue starting from 2015-01-05 and each group should have +30 days like 2015/01/05 - 2015/02/04 2015/02/04 - 2015/03/06 2015/03/06 - 2015/04/05 etc So i want the result to be grouped in 30 days periods (not months)
Use GROUP BY FLOOR(DATEDIFF(date, '2015-01-05')/30) `DATEDIFF` calculates the days between two dates. Then we divide by `30` to reduce them to 30-day blocks, and use `FLOOR` to remove the fraction.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql" }
VDI usage inconsistent between host and guest `vbox 5.0.24`, `ubuntu 16.04` on host & guest (`myguest`) with dynamically allocated VDI. Why was the VDI usage vastly inconsistent between host and guest, when I checked it below? $ du -h myguest.vdi # from the host 5G $ df -h --total # from the guest ... used ... total ... 2G
**@Solution** * boot guest to `recovery mode [Esc, Enter]` * choose `drop to root shell [Down, Enter]` * go to `Maintenance [Enter]` * # mount -o remount,ro /dev/sda[id] / * # zerofree /dev/sda[id] * # shutdown -P now * shrink the guest VDI from the host via, * $ VBoxManage modifyhd [guest].vdi --compact Reference: < < <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "virtualbox" }
Change Validation Summary Text in MVC for a password validation How do I change the default message on the validation summary when a password does not meet the requirements. The current message the appears is > "Passwords must have at least one digit ('0'-'9'). Passwords must have at least one uppercase ('A'-'Z')." I want to change that text to something else.
You can also use DataAnnotations.aspx) In your example, you can use : // ~YourModelFile.cs [RegularExpression(@"^[A-Z0-9]{6,}$", ErrorMessage = "Password must be at least 6 characters long")] public string Password { get; set; } Interesting point is the `ErrorMessage` may be placed in a `Resources` files, so you can display it in multiple languages. Plus, you do not have to write a custom `AddError` method anymore.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "asp.net mvc, validation, validationsummary" }
How come I am getting the same total values of 2 different columns I need someone to correct the statement below please. Thank you in advance. SELECT CATEGORY --WHAT PERIOD? ,'P3' AS PERIOD ,'2013' AS FISCALYEAR ,COUNT(CASE SecurityLayer WHEN 'dblayer' THEN SecurityLayer ELSE '' END) DB_SEC_COUNT ,COUNT(CASE SecurityLayer WHEN 'Applayer' THEN SecurityLayer ELSE '' END) APP_SEC_COUNT FROM [db_eCAM].[dbo].[tbl_SecChecks] GROUP BY CATEGORY
Are you trying to return the # of times each of those things matches? Then use SELECT CATEGORY --WHAT PERIOD? ,'P3' AS PERIOD ,'2013' AS FISCALYEAR ,SUM(CASE SecurityLayer WHEN 'dblayer' then 1 else 0 end) AS DB_SEC_COUNT ,SUM(CASE SecurityLayer WHEN 'Applayer' then 1 else 0 end) AS APP_SEC_COUNT FROM [db_eCAM].[dbo].[tbl_SecChecks] GROUP BY CATEGORY Try that.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sql" }
Changing font for Hydrogen Atom Code Inspector How do I change the font (and font size) for the Code Inspector pane (accessible from the Command Palette 'Hydrogen: Toggle Inspector')? Asking mainly because the font size is a tad too small for me when I pull up the Inspector pane. Thanks in advance!
As of Hydrogen version 1.22.0 you can configure the font size for the output and side panels (including the inspector) inside the Hydrogen settings. For older versions you need to customize the user style sheet of Atom.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "atom editor, hydrogen" }
tensorflow efficient way for tensor multiplication I have two tensors in tensorflow, the first tensor is 3-D, and the second is 2D. And I want to multiply them like this: x = tf.placeholder(tf.float32, shape=[sequence_length, batch_size, hidden_num]) w = tf.get_variable("w", [hidden_num, 50]) b = tf.get_variable("b", [50]) output_list = [] for step_index in range(sequence_length): output = tf.matmul(x[step_index, :, :], w) + b output_list.append(output) output = tf.pack(outputs_list) I use a loop to do multiply operation, but I think it is too slow. What would be the best way to make this process as simple/clean as possible?
You could use `batch_matmul`. Unfortunately it doesn't seem `batch_matmul` supports broadcasting along the batch dimension, so you have to tile your `w` matrix. This will use more memory, but all operations will stay in TensorFlow a = tf.ones((5, 2, 3)) b = tf.ones((3, 1)) b = tf.reshape(b, (1, 3, 1)) b = tf.tile(b, [5, 1, 1]) c = tf.batch_matmul(a, b) # use tf.matmul in TF 1.0 sess = tf.InteractiveSession() sess.run(tf.shape(c)) This gives array([5, 2, 1], dtype=int32)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "python, tensorflow, deep learning" }
How to split a string on the first occurrence of one of multiple substrings in JavaScript? Given strings s1 = "abcfoodefbarghi" and s2 = "abcbardefooghi" How can I split s1 into "abc" and "defbarghi" and s2 into "abc" and "defooghi" That is: split a string into two on the first occurrence of either one of strings "foo" or "bar" I suppose this could be done with `s.split(/regexp/)`, but what should this regexp be?
Use a Regular Expression in this way: var match = s1.match(/^([\S\s]*?)(?:foo|bar)([\S\s]*)$/); /* If foo or bar is found: match[1] contains the first part match[2] contains the second part */ Explanation of the RE: * `[\S\s]*?` matches just enough characters to match the next part of the RE, which is * `(foo|bar)` either "foo", or "bar" * `[\S\s]*` matches the remaining characters Parentheses around a part of a RE creates a group, so that the grouped match can be referred, while `(?:)` creates a non-referrable group.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "javascript, regex, string, split" }
Inequality involving AM - GM: $\sum_{i=1}^n \frac{1}{1+a_i} \ge \frac{n}{1+{{(a_1.a_2...a_n)}}^{1/n}}$ given that $a_i > 1$, how do I prove that $$\sum_{i=1}^n \frac{1}{1+a_i} ≥ \frac{n}{1+{{(a_1.a_2...a_n)}}^{1/n}}$$ by applying AM - GM inequality? Thanks in advance!
According to AM/GM inequality, $$ \frac{1}{n}\sum_{i=1}^{n} \frac{1}{1+a_i} \ge \prod_{i=1}^{n} \left( \frac{1}{1+a_i} \right)^{\frac{1}{n}}. $$ Now let's see the RHS expression. $$ (1+a_1)(1+a_2) > 1+a_1a_2 \qquad \text{(as $a_i > 0$)} $$ Similarly, $$ \prod_{i=1}^{n} (1+a_i) > 1 + P_n \tag{1} $$ and you can also proof that $\prod_{i=1}^{n} (1+a_i) < \frac{1}{1-P_n}$. Since the reciprocal of the expression $\text{(1)}$ can be seen as $$ \frac{1}{n}\sum_{i=1}^{n} \frac{1}{1+a_i} \ge \prod_{i=1}^{n} \left(\frac{1}{1+a_i}\right)^{\frac{1}{n}} > \left(\frac{1}{1+P_n}\right)^{\frac{1}{n}} > \frac{1}{1+P_n^{1/n}} $$ Hope this helps.
stackexchange-math
{ "answer_score": 0, "question_score": 3, "tags": "inequality" }
c# and ffpmeg command line trouble I have a php code that calls ffmpeg from the windows command line (because I run apache locally) with: //ffmpeg -i input.mp4 -r 20 output.gif echo exec('C:\ffmpeg\bin\ffmpeg.exe -i videos/file.avi -r 10 -s 450x230 videos/file.gif'); And it works fine! Now I wrote a C# program and I try to do the same thing with: System.Diagnostics.Process.Start but it fails. Question: How do I execute the same command from the PHP code but from inside a C# code?
Process process = Process.Start( new ProcessStartInfo { FileName = @"C:\ffmpeg\bin\ffmpeg.exe", Arguments = "-i videos/file.avi -r 10 -s 450x230 videos/file.gif", WindowStyle = ProcessWindowStyle.Hidden } ); process.WaitForExit(); If it fails an exception will be raised, e.g. System.ComponentModel.Win32Exception with HResult=-2147467259 if the executable wasn't found.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, php, ffmpeg" }
C# Sleep Detection PowerModeChanged I want me program to write to the console when the computer it going to sleep but am unable to do so. I think I am setting this up wrong. Here is what I have... Edit: New .cs file using LightFX; using System; using System.Threading; using System.Text; using Microsoft.Win32; using ConsoleApplication3; namespace SampleApp5 { class Program { static void Main() { } SystemEvents.PowerModeChanged += PowerModeChanged; } class PowerModeChanged { } }
That event is raised by the `SystemEvents` class (it's a static event). You just need to bind to it: SystemEvents.PowerModeChanged += OnPowerModeChanged; You need to do this somewhere in your main method. And, of course, delete your custom delegate, since it's already defined by the framework. You don't need this line: > ~~public static event PowerModeChangedEventHandler PowerModeChanged;~~ UPDATE: static void Main() { SystemEvents.PowerModeChanged += OnPowerModeChanged; Console.ReadLine(); //just wait, don't exit immediately. } private static void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e) { //Handle the event here. }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "c#" }
Google Analytics Enhanced Ecommerce with datalayer - which events in Tag Manager? I'm using Google Analytics Enhanced Ecommerce with the datalayer on my webshop. Any event (product impression, detail view, add to cart, etc.) is added to the datalayer. I'm also using Google Tag Manager. Currently, I just have one tag with Enhanced Ecommerce enabled, and 'Use datalayer' enabled. I do get most data into Google Analytics, but in the Product Performance report, data like cart/detail and purchase/detail is all 0%. I feel like I am missing some events that need to be added to GTM, but I am not sure which ones, and I'm not able to find clear documentation. Should the single GTM tag with EE enabled cover everything, or should I add custom events? If so, which ones, and are there any examples available?
When you push e-commerce data to the dataLayer, you need to/should push an event as well, eg. dataLayer.push({ 'event': 'ee add to cart', // The rest of your ecom dataLayer info }) so that you can use an event tag that fires on the `ee add to cart` event and is also configured to read in the standard EE dataLayer. You should always push an event with the associated dataLayer and create event tags (or use the existing pageview tag) to capture that data. You should be able to find more examples here
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "google analytics, google tag manager, enhanced ecommerce" }
Calculate $442^{260} \bmod{616}$ using Euler's theorem I'm asked to calculate $442^{260} \bmod{616}$, using Euler's theorem. But if I am to use Euler's theorem to solve an expression on the form $a^x \bmod{n}$, then $a$ and $n$ needs to be relatively prime. How can I change the expression above so that I'll end up with an $a$ and a $n$ such that $\gcd(a,n) = 1$? I was thinking about using the Chinese Remainder Theorem to split up the expression, but since the prime factorization of $616$ is $2^3 \cdot 7 \cdot 11$, I'll always end up with an even $n$ in one of the equations.
Break the modulus into its prime power factors: $$442^{260}\equiv a\bmod8$$ $$442^{260}\equiv b\bmod7$$ $$442^{260}\equiv c\bmod11$$ $a$ is obviously zero as $442^{260}=8\cdot221^3\cdot442^{257}$. Since 442 is relatively prime to 7 and 11, Euler's theorem (actually Fermat's little theorem, as 7 and 11 are prime) can be used for $b$ and $c$: $$442^6\equiv1\bmod7$$ $$442^{260}\equiv442^{6\cdot43+2}\equiv442^2\bmod7$$ Since $442\equiv1\bmod7$: $$b\equiv442^2\equiv1^2\equiv1\bmod7$$ Meanwhile: $$442^{10}\equiv1\bmod11$$ $$c\equiv442^{260}\equiv442^{10\cdot26}\equiv1\bmod11$$ Hence we have $$442^{260}\equiv 0\bmod8$$ $$442^{260}\equiv 1\bmod7$$ $$442^{260}\equiv 1\bmod11$$ and using the Chinese remainder theorem we find that $$442^{260}\equiv1+3\cdot77\equiv232\bmod616$$
stackexchange-math
{ "answer_score": 2, "question_score": 4, "tags": "elementary number theory, modular arithmetic, totient function" }
C# syntax: Placing the interface's name in the implementation's declaration I came across some interesting C# syntax that I'm not familiar with in the source code for the Composite Application Library for WPF's `DelegateCommand<T>` class. There are some method declarations which are prefixed with the `ICommand` interface name, and they do not have accessibility modifiers specified. For example: bool ICommand.CanExecute(object parameter) { ... } What is this syntax called and where can I read more about it? I assume there's an implicit `public`, but I can't figure out what the benefit of specifying the class name is. My guess is that it might just be there for organization.
When you place a method like this, you're saying that this is the explicit implementation of the interface.aspx). You can read a good tutorial on MSDN via that link. Also, a comparison might be helpful for a full view of what this means.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "c#, syntax, interface" }
Find distance between point on tangent line and circle. Given a circle with radius r, and a tangent line segment with length a. The midpoint of line a is the point of tangency. Find the length of line segment b. I am trying to figure out an equation to solve for the length of b. I'm using javascript, but I can adapt general equations. thanks. ![enter image description here](
The Pytagorean theorem, $$ \biggl(\dfrac{a}{2}\biggr)^2 + (r - b)^2 = r^2 \quad \Rightarrow \quad b = r -\sqrt{r^2 - a^2/4} $$ if $a \leq 2r$.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "trigonometry" }
Stylistic error on the JavaScript SDK documentation page There is a small stylistic error on the JavaScript SDK documentation page. > Your application must have the client side OAuth flow enabled, and must not have **disabled** the desktop application redirect uri **disabled**. Note the redundant _disabled_. That paragraph should be more like this. > Your application must have the client side OAuth flow enabled, and must not have the desktop application redirect uri disabled.
This will be fixed in the next deploy.
stackexchange-stackapps
{ "answer_score": 1, "question_score": 4, "tags": "bug, status completed, documentation" }
Using sscanf for reading data separated by | I have to read data from a .txt file, this is a sample of the data: 1 | SMAX 0.3848 | 0.234 | 0.15 I am only interested on reading the first, third and fourth column (so I want to discard that weird SMAX 0.3848). So far I have this: while(fgets(buffer, BUFFER_SIZE, fp) != NULL) { sscanf(buffer, "%d | %*s | %lf | %lf", &id, &ra, &dec); } However it does not work, I think it is because of the "SMAX 0.3848", and I am incorrectly discarding it. My question is, how could I read this data? Note: There are many columns in my dataset, and there are other "weird data" that I will need to discard. Best regards.
The problem is the `"%*s"` it stops scanning when it finds a white space, try this1 if (sscanf(buffer, "%d |%*[^|]|%lf |%lf", &id, &ra, &dec) == 3) /* proceed to use `id', `ra', `dec' */ else /* invalid line of input */ To understand what the `"%*[^|]"` means/does read the manual page for `scanf(3)`. * * * 1Use meaningful variable names, with todays text editors it's no extra work as the autocomplete feature will help you a lot, meaningful variable names will make the program easy to understand a few months/weeks later when you get back to it for some reason (maintenance, reuse).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c, file, scanf" }
XCode Autocomplete of Int to intmax_t Can someone please help me fix this? It's getting real annoying when I'm trying to type fast and every time I declare an `Int` it tries to autocomplete to intmax_t... I'm currently using Xcode 10 Beta 4 but I checked and the issue is in Xcode 9 as well. ![xcode autocomplete example](
Do you use `intmax_t` at all? When I start typing `Int` it shows up int to autocomplete. What I've noticed is that the more you type a word and select it to autocomplete that would will show up first to auto complete. I would try selecting `Int` a few times in the autocomplete list that way it should change to recommend `Int` instead on `intmax_t`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "swift, xcode, autocomplete" }
Where is the error in the following json I have a json in following format( Its pretty long:( Please feel free to edit it in order to copy it. < and when i paste it here < to visualize it.. it throws an error I am trying to convert to this format < which is very heirachical in nature whereas my jsons are bit flat.. It says that it was expecting an EOF instead of "," How is first format different than second? Thanks Ahh.. they dont let me post without a code snippet {"name": "topic 0", "children": [{"name": "river", "size": 260462}, {"name": "water", "size": 154470}, {"name": "lake", "size": 137116}, {"name": "mountain", "size": 87756}..
< is a great site for things like this. The error is in the fact that your JSON is in the following format: { // stuff } , { // stuff } objects separated by commas are not valid json. I suspect you want this to be an array, in which case you need to surround it in `[]`: [{ // stuff } , { // stuff }]
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "javascript, json" }
How to replace any text between html tags i have text between html tags. For example: <td>vip</td> I will have any text between tags `<td></td>` How can i cut any text from these tags and put any text between these tags. I need to do it via bash/shell. How can i do this ? First of all, i tried to get this text, but without success `sed -n "/<td>/,/<\/td>/p" test.txt`. But in a result i have `<td>vip</td>`. but according to documentation, i should get only `vip`
You can try this: sed -i -e 's/\(<td>\).*\(<\/td>\)/<td>TEXT_TO_REPLACE_BY<\/td>/g' test.txt Note that it will only work for the `<td>` tags. It will replace everything between tags `<td>` (actually with them together and put the tags back) with `TEXT_TO_REPLACE_BY`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "bash, shell, sed, replace, grep" }
Why is the new Amarok prompting me for Wallet password on start? Why is the new Amarok prompting me for Wallet password on start? How can you switch it off? What is it used for anyway? Its not the kind of software that needs external passwords etc....
This is the KWalletManager checking for a last.fm password most likely. You can close the KWalletManager from the system tray, the symbol looks like this: !alt text
stackexchange-superuser
{ "answer_score": 3, "question_score": 1, "tags": "linux, debian, kde, amarok" }
Creating a nonperiodic function in mathematica I want to create a non-periodic square wave with values of 1 and -1(not necessarily alternating). For e.g. I want to convert an arbitrary array like {1,-1,-1,1,-1,1,-1} into a function. I tried using Piecewise but I don't know how to do this without typing a huge number of conditions. I also want to add the length of each stack(i.e. the duration for which it is in 1 or -1) e.g. two inputs value={1,-1,-1,1,-1,1,-1} and duration={5,6,1,2,3,8,2} Please Help P.S: The version I am using is 8.0.4.0
The edited question indicates that the function is supposed to be defined based on _two_ lists - one for the values and one for their respective durations. Here is how you could do that: vals = {1, -1, -1, 1, -1, 1, -1}; duration = {5, 6, 1, 2, 3, 8, 2}; f[v_, d_][x_] := Piecewise@ Transpose[{v, (#[[1]] <= x < #[[2]] &) /@ Partition[Accumulate[Prepend[d, 0]], 2, 1]}] Plot[f[vals, duration][x], {x, 0, 40}, ExclusionsStyle -> Automatic, Frame -> True] !piecewise The `duration` list is treated with `Accumulate` to get the absolute positions from the durations, and then a list of start and end points for the corresponding absolute intervals is created using `Partition` with an offset of `1` so that the end point of one interval is the start of the next. Then, `Piecewise` defines the whole thing as a function. To plot the function with its vertical jumps displayed as lines, I set `ExclusionsStyle -> Automatic`.
stackexchange-mathematica
{ "answer_score": 7, "question_score": 5, "tags": "functions, function construction" }
Keyboard Behavior on ContentDialog with Windows 10 Mobile (UWP) When I open a content dialog programmatically, the first objet catching the focus and the content dialog's shape was distorted. Are any way available show the keyboard on the content dialog without distort the general shape ? Thanks. **Screenshot:** ![Keyboard opened on content dialog.](
When the keyboard shows, the `ContentDialog` will adjust its height automatically. And this will cause the change of `ContentDialog`'s Content's height. So when the keyboard shows, the Content's height becomes small and the rest of the Content is blocked. If you want the keyboard shows without distorting the general shape, you can set the `MinHeight` property of `ContentDialog`. For example, you can give `ContentDialog` a large `MinHeight` like "500" <ContentDialog x:Name="contentDialog" MinHeight="500" /> Or contentDialog.MinHeight = 500; After this, when the ContentDialog adjust its height, its height will be 500 at least and if this height is large enough, it will not distort the general shape. You may set the `MinHeight` equal to ContentDialog's default height to make sure it's large enough.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, xaml, uwp, windows 10 mobile" }
Qlik Sense Drawing multi line graph I'm new to Qlik Sense. I've data from MongoDB and trying to visualize data using Qlik Sense. Data: Name Time Value Sig0 1434443400061 0.78535046693984389 Sig0 1434365571861 0.47410865876843988 Sig0 1434367800061 0.52816115795111507 Sig1 1434443400062 0.54981022370331589 Sig1 1434365571862 0.48053196850949664 Sig1 1434367800062 0.28258334531262386 How to draw Multi Line Graph? X Axis - time Y Axis - Line 1 - Sig0 Y Axis - Line 1 - Sig1 Currenty, im connecting to QV Source MongDBConenctor to load data. Any suggestions would be greatly appriciated.
The simple bit of splitting your data into Sig0 and Sig1 is done with an if statement in your measure expression. sum(if(Name='Sig0',Value)) !Add a measure Same for Sig1. That will draw this graph. You'll have to do the time to normal date conversion yourself. !enter image description here
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mongodb, linegraph, qliksense" }
Binary Serialization Namespace Change I have serialized a class which used to be in namespace Temp, but now I am deserializing inside another namespace (I mean the class which I use to fetch the objects currently resides in another namespace). I am facing the error that the Temp namespace could not be found. I have found this mapping useful: Maintain .NET Serialized data compatability when moving classes. Is there any way to just serialize the class object and not assembly info or the namespace info? (I am thinking of future change and getting rid of that mapping).
The easiest to handle this is with the `AppDomain.TypeResolve` event.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": ".net, deserialization, binary deserialization" }
Select all links and forms without jQuery How can I select all `a` and `form` tags without needing to include jQuery? I ultimately am trying to do the following: $("a").click(function { window.onbeforeunload = null; }); $("form").submit(function { window.onbeforeunload = null; }); But I really would rather not include jQuery (or even Sizzle.js), if there's a more compact way to do that.
You can use `document.querySelectorAll()` like this: var els = document.querySelectorAll( 'a' ); for( var i=els.length; i--; ) { els[i].addEventListener( 'click', function(){ window.onbeforeunload = null; } ); } Similar for the `<form>` tags. It is available in most modern browsers (caniuse.com).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery, selector, sizzle" }
Javascript find intersections given two functions I am trying today to solve for the coordinates where functions intersect. I am using the nerdarmer library right now, but it only returns only one solution out of all the possible solutions. For example, I want the code below to print -1, 0, 1 but it only outputs 0. Another example is if I want to find intersections between y = 0 and sin(x), I want the output to be ..., (-2pi, 0), (-pi, 0), (pi, 0), (2pi, 0), (3pi, 0), ... intersect("x^3", "x") function intersect(f1, f2){ var x = nerdamer.solve('f1', 'f2'); console.log(x.toString()); } Is there any way to get all the possible solutions?
You've misunderstood the syntax of nerdamer.solve The first argument is the formula or equation. The second argument is the variable to solve for. If the first argument is not an equation, it is assumed to be equal 0. In your case x^3=0. which only has the solution 0. If you want to intersect the equations you will need to set them equal to each other in the first argument. And in the second argument just specify x. (or change it to suit your needs if required). intersect("x^3", "x") function intersect(f1, f2){ var x = nerdamer.solve(f1+"="+f2, "x"); console.log(x.toString()); //outputs [0,1,-1] } Edit: In your example you also directly put the strings "f1" and "f2" into the solve function which seems to just solve f=0;
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "javascript, math, equation, solver" }
To handle special characters in SQL server database, which should be used varchar or nvarchar? I am asking a simple question that, to handle special characters in my Mobile/Tablet web app, which data types should I use? 1. Varchar 2. NVarchar 3. Text 4. NText EDIT: IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. More Detail Here Should we use nVarchar as I read somewhere that some devices, such as mobile phones, still cannot correctly handle Unicode data. Please give your expert suggestions?
1 or 2 depending on the "special characters" you'll be saving. Just depends on how "special" they are. I will say though, definitely not Text as it's deprecated. <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -3, "tags": "sql server, text, varchar, sqldatatypes, nvarchar" }
What is "Platform Toolset" setting in visual studio project I have three doubts. Anyone there for help? 1. What is the "Platform Toolset" project setting in VS project 2. Why such setting required 3. What happen, if I change the setting (v110 to v100)
It is an MSBuild property that controls the specific version of the platform toolset that you want to use. More info here: < Most likely you want to use the last stable Windows SDK. You can check the toolset that you are using looking at your Visual Studio project file (.vcxproj), looking for this XML entry: <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Driver</ConfigurationType> <DriverType>KMDF</DriverType> <PlatformToolset>WindowsKernelModeDriver8.1</PlatformToolset> </PropertyGroup>
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 28, "tags": "c++, visual c++" }
Tactics for dealing with misbehaving robots I have a site that, for regulatory reasons, may not be indexed or searched automatically. This means that we need to keep all robots away and prevent them from spidering the site. Obviously we've had a robots.txt file that disallows all right from the start. However, observing the robots.txt file is something only well behaved robots do. Recently we've had some issues with less well behaved robots. I've configured Apache to ban a few user-agents but it is pretty easy to get around that. So, the question is, is there some way to configure Apache (perhaps by installing a some module?) to detect robot-like behavior and respond? Any other ideas? At the moment all I can do is ban IP addresses based on manual inspection of the logs and that is simply not a viable long term strategy.
You can link to a hidden page that, when visited, captures the useragent and IP address of the bot and then appends one or both of them to a .htaccess file which blocks them permanently. It's automated so you don't have to do anything to maintain it.
stackexchange-webmasters
{ "answer_score": 7, "question_score": 9, "tags": "apache, web crawlers, user agent" }
How to get Centos security update notice? My system is centos 7.4. As I know, RED HAT has security-updates notice. I want to know where can I get the Centos security update notice.
A quick google search for `centos security announcments` yields this result: < After subscribing you can elect to only receive security announcements in the mailinglist options : ![enter image description here](
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "centos, centos7" }
Is there a Windows Media Player plugin to send music info to a webpage? I'm looking for a way to track my music playing on my website and am trying to find a way to post the music information, such as all the music file details (i.e. title, album, year, etc), when the song is played to a page on my website for processing. Is there a plugin for this or a way to make a plugin for this easily? Or even an alternate way of doing this?
Last.fm utilizes a service known as 'Scrobbling' which does integrate with Windows Media Player as well as most other common media players. Sign up on their website and follow the instructions to setup Windows Media Player to report what you are listening. I'm sure that you can pull your last.fm stats via RSS feed to your own site and then regurgitate the results in your own format as well.
stackexchange-superuser
{ "answer_score": 2, "question_score": 1, "tags": "windows 7, plugins, windows media player, http, tracking" }
Best database to store locations of users as they move, priority given to read & write speed? Hi Stack Overflow community, making some architectural decisions & trying to figure out the best strategy to store locations of 50k users who are moving around, in an environment where we care about read & write speed a lot, but don't mind occasionally losing data. Should one 1. use an in-memory datastore like **Redis** or **Memcached** , or 2. use **Postgres** , with an index on the user_id so that it's fast to insert & remove, or 3. use the **filesystem** directly, have a file for each user_id, and write to it or read from it to store new locations, or 4. just store the locations **in memory** , in a Python program which maintains an ordered list of (user_id, location) tuples What are the **advantages/ disadvantages** of each?
I've had tremendous luck with MySQL and SQLAlchemy. 50k writes per day is nothing. I write my logs to it, I log my _threads_ (think about that, I write logs to it and log each thread) and I process 2.5 million records per day, each generating about 100 logs each.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, postgresql, memory, redis, memcached" }
applying varnish to wood in the sun I have some wood that I want to apply varnish to. My garage is exceptionally dusty and my house is pretty bad too. My question is, is it okay to apply varnish outside in the sunshine? Will it still cure properly because the sun is now quickly drying it off. Note: I'm actually using spar urethane. It's for a sign.
Urethane doesn't "cure". It dries as the solvent (which may or may not be water) evaporates. It isn't like masonry where time and moisture are critical. There's no problem applying urethane in the sun other than the challenges it poses to the actual application. Very quick dry times mean less time to get good coverage and work out runs. Never apply heavier than a minimal thorough coat. Apply liberally, then spread well, leaving just barely a glossy appearance. Multiple thin coats are much better than heavy coats, which will sag and run.
stackexchange-diy
{ "answer_score": 2, "question_score": 2, "tags": "varnishing" }
Where does GNOME Network Manager store passwords? In Network Manager, under the Identity tab, I can enter a username and password for my OpenVPN connection. I can also enter a password for the "User private key". Both password fields have the following options: * Store the password only for this user * Store the password for all users * Ask for this password every time * The password is not required If I choose to store the password ("for this user" or "for all users") where is it stored?
Go to the `/etc/NetworkManager/system-connections/` directory, here all the connection details are saved. And use the `cat` command or any text editor as **root** to view the saved passwords. There should be a security related entry, like `[vpn-secrets]` or `[wifi-security]`. [wifi-security] auth-alg=open group= key-mgmt=wpa-psk pairwise= psk=sat004321 For VPN, [vpn-secrets] password=arnab002 The string after `psk=` is the password. I think it's the same location for all users.
stackexchange-unix
{ "answer_score": 16, "question_score": 16, "tags": "security, gnome3, openvpn, networkmanager" }
Exporting From Google Spreadsheet To XML I have a google docs spreadsheet and an XML file which is made on the base of this spreadsheet. What I need right now is a way to speed up exporting information to XML format. So I've turned to google scripts. I can currently retrieve certain cells from a spreadsheet and make string variables, however I need to save the resulting strings to an XML file using minimum amount of clicks. Is there any way to instantly make an xml file using google scripts and send it to download from the browser? The only way to save the result I've found is creating a plain text document in google drive folder, opening this document and manually copypasting it's content to my xml file. But it seems that this plain text documents do not understand tab-characters (\t) and I kinda need them to make a certain structure in my xml.
Have you looked into Content Service? You would generate the XML and serve it via Content Service, set the XML mime-type, then use downloadAsFile to tell the browser to just download the file instead of displaying it.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 9, "tags": "xml, google apps script, google sheets" }
not allowed to return a result set from a function mysql error? DELIMITER $$ DROP FUNCTION IF EXISTS `workplantype`.`FUN_STOCKINVENTRY_CHECK` $$ CREATE FUNCTION `workplantype`.`FUN_STOCKINVENTRY_CHECK` ( PONo1 VARCHAR(20), PartCode1 VARCHAR(45) ) RETURNS bool BEGIN DECLARE diff bool; set diff=false; select if(Remaining_Quantity=0.00, true, false) as diff from tblstockinventory where PONo=PONo1 && PartCode=PartCode1; return diff; END $$ DELIMITER ; how ro avoid the not allowed to return a result set from a function mysql error?
select if(Remaining_Quantity=0.00, true, false) into @diff from tblstockinventory where PONo=PONo1 AND PartCode=PartCode1; You can reduce IF() to select Remaining_Quantity=0.00 into @diff And get the same result
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "mysql" }
Appending to Pandas DataFrame with categorical columns How do I append to a Pandas DataFrame containing predefined columns of categorical datatype: df=pd.DataFrame([],columns=['a','b']) df['a']=pd.Categorical([],categories=[0,1]) new_df=pd.DataFrame.from_dict({'a':[1],'b':[0]}) df.append(new_df) The above throws me an error: ValueError: all the input arrays must have same number of dimensions Update: if the categories are strings as opposed to ints, appending seems to work: df['a']=pd.Categorical([],categories=['Left','Right']) new_df=pd.DataFrame.from_dict({'a':['Left'],'b':[0]}) df.append(new_df) So, how do I append to DataFrames with categories of int values? Secondly, I presumed that with binary values (0/1), storing the column as Categorical instead of numeric datatype would be more efficient or faster. Is this true? If not, I may not even bother to convert my columns to Categorical type.
You have to keep the both data frames consistent. As you are converting the column `a` from first data frame as categorical, you need do the same for second data frame. You can do it as following- import pandas as pd df=pd.DataFrame([],columns=['a', 'b']) df['a']=pd.Categorical([],[0, 1]) new_df=pd.DataFrame.from_dict({'a':[0,1,1,1,0,0],'b':[1,1,8,4,0,0]}) new_df['a'] = pd.Categorical(new_df['a'],[0, 1]) df.append(new_df, ignore_index=True) Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "python, pandas" }
What is the quotient space $\mathbb{R}^2/F$ where $F =a[1,1]$? What is the quotient space $\mathbb{R}^2/F$ where $F =a[1,1]$? How do you find a basis of it? What is a good way to think of it in mind?
If you meant the quotient space $\;U:=\Bbb R^2/F\;$ , then as $\;\dim U=1\;$ , you only need one non-zero vector to span it, and since $$\binom10\notin F\implies \left\\{\binom10+F\right\\}\;\;\text{is a base for the quotient space}$$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "linear algebra, quotient spaces" }
What is the fastest way to test prime number i for ruby 2.2.0? **Fastest way to test prime number for ruby 2.2.0?** def prime? ('1' * self) !~ /^1?$|^(11+?)\1+$/ end _I found this code somewhere but its not working properly someplaces_
You can use prime library. irb(main):002:0> require 'prime' => true irb(main):003:0> Prime.prime?(2) => true as @Stefan said, you can simply write 2.prime? => true
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby, primes" }
Can I cache OleDbConnection and keep it long time In static constructor I check if I can open connection with all databases and then keep a static copy of ConnectionStrings and afterwards when needed use it. Now if I create private static List < OleDbConnection > _connections; and store all the open connections as open connections? Can I use these connections till the application is on. Is there any harm in doing this?
This is already done for you by the system using connection pools. < > To deploy high-performance applications, you must use connection pooling. **When you use the .NET Framework Data Provider for OLE DB, you do not have to enable connection pooling because the provider manages this automatically.** For more information about how to use connection pooling with the .NET Framework Data Provider for OLE DB, see OLE DB, ODBC, and Oracle Connection Pooling (ADO.NET) (<
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "c#, c# 4.0, static, oledb, oledbconnection" }
Phases for mobile game development I'm currently thinking of developing chess code with multi-player facility connected and played via bluetooth. For that I need to chalk out the phases, i mean systematic modules, that I should follow to develop the game. If anyone can state it or have any link that can help it out, it would be great. Another thing I am developing this in J2ME, so can anyone give me an idea about the way to connect the game in two mobile devices through bluetooth in J2ME. I mean to say the class or file that is used to connect the gaming devices.
For the second part of your question: you need to make an SPP (serial) connection between the two devices, with one acting as a client and the other as a server; see this tutorial for more information. Then you need to create your own protocol to allow the two devices to communicate everything they need to. This will only work on handsets with JSR 82.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "java me, bluetooth" }
IBM WCS 9 - solr search index building and pre processing Working in a set up which uses IBM WCS 9 Developer in local machine. Based on the information from ibm tried building index using REST url invocation? And it failed. In previous versions we have batch files which we can execute to run preprocessing and indexing, Is this possible in wcs version 9 as well? Any one tried executing bat files in Version 9. Please share findings
On the version 9 you only have the REST call (using curl on Postman). Here is the documentation page : < I've checked on the toolkit and the binary for di-preprocess and di-buildindex files also disappeared. About your rest call failing, dit you specified the spiuser and password in the Authorization tab of postman ? Cheers
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "solr, websphere commerce, wcs" }
Node parse raw string into query params string: ?utm_campaign=My+Campaign+Name&amp;utm_medium=email I want to turn this into an object: { utm_campaign: "My Campaign Name", utm_medium: "email" } I'm trying to find a way to accomplish this with the `querystring` module but can't seem to do it. Thank you!
Your problem is the `&amp;`. It should be `&` otherwise it is treated as a regular character and not the special character separating query parameters.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, query string" }
Use RegEx to find and transform characters to capital case In **notepad++** I need to use `RegEx` transform all phone1_id, phone2_id, phone3_id in PHONE1_ID, PHONE2_ID, PHONE3_ID This `RegEx` helps me find all those `strings: phone\d+_id` but how can I transform them to capital case?
* `Ctrl`+`H` * Find what: `phone\d+_id` * Replace with: `\U$0` * _check Wrap around_ * _check Regular expression_ * `Replace all` **Replacement:** \U : Change to uppercase $0 : contains the whole match **Result for given example:** PHONE1_ID, PHONE2_ID, PHONE3_ID
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "regex, notepad++" }
Помогите разобраться с jmap В туториалах видел, что раньше по jmap -heap можно было получить в консоль информацию по параметрам кучи в процессе. В моей нынешней версии jmap так сделать нельзя, есть только jmap -dump:live,format:b,file=heap.bin , но он сохраняет данные в файл в нечитаемом бинарном формате. Как получить с помощью jmap информацию по куче именно в консоль (не в графический интерфейс) в Windows?
Нашел решение. Закрываю вопрос. В новых версиях jdk: jhsdb jmap --heap --pid <pid number>
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, jvm" }
Unexpected spacing on list-item with list-style-position: inside in Internet explorer < ,right column ordered list. HTML: <ol class="instructions"> <li> <p>För att hitta samåkningar, klicka på kartan på platsen du vill åka ifrån.</p> </li> </ol> What I believe is the relevant CSS: .instructions{ padding-left: 0; } .instructions li{ padding: 0 10px; margin: 0 0 10px 0; list-style-position: inside; font-size: 25px; } .instructions li p{ font-size: 12px; display: inline-block; vertical-align: middle; width: 360px; } In internet explorer 9, a large space is added on the right side of the "1". What can I do about this? If possible I would like to keep the html-markup.
The different browsers render slightly differently but I would personally do the following: .instructions li{ padding: 0; margin: 0 0 10px 30px; font-size: 25px; } That will display fairly close in all browsers, and if you want it closer you need to either make the font size of the 1. smaller **or** add a left margin of -XXpx to the paragraph .instructions li p{ font-size: 12px; display: inline-block; vertical-align: middle; width: 360px; margin-left:-8px; } Another alternative would be to have the numbers as a CSS sprite + background image on the li.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "html, css, internet explorer, internet explorer 9" }
Sequelizejs "isAfter" validation with other field In the Sequelize's docs, they have mention following way to restrict a date field value to after a certain date. validate: { isAfter: '2018-10-02' } But I want to perform this validation against another date field from `req.body` Like validate: { isAfter: anotherFieldName // fieldname instead of static value }
The field validators do not have access to the model instance's other properties. In order to validate that two values on an instance pass your validation check, You should make use of Sequelize's custom validate object in the model options: const SomeModel = db.define( 'some_model', { start_date: { type: Sequelize.DATEONLY, validate: { isDate: true } }, end_date: { type: Sequelize.DATEONLY, validate: { isDate: true } }, }, { validate: { startDateAfterEndDate() { if (this.start_date.isAfter(this.end_date)) { throw new Error('Start date must be before the end date.'); } } } } );
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "node.js, validation, sequelize.js" }
AWS lambda does not write logs in the CloudWatch I have made a simple **AWS lambda** and deployed it to with **AWSLambdaFullAccess** permissions. There was some logs after invocation. Next day I invoked the lambda again multiple times, all executions were successful but I didn't see any new logs into **CloudWatch**. I saw some logs only after redeploy the lambda There is the code: public string FunctionHandler(string input, ILambdaContext context) { LambdaLogger.Log(input); return input.ToLower(); }
Lambda writes logs to a buffer which should be flushed after completing the lambda. But looks like for some reason lambda cannot flush it. I have notified AWS team about it few weeks ago, but the issue still not fixed.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "c#, amazon web services, aws lambda" }
How to implement the transition through the pages of the site without breaking the music using AJAX? How could i implement the transition through the pages of the site without breaking the music using AJAX? **1.** Turn on the music in the "< **2.** The music is playing **3.** Go to another page (For example, "< **4.** The music is still playing
To do that you should make `Single Page Application`. To make `Single Page Application` use `Vue`, `Angular` or `React`. I recommend you to use `Vue`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ajax" }
How show Statically a Picture With Picture Control in MFC? I Have do Follow : Drag Picture Control to dialog. Go to Picture Control propeties. Change its "Type" to Bitmap. Then I Add Bitamap ID, and Picture is showed in Picture Control, But When I Run the Program, nothing show in Picture Control. Wheres the Problem?
I used the following procedure to make this work. First: Add "Microsoft Forms 2.0 Image" Control to the ToolBox. Second: Drag a "Microsoft Forms 2.0 Image" to Form. Third: Select That and Add a Picture From Picture Properties. Is OK and Work 100 Percentage.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mfc, graphic" }
Add Bootstrap Glyphicons in Bootstrap table I'm trying to add a Glyphicon in a table cell. I'm using a Bootstrap table that has the following skeleton: <table class="table table-striped table-bordered table-hover table-condensed"> <thead> <tr> <th>#</th> <th>Firstname</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </tbody> </table> I insert the Glyphicon into one of the cells like this: <td> <span class="glyphicons glyphicons-magnet"></span> </td> However It's not working. Thank you in advance.
use <span class="glyphicon glyphicon-magnet"></span>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, twitter bootstrap" }
Is it possible to split partition on Bitlocker encrypted drive? I'm currently using Bitlocker encrypted external hard drive. It's single partition and the entire disk is encrypted. I'd like to split the single partition into two partitions while enabling Bitlocker encryption. Can it be done without turning encryption off?
No, a Bitlocker partition cannot be shrunk. You can see this in Disk Management : Right-click the partition and you will see that the "Shrink Volume..." option is gray and disabled. There is no other option than turning encryption off (waiting as required), then shrinking the partition and creating the second partition in the new unallocated space. Do NOT try to shrink the partition using any third-party product. Be sure to backup first your entire disk from inside Windows, in addition to the backup of your data. AOMEI Backupper Freeware is a good backup utility that also has a boot CD/USB for emergencies.
stackexchange-superuser
{ "answer_score": 1, "question_score": 2, "tags": "partitioning, bitlocker, disk encryption" }
Integrate the following integral using partial fractions I want to integrate $$\frac{1}{(1-u^2)^2}. $$ I have used the difference of two squares to get $$\frac{1}{2(1-u^2)} + \frac{1}{2(1+u^2)} $$ and then integrated it to get $$\frac{1}{2ln|1-u^2|} + \frac{1}{2ln|1+u^2|}.$$ > Just wondering if this is correct? thanks
If you want to use partial fraction decomposition, then note that: $$\dfrac 1{(1-u^2)^2} = \dfrac 1{[(u-1)(u+1)]^2} = \dfrac 1{(u-1)^2(u+1)^2} $$ $$= \dfrac{A}{(u-1)} + \dfrac{B}{(u -1)^2} + \dfrac{C}{(u+1)} + \dfrac D{(u+1)^2}$$ Now try solving for the needed constant terms: $A,\, B, \,C,\, D$. **Spoiler I** (to check your solutions to $A, B, C, D$) > $$A = -\dfrac 14, \;B = C = D = \dfrac 14.\quad$$ **Spoiler II** > $$\int \dfrac {du}{(1-u^2)^2} = \dfrac 14 \left(\int \dfrac{-du}{(u-1)} + \int \dfrac{du}{(u -1)^2} + \int \dfrac{du}{(u+1)} + \dfrac {du}{(u+1)^2}\right)\\\ \\\ = \dfrac 14 \left(-\ln|u - 1| - \dfrac{1}{u - 1} + \ln|u+1| - \dfrac{1}{u+1}\right) + C \\\ \\\ = \dfrac 14\left( \ln \left|\dfrac{u+1}{u-1}\right| - \dfrac{2u}{u^2 - 1}\right) + C$$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "integration" }
しとけ and sentence translation I've some trouble with the translation of this sentence: > I don't know what stands for. Could you please tell me how would you translate this sentence? Something like: > You are not going anywhere but here. Maybe?
+ Combined with , this means " ** _to choose_** ", not "to do". suggests that someone has been looking for a good/best place for something, and the speaker says that no more searching is necessary because that place has been found, which is "this" place. So, your translation is already good. literally means "Choose this place for good." **This is extremely useful at an eatery** : Me: = "What y'all having?" Girl A: = "A coffee for me." Girl B: = "I'll have an iced tea." Girl C: = "What should I have? I guess I'll have a coffee."
stackexchange-japanese
{ "answer_score": 7, "question_score": 3, "tags": "translation, contractions, subsidiary verbs" }