INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
store or check value of getenv() only once in a shared library/DLL I have a function to print debug logs which has to be toggled depending on the environment variable. Instead of checking the env var each time the `print_trace()` is called, what should be the best method to store it and reuse that value? void print_trace(const char* msg) { const char* s = getenv("DEBUG_TRACE"); if(!strcmp(s,"ON")) printf(msg); } There is no `main()` as this is a shared library.
You could save the result of the decision in a static variable. void print_trace(const char* msg) { static int debug_on = -1; // -1 == not yet set if (debug_on == -1) { const char* s = getenv("DEBUG_TRACE"); debug_on = s && (strcmp(s, "ON") == 0); } if(debug_on) printf("%s", msg); }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "c, dll, strcmp, getenv" }
R - Identifying ranges of fixed width by value count Assume an ordered set of 100 binary values. Using a window size of 10, I would like to know the ranges (i.e., start and end position) of those windows that contain at least _x_ "1s" (where _x_ =3, for example). > set.seed(123456789) > full=rep(0,100) > full[sample(1:100, 15)]=1 > split(full, ceiling(seq_along(full)/10)) $`1` [1] 0 0 0 0 0 1 0 0 0 0 $`2` [1] 0 0 1 0 0 0 0 0 0 0 $`3` [1] 0 0 1 0 1 0 0 0 0 0 $`4` [1] 0 0 0 0 0 0 0 1 0 0 $`5` [1] 0 1 0 0 0 0 0 0 1 0 $`6` [1] 0 0 0 0 0 0 0 0 0 0 $`7` [1] 0 0 0 0 1 0 1 0 0 1 $`8` [1] 0 0 0 0 0 1 0 0 0 0 $`9` [1] 0 0 0 0 0 1 1 0 1 0 $`10` [1] 0 0 0 0 0 0 0 0 0 1 Here's what I am looking for: > desired_function(full) 61-70 81-90
An option would be to do a rolling apply function or (`rollsum`) with `width` 10, check if there are 3 1s (binary data), get the position of logical vector with `which`, convert it to buckets using `cut` and get the `unique` values of the bucket library(zoo) unique(cut(which(rollapply(full, 10, function(x) sum(x) == 3)), breaks = c(-Inf, 11, 20, 31, 40, 51, 60), labels = c('11-20', '21-30', '31-40', '41-50', '51-60', '61-70')))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "r, range, binning" }
Text editor with function calls references In the DOS era I used a text editor (forgot the name) which had a outstanding feature. Whenever i was over a function call, hitting a key combination it took me to the function definition. Also, when I was in the function definition, I was able to see all calls to that function. Something like This function is called from: * function1, line 154, source1.c * function3, line 500, source2.c I loved this feature and I miss it. Is there any actual editor with a feature like this? I'm on windows, but if I can get this function, i'm capable of buy a mac :-D (kidding) Update I'm using php. My example was with .c files because I used that editor with c
The most recent versions of **Kate** , KDE's advanced text editor, come with a plugin called **ctags** that does exactly what you want. Since KDE 4, you can install some KDE programs in Windows thanks to the KDE on Windows project. Kate is one of those you can install. Once you have launched it please go to _Settings -> Configure Kate..._ , choose _Plugins_ from the left pane and enable the **ctags** plugin.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "text editor" }
How to use grunt-UglifyJS and sourcemaps? I'm trying to make sourcemaps to play nice while i'm using Grunt and UglifyJS Grunt task. Here is the current task: uglify: { dist: { options: { sourceMap: function(path) { return path + ".map"; }, }, files: { 'dist/video.min.js': [ 'javascripts/video.js' ] } } } What's the problem? The sourcemap is generated but Chrome is searching for the sourcemap in the wrong location ( that is `dist/dist/video.min.js.map`). I know this because i get 404 in console. So I edited `dist/video.min.js` and changed `sourceMappingURL` to point to correct location. Now, the sourcemap is loaded but is looking for video.js in completely wrong place: `dist/javascripts/video.js` (that dist again!) So basically now i'm out of any ideas, just poking the gruntfile with no luck. Any ideas? Thanks!
It seems that < is a potential fix. Bummer, i always find the solution after i post on SO. This place is magic!
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "gruntjs, uglifyjs, source maps" }
Deeplinking - Opening an Ionic App through another Ionic App I'm trying to develope two Ionic applications which are apple to communicate at least in one direction. How do I enable one application to directly open the other one? I have red many things about Deep-Linking but I'm not sure if this is the right way as I only want to open one app (and maybe passing data) through the calling of a function within the other app. Does anyone have experience with this scenario? I'm happy for every answer!
You can use the Custom-URL-scheme plugin Install it like this: cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME=mycoolapp Then in the other app install cordova-plugin-inappbrowser to open the first app like this: window.open('mycoolapp://', '_system'); Then install the Custom-URL-scheme plugin in this app with a different variable and use above code with the different variable value to open the other app. You can get the url (in case you also pass some params) like this: function handleOpenURL(url) { console.log("received url: " + url); }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "android, ios, cordova, ionic framework, deep linking" }
Use awk to print $0 using the same format for all columns Taking an example, I have a file with one line 0.1 35 23.0e3 4.0D+03 and I'd like to convert it to a nicely formatted file like 1.00e-01 3.50e+01 2.30e+04 4.00e+03 I know we can do this in `awk` using the `printf` statement, but that would be tedious if the number of columns is big. I was wondering if there is a way to set the format for all columns, and just use `print $0`?
Considering this input: $ a=$'0.1 35 23e3\n0.2 36 24e3';echo "$a" 0.1 35 23e3 0.2 36 24e3 This gnu awk will achieve what you expect without looping over the fields: $ echo "$a" |awk '{printf "%.2e%s",$0,RT}' RS="[ ]|\n" 1.00e-01 3.50e+01 2.30e+04 2.00e-01 3.60e+01 2.40e+04 I have intentionally exclude `4.0D+03` since does not seem valid.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "linux, string, bash, text, awk" }
GoCD Custom Command I am trying to run a very simple custom command "echo helloworld" in GoCD as per the Getting Started Guide Part 2 however, the job does not finish with the Console saying `Waiting for console logs` and raw output saying `Console log for this job is unavailable as it may have been purged by Go or deleted externally.` ![enter image description here]( My job looks like the following which was taken from typing "echo" in the Lookup Command (which is different to the Getting Started example which I tried first with the same result) ![enter image description here](
Judging from the screenshot, the problem seems to be that no agent is assigned to the task. For an agent to be assigned, it must satisfy all of these conditions: * An agent must be running, and connected to the server * The agent must be enabled on the "Agents" page * If you use environments, the job and the agent need to be in the same environment * The agent needs to have all of the resources assigned that are configured in the job
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "go cd" }
The genus of a curve with a group structure I'm reading Milne's _Elliptic Curves_ and came across this statement: If a nonsingular projective curve has a group structure defined by polynomial maps, then it has genus 1. In this question a similar question was asked, and an answer given there (the one that was not accepted) someone backs this up using machinery/notation that I do not understand. Can someone give or direct me to a proof of this statement? It doesn't have to be very formal; this isn't homework. Also, in the affine case this statement clearly breaks down - the affine line has the group structure of addition, for instance. Is there some sort of correction or does the group structure bear no relation to the genus in this case?
Just to throw another way to formalize this fact, if $X$ is a variety that is a group, then the canonical sheaf $\omega_{X}$ must be trivial. The intuitive reason is that there is a canonical way to identify the tangent space $T_{x}$ at any point $x \in X$ with the tangent space $T_{e}$ at identity. (Namely, the map $y \leadsto y * x^{-1}$). If $X$ is a curve, then Riemann-Roch implies that $deg(K) = 2g-2$, where $K$ is the divisor corresponding to $\omega_{X}$. Since $\omega_{X}$ is trivial, $deg(K) = 0$. This implies that $g = 1$.
stackexchange-math
{ "answer_score": 13, "question_score": 9, "tags": "algebraic geometry, elliptic curves" }
Vagrant ssh code executing gives an error I'm stuck with a silly problem. I'm using **Vagrant** with **Homestead** and **Laravel** for developing. The problem is when I go to a project and try to execute any command it gives me the following error: ![Error message]( I have set the `PATH = "usr/local/bin"`. I'm stuck with this for 2 days and I don't know what to do so If you had the same problem please share your experience with me.
First, be sure that your PATH is set correctly: `PATH=$PATH:/usr/bin:/usr/local/bin` If you're getting a `permission denied` error try giving yourself execute permission on `artisan` and `laravel` like so: `sudo chmod +x /usr/local/bin/laravel`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "laravel, command, vagrant, homestead" }
I reinstalled Ubuntu and while downloading Chrome I am getting "Error: Dependency is not satisfiable: libasound2 (>> 1.0.23):" Due to this error I am not able to I install Chrome in my system. Please help me! Output of `apt-cache policy libasound2` libasound2: Installed: 1.0.27.2-3ubuntu7 Candidate: 1.0.27.2-3ubuntu7 Version table: ** 1.0.27.2-3ubuntu7 0 500 trusty/main amd64 Packages 100 /var/lib/dpkg/status Now getting one more error from Software Center > The system package is broken
I think it can be solved by installing Chrome through repository directly. Just run: sudo add-apt-repository "deb stable main" sudo apt-get update sudo apt-get install google-chrome-stable This works for me. You can also install `google-chrome-beta` or `google-chrome-unstable` to get later versions of Chrome.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 0, "tags": "google chrome, software installation" }
Append/edit JSON file at runtime in iOS5 I have JSON file which has names and details. I want to edit JSON file at runtime as user adds a new name in iPhone application at client side. This means the name should be added in the JSON file when the user adds a name. Is this possible ... and how? Thanks.
Here is a good tutorial for parsing JSON < Apple documentation is also good To be short — you first read JSON to JSON object, then create additional NSDictionary objects, add your data to according dictionaries and then write to JSON object.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios5, xcode4.2, nsjsonserialization" }
Is there any Java MultiMedia Conversion Library I wonder if there is a lib, like Apache Commons, or something of that sort to help convert media-files (e.g. avi, mkv, mp4 etc) any-to-any? For example an InputFile is in format .avi and an OutputFile is in mp4.
The only library I know for that is ffmpeg, but you will have to run it through JNI.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "java" }
Two ordered relations on projections. Let $A$ be a vn-algebra. Let $p$ and $q$ be two projections. In the literature, we say $p$ is majorised by $q$ if $pq=p$. > Q. Suppose that $q-p$ is a positive element in $A$ (meaning $q-p=x^*x$ for some $x\in A$). Is necessary $p$ majorised by $q$?
If $q-p=x^*x $, then $$-(1-q)p (1-q)=(1-q)(q-p)(1-q)=[x(1-q)]^*x(1-q)\geq0. $$ it follows that $(1-q)p (1-q)=0$. Thus $$0=(1-q)p (1-q)=[p (1-q)]^*p (1-q), $$ and $p (1-q)=0$.
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "functional analysis, operator algebras, c star algebras, von neumann algebras" }
Interoperability problems using dataset in .NET I have to consume some web methods in Java but I made the mistake to return Datasets instead of another type which has made the code less interoperable. Here is an example of a webmethod that i want to consume: [WebMethod (Description =" Returns all employees")] public DataSet GetAllEmployees() { RefreshConnection(); SqlDataAdapter sql = new SqlDataAdapter("select * " + " from Employee_Table", OpenConnection()); DataSet employeeDataSet = new DataSet(); sql.Fill(employeeDataSet, "Employees"); return employeeDataSet; } Now I don't know how to get rid of this problem. I'm a beginner in web services so please give also an explanation of your solution.
I think I solved the problem by converting the result of sqlDataReader to a List with strings. [WebMethod (Description =" Returns all employees")] public List<string> GetAllEmployees() { RefreshConnection(); List <string> data = new List<string>(); SqlCommand sqlData = new SqlCommand("select * " + " from Employee_Table", OpenConnection()); SqlDataReader sqlReads = sqlData.ExecuteReader(); while (sqlReads.Read()) { data.Add((string)sqlReads.GetValue(1)); data.Add((string)sqlReads.GetValue(2)); } return data; } And in java by the proxy object: private List<String> getEmployee() throws RemoteException{ return Arrays.asList(proxy.convertToList()); } Now my problem is how to differ between two columns?The array takes all in without formatting the result as it would be by using a resultSet.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net, web services, dataset" }
How do I solve the JavaScript error: method XX is undefined? I am working on asp.net and jquery website , and when run browse the site an java script error has occurred . Visual studio debuger references that GetMainFrameUrl is undefined : function EBNavigateComplete() { if (!GetMainFrameUrl()) { navCounter++; if (navCounter%100==0) { o.loadEmptyTerm(); counter = 0; } } else { if (o.pbNavigateComplete(GetMainFrameUrl())) { counter = 0; } } } is there help please???
Are you using the Conduit API? If so, do you have that script library referenced? < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, asp.net, jquery" }
Show that $\prod x_i \ge 1$ is a convex set I'm trying to generalize this question to arbitrary $n$ dimensions, i.e. to show that $C = \\{x\in \mathbb R^n_{++} : \prod_i^nx_i \ge 1 \\}$ is convex. At first I thought maybe through induction, but I reached a dead end there. Any suggestions?
The set can be expressed as $$\left\\{ x \in \mathbb{R}_{++}^n : \sum_{i=1}^n \log x_i \geq 0 \right\\},$$ which is convex as $g(x)=\sum_{i=1}^n \log x_i$ is a concave function.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "convex analysis" }
mysql connector problems I have problems with MySQL Connector (MyConnector) it seem there is a problem when I modify my connection via ODBC, I can create new entries, but I am unable to edit them.. I found a patch for windows 7, 32Bit. but I also need a fix for Windows 7, 64bit.
It appears that the connector for Windows 7 is 64-bit is the same as the one for 32-bit(x86) < Would the patch be different for the two CPU types?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql, odbc" }
Split a string in AngularJs 2 I have an object profileObj.details[0].time which is equal to "10AM-4PM" I want to split this string into **10AM** and **4PM** . please help to solve this issue. Thanks in advance
You can use `.split` together with `array destructuring`: const [first, second] = "10AM-4PM".split('-'); console.log(first); // 10am console.log(second); // 4pm
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -1, "tags": "javascript, html, typescript" }
MySQL easier join with fixed table reference I'm starting to learn/use SQL and I'm wondering if I can make the usage easier. I have tables with ID which reference each other. So I often issue queries like SELECT ... FROM Object o JOIN Property p on o.uid=p.object_uid AND ... There are other tables with similar ID references. Is there a comfortable way to avoid writing out these ID clauses over and over again? I mean that particular Object table will always reference the Property table this way.
As far as I know, with using the alias functionality you are doing the best you can shortening the query. Alternatively there is a shorter syntax but only there a similar field in both tables a LEFT JOIN b USING (c1,c2,c3) < all the best
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, join" }
Consecutive assignments in python Is it legal to do a = b = 3 in python? If so, is it a bad practice?
Yes, it is legal to do so. No, it is not bad practice. Just take into account that the right-hand side, the value expression, is evaluated first, and assignment then takes place from left to right; `3` is assigned to `a` first, then to `b`. From the assignment statement documentation: > An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. You assign _the same value_ to all targets. That means that each variable refers to _one_ value only. This is important when that value is mutable, like a list or a dictionary.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 1, "tags": "python, variable assignment" }
How to get work item Id using link source Reference? I am using the below code to fetch parent and children of the work item and I got link reference, Now I want to fetch the work item Id from object. Please help IReference reference = linkManager.referenceFactory().createReferenceToItem(workItem .getItemHandle()); ILinkQueryPage page; ILinkQueryPage page1; page = linkManager.findLinksByTarget("com.ibm.team.workitem.linktype.parentworkitem", reference, monitor); ILinkCollection linkCollection = page.getLinks(); Collection childWI = linkCollection.getLinksById("com.ibm.team.workitem.linktype.parentworkitem"); System.out.println(childWI);
ILinkCollection linkCollection = page.getLinks(); Collection childWI = linkCollection.getLinksById(...) That means you have a collection of ILink(s). As seen here, it is easy to resolve a link to a WorkItem: for (ILink l : links) { IItemHandle linkHandle = (IItemHandle) l.getTargetRef().resolve(); if (linkHandle instanceof IWorkItemHandle) { IWorkItem aWorkItem = (IWorkItem) teamRepository.itemManager().fetchCompleteItem(linkHandle, IItemManager.DEFAULT, monitor); } } Each `WorkItem` has a `getId()` method to access its ID.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "java, api, rtc, workitem" }
Converting LINQ to loops in C# using resharper I am using Resharper 6.1 and I am pretty sure there is a way to convert LINQ into the loops. They have listed that functionality as one of their version 6 features here. < it also "sometimes" allows me to do it by showing a little pop-up besides my code asking me if I want to convert the LINQ expression into a loop. But I am not sure under which condition does it show that little pop-up. Any ideas?
Resharper is smart. But not smart enough to understand every linq query. If it's simple enough to convert then reshaper will understand it's possible and will show you the hint (which you can control under Resharper -> Options -> Inspection Severity). When the linq expression is not simple enough for resharper to understand it can't know how to convert it..
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, .net, linq, resharper, resharper 6.0" }
R fill matrix based on element names from data frame If I have data that may be modelled as so: a1 <- c("bob","bill",0.2) a2 <- c("bob", "bert", 0.1) a3 <- c("bill", "bert", 0.1) my.df <- as.data.frame(rbind(a1, a2, a3), stringsAsFactors = FALSE) colnames(my.df) <- c("name_1", "name_2", "value") row.names(my.df) <- NULL my.names <- unique(as.character(c(my.df$name_1, my.df$name_2))) my.matrix <- matrix(0, nrow = length(my.names), ncol = length(my.names)) row.names(my.matrix) <- my.names colnames(my.matrix) <- my.names How may I fill `my.matrix` using the values from `my.df`. The first two columns in `my.df` describe the coordinates of `my.matrix` to fill?
You can coerce the first two columns of `my.df` into an index matrix, and index-assign `my.matrix` with the remaining column of `my.df` as the RHS: my.matrix[as.matrix(my.df[c('name_1','name_2')])] <- as.double(my.df$value); my.matrix; ## bob bill bert ## bob 0 0.2 0.1 ## bill 0 0.0 0.1 ## bert 0 0.0 0.0 I also coerced the RHS to a double, since I assumed you want to preserve the type of `my.matrix`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "r, matrix, dataframe" }
How to find out do I have NAND Flash or NOR flash (Compact Flash) How to find out do I have NAND Flash or NOR flash (Compact Flash) I have Transcend UDMA 300x 2Gb. No mention is it NAND or NOR flash
NOR flash is byte-addressable. It's usually used in applications where a CPU needs to execute code from it directly, like BIOS or boot ROM firmware. NAND works in blocks somewhat like disks. So generally anything else, especially in memory card or storage device situations, is going to be NAND. Some NAND has a "Disk On Chip" mode where block 0 can be executed directly, but not any other blocks. You could always open up the card and run any numbers on ICs you find within through Google to absolutely confirm.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "compact flash" }
getting table contents with javascript how to read data from a table that haven't any id <table> <tr> <td>td 1</td> <td>td 2</td> <td>td 3</td> </tr> <tr> <td>td 1</td> <td>td 2</td> <td>td 3</td> </tr> <tr> <td>td 1</td> <td>td 2</td> <td>td 3</td> </tr> </table> i need the text inside td1 and td3 of all tr's
This efficient code to do. let result = document.querySelectorAll('tr td:nth-child(1), tr td:nth-child(3)'); console.log("result", result); let len = result.length; for(let index=0; index < len; index++) { if (index%2 == 0) { console.log("td 1 data ---", result[index].textContent); } else { console.log("td 3 data ----", result[index].textContent); } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "javascript" }
Using doubleclick to catch x,y coordinates outside of a form C# I'm making a form application in C# and what I need is to able to capture x,y coordinates outside of the form when the user doubleclicks. I have not been able to find anything that can help me. I'm new to C# so I might be looking for the wrong thing. Any help would be appreciated. Thanks,
This old MSDN blog has sample code for using `WH_MOUSE_LL`, a low-level mouse hook that you can use to capture mouse events in Windows. Mouse hooks do not distinguish double clicks however, you will need to do that yourself. You can use `SystemInformation.DoubleClickTime` and a timer to determine if the click was a double click or not.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, events, click, mouse, double click" }
Double suffixes? Is there any specific rule which forbids the same **suffix applied twice in a row**? Context: I've randomly tried to imagine what programming variables would be called in Esperanto and realized that "workshopFactory" is technically _laborejejo_ , since it's a place where places for working reside. So I tried creating more -- I've thought that you could jokingly say that you're _laboremema_ , meaning you're eager to be eager to get working on something, in a sense that you're lazy. In a similar way you can go overboard with -aĉ-, like _hundaĉaĉo_. I have a feeling that -ar- (along with my original -ej-) might be the easiest to imagine, like a group of forests in close proximity could be _arbararo_ , but they still keep looking fabricated to me. I couldn't come up with something more concrete and common, so I'm also wondering: are there **common words** which use this pattern?
There is no rule that forbids the combination of affixes in Esperanto, **as long as the resulting words have a recognizable sense**.* There is, however, outside joking/mocking language (IIRC Karol Pič named Richard Schulz "tradukantanto", in order to mock his overly complicated style), no example known to me where the same affix would appear twice and have a clear sense. In any case you should know that "stacking" affixes does not reinforce their meaning, so your *hundaĉaĉo wouldn't do the trick. *There may be some minor exceptions, which however are not worth consideration here. TL;DR: Nothing forbids you to do so, but there are hardly any use cases.
stackexchange-esperanto
{ "answer_score": 7, "question_score": 9, "tags": "word formation" }
Impersonating an Assembly I have 2 compiled assemblies. Assembly A references assembly B. I would like to change some code in assembly B. I would like to create a class library that impersonates assembly B in the eyes of assembly A. I want assembly A to continue working with my new types and namesspaces as if nothing ever happened. Can I just create the new assembly with the same name and version number? Will assembly A assume that the new assembly is just like the old assembly B?
Assuming that the original assembly is not signed and the old assembly's interface is a subset of the new one's (could be the same), you should be ok. It would basically be the same as changing all the internals of B and possibly adding new methods without updating the version number.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "impersonation" }
Riddle about a big family We are a big family. We are of alien origin, but bear Latin names. We are all descendants from one, but some of us are born "in vitro". Our 101st family member, although is not noble, and is not "the one", is the one that united us as a family.
You're > the chemical elements. Reason: > There are very many of them; humans did not make them; many have names derived from Latin; each is made from fusion of hydrogen; some are made in the lab; and finally, the 101st element, Mendelevium, is not a noble gas, but its namesake (Dmitri Mendeleev) was the one to make a periodic table like the one we use today.
stackexchange-puzzling
{ "answer_score": 11, "question_score": 8, "tags": "riddle" }
how can i get the selected value of dropdown list in php? i have seen several question but i can not find any answer? i am add a some value to dropdown through the loop and want to show the value when i select one value from dropdown box .but i can not find . $items[] = $file ; echo '<select name="value">'; foreach($items as $video){ echo '<option value="' . $video . '">' . $video . '</option>' ; } echo '</select>'; $value = $_GET['footage']; How can I get the value when I select some value in the dropdown box.
You need to add `HTML selected` attribute to `<select>` $value = $_GET['footage']; /* typo*/ $items[] = $file ; echo '<select name="value">'; foreach($items as $video){ $selected = ($value == $video) ? 'selected="selected"' : ''; echo '<option value="' . $video . '"' . $selected . '>' . $video . '</option>' ; } echo'</select>';
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, html" }
How do I assign a axios put request's response to variables I'm trying to assign a value from my axios' response to a variable. How do I assign ContactID to a variable to use further? my axios response: `{"0":{"Type":"ACCREC","Contact":{"ContactID":"b612f859-b9ea-4b98-a888-f0a666f859d4","AccountNumber":"TestingSylvester","ContactStatus":"ACTIVE","Name":"Testing }}}` my axios request: .then(function (response) { console.log(JSON.stringify(response.data)); this.axiosResponse.push(JSON.stringify(response.data)); }) .catch(function (error) { console.log(error); }); I tried this, but I get the error: "Cannot read property 'axiosResponse' of undefined"
Most likely `this` is not bound, which would explain the error message you are getting. Check how can I retrieve a reference to this in a promise.then ()?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vue.js" }
Is stereo olfactory ability restricted to humans? Most animals I see around seem to have two nostrils - humans, snakes, birds, fish .. and so on. From reading online I see that 2 nostrils provide a stereo olfactory effect. This stereo effect is caused by the difference in flow of air through the nostrils. Does this stereo effect apply only to humans? Are there any animals that have a different number of nostrils? Say, more than 2, or less.
Moles and rats also smell in stereo (Catania 2013 and Rajan et al 2006), as do desert ants (link). The latter is rather interesting, given that ants "smell" using their antennae, which suggests multiple sensory structures, not necessarily nostrils, are required for stereo olfactory ability. EDIT: Hammerhead sharks have two nares and also stereo olfactory ability (here). Dolphins have one spiracle, as do a number of other cetaceans. ~~It's actually not clear whether humans have stereo olfactory ability,~~ **(see edit below)** as the "stereo" aspect derives from having nostrils that are sampling from different spatial locations. However, the research in the eastern mole suggests that this is not so far-fetched an idea, as their nostrils are not so far apart. EDIT of EDIT: I take that back about humans: we do appear to have stereo olfaction.
stackexchange-biology
{ "answer_score": 1, "question_score": 1, "tags": "physiology, anatomy" }
How to panning camera on XZ axis with different angles I have an Orthographic camera where the position is `{ x:0, y:100, z:0 }` and is pointing/looking at `{ x:0, y:0, z:0 }`. At this point, I'm able to capture the mouse movement and translate it to make the pan correctly. If the mouse goes 10 px down/y I just have to move Z in the 3D world. The problem is that I don't know how to calculate if the camera position is in perspective, let's say: position: { x:50, y:50, z:50 } lookAt: { x:0, y:0, z:0 } I guess I have to use some trigonometry, but I'm very lost, to be honest. Any guide would be very helpful.
You can construct the camera's forward direction vector as: forward = normalize(lookAt - position) Then you can construct a vector pointing to the camera's right like so: right = normalize(cross(worldUp, forward)) (Or the negation of this if you're in a right-handed coordinate system) And lastly you can construct a vector pointing along the camera's local up direction like so: up = cross(forward, right) (Again, negate if you're in a right-handed coordinate system) Then you can pan the camera by adding a multiple of these `right` and `up` vectors to its position. You'll likely want to move the lookAt point by the same amount, unless your goal is to orbit around the point.
stackexchange-gamedev
{ "answer_score": 2, "question_score": 0, "tags": "camera, mouse, trigonometry" }
Libgdx change to other screen and dispose current one I am trying to switch to a GameScreen when the LinearVelocity of a Box2D - Object is x = 0. If it is so, I am using the setScreen() - Method by calling the main class. This works perfekt, but when the screen should change, it just flickers, which is most likely caused by the render() - method in the screen class. So my question is now, how to dipose that render method or how to dispose the whole screen class, so that I only the new screen appears! Thanks
The **libGDX** `Game` class delegates to a single `Screen` so if your game is flickering between the new `Screen` and the old `Screen` after you call `Game.setScreen` it is likely because the new `Screen` sets the old screen back.
stackexchange-gamedev
{ "answer_score": 1, "question_score": 1, "tags": "libgdx, rendering, box2d, screen" }
How to dynamically get MTM/TFS Test Case ID calling associated automation Right now our test base has 1:1 association in that for every Test Case on MTM/TFS - there is a C# test class that is associated to that test case only. Within the test class the test case ID is hard coded as a value and that's how the data parameters are retrieved from the MTM/TFS Test Case to be executed at run time. Unfortunately this has caused a lot of bloat and a lot of test cases that aren't much more than copy/pasted templates with the hardcoded test case Id being modified. _Is there a way for a SINGLE C# TestClass to retrieve the data dynamically from the MTM/TFS Test Case that is associated with it? And therefore the ability to have many MTM/TFS Test Cases associated to that SINGLE C# Test Class?_
If you are looking to get test case id from code within a test case class, you can get it from the TestContext instance. The following blog post gives you the list of a properties present in the class. < The following code will give you the test case Id var testCaseId = TestContext.Properties["__Tfs_TestCaseId__"].ToString() Hope it helps
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, unit testing, tfs, microsoft test manager" }
In the AWS Appsync resolver, is it `$util.` or `$utils.`? The AWS Appsync documentation seems to use `$util.` and `$utils.` interchangeably. Are they actually different, or synonyms of the same thing? Best example is the the resolver transformation helpers documentation page where they appear side by side... ![screenshot of appsync developer guide](
Yes, you can do both. It's like ctx and context, they are interchangeable.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "aws appsync" }
Display an error when user enters a number instead of a string I've tried to find something on this but have not seen anything related in the past hour of searching. I am looking to throw an error when the user tries to enter a number instead of a String. I've found more than enough resources on how to throw and error when the user enters a string instead of a int, but nothing about the other way. I'll just make up some code real quick import java.util.Scanner; public class ayylmao { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter your first name"); String AyyLmao = scan.nextLine(); System.out.println("Your first name is " + AyyLmao); /* Want it to say something like "Error: First character must be from the alphabet!" if the user tries to enter a number. */ } }
If it's only the first character you're interested in, you could use a test like this: if (AyyLmao.charAt(0) >= '0' && AyyLmao.charAt(0) <= '9'){ /* complain here */ } A test on the whole string, as you apparently have found out already, would be: try{ Integer.parseInt(AyyLmao); /* complain here */ } catch(NumberFormatException ex){ /* this would be OK in your case */ }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, string" }
How to take screenshot for window I'm beginner in Qt/C++ programmation and i want to get screenshot of my window using Qt. #include <qapplication.h> #include <qpushbutton.h> int main( int argc, char **argv ) { QApplication a( argc, argv ); QPushButton hello( "Hello world!", 0 ); hello.resize( 100, 30 ); a.setMainWidget( &hello ); hello.show(); return a.exec(); } Anyone can help me please ?
Here is a short way to take a screenshot of a specific window : /* Take a screenshot of a window Notice that window is a: QWidget *window; */ originalPixmap = QPixmap::grabWidget(window);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++, qt" }
Conversion Class Extensiblity (Extension Methods vs Parital Class) I am creating a conversion class for frequency, and I wanted to allow my team to be able to add additional conversions when they are needed. Frequency myFrequency = new Frequency(100, MHz); double value = myFrequency.InKhz(); The source code for the class will not be include in future projects, so I will either have to have the class be a partial class or the additional conversions will need to be extensions. An example would be adding a conversion to GHz myFrequency.InGHz() Which is the best way to proceed with this? Update: After reading Randolpho's answer I am going with the extension method approach. As time allows the extensions will get rolled into the base code, but I didn't want to make the other team members wait for updated assemblies and this allows them to move on to the next task a little faster.
Partial classes will not work unless you have the original source. If you are denying the developers access to that source, their only alternative is to use extension methods. That said, you probably just want to have a process to update the library with new additions; it looks like they'll be rare.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c#, extension methods, partial classes" }
SQL: Increment row value when selected Within Amazon RDS, I have a table, `source`, in the form of id | name | times_shown ------------------------ 0 | matt | 0 1 | jeff | 0 2 | jake | 0 . | ... | . . | ... | . . | ... | . I have a SQL query that randomly selects a row from this table SELECT * FROM source ORDER BY RAND() LIMIT 1; Is there a way for me to modify this query so that when it selects a row, it also causes the value of the `times_shown` column to increment? If not, is there some other way, maybe an obscure column type or PHP SQL PDO driver setting, that would let me do this? From my understanding, this SO question asking something similar is about changing the results of the SELECT, rather than actually changing the value in the db as I am hoping to do.
What RDMS? If MySQL, probably need to do in two parts, change your `SELECT` to `SELECT ... FOR UPDATE` and then separately update the `times_shown` field Take a look at: < And the example there: SELECT counter_field FROM child_codes FOR UPDATE; UPDATE child_codes SET counter_field = counter_field + 1;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, sql, select, increment, amazon rds" }
Return the nth record from MySQL query I am looking to return the 2nd, or 3rd, or 4th record from a MySQL query (based on a query by ID ascending) The problem being, I won't know the ID, only that it is the 3rd row in the query.
`SELECT * FROM table ORDER BY ID LIMIT n-1,1` It says return one record starting at record n.
stackexchange-stackoverflow
{ "answer_score": 122, "question_score": 64, "tags": "mysql" }
Create dynamically a webpage according to variables and save it I've created a website which takes the parameters of a query and I'd like to create and redirect to a webpage having as URL my_site/first_parameter-second_parameter.php So far I am able to display in the browser the address of the page but the thing is that I don't know how to really create and save it.
If i understand your question correctly, you can just create html files at the location that you receive? Ist that what you want? < You can then use your location inside fopen. (Make sure, that the user associated with the webserver has the access rights on that path). And then you can write your contents into that file.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, url, web" }
equality of two sums Is $\sum _{t=1}^m \sum _{k=t}^m (a_{k+1}-a_k)b_t$ equal to $\sum _{k=1}^m \sum _{t=1}^k (a_{k+1}-a_k)b_t$? If not, then how to derive equations for temporal difference algorithm in machine learning: page 14 at the end, and page 15 equation (3). < It seems like an error?
$$\begin{align} \sum_{t=1}^m\sum_{k=t}^m(a_{k+1}-a_k)b_t & =\sum_{t=1}^m((a_{t+1}-a_t)b_t+(a_{t+2}-a_{t+1})b_t+\cdots+(a_{m+1}-a_m))b_t\\\ & =(a_2-a_1)b_1+(a_3-a_2)(b_1+b_2)+\cdots+(a_{m+1}-a_m)(b_1+\cdots+b_m)\\\ & = \sum_{k=1}^m\sum_{t=1}^k(a_{k+1}-a_k)b_t. \end{align}$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "summation, arithmetic" }
Drop multiple mysql databases with a shell script I am migrating one large SQL file that contains all the databases from server A to Server B. Before I can import the file I need to drop all the databases that will be recreated with the import on server B. How do I programatically remove multiple mySQL databases with a shell script while preserving specific databases such as `information_schema`.
The following selects all the databases available to your mySQL user. It then filters out the databases you want to preserve using `grep`. DBUSER='user' DBPASS='password' SQLFILE='/path/to/file/databases.sql' echo '* Dropping ALL databases' DBS="$(mysql -u$DBUSER -p$DBPASS -Bse 'show databases' | grep -v -e '[dD]atabase' -e mysql -e information_schema -e test)" for db in $DBS; do echo "Deleting $db" mysql -u$DBUSER -p$DBPASS -Bse "drop database $db; select sleep(0.1);" done There were some partial answers but I'm hoping this will save some people some time. TIP: You test with `$ echo $DBS` to see which Databases will be selected to be dropped after you type your first command. `DBS="$(mysql -u$DBUSER -p$DBPASS -Bse 'show databases' | grep -v DatabaseToFilter)"`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, linux, shell" }
Open maps iphone app from my app, with pin drop at the coordinate I'm using < to open maps iPhone app from my app, but it only show the coordinate without the pin drop automatically. How can i make the pin to drop automatically?
You are required to pass lat-long by appending into the URL like following way - <
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 3, "tags": "iphone, google maps" }
Как сделать изменяющуюся(динамичную/анимированную) иконку приложения Android? У некоторых системных приложений вроде Календаря и Часов имеются динамично меняющиеся иконки. У календаря на иконке отображается число текущего дня, а у часов на иконке каждые 5 минут обновляется состояние стрелок, показывающих время. Можно ли как-то реализовать такую иконку в своем приложении?
Это не совсем иконки, а виджеты приложений. API создания виджетов известно и открыто. Ссылка на официальную документацию Краткий туториал здесь Касательно комментария @Style-7 - он ссылается на инструкцию (сильно устаревшую) по созданию shortcut'а (ссылки) на приложение в Home Screen.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "java, android" }
Does anyone have the datasheet for this display? Does anyone have the datasheet for this display there is no serial number or Ebay link. A student came to me with this 4 digit 7 segment LED, there are 12 pins in one side, and nothing on the other side. Model number is, WP02841MGA. !7
after testing, this is the result :) thanks everyone - if someone have problem just use this always the (-) is the first number !led
stackexchange-electronics
{ "answer_score": 9, "question_score": 1, "tags": "led matrix" }
Use VirtualBox to access site on host from guest? I'm running VirtualBox on a Mac (host), the VM i'm using is windows 7 (guest). VirtualBox is setup to use the `NAT` network adapter, and I'm able to get to the internet just fine (google, msn, everything) however I'm hosting a site on the Mac(host) and I cannot access it from the VM. The guest is assigned the IP `10.0.2.10` and my host's IP is `10.0.2.100`, I think the issue might be that these are separate networks, but I don't know. I just want to test the site in IE (I don't have a separate/remote server to host it on)
You should really consider switching from NAT to bridged mode. This way both "systems" will be on the same network. When you run with NAT it subnets the network and your VM effectively exists in another network. In order to make it work with NAT you will need to configure (through configuration files, not GUI options) the NAT routing to open connections/ports between the networks, and also setup routing tables. If you set bridged mode, the VM requests the IP from the same router that your host does, instead of from the VM system on the host. In turn it will be as easy as just going to the IP of your host.
stackexchange-superuser
{ "answer_score": 6, "question_score": 5, "tags": "windows 7, macos, networking, virtualbox" }
How to correctly inherit std::iterator Guys if I have class like below: template<class T> class X { T** myData_; public: class iterator : public iterator<random_access_iterator_tag,/*WHAT SHALL I PUT HERE? T OR T** AND WHY?*/> { T** itData_;//HERE I'M HAVING THE SAME TYPE AS MAIN CLASS ON WHICH ITERATOR WILL OPERATE }; }; Questions are in code next to appropriate lines. Thank you.
As a starting point, your value type should be the type of object your container holds. My guess would be either T or T*, you don't really provide enough information to say. See here for an explanation of what the various parameters mean. The rest can often be left as defaults.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "c++, iterator" }
What's meant here by "pattern"? In "The Song of Flying Fish" by G. K. Chesterton, the author was describind the dreams of someone, saying: > Boyle, being young, was naturally both the healthier and the heavier sleeper of the two. Though active enough when he was once awake, he always had a load to lift in waking. Moreover, he had dreams of the sort that cling to the emerging minds like the dim tentacles of an octopus. They were a medley of many things, including his last look from the balcony across the four grey roads and the green square. But the **pattern of them** changed and shifted and turned dizzily, to the accompaniment of a low grinding noise, which sounded somehow like a subterranean river, and may have been no more than old Mr. Jameson snoring in the dressing-room. What's meant here by "pattern", I mean how "pattern" can turn to "noise"?
In the context of this dream, the dreamer is seeing these things: four grey roads and a green square. But, like it happens in a dream, they shift and change shape, and no longer appear as the (implied) square, but twist around "dizzily". The "pattern" in this context means "the visual arrangement", which changes in dreamspace to something more chaotic and less easy on the eye. The "noise" is another concept being introduced at the same time, and is independent of the "pattern" being seen -- or should I say, they are "dependent" only in the sense that they are happening together.
stackexchange-ell
{ "answer_score": 2, "question_score": 0, "tags": "meaning" }
How to calculate velocity of the ship in the direction of the current? A ship travels with velocity given by [1 2], with current flowing in the direction given by [1 1​] with respect to some co-ordinate axes. What is the velocity of the ship in the direction of the current? Can anyone please help me with this question with intuition behind it?
Since the problem is using velocity as a vector, we can continue that. If you want speed, the take the absolute value of the answer. We want the projection of the ship velocity onto the current velocity. Let $u=(1,2)$ the ship. Let $v=(1,1)$, the current. $$v\cdot \left ( \frac{u\cdot v}{|v|^2} \right )=(1.5,1.5)$$ Intuitively, we want to divide the ships velocity into x and y parts where the x part is in the direction of the current and the y part is 90 degrees to the current. You could do that any number of ways, but the easiest way to write notation, is the one shown.
stackexchange-math
{ "answer_score": 9, "question_score": 2, "tags": "linear algebra, vectors" }
Flag Declined although suggested action was followed I flagged Hide TD into DIV Using jQuery as a duplicate of Hide TD into DIV Using jQuery which are exact duplicates. I voted to close it as an exact duplicate and also flagged it and mentioned in the comment that it might be a good idea to merge the two ( _as both had comments/answers_ ), if possible, to a single Question. The flag was declined with **_declined - The other post was closed and the answers merged with this one_** Is that a valid decline reason ? ( _the fact that the merge was not done from Question-1 to Question-2 but instead from Question-2 to Question-1_ ) I am just asking for clarificaion reasons. ( _not hurt or anything.._ )
This was my doing, it was not an unintentional dismissal of the flag. I had performed all of the actions outside of the browser window. When I returned to the browser window with the mod queue, it was refreshed, and I lost track of the fact that it was you that submitted the flag in the first place by the time I saw the flag again. I would have marked it as "helpful", but at that point, the merge had already been done, and I thought it was a flag from someone else, to which I wanted to convey the message that it had already been done. Unfortunately, the _only_ way to send a message is to decline. It was a mistake on my part, and I apologize that it conveyed the wrong message, and impacted your flag weight.
stackexchange-meta
{ "answer_score": 7, "question_score": 12, "tags": "discussion, flags, merged questions, declined flags" }
Rational points on a circle with centre $(\pi, e)$ A circle is centred at $(\pi,e)$. What is the maximum no. of rational points it can have? (A rational point is one with both coordinates rational). 1 rational point is definitely possible, just choose any rational point, and alter the radius to get it through. My book says that only one rational point is possible, as $\pi\neq qe\quad q\in Q$. That's their whole explanation. I don't understand how that's enough. **Edit:** It has been pointed out that the problem is equivalent to showing $q_1\pi+q_2e=q_3$ has no non trivial solutions. Is this known to be true? Can someone prove it in an elementary way?
Okay I got it, suppose it passes through (a,b). Then the equation of circle is $x^2-a^2+y^2-b^2-2\pi( x-a)-2e(y-b)=0$ If x and y are both rational then $q_1\pi+q_2e=q_3$ with not everything 0 .I still have to prove this impossible. I don't think it's equivalent to $\pi \neq qe$. **Edit:** As has been pointed out to me, two rational points are not possible if $\pi $ and $ e$ are linearly independent over the rationals, and this is still an open problem
stackexchange-math
{ "answer_score": 10, "question_score": 13, "tags": "geometry, elementary number theory" }
Why doesn't the law of total expectation apply here? $E[X] = E[E[X \mid Y]]$ I'm learning about Entropy for the first time. From Wikipedia, $$H(Y \mid X = x) = E[I(Y) \mid X=x]$$ and the confusing part for me is this statement: " $H(Y \mid X)$ is the result of averaging $H(Y \mid X = x)$ over all possible values $x$ that $X$ may take. " This reminds me exactly of $E[X] = E[E[X|Y]]$. **My question** It seems to me $H(Y \mid X)$ should equal $H(Y)$ but this is wrong. Here's why I think this... because of the total law of expectation, $$H(Y \mid X) = E[H(Y \mid X)] = E[E[I(Y) \mid X]] = E[I(Y)] = H(Y)$$ Can you help me understand where I'm going wrong? Thank you.
Your mistake is $$ H(Y|X)=E[H(Y|X)]. $$ There is no reason for this to be true.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability, entropy" }
Where does Cthulhu slumber in "The Call of Cthulhu"? I know it's in the ocean, and off the coast of an uncharted island, but I'm not sure where the island is. I'd been thinking it was Antarctica but I recently realized I was confusing it with _At the Mountains of Madness_.
From the Wikipedia article on R'lyeh: > * Lovecraft claims R'lyeh is located at 47°9′S 126°43′W. _[H.P Lovecraft, "The Call of Cthulhu" (1928)]_ > * Writer August Derleth, a contemporary correspondent of Lovecraft and co-creator of the Cthulhu Mythos, placed R'lyeh at 49°51′S 128°34′W. _[Derleth, A. The Black Island (1952)]_ > > > The latter coordinates place the city approximately 5,100 nautical miles (9,400 km) from the actual island of Pohnpei (Ponape), the location of the fictional "Ponape Scripture". Both locations are close to the Pacific pole of inaccessibility (48°52.6′S 123°23.6′W), a point in the ocean farthest from any land mass.
stackexchange-scifi
{ "answer_score": 19, "question_score": 10, "tags": "h p lovecraft, the call of cthulhu" }
Can allelopathy succesfully be used against algal blooms? Algal blooms caused by man (harmful algal blooms) are a major ecological problem. An excessive amount of algae causes hypoxia and logically, most marine wildlife can't be sustained in hypoxic conditions. Can't we use allelopathic plants to reduce the amount of algae significantly?
This has been tried and it sorta works. Algae in general seems to be inhibited by rotting barley straw in the water. There is also an observation (not universally accepted) that many plants in the water do not have as much algae. This post is from April 2011, so it seems pretty current.
stackexchange-biology
{ "answer_score": 3, "question_score": 8, "tags": "ecology, allelopathy" }
Custom routes in rails I have a users controller. For a specific user I want to have something like this example.com/a_constant_string ==> example.com/users/2 I just need for a specific user, not for all users. You can say link_to 'Go to a specific user', @user link_to 'Go to a specific user', user_path(@user) link_to 'Go to a specific user', a_constant_string_path Should be same.
You could create a redirect route in config/routes.rb: match '/a_constant_string', :to => redirect("/users/2") Which would redirect to the correct path, and gives you the URL and PATH helpers: `a_constant_string_path` and `a_constant_string_url`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "ruby on rails, ruby on rails 3, routes, custom routes" }
PIN password: possibilities with several users in an attempt. I have a $4$-digit PIN and a list "user:pin". The possibility of guest the PIN's user is \frac{1}{10.000}. Example: user1:0001. But if I try 10.000 user at the same time what is the possiblity?. Example: user1:0000, user2:0001, ..., user10000:9999. Is it something like the birthday paradox?.
The probability of zero correct guesses is $$p_n=\left(\frac{9999}{10000}\right)^n$$ where $n$ is the number of guesses. You can see that $p_n\to0$ as $n\to\infty$, however it may take some time to reach low values. For $n=10000$, the probability of having zero correct guesses is about $37\%$, so there is a probability of $63\%$ of guessing at leas one password.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability" }
Resize GIF and save animation? I'm using this code i wrote to resize my images to fit my PictureBox: //Creates a new Bitmap as the size of the window Bitmap bmp = new Bitmap(this.Width, this.Height); //Creates a new graphics to handle the image that is coming from the stream Graphics g = Graphics.FromImage((Image)bmp); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //Resizes the image from the stream to fit our windows g.DrawImage(Properties.Resources.loading, 0, 0, this.Width, this.Height); this.Image = (Image)bmp; Works perfect ! The only problam is when im trying to resize a GIF... it resizes but i lose the animation... Any fix for that?
You should simply set the PictureBox's `SizeMode` to `StretchImage` to make the PictureBox stretch the image for you.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c#, .net, graphics, picturebox, animated gif" }
Passing parameter map (list of values) to JQuery to initialize a javascript loaded grid, I need to pass a list of values from controller/gsp. Since the javascript is activated once the page is rendered/loaded, there may not be a direct way to do it. 2 possibilities 1\. do an ajax call, and retrieve the list of values from the server 2\. store the list in html as a hidden element, and read it from javascript. option 2 seems better as it avoids few calls back to server. So, which control should I use for a list of values? Any jQuery code snippet to read it back into array/list. thanks in advance.
It depends on the size of that data. It it's small enough, you could embed it in the page. For example, to populate a calendar with events, I used something like: <div id="calendar" data-events="[/* event list */]"></div> (the `data-events` attribute contained a JavaScript array of event objects in JSON format) However, if you're talking about a huge amount of data, loading it (possibly in chunks) asynchronously after the page load (or when the document is ready) could increase your app's performace and make it more interactive (i.e. I don't want to wait and load that data if the next thing I'm gonna do is navigate away) Does that answer your question?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, grails" }
Apache/nginx are running but browser show connection failure I have just installed nginx and apache on a dedicated server with redhat, how ever when I go to < I get a connection failure. I tried changing nginx port con conf, but it didn't work neither. Both services are running: /etc/init.d/httpd status httpd (pid 22498) is running... /etc/init.d/nginx status nginx (pid 22534) is running... Some advices? By the way I have no experience at all, so anything could be missing..
You may want to check if the default firewall is running: iptables -nL Sounds simple but I've seen many people run in circles before remembering to check this. Run a netstat so you can be sure the service is actually bound to the port. Note that you cannot bind both nginx and apache to the same port.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 1, "tags": "apache 2.2, nginx, redhat" }
Is an NSUInteger equivalent to a plain old int? I'm just learning. In this tutorial, they've declared a block that takes `NSUInteger` arguments, and then they simply pass in `6` and `4` . . . I was under the impression all these `NS` things are object wrappers, different from the built-in c-types. Now that I'm writing this, I remember them saying earlier that we didn't need the `*` in `NSUInteger` declarations because it _wasn't_ like the other `NS` objects. But...an `NSUInteger` is obviously not a c-type. So...what's going on here?
Short Answer: Sometimes, NSUInteger is "unsigned int". But sometimes it is not. It depends the platform you compile your code. Long Answer: NSUInteger or NSInteger is defined in the NSObjCRuntime.h, you can Command+click on an NSUInteger and see the define below: #if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 typedef long NSInteger; typedef unsigned long NSUInteger; #else typedef int NSInteger; typedef unsigned int NSUInteger; #endif So, generally speaking, it means in a 64-bit environment, NSUInteger is an alias of unsigned long, while in a 32 bit environment, it is an int. Because the new iPhone 5s is running on a 64-bit CPU, so it is recommended to use NSUInteger or NSInteger instead the plain unsign int or int. And at last, NSUInteger is a real c-type indeed, in another name so the complier can do some work for you to handle it better.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "objective c" }
universal properties of dependent types What is the universal property of dependent product / dependent sum? (I want to see a diagrams) They are must be different from usual ones, aren't they? (i'm trying to understand category theory after I learned homotopy type theory. Is there a possibility to learn a category theory without learning some mathematical foundations like ZFC or HoTT?)
Short answer: dependent sum, dependent product. It's certainly not necessary to learn a foundation in order to learn category theory; there are now several good books on category theory out there, like Awodey's and Leinster's.
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "category theory, universal property, homotopy type theory" }
Is this a square wave signal? i have a decomposition of a square wave signal: $$ y = \frac{4h}{\pi}(\sin(x) + \frac{1}{3}\sin(3x) + \frac{1}{5}\sin(5x) + ...) $$ I computed the fundamental wave and 2 harmonic waves: $$ U_{r0} = 27.5e^{j90.8} $$ $$ U_{r1} = 35e^{j63} $$ $$ U_{r2} = 38 $$ Till here, it is correct. Now i have to show the time function of this square wave and my solution is this one: $$U_r(t) = 27\sin(628t+86.497) + 35\sin(628\cdot 3t+56) + 38.2\sin(628\cdot 5t)$$ But when i plot with Wolfram Alpha it does not look like a square wave. Just too less harmonics or did i do something wrong? !enter image description here
If I plot $\sin(x)+\sin(3x)/3+\sin(5x)/5$ I get a pretty nice square wave. In your case the +86.497 and +56 introduce phase shifts, which will ruin the wave. Your leading coefficients are also not in the ratio $1:\frac{1}{3}:\frac{1}{5}$ that they should be. Presumably this came out of your calculation of $U_r0, U_r1, U_r2$, which you don't describe. Note that $e^{90.8}$ is a _very_ large number. Where did that come from? Added: from your circuit, it appears the output voltage is taken from a divider. So $U_o=\frac{R}{R+j\omega L+\frac{1}{j \omega C}}U_i=\frac{j \omega CR}{j \omega CR-\omega^2 CL+1}U_i$ The fact that the filter ratio depends upon the frequency means that a square wave in will not come out a square wave.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "signal processing, harmonic analysis" }
what does the assignment mean interface Squel<S extends Select = Select> interface Squel<S extends Select = Select, U extends Update = Update, D extends Delete = Delete, I extends Insert = Insert, C extends Case = Case> { I cannot understand the assignment after extends. Could someone explain it? I do not find in Typescript official document.
These are _generic parameter defaults_. They work similarly to default values for regular function parameters. They allow you to not provide _type arguments_ for _type parameters_. let squel: Squel/*< no need to pass type arguments, yay! >*/ And if your type was like this: interface Squel<S extends Select, U extends Update, D extends Delete, I extends Insert, C extends Case> Then you would have to always pass type arguments: let squel: Squel<Select, Update, Delete, Insert, Case> ^^^ this part is mandatory now ^^^ P.S. The typescript handbook seems to not have information about this feature, but 2.3 release does have it (scroll to **Generic parameter defaults** )
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "typescript typings" }
Deploying Cloud Servers on the Fly I'm wondering if it's possible to deploy a clone of a server on a per user basis on something like AWS? I want to simulate interaction for training purposes with a small network (pings, TCP scans etc) through a Web application. My initial thoughts are to just fake the responses one would expect to see with another part of the Web app. However I'm wondering if this could be done by actually setting up a network on AWS once the user loads my application. Ideally it would be great if the instance could be torn down again once the user has finished for security reasons. Is this sort of thing possible yet or am I living in a dream world? I don't need any specifics as of yet, just a pointer in the right direction.
Yes this is definitely possible. You can use the AWS APIs in whichever your chosen language is (< to communicate with AWS and set up EC2s (machine instances). If you manually set them up in the console first, remote onto them, and then setup all the software etc you require. Them if you save these as AMI (amazon machine images) you can programmatically relaunch as many of these whenever required based on this AMI. Make sure you are using --instance-initiated-shutdown-behavior terminate to ensure when you shut down these ec2 instances they terminate and stop charging you money. I would have a go with the AWS Console first, see if you can set up what you want, then look at saving these as AMI's and programmatically launching them
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "networking, amazon web services, cloud, vps" }
How to get previous date in java I have a String Object in format **yyyyMMdd**.Is there a simple way to get a String with previous date in the same format? Thanks
I would rewrite these answers a bit. You can use DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); // Get a Date object from the date string Date myDate = dateFormat.parse(dateString); // this calculation may skip a day (Standard-to-Daylight switch)... //oneDayBefore = new Date(myDate.getTime() - (24 * 3600000)); // if the Date->time xform always places the time as YYYYMMDD 00:00:00 // this will be safer. oneDayBefore = new Date(myDate.getTime() - 2); String result = dateFormat.format(oneDayBefore); To get the same results as those that are being computed by using Calendar.
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 16, "tags": "java, date" }
Handling csv files on Python I have to compare data from different csv files on Python that consist of 84 columns and about 40.000 ~ 50.000 rows. This is a process that I need to do several times for several files. Which library should I use to have good performance? Should I use the regular csv library from python or would it be better to use something like Pandas?
Working with csvs usually will import the data in table formats. Typically R is a great language to manipulate columns and data in table (data frames) format, but when doing this in python, pandas is the go to library.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python 3.x, csv" }
How to detect errors in particular records when using the MERGE clause in T-SQL I have a stored procedure in T-SQL where I receive a table type as input parameter and then I use this table parameter in a MERGE clause. Thanks to the MERGE clause I'm able to insert or update records in a table in my database. Sometimes there are issues for several records (because of data quality). When this occurred, is it possible to commit all records that were inserted/updated and in the OUTPUT of the MERGE clause to have the list of records that were in error? Or is it in a single transaction and then if one error occurred I will have the whole transaction rollbacked?
Single transaction, it will rollback everything on error.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql server, tsql" }
Blender 2.8 Moving Vertices With G + X, Y, or Z Generates Odd Angles ![enter image description here]( I started working on a low poly model today and have run into trouble with the move tool. Normally, I press g + x, y, or z, and then the vertices snap to the axis I chose. However, for some reason now whenever I press g and one of the three axes, it no longer snaps to the axis I chose but rather some odd diagonal. I'm extremely new to blender so any help is much appreciated. ![enter image description here](
it is because you've set your transform orientations to Normals. Try settings it back to global. That should fix it ![transform orientation normal to global](
stackexchange-blender
{ "answer_score": 1, "question_score": 1, "tags": "modeling" }
How to secure JSON files against another websites I have JSON file on my server(on my website).My Iphone and Android app use this JSON. I would like to hide or secure json files from another websites or app. Is it possible ?
The most common way to do this it´s by using a Token that signs every WS call. You can generate this Token in many ways, the most extended it´s by password username encryption. Users in App sends USER/PASSWORD by SSL secured connection to the server. Server validates USER/PASSWORD and sends back a token that will be used to sign every call made now on, so the user doesn't have to be sending every time the USER/PASSWORD info. You can also check how to secure your web service following this SO link. > Best Practices for securing a REST API / web service Hope it helps. :)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -2, "tags": "php, android, iphone, json, security" }
Add Comment To JPEG in C# Sorry for my English. How I can add comment to Jpeg file to COM-marker section (0xFFFE)? Not a Exif comment. I try `Image.SetPropertyItem()` but it's save only first char of string.
You will probably have to use some metadata, for example, check out these two sites, MSDN, dreamincode.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, header, comments, jpeg, exif" }
FLEX for generating AWK scanner - Identify Variables I am trying to build a scanner for AWK source code using (F)Lex analysis. I have been able to identify AWK keyworkds, comments, string literals, and digits however I am stuck on how to generate regular expressions for matching variable instance names since these are quite dynamic. Could someone please help me develop a regular expression for matching AWK variables. < provides definition for the AWK language. Variables must start with a letter but can be alphanumerical without regard to case. The only special character that can be used is an underscore ("_"). I apologize I am not very experienced with REGEX let alone regular expressions for FLEX. Thank you for your help.
[a-zA-Z_][a-zA-Z_0-9]* Alphabetic or underscore to start, followed by zero or more alphanumerics or underscore. Special cases will be fields, which are prefixed by `$`: $0 $1 and also $NF $i You'll have to decide how you're going to deal with those.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c, regex, awk, flex lexer" }
getting a list of files from secure server i am trying to get a list of files from secure server to compare them (using diff) to the ones i modified on local version (unfortunately the company i work in is not using subversion nor git yet) i get list of files easily with: find . -mtime -20 | grep "\.php\|\.js\|\.css" > changedfiles.log what i need is a script which would loop over this list and secure copy each of them (scp or rsync) to a local directory, preserving relative path name. i tried: for line in `cat changedfiles.log` do DIRPATH=`dirname "$line"` `mkdir -p myfiles/$DIRPATH` scp user@host:/remotepath/$line myfiles/$line done but scp keeps asking me for the password (i dont want to setup key-based authentication to scp without password) i am not allowed to ssh on remote server so i cannot just zip the list and download them in one command is it possible to do something to input password only once?
Rather than set up a passphraseless key, create a passphrase-protected key and use ssh-agent to ensure you only need to enter it once per job. After generating your keys, prefix your script with something like this: # Start a new agent eval `ssh-agent -s` # add keys with a two-hour time limit ssh-add -t 7200 ~/.ssh/id_rsa At this point, you'll be prompted for your passphrase. After your script is finished, you can have ssh-agent be killed automatically if you do not wish to let it continue to run: # kill the agent ssh-agent -k
stackexchange-serverfault
{ "answer_score": 3, "question_score": 2, "tags": "rsync, files, synchronization, scp" }
targeting frame one frame from another i have main html page which have two frames frame1 and frame2. frame1 is showing tree.php page and i want that when i click on node of tree displayed in tree.php some html or php page should be displayed in frame2. how i can achieve this???
Give frame2 a name <frameset cols="35%,65%"> <frame src="page1.php"> <frame src="page2.php" name="MainWindow"> </frameset> And set the target of the linking node to that name <a href="page3.php" target="MainWindow">
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "html" }
Prolog - parsing functions with DCG I need to parse a string representing function like this: <fsignature>"(" <term1>, <term2> ... <termn>")" The function' signature and terms also have to be controlled further for the function to be accepted. I've written this DCG in Prolog: fsign --> {is_leg(A)}, [A]. terms --> (funct, funct; terms). terms --> (terms, terms; term). term --> {is_term(T)}, [T]. But it doesn't seem to work, when I try to use phrase(funct, [foo, "(", a, a, ")"]). it goes into overflow. is_leg just checks if the string is legal (a string starting with a character), while is_term should check if the term is a literal (either a constant, a variable or a function). What is that it's not working? I figure, probably the variables - should I put them as arguments of the nonterminals? Thanks for any help.
If your expressions all look like this: <fsignature> "(" <term1> <term2> ... <termn> ")" Then writing this out in terms of DCG, it should look something like this (minus any string validation predicates you're suggesting): expression --> fsignature, ['('], terms, [')']. fsignature --> ... % whatever fsignature looks like terms --> term. % "terms" is a single term, or... terms --> terms, term. % ... more terms followed by a single term. term --> ... % whatever a term looks like You can also write the definition of `terms` as: terms --> term | terms, term. Note that the non-recursive definition of `terms` occurs before the recursive one. Also, the definition for `terms` above assumes that you must have at least one term (this requirement wasn't stated in your question).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "parsing, prolog, dcg" }
sequence of sets with $\limsup A_n = \mathbb N$ Find a sequence of one-point-sets $A_n = \\{\ell_n\\}$ with $\ell_n\in\mathbb N$ for all $n\in\mathbb N$, such that $$\limsup_{n\to\infty} A_n=\mathbb N$$ I know the definition of the $\limsup$ of a sequence of sets, $$\limsup_{n\to\infty} A_n = \bigcap_{n=1}^\infty \bigcup_{k=n}^\infty A_k$$ I know the sequence has to contain each number of $\mathbb N$ infinitely often, but I'm not able to find a suiting sequence.
$1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,\ldots$
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "limsup and liminf, natural numbers" }
Is there a 3rd-party app that uses iPhone 6's barometer? I have an iPhone 6 and was wondering if there is any app that will simply display the current pressure using the barometer built into the phone? Or an app, other then the built in HealthKit which tracks stairs climbed, that uses that barometric pressure for something?
Barometer++ (full disclosure: I worked on the app at Friends of The Web) shows the raw pressure values from the iPhone 6 or 6 Plus's barometer sensor. It also shows sea-level adjusted pressure to compare to weather stations around the world (using your GPS altitude), and shows elevation changes based on the barometer.
stackexchange-apple
{ "answer_score": 1, "question_score": 5, "tags": "applications, iphone, temperature, apple watch" }
creating html in php while loop I am looping through a recordset in php and building up the html and then returning it to the calling webpage. However the HTML I create isn't returning and the numbers are adding together. What silly mistake am I making. I know the HTML basic structure is ok as hardcoded all my results in the loop. When the recordset onlt contained a single row and this worked fine. $myres =""; while (odbc_fetch_row($result)){ $myres = $myres + '<option value=' + odbc_result($result,"load_no") + '>' + odbc_result($result,"load_no") + '</option>'; } echo $myres;
please try the following: $myres =""; while (odbc_fetch_row($result)) { $myres = $myres . '<option value=' . odbc_result($result,"load_no") . '>' . odbc_result($result,"load_no") . '</option>'; } echo $myres;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "php, html, loops" }
Looking for a movie from my childhood I once saw a movie(sci-fi/fantasy) that I can't remember, but I know I liked it. I was really small and can't get any of the plot back together, but it was fairly old-ish movie (my guess would be 70's ~ 90's). The only clues I remember are: 1. Hairy legged horses (like furry legs) 2. Star-like metal weapon that appeared multiple times 3. Group of people going from A to B, looking for something 4. One of the heros was a cyclops that died during the film by being squeezed between rocks 5. It wasn't animated. If it rings any bell to anybody it would mean the world to me. Thanks a lot! **EDIT:** Somebody marked my question as duplicate of this one. While it points towards the same answer, the question was different. I didn't remember any teleporting castle and therefore my question wasn't answerable simply by using search.
This could be the 1983 live-action movie Krull) \- which includes: * the Glaive, "an ancient, magical, five-pointed throwing weapon"; * a series of journeys, with the ultimate goal of reaching the Black Fortress; * a cyclops (called Rell), who "sacrifices himself to hold open the huge spaceship doors long enough to allow the others to enter".
stackexchange-scifi
{ "answer_score": 16, "question_score": 6, "tags": "story identification, movie" }
how to improve .collect() in pyspark? Is there any other way to tune pyspark so that .collect()'s performance can be improved? I'm using `map(lambda row: row.asDict(), x.collect())` which is taking more that 5seconds for 10K records.
I haven't tried it, but maybe the Apache Arrow project could help you
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "pyspark, apache spark sql" }
Windows Phone 8 Multiple Build From Same Solution I have created a windows phone 8 application in VS2012. Now I have to take 2 two builds of same application (ex: "App1" and "App2") with some customization in the GUI. I have created two copies and renamed "Display Name", and "Assembly Name" and "Xap File Name" in project properties. But while deploying application (ex: "App1") to the phone the other (ex: "App2") is getting replaced. **Please let me know how to create two customized applications from same code?** Regards
To be able to deploy two applications side by side, they need to have a different product ID declared in the manifest (WPAppManifest.xml).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "windows phone 7, windows phone 8" }
Check status of Mysql replication I am using Centos 6.7. I have mysql database on my two servers and i have created the replication (Master - Master) on both. Now i want to check the status of replication that is it working fine or not. I have searched and found that **repadmin /showrepl** will give the status of all replication. But this command is not available in my centos. I am interested to make this alert using PHP. Any response will be highly appreciated.
I found my answer. < It have given exactly what i need for my requirement. Edit: Command on link above is: `SHOW SLAVE STATUS` . For someone only need run command to check. Thanks @PaPu for suggestion
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, mysql, database replication" }
Python Mock not asserting calls I'm using the mock library to patch a class in a program that connects to a external resource and sends a dictioanry. The structure goes a litle like this... code.py def make_connection(): connection = OriginalClass(host, port) connection.connect() connection.send(param) connection.close() test.py @mock.path('code.OriginalClass') def test_connection(self, mocked_conn): code.make_connection() mocked_conn.assert_called_with(host, port) mocked_conn.connect.assert_called_once() mocked_conn.send.assert_called_with(param) The first assert_called_with works perfectly, but the calls to method of the mocked class don't pass. I have tried using patch.object as a decorator also with no luck.
The `connect()` and `send()` methods are called on the _return value_ of the first call; adjust your test accordingly: mocked_conn.return_value.connect.assert_called_once() mocked_conn.return_value.send.assert_called_with(param) I usually store a reference to the 'instance' first: @mock.path('code.OriginalClass') def test_connection(self, mocked_conn): code.make_connection() mocked_conn.assert_called_with(host, port) mocked_instance = mocked_conn.return_value mocked_instance.connect.assert_called_once() mocked_instance.send.assert_called_with(param)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, unit testing, mocking, python mock" }
The difference in these 2 snippets of code Here are 2 snippets of code, one is a macro and one is a function. They seem to do the same thing but after running them it seems that they exhibit different behavior and I don't know why. Could anyone help me please? Thanks! #define ROL(a, offset) ((((Lane)a) << ((offset) % LANE_BIT_SIZE)) ^ (((Lane)a) >> (LANE_BIT_SIZE-((offset) % LANE_BIT_SIZE)))) Lane rotateLeft(Lane lane, int rotateCount) { return ((Lane)lane << (rotateCount % LANE_BIT_SIZE)) ^ ((Lane)lane >> (LANE_BIT_SIZE - (rotateCount % LANE_BIT_SIZE))) ; } Note: the Lane type is just an unsigned int and LANE_BIT_SIZE is a number representing the size of Lane in terms of No. of bits.
Think of using a macro as substituting the body of the macro into the place you're using it. As an example, suppose you were to define a macro: `#define quadruple(a) ((a) * (a) * (a) * (a))` ... then you were to use that macro like so: int main(void) { int x = 1; printf("%d\n", quadruple(x++)); } What would you expect to happen here? Substituting the macro into the code results in: int main(void) { int x = 1; printf("%d\n", ((x++) * (x++) * (x++) * (x++))); } As it turns out, this code uses undefined behaviour because it modifies x multiple times in the same expression. That's no good! Do you suppose this could account for your difference in behaviour?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c" }
UITabeView перенос текста Уважаймые iПрограмисты есть проблема с переносом текста в таблице. Написал код, он должен переносить слова которые не влезают в таблицу в низ. Но он не работает поеу-то и я не могу в понять почему. Помогите !!! - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath { SMXMLElement *elem=[citation objectAtIndex:indexPath.row]; NSString *str = [elem attributeNamed:@"text"]; UILabel *longi = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 0, 0)]; longi.numberOfLines = 0; longi.text = str; [longi sizeToFit]; float i = longi.frame.size.height+10; return i; }
Не уверен, но вроде sizeToFit фиксирует для UILabel ширину и наращивает высоту, а т.к. у вас ширина задана в 0, то ему не удается посчитать необходимую высоту. Если же брать весь код в целом - не надо создавать отдельную UILAbel, у NSString есть несколько методов которые умеют считать размер куда строка поместится - см. NSString UIKit Additions
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ipad, xcode, ios, objective c, iphone" }
Using Application.WorksheetFunction.Trim to trim a range of cells I'm trying to Trim a range of cells using the `Application.WorksheetFunction.Trim`. I'm trying to define my range, but I get a type mismatch error I created Dim and set my range and created a variable for the function. Dim rng As Range Dim myanswer Set rng = ActiveSheet.Range("T2:T10") myanswer = Application.WorksheetFunction.Trim(rng) Here's another one of my codes Dim rng As Range Dim LastRow As Long LastRow = Cells(Rows.Count, "T").End(xlUp).Row Set rng = Range("T2:T" & LastRow) Application.WorksheetFunction.Trim (rng) I want it to trim each of cells to get rid extra spaces. Also tried using this but get out of memory. rng = Application.WorksheetFunction.Trim(Cells.Value)
`Trim()` expects string argument. The argument in `Application.WorksheetFunction.Trim (rng)` is a Range, which can be parsed to a string, only if the range consists of a single cell. To `Trim()` all cells in a given range, they should be looped: Public Sub TestMe() Dim myCell As Range For Each myCell In Worksheets(1).Range("A1:A5") myCell = WorksheetFunction.Trim(myCell) Next myCell End Sub
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "excel, vba" }
Pythonic way of handling string formatted loop I have the following code, and the idea is to be able to iterate over `root` for each string in `some_list[j]`. The goal is to stay away from nested for loops and learn a more pythonic way of doing this. I would like to return each `value` for the first item in `some_list` then repeat for the next item in `some_list`. for i, value in enumerate(root.iter('{0}'.format(some_list[j]))) return value Any ideas? EDIT: root is tree = ElementTree.parse(self._file) root = tree.getroot()
I _think_ what you're trying to do is this: values = ('{0}'.format(root.iter(item)) for item in some_list) for i, value in enumerate(values): # ... But really, `'{0}'.format(foo)` is silly; it's just going to do the same thing as `str(foo)` but more slowly and harder to understand. Most likely you already have strings, so all you really need is: values = (root.iter(item) for item in some_list) for i, value in enumerate(values): # ... You could merge those into a single line, or replace the genexpr with `map(root.iter, some_list)`, etc., but that's the basic idea. * * * At any rate, there are no nested loops here. There are two loops, but they're just interleaving—you're still only running the inner code once for each item in `some_list`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.3" }
Jquery scrollto with offset I have this code: < However, at the moment when it does the `scrollto` using the text links in the black menu it scrolls so that the black bar is inside the section. I want to have it so the black bar is on top of the section. just enough to trigger that section as active. Can anyone show me how to do that. I think it would be something like this (but this is more like sudo code): scrollTop: $('#'+sectionId).offset().top-nav.height
You could just add a pixel to have the section active: scrollTop: ($('#'+sectionId).offset().top - $('nav').height()) + 1
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery" }
不知說謂, 不三不四 - Meaning In Context? I have heard pronounced (m sarm m sei) in Cantonese. I wonder if Mandarin speakers use this term and in what context? When I asked, someone they supposed that Mandarin speakers might prefer to use something like > Which is correct and could anyone supply sample context? Is there a deeper meaning other than the literal sense? Some one said the phrase is a bit degrading.
is a perfectly acceptable term in Mandarin **Oxford** > IDIOM > > 1 shady > > > > make friends with dubious characters > > 2 neither one thing nor the other > > > > make frivolous remarks I think you might be mistaking for which defines as: > , is definitely better though!
stackexchange-chinese
{ "answer_score": 2, "question_score": 2, "tags": "mandarin, meaning in context" }
Keep Task iteration synchronsied with User Story iteration When I move a user story from one iteration to another in TFS 2010, I then have to update the iteration in each child task manually. Otherwise it retains the previous iteration value and the various reports and filters don't produce the intended result. Can anyone recommend a method, or extension, that will either keep the task iterations synchronised to their user story iterations automatically, or failing that, do it for all user stories/tasks in a product on demand?
Try **TFS Aggregator** ## Example Uses * Update the state of a Bug, PBI (or any parent) to "In Progress" when a child gets moved to "In Progress" * Update the state of a Bug, PBI (or any parent) to "Done" when all children get moved to "Done" or "Removed" * Update the "Work Remaining" on a Bug, PBI, etc with the sum of all the Task's "Work Remaining". * Update the "Work Remaining" on a Sprint with the sum of all the "Work Remaining" of its grandchildren (i.e. tasks of the PBIs and Bugs in the Sprint). * Sum up totals on a single work item (ie Dev Estimate + Test Estimate = Total Estimate)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 6, "tags": "tfs, tfs workitem" }
how to narrow down search results with mysql I'm running big search querys such as: WHERE 'gender' LIKE '%a%' OR fname LIKE '%a%' OR mname LIKE '%a%' OR lname LIKE '%a%' OR address LIKE '%a%' OR card LIKE '%a%' OR email LIKE '%a%' OR fname LIKE '%ryan%' OR mname LIKE '%ryan%' OR lname LIKE '%ryan%' OR address LIKE '%ryan%' OR card LIKE '%ryan%' OR email LIKE '%ryan%'` It searchs though all this based on what you place in the search box. mysql would give me the following rows: < Ryan Anthony Okeefe John Albert Doe Beau Jacob Diddly Anthony Quinn Jims Brooke Wame Gagne Heres my problem. I want to get only the most accurate result for this because this. in this case it would be the first result, for the first name is Ryan and it contains the letter a in the first and middle name. Can anybody help me with this?
It won't be too efficient, but you could try with: ORDER BY (gender LIKE '%a%') + (fname LIKE '%a%') + (mname LIKE '%a%') + (lname LIKE '%a%') + (address LIKE '%a%') + (card LIKE '%a%') + (email LIKE '%a%') + (fname LIKE '%ryan%') + (mname LIKE '%ryan%') + (lname LIKE '%ryan%') + (address LIKE '%ryan%') + (card LIKE '%ryan%') + (email LIKE '%ryan%'`) DESC LIMIT 1 however, I would investigate on Full Text Search Functions.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql" }
How to change layout in magento 2.2.0 I am using Magento blank theme, I want to change the layout on Product detail page, on product details page the default layout is 1column layout. How to change from 1column layout to 2columns-left layout. Please help me. Thanks in Advance.
You can try following : In your Layout file inside the theme : app\design\frontend\Vendor\ThemeName\Magento_Catalog\layout\catalog_product_view.xml <?xml version="1.0"?> <page layout="2columns-left" xmlns:xsi=" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> ............. ............. Another option in your Layout file inside the custom module: app\code\Vendor\ModuleName\view\frontend\layout\catalog_product_view.xml <?xml version="1.0"?> <page layout="2columns-left" xmlns:xsi=" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> ............. .............
stackexchange-magento
{ "answer_score": 2, "question_score": 0, "tags": "layout, magento2.2.0" }
Why do low energy particles ionise more than high energy particles when traveling through matter? Regarding the Bethe Bloch formula, low energy particles ionise more than high energy particles as you can see in the plot. ![Plot of Bethe Bloch formula]( I would be interested in a physical explanation of that since it seems intuitive to assume that high energy particles ionise more.
The graph shows $\frac{dE}{dx}$ of an ionizing particle, i.e. its energy loss _per length_. When a fast particle flies through matter, it stays only a short time in the vicinity of any atom, and therefore has little chance to transfer part of its energy to the atom and kicking out an electron. A slower particle on the other hand, stays a longer time near any atom and therefore feels the electric field of its constituents (electrons and nucleus) for longer time, thus transfering more energy to it. You find this reasoning in a more quantitative way in every derivation of the Bethe-Bloch formula, and also in the derivation of its non-relativistic counterpart (the classical Bohr formula). See for example DKFZ - Physics of Charged Particle Therapy (especially page 15): ![enter image description here](
stackexchange-physics
{ "answer_score": 1, "question_score": 2, "tags": "particle physics, ionization energy" }
Display Images from Umbraco Media in Document i create a Document(PDF) and get the Content from the Umbraco nodes. But there's a problem by displaying the images. How can i display or get the images from the Media libary of Umbraco? Is there a way, offered from Umbraco to get the Image(s)? Thanks a lot.
If I understand your query correctly, you a pretty much there. You should simply be able to get the umbracoFile path (just like you are for the PDF file) and simply declare it as the img src! With Razor... <umbraco:Macro runat="server" language="cshtml"> <img src='@Model.MediaById(@Model.imgProperty).umbracoFile' alt="" /> </umbraco:Macro>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "image, umbraco, richedit" }
Which Jean Giraud book is containing those organic wall Moebius textures? Which Jean Giraud book is containing those organic wall Moebius textures? ![enter image description here]( ![enter image description here](
These two paintings appear to be from his art book _Quatre-vingt huit_ (1990), if that's what you're asking. I'm not sure this is on-topic, though, it doesn't seem to have any obvious SF content.
stackexchange-scifi
{ "answer_score": 6, "question_score": 5, "tags": "comics, illustrated story" }
What's the difference between a closed set and a bounded set? (basic real analysis) This is perhaps a stupid question. I see that you can have a bounded set that's not closed, for instance (0,2) in which the sequence $\\{a_n\\}$ with elements $a_n = \frac{1}{n}$ never reaches 0 for $n\in\mathbb{N}$. But how can you have a closed set that's not bounded?
The set $\mathbb{R}$ is for example closed, since its complement is the emptyset $\varnothing$ but clearly $\mathbb{R}$ is not bounded.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "real analysis" }
Сделать точку доступа wi-fi из Win 10 Здравствуйте! Подскажите как стандартными средствами Win10 расшарить VPN соединение для wifi? Поясняю: Есть Машина с win10 и двумя сетевыми картами. Одна (LAN ethernet) смотрит в сеть провайдера, получает серый dhcp (без доступа в инет) и далее через эту же сеть поднимается VPN который имеет доступ в интернет. Вторая сетевая карта (WLAN) с помощью стандартной утилиты "Мобильный хот-спот" настроена в режим AP и раздаёт лок. сеть 192.168.x.x к которой я успешно коннекчусь по wi-fi с гаджета. Так вот как мне попасть теперь в интернет через VPN поднятый на машине (НЕ на гаджете)? Схему прилагаю: < P.S. [1] Расшарить общий доступ к VPN через свойства - не вкатывает. Он расшаривается, но инет всё так же недоступен. Если есть соображения как это дебажить без банального traceroute на гаджете - готов выслушать. P.S. [2] Если есть бесплатные opensource утилиты вроде dragonfly под win10 облегчающие этот процесс - велкам.
Привет! Тут такое дело что твой телефон получает ip адрес вида 192.168.x.x от утилиты "Мобильный хот-спот", а так как в Windows 10 по умолчанию включен брандмауэр и выключена маршрутизация понять в чем причина того что он не шарит VPN сложно. Как вариант подключится к wifi с ноута и посмотреть таблицу маршрутизации, а там уже tracert'ом разбиратся куда уходят пакеты. P.S. Есть утилита MyPublicWiFi вроде она может то, что нужно (не знаю платная она или нет)
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "windows, сеть, администрирование, vpn" }
Recommend a slideshow module that can create a display from a view? We have a design comp that looks like this: !enter image description here We have a content type called `speaker`, which contains a file field that the headshot image is uploaded to. There are also several other fields, including an entity reference to another content type. What we'd like to do is be able to create a view that contains all the info we need and then have it formatted as a slideshow (where mousing over a single image brings up a div or something containing speaker name, company, etc.) I've found several slideshow modules that are integrated with Views, but none of them seems to do quite what we need. Any suggestions?
Looks like the jCarousel module has Views support and produces a similar looking display: < !jcarousel example It is also maintained by one the top Drupal contributors.
stackexchange-drupal
{ "answer_score": 2, "question_score": 0, "tags": "7, views, javascript" }
Backbone collection different result strategy Lets say I have method that returns from server 2 data sets: On success: {"status":true,"data":[{"id":1, "name": "yolo"}, {"id":2, "name": "yolo2"}]} On fail: {"status":false,"data":["Some error"]} I use following collection: var Entities.Collection = Backbone.Collection.extend({ url: "/entity", model: Entities.Model, parse: function(json) { // return different data ? // trigger something ? return json.data; } }); The problem is when I have fail result after fetch it will set collection with error details. What is the best practice to handle such issue ?
I'd say populate the collection only if you have a success scenario, which would look something like this: var Entities.Collection = Backbone.Collection.extend({ url: "/entity", model: Entities.Model, parse: function(response) { if(response.status) return response.data; else {} // handle this if you want to do something like triggering an event or // setting a flag, else leave it } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "backbone.js, backbone.js collections" }