INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How do these buttons work? ![This is a picture of a metal dome switch taken off of the PCB it's mounted on.]( I can see traces that connect the corners of where the button is mounted, but it seems to me then that the contacts should be always connected via the metal dome button. There's nothing in the middle on the PCB where the button makes contact whenever it's actuated. Could someone explain to me how these particular switches work? Thanks!
Notice that the top two contacts (1, 3) in your picture are not connected to the bottom two contacts (2,4). Presumably the switch connects between those two points. They could be surface mount membrane switches. A membrane switch is basically two conductors separated by a thin membrane that keeps them apart until they are pressed together by an external force. This is what is used by most devices that have flat plastic keypads, like a microwave oven. Another possibility is that they are capacitance based, and pressing down the dome increases the capacitance, thus causing the trigger. You might be able to figure this out by looking at the chip they are connected to. Some MCUs have built in capacitance switch circuitry and there are also dedicated capacitance switch controllers.
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "pcb, switches, button" }
Mesh convergence and its affect on results Let’s say I had a mesh with 10000 nodes, then made another with 13000 nodes, why would the finer one give me slightly different results to the other even if it appears like results converged? Also, why do results vary lots before they converge? Why don’t they converge straight away?
Remember that you are trying to approximate real solution using simple shape functions. Depending on the problem, you may need to use lots of elements to be able to describe the solution with sufficient accuracy. It is a feature of FEA that if your model is correct, the value you are trying to calculate should converge to the exact solution when you are refining the mesh. Just try "mesh convergence". When you right click on a result in the tree, you can add "convergence" to it and ANSYS will try to refine the mesh automatically. Regarding varying results before convergence in nonlinear analysis, ANSYS uses Newton method and especially in cases where the load step is big, the method may make a lot of wrong guesses all over the place. After a certain number of iterations, where solution has not been found, this is stopped, the load step is halved (bisection) and Newton method starts again.
stackexchange-engineering
{ "answer_score": 0, "question_score": 0, "tags": "mechanical engineering, ansys, meshing" }
How to reference parent model from Carrierwave Uploader object I want to run some methods after the upload of a file has been completed via Carrierwave. Carrierwave includes several callback methods detailed here. I'm planning on using the :store callback. That's great, but it requires me to run the callback method in the Uploader object instance. This isn't the end of the world, but I want to keep all the logic inside of my parent Model. **My question is: How should I be referencing the parent model from the Uploader? I don't see anything obvious in the documentation?** I suppose I could do something like ParentModel.last.call_my_method_here but this seems like a very brittle way to code this (not expecting a lot of requests, but still).
I guess the `model` variable is what you were looking for, see examples using it here
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 4, "tags": "ruby on rails, ruby, ruby on rails 3, rubygems, carrierwave" }
Lightning Wait Component Is there a lightning component that loops or waits for a record to be updated? I want to make a lightning component that is checking to see if this record has a field populated after a API call that is called from another process. The flow I want to do, lightning component loads, checks field, waits checks again, then once populated does something else. I found this documentation but it shows that it's depreciated and I don't understand it enough to know what to search for next. Is there a keyword or concept to search about this?
I think you should use Change Data Capture to wait for Record Updates. Salesforce Guide on CDC < LWC component to work with Streaming API ( CDC too) < use `/data/SObject__ChangeEvent` to subscribe to it
stackexchange-salesforce
{ "answer_score": 2, "question_score": 0, "tags": "lightning aura components" }
What does Source values in Acquisition table mean? I see the folowing values in Acquisitions table on the Android app dashboard: 1. google-play 2. (direct) 3. google 4. (not set) Could someone please tells me what's the difference between them? Examples would be the best! Thanks.
* google-play: the conversion source is from the Google Play Store. * direct: the conversion source can't be determined by Firebase. * google: the conversion source is from AdWords campaign. The AdWords account should be linked with Firebase account. * not set: the conversion source is from AdWords campaign. The AdWords account is not linked with Firebase account.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "firebase analytics" }
Review examples for all application I am using Microsoft LUIS in one of my application in which we are going to provide facility to review failed utterances/examples. Currently I am able to do this for single LUIS application using Review labeled examples API in which I provide single application id. Now I need to review labeled examples for all of my LUIS application but I didn't find any suitable API. Is there any single API in which I can pass array of application id's and get the review data? or I need to call Review labeled examples API each time?
Currently, there is no provision to review labeled examples for all of your LUIS apps using the LUIS Programmatic API. You will need to call the Review labeled examples API for each LUIS app by passing the appId to return the examples to be reviewed.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "azure, azure language understanding" }
Subgroup lattice of this cyclic group I am being asked to create the subgroup lattice of the cyclic group $Z_{90}$=$\left \langle x \right \rangle$. I went ahead and found all the factors of 90 and created the diagram below. Is it done correctly? For example should $\left \langle 3 \right \rangle$ be connected with both $\left \langle 6 \right \rangle$ and $\left \langle 9 \right \rangle$? Thank you in advance for the help!
The new one looks better, and, as far as I can tell, correct. It's also good to see that you've ordered it nicely in levels the way you have with $2, 3, 5$ on the first, $6, 9,10, 15$ on the second and $18, 30, 45$ on the third. Yes, it's supposed to be that many lines, but I think it would've been slightly less messy if you'd put $3$ between $2$ and $5$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "abstract algebra" }
Remove event with off without removing delegate I have two listenners in my code, the first one is for all elements with the attribute `data-listen-enter` in the document, I use `$(document).delegate` so new elements will listen to this event too $(document).delegate('[data-listen-enter]', 'keyup', function (e) { if (e.keyCode === 13) $($(this).data('listen-enter')).trigger('click'); }); The second one is after I open my "dinamic confirm" function, so when it shows up it listen when I press enter to confirm or cancel $(document).on('keyup', function(e){ if (e.keyCode === 13) $myConfirm.find('.myConfirm-confirm').trigger('click'); }); So when I click in confirm or cancel, it removes the event $(document).off('keyup'); But it also removes the first event that listen to all elements with the attribute `data-listen-enter`
I discovered event.namespace in jQuery I can give a name to my event so late I can specify exaclty witch one I want to remove **all elements with the attribute data-listen-enter in the document** $(document).delegate('[data-listen-enter]', 'keyup.listenEnter', function (e) { if (e.keyCode === 13) $($(this).data('listen-enter')).trigger('click'); }); **my "dinamic confirm"** $(document).on('keyup.myConfirm', function(e){ if (e.keyCode === 13) $myConfirm.find('.myConfirm-confirm').trigger('click'); }); **So when I click in confirm or cancel, it removes just the event from my dinamic confirm** $(document).off('keyup.myConfirm');
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, html, bind" }
How to set label mouse icon dynamically I create dynamic labels inside a form and want the cursor to change its style from a standard one to a pointer. At this moment code look like this: Set lbl = Me.Controls.Add("Forms.Label.1") With lbl .Caption = myArray(i) ' array of label names .Top = i * 25 '.MouseIcon = "C:\hand.cur" <- this does not work End With Unfortunatelly, this does not work.
You would need to: ... .MousePointer = fmMousePointerCustom .MouseIcon = LoadPicture("C:\hand.cur") End With
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "vba, ms word" }
Is it possible to extract elements from google maps? I want to make my final year project and for my idea I'd need the 3d buildings from google maps extracted somehow. Does google maps support this? Is it achievable ? I couldn't find anything really relevant on the internet.
I think the reason why you didn't find anything related to Google Maps is that the 3D information belongs to Google Earth. Google Maps/Earth API doesn't support this directly as far as I know. The link below describes a process to get the information, I didn't test it and it's too complex and not mine to repeat here but basically "the only way to obtain this geometry is to capture it from the systems graphics engines (directX or opengl)." : < If you google "Extracting 3d models from google Earth" you'll get more results.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, google maps, extract, feature extraction" }
How does the chip transactions happen throughout a hand on a live game? Everyone has 100$ chips on their stack. Then 10/20$ blinds are posted. Where do these blinds physically stand as they are posted, in front of the stacks, or put in the main pot in the middle. Then once someone raises or calls, or goes all in, does the chips stay in front of the players, or in the main pot, or is there a timing before the dealer collects all the raises made in a hand and put in the main pot in a batch.
Players usually place their bets (including blinds) in front of their stack, but separated from it to make clear those aren't part of the stack anymore. Most tables in casinos will have lines separating the area for the players' stack and hidden cards from the area dedicated to the pot and community cards. After each betting round, the dealer will pick all the chips and bring them to the center of the table, merging with the rest of the pot.
stackexchange-poker
{ "answer_score": 1, "question_score": 0, "tags": "live" }
Handling large Java Server project with Maven I have never worked before with Java Server development, and i need to build a large Server project with around 10 libraries. The project already uses Maven for building. I have setup the building process, and now i came to development part. (need to change a small part of the code) **Question** I am used to 5 - 10 seconds building (without rebuilding the whole project). How can i achieve that with maven? Use case: Write a line of code and test it. If there is no way to do it with maven, can i do it other way? Otherwise it is a big pain to wait 3 - 5 minutes every time i need to test the code. **Edit:** There is more than hundred linked libraries (jar), but there is around 10 projects in workspace with dependencies. mvn install takes about 5 minutes or more. There is several thousands .java files in the project and tons of resources
Tools for Hot Deployment like JRebel are able to do it without restarting the server. Otherwise you'll need to restart it, with no problem for 10 libraries I think. I usually work with 7 or 8 and you only have to wait while the server restarts, cause the deploy is automatically managed with Eclipse+m2e-wtp. If you have the project divided in multiple modules this plugin takes care about compiling only what you want and deploying it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "java, maven, build" }
Is there any "short way" to check for multiple empty fields in large tables? I have a large table with alot of column and I want to check if any column is empty The way that i aproach this is by writing the query and check very column one by one, but it is not a good practice for tables that have more than 20 columns, the query will be to long and tiring to write Select * from Table_name where `col1` = '' or `col2` = '' or `col3` = '' or `col3` = '' or `col4` = '' or `col5` = '' or `col6` = '' or `col7` = '' or ....... `col20` = '' Is there any **"Loop like"** query to loop over all columns names without writing them in the query and check them one by one? _Edit For people marked my question as duplicated:_ My question asking to check all column at once if they are Null or empty **not only one column**
You can use `WHERE` `IN()` `SELECT * FROM Table_name WHERE "" IN (col1,col2,col3...)`
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "mysql" }
get count of all related column on relationship in sqlite i have this tables: CREATE TABLE sessions( id INTEGER PRIMARY KEY AUTOINCREMENT, session_name TEXT, session_comment TEXT, session_type INTEGER, date_time TEXT) CREATE TABLE barcodes( id INTEGER PRIMARY KEY AUTOINCREMENT, barcode TEXT, session_id INTEGER, enter INTEGER, exit INTEGER, date_time TEXT) `sessions` is main table and i store some data in other table as `barcodes` with specifying `session_id` in `barcodes` table, now i want to get all column data from `sessions` with count of all `barcodes` table witch `session_id` in that equals with `sessions.id` for example: select *, count(barcodes) as cnt from sessions left join barcodes on sessions.id = barcodes.session_id
try below query SELECT *, COUNT(b.barcodes) as cnt FROM sessions s LEFT JOIN barcodes b ON s.id = b.session_id GROUP BY b.id
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sqlite" }
Stream join result default value If I join a couple of string via streams and there is nothing to join the result is an empty string like "". Is there a possibility to add a default value in case it is empty? E.g. "-" someList.stream() .filter(a -> a.getKey() != null) .map(a -> a.getKey()) .sorted() .collect(Collectors.joining(", ")); Update: I know there are other ways to do it but I just wanted to know if the default value of "" (empty string) can be overriden
String result = someList.stream() .filter(a -> a.getKey() != null) .map(a -> a.getKey()) .sorted() .reduce((a,b) -> a + ", " + b).orElse("-"); where we use reduce instead of collect. EDIT: First solution was indeed not working as expected. This one is.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java" }
How to insert an elements from vector into matrix based on array of random indexes Basicly, im trying to insert an elements from vector into matrix based on random index size = 100000 answer_count = 4 num_range = int(1e4) a = torch.randint(-num_range, num_range, size=(size, )) b = torch.randint(-num_range, num_range, size=(size, )) answers = torch.randint(-num_range, num_range, size=(size, answer_count)) for i in range(size): answers[i, np.random.randint(answer_count)] = a[i] + b[i] I tried something like c = a + b pos = torch.randint(answer_count, size=(size, )) answers[:, pos] = c But i'm certainly doing something wrong
I think you need to change the last line like this: answers[np.arange(size), pos] = c The problem lies in incorrect use of advanced indexing. To understand the difference of those indexing try printing out `answers[:, pos]` vs. `answers[np.arange(size), pos]` and you will see why the previous one does not work. `answers[np.arange(size), pos]` selects each `pos` with **a single row** while `answers[:, pos]` selects **ALL rows** with each `pos`. More information on advanced indexing in numpy doc here.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, arrays, numpy, torch" }
Comparing string array xml I'm trying to take two "string array" from XML file, and make a guessing game First of all showing random symbol on screen from string array "first" this symbol is equal "a" from the "second" and so on. User has to guess what kind of letter does that symbol refers to. Since I'm going to make a lot of these arrays, anyone has an Idea or peace of code as an example, other options are also fine. <string-array name="first"> <item></item> <item></item> <item></item> <item></item> <item></item> </string-array> <string-array name="second"> <item>a</item> <item>b</item> <item>c</item> <item>d</item> <item>e</item> </string-array>
Alternatively, you can do this: static String[] sFirst; static String[] sSecond; static void load(final Context context) { sFirst = context.getResources().getStringArray(R.array.first); sSecond = context.getResources().getStringArray(R.array.second); } // Somewhere along the way, an index from the first array is chosen. int selected = 0; String weirdLetter = sFirst[selected]; String normalLetter = sSecond[selected]; // Do stuff with both letters
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, arrays, string" }
Comparing in data in excel Anybody knows how to compare data in two columns in excel? This is the conditions, if `column R = Column S` result should be `PASSED`, else if `column R - Column S > 1`, result is `FAILED` and if the two column's difference is `0.01` only, it should return `Rounding Off Error`. I've already tried this one but is not working well : =IF(ROUND(R5,2)=ROUND(S5,2),"PASS",IF(ROUND(R5,2)>ROUND(S5,2),"Rounding Off Error", IF(ROUND(S5,2) > ROUND(R5,2), "Rounding Off Error","FAIL"))) In this conditions, `-100.71 - 0.00` and `100 - 0.00` it should return `FAIL`. The conditions I've done only works when this condition is met `-100.71 - 0.00`, it returns `FAILED`. But in this one `100 - 0.00`, it returns `Rounding Off Error`. Any help? Thanks in advance!
Try this: =IF(ROUND(R5,2)=ROUND(S5,2),"PASS",IF(ABS(ROUND(R5,2)-ROUND(S5,2))<=.01,"Rounding Off Error","FAIL")) Though you may want to also put in a condition when they are both empty. Because two empty cells are equal to each other and will return "PASS". To deal with that add another if at the beginning: =IF(AND(R5="",S5=""),"",IF(ROUND(R5,2)=ROUND(S5,2),"PASS",IF(ROUND(R5,2)-ROUND(S5,2)<=.01,"Rounding Off Error","FAIL"))) ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "excel" }
Sql query help, grabbing dates, counts, averages I have a table called `payhistory`, and from this table I need to grab the `Year`, `Month` when a payment was made. I then need to get an average of payments grouped by Year and then month. select AVG(totalpaid) from payhistory This table has a column called `datepaid` that is where I need to grab the date from. It has a column called `totalpaid` which is where I need to grab the average from. I then need a count of every payment within that month. And finally a column displaying which Year/Month it was from. Important columns in the table: * `number` (account number can use this to get a count) * `datepaid` (contains the date the payment was entered '2009-09-28 00:00:00.000') * `totalpaid` (contains the specific payment for that date)
This should work: select AVG(totalpaid), COUNT(number), MONTH(datepaid), YEAR(datepaid) from payhistory group by MONTH(datepaid), YEAR(datepaid)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "sql, sql server, tsql" }
Convert many files to the same encoding I would like to make sure that all of my files are correctly encoded in UTF-8 in a big project repository. Is there a tool for that or a way to do it using unix tools?
In general, there _is no way_ to do this. UTF-8 has no "magic number" or marker, so you can only prove that a file is not in UTF-8 (if it contains invalid sequences), but not that it is. You can however use a heuristic approach. What exactly works will depend on your data. One idea: * Make a list of all files that are text files and contain non-ASCII characters. The second part is easy to do using perl or similar; the first will depend on what files you have. Unix `file` will also check for non-ASCII characters, but it's less reliable (only checks start of file). * If the list is small, check files manually. Otherwise, check which are valid UTF-8 (again, perl has modules for this, or use a tool like `iconv` or `recode`). The valid UTF-8 files are _probably_ OK. The rest will have to be checked by hand (unless you know for certain how they are encoded).
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "file management, character encoding, repository" }
The path admin/content/files is missing in Drupal 8.5 I have installed Drupal 8.5 and today I realised that the tab `admin/content/files` is missing. Thanks to my backups I realized that this tab link is already missing since the 14th of March. Prior to the disappearance on the link I did not install any module. How can I solve this issue?
By mistake I’ve disabled the View that generates the page, and the only thing I needed was to enable it again, and the tab reappeared. Thanks for the support.
stackexchange-drupal
{ "answer_score": 1, "question_score": 2, "tags": "views, 8, files" }
Multiple mysql joins I have three tables that I need get information from, 1 table has the information in and the other two hold information that i need to count. so the first tables structure is: tbl_img img_id img_name tbl_comments comment_id img_id comment tbl_vote vote_id logo_id I want the results to have the count of comments and votes that relate to each logo. I have a bit of the query which is for the count of comments, but have no idea for the syntax for the second join. SELECT l.img_id, l.img_name, COUNT(c.comment_id) AS comment_count FROM tbl_images as l LEFT OUTER JOIN tbl_comments AS c USING (img_id); Can anyone help?
how about this : SELECT l.img_id, l.img_name, (SELECT COUNT(*) FROM tbl_comments c WHERE i.img_id = c.img_id ) AS comment_count, (SELECT COUNT(*) FROM tbl_vote v WHERE i.img_id = v.img_id ) AS vote_count FROM tbl_images i
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "mysql, sql, join" }
How do I add unity script settings? how do I make a script, that when attached to an object, you can change the settings of it under the script, like a number value or string?
You need to add the variables in `public` visibility. Source: Variables and the Inspector For instance: using UnityEngine; using System.Collections; public class MainPlayer : MonoBehaviour { public string myName; // Use this for initialization void Start () { Debug.Log("I am alive and my name is " + myName); } } You can now change "the settings" of the variable `myName` when attached to an object.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, unity3d" }
External jar dependcy in java, compile time vs run time Suppose you have a simple Hello world java program that uses an external user-defined class. When will you need this .jar? During compile time or during runtime? It was asked from me in a recent interview and I answered both. Later I thought that to compile we only need the class definition (i.e. method names, variable names) etc. But can we have that without a .jar?
During compilation you need either the source file of the class (and compile everything together) or the .class file (compiled file) in your build path. That can be achieved without a .jar file, as long as your external .class file does not have other dependencies as well. A jar file can be used for compile time, for runtime, or for both. It depends on what kind of dependency you have. For example, you need it during compilation, and not need it at runtime because you run your application in a managed environment (like an application server) which already has the jar (or a version of it). You needed it directly at runtime if, for example, your code does some dynamic class loading (for example `java.sql.DriverManager` does that when loading the SQL driver class). And of course, the most common case, when is needed both at compile and run-time.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java" }
Paths between 0-cells in a classifying space. II Let $\mathcal{C}$ be a small category and $X,Y$ objects within. > If $X$ and $Y$ (as $0$-cells) lie within the same path-component in $B\mathcal{C}$, can one say anything in general on how $X$ and $Y$ are related in $\mathcal{C}$? This is a follow up to this question. I had thought that maybe there might exist a morphism from one of the objects to the other, but this is false. Is it maybe true that there exists a sequence of objects $X = Z_0, Z_1, \dots, Z_n = Y$ such that there exists an arrow $Z_i \to Z_{i+1}$ or $Z_i \leftarrow Z_{i+1}$ for each $i$?
What you describe in the last paragraph is the equivalence relation of being connected on the class of objects of a category. Every category is the disjoint union of its connected components, and the classifying space preserves disjoint unions, as can be checked directly. The answer to your question is therefore: Yes. This argument also shows (as confirmed by the nlab article on connected categories) that a category is connected if and only if its classifying space is connected.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "general topology, algebraic topology, category theory, simplicial stuff" }
Referencing env variables from Elastic Beanstalk .ebextensions config files Is it posssible to reference the PARAM1 / PARAM2 etc.. container environment properties from the .ebextensions config files. If so, how? I tried $PARAM1 but it seemed to be an empty value. I want to set the hostname on startup to contain DEV, QA or PROD, which I pass to my container via the PARAM1 environment variable. commands: 01-set-correct-hostname: command: hostname myappname{$PARAM1}.com
It turns out you can only do this in the `container_commands` section, not the `commands` section. This works: container_commands: 01-set-correct-hostname: command: "hostname myappname{$PARAM1}.com" See < for more details.
stackexchange-stackoverflow
{ "answer_score": 28, "question_score": 38, "tags": "amazon web services, amazon elastic beanstalk" }
How to extend linq partial classes I need to extend a subsonic generated (using linq templates) I have created the class with the same name and namespace in the same project when I run a query like this IMBDB db=new IMBDB(); var r = (from query in db.Articles join cat in db.ArticleCategories on query.CategoryID equals cat.ID where query.ID == articleId select new Article() { CategoryName = cat.Description, ID = query.ID }); return r.SingleOrDefault(); //The CategoryName is created in the extended partial class is always null //while the generated sql is as expected SELECT [t0].[ID], [t1].[Description] FROM [dbo].[Articles] AS t0 INNER JOIN [dbo].[ArticleCategories] AS t1 ON ([t0].[CategoryID] = [t1].[ID]) WHERE ([t0].[ID] = 40) Any ideas how to correct this? Thanks
There's a really annoying bug that I think I have a patch for - long story short I took a patch over the last few months that hosed projections and I have no idea where the bug is in the sea of Linq crazy-code. Yes, this makes me very anxious in case you're wondering. I had a nice person send me an email with code file attachments (instead of a patch) and I need to diff them, I'm just flat out of time. However I think that the issue has been addressed in a recent patch as well. So, if you download the latest source it may very well be fixed. If not - then I need to get that damn patch put in place and push 3.0.4 pronto.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, linq, subsonic" }
Google cast , what jar file are these located in? I am attempting to build and run an android google cast example. I can't seem to figure out which jar these import are located in. import com.google.android.gms.cast.ApplicationMetadata; import com.google.android.gms.cast.Cast; import com.google.android.gms.cast.Cast.ApplicationConnectionResult; import com.google.android.gms.cast.CastDevice; import com.google.android.gms.cast.CastMediaControlIntent; import com.google.android.gms.common.api.ResultCallback;
these are part of Google Play Services library, you should download the latest one with the Android SDK Manager in ADT Tools edit: they will be available in revision 15
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, android, google cast" }
Firebase auto generated UID changed? I am using firebase for login and auth, and was using $createUser. For the first couple weeks working on my app the users I created were being generated with an UID like 'simplelogin:83'. Today, I am working on my app and users are being created with an UID that looks more like a GUID. Did something change on firebases' end? Can I control how that gets generated?
The format has indeed changed from `<provider>:<id>` into a single opaque UUID. For more information see this post where the change was announced. There is no way for you to control the format of the user ids for your app. If you're having trouble adapting your code to the new format, reach out to [email protected].
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "firebase" }
Segue passing uiimage and open in UIwebview I would like to passing a uiimage from one view to another view which contains a uiwebview. So that i can allow easy interaction and gestures on the image. But i have no idea how to code in the viewdidload method should be used. Here is my code: //first view - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"showbig"]) { bigpic *image = [segue destinationViewController]; image.bigpicture1 = set11.image; } //new view - (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:bigpicture1]; NSURLRequest *requestURL = [NSURLRequest requestWithURL:url]; [self.bigpicture loadRequest:requestURL]; }
In the destinationViewController you should have a property `UIImage *imageThatIShouldDisplay` In your sourceView controller `prepareForSegue` method you will have something like this: if ([segue.identifier isEqualToString:@"showbig"]) { YourDestiantionVC *vc = (YourDestiantionVC*)[segue destinationViewController]; vc.imageThatIShouldDisplay = set1.image; } In your destiantion view controller `viewDidLoad` method you will have: if(self.imageThatIShouldDisplay != nil) { imageViewThatHandlesImageDisplay.image = self.imageThatIShouldDisplay; } else { imageViewThatHandlesImageDisplay.image = [UIImage imageWithName:@"my_image_placeholder.png"]; // in case you want a placeholder. }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone, ios, xcode, uiwebview" }
Select join tables conditionally i have three tables A, F, R Table A ----- id | type | user_id Table F ----- id | Title Table R ----- id | Title In A there is a column `Type` which can only contain values `f` or `r`. Now i want to select and join the three tables conditionally, joining rows from A to R if column value `Type` in A is `r` and joining rows from A to F if column `Type` in A is `f` I tried SELECT a.*,f.* FROM `A` a INNER JOIN F ON F.type= a.type AND a.type = 'f' INNER JOIN R ON F.type= a.type AND a.type = 'r' I get am empty row
You are close, but need to change to a LEFT-JOIN and use coalesce... if the first value is null, it grabs from the other table... But your sample structures don't really match as you are not showing a "TYPE" column in the "F" and "R" tables. SELECT a.*, COALESCE( f.title, r.title ) as WhichTitle FROM `A` a LEFT JOIN F ON a.type = F.type LEFT JOIN R ON a.type = R.type where a.type = 'f' or a.type = 'r' However, that said, if you can also supply some sample data to show context of each table and what you expect, would help.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, left join" }
Добавленеи и удаление из массива Есть ли метод или как можно сделать за минимальное количества кода.Добавление элемента в массив если его нету или удаление его если он есть.Нужна функиция которая принимает элемент и далее работает с массивом.
function changeArray(arr, el) { return arr.includes(el) ? arr.filter(item => item !== el) : [...arr, el] } console.log(changeArray([1,2,3], 4)) console.log(changeArray([5,4,3], 4))
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, reactjs" }
AVL tree height in O(logn) I'm trying to figure out a way to calculate the height of the tree using the fact that each nodes knows about its balance. This complexity must be in O(logn) Here's what I've got so far. if(!node) return 0 if(node.balance > 0) return height(node.right) + 1 if(node.balance < 0) return height(node.left) + 1 return max( height(T.left), height(T.right)) + 1 My thought was that if the tree is right heavy, traverse the right side and ignore the left. If the tree is left heavy, ignore the right and keep traversing in there. However, I'm a little confused as to what to do if the tree is balanced. At that point, wouldn't we be forced to run `max( height(T.left), height(T.right)) + 1` which would mean that each node in the subtree would be visited, hence making this complexity O(n) either way?
The height/depth is linked to the size of the tree as a direct result of the tree being balanced. Because an AVL is balanced, you can use its structure to calculate the depth of the tree in O(1) if you know its size: lg N = log(N) / log(2) -- define a helper function for 2-log depth N = 1 + floor(lg(N)) -- calculate depth for size N > 0. Picture the tree as it fills: each new 'level' of depth corresponds to a threshold in the size of the tree being reached, namely the next power of 2. You can see why this is: the deepest row of the tree is 'maxed out' when the size of the tree `N` is just one short of a power of two. The `1+` corresponds to that deepest row which is currently being filled until the depth of the tree changes to the next 'level', the `floor(lg(N))` corresponds to the depth which the tree had on the previous 'level'.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "algorithm, time complexity, avl tree" }
How to make text/div appear when the user stops scrolling I'm trying to achieve an effect where the javascript detects whether the user has stopped scrolling/hovering over the page, and slowly shows a piece of text over the page, sort of like a paywall. The effect I'm trying to achieve is a simplified version of this website where when the user is inactive for a certain amount of time, eyes start to appear on the page
You can use setTimeout and clearTimeout to perform an action when the mouse stops moving. Here the text would reappear after 3 seconds of inactivity var timeout; var element = document.getElementById("element"); document.addEventListener("mousemove", function(e) { element.style.opacity = 0; clearTimeout(timeout); timeout = setTimeout(function() { element.style.opacity = 1; }, 2000); }); #element { transition: opacity 0.5s; opacity 0; } <div id="element">I see you<div>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, html, css" }
Creating a network flow model for building a new organizing schema for a departament The problem I'm attempting to solve is formulated like this: A department consists of _n_ groups such as for each group _i_ in $\overline{1,n}$ contains $p_i$ members. A change in the organization is wanted so that: * the new organizing schema contains _q_ groups of members * each group in $\overline{1,q}$ will contain $k_i$ members * the new groups may not contain more than _c_ members which were part of the same old group (c $\geq$ 2 , c $\in \mathbb{N}$) How to find a model based on a flow network to build this new organizing schema? I've tried building a network flow graph but I had trouble in representing the member groups and the restriction that no more than _c_ members which were part of an old group can be present in a new group. Thank you for reading the question, any hint or solution is greatly appreciated.
I'll repeat my answer from this deleted question from another user earlier today: Define a complete bipartite graph with $n$ supply nodes and $q$ demand nodes. The flow from node $i$ to node $j$ indicates the number of students that move from old group $i$ to new group $j$. Each flow variable has an upper bound of $c$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "graph theory, computer science, bipartite graphs, network flow" }
What is this M01PTH I see referenced on schematics? What is this part "M01PTH"? I'm interested in building this "BBQ Temp Controller" Arduino-based project here: < One component involved is a 12v blower. In looking at the schematic for the above link, I see that the positive for the blower is connected to something that says "M01PTH" above the designation "12V". I cannot find any parts online that correspond to "M01PTH". I see the same reference to "M01PTH" on a couple other schematics for power supply stuff as well, for example here: < and here: < but I have no idea what this is. Does anyone know what this is or means?
It's the EAGLE part designator for a single pin through hole header.
stackexchange-electronics
{ "answer_score": 3, "question_score": 0, "tags": "arduino, power supply, schematics" }
HtmlAgilityPack GetElementby Name I using HtmlAgilityPack HtmlAgilityPack.HtmlDocument DocToParse = new HtmlAgilityPack.HtmlDocument(); DocToParse.LoadHtml(HtmlIn); HtmlAgilityPack.HtmlNode InputNode = DocToParse.GetElementbyId(IDToGet) This works fine for element that have Id like <input type="hidden" id="nsv" value="y"> But elements that i need dont have Id only name <input type="hidden" name="Pass" value="106402333"> <input type="hidden" name="User" value="145"> sow i can't use HtmlAgilityPack.HtmlNode InputNode = DocToParse.GetElementbyId(IDToGet) and there is no method GetElementbyName,sow any one know how i can get element by Name?
You may use XPath selector: var nodes = DocToParse.DocumentNode.SelectNodes("//input[@name='" + NameToGet + "']");
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "c#, html agility pack" }
xsendfile on Amazon EC2 AMI I'm trying to install `xsendfile` on Amazon's own Linux AMI with this command: yum install mod_xsendfile but it can't find the package. Can anyone help with a solution please?
You can try this, but you might have to download some packages to be able to compile it > wget < \--no-check-certificate and for apache2 to compile it's: > apxs2 -cia mod_xsendfile.c
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "apache, apache2, amazon ec2, apache modules" }
virtualenv does not copy standard modules like shutil and urllib2 When I create a new virtualenv, `virtualenv .virtualenvs/my_env`, there is only a subset of the standard python modules copied/linked to the new virtualenv. For example, when I do `ls -l` in .virtualenvs/my_env/lib/python2.6, I see: ... ... os.py -> /usr/lib/python2.6/os.py ... os.pyc -> /usr/lib/python2.6/os.pyc but modules like `shutil` and `urllib2` are not copied even if they are in `/usr/lib/python2.6/shutil.py`. I am using Ubuntu 9.10. Is this the expected behavior? How can I install modules such as shutil in a virtualenv (I could not find these modules on pypi)?
virtualenv munges `sys.path` to insert your virtual environment _in front_ of the system libraries, but the system libraries are still on the path, so they should still be accessible. So, for instance, do: >>> import os >>> os <module 'posixpath' from '/environments/userpython/lib/python2.6/posixpath.pyc'> >>> import shutil >>> shutil <module 'shutil' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/shutil.pyc'> My os module is from my virtual environment, but the shutil module is coming from my system Python.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "python, virtualenv" }
How to have a textfield load with todays date through NSDate? How do I have a textfield with on viewdidLoad load with today's date? i think it requires nsdateformatter but i don't know how to do it if somebody could provide some code. Thank you.
You can try this NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"YYYY-MM-dd"]; NSDate *todaysDate = [NSDate date]; NSLog(@"Todays date is %@",[formatter stringFromDate:todaysDate]);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, nsdate" }
Limit \renewcommand{\chaptername}{} for one part only I'm currently compiling a manual in LaTeX and the manual has 3 parts. For part 1 the chapters are called core, for part 2 the chapters are called QI and for part 3 the chapters are called GP. I want the chapters to look like the photo I attached. ![what I want the chapters to look like]( I'm currently using `\renewcommand{\chaptername}{}` but it also applies that the chapters for Part 2 are called core but I want the chapters for part 2 and part 3 to be different from each other as well. What command can I use?
You can define the names at the beginning, based on the value of the `part` counter. \documentclass{book} \usepackage[a6paper]{geometry} % to get a small image \renewcommand{\chaptername}{% \ifcase\value{part}% Chapter\or % 0 Core\or % 1 QI\or % 2 GP\else % 3 Chapter % else \fi } \counterwithin*{chapter}{part} \begin{document} \part{Core} \chapter{Test} \part{QI} \chapter{Test} \part{GP} \chapter{Test} \clearpage \mbox{} \end{document} ![enter image description here](
stackexchange-tex
{ "answer_score": 4, "question_score": 4, "tags": "chapters" }
Android: Yeahpad Pillbox7´s idVendor? !enter image description here I am trying to run/debug and my Android-app via Eclipce on an Yeahpad Pillbox7. My OS is Ubuntu 12.10.. From the < page, I can see I need to set the: > sudo gedit /etc/udev/rules.d/51-android.rules Then I need to add this: > SUBSYSTEM=="usb", ATTR{idVendor}=="?", MODE="0666", GROUP="plugdev" **_But I can´t find the** `ATTR{idVendor}` **for Yeahpad devies!!_** **UPDATE:** Just use > 18d1 So it look like this. > SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev"
Show connected devices by running `sudo lsusb -v`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, eclipse, ubuntu" }
Cannot access member object inside activity Why can't I access remTime object? I get runtime exception while I can access all other Activity members declared the same way. public class MainActivity extends Activity { ListView lstDayInterval, lstWeekDay, lstMonthDay, lstMonth; ... RemCalendar remTime; @Override public void onCreate(Bundle savedInstanceState) { ... remTime.setToNow(); } public class RemCalendar { private Calendar C; public RemCalendar() { C = Calendar.getInstance(); } public void setToNow() { C = Calendar.getInstance(); } } Thanks
you forget to initialize `remTime` instance before calling method from `RemCalendar` class. initialize it inside `onCreate` : @Override public void onCreate(Bundle savedInstanceState) { ... remTime=new RemCalendar(); remTime.setToNow(); }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "java, android" }
Content isn't hidden on url-rewrite url, but is on normal url I am using this code to prevent a `<div>` element from being displayed on the page example.php: <?php if($_SERVER["SCRIPT_NAME"] !== '/example.php') { ?> <div>Example</div> <?php } ?> Using this code in `.htaccess`, I can change the page name from `example.php` to `example`: RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L] When I visit < the `<div>` element does not show - but when I visit < it does - how can I stop this?
use `strpos()`:- <?php if(strpos($_SERVER["SCRIPT_NAME"], 'example') === false) { ?> <div>Example</div> <?php } ?>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, .htaccess, url rewriting, file extension" }
Oracle Rounding down Here my partial statement. The statement works and receive the value of 4 but instead I would prefer 3.9 in some cases the number may not be a whole number but .4,.2,.1 etc. Those numbers currently show up as "0" because Oracle rounds up. If I remove "round" I receive 3.9123458543845474586. Is there a way to display 3.9 only and .4,.2 etc. without the rounding? I know its got to be a syntax issue. When I remove round I receive an error. round((total_qty)*((avg_qty/(sum(avg_qty)over(partition by ID)))/5),0) avg_qty Thanks in advance.
Try like this, SELECT ROUND(3.9123458543845474586, 1) Round FROM DUAL; Round ---------- 3.9 For better understanding please refer this link.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "oracle, math, rounding" }
Bidirectional connection I want to know how can we have a bidirectional connection physically and electrically for example how can we send and receive signals at the same time in telephone wire without interference? thanks for your answers!
Although your question is off-topic the answer is pretty simple. You have multiple wires. For a signal you need at least two. One for the signal and one to have a common reference the signal refers to. So either you have at least 2 signal lines so you can send and receive at the same time or you have 1 signal line and both sides send/receive alternatingly.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -6, "tags": "communication" }
Running multi-module project successfully with error in an module Starting position: * SonarQube 4.5.2 * SonarRunner 2.4 * Multi-module project * 4 modules Goal: To run the sonar analysis for the modules, even if the sonar analysis of a module fails. And show the metrics of the multi-module project. The problem is, if the sonar analysis of one module fails, the sonar analysis of the whole multi-module project fails. And I can't see anything in my SonarQube webbrowser. My idea was that I run the sonar analysis for each module separately, but with the Project.Key of the module in the Multi-module project. The problem is that SonarQube creates a separate project with this Project.Key and "deletes" the module in the multi-module project. Do you have any suggestion how to realize the mentioned goal? Thanks in advance.
This is not possible. If one of your modules fail to be analyzed correctly, simply remove it from your configuration.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sonarqube, multi module" }
Correct specification of a hierarchial model for analysing temporal trends My data has a nested structure, which is suitable for hierarchical modelling. The categorical variable used as a hierarchical level is **county**. As the counties are unequally sized (different number of subjects), I use hierarchical modelling for analysing temporal changes. **First, am I correct, that the hierarchical modelling allows reporting temporal changes in a way, where all counties (small and big-sized) have equal contribution to the conditional effects?** Or in other words, the results are less affected by the big counties. **Second, which of the following model structures should I use if I am interested in county-level trends only (not country-wide trends):** **A** y ~ time + (time | county) **B** y ~ (time | county) When plotting the conditional effects of these models, the results are more or less the same. I use <
The two models: y ~ time + (time | county) and y ~ (time | county) ..only differ in the presence of the fixed effect for `time`. In the first model, the software will estimate a fixed (overall) effect for time, and each `county` will have it's own offset from this fixed effects. In the 2nd model, since the fixed effect of `time` is absent, the overall effect of time is implicitly zero. Each `county` has it's own effect for `time`, but rather than being an offset from the fixed effect, it is an offset from zero. In most cases, it rarely makes sense to exclude the fixed effect unless you know that the overal trend is zero.
stackexchange-stats
{ "answer_score": 3, "question_score": 3, "tags": "multilevel analysis, hierarchical bayesian" }
Composite key as foreign key (sql) here are my two tables of concern: CREATE TABLE IF NOT EXISTS `tutorial` ( `beggingTime` time NOT NULL, `day` varchar(8) NOT NULL, `tutorId` int(3) NOT NULL, `maxMembers` int(2) NOT NULL, `minMembers` int(1) NOT NULL, PRIMARY KEY (`beggingTime`,`day`,`tutorId`), KEY `tutorId` (`tutorId`) ) CREATE TABLE IF NOT EXISTS `group` ( `groupId` tinyint(3) NOT NULL AUTO_INCREMENT, `status` varchar(20) NOT NULL, `groupName` varchar(50) NOT NULL, PRIMARY KEY (`groupId`) ) I would like to create a field in 'group' that would link to the composite unique keys in 'tutorial'. So I guess my question is, how do I relate these tables? do I have to to create foreign keys field in 'group' for each primary key in 'tutorial'?
Per the mySQL documentation you should be able to set up a foreign key mapping to composites, which will require you to create the multiple columns. Add the columns and put this in your `group` table FOREIGN KEY (`beggingTime`,`day`,`tutorId`) REFERENCES tutorial(`beggingTime`,`day`,`tutorId`) As Steven has alluded to in the below comments, you SHOULD try to re-architect this so that the tutorial table uses an actual primary key (even if it is just an identity surrogate key). This will allow for greater performance as SQL was built for this type of relationship, not composite.
stackexchange-stackoverflow
{ "answer_score": 38, "question_score": 31, "tags": "mysql, sql, phpmyadmin" }
How can I expose the faces data from macOS Photos to iOS Photos? I've spent some time teaching Photos on my Mac to know which face belongs to what name and now have a nice set of groups. I'd like to be able to access that metadata on iOS - preferably through automation and the iCloud Photo Library. Is there any way to see these groups/tags/keywords attached to photos in any usable way on iOS? * * * macOS 10.12 - Photos app Version 2.0 (445.1.15) iOS 10.0.2 + Photos
Kind of. The metadata is there and can be read by Photos on the iOS - I'm just not sure that there's a good way of automatically doing it and grouping them as you want. But try this: launch Photos on your phone, hit the search magnifying glass, and start typing someone's name. It'll give you a menu list of all of the people, locations, albums, keywords etc that match your search. My guess is that 'smart searches' will be coming soon, where you can then save that search and then later just pull it up as though it were an album. You can do the same in Photos on OS X but it doesn't sync that album over to iOS ... yet.
stackexchange-apple
{ "answer_score": 3, "question_score": 6, "tags": "macos, ios, icloud, photos, face recognition" }
AttributeError: 'tuple' object has no attribute 'stripe_customer_id' I am receiving the error below when attempting to submit a purchase using stripe api within django app. > line 115, in post if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: AttributeError: 'tuple' object has no attribute 'stripe_customer_id' [09/Oct/2019 19:18:26] "POST /api/checkout/ HTTP/1.1" 500 16291 Everything was working until i made alterations based on 22:33. This is line 115: if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: customer = stripe.Customer.retrieve( userprofile.stripe_customer_id) customer.sources.create(source=token)
You've posted _far_ too much code here. The problem is here: userprofile = UserProfile.objects.get_or_create(user=self.request.user) `get_or_create` returns a tuple: `(object, created)`. You've assigned the whole tuple to the `userprofile` variable. Since you don't care about `created`, assign it to a throwaway name: userprofile, _ = UserProfile.objects.get_or_create(user=self.request.user)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "django, stripe payments" }
Convergence of series of expectations implies finite stopping time? Let $a_1,a_2,\dots $ be a sequence of random variables. They are not assumed i.i.d. Say that $$\sum\limits_{k=1}^{\infty}\mathbb{E}[|a_k|^2] := A < \infty.$$ For $\epsilon> 0$, define the stopping time$$T_{\epsilon} = \inf\\{ k \mid |a_k| < \epsilon\\}.$$ Does $T_{\epsilon}$ necessarily have finite expectation? and can I bound $\mathbb{E}[T_{\epsilon}]$ in terms of $A$ and $\epsilon$? In the deterministic case, this is straightforward: If $T_{\epsilon} \geq \lceil \frac{A}{\epsilon^2}\rceil$ then $$\sum\limits_{k=1}^{\infty}|a_i|^{2} > \frac{A}{\epsilon^2} \epsilon^2 = A,$$ a contradiction. Can any similar result be proven for the stochastic case?
$E\sum _{k=1}^{T_\epsilon -1} a_k ^{2} \leq E\sum _{k=1}^{\infty} a_k ^{2} = A$. This gives $E\sum _{k=1}^{T_\epsilon -1} \epsilon^{2} \leq A$. Hence $ET_{\epsilon} \leq 1+\frac A {{\epsilon}^{2}}$. ( $T_\epsilon -1$ need not be an integer, so an obvious modification is needed, but I will that to you).
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "sequences and series, probability theory, stopping times" }
Why do I get a StringFormat error with this? With this code (sbJava is a StringBuilder): String androidFindLine = string.Format("Button _{0} = (Button) findViewById(R.id.{0});\"", btnId); sbJava.Append(androidFindLine); sbJava.Append(Environment.NewLine); sbJava.Append(string.Format("_{0}.setOnClickListener(new View.OnClickListener() { ", btnId)); ...I get, > System.FormatException was unhandled _HResult=-2146233033 _message=Input string was not in a correct format... The value of btnId is "btnbutton_up" What is the problem?
You should escape those `{` with double `{{`: sbJava.Append(string.Format("_{0}.setOnClickListener(new View.OnClickListener() {{ ", btnId));
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c#, stringbuilder, string.format" }
Type error primeFactors.for is not a function I've got a 'TypeError: primeFactors.for is not a function' error from Jasmine when I try to run this code, I've run into this type of error so many times. What's the best way to resolve it? I know that clearly .for is not a function but I'm not sure why? var primeFactors = function(){}; primeFactors.prototype.for = function(num){ var array = []; for(var i = 2; i < Math.ceil(Math.sqrt(num)); i++){ if(num % i === 0){ array.push(i); num = num/i; i--; } } return array; }; module.exports = primeFactors;
When you want to call `.for`, you must create an object instance for that prototype, for instance with the `new` keyword: This is not OK: primeFactors.for(3); But this is OK: var obj = new primeFactors; obj.for(3); For your Jasmine test, it would work like this: it('returns an empty array for 1', function() { expect((new primeFactors).for(1)).toEqual([]); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jasmine" }
Can't get ScrollViewer to work within ItemsControl>WrapPanel I have the following code: <ItemsControl ItemsSource="{Binding ItemsList}" Visibility="{Binding HmiState, Converter={StaticResource IsHmiViewState}}"> <ItemsControl.ItemsContainerStyle> <Style> <Setter Property="FrameworkElement.Margin" Value="5" /> </Style> </ItemsControl.ItemsContainerStyle> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <WrapPanel Width=300 Height=200 ItemsHost="True" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollVisibility="Auto" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> It display everything up to the 200 height correctly (wrapped), but doesn't display anything below that and there's no scroll bar. ItemsList is an ObservableCollection. Does anyone have any suggestions?
There should be a ScrollViewer that hosts an ItemsPresenter in the ControlTemplate of the ItemsControl: <ItemsControl ItemsSource="{Binding ItemsList}" Width="300" Height="200"> <ItemsControl.Template> <ControlTemplate TargetType="ItemsControl"> <ScrollViewer> <ItemsPresenter/> </ScrollViewer> </ControlTemplate> </ItemsControl.Template> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <WrapPanel/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style TargetType="ContentPresenter"> <Setter Property="Margin" Value="5" /> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "wpf, scrollviewer, itemscontrol, wrappanel" }
make a ruby code as a console command I created a gem with jeweler and I want a command `hat` to call a specific function in my gem. In Python I can put this entry_points=""" [console_scripts] hat = hat:hat """ in `setup.py` and it works, but how is it done in ruby?
$ mkdir bin $ touch bin/foo $ chmod a+x bin/foo Edit **bin/foo** #!/usr/bin/env ruby require 'foo' #Anything you want....... Add following to Gemfile s.executables << 'foo' As per: Making ruby gems respond to terminal commands There is also: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ruby, console" }
What did i mess up in this for loop? So what i'm trying to achieve here is basically doing a subnet _lookup_ (in networking). for (i = 0; i < sorEgy.Length; i++) { if (sorEgy[i] == 1 && sorKetto[i] == 1) { Console.Write("1"); } else { Console.Write("0"); } } sorEgy is the given IP in binary: 11000000101010000000000000100000 is for the given IP of 192.168.0.32. sorKetto is the binary mask:11111111111111111111111100000000 is for /24 which means 24 1-s. With this for loop, i wanted to write 1 in the output if both strings have a _1_ at _i_ , and write a 0 if they don't match. I can't really think of what the problem could be.
The values being indexed are strings of the form `"100101010101111"`... The index operator on the string produces a `char`, and a `char` may be compared to an `int`, which you are doing. But the `int` is the _Unicode 16 bit encoding_ of that character, not the _text_ of that character. Unicode encoding 1 is an unprintable formatting code for "start of heading", not the character `1`. If you want to compare to the _character_ `1` then use `'1'`, not `1`, or use the Unicode encoding of the character `1`, which is `49`. The preferred way to do it would be `'1'`, as comparing against `49` looks strange, to say the least.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, for loop" }
Negative lookahead alternative for bigquery I'm using `REGEXP_CONTAINS` of Big query and want to implement it for pattern ^[-]?(?!0\d)\d*.?\d*$ But Big Query doesn't support Negative Lookahead and hence I'm looking for alternative of above pattern which is supported by Big Query. Can anyone help me with this ?
An alternative to asserting not zero would be to just assert one through nine: ^-?(?:0|[1-9]\d*)(?:\.\d+)?$ Your phrasing of an optional decimal component also needed a refactor. The above pattern is matching either an integer or decimal number which does not begin with zero.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "regex, google bigquery, regex lookarounds" }
How to draw equal-angle triangle? I want to draw an equal-angle triangle (like the one below) but with small sentences instead of A, B, C ![enter image description here]( Thank you
Using `tkz-euclide` package: \documentclass{article} \usepackage{tkz-euclide} \begin{document} \begin{tikzpicture} \tkzDefPoints{0/0/A,3/0/B} \tkzDefPointByrotation=center A angle 60\tkzGetPoint{C} \tkzDrawPolygon(A,B,C) \tkzLabelPointabove{Top small sentence} \tkzLabelPointbelow left{below left small sentence} \tkzLabelPointbelow right{below right small sentence} \tkzDrawPoints(A,B,C) \end{tikzpicture} \end{document} ![enter image description here](
stackexchange-tex
{ "answer_score": 3, "question_score": -3, "tags": "tikz pgf, diagrams" }
Android java.util.concurrent.Executors newSingleThreadScheduledExecutor example I am having a problem with Android java.util.concurrent.Executors. I am trying to use newSingleThreadScheduledExecutor to run my runnable every x seconds. I saw `executor.scheduleAtFixedRate(myTask, 0, 50, TimeUnit.MILLISECONDS);` however it doesn't exists in Android. The Android documentation link , does not give a clue how I should use the newSingleThreadScheduledExecutor; Could someone give me an example how I should use it to run a runnable every x seconds? I know you can use Handler, but I am wondering how you can use SingleThreadScheduledExecutor to do the same. Thanks in advance.
You can get an example here: < Actually Executors comes with Java 7 .
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, multithreading, concurrency, executors" }
Return updated value with PDO connection Is it possible to get the updated value on a row. ex: I get a table called 'invoice', in this table there is a field called 'balance'. I make an update on balance and I would like to get the new value of balance. Is it possible to return the new value of the affected field?
No, you can get only number of affected rows. If you want to have updated data you have to `SELECT` it. BTW Database wouldn't know what to return - only updated fields? All rows? Whole resultset?
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, pdo" }
What's the best language to write Selenium Tests? I'm thinking of using Selenium IDE for automate testing of a web app. My question is what is the weight of selecting a programming language for test case writing? I'm not worried about nitty-gritties of languages themselves, but more concerned about how easy it's to maintain a large test collection (i.e it looks as if C# uses NUnit for test suit creation, while python uses code to do that). And how it affects the portability of tests?
Maintaining a large test suite will have a degree of effort, regardless of what language you use to create your tests. As a personal preference, I would go with Ruby / Cucumber framework.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "selenium, selenium ide, automated tests" }
How do I create animated charts on iOS? Is there a good third party framework available for creating animated charts and graphs on iPhone or iPad? I'm looking to do something similar to what FusionCharts provides. How could I achieve this?
hey this will be helpful core Plot
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "iphone, ios, cocoa touch, ipad, charts" }
How to focus and select part of content in a textarea I have a textarea which already contains some content (haml code below) //haml code for textarea %section.input .muse_text %textarea{placeholder: "Type your muse here..."} //Content in textarea "Share why you are re-musing this ------------------ I am remusing this because I like it!!!! ------------------ xxxx" How can I use jquery to autofocus the textarea and highlight only the first line of the content i.e. "Share why you are re-musing this (when the page loads up)
When the page loads, focus the textarea (use `.focus`) after `document.ready`, or after the textarea is loaded into the DOM. You can use `createTextRange` or `setSelectionRange` (depending on the browser) to create a range of text to select .. this can be done when you focus the textarea. You know the length of the "share why.." text, so it should be pretty easy to count.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery, textbox, backbone.js, haml, highlight" }
Grouping content by category - Drupal is there a good way of grouping content up by category. I wish I could have a CCK category field.
Use Taxonomy. It has good integration with views. We use it to group portfolio projects by taxonomy word on our portfolio. < Using only views and taxonomy for data.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "drupal, content type, drupal views, cck, categories" }
Do absolutely continuous functions have bounded derivative? I am an outsider for this field of mathematical analysis. But to analyse a problem of Control Systems, which is my area of interest, I need to know this. I learned that _absolutely continuous functions_ are also _differentiable almost everywhere_. On the other hand, _Lipschitz continuity_ ensures _bounded derivative_ of the function a.e. I am wondering whether there is any link between the derivative being bounded and the function being absolutely continuous. Or, is there any sufficient condition to be imposed over the _absolute continuity_ to ascertain that the derivative of the function will be bounded?
If a continuously differentiable function has a bounded derivative, then it is absolutely continuous. The inverse is _not_ true, as shown by the function $f(x)=\sqrt{x}$ on $[0,\infty)$.
stackexchange-math
{ "answer_score": 6, "question_score": 3, "tags": "real analysis, analysis" }
Reset lightning:input textbox Field Value to Null I am trying to create a button which will update a field value to null (RESET it). However, it's not working and not even giving any error. So when I click on the button, nothing happens. lc.cmp: <aura:attribute name="myObj" type="Account" default="{'SObject':'Account'}"/> <lightning:input type="text" name="accountPhn" label="Enter Account Phone" value="{!v.myObj.Name}"/> <lightning:button label="Reset" onclick="{!c.resetMe}"/> lc.js: resetMe : function(component, event, helper) { //alert("Called"); component.set("v.accountPhn",""); } Appreciate help around this.
Please change 2nd line with below code. It will work. <aura:attribute name="accountPhn" type="String" default="{!v.myObj.Name}"/>
stackexchange-salesforce
{ "answer_score": 0, "question_score": 0, "tags": "lightning aura components, lightning, lightning experience" }
Nav Menu - Drop down menu z-index? been working on a site building software and have a bug thats driving me nuts: when you go to < And you mouse over the nav the drop downs go behind the content. I cant figure it out. Ive tried just about everything I know of and others that I found on research and nothing seems to be working right. I just need to make sure the nav menu displays over the top of the content and not under it like its doing. If anyone could take a look at the css and maybe offer up a suggestion it would be greatly appreciated. The css can be seen here < Thanks
In the rule for `ul.nav`, position it relative and change z-index from -1000 to positive 1000. This worked from the inspector tools for `ul.nav`: z-index: 1000; position: relative;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "css, drop down menu, nav" }
Am I still visible to old contacts I have deleted long ago, when they intall whatsapp if they still have my number in their contacts? I've had my mobile number 15+ years and have used it for work purposes as well as private over this time, even though its my personal number. Could someone clarify - if anyone from the distant past who still had my number in their contacts then installed WhatsApp - would they now be able to see me in their WhatsApp contacts even though I deleted them as a contacts long before installing the App?
If they have your old number then they are still able to see your old profile. You are not deleting your profile by simply uninstalling WhatsApp, you need to properly delete your profile by going into `Settings->Account` and select `Delete my account`. Then your old profile is deleted and nobody will be able to see it or send any messages to it.
stackexchange-android
{ "answer_score": 1, "question_score": 0, "tags": "whatsapp messenger" }
How download multiples URL to local folder? I have multiples URLs and I would like a online site/ program to download those files. please help
Try using a download manager such as DownThemAll (Firefox extension), wget (Linux command line), fatrat (Linux GUI), InternetDownloadManager (Windows GUI), or VBDownloader (Windows GUI, I am one of the developers). My favourite for mass downloading of many small files is DownThemAll. My favourite for downloading a few large files is VBDownloader. My favourite for Linux is fatrat.
stackexchange-superuser
{ "answer_score": 1, "question_score": -1, "tags": "windows, download, url" }
How rand() is calculated in PHP I was just wondering how rand() really works in PHP, what's the math behind the scenes. So when I call: rand(1,10); What is PHP (or any there language) really doing to return a value?
Random Number Generators also called RNG in short are actually generating pseudorandom numbers, since it's impossible to actually generate a TRULY random number. There are basically two parts of an RNG: **the seed** , and **the random number** chosen from that seed. When you seed the RNG, you are giving it an equivalent to a starting point. That starting point then has a bunch of numbers that are "inside" of it that the program chooses from. In PHP, you can use srand() to "shuffle" the seeds, so you almost always get a different answer. You can then use rand(min, max) to go into the seed and choose a number between the min and the max, inclusive. I don't have enough idea on how php chooses its seed to generate random number.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "php, random" }
Use multiple elements to trigger single onclick function Right now this will work when I click "box1" but not "box2". I'd like to have a single tapBoxes variable that listens for a click on either box1 OR box2, and triggers the function. Any ideas? var tapBoxes = document.getElementById("box1") || document.getElementById("box2"); tapBoxes.onclick = function() { ... }
Define the function first. Then assign it to all the buttons you want. tapBoxesClick = function() { ... } document.getElementById("box1").addEventListener("click", tapBoxesClick, false); document.getElementById("box2").addEventListener("click", tapBoxesClick, false);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, onclick" }
How to dry run a request in a browser? I am clicking a button in chrome upon which a POST request is sent to the server. I want to capture this request without actually sending the request to the server something like a dry run. Because if I let this request succeed and I replay it, I know the backend will throw the exception. Another reason is that the front end is dynamically setting a lot of fields every time. If I can do this, I can easily copy the request body and play around with it. Can we do something like blocking a request ? Does chrome or any browser support it or is there an extension?
Go to the Network tab in Chrome. On top, you can see a dropdown with Online selected by default. Select offline. ![Network tab]( Now send the request. You will see the request fails as if the network is disconnected. ![Request failing after switching to offline mode](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "google chrome, firefox, browser, safari, http post" }
Requiring from lib/GEM_NAME in Ruby I have a Gem which has the following structure: gem | |- lib/ | |- gem.rb |- gem/ | |- router.rb Inside `gem.rb`, there's the following code: module Gem VERSION = '0.1.8.beta' end require 'gem/router' However, despite using hundreds of functions and methods of my knowledge, `router.rb` cannot be required! Any tips? Thanks.
One of two things could be happening. If you are on 1.8.7 and friends, Ruby is probably seeing some standard library folder called `gem` (don't name things after standard libraries). If you are using Ruby 1.9.*, you must use a method called `require_relative` that only searches relative to the current working directory.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ruby, rubygems, require" }
The most Comprehensive Jquery Validator plugin? I looking for jquery validator plugin. I have done lot of searches, some plugins UI looks good, some providing low criteria's to check. I want the most comprehensive and light weight jquery plugin for form validation. Can anyone tell suggest me any plugin which you have used and is more comprehensive??!! Thanks!
jQuery Validate from Bassistance great customization, complete documentation and is fairly easy to use. You can either add classes to form elements like <input type="text" name="useremail" class="required email" /> And then just: $("#myForm").validate(); Or you can set the rules from the jQuery like: $("#myForm").validate({ rules:{ useremail:"required email" } });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery, validation" }
Induction proof involving divisibilty Show that for every $n \geq 0 \in \mathbb{N}$, $3^{n+1}|(2^{3^n}+1)$ (in addition, I must use proof by induction, strong induction, or minimum counterexample). Initially, I thought that normal induction would be enough. To simplify the problem, I tried letting $3^n = k$ and then prove for every $k$, except I couldn't get it to work (plus I'm not sure if that is entirely "accurate," that is whether or not I have to prove this for just the $k$s that are a power of $3$). I also tried to rearrange $2^{3^{n+1}}+1$ so that it would have a factor of $3^{n+2}$ in all terms (using the assumption that $2^{3^n}+1$ is divisible by $3^{n+1}$), but got nowhere. For the same reasons, strong induction also failed to work out, but I still suspect that I just need to rearrange the terms correctly. I appreciate all and any help. Thank you kindly!
Let $P(n) \equiv 3^{n+1} \mid (2^{3^n}+1)$ $P(0)$ is true since $3 \mid 3$. Suppose $P(k)$ is true for some $k \in [0..\infty)$. We need to demonstrate that this implies $P(k+1)$ is true. $2^{3^{k+1}}+1 = \left( 2^{3^k} \right)^3 + 1 = \left(2^{3^k}+1 \right) \left( \left( 2^{3^k} \right)^2 - 2^{3^k} + 1 \right)$ We note that, by hypothesis, $3^{k+1} \mid 2^{3^k}+1$. If we can demonstrate that $3 \mid \left( 2^{3^k} \right)^2 - 2^{3^k} + 1$, then it will follow that $3^{k+2} \mid (2^{3^{k+1}}+1)$; that is to say P(k+1) is true, and we will be done. * * * We demonstrate below that $3 \mid \left( 2^{3^k} \right)^2 - 2^{3^k} + 1$ Note that $3^k$ is an odd number for all $k \in [0..\infty)$. Computing modulo $3$, we find \begin{align} \left( 2^{3^k} \right)^2 - 2^{3^k} + 1 &\equiv \left( (-1)^{3^k} \right)^2 - (-1)^{3^k} + 1 \pmod 3\\\ &\equiv (-1)^2 - (-1) + 1 \pmod 3\\\ &\equiv 1 + 1 + 1 \pmod 3\\\ &\equiv 0 \pmod 3\\\ \end{align}
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "induction, divisibility" }
Rear derailleur speed number interchangability I have a bike with an 8-speed cassette and would like to switch to 9-speed cassette. Can I keep my rear derailleur? which is a Shimano Alivio one? I understand the indexing might mess up this, but I figure the indexing is handled by the shifters, rather than the derailleur itself! Also, Saint Sheldon seems to confirm it is possible , is that really reliably so? Apart from that, I know I will need a new chain to handle the 9 speeds, is there a consequence on the crankset? or do cranksets support all chains width?
You're right, indexing is handled by the shifters. So if you replace the 8 speed to cassette with a 9-speed cassette you should be able to use the same derailleur. But you will have to upgrade your shifters. The only caveat with the derailleur is that it has to be long enough to accommodate the amount of chain slack generated by going from the largest gear to the smallest gear. This becomes a problem when trying to use a road derailleur with a mountain bike, which usually has a much bigger range of gears.
stackexchange-bicycles
{ "answer_score": 1, "question_score": 2, "tags": "derailleur, cassette" }
A proper place for a web-service backing logic I'm going to create Axis2 web-service on WSO2 AS. AFAIK .aar must contain a service class and its configuration in service.xml. To process requests received by the web-service I'm going to implement some business logic including interaction with DB through Hibernate. In respect to a system architecture it would be wrong to place all this logic into the web-service class. What would be a proper place for the business logic implementation in my case?
You can model this inside the Axis2 project. You should only add the service publishing methods in the service class and no need to implement the core logic there. You can easily model it as project with different hierarchies and aspects. Look at this example blog post and how the project is modeled which can be found at the end of the tutorial.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "web services, axis2, wso2" }
How to handle multiple date formats? When I get to the df.date() line below, the app crashes when a date with this format `2016-12-27 14:40:46 +0000` is used: > fatal error: unexpectedly found nil while unwrapping an Optional value And I also see this: > error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) I have strings that can be in this format 12/27/2016 but sometimes in this format 2016-12-27 14:40:46 +0000 Here is the code snippet that crashes on the above format: let mydate = "12/27/2016" //this works but not the longer format let df = DateFormatter() df.dateFormat = "MM/dd/yyyy" //this is the format I want both dates to be in newDate:Date = df.date(from: mydate) How do I handle both formats using basically one function?
Check if the date string contains a slash and set the date format accordingly: if mydate.contains("/") { df.dateFormat = "MM/dd/yyyy" } else { df.dateFormat = "yyyy-MM-dd HH:mm:ss Z" }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "swift, date, swift3" }
Prove the nonzero postive operator $P$ has 1 dimensional range > Let $V$ be a finite-dimensional complex inner product space, and let $P \in L(V)$ be a non-zero positive operator with the property that for all positive operators $Q, R$ such that $P = Q+R$, there is a real number $0 \le r \le 1$ such that $Q = r P$. Prove that $\dim \text{range} P = 1$. I don't have any ideas about how to approach this problem. I tried to use a complex spectral theorem, but I failed. Then I also noticed that if $Q+R=P$ and $Q, R$ are positive, this means that $P=rP+R$ which makes $R=(1-r)P$. Thus, I think this means that $P$ can only be rewritten as $(1-r)P+rP$ and it can't be rewritten as the sum of other positive operators. This is also the given information that I'm not able to use in my proof. Thus, any help on this? Thank!
**Hint:** I think it is easiest to prove this statement by contrapositive. If $P$ is a positive operator with range of dimension $2$ or greater, use the spectral theorem to construct positive operators $Q,R$ such that $Q + R = P$ but $Q$ and $R$ are not multiples of each other (in fact, we can select such operators $Q,R$ so that $QR = 0$).
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "linear algebra, positive semidefinite" }
Scale on an elevator When you are accelerating upwards in an elevator, you feel an increase in apparent weight. A scale measures the total amount of force pushing down on it, and if you were to step on a scale in an elevator, you would see an increase in its reading. However, when accelerating upwards only the normal force increases -- how does this translate to an increase in the "downward push" needed for an increase in apparent weight? Similarly, when accelerating downwards, the normal force decreases but how does this translate to a decrease in the "downward push" needed to result in a decrease of apparent weight.
As you said correctly: as you accelerate upwards, the normal force acting on **you** will increase. Now look at the situation from the **scale's** "perspective" -- consider the forces acting on the scale: Since the ground (i.e. the scale on which you stand) applies a normal force $F_N$ (upwards) on you, Newton's 3rd law says that you must also be applying a force $F_N$ (downwards) on the scale. To summarize: the scale will measure the magnitude of the normal force acting on you; which is also the magnitude of the force you exert on the scale (by Newton's 3rd law).
stackexchange-physics
{ "answer_score": 1, "question_score": 2, "tags": "newtonian mechanics, weight" }
Is c++ a space free language? #define PR ( A, B ) cout << ( A ) << ( B ) << endl ; > \- error -> A was not declared in scope > \- error -> B was not declared in scope > \- error -> expected "," before "cout" I thought C++ was space free language but when I write above code, then I see some errors. I am still thinking "Is my console is not working properly or library?". If I am not wrong, how can someone say _"C++ is a space free language"_?
There are numerous exceptions where whitespace matters; this is one of them. With the space after `PR`, how is the preprocessor supposed to know whether `(A,B)` is part of the macro expansion, or its arguments? It doesn't, and simply assumes that wherever it sees `PR`, it should substitute `( A, B ) cout << ( A ) << ( B ) << endl ;`. Another place where whitespace matters is in nested template arguments, e.g.: std::vector<std::vector<int> > That final space is mandatory, otherwise the compiler assumes it's the `>>` operator. (Although I believe this is sorted out in C++0x). Yet another example is: a + +b; The space in between the two `+` symbols is mandatory, for obvious reasons.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 2, "tags": "c++, macros, c preprocessor, whitespace" }
If a graph is not 3-COLORable, then there are at most 2 Independant Sets in G? Assuming $G=(V,E)$ is a 3-colorable graph, then there are 3 disjoint independent subsets of $V$: $S_1,S_2,S_3$ such that $S_1 \cup S_2 \cup S_3=V$, by taking each $S_i$ to include the vertices of color $i$. I wanted to know - if $G$ is not 3-colorable, then can it has 3 disjoint subsets that their union is $V$? I think it can't be by the definition of 3-colorable. Am I correct? Thanks!
This sounds like homework, so you should try to prove it. The title, by the way, doesn't make sense. **Proof sketch.** Suppose that you can partition the vertex set into three independent sets, $S_1, S_2, S_3$. Color the vertices in partition $S_1$ red, $S_2$ green, and $S_3$ blue. **Claim.** This is a proper coloring, hence the graph is 3-colorable. We conclude that _if_ the graph is 3-colorable, _then_ its vertex set can be partitioned into three independent sets.
stackexchange-cs
{ "answer_score": 1, "question_score": 0, "tags": "algorithms, complexity theory, graphs, np complete" }
Auto log-out sequence based on inactivity on desktop devices Applications that monitor user activity may log out of the app if there is no user activity in the app for more than `kLogoutInterval` period. This value could be 1 or 5 or 10 15 minutes based on the type of the app. The question is however — how do you store the timestamp? Do you store the timestamp in the memory using some `ActivityManager` singleton class? OR for every activity, you would update the timestamp in the keychain? OR any other pointers? EDIT: Just to clarify, the question is — is this timeout filed critical? Can it be simply exposed in the memory? Does it need to be stored in a secured asset like a keychain? What is the overall risk assessment for using this timestamp casually?
If an attacker can write to specific memory locations to prevent logout, you're already severely compromised. Any attacker that can change arbitrary memory can write arbitrary code to it. If an attacker can read specific memory locations, you're also very likely severely compromised if you store anything in memory you wouldn't want world+dog to know.
stackexchange-security
{ "answer_score": 1, "question_score": 1, "tags": "authentication" }
How to set NoDelay socket option How to set `NoDelay` socket option (or socket options in general) with supersocket?
Ok that was easy, don't know why I didn't see it before. Underlying `Socket` object is accessible through session. WebSocketServer appServer; appServer.NewSessionConnected += session => session.SocketSession.Client .SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "supersocket.net" }
Can Visual Studio 2005 wsdl.exe create proxy methods with generic parameters? The proxy methods that I am seeing generated for methods that have generics for parameters like `List Of <T>` are getting converted to arrays in the proxy methods. I am not sure what the problem is, is it that the wsdl.exe that shipped with Visual Studio 2005 can't handle generics, or is it the version of soap on the machine where the web service is deployed or something else? When I view the asmx file in IE 7, I see SOAP 1.1 I expected to see soap 1.2 but that could be an IE7 thing.
WSDL.EXE and "Add Web Reference" will always use an array. This has nothing to do with generics. When you upgrade to WCF, you'll be able to specify to use `List<T>` for lists like this. * * * XML Schema has neither arrays nor lists, just repeated elements. For instance, if your service returns `List<int>`, the XML Schema in the WSDL will be something like <xs:element name="result" maxOccurs="unbounded" type="xs:int"/> The program that creates the proxy class has to decide whether to translate this into arrays or lists. With "Add Web Reference", the choice is always "array". With "Add Service Reference", you get a number of choices, including `List<int>`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "visual studio, wsdl.exe" }
Does the AT-AT type ocean crane walker in The Mandalorian S2E3 have a model name? In S2E3 of The Mandalorian, the Razor Crest misses a landing pad on Trask and has to be lifted out of the water by this walker. ![Trask Walker lifting the Razor Crest out of the water.]( Does this walker have a class/model name? Has anything similar (industrial use of a walker) shown up in canon (or extended canon) before? This ScreenRant article seems to say it is a modified AT-AT, however this seems more to just be speculation and the entire body of the vehicle seems far too different from an AT-AT for it to just be modified, so in my opinion it is more likely to have been mass produced for industrial purposes.
**TL;DR** Does this walker have a class/model name? - **No official name.** Has anything similar (industrial use of a walker) shown up in canon (or extended canon) before? - **Yes, the OI-CT.** * * * We do see something very similar known as the OI-CT appear in _Solo: A Star Wars Story_ on Corellia. ![Screenshot of an OI-CT in Solo: A Star Wars Story walking in the water]( This screen shot comes from an official Star Wars Kids video, "Every Surface Vehicle in Star Wars Movies | Star Wars By the Numbers" in which the walker was first named. The video was released in March 2019 over a year before the other walker appears in _The Mandalorian_. So the walker you ask about _could_ be a modified OI-CT or something else entirely...
stackexchange-scifi
{ "answer_score": 12, "question_score": 13, "tags": "star wars, the mandalorian" }
Devise throwing MySQL error I have Devise installed to manage my Users and it seemed like everything was working fine a couple days ago, except today I get this error: > > Unknown column 'users.password' in 'where clause I don't know why Devise is doing thing, any ideas would be great.
I found out the answer, I had password defined as a key and it was causing devise to throw an error.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, ruby on rails 3, devise" }
ASP.NET 5 web application as Azure Web Role? We have a ASP.NET 5 web application in our solution. Typically, we could right click on the Cloud Service "Roles" item and add a new role from an existing project in the solution. But it cannot identity this project as a Web Role: ![Add Web Role Project in solution...]( How are we able to host a ASP.NET 5 project in a Azure Web Role? **Edit:** We are using Azure SDK 2.7
Sorry, we don't support WebRoles at the moment. You might* be able to hack your way around but officially there is no support. That means that any hack you do, will be in a text editor, not from tooling. However, you can use an Azure WebSite instead. That's fully supported. * it might not work at all. I am not aware of anyone who did this.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 12, "tags": "azure, visual studio 2015, asp.net core, azure sdk .net, .net 4.6" }
AnyChart. How to add|remove markers? Anybody know how to add|remove custom markers from series in AnyChart JS? I cant find it in documentation.
I believe you mean series markers. To turn them on and off use markers() method, available for all series except the markers series itself. Example: < var markers = series.markers(); markers.enabled(true); markers.fill('gold'); Method reference: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, anychart" }
Setting the event for first form when the second form is closed that is opened by first form in Windows form I am developing a .NET windows form application. I am absolute beginner to .NET Windows form, I am an asp.net developer. I am having a problem with setting events to forms. Inside the form1, I open the form2 like this in a click event Form2 form2 = new Form2(); form2.show(); Inside the form2, there is a button and when the button is clicked, I will close the form2 and the fire an event in form1 that opened form2. How can I bind event between that 2 forms? How can I do it?
You can use the FormClosed event on the Form class. < form2.FormClosed += Form2_FormClosed; private void Form2_FormClosed(object sender, FormClosedEventArgs e) { }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, .net, forms" }
Executing built-in commands I would like to execute an external program from inside a Rascal program without creating a new process using `createProcess()` and `killProcess()`. Is this possible or have I missed something in the documentation? Thanks.
It's a matter of calling the `readEntireStream` function: rascal>readEntireStream(createProcess("ls", ["-l","-a"])) str: "total 192drwxr-xr-x@ 5 jurgenv admin 170 Mar 24 21:10 .drwxr-xr-x@ 5 jurgenv admin 170 Mar 3 20:05 ..-rwxr-xr-x 1 jurgenv admin 25160 Feb 4 18:43 eclipse-rw-r--r--@ 1 jurgenv admin 637 Apr 3 13:58 eclipse.ini-rw-r--r-- 1 jurgenv admin 64679 Mar 24 21:10 hs_err_pid25121.log"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "rascal" }
Are the historical differences in Tarantino's alternate history movies mentioned in any of his other movies? Quentin Tarantino has three movies in his alternate history universe: _Django Unchained_ (2012), _Inglourious Basterds_ (2009), and _Once Upon a Time in Hollywood_ (2019). Are any of the historical changes in these movies mentioned in any of the other movies directly or with Easter eggs? Please note I am not asking about connections between the movies, I am asking about mentions of the 'alternate' aspects of the movies i.e. Hitler's death in the movie theater.
In what Tarantino himself calls the "realer than real universe" the world operates a lot like the real one, where fictional characters can interact with real ones (such as Sharon Tate, Charles Manson, and Bruce Lee in _Once Upon A Time In Hollywood_ , for example). Despite that, there seems to be no mention of the alternate historical events in any of the other movies.
stackexchange-movies
{ "answer_score": 3, "question_score": 3, "tags": "reference, quentin tarantino" }
How to remove Alt+F7 window moving hot-key in Xubuntu? I'd like to use `Alt`+`F7` to search for files in `Double Commander`. But when I press `Alt`+`F7` \- the hotkey is intercepted and I am offered to move the window. `Settings - Settings manager - Keyboard - Application shortcuts` doesn't show `Alt`+`F7` to be bound to anything. Where can I undefine `Alt`+`F7` hot key then?
_Settings - Window Manager - Keyboard_ !enter image description here Double Click the short cut field and choose the key-combination you want !enter image description here
stackexchange-askubuntu
{ "answer_score": 39, "question_score": 37, "tags": "shortcut keys, xubuntu, xfce" }
What is the command line for skype installation? > **Possible Duplicate:** > How do I install Skype? I am wondering what the command line is for the installation of skype-ubuntu_2.2.0.35-1_i386.deb from the terminal?
Since Ubuntu 10.04 (Lucid Lynx), Skype is part of the Canonical partner repository. To install Skype first you need to add the Canonical Partner Repository. You can do this by running the command sudo add-apt-repository "deb $(lsb_release -sc) partner" Then install Skype via the Software-Center or via the Terminal. sudo apt-get update && sudo apt-get install skype It is highly recommended to use the package provided in the Canonical partner repository, not the one distributed from the Skype website, as the Skype website currently points users to the wrong package for 64-bit systems of Ubuntu 11.10 and above. * * * Refer to this community documentation for more details in case of any problems.
stackexchange-askubuntu
{ "answer_score": 6, "question_score": 0, "tags": "installation, command line, skype" }
TLSはパケットに送信元IPアドレスが含まれない? HTTPSTLS TLSIP 3TLS - Qiita > TLSHTTPSSMTPIMAPPOP3FTP ()/IP TLSIPTLSIPIPIP IPTLS
TLS TLSTCP/IP Microsoft WindowsSChannelTLS > TLS TCP/IPTLSTCPIP
stackexchange-ja_stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "network, ssl" }
Grouping by date period name in Entity Framework I have table with DateTime? column 'DueOn'. And I am trying to group all rows by this column. var groupBy = new Expression<Func<MyEntity, DateTime?>>(t => t.DueOn); var groups = sequence.GroupBy(groupBy).ToList(); All works fine. But I would like to groups in form of: Yesterday Today Tomorrow Someday if nullable One way i see is to loop through list from result, compare DueOn and copy items to another list with mentioned above groups. But maybe there is more efficient solution for this? Thanks
Without creating an explicit expression object, a way to group dates in predetermined time buckets is this: dates.GroupBy(da => da.HasValue ? da.Value.Date > DateTime.Today.AddDays(1) ? "Future" : da.Value.Date > DateTime.Today ? "Tomorrow" : da.Value.Date == DateTime.Today ? "Today" : da.Value.Date == DateTime.Today.AddDays(-1) ? "Yesterday" : "Overdue" : "Some day") Of course you can store the entire expression in the `groupBy` variable.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, .net, entity framework, group by" }
If $E(X_n) = 1/n$ and $\mathrm{Var}(X_n) = 1/n^2$ then $X_n\to0$ almost surely I would like to show that > If $E(X_n) = 1/n$ and $\mathrm{Var}(X_n) = 1/n^2$ then $X_n\to0$ almost surely. I can not find some relation between the almost sure convergence and $E(X_n)$ and $Var(X_n)$.
**HINT** Chebyshev gives $P(|X_n-1/n| \ge \epsilon )\le \frac{1}{\epsilon^2n^2}.$ Then apply Borel-Cantelli. The key relationship here is that often "in probability" + "Borel-Cantelli" = "almost sure"
stackexchange-math
{ "answer_score": 5, "question_score": 3, "tags": "probability theory, convergence divergence, limsup and liminf, borel cantelli lemmas" }
How to make table row at server side visible using javascript? I am making a tr which runs at server side to invisible. But in some conditions,I want it to be visible.I am using the bellow script to make it visible: document.getElementById('trID').style.display = "block" and also i used: document.getElementById('hidebuttons').style.visibility = "visible"; But it is not working. Please help me on this.
Once control is marked as invisible at server side, no mark-up (html) is emitted for it. So it cannot be made visible at JS, because it (corresponding html) does not exists at client side. you can do something like trID.Attributes.Add("style", "display:none"); then in javascript document.getElementById('trID').style.display = "block" **NOTE** : If you set the control `visible=false` in server side then it will not render at client side
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, asp.net, c# 4.0" }
Why does cmake return an error when i build my c++ code? I want to start learning OpenGL, so I learnt some C++, installed CLion (JetBrains IDE), and tried to make everything work. I work on Ubuntu 20.04. I checked that freeglut and OpenGL are installed, I don't know what else to do. This is the `CMakeLists.txt` file: cmake_minimum_required(VERSION 3.16) project(OpenGlmessing) set(CMAKE_CXX_STANDARD 17) add_executable(OpenGlmessing main.cpp) find_package(OpenGL REQUIRED) find_package(GLUT REQUIRED) include_directories(${OPENGL_INCLUDE_DIRS} ${GLUT_INCLUDE_DIRS}) target_link_libraries(${OpenGlmessing} ${OPENGL_LIBRARIES} ${GLUT_LIBRARY}) And the error I got: CMake Error at CMakeLists.txt:13 (target_link_libraries): Cannot specify link libraries for target "/usr/lib/x86_64-linux-gnu/libOpenGL.so" which is not built by this project.
You might need to remove "$" inside target_link_libraries target_link_libraries(OpenGlmessing ${OPENGL_LIBRARIES} ${GLUT_LIBRARY})
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, opengl, cmake, clion" }