INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How many transactions have been included into the blockchain? This website shows the number of bitcoin transactions per day, but I want to know how many there are total. How can I do this?
As of block 210000, the total number of transactions in the chain is 9344662. Version 0.8 of the reference client keeps track of this number, and reports it for every connected block in debug.log. I just copied the number from the debug.log of a node running pre-release code.
stackexchange-bitcoin
{ "answer_score": 2, "question_score": 3, "tags": "transactions" }
Storing and retrieving strings in Multidimensional array I have the following code which stores string-input from a user N times in a multidimensional array. And then print out the second element. main() { // Array to store 10 strings, 20 characters long. char strStorage[10][20]; printf("\nEnter how many strings: "); scanf( "%d" , &num); fflush(stdin); for ( count = 0 ; count < num ; count++) { printf("Enter a string: "); gets(strStorage[count]); fflush(stdin); } printf("%s", strStorage[2]); Last line prints out garbage. The user-input is not visible inside the garbage hence either my element access is wrong or my storage is wrong. Can anyone help me with regards to what is the problem? Thanks in advance...
`strStorage[2]` is the **third** string, so if `num` is less than **3** , you won't initialize it and it will contain garbage.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c, arrays, string" }
How to easily truncate an array with JavaScript? Linq has a convenient operator method called `Take()` to return a given number of elements in anything that implements `IEnumerable`. Is there anything similar in jQuery for working with arrays? Or, asked differently: how can I truncate an array in Javascript?
There is a slice method let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] arr = arr.slice(0, 4); console.log(arr); Will return the first four elements. Don't forget to assign it back to your variable if you want to discard the other values. Note: This is just regular javascript, no need for jquery.
stackexchange-stackoverflow
{ "answer_score": 267, "question_score": 157, "tags": "javascript, arrays" }
PSQLException: ERROR: operator does not exist: character varying = uuid I have this repository: @Repository public interface DomainRepository extends CrudRepository<Domain, String> { Domain findByUuid(UUID uuid); } I have this entity: @Entity @Data @AllArgsConstructor @NoArgsConstructor @Table(name="a", schema="b") public class Domain { @Id private String id; private UUID uuid; } But when I do `Domain d = domainRepository.findByUuid(UUID.randomUUID());` I get `PSQLException: ERROR: operator does not exist: character varying = uuid` (column type in table is `VARCHAR`). How to fix this?
Try defining the type for the field as Hibernate unable to understand the type by annotating field with `@Type(type="org.hibernate.type.UUIDCharType")` @Type(type="org.hibernate.type.UUIDCharType") private UUID id;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "java, spring, postgresql, hibernate, uuid" }
Who replaced Kinsey as Vice President? In the finale of Season 8, President Hayes informs Vice President Kinsey that he should "consider [his] resignation accepted". We later see that indeed, Kinsey is no longer the vice president. Is there any indication in any canonical source who replaced him?
## We don't know / it's not confirmed / it's not relevant. There's no mention in the TV series, TV films, nor in any of the published novels regarding the identity of Kinsey's replacement. Since we know that President Hayes must have nominated a new VP almost immediately, it stands​ to reason that their identity must have been **_wholly irrelevant to the plot_**. After Kinsey's removal as VP, the President seems to have taken _personal_ control of the Stargate project, liaising directly with Stargate Command. He also personally spearheads several diplomatic projects and meets with Earth's allies, a role previously taken by the VP. My feeling was that given how disastrous Kinsey's interference proved in the Stargate Programme, it's a reasonable possibility that President Hayes may have decided to restrict the duties of the new VP to those _normally associated_ with the role. There's a possibility that they may have even have been unaware of the existence of the Stargate entirely.
stackexchange-scifi
{ "answer_score": 3, "question_score": 3, "tags": "stargate, stargate sg1" }
Perl regex groups do not display unicode characters correctly If I use the following code, the regex group does not show the expected unicode string. Can somebody explain to me whether I did a mistake, or is it even possible that it is an intrinsic problem in perl itself. echo 'éá'|perl -ne 'if ( /(\P{L}+)/ ) { print $1; }' Even if I take this explanation into account and add the UTF-8 encoding layers to perl, it still does not give me the string 'éá' for the regex group: echo 'éá'|perl -CS -ne 'if ( /(\P{L}+)/ ) { print $1,$_; }' éá The output for the group seems to be empty and includes a newline sign. Any help is much appreciated.
In your input, `éá` are 2 Unicode letters. `\P{L}` is a construct matching any character _other than_ a Unicode letter. So, using the opposite construct - `\p{L}` \- you will fix your issue. Use /(\p{L}+)/
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "regex, perl, unicode" }
Can one precompile opencl kernels for devices s/he doesn't have? We are currently investigating switching from Cuda to openCL. I have pre-built the openCL kernels like you can in Cuda (using CL_PROGRAM_BINARIES). My quick question: is it possible to compile a byte code for a device you don't have (I install the AMD driver, for example, then compile for a set of Radeon cards, despite us only having NVIDIA cards in house?) I know this would be torturous to maintain and is not suggested, I just want to know if it is currently even possible.
AFAIK AMD does support this, but as an example, you can't install the Nvidia GPU driver (which provides their OpenCL support) without an Nvidia GPU. Therefore, an Nvidia GPU is needed. Honestly, this does not seem to be an intended use case. Instead, loading and saving binaries is meant for caching a kernel so that it only gets compiled on the first time your app is run (and after any hardware changes or driver updates).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++, build, opencl" }
How can I mock an `instanceof` test? In my React code, I listen for a FocusEvent, and perform a check on the type of the element that is being focused: function onBlur(event) { if(event.relatedTarget instanceof HTMLInputElement) { /* ... */ } } This works fine. I just don't seem able to write a proper unit test for it though... I figured I'd be able to call the `onBlur` method as follows: onBlur({ relatedTarget: new HTMLInputElement() }); ...but unfortunately, that results in an error: TypeError: Illegal constructor I'm using Jest and Enzyme (which I think uses jsdom?), if that matters. How best to approach this?
Using this you can mock your element: var a = document.createElement('input') a instanceof HTMLInputElement // returns true If you need to add more behaviour then you can just add it to object a.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "javascript, reactjs, dom, jestjs, jsdom" }
VirtualBox: Unable to access "USB subsystem" I have a VirtualBox running inside a Debian Squeezy 64 bit machine. For some reason, none of my virtual machines can use the USB ports of the host machine. This error is popping up: Cant load Host USB Proxy service (VERR_FILE_NOT FOUND). The service may not be installed on host machine. Details: Result code: NS_ERROR_FAILURE (0x0004005) Component: Host Interface: IHost {--a big number here--} Receptor: IMachine {--another big number here--} It would be useful for me to use some USB devices inside my VMs (a USB drive and a printer, for example). Any help?
You need to install Virtual Box Guest Additions: $ sudo apt-get install virtualbox-guest-additions For a howto, see here.
stackexchange-superuser
{ "answer_score": 1, "question_score": 3, "tags": "usb, virtualbox, debian, debian squeeze" }
PHP: MySQL Select with multiple Where I looked mostly everywhere on Stackoverflow for adding multiple WHERE instances but none of them seem to work. My Select query: $result = mysql_query("SELECT * FROM $tableName WHERE user = $user AND column = 1"); //query I tried IN and some other ways but I dont know why it wont get the column. If I take out the user column it works, but I want it to also restrict to the column as well.. Any help will be appreciated!
`column` is reserved word in `mysql`. You have to use ``` around that kind of column_name and use `'` single quotes around string data `'$user'` SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, mysql" }
Undo all the changes done by adview I recently added an adview to my app. But dint knew anything about admob. I got an error bcz I didn't link it with admobId. So I deleted the adview from the layout. But the same error came again. I think the adview changed the scource code in many files like gradle, manifest etc. I don't know what changes shoud be undone. Help!
I got the answer. First of all delete the adview if u haven't. Secondly delete the metadata in your manifest file Thirdly open build.gradle(module:app) and delete the implementation 'com.google..........ads:... It helped me!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android studio, adview, banner ads" }
generate table in java I am trying to create table in java by taking in user input. So for the three the table should look like: I am looking for any idea on how to go about doing this - may be just pseudo code would be helpful I can fill in the blanks. Thank you for your help :)
Here is Javascript code to do what you want: var input = 3; // Read 3 from user var lines = 1 << input; var i, j; for(i = 0; i < lines; i++){ var str = ""; for(j = input - 1; j >= 0; j--){ if(i & 1 << j) str += "1"; else str += "0"; } document.write(str + "<br />"); } Here it is working: < I won't give you Java code since this is probably homework and you should try to understand it while converting it to Java. If you are unsure of the `<<` operator. Just know that `(1 << x)` means 2 to the power of x. That should help you understand it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, string" }
How could I select a column based on another column in mySQL? The following script works fine. But I want to write it in one line rather than three lines. 'Size" is passed from my main program and its used here to test. Simply I want to get Price based on size. Table columns : LISTING_ID, PRICE_LARGE_PRICE, PRICE_SMALL_PRICE. SET @Size = 'SMALL'; SELECT PRICE_LARGE_PRICE,PRICE_SMALL_PRICE INTO @PRICE_LARGE_PRICE,@PRICE_SMALL_PRICE FROM prices WHERE PRICE_LISTING_ID = 60; SET @ITEM_PRICE = (CASE @Size WHEN 'REGULAR' THEN @PRICE_LARGE_PRICE WHEN 'SMALL' THEN @PRICE_SMALL_PRICE ELSE null END); SELECT @ITEM_PRICE; Any help is appreciated.
Following may work. SET @Size = 'SMALL'; SELECT PRICE_LARGE_PRICE, PRICE_SMALL_PRICE, CASE WHEN @Size = 'REGULAR' THEN PRICE_LARGE_PRICE WHEN @Size = 'SMALL' THEN PRICE_SMALL_PRICE END AS ITEM_PRICE INTO @PRICE_LARGE_PRICE, @PRICE_SMALL_PRICE, @ITEM_PRICE FROM prices WHERE PRICE_LISTING_ID = 60;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql, select, case, case when" }
Pycharm doesn't recognize any python interpreters I have downloaded a PyCharm 2021.3 on Windows 10, and when I want to configure a python interpreter for the project, I don't have any options except . When I try to do it with the menu ctrl+Al+s python via python interpreter, I also see no available options. When I run code, it returns the first occurred exception, ModuleNotFoundError. I have python version 3.9.9 and conda installed, and they both are working perfectly fine via command prompt and Jupyter Notebook. That's how it looks: no interpreter via python interpreter menu no interpreter in edit configurations window
For me, the following worked: 1. Delete folders with the current project in the PycharmProjects directory. 2. Create a new project, clone to this new project my project from git. Then I had an option to edit configurations and select python interpreter.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, configuration, pycharm, interpreter" }
strstr() don't work in PHP I have this code in PHP with that uses the function, `strstr()`: $conversation = strstr($bash, '_'); $pseudo = strrchr($bash, '_'); //On ajoute les balises html au pseudo et a la conversation $cherche = array($pseudo, $conversation); $remplace = array("'<span class=\"pseudo\">' , $pseudo , '</span>'", "'<span class=\"pseudo\">' , $conversation , '</span><br />'"); str_replace($cherche, $remplace , $bash); echo $bash; However, `echo function display $bash` does not display any error message.
`str_replace()` RETURNS the modified string, it does not do an in-place change. $new_bash = str_replace($cherche, $remplace, $bash);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "php, strstr" }
Theoretical Physics Notation (Hamilton-Jacobi in the Relativistic Domain) I am having trouble understanding how to solve some theoretical physics problems I have come across. Specifically how to convert the Hamilton-Jacobi equation: $$(\partial_\mu S+e A_\mu)^2=m^2$$ From Minkowski-space notation to conventional form: $$(\frac{\partial S}{\partial t}+\frac{\alpha}{r})^2-(\nabla S)^2=m^2$$ where $A_0=-\frac{\alpha}{er})$ and $A_x=A_y=A_z=0$ Any help would be appreciated.
You should know that $\partial_\mu$ is shorthand for $\frac{\partial}{\partial x^\mu}$ where $x^\mu=(t,x,y,z)$. Furthermore, it can be seen from your question that the metric convention that is used is $+ - - -$, so that $x_\mu=(t,-x,-y,-z)$. Then, one can easily write out your equation. The Einstein summation convention is used. \begin{align} (\partial_\mu S+eA_\mu)^2&=m^2\\\ (\partial_\mu S+eA_\mu)(\partial^\mu S+eA^\mu)&=m^2\\\ \partial_\mu S\partial^\mu S+e^2A_\mu A^\mu+2e\partial_\mu S A^\mu&=m^2 \end{align} Your final equation follows pretty much trivially, once you set $A_0=-\frac{\alpha}{er}$ and $A_i=0$.
stackexchange-physics
{ "answer_score": 0, "question_score": 0, "tags": "spacetime, relativity, notation" }
How to remove flashlight from iPhone X lock screen? The iPhone X lock screen has two default buttons, one is Camera and other is flashlight. Is there any way to remove/customize the flashlight shortcut? I could not find any solution for it anywhere.
On iOS 11 - the flashlight is tied to the 3D Touch feature. If you turn that off in General> Accessibility>3D Touch, then the flashlight disappears. On iOS 12 - there's no known way to remove this with a setting on the phone or action short of jailbreaking (which would be a different question entirely on how to jailbreak)
stackexchange-apple
{ "answer_score": 11, "question_score": 9, "tags": "iphone, ios" }
What Web-Engines do I've aviable when developing a C# Application in Windows? I want to know what are the most popular Web-Engines to use in a Desktop Aplication using C# and WinForms. Can you suggest some ? **edit:** I've edited the question, I think it's OK now.
I would use Awesomium. It has a good .NET/WPF support.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, winforms, visual studio, visual studio 2010" }
returning null values as something else from a query SELECT TEST_CODE, TEST_MDL FROM TEST WHERE TEST_CODE LIKE 'DW-LI' OR TEST_CODE LIKE 'DW-BE' OR TEST_CODE LIKE 'DW-SC' OR TEST_CODE LIKE 'DW-V' OR TEST_CODE LIKE 'DW-CR' OR TEST_CODE LIKE 'DW-CO'; I have this query and I need to write the results to an excel file. I can do that, however when the a field is null I need the query to return null or something else instead of just a blank. I tried doing something like this: SELECT TEST_CODE, TEST_MDL, ISNULL(TEST_MDL),'null')' FROM TEST; That didn't work. Any suggestions? I am running the query from a program using vb.net and also connecting as odbc, because of some limitations. I hope this helps. Thanks!
Try this: SELECT TEST_CODE, TEST_MDL, CONVERT(varchar(20),ISNULL(TEST_MDL,'null')) FROM TEST;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, odbc" }
Different views for landscape and portrait - Xcode 6 I making a project in which i need to have one view for horizontal and the other one for vertical orientation. Also i need to have a collection view in the horizontal view and table view for my vertical view. I have been trying to found some tutorials, but without success or the solution was to old. I am using Xcode 6.
But you can implement the equivalent of a table view using a collection view. A collection view is basically a table view on steroids: more powerful, more configurable, more generic. Rather than try to implement two types of views and switch between them, a design which fits the Apple pattern would contain just a collection view, which in landscape mode displays the items in two or three columns, but in portrait mode displays just a single column. This article describes how to implement custom layouts for collection views, and it contains links to other hopefully relevant material.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "ios, objective c, xcode, layout" }
Why has AskUbuntu disappeared from the Stack Exchange sites? Browsing < I can't find AskUbuntu and calling the SE API sites route does not return anything related to Ubuntu. Do you know why?
Gah, a bad setting got out there for Ask Ubuntu. Took a while to get noticed due to caching. API should report Ask Ubuntu just like everything else now. Downstream sites (like StackExchange.com) will take a bit to catch up.
stackexchange-meta
{ "answer_score": 3, "question_score": 8, "tags": "support, status completed" }
ECSlidingDrawer theming and animation so I have an app and I have a sliding drawer on the left that can be pulled out/revealed by a button tap or a gesture. It looks like this. I wanted to animate the drawer so it had a folding animation kind of similar to this. I have looked around the internet extensively and didn't find anything. Does anyone know whether this is possible? Thanks.
The following article describes the folding animation using CATransfromLayer. I think this might help. <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, ios, animation, slidingmenu" }
Unexplicable increase in page load time I'll try to be as brief as possible; My page load time increased 40% and I don't know why, in the atttached image you have the before and after loading times, plus the waterfall view for both the first and the repeated view. The setup: LNMP VPS, opcache, memcache, joomla with T3 framework template, using joomla file caching I did the following changes (unfortunately I didn't think about testing after each individual change): -upgraded to the latest joomla, template, and template engine -compressed images -upgraded to PHP 7 (from 5.6) -everything else is the same, including using the same server for testing and having the same server load The only explanation I can come up with is that the provider is overloading their servers, making my VPS slower. Please feel free to write any insight/ideas you have. Thanks! Screenshots from webpagetest.org
After extensive testing on various other platforms, using the same setup (I even copy-pasted the config files for php, php-fpm, mysql, etc) I found out that the issue was the hosting company which seems to be overselling. Using different but identically specced hosting the page now has a first view load time of ~0,9s.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "performance, load, vps, php 7" }
Autodeleting files from repository I've deleted manually from a working folder I've working with git for pretty long time and still can figure out that. I **add** some files, I **delete** some files... When I want to commit, what do I do? #1 git add . git commit -m "123" or #2 git rm file1_I_removed git rm file2_I_removed git rm file3_I_removed git rm file4_I_removed git add . git commit -m "123" or #3 git add -u git commit -m "123" Note that most probably I don't remember exactly what files I have deleted (even thought I can use `git status` and see them), and once I've **deleted** them, I want them **to be deleted from repository** as well without trying hard like git rm file1_I_removed git rm file2_I_removed ... git rm fileN_I_removed
Try this: git add -u This command deletes all removed files, and updates what was modified. If you have new files to add to the commit after that you can always `git add .` after.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "git" }
fpaq0.cpp is supposedly a "0-order" compressor. Why does it use a context then? In < Matt Mahoney states: The simplest of these is the order 0 coder fpaq0. in < he states: An order 0 model uses no context. but in < the Predictor (model) is defined with a context: class Predictor { int cxt; // Context: last 0-8 bits with a leading 1 int ct[512][2]; // 0 and 1 counts in context cxt public: Predictor(): cxt(1) { memset(ct, 0, sizeof(ct)); } // Assume a stationary order 0 stream of 9-bit symbols int p() const { return 4096*(ct[cxt][1]+1)/(ct[cxt][0]+ct[cxt][1]+2); } void update(int y) { if (++ct[cxt][y] > 65534) { ct[cxt][0] >>= 1; ct[cxt][1] >>= 1; } if ((cxt+=cxt+y) >= 512) cxt=1; } }; Why is that?
From Matt Mahoney himself in an email: "It is bytewise order 0, not bitwise. It models byte probabilities independently one bit at a time. The bit probabilities depend on previous bits."
stackexchange-cs
{ "answer_score": 1, "question_score": 1, "tags": "data compression, encoding scheme" }
How to drop all rows of data frame after specific row number or date in R? I have a data frame with a certain number of rows. Would like to drop all rows after a specific row number or after a date. Any suggestions? Could not find anything on the web that works for me for the moment...
We can use `head` n <- 5 df2 <- head(df1, n) df2 # date col2 #1 2019-01-01 -0.5458808 #2 2019-02-01 0.5365853 #3 2019-03-01 0.4196231 #4 2019-04-01 -0.5836272 #5 2019-05-01 0.8474600 Or create a logical vector df1[seq_len(nrow(df1)) <= n, ] * * * Or another option is `slice` library(dplyr) df1 %>% slice(seq_len(n)) Or with `data.table` library(data.table) setDT(df1)[seq_len(n)] If it is based on a date value date1 <- as.Date("2019-05-01") subset(df1, date <= date1) ### data set.seed(24) df1 <- data.frame(date = seq(as.Date("2019-01-01"), length.out = 10, by = "month"), col2 = rnorm(10))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "r" }
Softlink in rc0.d is working on poweron rather than shutdown I want to run a script on poweroff in Ubuntu. so I made a script, placed it in init.d & made a softlink in rc0.d with name S36xyz. my script is working perfectly when I run it in terminal. so there is not any problem with script. But my script is executing at poweron rather than poweroff. I don’t know what I am doing wrong. Can any one help me with this.
You have to make a softlink with the name `K36xyz`. The `K` at the start stands for Kill. You used `S` which stands for Start Additionally, custom is to test `$1` within the script, as the `Sxy` links/scripts are invoked with `start` as a parameter and the `Kxy` ones with `stop`. That way you can use the same script for starting and stopping a service if you make the appropriate links. You can only do so much in such a script. E.g. postfix on my Ubuntu 12.04 system is being shut down (`/etc/rc0.d/K20postfix`) before `K36xyz`, so sending mail from such a script probably won't work as expected.
stackexchange-unix
{ "answer_score": 4, "question_score": 4, "tags": "linux, ubuntu, runlevel" }
Does "x = x = .." (double equals/assignment) mean anything special? In a server programmed in Java, I found this statement: buffer = buffer = new byte[bufferSize]; What I don't understand is that "buffer = " is stated twice. Would not this code do the exact same thing? buffer = new byte[bufferSize]; Thanks.
Java assignment (`=`) is evaluated right-to-left so, * First `buffer` is assigned to `new byte[bufferSize]` * then `buffer` is assigned to the value of `buffer` While the second statement is exactly as you'd expect. `buffer` is assigned to `new byte[bufferSize]`. It's likely the compiler would optimize this away.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "java, syntax, variable assignment" }
Retrieving user information from Parse in swift I am trying to get user information (email address) from Parse. I have tried the following code, but it displays an error, saying that "Anyobject is not convertible to String". What am I supposed to do to get the email address? Thanks in advance. //Retrieve user info from parse var query:PFQuery=PFQuery(className: "_User"); query.whereKey("objectId", equalTo: PFUser.currentUser()!.objectId!) query.findObjectsInBackgroundWithBlock{ (posts: [AnyObject]?, error: NSError?) -> Void in if !(error != nil) { let user = PFUser.currentUser() var email = user["email"] as! String } }
Since you already have a PFUser.currentUser you can just fetch that object without a query like so PFUser.currentUser()!.fetchInBackgroundWithBlock({ (currentUser: PFObject?, error: NSError?) -> Void in // Update your data if let user = currentUser as? PFUser { var email = user.email } })
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios, swift, parse platform" }
Sending POST request with AJAX which is intercepted by Burp Suite I intercepted a POST request with Burp Suite and I want to send this request manually from JavaScript Ajax call. This is my request's raw: !Burp Suite - Raw Post Request I tried to send POST request like that: <!DOCTYPE html> <html> <head> <script src=" <script> $.ajax({ type: 'POST', url: ' data: { 'csrf-token': '', 'blog_entry': 'post from ajax', 'add-to-your-blog-php-submit-button': 'Save+Blog+Entry' }; }); </script> </head> <body> </body> </html> But I couldn't manage it. Where is my mistake? Or, how should I do this? How could I convert raw request to Ajax request? Thanks!
The correct solution is: <!DOCTYPE html> <html> <head> <script src=" <script> $.ajax({ method: 'POST', url: ' data: { 'csrf-token': '', 'blog_entry': 'post from ajax', 'add-to-your-blog-php-submit-button': 'Save+Blog+Entry' }, xhrFields: { withCredentials: true } }); </script> </head> <body> </body> </html> I forgot a semicolon at the end of the data field's closing curly brace. An addition, I must add xhrFields field for bypassing cookie needing.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, ajax, post, csrf, burp" }
Left join two JSONs It is possible to JOIN, find and print not joined row on PHP two JSONs? Data looks like that: [{"column_name":"test","position":10},{"column_name":"test2","position":12},{"column_name":"test3","position":14}] [{"dbcolumnname":"test"},{"dbcolumnname":"test3"}] Ouput should looke like this: [{"column_name":"test2","position":12}] Thanks in advance for help.
This ? <? $json = '[{"column_name":"test","position":10},{"column_name":"test2","position":12},{"column_name":"test3","position":14}]'; $db_json = '[{"dbcolumnname":"test"},{"dbcolumnname":"test3"}]'; // Convert json to arrays of objects $array = json_decode($json); $db_array = json_decode($db_json); // Extract all dbcolumnnames $dbcolumnnames = array(); foreach($db_array as $v){ $dbcolumnnames[] = $v->dbcolumnname; } // Rebuild an array with $array's objects where column_name is not in dbcolumnnames $new_array = array(); foreach($array as $v){ if (!in_array($v->column_name , $dbcolumnnames)) { $new_array[]=$v; } } // echo it, json encoded : echo( json_encode($new_array) ); // will display : // [{"column_name":"test2","position":12}] ?>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "php, json" }
O que é a interpolação de quadros de vídeo (video frame interpolation)? Lendo algumas notícias me deparei com esta: Transforming Standard Video Into Slow Motion with AI ou AI da NVIDIA cria vídeos em câmera lenta sem “gravar mais quadros", em que a NVidia usou um algoritmo que transforma um vídeo normal em câmera lenta, mas suaviza os movimentos no vídeo criando/prevendo mais quadros ( _frames_ ) com interpolação e inteligência artificial. Um vídeos dos resultados pode ser visto no Youtube. Então surgiu uma dúvida, o que é a interpolação de quadros de vídeo ( _video frame interpolation_ )?
No contexto da pergunta, _video frame interpolation_ se refere à prática de geração de frames intermediários entre dois _frames_ de referência. Considere a animação abaixo: > ![inserir a descrição da imagem aqui]( Ela é composta de 3 frames, onde a localização do pixel preto cria uma ilusão de movimento. Entretanto o efeito é de baixa qualidade - você percebe o 'pulo' entre as posições. A animação abaixo possui os mesmos pixels pretos, porém outros frames são adicionados contendo pixels localizados nas posições interpoladas dos frames de referência: > ![inserir a descrição da imagem aqui]( A técnica utilizada pela NVidia, neste caso, é uma versão extremamente mais sofisticada desta prática - dados dois _frames_ as diferenças são analizadas e conteúdo interpolado é gerado.
stackexchange-pt_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "algoritmo, video" }
Regex to check if a number is even Can we have a regex to detect if a number is even ? I was wondering if we can have a regex to do this instead of usual `%` or bit operations. Thanks for replies :)
Since the correct answer has already been given, I'll argue that regex would not be my first choice for this. * if the number fits the `long` range, use `%` * if it does not, you can use `BigInteger.remainder(..)`, but perhaps checking whether the last `char` represents an even digit would be more efficient.
stackexchange-stackoverflow
{ "answer_score": 22, "question_score": 9, "tags": "java, regex" }
PHP File Upload security I have a script that upload files to my server here is my code When a user uploads a file to the server 1. My script renames the file and save the details in db. 2. I place files outside of web root. so is my approach safe?
You should do further input validation on your file, like: * check the file size * check the file type with a "File Type Recogniser" * check content header You can also check best practices for file uploads here: < Never run the file on your server. to check content type (i've never done this myself btw) you can try soemthing like: $file = "path2file"; $finfo = new finfo(FILEINFO_MIME); $type = $finfo->file($file); if(in_array($type,array("application/zip", "application/x-zip", .. whatever content types are ok...))) //you passed
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "php" }
How to scroll a ListView until I see a specific string with Calabash-Android I have exact same question as the post below, except that I need it to work for Android and the post below is for iOS. I have tried both solutions given in that post, but they don't seem to work for Android. All help is appreciated! How do i scroll a UITable view down until i see a cell with label "Value" in Calabash
you can add this new step definition and it should do the trick for Android: Then /^I scroll until I see the "([^\"]*)" text$/ do |text| q = query("TextView text:'#{text}'") while q.empty? scroll_down q = query("TextView text:'#{text}'") end end It works for me and I hope it does the same for you!
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 6, "tags": "android, calabash, calabash android" }
What to choose between 'export' and 'default export' in React? I understood that we export components to be able to import into some other file and to do so we use 'Named exports'and 'default exports', But i am indeed not sure about following things, 1.Are there any specific contexts to choose between any of them? 2.'Are named exports' and 'default exports' interchangeable?
It is mostly question of style and consistency. Rough rule of thumb might be: * If you have just one item that you would like to export from module, use default export * If you have several equally important items that you would like to export from module, use named exports * If you have several items that you would like to export, but one of them stands out by far, than use default export for that item, and named for others. One thing though, is to try to stick to your decisions, and do not try to endlessly move some items from default to named and vice versa, since code that uses your module might need updating as well.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "reactjs, react redux" }
How to find the number of pages scraped by spider I am using Scrapy in Python to scrape data from website. I successfully scraped data from website but I want to know how many pages did my spider scrape. Scrapy stats is as follow: ![enter image description here](
While `scrapy` uses `requests` to ask for a page and gets `responses` from the webserver the statistics labeled as such are informative. downloader/request_count: 421 downloader/response_count: 421 downloader/response_status_count/200: 420 downloader/response_status_count/404: 1 So `scrapy` made 421 requests and got 420 times a valid response (code 200). One time there was no reponse (code 404).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python 3.x, web scraping, scrapy, web crawler" }
Need of normalization in KNN algorithm Why normalization is necessary in KNN ? I know that this process normalizes the effect of all the features on the results but **_the 'K' nearest points to a particular point V before normalization will be EXACTLY SAME as the 'K' nearest points to that particular point V after normalization_**. So what difference does normalization make regarding Euclidean Distance. After all KNN depends completely on Euclidean Distances ? thanks in advance !
Most normalization techniques will change the 'K' nearest neighbours, if you have different variability in different dimensions. Imagine dataset of A=(-5,0), B=(-5,1) and C=(5,1). Now consider a point of interest (4.5, 0). Clearly, C is the closest neighbour. After min-max normalization to (-1,1) in both dimensions, your dataset becomes A=(-1, -1), B=(-1,1), C=(1,1). Your point of interest corresponds to (0.9, -1) in this new space. Thus, A is now the closest neighbour.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "algorithm, machine learning, normalization, knn, nearest neighbor" }
Get value from array couses "Property 'value' does not exist on type" I'm trying to pull out the data from array images. In ImageValue i have two strings: symbol and imageType. Why i get this error about property 'value'. **Error** > Property 'value' does not exist on type 'ImageValue' **Array with data** ![enter image description here]( **Component** this.props.images.filter((image) => image.value.symbol.toLowerCase().includes(this.state.searchSymbol.toLowerCase()) ).map(image => ( table.push( <div>{image.value.symbol + "." + image.value.imageType}</div> ) )); **ImageValue** class ImageValue { symbol: string; imageType: string; }
I think that you have mistaken typing the `ImageValue`: type ImageValueType { value: { symbol: string; imageType: string; } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, reactjs, react redux" }
Some songs are skipped over/broken on my iPhone; how can I find these? Sometimes when I go to play a song on my iPhone, it skips over it entirely and goes onto a song after it in the list. The same happens when I try and play it in iTunes directly from the device - it gets a exclamation-mark-circle icon to its left when I try and play. The songs have all been copied on by drag/drop from MP3 folders, so I suspect the copy process didn't completely properly. Is there a way I can find all these songs so I can re-copy them? (Trying to copy the entire album over again creates duplicate entries.)
Finally found an answer to this, thanks to Galley from iLounge! 1. Create a standard playlist called "Not Missing". 2. Drag your entire library into that playlist. Missing tracks cannot be copied to a playlist. 3. Create a smart playlist called "Missing" where: * Playlist - is not - Not Missing * _(additional to this post)_ Media type - is - Music You now have a playlist which contains only your songs with the dreaded exclamation mark, and you can re-add them from your original source.
stackexchange-apple
{ "answer_score": 2, "question_score": 3, "tags": "iphone, itunes, ios, music" }
Is there a way to know when allocated nodes become available in Slurm? sinfo only shows the current status (`alloc`, `idle`, etc) and a time limit of Slurm nodes. squeue seems only to show the jobs submitted by a user themselves, but not the jobs submitted by other users. Is there a way to know when the nodes allocated by other users would become available?
> Is there a way to know when the nodes allocated by other users would become available? The only reliable way would be to submit a job. Then Slurm can warn you by email with `--mail-type=BEGIN`. Note that `sbatch` has a `--test-only` argument that tells you when your job would run if submitted, without actually submitting a job. Also, `srun` has an `--immediate` argument that allows submitting and job and cancelling it if it does not get an allocation within a few seconds. `sbatch` has a similar parameter `--deadline` Finally, if you need an interactive session and be available when the job starts, you can submit a job with `--begin`. For instance if you want to have an interactive session at the same time the next day, submit a job the day before (assuming reasonable job length) with `--begin=now+24hours`
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "slurm" }
Remove elements from arrayList1 which are available in arraylist2 How to remove the elements of array list 1 which are avaliable from array list 2? for example ArrayList<AClass> list1 = new ArrayList<AClass>(); //AClass(int IDNumber, String date) ArrayList<Integer> list2 = new ArrayList<Integer>(); AClass a1 = new AClass(1, "20/01/2013"); AClass a2 = new AClass(2, "21/01/2013"); AClass a3 = new AClass(3, "22/01/2013"); AClass a4 = new AClass(4, "23/01/2013"); list1.add(a1); list1.add(a2); list1.add(a3); list1.add(a4); list2.add(2); list2.add(4); //remove 2 and 4 from list1, the size of the lists will be big, is there any methods or algorithms to remove them. Im expecting answer as // after removing Im expecting answer from list1 as [1,22/01/2013] [3,22/01/2013]
Use a `HashSet<Integer>` rather than a `List<Integer>`, then iterate through `list1`, and remove every element which has a num contained in the `Set<Integer>`: for (Iterator<AClass> it = list1.iterator(); it.hasNext(); ) { AClass c = it.next(); if (set.contains(c.getNum())) { it.remove(); } } A HashSet lookup is O(1), whereas a List lookup is O(N).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "java, arraylist" }
Wordpress Version 2.9.2 BUG or is it me? Has anyone noticed that in Version 2.9.2 of wordpress.org there is no facility to choose a page template? Or has the tag used in the template file changed? I hope someone can help. Thanks.
Temporarily switch to another theme and then reactivate your original theme. This does some kind of "reset" in custom templates. I've had this problem as well. Don't remember though which Wordpress version started with this bug.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "wordpress" }
Store Array of Data in a Session Variable Drupal 7 Array ( [step1] => 1 [step2] => 18 [step3] => 2000 [step4] => Array ( [crdStat] => step3-slctcrdtcrd ) [step5] => Array([cardName] => Test ) [step6] => Array([mnthSpend] => 1000 ) [step7] => Array ([payFrq] => undefined ) [step8] => Array([rolAmnt] => 344 ) Currently I am Just assigning that in PHP way $_SESSION['mcwizard'][$step]['bTransStat'] = $_GET['bTransStat']; I want to save this array in a session in Drupal 7 What is the best Drupal 7 way to achieve this. So I can use these session variable anywhere in the application. Thank You
There isn't really a Drupal way to set session variables, outside of the regular $_SESSION global. You should however be careful when choosing where to place it. If you're placing it in a Hook you need to make sure that the hook won't be cached and will always be called, otherwise your variables won't get updated every time and might be out of date. Hope this helped, sorry there isn't a Drupal way of doing this!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, drupal, drupal 7" }
Can I use my auto-generated SO gravatar in other places? I have an auto-generated gravatar as my display on SO. I wish to associate that unique, but non-descriptive, gravatar in other places (such as github). I have grown rather fond of it. Is there anyway to do this? Do I have to go to gravatar and actually sign up for an account?
Your gravatars are generated based on hashed values of your email addresses. It has been explained in details on Gravatar's Creating Hash page. 1. Trim leading and trailing whitespace from an email address 2. Force all characters to lower-case 3. md5 hash the final string As long as you keep using the same email address, you'll have the same image generated. In your case, the image is: !Image and the hashed value will be: **`e328e5547ae249f222721cba4a7010eb`**
stackexchange-meta
{ "answer_score": 2, "question_score": 2, "tags": "support, gravatar" }
Is the S is open? let $$S =\left \\{ \frac 1{3^n} + \frac 1{7^m} |n,m ∈ \mathbb N \right \\}$$. then which of the following statement is are true ? (a) S is closed (b) S is not open (c) S is connected (d) o is a limit point of S . my attempt : option D is clearly true 0 is a limit point. option(a) is not true because 0 is not contain in the set S and option (b) is not true,,as S is an open set . and option (c) is not true because $\frac{1}{3^{n}}$ is of the form rational number as rational number is not connected .. Is my answer is correct or not and pliz verified and tell me the solution...i would be more thankful
> option D is clearly true 0 is a limit point. You're right, but whether it's "clearly true" is perhaps a matter of judgment. Assuming that this is something for a class, you may well need to _prove_ that result. (But again, you are correct.) > option(a) is not true because 0 is not contain in the set S Correct. > option (b) is not true,,as S is an open set . I disagree with your assessment that $S$ is open. Note that $1/3$ is in the set, for instance, but that there is no interval $(a,b)$ such that $1/3 \in (a,b)$ and $(a, b) \subset S$. > and option (c) is not true because $\frac 1 {3^n}$ is of the form rational number as rational number is not connected .. You're right that (c) is false, but I don't know that I see a good argument for it in what you've written. I recommend returning to the definition of a connected set and showing that it is not fulfilled here.
stackexchange-math
{ "answer_score": 5, "question_score": 2, "tags": "real analysis, general topology" }
Need a css or jquery solution to expand a nested div to 100% > **Possible Duplicate:** > nested relative positioned div needs to have a 100% height I haven't figured out what needs to be done to get this < white nested div to expand to 100% height of the container size. I have tried css variations for a few hours and have nothing to show for it. Original question: nested relative positioned div needs to have a 100% height Anyone know of a solution?
This should do it in your javascript file or in a javascript block (make sure you've included jquery above this code) var h = window.innerHeight; $('div#canvas').css({'height':h+'px'});
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, css" }
how can I tell if someone printed from printPreview? Using printPreview As New PrintPreviewDialog() ' Dim x As New Printing.PrintDocument() ' AddHandler x.PrintPage, AddressOf PrintData printPreview.Document = Me.CurrentDocument If ShowPrinterSetup Then Dim x As New PrintDialog() x.Document = CurrentDocument x.ShowDialog(Anchor) End If whichPage = 0 Return printPreview.ShowDialog(Anchor) End Using So far no matter what I clicked in printpreview, the showdialog returns cancel? How can I tell if the user did print? I'd like to clear the print queue of items if they did actually print to a printer or ask them if I should clear it, but only if they actually did print something.
You can get the result of the print job from the CurrentDocument EndPrint event Private WithEvents CurrentDocument As New PrintDocument Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Using printPreview As New PrintPreviewDialog() printPreview.Document = Me.CurrentDocument printPreview.ShowDialog() End Using End Sub Private Sub document_EndPrint(ByVal sender As Object, ByVal e As PrintEventArgs) Handles CurrentDocument.EndPrint If e.PrintAction = PrintAction.PrintToPrinter Then MsgBox("Document Printed to Printer") End If End Sub
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "vb.net, printing" }
asp.net core mvc razor page css not loading on specific route I have setup a new/basic Asp.Net Core MVC project. All the CSS and JS are working fine when I am on homepage: ![enter image description here]( But when I go to some specific route like "/Role/Create", CSS and JS files are not loading correctly: ![enter image description here]( The error basically originates from jquery.min.js and I am not sure why its prepending /Role before /assets in the url. I might be missing a very small thing. Here is the complete code: <
this is because the css files path is relative to your page route not to the base path you can fix it by adding `<base href="~/">` in your layout page `_layout.cshtml` before the `<head>` tag
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, asp.net, asp.net core, bootstrap 4, razor pages" }
Combining count and distinct I am having some difficulty using COUNT and DISTINCT. I have a mysql table in the following format: phone_number language_id 100 1 200 2 100 1 100 2 200 3 How can I get the count in the following format: phone_number language_id count 100 1 2 100 2 1 200 2 1 200 3 1 Does it requires a sub-query to get the desired output? I tried combining count and distinct but still no luck, so I was wondering if anyone could help me. Thanks in advance...
Try this: SELECT `phone_number`, `language_id`, COUNT(*) AS `count` FROM `test` GROUP BY `phone_number`, `language_id`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql" }
How do you check the Gem Version in Ruby at Runtime? Is it possible to check the gem version of the currently loaded gem in a ruby/rails app? During debugging, I would like to be able to do something like: puts RubyGem.loaded_version(:active_support) Anything like that exist?
puts Gem.loaded_specs["activesupport"].version
stackexchange-stackoverflow
{ "answer_score": 80, "question_score": 49, "tags": "ruby, rubygems" }
The shape does not fit the ggmap I try to fit my shape to the google map. require(rgdal) in.dir <- getwd() sh <- readOGR(in.dir, layer = "Ytor", p4s = "+proj=tmerc +lat_0=0 +lon_0=15.80827777777778 +k=1 +x_0=1500000 +y_0=0 +ellps=bessel +units=m +no_defs") sh@proj4string sh2 <- spTransform(sh, CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +no_defs")) sh2@proj4string sh2.df <- fortify(sh2) library(ggplot2) library(ggmap) swe <- get_map(location = c(15.3, 63.63, 15.5, 63.68), maptype = 'satellite') ggmap(swe) + geom_polygon(aes(x = as.numeric(long), y = as.numeric(lat), group = group), data = df, color = "white", fill = "white", alpha = 0.1) Finally I got the map as below![enter image description here]( The borders of the shape are not going as the ggmap borders. What did I wrong that the borders does not fit?
Your projection string has no `towgs84` parameters. Assuming your data is in `EPSG:3021 RT90 2.5 gon V`, it should be: +proj=tmerc +lat_0=0 +lon_0=15.80827777777778 +k=1 +x_0=1500000 +y_0=0 +ellps=bessel +towgs84=414.1,41.3,603.1,-0.855,2.141,-7.023,0 +units=m +no_defs
stackexchange-gis
{ "answer_score": 0, "question_score": 1, "tags": "shapefile, r, ggmap" }
Connecting relay switch to GPIO I am a complete noob in this field but am trying to embark on this project to modify an old automatic pet feeder to have better control by using Raspberry Pi. Below is a picture of what is under the hood, I believe it's a motor connected to a relay. The wires go to C and NO. The grey wires on the bottom go to an on/off switch and the red and black on the left go to the power inlet. The bundle goes up to what I assume is its micro controller. I'm trying to control the motor with the Raspberry Pi with the least amount of modification. I'm wondering whether I can route the connections going to the relay to Raspberry's GPIO, or is it not as simple as that, or is it not possible to tell just by looking at this setup. ![motor and relay](
That looks like a **micro-switch** rather than a **relay**. I'd guess that the micro-controller is starting the motor at set times (or has some other way of initiating the event) and the motor runs until the micro-switch closes (which is done by the knobbly bits turning and pushing the _arm_ of the micro-switch in). **C** is `common` and **NO** is `normally open` (meaning the switch is normally open but when the arm is pushed in it closes. You will want to check the voltage on the **NO** wire both when the switch is activated and when it's not to ensure it is within the range of the GPIO pins (0v-3.3v). I'd start by driving the motor from one of the Rapberry Pi GPIO pins (via a motor driver circuit or a transistor, as the GPIO will not supply enough power). Next I'd use the micro-switch to signal to a GPIO pin (possibly via a voltage divider circuit to get the voltage in the correct range) that we have reached the desired point and stop the motor. Good luck!!
stackexchange-raspberrypi
{ "answer_score": 0, "question_score": 0, "tags": "gpio, relay" }
How to change a marker base in mapbox gl? When I add a marker to my mapbox gl script, it's positionned in a way that its center indicates the location, not the base. As a consquence, the marker seems to indicate an incorrect location. Please see the screenshot Is there a way to change the part of the image that is used as the base for the coordinates? Thanks in advance! Oktawia
Use the icon-offset layout property to offset the icon from your coordinates map.addLayer({ "id": "pointclick", type: 'symbol', source: 'pointclick', "layout": { "icon-image": "{marker-symbol}", "icon-size":1, "icon-offset": [0, -13] }, "paint": {} });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "mapbox, geojson, marker, mapbox gl" }
python 3 comprehension dictionary This is my code: def brujinGraph(k, strList): vertex = [[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0]] brujinGraph = {strList[i]: strList[j][:-1] for i in range(len(vertex)) for j in range(k) and vertex[i][j] == 1} return brujinGraph strList = ['AAGA', 'AAGA', 'AGAT', 'ATTC', 'CTAA', 'CTCT', 'GATT', 'TAAG', 'TCTA', 'TCTC', 'TTCT'] brujinGraph(4, strList) and it is throwing me an `UnboundLocalError: local variable 'j' referenced before assignment` any idea what does it means and why am I getting this error?
Without knowing exactly what vertex and strList are : Do you actually mean : {strList[i]: strList[j][:-1] for i in range(len(vertex)) for j in range(len(vertex[i])) if vertex[i][j] == 1} i.e. change that **and** into an **if**
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python 3.x" }
Java | API to get protocol://domain.port from URL I have got URL as referrer and want to get protocol and domain from it. For example: If URL is ` then output needs to be ` I have gone through ` and I can't seems to find any method that can directly do so. * * * I am not using Spring, so can't use Sprint classes (if any). * * * Guys I can write custom login to get port, domain and protocol from URL, but looking for API which already has this implemented and can minimize my time in testing various scenarios.
Create a new `URL` object using your `String` value and call `getHost()` or any other method on it, like so: URL url = new URL(" String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); // if the port is not explicitly specified in the input, it will be -1. if (port == -1) { return String.format("%s://%s", protocol, host); } else { return String.format("%s://%s:%d", protocol, host, port); }
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 12, "tags": "java" }
Find general term of a sequence .... Suppose $$a_1=2,a_2=6,a_3=12,a_4=20,....$$ be a sequence. What is $a_n$?
It could be $a_n=\sum_{k=1}^n2k=n(n+1)$. The sequence is A002378: $2, 6, 12, 20, 30, 42, 56, 72, 90, 110,\dots$. However, this is only one of the possible answers. Consider the sequence A045619, i.e. the increasing sequence of numbers that are the products of two or more consecutive positive integers. It starts in the same way 2,6,12,20, but the next one is $2\cdot 3 \cdot 4=24$. More terms are: $2, 6, 12, 20, 24, 30, 42, 56, 60, 72, 90, 110, \dots$.
stackexchange-math
{ "answer_score": 3, "question_score": -2, "tags": "sequences and series" }
Add target attribute to anchor tags without id or class I've got an input which allows users to add text with anchor tags for hyperlinks. I'd like to keep it simple for the user so all they need to enter is `<a href="www.google.com">link</a>` but would love to add a `target` attribute to the tag systematically. Is there an elegant way in JavaScript I can do this without having an ID associated with the tag? (e.g. `getElementById` wont work here). Other entries I found in stackoverflow address this but only when the anchor tag has an ID. These links will, however, always have the same parent div class.
Found a JavaScript-only way to accomplish this: var nLink = $("div.notification-popup-message > a"); nLink.click(function(e) { e.preventDefault(); window.open(this.href); }); Another method using querySelecterAll that actually adds the attribute to the HTML in the DOM: var messageLink = document.querySelectorAll("div.message > a"); $(function() { $(messageLink).attr("target", "_blank"); });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, html" }
Register New Global Scope in Laravel I want to register a new global scope in Laravel 5.7 but I got the following error: > Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_PARSE) syntax error, unexpected 'static' (T_STATIC) <?php namespace App; use Auth; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Order extends Model { use SoftDeletes; /** * Anonymous scope */ protected static function boot() { parent::boot(); static::addGlobalScope('authenticated', function (Builder $builder) { $builder->where('id_user', '=', Auth::id()); }); } } I'm using laravel 5.7 PHP 7.2
You are trying to add an anonymous global scope which is absolutely fine but you need to use Eloquent\Builder for that approach to work (this doesn't seem to fit your exact error, however, you will need this) so add the following to your class and see if the error changes!! use Illuminate\Database\Eloquent\Builder;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, laravel, laravel 5, laravel 5.7, global scope" }
Fxml file not updating in Eclipse I'm experiencing a weird behaving in **Eclipse** when working with **JavaFx** , when I modify a FXML document in SceneBuilder, I save the changes, but when I run the project, my changes don't appear, it s after I refresh the concerned **Fxml** document that the changes work when I run the application, I'm obliged to do this every time I change something using **SceneBuilder** , any explanation or solution for this problem ?
The problem is that Eclipse does NOT by default track external changes to files and when you execute an application you are not executing the stuff in the "src" folder but the one that gets copied by eclipse to your "bin" one. You can turn on active polling of sources on in the Eclipse Preferences page "General > Workspace" by checking "Refresh using native hooks or polling".
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "java, eclipse, javafx, fxml, scenebuilder" }
BehaviourSubject and CombineLatest - Weird behaviour Given the following code. EventLoopScheduler scheduler = new EventLoopScheduler(ts => new Thread(ts)); BehaviorSubject<int> subject = new BehaviorSubject<int>(0); subject .ObserveOn(scheduler) .CombineLatest(Observable.Interval(TimeSpan.FromSeconds(1), scheduler), (x, y) => x) .Subscribe(x => Debug.WriteLine(x)); subject.OnNext(1); Why does it print? 0 1 0 1 0 1 ... Instead of: 0 1 1 1 1 1 ...
First of all your output looks really strange. I would say both of them. I guess the output should be: 1 1 1 1 1 **without** `0`. This is because of the first interval value will be produced in 1 second - definitely after you call `subject.OnNext(1);` The other strage thing `BehaviourSubject<int>` \- is it the UK version of the BehaviorSubject(Of T) ? :) If you have your own `BehaviourSubject` implementation, then please extend your question with it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, system.reactive" }
PHP: serializing and unserializing string containing escaped characters How do I correctly serialize and unserialize a string containing escaped characters? Given: $data = "\'test\'"; $out= serialize($data); print_r($out); // -> s:8:"\'test\'"; The problem here is, that the string length is not accepted by unserialize: $out = 's:8:"\'test\'"'; var_dump(unserialize($out)); // -> bool(false) But if I change the string length to 6 (ignoring the escape chars): $out = 's:6:"\'test\'"'; var_dump(unserialize($out)); // -> string(6) "'test'" It unserializes correctly. What would be a good way of handling this problem?
Your test cases don't match, you're wrapping the string in double quotes in your first example and single quotes in the second, causing the escape character to be taken literally in the latter. $out = '\'test\''; is different from $data = "\'test\'"; if you do $data = "\'test\'"; $out= serialize($data); print_r($out); // -> s:8:"\'test\'"; $data = unserialize($out); print_r($data); // -> \'test\' it will work.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "php, serialization, escaping" }
How to obtain accurate accelerometer readings from phone? I am developing a game and I'm trying to use the accelerometer to detect the amount of push by the user. However, the force applied and the abrupt stopping of the phone imposes an opposite force thus nullifying the applied initial force. How do we refine the accelerometer readings? As of now, I'm getting the readings from an interval of 500 ms to get a delta of the various axis readings but still not able to get a proper solution. Any ideas/examples/suggestions? Thanks.
I would suggest you read the Accelerometer article on the Windows Phone Team blog. It covers practical issues such as smoothing accelerometer input: !enter image description here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, silverlight, windows phone 7" }
Increasing limit of FD_SETSIZE and select I want to increase FD_SETSIZE macro value for my system. Is there any way to increase FD_SETSIZE so select will not fail
Per the standards, there is no way to increase `FD_SETSIZE`. Some programs and libraries (libevent comes to mind) try to work around this by allocating additional space for the `fd_set` object and passing values larger than `FD_SETSIZE` to the `FD_*` macros, but this is a very bad idea since robust implementations may perform bounds-checking on the argument and abort if it's out of range. I have an alternate solution that should always work (even though it's not required to by the standards). Instead of a single `fd_set` object, allocate an array of them large enough to hold the max fd you'll need, then use `FD_SET(fd%FD_SETSIZE, &fds_array[fd/FD_SETSIZE])` etc. to access the set.
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 18, "tags": "c, linux, file descriptor" }
Broken Sandisk usb stick A friend of mine is afraid of losing lots of data from her lawyer work because of a broken usb stick (shown on picture below). My idea is the following: As you can see at the bottom of the stick, there are 8 copper pins. I have thought that 4 of these pins were actually the same circuit point as principal ones. If so, I could make a "bridge" and try to read the card. What do you think, am I right? do I have any chance? Do you think that some IC is also broken and there is no option to access the data? Thank for reading and sorry for my english ;) !enter image description here
There is no reason to provide same circuit points on the other side of a highly-integrated device. There can be even some electronics under the USB connector, so the part without connector may be not able to work alone. These solder points are more likely designated for SMD LEDs (and resistors for them probably). My friend attached an SMD LED to a disassembled Kingston flash drive looking similar and it really works to indicate data transmission.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "usb" }
Using Visual Studio or Resharper, can I jump to the .aspx page while in the code behind? Using Visual Studio or Resharper, can I jump to the .aspx page while in the code behind?
I guess it is F7 or Shift + F7 (that toggles between code view and design view).
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 1, "tags": "visual studio, resharper" }
How to prove $x^3$ is strictly increasing I am trying to use $f(x)=x^3$ as a counterexample to the following statement. If $f(x)$ is strictly increasing over $[a,b]$ then for any $x\in (a,b), f'(x)>0$. But how can I show that $f(x)=x^3$ is strictly increasing?
Consider $a^3-b^3$, where $a\gt b$. We want to show this is **positive**. We have $$a^3-b^3=(a-b)(a^2+ab+b^2).$$ Note that $a^2+ab+b^2$ is positive unless $a=b=0$. There are many ways to do this. For example, $$a^2+ab+b^2=\frac{1}{2}\left(a^2+b^2+(a+b)^2\right).$$ More conventionally, complete the square. We have $4(a^2+ab+b^2)=(2a+b)^2+3b^2$. **Remark:** If we are in a calculus mood, note that $$\frac{a^3-b^3}{a-b} =3c^2$$ for some $c$ between $a$ and $b$. This argument breaks down if $c=0$. But that can only happen when $0$ is in the interval $(b,a)$. That means $b$ is negative and $a$ is positive, making the inequality $a^3\gt b^3$ obvious.
stackexchange-math
{ "answer_score": 16, "question_score": 10, "tags": "calculus, monotone functions" }
synchronized method use as a mutex in java i coundn't understand an simple question, what does a synchronized method use as a `mutex` in java- a) A globally declared mutex b) A method's mutex c) A owning object's(this's) mutex can anybody elaborate this? thanks in advance
It’s option c); from Goetz et al. (2006), _Java Concurrency in Practice_: > A `synchronized` method is a shorthand for a `synchronized` block that spans an entire method body, and whose lock is the object on which the method is being invoked. (Static `synchronized` methods use the `Class` object for the lock.)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, mutex" }
Rails validation on content type not working with Paperclip I have a validation in my Rails (3.1.4) model to make sure no one tries to upload anything malicious in leiu of their profile image, but when I try to upload a jpeg, the validation is triggering. I'm using the Paperclip gem and I'm unsure if that is having an impact. validation in user.rb model validates_attachment_content_type :profile_image, :content_type => ['image/jpeg', 'image/png', 'image/gif'], :message => "Only jpeg, gif and png files are allowed for profile pictures" When I look at the properties of the jpeg locally (Windows O/S): * Item type = JPEG image * Type of file: JPEG image (.jpg) Am I doing something wrong in my validation? Also, when it triggers, it puts the model and field name before the message. Is there a way to avoid that? ie 'Profile image profile image content type Only jpeg, gif and png files are allowed for profile pictures' Thank you!
You should add `'image/jpg'` to the content type array, I think that's what you're missing.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "ruby on rails 3, content type" }
Simple question on sudo su - What is wrong with the following? [cloudera@localhost zookeeper]$ sudo su - zookeeper [cloudera@localhost zookeeper]$ whoami cloudera In response to one of the comments: [cloudera@localhost zookeeper]$ cat /etc/passwd | grep zook zookeeper:x:492:488:ZooKeeper:/var/run/zookeeper:/bin/false [cloudera@localhost zookeeper]$ cat /etc/passwd | grep cloudera cloudera-scm:x:497:498:Cloudera Manager:/var/run/cloudera-scm-server:/sbin/nologin cloudera:x:500:500::/home/cloudera:/bin/bash
You're trying to `su` to a user who's shell is `/bin/false`. `/bin/false` always exits with code 1, so you're never that user: $ sudo su - dnsmasq $ echo $? 1 If you want to start a shell with such a disabled user, use `sudo`: $ sudo -u dnsmasq /bin/bash $ whoami dnsmasq Note that `dnsmasq` usually has `/sbin/nologin` (a politer version of `false`) as the shell, so the same principle applies.
stackexchange-askubuntu
{ "answer_score": 3, "question_score": 1, "tags": "sudo" }
Warning: file_get_contents I'm currently getting errors of > Warning: file_get_contents() [function.file-get-contents]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\app\class.users.php on line 505 > > Warning: file_get_contents( [function.file-get-contents]: failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\app\class.users.php on line 505 I was wondering if anyone could help with this maybe fix the whole file make it neat. class.users.php: < Thank you :)
There is nothing to fix. The error you are getting is because the source that your script is getting data from (forum.habborp.com) doesn't seem to exist anymore. I'm not sure what kind of data used to be there, but your best/only best is to find a drop-in replacement for that or completely remove that dependence. Can't offer another solution without knowing more about your project.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, xampp, host" }
Limit of product of infinite sequences and infinite series If the limit $$\lim_{n\to \infty} n^p u_n =A \tag{1}\\\ p\gt 1;A \lt \infty$$ then I have to show that the limit of the series $\sum_{n=0} ^{\infty}u_n $ converges. I know that since $n^p$ blows up at infinity $u_n$ must somehow go to zero. I have tried the following: $$\lim_{n\to \infty} n^p u_n =A \tag{2} = \lim_{n\to \infty} n^p \cdot \lim_{n\to \infty} u_n \\\ \therefore$$ $$\lim_{n\to \infty}u_n = \frac{\lim_{n\to \infty}n^p}{A} \tag{3}$$ From there I concluded that $u_n = \frac{n^p}{A}$. Then applying the ratio test: $$\lim_{n\to \infty}\frac{u_{n+1}}{u_n} = \lim_{n\to \infty} {}\frac{(n+1)^p}{n^p} \lt 1 \tag{4}$$ but obviously this doesn't work and is wrong. I am not convinced that $(2)$ is correct because I am not sure if the limits ($\lim_{n \to \infty }n^p $ is $\infty$ ???) exist. Also $(4)$ doesn't really work I guess because the limit is probably $=1$.
First of all, you are doing a lot of illegal stuff there. (2), as you already pointed out, does not work as $n^p$ is not convergent. Then you are essentially dividing by $0$ from (2) to (3) (among another elementary mistake) and after that, you conclude $u_n = \frac{n^p}{A}$ from $\lim\limits_{n\to \infty}u_n = \frac{\lim\limits_{n\to \infty}n^p}{A}$, which is obviously not correct, either. Now for your actual question. Write $$\sum_{n=0}^{\infty}u_n = \sum_{n=0}^{\infty} \frac{1}{n^p}(n^pu_n).$$ Can you figure it out now?
stackexchange-math
{ "answer_score": 0, "question_score": 2, "tags": "real analysis, sequences and series, limits" }
Confused about Full-Subtractor truth table I'm a little confused about the 011 condition in the Full-Subtractor truth table. !enter image description here I don't get how the output can be D = 0, B = 1. Since D = A - B - C, that gives D = 0 - 1 - 1 = -2 How does a difference of 0, and borrow of 1 represent a -2? Makes no sense at all.
"How does a difference of 0, and borrow of 1 represent a -2? Makes no sense at all." That makes perfect sense, because a borrow is in effect a -1 in the next column (to the left), which has a weight twice the weight of the column we are working on. Hence when a 1 in your column represent 1, borrowing (= subtracting) 1 from the next column (to the left) represents -2.
stackexchange-electronics
{ "answer_score": 4, "question_score": 0, "tags": "digital logic" }
Color Time Series Based on The Cluster Assignment Say I have the following Time Series: `a = [1 3 1 5 1 3 5 1 5];` Now, on doing kmeans(a,3), I obtained: `b = kmeans(a,3); // [1 2 1 3 1 2 3 1 3];` based on the clusters. I now wish to plot a, so that the color for a(i) corresponds to the cluster that is has been assigned in b. Can someone show me how to do that?
This plots each point with increasing x coordinates, y coordinate equal to `a`, and the color as given by `b`: colors = hsv(max(b)); %// or use other color maps: hold on for ii = 1:length(a) plot(ii,a(ii),'marker', 'o', 'color',colors(b(ii),:)) %// option 1 end axis([0 length(a+1) min(a)-1 max(a)+1]) !enter image description here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "matlab, plot, k means" }
Here android sdk - extend pre recorded voices list I'm using Here android sdk, voice instructions for Turn-to-turn navigation. I tried pre recorded voices, they works fine, but I wonder if I can somehow extend its list and add more pre-recorded voices? Is it supported somehow record my own voice for navigation and make it work with nav manager? I know how to install additional tts voices, but interested in pre-recorded ones.
Sorry that is not supported. Only the skins HERE provides will work with the engine.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, here api" }
In-memory cache for saving strings or NSNumbers Is there any external library out there that does in-memory caching? I was just thinking of creating a `NSDictionary` with key-value stores for this if there isn't any. I know there's `EGOCache` but this does disk caching. Any ideas?
NSCache is basically like an NSDictionary with a few modifications to let you purge data based on priority etc.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "objective c, ios, caching" }
Why use CBC-MAC? Why not just apply hash function on the whole message? Why not just apply hash function on the whole message? Why convert that message into blocks and hash those blocks? To avoid collisions?
A hash function is not a MAC, although you can turn it into a MAC (see e.g. HMAC). The purpose of a MAC is message authenticity / integrity -- to prevent attackers (i.e. people who don't know the secret key) from modifying the message or forging fake messages. A hash function trivially cannot fulfill the function of a MAC, because hash functions are unkeyed -- thus an attacker can always forge fake messages because they can calculate the digest of any message as easily as the legitimate parties. With a MAC, such as CBC-MAC or HMAC, only the people who know the secret key can easily calculate the authentication 'Tag' for a given message, so if a message is sent accompanied by the correct Tag for that message then the receiver knows the message was almost certainly sent by someone who knew the key, and has not been altered (i.e. changed to a different message) in transit.
stackexchange-crypto
{ "answer_score": 3, "question_score": 1, "tags": "cbc mac" }
How to run an empty background process with a specific name? I want to have a certain process always running in the background so it will be viewable in the Task Manager of windows, with the specific name I give it. The process shouldn't do anything really, all I care about is to see the process name whenever I open the task manager and choose "processes". One way to achieve this is to copy Notepad.exe , change its name to something and then run it. The problem is I don't want to have an open window of notepad everytime I'm using the PC. I need it to run on background. If it matters, I have Windows 7. Thank you.
You are looking for something like this: #include <windows.h> int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { MSG msg; while (GetMessage(&msg, NULL, 0, 0)) return 0; } This is the most simple Windows program. It does absolutely nothing and does not consume CPU. I can't imagine why you want it, but this is what you describe!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "windows, process, taskmanager" }
How to avoid DuplicateProjectException exception Hy, I have a multi-module maven project. I use to create these projects with Talend studion. I try to create a CI/CD build flow in MS Azure devops based on the Talend studion generated code. The generated maven poms are look like: Parent pom: <Modules> <Module>Project A<Module> <Module>Project B<Module> </Modules> Module A pom: // no reference to other module Module B pom: <Modules> <Module>Project A<Module> <Module>pom-control-bundle.xml<Module> <Module>pom-feature.xml<Module> </Modules> When I try to queue with MS Azure devops, I encounter this error message: DuplicateProjectException : Project A is duplicated in the reactor @ Any idea, what should I configure to solve this problem?
I just recognised no need to build the whole project but the subproject. In Talend, you create jobs, services, route, and they are separated java projects. If they will publish somewhere you need to upload the job, service, route, not the whole project. So, I need to run the build flow on the job, service, route. So I need to point on the job's -also service, route, etc...- pom.xml not the parent project's pom.xml. So you can avoid this error above, if you build the modules separate.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, maven, continuous integration, azure devops, talend" }
Jupytext pre-commit config when notebooks are ignored in git My current hook looks like this: - repo: local hooks: - id: jupytext name: jupytext entry: jupytext language: conda files: '^notebooks/(.*\.py|.*\.ipynb)$' args: [--sync, --pipe, black] The directory structure is like this: . notebooks dataset-exploration 01-amplitude-exploration amplitude_exploration.ipynb [other folders]* I have `*.ipynb` in my `.gitignore` file, which means that notebooks are ignored (because of git size issues), but I want pre-commit to automatically create/sync python scripts and their paired notebooks in each commit. But apparently because my hook is not working as intended, and no `*.py` file is being generated (or synced) from my `*.ipynb` files.
`pre-commit` only operates on checked in files -- since yours are gitignored you'll need to find some other way to synchronize them one idea is to `always_run: true` and `pass_filenames: false` and list the notebooks to sync explicitly: - repo: local hooks: - id: jupytext name: jupytext entry: jupytext --sync --pipe black notebooks/foo.ipynb notebooks/bar.ipynb language: conda always_run: true pass_filenames: false though this kind of defeats the purpose of the framework (you'd always run the slow operation all the time) * * * disclaimer: I created pre-commit
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "git, pre commit, pre commit.com" }
Does GAE ProtoRPC support json data field for request I am doing development on python and GAE, When I try to use ProtoRPC for web service, I cannot find a way to let my request contain a json format data in message. example like this: request format: {"owner_id":"some id","jsondata":[{"name":"peter","dob":"1911-1-1","aaa":"sth str","xxx":sth int}, {"name":...}, ...]}' python: class some_function_name(messages.Message): owner_id = messages.StringField(1, required=True) jsondata = messages.StringField(2, required=True) #is there a json field instead of StringField? any other suggestion?
What you'd probably want to do here is use a MessageField. You can define your nested message above or within you class definition and use that as the first parameter to the field definition. For example: class Person(Message): name = StringField(1) dob = StringField(2) class ClassRoom(Message): teacher = MessageField(Person, 1) students = MessageField(Person, 2, repeated=True) Alternatively: class ClassRoom(Message): class Person(Message): ... ... That will work too. Unfortunately, if you want to store arbitrary JSON, as in any kind of JSON data without knowing ahead of time, that will not work. All fields must be predefined ahead of time. I hope that it's still helpful to you to use MessageField.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "google app engine, protorpc" }
How to extend function in another anonymous function? All I have following code: (function($,undefined){ function Abc(){ function sayHello(){ console.log("I am Abc"); } } })(jQuery); And my question is, how can I add more methods to `Abc` or overwrite `sayHello`? Thanks!
You can't. It's a local variable, private to that invocation of `Abc`. It cannot be overridden if `Abc` is written that way. If you were actually making methods, perhaps like this: function Abc() { this.sayHello = function() { console.log("I am Abc"); }; } Then you could extend and override it like so: function Cba() { Abc.apply(this, arguments); this.sayHello = function() { console.log("I am Cba"); }; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery" }
Is there a freely downloadable LEGO set and part dataset? I'm working on a project that will require a list of all sets including all of the parts they contain. I'm aware of at least three sites which have this information (Peeron, BrickLink, and Rebrickable), but I haven't been able to find a way to download all of this data easily. The closest thing I have been able to find so far is the Brickset API, but Brickset only has a limited amount of set metadata (year, theme, part count, etc) and does not seem to have a full listing of parts contained in each set.
I wasn't able to find anything like this, so I contacted the admins of the sites that I mentioned in the question. Rebrickable was kind enough to send me a dump of their set inventories under a Creative Commons 3.0 BY-SA license, which basically means that you can do whatever you want with the data as long as Rebrickable is acknowledged as the source and you share any updates that you make. I've created an archive which contains a spreadsheet for each set that was in the dump that I received. Hopefully this is useful to someone else. Lego Set Inventories as of March 2014 Update: The raw data that I used to create these spreadsheets is now available directly from Rebrickable and is updated monthly there. I also maintain software to build an SQLite database from these dumps.
stackexchange-bricks
{ "answer_score": 22, "question_score": 25, "tags": "set database" }
Classic ASP : Capture Errors Is it possible to capture all 500 errors in Classic ASP at a global level? Maybe something in IIS. I'm using II6 at the moment. I like to capture the error message and then store it in the database. I know its possible in ASPX pages, but don't know exactly how you do in classic asp. Thank you
Yes, create an asp page which will log the error details to the database, and set this to be the 500 handler page in IIS as below. Use the Server.GetLastError object to get the details of the error in your handler script. It might be a good idea to log to a text file rather than a DB in your 500 handler for resiliency. !Set Custom 500 Handler in IIS
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 7, "tags": "asp classic, custom error pages" }
Quickest way to set many variables with similar names and values in PHP I want to set 26 "counters", one for each letter of the alphabet. They have similar names, and they all start with a value of 0. There has to be a faster way to do this. Here's the code: $a_count = 0; $b_count = 0; $c_count = 0; $d_count = 0; $e_count = 0; $f_count = 0; $g_count = 0; $h_count = 0; $a_count = 0; $i_count = 0; $j_count = 0; $k_count = 0; $l_count = 0; $m_count = 0; $n_count = 0; $o_count = 0; $p_count = 0; $q_count = 0; $r_count = 0; $s_count = 0; $t_count = 0; $u_count = 0; $v_count = 0; $w_count = 0; $x_count = 0; $y_count = 0; $z_count = 0; How do I do this without taking up 26 lines?
Use an array instead. It will make your code a **lot** simpler in the long run. $counts = array_fill_keys(range('a', 'z'), 0); Demo on 3v4l.org
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "php, shortcut" }
var A == var B == 1 looking for truthy. Not working. Is it possible? Not sure this is doable, but I am looking for a truth return if, for example.. var A = 100; var B = 100; (A == B == 100) I figured this would return true. Because A == B (they are both 100) and as such, they both equal 100. But it is always false. EDIT::: Thanks, Yeah - I appreciate the repsonses.. I was hoping there was some nifty shorhand than doing (A === 100 ) && ( B === 100) etc... But thank all very much.
Either it evaluates as (A == B) == 100 or as A == (B == 100) In both cases you compare a boolean with 100. This is of course always false. You want (A==100) && (B==100) To see what is going on you might want to run the Example below as JSFiddle: var A = 100; var B = 100; alert("B == 100: " + (B == 100)); alert("A == (B == 100):" + (A == (B == 100))); alert("A == B:" + (A == B)); alert("(A == B) == 100:" + ((A == B) == 100)); alert("A == B == 100):" + (A == B == 100)); alert("(A == 100) && (B == 100):" + ((A == 100) && (B == 100)));
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 1, "tags": "javascript" }
Rails User Membership Groups I'm trying to make a application where a user belongs to multiple courses and multiple assignments belong to a course. I'm using devise for the user model. I want to be able to find all the courses a user belongs to and all the assignments their courses have.
User model: has_and_belongs_to_many :course has_many :assignments, :through => :courses Course model: has_and_belongs_to :user has_many :assignments Assignment model: belongs_to :course this requires an intermediate table CoursesUsers with columns user_id and course_id and column course_id in Assignment with this give you can do things like current_user.courses current_user.assignments some_course.assignments some_course.users (assuming there is a current_user or some_course) Read about details here: Active Record Associations Especially how to setup the has_and_belongs_to_many association
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, devise" }
Reset a user's security information (Q&A) in asp.net I want to change the user's password Question and Answer by calling the method ChangePasswordQuestionAndAnswer MembershipUser user = Membership.GetUser(userName); string password = user.GetPassword(); // error here string sQuestion = DropDownList1.SelectedValue.ToString(); string sAnswer = txtAnswer.Text.ToString(); user.ChangePasswordQuestionAndAnswer(password, sQuestion, sAnswer); But I am an administrator; I can not pass the user's password because I do not know it.
Since you are already asking the user to enter data, why not ask again for the password? Then you can use that with the same code, just setting the password to the value of a text box. string password = txtPassword.Text; An alternative is to automatically reset the password, then ask the user to change it to a better password choice: MembershipUser user = Membership.GetUser(userName); string password = user.ResetPassword(); string sQuestion = DropDownList1.SelectedValue.ToString(); string sAnswer = txtAnswer.Text.ToString(); user.ChangePasswordQuestionAndAnswer(password, sQuestion, sAnswer); The latter is not a great solution because it requires additional steps to occur after this code.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, asp.net, security, passwords, asp.net membership" }
What can be the causes of the difference in student performance? ![enter image description here]( The box-plot represents the number of programming tasks performed correctly in 30 minutes.These tasks are designed to learn basic CS concepts: sequences, loops, conditional ... Each box represents an age group: * p1 = 6 - 7 years old * p2 = 7 - 8 years old * ... * p6 = 11 - 12 years old * ... * s1 = 12 - 13 years old * s2 = 13 - 14 years old * ... * b1 = 16 - 17 years old * b2 = 17 - 18 years old When I see the results, I am surprised by the difference between p4, p5 and p6. The set of tasks was almost identical by age. The only difference is that by increasing the age they have some less start tasks. I think it may be due to the ability of reading comprehension and motor development ... Can be? Are there more factors that can influence?
There is a point, somewhere around where puberty starts but I don't think identical, in which the brain changes its structure. It is much more capable of abstraction after that point than before. Young kids don't do a lot of generalization, for example, adults do. So, perhaps the study just captures part of that. I don't have it available, but I think there is a lot of brain science around that structural change. A simple search may turn up some of it. We aren't born fully formed either in mind or body. An implication of that is that how and what you teach toddlers and youngsters isn't the same as what and how you can teach teenagers. Also, every person hits that change at a slightly different age and it isn't instantaneous any more than any other brain change is. For the youngest, make it visual and tactile, even aural.
stackexchange-cseducators
{ "answer_score": 4, "question_score": 4, "tags": "secondary education, self learning, primary school" }
How do I call a method present in root view controller from my second view controller? when iam trying to call rootviewcontroller *rootview=[rootviewcontroller alloc]; [rootview methodname]; is showing warning "root view controller may not respond"
It means that "methodname" is not a "public" (*) method of your rootviewcontroller class. You need something like @interface rootviewcontroller : baseclass { - (void) methodname; } At the moment, while rootviewcontroller _might_ respond to the message called "methodname", the compiler can't see that it does (because you've not told it so through the above). (*) Objective-C methods are all public in way C++/Java people would understand the term. I suppose I should really say "is not a method declared in the `@interface` of the class".
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone" }
Не могу устаноить Mongodb driver java Не могу устаноить библиотеку для подключения базы данных библиотека не jar. платформа А-С Кто может помоч а вот и сама библиотека Библиотека драйверя для удаленного подключения
В `build.gradle` добавьте зависимость: compile 'org.mongodb:mongo-java-driver:3.4.0-rc1'
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android, mongodb" }
How do I use file_get_contents() when the filename contains a single quote? I have to read the contents of a file with a single quote (`'`) in the file name. I have no influence on the file name, so renaming is not an option. Unfortunately, simply escaping it doesn't work, as in: $myFile = 'John\\\'s file'; $text = file_get_contents($myFile); What would be the correct way to access this file in PHP 5 on a Linux system?
You don't need to double-escape your string: $myFile = 'John\'s file'; // This works fine. $text = file_get_contents($myFile); I've just tried a similar command on my terminal: php -r "chdir('te\'st');" It works.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "php, single quotes" }
How to correctly choose work_group_size? I'm trying to do matrix multiplication with OpenCl. A is 1000x1000, B is 1000x1000, so my C=AxB is 1000x1000 also. My local_size is, for example, 14. size_t local_item_size[2] = { local_size, local_size }; I've read that the work group size it's the size of my problem. C has 2 dimensions, so I would try to set size_t work_group_size[2] = { N, N }; err = clEnqueueNDRangeKernel(dev.queue, kernel, 2, 0, global_item_size, work_group_size, 0, NULL, &event); But I get a `CL_INVALID_WORK_GROUP_SIZE`. How can I correctly choose global_item_size My pc's max work group size is 1024. Does it mean that I can't work with bigger matrices? Thanks a lot
Local size must be an exact divisor of global size. 1000x1000 is exactly divisible by 10x10 or 20x5 and similar If you insist on local size 14, you should pad your whole array to have something like 1400x1400 so it works but not exactly at the padded patches. This has wasted cycles but at least compatible for any sizes until(and including) 1400x1400. If your device has max local size of 1024, then it can handle 32x32 local size. Or 1024 in 1-D.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "opencl" }
Launch Agent with Relative Path Is it possible to execute a script in the current user's home directory with a `~/Library/LaunchAgents/` agent? I current have (not working): <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" " <plist version="1.0"> <dict> <key>Label</key> <string>com.puppies</string> <key>OnDemand</key> <true/> <key>RunAtLoad</key> <true/> <key>ProgramArguments</key> <array> <string>/bin/sh</string> <string>~/script.sh</string> </array> <key>StartInterval</key> <integer>3600</integer></dict> </plist>
Set EnableGlobbing to true: <key>EnableGlobbing</key> <true/> <key>ProgramArguments</key> <array> <string>say</string> <string>~/*</string> </array> EnableGlobbing enables expanding tildes and globs in ProgramArguments but not in Program. Tildes are expanded in WatchPaths and QueueDirectories by default.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "macos, bash" }
The sequence $\left\{ \frac{5}{n} \right\}_{n=1}^\infty$ is not monotonic, or not convergent, or bounded. Why? I recently watched a video where a Calculus instructor asked the viewers to try to come up with a monotonic, unbounded, convergent sequence, if they could, as an exercise to understand these concepts better. I came up with $$\\{a_n\\}_{n=1}^\infty = \left\\{ \frac{5}{n} \right\\}_{n=1}^\infty$$ 1. I claim it is monotonic because because the sequence is decreasing. 2. I claim it is convergent because as $n \to \infty, \, a_n \to 0$. 3. I claim it is unbounded because for every one of its members, we can always find a smaller one. However, right after the exercise, we were presented with the following theorem: > If a sequence is convergent, then it is bounded. Hence my solution must be wrong, and at least one of my claims must be false. But I'm not sure which one, or why. Is anyone able to shed some light on this?
You are correct that the sequence is monotonically decreasing. It is convergent, as you say. An upper bound is just a number that is at least as large as all the members of the sequence, and a lower bound is just a number at least as small as all the members of the sequence. $1000$ is an upper bound and $-1000$ is a lower bound, so the sequence is bounded. There are tighter bounds, $5$ and $0$, but we were not asked for the greatest lower bound and least upper bound.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "calculus, sequences and series, definition" }
How can I finish the mission High Noon? I have problems killing Pulaski in the mission High Noon. I am stuck in the desert and he flees. The only car I get is a Bandito (Buggy). I tried to shoot and crush my Bandito into his car, but somehow either he escapes or my Buggy gets destroyed. I even tried to bring a good car, but somehow I cannot find it once the mission starts. How can I finish this mission?
I recommend you use the method in the following video: > As soon as the mission starts, shoot the wheels of the car Pulaski is about to enter The mission shouldn't prove to be a problem while Pulaski escapes driving around in circles...
stackexchange-gaming
{ "answer_score": 3, "question_score": 1, "tags": "grand theft auto san andreas" }
Using symmetry of Riemann tensor to vanish components The Riemann tensor is skew-symmetric in its first and last pair of indices, i.e., \begin{align} R_{abcd} = -R_{abdc} = -R_{bacd} \end{align} Can I simply use this to say that, for example, the component $R_{0001} = 0$ because $R_{0001} = -R_{0001}$?
Yes. All the components where the first two indices are the same, or the last two indices are the same, are zero. Sometimes it is useful to think of this tensor as a $6\times6$ symmetric matrix where the “indices” are $01$, $02$, $03$, $12$, $13$, and $23$. However, don’t conclude from this that there are $6+5+4+3+2+1=21$ independent components. There are actually only $20$ because of the algebraic Bianchi identity. Note that without any of these relations between components, there would be $4^4=256$ components! So the Riemann curvature tensor is about 13 times less complicated than it might appear.
stackexchange-physics
{ "answer_score": 5, "question_score": 2, "tags": "general relativity, tensor calculus, curvature" }
CSS relative positioning I want the `.tag` element to be placed literally on top of the img tag. I've tried `position: relative` but it's not quite working as I'd like it to. I don't want the `.tag` to push the image below it. <div class="first center"> <div class='tag'></div> <img src=''/> </div>
`position: relative` on the outer div, and `position: absolute` on the ~~two elements~~ `div` inside. See here for an explantion of why this works: < **Live demo:** <
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "css" }
PreparedStatement.executeUpdate() not affecting database I want to insert values into a database table. The table has two columns: id and image. The id is an auto-increment int and the image is a blob type. Here is my code: try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, userName, password); File imgfile = new File(request.getParameter("img")); InputStream fin = new FileInputStream(imgfile); PreparedStatement pre = con.prepareStatement("insert into pictures (image) values(?)"); pre.setBinaryStream(1, fin, imgfile.length()); int done=pre.executeUpdate(); } catch(SQLException | ClassNotFoundException e) { e.printStackTrace(); } I check the database and nothing inserted. Server Output: > com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'image' at row 1
I fixed it. I changed the data type of the `image` column from `blob` to `longblob` Thanks.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "java, mysql, jdbc, insert, prepared statement" }
First movie remake of an original motion picture What is the first movie remake of another _original_ movie (wholly written for the screen, not based on a book or play)? This question is _very_ close, but not a duplicate as The Squaw Man was originally a play. No adaptations count for this question. I'm looking for the first truly remade "original" movie. Example: Intermezzo (1936) seems to have an original screenplay co-written by director Gustaf Molander which was remade in 1939 as a David O. Selznick production. This is the one to beat, I guess. (I was thinking The Man Who Knew Too Much, 1934, 1956, until I remembered this one.) I'm not looking for shorts, like Our Gang or the like, but a feature. I don't want to get too bogged-down by run-times, just use your best judgement here as to what constitutes feature-length. (Even back in 1936, Intermezzo was 93 minutes long. Don't pick something _too_ short, okay?)
The movie _Forbidden Fruit_ from 1921 is the earliest remake of an original movie that I could find. The film is 87 minutes in length). > **Forbidden Fruit** is a 1921 American drama film directed by Cecil B. DeMille. It is a remake of the 1915 film **The Golden Chance** , which was also directed by DeMille. The movie was an original story, written by Cecil B. DeMille and Jeanie Macpherson.
stackexchange-movies
{ "answer_score": 5, "question_score": 4, "tags": "cinema history, remake" }