INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How can I access blocked sites while in China? I have some colleagues who need to go to China for work, however while they're there, they can't access a lot of sites. One of which is GMail (Google Apps), which they need for work. We have a UK based Ubuntu server, which I have root access for. What can I do for them? I thought about a Squid proxy, but it might rely on their hotel having port 8080 open, so, not ideal. Are there any workarounds or other solutions?
My favorite solution to this problem simply requires SSH. SSH is the poor man's vpn. If the ubuntu box isn't already running ssh: apt-get install openssh-server If your colleague is using OS X/Linux in China, they would simply type: ssh -D1080 your.ubuntu.server.tld You can also set this in putty or other windows SSH clients. Then your colleague would set their web browser to use a SOCKS proxy at localhost:1080. Done. Should be easier than configuring a VPN. Your colleague just has to remember to uncheck the proxy setting when they are done. For better server security require public key authentication instead of password authentication. But this is independent of tunneling traffic through China.
stackexchange-superuser
{ "answer_score": 10, "question_score": 6, "tags": "proxy, squid, pptp, tunnel" }
What is a quick way to farm demon skin on lvl 70? I found a set plan today, which requires Demon Skin as an ingredient. I was trying to look it up on Battle.Net, but there seems to be no page for that material and most stuff I found on the internet was outdated. So what is the best and quickest way to farm Demon Skins? Does it drop in a specific place or is it just random? I never seen that one at all. !Screenshot of ingredient
Legendary materials are usually found as drops off super-unique monsters (the ones with the purple names). Demon Skins can be found on the following monsters: * Axgore the Cleaver (Phase Beast): Act III, The Core of Arreat * Haxxor (Phase Beast): Act III, Tower of the Damned Level 1 * Khatun (Sky Terror): Act IV, Gardens of Hope Tier 1 * Razorclaw (Sky Terror): Act IV, Gardens of Hope Tier 2 (spawns during the quest, The Light of Hope). Because they drop off super-unique monsters, you won't be guaranteed a chance at the drop when you create a new game as the monster may not even spawn! Be sure to pay attention to bounties that target these monsters, as the bounty guarantees that the monster will spawn.
stackexchange-gaming
{ "answer_score": 11, "question_score": 8, "tags": "diablo 3" }
What does "bin" in "Ich bin vor 2 Jahren nach Berlin gezogen" mean? I translated "I moved to Berlin 2 years ago" to German, using Google translate, and it says "Ich bin vor 2 Jahren nach Berlin gezogen". I'm trying to figure out the logic behind the "bin". The first thing that came to my mind was that it would be the present perfect, translating literally to "I have, two years ago, to Berlin, moved". However, apparently, the present perfect in German would be "ich habe". What is the logic behind this "bin"?
German _Perfekt_ is built with the _haben_ auxiliary for **most** verbs. However, there is a significant minority of verbs which build their _Perfekt_ with the _sein_ auxiliary. Some other verbs build their _Zustandspassiv_ voice with the _sein_ auxiliary instead. _Ziehen_ is an extra special case, as it allows all three options. > Ich habe eine Niete gezogen. _(Perfekt, 1st meaning)_ _I drew a blank._ > Ich bin zu ihm gezogen. _(Perfekt, 2nd meaning)_ _I moved to him._ > Dieses Blech ist gezogen. _(Zustandspassiv **or** predicative expression, 1st meaning)_ _This metal sheet is drawn._
stackexchange-german
{ "answer_score": 2, "question_score": 0, "tags": "grammar identification" }
Check for missing (nonexistent / tampered) query string and redirect to a 400 BAD REQUEST page (WebMatrix / Razor syntax) I can test query strings parameters: Request.QueryString["value"].IsEmpty() Request.QueryString["value"].Isint() Etc. But how can I **avoid** that there is **no query string at all** ? In other words, I want to `prevent` users to access `the root` of each folder or subfolder. instead of: If I remove the query string (up to the page extension), I get a `cannot perform runtime binding on a null reference`error since the next part of the code is still executed. Instead, I would like the user be `redirect` to a `400 BAD REQUEST`: The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications
Users can't "access the root of the folder" by omitting a querystring value. All that will happen if they request ` instead of ` is that any code that relies on `Request["providerId"]` having a value will likely blow up. If you want to test if a query string value exists, you only need to use IsEmpty(): if(Request["providerId"].IsEmpty()){ //the value is missing. Redirect ot a safe page or provide a default value } else { //run your code }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "query string, webmatrix, bad request, tampering" }
HTML Fonts that will work regardless of OS? I've been making a website, but the only fonts I could get working were Monospace, Arial, and the default (Times New Roman?) I tried to find a font like this: ![enter image description here]( I tried: `<body style="font-family:tahoma;">`, `<body style="font-family:cabin;">`, and many others, but I couldn't find any fonts that would work. And the ones that did work all looked the same and were very ugly. Do you know of any fonts that would work regardless of operating system?
To get your font looks the same in all OS you'll better use a font from a font provider like Google Fonts for your case you can add this line in your header <link href=' rel='stylesheet' type='text/css'> and after that try <body style="font-family:Lato">
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css, fonts, operating system" }
How to unescape string in php? Given a string like this `$str = '\007\t\007\006\006\t\n\026\r\\\045';` format and output unescaped string so that `\t - tabulation` and so on. I could solve this by using replacements, but maybe there is a better solution?
The best I can think of is: eval('$str_unescaped = "' . str_replace('"', '\"', $str) . '";'); `str_replace` is needed in case the string contains any embedded double quotes. But it still gets an error if it contains an embedded `\"` sequence.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, string, escaping" }
How to type Ŭ (U with breve)? Esperanto uses the letter Ŭ. `Compose`, `Shift`+`9`, `a` = ă, but `Compose`, `Shift`+`9`, `u` = u. How do I type this with the compose key? If that is not possible, what is the next easiest way to type it?
Depends on the version of X11 ( ~~assuming you are not using~~ or wayland) and keyboard layout, but generally `Compose`, `b`, `u` or `Compose`, `u`, `u` should work (IIRC `Compose`, `(` was used for breve some (long) time ago). See also `/usr/share/X11/locale/*/Compose`.
stackexchange-askubuntu
{ "answer_score": 8, "question_score": 7, "tags": "compose key" }
Cross Compilation of OpenCV for ARM fails I am following this site to compile OpenCV for ARM. It could not find my compiler so i hardcoded it into cmake file > find_program(CMAKE_C_COMPILER NAMES arm-linux-gnueabi-gcc-4.7) find_program(CMAKE_CXX_COMPILER NAMES arm-linux-gnueabi-g++-4.7) set(ARM_LINUX_SYSROOT /usr/arm-linux-gnueabi CACHE PATH "ARM cross compilation system root") It compiles to aproximately 50% and then throws the following error: > Linking CXX shared library ../../lib/libopencv_viz.so /usr/lib/libvtkCharts.so.5.8.0: file not recognized: File format not recognized collect2: error: ld returned 1 exit status I am not every experienced in cross compilation (or straight compilation for the matter). How do i fix this?
Compiling OpenCV 2.4.10 worked for me. I did not have any preferred version. If you want to compile v3.0 see @Kornel's answer, that suggests to leave viz library out of compilation. Use this command to checkout v2.4.10 > git checkout 2.4.10
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 3, "tags": "linux, opencv, cmake, arm" }
EDB Replication Server, Sequences not updating I'm using EDB Replication server to have 3 **postgres 14** databases in sync (MMR Replication). I'm using Table Trigger as changeset logging It's working fine for the most part, but I have a problem with Sequences. Although the table rows change properly, the sequence is not updated on replicated tables. I can update the Sequences manually, I use this code: SELECT SETVAL( (SELECT PG_GET_SERIAL_SEQUENCE('"table"', 'id')), (SELECT (MAX("id") + 1) FROM "table"), FALSE); and it all works fine after that, but it's a real hassle to run that code every time there is an addition on the database. And for each table affected. Is there a way to update the Sequence during replication automatically? Machines are all using Windows 10
This is working as designed. In a multi-master replication setting sequences can be (and normally are) updated independently on each write node. To avoid conflicts consider using multimaster-ready sequences or other techniques described in the documentation.
stackexchange-dba
{ "answer_score": 0, "question_score": 0, "tags": "postgresql, replication, sequence" }
How do I give a UITextView focus programmatically? So I want to bring in a modal view controller that has a UITextView in it and I want the keyboard to automatically popup and the UITextView have focus. I found a way to accomplish this by doing the following: textView.editable = YES; textView.editable = NO; This just seems hacky to me, is there another way?
Since `UITextView` inherits from `UIResponder` (indirectly, it actually inherits from `UIScrollView`, which inherits from `UIView` which _then_ inherits from `UIResponder`) you can call the `-becomeFirstResponder` method on your text field, which will cause it to become the first responder and begin editing: [textView becomeFirstResponder];
stackexchange-stackoverflow
{ "answer_score": 168, "question_score": 68, "tags": "ios, objective c, cocoa touch, uikit" }
Importing LARGE quantity of data into a PostgreSQL database I am importing a large amount of data into a PostgreSQL server (across multiple databases on the server). When I last attempted to import the data, it effectively "crashed" my machine (Ubuntu 10.0.4), because /var/log/postgres contained over **360G** of files (and I was only about 1 half way through the import). I am not sure what the log files are for (I am guessing it must be for ACID compliancy etc). But I would like to know if there is a way to reduce the size of the log files generated during import of a large amount of data.
Log files in `/var/log/postgres` are only _for your information_ (in a standard installation) and do not serve the system itself, especially not "ACID compliancy". They need to be writable once configured, that's all the server needs. There are a number of settings in your `postgresql.conf` that govern what is logged. Most of them can also be set at the command line to overrule the setting in the config file. We are not talking about WAL files, which are not usually placed in `/var/log/postgres`. I would drastically reduce the verbosity in your case. Among others, I would set (and reload the server): `log_statement = none` Depending how you import the data, you probably need to do more than that. Look at: `log_min_messages` To skip writing log files altogether you can set: `log_destination = 'stderr'` ... More in the manual.
stackexchange-dba
{ "answer_score": 6, "question_score": 6, "tags": "postgresql, import" }
Pass over ExceptionInInitializerError I have a static initialization block and from it is thrown an `ExceptionInInitializerError` Exception. Is there any way to pass over this exception and to access the other fields and methods from this class? Thank you.
Put the call to initiate the class which contains the static block into try block and catch `ExceptionInInitializerError`. Like the following: try{ ClassWithStaticBlock cb = new ClassWithStaticBlock(); } catch(ExceptionInInitializerError ex){ }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java, exception, classloader" }
How to determine if a variable exists in another Python file I have two python files. From python file #1, I want to check to see if there is a certain global variable defined in python file #2. What is the best way to do this?
try: from file import varName except ImportError: print 'var not found' Alternatively you could do this (if you already imported the file): import file # ... try: v = file.varName except AttributeError: print 'var not found' This will work only if the var is global. If you are after scoped variables, you'll need to use introspection.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 7, "tags": "python, file" }
Double は with 言っていました? Is it suitable/permitted to use twice when relaying what someone else said? E.g: >
Yes it's perfectly suitable. The quote part (marked with ) is an independent sentence and can have another . Another situation where you have two 's is when you want to use as an explicit contrast marker (e.g., "He is (at least) tall").
stackexchange-japanese
{ "answer_score": 2, "question_score": 2, "tags": "particle は" }
Haskell: Library function to convert hexadecimal to binary notation Is there a library function to convert a hexadecimal digit (0-F) to its equivalent four-digit binary value? For example, 9 = 1001, C = 1100. I've looked at Data.Hex, Data.HexString, Numeric, and several other libraries that should be relevant, and I had assumed I would be able to find the function I am looking for. However, I'm quite new to Haskell and may be overlooking something simple. EDIT: Not a duplicate, IMO. My question is about conversion directly from hexadecimal to binary, which the linked question (and its answers) does not mention.
There isn't a single library function to convert a hex digit to a binary string. You can use `readHex` from module `Numeric` to convert a hex digit to an integer and `printf` from the `Text.Printf` module to generate a binary string, like so: import Numeric (readHex) import Text.Printf (printf) hexToBin :: Char -> Maybe String hexToBin c = case readHex [c] of (x,_):_ -> Just $ printf "%04b" (x::Int) _ -> Nothing giving: > map hexToBin (['0'..'9'] ++ ['A'..'G']) [Just "0000",Just "0001",Just "0010",Just "0011",Just "0100", Just "0101",Just "0110",Just "0111",Just "1000",Just "1001", Just "1010",Just "1011",Just "1100",Just "1101",Just "1110", Just "1111",Nothing]
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "haskell, hex, libraries" }
Boost regexp match I have such a regular expression boost::regex isAgent ("Mozilla/\d[.]\d \(Windows NT \d[.]\d; (Win64; x64;|WOW64;)?(.*?)\) Gecko/\d{8} Firefox/\d\d[.]\d", boost::regex::perl); if (boost::regex_search(auxAgent.c_str(), match, reg)){...}... i know that in `auxAgent` i have exacly `Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0` on this page < everything matches but not in boost, what am i doing wrong?
In C++, the character `\` needs to be escaped. So if you want to escape anything, you need to do `\\`. That should fix the problem. Whenever you use the backslash in a string, you need to escape it like that. If you ever need to find it in a string with the regex, you'll need to search for it with `\\\\`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, regex, boost" }
How is link-to used with a nested route when resetNamespace is specified? Using the example route defined below how can a link be defined to /post/123/comments? Router.map(function() { this.route('post', { path: '/post/:post_id' }, function() { this.route('edit'); this.route('comments', { resetNamespace: true }, function() { this.route('new'); }); }); }); Since `resetNamespace: true` is set on comments, the route post.comments does not exist. Otherwise the following would work. {{#link-to "post.comments" "123"}}Link{{/link-to}}
You have to link directly to `comments`: {{#link-to "comments" "123"}}Link{{/link-to}} It will transition to `/post/123/comments` after you click it. See working demo.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ember.js" }
Alternative to security questions for account recovery when email isn't an option I'm working on a project whereby a certain level of anonymity is required for users. One of stipulations is that no email is used at all, as it makes the barrier to entry too high for people who want anonymity in this service but don't have an anonymous email account to hand. One of the issues with this is that account recovery becomes painful if someone forgets their password. Security questions would end up being a massive security hole, as there isn't the burden upon the attacker to compromise the email account as well as guess the answers. A potential method I'm considering is to give the user a file full of random data upon account creation, and have them use that as a token for resetting their account. The only issue I can see with that, though, is that people would likely lose the file. What other options do I have?
> A potential method I'm considering is to give the user a file full of random data upon account creation, and have them use that as a token for resetting their account. The only issue I can see with that, though, is that people would likely lose the file. Let the user upload this verification file and verify the hash. So a potential attacker need to know the username and the file. EDIT: Hopefully they lose their own file less likely than a generated
stackexchange-security
{ "answer_score": 2, "question_score": 5, "tags": "authentication, password management, anonymity" }
What is the Excel IdMso of "Insert Copied Cells" I am looking to find the idmso of the "Insert Copied Cells" Excel ribbon button found under Home->Cells->Insert. The "Insert Copied Cells" ribbon button is only visible if you have something on your clipboard. The idmso of the "Insert" splitbutton is "InsertCellstMenu". However, of all the sites that list the Excel idmsos and even Microsoft official spreadsheet of idmsos, none of them seem to list the idmso for "Insert Copied Cells". <
I figured it out, the idMso is "CellsInsertDialog". The confusing part is that the text of the ribbon button changes depending on what you've done before you show it (like if you have done a cut or a copy). It could be "Insert Cells", "Insert Cells...", "Insert Copied Cells", "Insert Copied Cells...", "Insert Cut Cells", or "Insert Cut Cells..." depending on if you have anything in your clipboard and if your current selection is a range, a column, or a row.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "vba, excel, vsto" }
False proof of $\pi=0$ In an attempt to prove to myself that the equation $e^{i\pi} = -1$ is indeed true, I attempted to 'reverse engineer' it into a state that I already know to be true using Year 12 methods, (i.e. able to verify it in a basic calculator), but ended up with $\pi = 0$ and was wondering where I went wrong. I don't doubt it comes down to me knowing pretty much nothing about imaginary numbers other then '$i$' is defined as the square root of $-1$. Anyway here was my attempt: \begin{align} e^{i\pi} &= -1 \\\ \ln(-1) &= i\pi \\\ 2 \ln(-1) &= 2i \pi, \text{ multiplied all by $2$} \\\ \ln((-1)^2) &= 2 \sqrt{-1} \pi \\\ \ln(1) &= 2 \sqrt{-1} \pi, \text{ it was at this point I realised I'd messed up} \\\ 0 &= 4 \cdot -1 \cdot \pi^2, \text{ pointless squaring} \\\ 0 &= -4 \cdot \pi^2 \\\ 0 &= \pi \end{align}
Here's a quick way to summarize the essence of your paradox: $$ e^{2 \pi i} = e^0 \overset{?}\implies 2 \pi i = 0 $$ The first equation is true, the second is not. The problem is that the log is no longer uniquely defined. If it were defined in that sense, then taking the "log of both sides" would take us from the first equation to the second. With real numbers, we can only have $e^x = e^y$ when $x = y$. This is **not** true if $x$ and $y$ are complex. * * * Since you are learning about complex numbers for the first time, it is worth noting that for real numbers $x$, we have Eulers formula: $$ e^{xi} = \cos(x) + i \sin (x) $$ Notably, both cosine and sine are periodic, so this function will be periodic (over the real values of $x$) with period $2 \pi$. For more on all this, I recommend this video (mathologer) and this video (3blue1brown).
stackexchange-math
{ "answer_score": 10, "question_score": 3, "tags": "exponential function, pi" }
Why does geth say "Mining too far in the future"? I left my PC mining overnight (geth not running) and then cancelled the mining and started up geth. I get: Mining too far in the future wait=1h8m29s Presumably I have to wait for that long before geth will function again, but what does it actually mean? Should I be running geth at the same time as mining to prevent it?
One idea would be to check your machine's clock is correct. (Using something like < * * * You're hitting a check that's in place (I believe) to prevent miners from manipulating the timestamp in the blocks they've created and are are attempting to mine. For those interested, the code is in `worker.go`. We're effectively comparing the miner's current local time, `time.Now()`, against the timestamp in the last successfully mined block (here `parent`). tstart := time.Now() parent := self.chain.CurrentBlock() tstamp := tstart.Unix() if parent.Time().Cmp(new(big.Int).SetInt64(tstamp)) >= 0 { tstamp = parent.Time().Int64() + 1 } // this will ensure we're not going off too far in the future if now := time.Now().Unix(); tstamp > now+1 { wait := time.Duration(tstamp-now) * time.Second log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait)) time.Sleep(wait) }
stackexchange-ethereum
{ "answer_score": 1, "question_score": 1, "tags": "go ethereum" }
What is a good Javascript debugging tool? Haven't touch javascript for 3 years. Just got a javascript project and wanted to know any new ways or tools emerged these years to debug javascript? I used alert 3 years ago. I am using IE
Use the Firebug extension for Firefox, or the built-in Web Inspector in any WebKit browser (Chrome or Safari). In IE8, you can use the built-in Developer ToolS.
stackexchange-stackoverflow
{ "answer_score": 40, "question_score": 17, "tags": "javascript, debugging" }
web user controls have made my default page so heavy my web site structure is like this : 1- master page with stylesheet and scripts 2- aspx which render (number 3) 3- web user control and scripts inside them in the number 3 I have some javascript that are call some ajax method they are about 20 lines code and I can not move them to js file in order to using <%= myAspControl.ClientID %> for some purpose my default.aspx is so heavily now I checked it by google chrome developer tools it is equal to 2.7MB for document only document not images or style sheet. I have about ten controls but I think it is effect on viewstate and encoding them it creates all in default.aspx dynamicly and make it so heavy.
Have you read these SO-suggestions to minimize ViewState?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, ajax" }
Uninstalls from ChromeOS increased in my extension. Have ChromeOS any browser API difference from other OS? I have the extension New Tab Studio < Several days ago uninstalls from ChromeOS became so big (other OS - as usual). I wanna try to install ChromeOS on VirtualBox and test my extension, but it's not a very easy task, maybe it's easier to buy Chromebook. But first of all, **Can my extension has specific bug only for ChromeOS?** _Also, I have anonymous messages from google forms, that app crashes (on the background button click), but I cannot reproduce any bugs on Mac OS or Windows._
I reproduced it on Linux (i think that the cores of ChromeOS browser and Linux are the same) So, the case was that I had the image with path `/all.jpeg`, but was requesting `/All.jpeg`. MacOS and Windows was fine with this typo, they even show me the image. But Linux (and I guess ChromeOS) crashed the extension. And the crash was observed only in the extension installed from Chrome Web Store (my local production build just didn't show the image, but worked fine)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "google chrome, google chrome extension" }
List.Find<T>() returning null even though predicate matches I'll just attach a picture for reference on this one. I am stumped. In the debugger, the values definitely equal each other, but `Find<T>` is still returning null and `Exists<T>` is still returning false. For reference: `UserRepository` implements `IEnumerable<T>` where `T` is `DomainUser`. !Debug screencap
The problem is that the type of `CommandArgument` is `object`, so it's performing a reference identity check. (I'm surprised this isn't giving you a compile-time warning.) You could either cast `CommandArgument` to `string`, or use `Equals`: u => u.Username == (string) args.CommandArgument or u => Equals(u.Username, args.CommandArgument) (Using the static `Equals` method this way means it'll work even for users with a `null` username, unlike `u.Username.Equals(args.CommandArgument)`.) I wouldn't convert the sequence to a list though - I'd just use LINQ instead: DomainUser toRemove = repo.FirstOrDefault(u => u.Username == (string) args.CommandArgument);
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 6, "tags": "c#, .net" }
git local branch and origin/master still diverged after git reset --hard After doing git reset --hard I expected to see 'HEAD is now at hexNumber' and then 'on branch master....nothing to commit. Instead I see wb316-mac03:MoodTrack student$ git reset --hard HEAD is now at ec11193 preparation for merge wb316-mac03:MoodTrack student$ wb316-mac03:MoodTrack student$ git status # On branch master # Your branch and 'origin/master' have diverged, # and have 2 and 9 different commits each, respectively. # nothing to commit (working directory clean) I want to be completely overwritten by what's in the remote master (without recloning). Did I do something wrong?
You should add the commit that you want to reset to: $ git reset --hard origin/master `git reset --hard` will just reset to `HEAD` (which was probably `master` in your case).
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "git, version control" }
$f$ is a 4th degree polynomial and $f(-0.2)=2.226, f(-0.1)=2.460, f(1)=3.004, f(0.2)=3.320$. Find $f'(0)$ $f$ is a 4th degree polynomial and $f(-0.2)=2.226, f(-0.1)=2.460, f(1)=3.004, f(0.2)=3.320$. Find $f'(0)$ My attempt: Let $$f(x)=ax^4+bx^3+cx^2+dx+e$$ then \begin{align*} 2.226&=a(0.2)^4+b(-0.2)^3+c(0.2)^2+d(-0.2)+e\\\ 2.460&=a(-0.1)^4+b(-0.1)^3+c(-0.1)^2+d(-0.1)+e\\\ 3.004&=a+b+c+d+e\\\ 3.320&=a(0.2)^4+b(0.2)^3+c(0.2)^2+d(0.2)+e\\\ \end{align*} Is there any good ways to approach these equation?
Differentiating $f$ and substituting zero, you find that you only need to find the value of $d$ from your linear system.
stackexchange-math
{ "answer_score": 1, "question_score": -2, "tags": "calculus, derivatives, polynomials" }
pytz adding extra minutes What's the difference between US/Mountain and AZ timezone. Why is it adding an extra **28 min**? >>> strtime = datetime.datetime.strptime('10:00pm', '%I:%M%p') >>> tz = timezone('US/Mountain').localize(strtime) >>> print tz 1900-01-01 22:00:00-07:00 >>> tz = timezone(us.states.lookup('AZ').capital_tz).localize(strtime) >>> print tz 1900-01-01 22:00:00-07:28 <<-----
this is most likely due to the fact that your year is 1900 (see also this question); it works fine if you add a current year: import datetime from pytz import timezone import us strtime = datetime.datetime.strptime('2020 10:00pm', '%Y %I:%M%p') tz = timezone('US/Mountain').localize(strtime) print(tz) # 2020-01-01 22:00:00-07:00 tz = timezone(us.states.lookup('AZ').capital_tz).localize(strtime) print(tz) # 2020-01-01 22:00:00-07:00 (I'm using Python3 but that shouldn't make a difference, I get the same 28 min offset for year 1900)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "datetime, timezone, pytz" }
Unpack all files in subdirectories and rename them after their original directory I've ended up in an odd situation. I have 35 folders. The first is named 1, the second is named 2, and so on. In each of these folders, there are 4 files. '1.png', '2.png', '3.png', '4.png'. In each of these folders, I wish to run "convert *.png -append out.pdf", and rename each 'out.pdf' after its original directory (e.g. 'out1.pdf' from the first folder) and then unpack each pdf from its original folder. Is this possible? I've tried loops, but all that I've tried seem to disagree with the naming system.
Try something like this: #!/bin/sh for dir in $(seq 1 35) do ( cd $dir || exit 1 rm -f out$dir.pdf for n in 1 2 3 4 do convert $n.png -append out$dir.pdf || exit 2 done ) done This script is posix compliant and does not require `bash`, hence the `#!/bin/sh`. The code between parenthesis runs in a subshell, so the `cd` command only changes the directory until the closing parenthesis. The next iteration of the loop will begin in the original working directory. In your example, I think the syntax for `convert` is incorrect. Convert takes only one input file, and in your original question the `*.png` would pass four input files. Perhaps that's part of your problem.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "linux, bash" }
Does ScopeGuard use really lead to better code? I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code?
It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a `catch` block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ _is_ done by resource acquisition and garbage collection is done by implicit destructor calls. On the other hand, explicit `catch` blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly. RAII (including `ScopeGuard`s) isn't an obscure technique in C++ but firmly established best-practice.
stackexchange-stackoverflow
{ "answer_score": 62, "question_score": 33, "tags": "c++, raii, scopeguard" }
Using the EPiServer Communities API from a console app? I'd like to write a console or winforms application that will interact with the EPiServer database. Since I don't want to muck about in the deep inards of the database I'd like to use the EPiServer API. However, all the examples are using the "CommunitySystem.CurrentContext" which is null when running outside the website. Now, I'm going to transfer a large amount of data from a legacy system to EpiServer Community and I really don't want to do that from a web page but from an application I have a little more control of. Is there any way I can use the API from outside the web context?
My colleague Jarle figured out the last bits and blogged the whole process here So if you want to run the EPiServer API outside of IIS, that's the place to start. Works like a charm!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "episerver" }
Update process CUBE I am using the SSIS Analysis task to process CUBE using the update only process. The source records is a transactional TYPE 1, so when we get an update records to exisitng records in the source will delete and insert the new records, here Update process cube failing due to missing key at source(which is due to deleting the source records on updated source) source table records cube process records 1000 1000 deleted 5 and inserted 5 new 5 and key error while processing the cube. we could use FULL PROCESS to avoid this problem but having performance hit, How to do this process using the update process only. thanks prav
A quickfix could be done in analysis services deployment * Select Process>Change Settings…> Dimension key errors * Choose Use custom error configuration * In Stop on Error, ensure that On Error Action is set to "Stop Logging". * In Specific error conditions make sure that "Report and Continue" is selected. * Click OK and the cube will be reprocessed ignoring this error.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql server, sql server 2008, ssis, ssas" }
How does Git know which repository to push to? I'm a complete noob when it comes to version control, but I recently started using GitHub to host some of my projects. I blindly use the command `git push origin master` to push changes to either of the two repositories. I don't understand how Git knows which repository to push to. I use the same command to push to each. Does the directory I'm in have anything to do with it? Thanks for clearing this up for me.
Git repositories contain a `.git` directory that contains metadata about the repository. That's what Git uses to determine where to push your changes.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "linux, git, version control, push" }
How to create group header in jasper report table using iReport? Im trying to recreate a jrxml to be familiar in iReport. I already know how to create a simple table but this one's a bit complicated because of the grouping. ![enter image description here]( ![enter image description here]( Could you tell me how to create another band called group header like the one shown in the screenshot? By the way i'm using iReport 5.6
Add the group in your **tabelDataSet** <subDataset name="tableDataSet" uuid="c72d8dbd-d63e-411b-862d-a0d6e1e25d37"> .... <group name="group1"> <groupExpression><![CDATA[$F{YourField}]]></groupExpression> </group> </subDataset> and you will find it magically in your table structure. **EDIT: Added instructions for iReport:** In iReport right click the groups in your tableDataset and select "Add group" (the screen shot is in Italian but "Aggiungi Gruppo" = "Add Group" ![iReport](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jasper reports" }
Given gender distribution of two programmes, which one does class belong to? Classes at a high school are divided into two branches: * Mathematics (65% boys) * Languages (45% boys) Matthew observes that 55% of his class is made up of boys. Which branch does it most likely belong to: Mathematics or Languages? I believe the answer can be found by solving Bayes' theorem for each branch, but I'm not sure how to set it up. I'd appreciate any help given in standard P(A|BI) notation.
Let $M$ be the mathematics branch, $M'$ be the languages branch, and $B$ signify "boys." We are given $\mathbb{P}\left(B\mid M\right) = 0.65$ and $\mathbb{P}\left(B\mid M^{\prime}\right) = 0.65$. Furthermore, for this particular class, $\mathbb{P}\left(B\right) = 0.55$. By the Law of Total Probability, $$\mathbb{P}\left(B\right) = \mathbb{P}\left(B \cap M\right) + \mathbb{P}\left(B \cap M^{\prime}\right) = \mathbb{P}\left(B \mid M\right)\mathbb{P}\left(M\right) + \mathbb{P}\left(B \mid M^{\prime}\right)\mathbb{P}\left(M^{\prime}\right)\text{.}$$ Since $\mathbb{P}\left(M\right) = 1 - \mathbb{P}\left(M^{\prime}\right)$, you just need to put in the numbers now and see which one is higher: $\mathbb{P}\left(M\right)$ or $\mathbb{P}\left(M^{\prime}\right)$ .
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "statistics" }
When attempting to deploy a business network I get an error 'Failed parsing HTTP/2' in grpc The command that was issued was > composer network deploy -a my-network.bna -i admin -s adminpw The full error received was > Error: {"created":"@1495236947.733570390","description":"Failed parsing HTTP/2","file":"../src/core/ext/transport/chttp2/transport/chttp2_transport.c","file_line":2022,"grpc_status":14,"referenced_errors":[{"created":"@1495236947.733545222","description":"Expected SETTINGS frame as the first frame, got frame type 80","file":"../src/core/ext/transport/chttp2/transport/parsing.c","file_line":479}{"created":"@1495236947.733562422","description":"Trying to connect an http1.x server","file":"../src/core/ext/transport/chttp2/transport/chttp2_transport.c","file_line":1995,"http_status":400}]} Command failed
This error is the result of trying to deploy to a Hyperledger Fabric V1 runtime using a Hyperledger Fabric V0.6 profile. In the above example, no profile was specified which means it will use a default profile and that default profile is specific to Hyperledger Fabric V0.6 It is highly recommended that for all command line interaction that you explicitly specify the profile you want to use, so for example if you have a profile for connecting to your local Hyperledger Fabric V1 runtime called `hlfv1` then you should issue the command `composer network deploy -p hlfv1 -a my-network.bna -i admin -s adminpw` (note the -p option to specify the profile to use)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "hyperledger composer" }
Facebook key hash for Android According to this tutorial you need to run this command to generate key hash: keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 When I do that it asks for a password. What password it needs?
Presumably it's asking for the password to the debug.keystore specified in the keytool command. which should be defaulted to `android` If you've manually changed the password of the keystore, then you'll obviously need to enter the password that you changed it to.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, android, facebook" }
What's the difference between ( ' ' || false) and (false || ' ' ) in JavaScript? In developer.mozilla website there are some examples to show different usage of logical OR operator, but this two examples got my attention, here they are : o8 = '' || false // f || f returns false o9 = false || '' // f || f returns "" Why this two, return different results? I expected both of them return false.
See in the same page: < > `expr1 || expr2` > > If `expr1` can be converted to `true`, returns `expr1`; else, returns `expr2`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript, logical operators, logical or" }
add JList to JFrame I use these lines of code to add a JList to my frame but it doesn't do the job. DefaultListModel model = new DefaultListModel(); model.addElement("one"); model.addElement("two"); JList list = new JList(model); this.add(list);
you try this code DefaultListModel<String> model = new DefaultListModel<>(); model.addElement("one"); model.addElement("two"); JList<String> list = new JList<>(model); this.add(list);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, jframe, jlist" }
How do I upgrade postgresl database? Incompatibility error I installed postgresql via Homebrew. I have the following issue after upgrading: `FATAL: database files are incompatible with server DETAIL: The data directory was initialized by PostgreSQL version 9.0, which is not compatible with this version 9.1.2.` Any tips on how to upgrade? I tried the following: $ pg_upgrade -d /usr/local/var/postgres/ -D /usr/local/var/postgres -b /usr/local/Cellar/postgresql/9.0.4/bin -B /usr/local/Cellar/postgresql/9.1.2/bin It didn't work. Here's the output. Performing Consistency Checks Checking current, bin, and data directories ok Checking cluster versions This utility can only upgrade to PostgreSQL version 9.1. Failure, exiting error.
For me on OS X with Homebrew it was like this. 1. Installed new postgres with Homebrew (started getting the error) 2. `mv /usr/local/var/postgres /usr/local/var/postgres.old` 3. `initdb -D /usr/local/var/postgres` 4. `pg_upgrade -b /usr/local/Cellar/postgresql/9.0.4/bin -B /usr/local/Cellar/postgresql/9.1.2/bin -d /usr/local/var/postgres.old -D /usr/local/var/postgres` 5. `./delete_old_cluster.sh` (this script is created for you automatically in current dir when you go through above steps) 6. `rm delete_old_cluster.sh`
stackexchange-serverfault
{ "answer_score": 42, "question_score": 32, "tags": "postgresql" }
I have a json respons as followed using java. One of the field is a key:value pair of an array. And I have no idea how to get that as an array { "items": [ { "volumeInfo": { "industryIdentifiers": [ { "type": "ISBN_10", "identifier": "0080509576" }, { "type": "ISBN_13", "identifier": "9780080509570" } ] } } ] } In the above json, I need to extract industryIdentifiers' identifier value without losing any digit. I have tried using JSONArray but it eats up some of the digits jsonObj.getJSONObject("items") .getJSONObject("volumeInfo").getJSONArray("industryIdentifiers") .getString(0); Can anyone help me out?
Get the json array first and then iterate through it to parse. Use `org.json` import org.json.JSONArray; import org.json.JSONObject; JSONArray array = jsonObj.getJSONArray("items").getJSONObject(0).getJSONObject("volumeInfo") .getJSONArray("industryIdentifiers"); for (int i = 0; i < array.length(); i++) { String type = array.getJSONObject(i).getString("type"); String identifier = array.getJSONObject(i).getString("identifier"); System.out.println(type + " identifier : " + identifier); } ## Output on Java 9 ISBN_10 identifier : 0080509576 ISBN_13 identifier : 9780080509570
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, json" }
Does the test set is used to update weight in a deep learning model with keras? I'm wondering if the result of the test set is used to make the optimization of model's weights. I'm trying to make a model but the issue I have is I don't have many data because they are medical research patients. The number of patient is limited in my case (61) and I have 5 feature vectors per patient. What I tried is to create a deep learning model by excluding one subject and I used the exclude subject as the test set. My problem is there is a large variability in subject features and my model fits well the training set (60 subjects) but not that good the 1 excluded subject. So I'm wondering if the testset (in my case the excluded subject) could be used in a certain way to make converge the model to better classify the exclude subject?
You should not use the test data of your data set in your training process. If your training data is not enough, one approach using a lot during this days(especially for medical images) is **data augmentation**. So I highly recommend you to use this technique in your training process. **How to use Deep Learning when you have Limited Data** is one of the good tutorial about data augmentation.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, keras, deep learning" }
How to insert <th> tag in the table in asp.net in code behind file? I am adding table in code behind file. and i want to add tag in that. <table id="tbl" runat="server"> <tr> <th>test</th> <td> </td> </tr> </table> I dont know how to add through code. So can any one tell me how to add tag?
HtmlTable t = tbl; //just to make it clear your table is an HtmlTable tbl.Rows[0].Cells.Add(new HtmlTableCell("th")); //adds an emtpy cell to the first row with th tagname
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "asp.net, html table, code behind, tablerow" }
Spring 3.2 @ControllerAdvice Not Working I am having trouble getting `@ControllerAdvice` to work. I updated my namespace location, which were 3.1 in my xml files. I moved the class with the controller to the same package as the controller. I am using 3.2.0 release jars. If I put the `@ExceptionHandler` annotation in the controller code, it works, but not in a separate class with the `@ControllerAdvice`. When the `@ControllerAdvice` class fails, I get my uncaught exception handler view. Anyone have ideas on how to trouble shoot this one?
There is no extra configuration required. It should just work. Look at this link for more details. This provide very simple example: * < * <
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 26, "tags": "spring mvc, exception" }
application open on startup in background Apologies if this question has already been asked. I currently have it in the startup folder, but I'm not sure what code to use to not open the parent form. I want my vb.net application to open on startup but in the background so it doesn't annoy users when they log in. How would i go about setting that up?
To prevent a form from showing itself (but still create itself) you can override the following code in the form. Protected Overrides Sub SetVisibleCore(value As Boolean) MyBase.SetVisibleCore(False) End Sub This will always hide your form. Obviously pass true to make it display on whatever criteria you'd like to use. This approach doesn't require you to restructure your application to separate ui + logic.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vb.net, visual studio, startup" }
Ember.js component with HTML input range does not set value correctly I have a simple Ember component that only contains a single input range slider, like so: <input type="range" value=500 min=0 max=500 > When it renders initially, the slider's position is not set to the very end as you would expect. It is set at around the 100 position. ![enter image description here](
The solution is to change the order of the attributes and set the value after the max: <input type="range" min=0 max=500 value=500 > Normally in HTML the order of the attributes does not matter. However, in this case Ember seems to be converting it into something along the lines of: let input = document.createElement('input'); input.setAttribute('type', 'range'); input.setAttribute('value', 500); input.setAttribute('min', 0); input.setAttribute('max', 500); The default max of an input is 100. In this case, setting the 'value' to 500 before setting the 'max' is invalid so it gets set to 100 instead. See discussion here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, ember.js" }
How does the alternate primary stat for a class effect the overall stats? What does cunning do for a trooper or bounty hunter, or willpower on a warrior or knight, and vise versa? EX: If I applied all cunning gear to my commando, how would that effect his combat efficiency?
It only affects special critical chance and bonus damage (in the same way that it would if it were mainstat). So, for example, Cunning will give a Trooper or Bounty Hunter extra damage and crit chance for Tech attacks. This is _very_ minor and is by no means an alternative primary stat. Getting datacrons will have a small beneficial effect, but trading other stats in gear for this "offstat" would be a mistake.
stackexchange-gaming
{ "answer_score": 2, "question_score": 2, "tags": "star wars the old republic" }
Read a file from an unknown location? I have got this read file code from microsoft @"C:\Users\computing\Documents\mikec\assignment2\task_2.txt" That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me. So i was wondering if there is a way to read it from just the file the program is held in?. I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file. Thanks
You can skip the path - this will read file from the working directory of the program. Just `@"task_2.txt"` will do. **UPDATE** : Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then @ken2k's solution will be much more robust.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, readfile" }
Can I boot my recovered SSD as a Mac OS X installation I recovered an SSD from an old, upgraded 2008 Macbook Pro with a broken keyboard in order to recover the data from it. Initially I was planning to put it in my other Mac Pro and simply copy the data as if it was another drive, but then another idea came to my mind. What if I could boot that SSD from my Mac Pro? I don't know if it's possible to set the SSD as a boot drive and start a MBP installation on another machine. Otherwise I though it could be possible to save the drive as an ISO image and boot is using a virtualization software on my other Mac. Is this even possible? (AFAIK virtualization from another Mac is permitted and legal).
It depends on the system installed on the SSD. If the Mac Pro is capable of booting with it and it fits physically, then I see no problem why it shouldn't work. * MacPro1,1 - 2,1: max system version: 10.7.5 * MacPro3,1 - 6,1: max system version: latest * all MacBookPros 2008 (4,1 and 5,1) can run the latest system Usually all necessary drivers for **any** Mac (which can run the system) are included in a standard system install. There is only one exception: systems for new Macs with absolutely new hardware usually contain new drivers though the minor system version number is equal to the general current one. The build number is different though. The newly released Mac can't start from the general system release valid for all other Macs.
stackexchange-apple
{ "answer_score": 1, "question_score": 0, "tags": "boot, ssd, recovery, virtualization" }
Indicator function of rationality Let $X: [0,1]\to \mathbb {R}$ be a function that maps every rational number in the interval $[0,1]$ to $0$, and every irrational number to $1$. Assume that the probability space where $X$ is defined is $([0,1],\mathcal{B}[0,1],\mathbb {P})$, where $\mathcal {B}[0,1]$ is the Borel $\sigma$-algebra on $[0,1]$, and $\mathbb {P}$ is the Lebesgue measure. Is $X$ a random variable (and why)? If it is, what are its distribution function and expectation? Does $X$ have a density function? Is $X$ discrete? First of all, I think $X$ is a random variable since $X^{-1}\\{\emptyset,\\{1\\},\\{0\\},\\{0,1\\}\\}\in \mathcal{B}[0,1]$. I wonder how to get its distribution function. It seems like it's a kind of indicator function. Thanks for helping.
The set of rational numbers has Lebesgue measure $0$. This implies that $X=1$ almost surely. Hence $X$ is discrete, it does not have a density and $EX=E1=1$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability theory, measure theory, probability distributions, random variables" }
Precompiling MVC ASP.NET application via publish, Are the resultant files IL Code or Native Images? Just wanted to check whether the precompiled files from "publish" are IL or Native. The file extension are .compiled for the views, and dlls for others. I have seen some comment that imply that one of the advantages for doing this is to eliminate startup lag due to JIT, but this implies that they are native, but I am not sure. I have chosed "no merging" of files for my first attempt. Confirmation appreciated. Thanks. EDIT Is there any potential difference if I select x86, or "mixed platforms" or "any cpu". The latter 2 might imply IL code whereas x86 could be native. I am targetting a 32bit Azure Websites instance. I am trying to get rid of the warmup period issue.
It is IL. You can confirm it by running CorFlags.exe.aspx). The CorFlags section of the header of a portable executable image will indicate whether its 32bit or AnyCPU etc. Another utility that comes in handy is DUMPBIN.EXE. Even if you precompile your web applications, there's going to be an initial hit when you access the website. That process is described here. Its a tad dated, but much of it still applies. But the hit with a precompiled website is going to be substantially less than a non-precompiled website. When compiling, select "Any CPU" and control whether its a 32bit or 64bit application via IIS, Azure or the hosting environment. Let the framework do what the framework does best.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "asp.net mvc, asp.net mvc 3, asp.net mvc 4" }
how do you generate an ordered linear combination of values in a dictionary? I have a dictionary set up like so: d1 = {1:['A'],2:['B'],3:['C','D'],4:['E','F'],5:['G'],6:['A']} I need to concatenate all of the linear combinations of the values from this dictionary. However, the order of the letter in each list is important: concatenated strings should only be generated for those which are in the same order, ie, 'C' and 'E' should be concatenated, not 'D' and 'E'. For example, the results using the dictionary above should look like: String 1 = 'ABCEGA' String 2 = 'ABDFGA'
Here's one approach using `itertools.zip_longest`: from itertools import zip_longest z = list(map(list,(zip_longest(*d1.values())))) # [['A', 'B', 'C', 'E', 'G', 'A'], [None, None, 'D', 'F', None, None]] for ix_i, i in enumerate(z): for ix_j, j in enumerate(i): if not j: z[ix_i][ix_j] = z[ix_i-1][ix_j] list(map(''.join, z)) # ['ABCEGA', 'ABDFGA'] * * * A rather obscurer `itertools` based approach: from itertools import zip_longest, accumulate z = zip_longest(*d1.values()) out = [[*accumulate(i, lambda x, y: y or x)] for i in zip(*z)] list(map(''.join, zip(*out))) # ['ABCEGA', 'ABDFGA']
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, list, dictionary, concatenation" }
How to make two echo string in the same line? How to make two echo strings in the same line? #!/bin/bash echo "A" echo "B" | grep B result is: A B but I want it to be: `AB`
You could avoid the line break in the first echo call with `echo -n`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "bash" }
OpenLayers 3 Draw Interaction onFeature added event In OL2 I was able to do the following: var drawControl = new ol.Control.DrawFeature( myLayer, ol.Handler.RegularPolygon, { handlerOptions: { sides: 4, irregular: true }, eventListeners: { featureadded: function( e ) { // process features } } } ); Is there a way to do access the features once added in OL3? What I am trying to do is project the features once they have been drawn. Ideally, I would project them before they are drawn if that's possible.
// draw is an instance of ol.interaction.Draw // when draw ended but the feature was not added yet to ol.source.Vector draw.on('drawend', function(evt){ console.info(evt.feature); }); // vectorSource is an instance of ol.source.Vector // added to source vectorSource.on('addfeature', function(evt) { console.info(evt.feature); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, openlayers 3" }
Symfony 2 - Fatal error: Cannot redeclare class SessionHandlerInterface in C:\...\app\cache\dev\classes.php on line 532 After reinstalling my wamp environment this error message is showing on screen after I open app_dev.php: > Fatal error: Cannot redeclare class SessionHandlerInterface in C:...\app\cache\dev\classes.php on line 532 Does anyone have any clue what is going wrong?
I solved it clearing the cache: app/console cache:clear
stackexchange-stackoverflow
{ "answer_score": 44, "question_score": 20, "tags": "php, symfony" }
Internationalize excel formula There is some way to type internationalized formulas on excel macros?? Right now im doing some like this: If (languageCode = 1033) Then 'type formula in english sheet.cell(r,c).Value = "=IF(A1=B1, "i18n", "#error")" Else 'type formula in another language sheet.cell(r,c).Value = "=SE(A1=B1, "i18n", "#erro")" End If Im using this logic because the client's excel is in a different language than mine, but the formula is realy big, and there are many other languages to cover.. so im not liking the way it going. :( I did some reseacrh but with no satisfactory answers. _This is my very first question so, sorry if I made some typo or format mistake._
Accorcing to this article vba works internally with English, and Excel translates to the destination language at runtime. You should be able to do this with the `formula` property of the cell instead of the `.value`. sheet.cell(r,c).Formula = "=IF(A1=B1, "i18n", "#error")" See also Internationally Valid Excel Formula.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "vba, excel, excel formula" }
Analysis: Show that this series converges, determine the limit. The series in question is $$\sum_{n=2}^{\infty}\frac{2}{n^2-1}.$$
We observe that $\frac{2}{n^2-1} = \frac{2}{(n-1)(n+1)}.$ Using partial fractions we see that $\frac{2}{(n-1)(n+1)}=\frac{1}{n-1}-\frac{1}{n+1}.$ Now we compute the $k$-th partial sum: $$S_k=\sum_{n=2}^{k}\frac{2}{n^2-1}=\sum_{n=2}^{k}(\frac{1}{n-1}-\frac{1}{n+1})=1-\frac{1}{3}+\frac{1}{2}-\frac{1}{4}+\frac{1}{3}-\frac{1}{5}+\space...\space+\frac{1}{k-1}+\frac{1}{k+1}=1+\frac{1}{2}-\frac{1}{k}-\frac{1}{k+1}$$ Hence $$\sum_{n=2}^{k}\frac{2}{n^2-1}=\lim_{k\rightarrow \infty}S_k=\lim_{k\rightarrow \infty}(1+\frac{1}{2}-\frac{1}{k}-\frac{1}{k+1})=1+\frac{1}{2}=\frac{3}{2}$$
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "real analysis, sequences and series, limits, convergence divergence" }
Python: Remove HTML Tags & text inbetween HTML Tags I'm trying to remove HTML tags (Python 3) but also trying to remove the text in between them. My below code snippet doesn't seem to give me the result I'm looking for and all the other questions I've found on SO seem to only look at removing the HTML tags but preserving the text inside the HTML tag which is not what I'm trying to do. **Current Code** import re ... price="12.00 <b>17.50</b>" price=re.sub('<[^>]*>', '', price) **String** 12.00 <b>17.50</b> **Expected Outcome** 12.00 **Current Outcome** 12.00 17.50
You can also do it with an HTML Parser, like `BeautifulSoup`. The idea is to find all the tags and _decompose_ them, then get what is left: In [8]: from bs4 import BeautifulSoup In [9]: price = "12.00 <b>17.50</b>" In [10]: soup = BeautifulSoup(price, "html.parser") In [11]: for elm in soup.find_all(): ...: elm.decompose() ...: In [12]: print(soup) 12.00 And, here is a famous topic explaining why you should not process HTML with regular expressions: * RegEx match open tags except XHTML self-contained tags
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "python, regex, python 3.x" }
Baixar arquivo PDF por link no e-mail Desenvolvi uma função que passando o id do Item ele gera um arquivo PDF. [HttpPut] public void GerarPDF(long idItem) { ....Função } Ela já funciona perfeitamente, fiz o teste através do app do Google Chrome chamado PostMan, e passando o caminho ele gera o PDF e baixa tudo certinho, porém se eu enviar este mesmo caminho no corpo de um e-mail através de um `<a></a>` para que a pessoa que recebeu o email possa gerar o PDF, este caminho não funciona: "<a href= + IdItem.ToString() + "> link Download PDF </a>" Dando o seguinte erro: ![inserir a descrição da imagem aqui]( Agora não sei se é pelo fato de estar tentando abrir por localhost ou não, se alguém puder me ajudar agradeço.
Eu utilizo assim para fazer o Download. public FileResult DownloadAnexo(int id) { string URL = //BUSCAR URL ARQUIVO DESEJADO; return File(URL, "multipart/mixed", "Nome_SeuArquivo"); } Observe que o retorno é um **`FileResult`**
stackexchange-pt_stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, asp.net mvc" }
How to display text from an array in a UITextView, I might just need the right string format? I have a multiline array which populates a tableview. I now also want to use the array for a UITextView to display the string as it's currently being displayed. I have it displaying everything as I want except for one of the symbols in the array which does not display as it should. I feel like all I need is the right string format? textView.text = String(format:"%@", array) The code above is how I have it ALMOST working but the "x" symbol from the array is being substituted with `"\U00d7"` The "x" does not appear to be an actual letter, (thus the `"\U00d7"`) not an iOS one anyway. Before adding the format `"%@"`, the "x" symbol was being displayed as an x. I want it to be displayed as I have entered it into the array rather than having to always change the "x" symbol for an iOS "X" symbol.
Using `String(format:_:)` is not a good idea in this case. `%@` does not work with `utf8` encoding. Try `textView.text = array.joined()` instead.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ios, arrays, swift, uitextview" }
Wordpress Widget auto activate I am new at widgets, but I have to write my own widget and get it to display correctly in my theme. Now, I have to add this widget "auto activate" in the sidebar. So, when user install this theme, Widget is automatically add in Sidebar, So user have to not set widget in sidebar from admin panel. Is that possible?
Yes and no. You can build it as a default widget to be included in the sidebar if no other widgets are there. But if the sidebar is truly widget-ready and the administrator pops a new sidebar widget into the lineup, things will automatically switch over to use the admin's specified settings (the list of widgets they've manually added to the sidebar). So yes, you can set it up as a default. But no, you can't make it auto-activate.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "wordpress, wordpress theming" }
How to create Tax rule programmatically in controller magento 2 I have try with this code make tax rule programmatically. but it's not working infact model not loaded. you can see this code : $objectManagers = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $fixtureTaxRule = $objectManagers->create('Magento\Tax\Model\Calculation\Rule'); i have get this error : Class 'Magento\TestFramework\Helper\Bootstrap' not found can you please suggest how can i create tax rule ?
Finally i have solve this issue. Now you can use this code and i hope it's also beneficial for you guys. $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $fixtureTaxRule = $objectManager->create(\Magento\Tax\Model\Calculation\Rule::class); $fixtureTaxRule->setCode("Test"); $fixtureTaxRule->setPriority(0); $fixtureTaxRule->setCustomerTaxClassIds(array(3)); $fixtureTaxRule->setProductTaxClassIds(array(2)); $fixtureTaxRule->setTaxRateIds(array(3)); $fixtureTaxRule->save();
stackexchange-magento
{ "answer_score": 4, "question_score": 1, "tags": "magento 1.9, magento2, tax, rules, object manager" }
How to start and keep sockets connections accross multiple activities? i'm having trouble finding a way to implement this: I have an activity A from where i'll start 2x separate socket connections. Afterwards i'll move to an activity B from where i'll go back and fourth with activities C and D. All 3 activities will exchange messages via the sockets. Now from my understanding i need to create a service for each socket, but how exactly do i maintain both sockets open, without creating a new connection everytime i switch to another activity? Also how do i keep the services running an "accept loop", prompting an action for the current activity the user is in? thanks
You're correct that you should use a `Service`. A good rule of thumb is that you should use a service for any background processing that is not logically bound by the lifecycle of a single activity. (And use `AsyncTask` for background processing that _is_ logically bound by the lifecycle of a single activity.) But you don't need to create a service for each socket. You should create one service that does whatever it is you need to do with the sockets. There are a variety of ways your activities can interact with the service and pass messages or obtain references to its sockets, which you can read about in the documentation.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, sockets, android service" }
How can I fix "cannot find declaration to go to" in WebStorm? I'm using WebStorm with JavaScript and when I press `F3` or `Ctrl + Click` on function I get message that say "cannot find declaration to go to". This happens only in functions that I wrote on my computer, with other functions it works great. I wrote my functions declarations exactly like all the other functions that go to declaration works for them. I'm using Ultimate version. I tried `File->Invalidate cache\Restart...` and it didn't work. Any suggestions? EDIT: Example of the function: FaasInitUtils.prototype.createCompnentData = function createCompnentData(app) { } when I call this function I do it like this: FaasInitUtils.prototype.configureSiteCdmRT = function configureSiteCdmRT() { var componentData = this.createCompnentData(app); }
I manged to fix it. I had a lot of projects and big one in Webstorm, what I excluded target folders and then everything started to work (including colors). So I think that there is a problem with the configuration of memory limitation/consumption.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "javascript, webstorm" }
Buying a Used Macbook, iCloud I'm purchasing a used 2013 Macbook Air on craigslist and the seller told me he formatted it already and created a dummy account so I can go through settings, etc.. and browse around to ensure all is working. I want to be sure that I do not get locked out of the Macbook Air. If he formatted and logged out of iCloud, what is the best way to check that I will come out of this purchase safely? Should I log myself into iCloud and turn on 'Find My Mac'? The reason is it is an old OSX so I need to do some updating afterwards. I don't have experience buying used macbooks so any help is appreciated, thank you.
Mac do not have hardware activation lock. Read the last paragraph of the "FAQ" for confirmation. * < You would want to check for a Firmware Password which might need another question if you don't know what that is, but iCloud cannot prevent you from reinstalling an OS or activating any Mac that has shipped thus far. * < Since a bad actor could use the lock function to remotely set a Firmware Password, your step of logging in and signing into your iCloud and successfully activating Find My Mac and locking it would ensure you have exclusive control of that device going forward.
stackexchange-apple
{ "answer_score": 2, "question_score": 1, "tags": "mac, icloud, hardware, activation lock" }
Data: Vacancies in the US before 2005 Shimer (2005) says > These [separation shocks] introduce an almost perfectly positive correlation between unemployment and vacancies, an event that essentially never been observed in the United States at business cycle frequency. What is the data corresponding to that? Since his publication was from 2005, he must be referring to data on vacancies before the big recession. However, the standard data on job openings, JOLTS, is only available from 2005 onwards.
JOLTS actually goes back to 2000 (though years before 2005 are only available on a SIC basis). Prior to JOLTS, most people used data on the number of help-wanted ads in newspapers, such as this series from the 1950s-60s or this one that goes back to 1919.
stackexchange-economics
{ "answer_score": 3, "question_score": 3, "tags": "macroeconomics, data request, unemployment, labor economics" }
Gmail apps script getBody/getPlainBody without signature? I'm calling `messages[j].getPlainBody();` to output the body of an email and log it in a spreadsheet. I want to log the plain text of the email - not the signature, footer etc from the email. How can I do this? I notice in Gmail there's a sort of tab that hides my signature when I'm writing/viewing emails - can I access this programmatically somehow to achieve the above?
The Gmail UI intelligently collapses the messages to hide previous messages or signatures. There is no way to do this in the API. You can log an enhancement request here - <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "google apps script, gmail" }
Python regex for something *not* in a dictionary? Say I have the following dictionary: d = {"word1":0, "word2":0} For this regex I need to verify that a word in the string **isn't** a key in that dictionary. Is it possible to set a variable to anything **not** in a dictionary, for the purposes of a regex?
>>> d = {"foo":0, "spam":0} >>> test = "This is a string with many words, including foo and bar" >>> any(word in d for word in test.split()) True If punctuation is a problem (for example, `"This is foo."` would not find `foo` with this approach), and since you said all your words are alphanumeric, you could also use >>> import re >>> test = "This is foo." >>> any(word in d for word in re.findall("[A-Za-z0-9]+", test))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, regex, dictionary" }
db_index in django as raw sql query Can anyone specify the raw sql query executing for a `db_index = True` in django, I have a model field which I need to alter with db_index as True, but my rds server crashes since a lot of db process runs in parallel, url = models.CharField(db_index=True,max_length=100, blank=True) What will be the raw psql query for this alteration
If you add `db_index=True` to the model and then run `makemigrations`, you can use `sqlmigrate` to show the SQL command for your database backend. python manage.py sqlmigrate my_app 000X_migration_name For postgres, this will generate SQL similar to the following: BEGIN; -- -- Alter field url on mymodel -- CREATE INDEX "myapp_mymodel_url_2e338adc" ON "myapp_mymodel" ("url"); CREATE INDEX "myapp_mymodel_url_2e338adc_like" ON "myapp_mymodel" ("url" varchar_pattern_ops); COMMIT;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "django, python 3.x, django models, django rest framework, psql" }
cast from varchar to long i need to cast from varchar(100) to bigint that way: select max(cast(referencia_factura as bigint))from ventas; but i get a syntax error. ¿how can i solve it? I need to get the maximum value of the "referencia_factura" field but I need to cast it to bigint.
As it is explained in Cast Functions and Operators, casting to `BIGINT` is not supported by MySql. I guess that `referencia_factura`'s values are too long so they can't be converted to `UNSIGNED` and also an implicit conversion like `referencia_factura + 0` would fail. In this case what you can do is left pad the column values with `0`s up to the max length of the column which is `100` and compare them as strings to find the maximum and then trim all the leading `0`s: SELECT TRIM(LEADING '0' FROM MAX(LPAD(referencia_factura, 100, '0'))) FROM ventas; See the demo.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, sql, casting, max" }
Is there an easy way to create an AI opponent for the Othello game? Is there a well known AI technique to create an opponent in the game Othello (aka Reversi)?
Standard game-tree search techniques will beat most human players easily. Othello has less combinatorial complexity than chess, and humans have a harder time forecasting the future in Othello. < <
stackexchange-gamedev
{ "answer_score": 7, "question_score": 3, "tags": "game design, ai, competition" }
Adding a column with character data to a ffdf I've tried to add a Source column to my ffdf, but can't seem to get it to work... if it was a normal df I would simply write mtcars$NewCol <- "AB" If I do this for the ffdf it returns an error require(ff) require(ffbase) mtcarsff <- as.ffdf(mtcars) mtcars$NewCol <- "testname" Error in `[[<-.ffdf`(`*tmp*`, i, value = "testname") : assigned value must be ff Any Ideas?
This should work: mtcarsff$NewCol <- as.ff( rep(factor("AB"), times = nrow(mtcarsff)) ) Note that "AB" must be considered a factor, not a character.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "r, dataframe, bigdata, ff, ffbase" }
Angular Sort columns Now this is what i'm working with because i can't get it to work. I don't think it's bad in anyway but still: In my app.component.html i've got: <table border="1"> <!-- ADD HEADERS --> <tr> <th><a href="#" (click)="send()">Name</a> </th> <th>Goverment form</th> </tr> </table> In my app.component.ts I've got: } return 0; }); } -------- Data: ------- export interface Country { Name:string; GovernmentForm:string; } export class AppComponent { public Countries: Country[];
You need to change your sort function to compare the `.Name` property, instead of the whole object. You can do this like so: this.Countries = this.Countries.sort((n1, n2) => { if (n1.Name > n2.Name) { return 1; } if (n1.Name < n2.Name) { return -1; } return 0; });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, angular, typescript, sorting" }
Reputation discrepancy > **Possible Duplicate:** > How does "Reputation" work? There is presently an unusually large discrepancy between my SO reputation (11,961) and that shown on < (11876). I check this page with some regularity, so this discrepancy is recent. I cannot think of a reason for an 85 point delta. Can one of the moderators please tell me what is going on?
I looked through your questions and answers, however I could not find anything deleted _recently_ (as in this week) that would fully account for the discrepancy. I'm not sure how often you check `/reputation`, but I don't think it was a 90 point drop all at _once_. Whatever the combination, such as: * Rep earned on posts later made CW then deleted recently (not your fault) * Irregular vote checks (not your fault) * The house cleaning we've been doing recently (not your fault) ... it was (not your fault). Note, I did not check every date on every answer and every question that was deleted, because I just don't have time to do that. However, nothing seems out of the ordinary.
stackexchange-meta
{ "answer_score": 2, "question_score": -3, "tags": "support, reputation" }
express.js app get not showing console log message const express = require("express"); const app = express(); app.listen(3000, function () { console.log("started at 3000"); }); app.get("/", function (req, res) { console.log("Hello"); const car = "read"; res.send("Hello, world"); }); res.send is working fine. However, console log is not showing. It only shows when I remove the variable. I am running using nodemon. Any idea what's going on?
Nodemon with Auto Save cause the problem, use manual save (Ctrl + S) instead
stackexchange-stackoverflow
{ "answer_score": -3, "question_score": 2, "tags": "javascript, node.js, express, console.log" }
Return result of query from function in postgresql I have the query for example "select id, field1, field2 from table1" (id and field1 are integer and field2 is varchar) and I need call the query from function and return result as is. CREATE OR REPLACE FUNCTION get_all_record() RETURNS TABLE(id integer , field2 varchar(20)) AS $$ BEGIN EXECUTE 'SELECT table1.id, table1.field2 FROM table1' INTO id, field2; RETURN; END; $$ LANGUAGE plpgsql but this solution returns only one record in one field. How can I correct it?
Try this: CREATE OR REPLACE FUNCTION get_all_record(OUT id integer, OUT field2 varchar(20)) RETURNS SETOF record AS $$ BEGIN RETURN QUERY SELECT table1.id, table1.field2 FROM tiers; END; $$ LANGUAGE plpgsql;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "postgresql" }
SharePoint 2007 Site Template (.stp) file display category I have created a Site Template file (.stp). When I add it to the site templates gallery of the target farm it shows up in a strange tab when you go to provision the a new sub-site based on the template. I would like it to display in the publishing tab or a new custom tab (display category) on the create site page. The site template gallery doesn't allow you to assign the category. My question is how does one configure which tab the template will show up in? Here is a link to the .stp file. !enter image description here
I never did figure this out. The solution I ended up going with was creating a custom site definition.
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 5, "tags": "site template, categories" }
View's in Entity Framework won't update I have a view which includes data from multiple tables. When I call that view, the results are loaded into the memory and stored. After I make some changes to the other tables which should effect the view, the view don't know anything about the changes. So when I call that view again, for example a Get() method, EF returns the values of the stored data. Of course I want the updated data. How can I force the view to get the data from DB and not from memory? Or is there a better strategy? Better if I can make the view aware of the changes being made. Is this achievable with entity configuration, maybe by using HasRequired() method to map FK's? **EDIT:** I am using repository and unit of work pattern. So I am not creating and disposing a new context each time. Please consider this.
When you execute the Linq query on the view use `AsNoTracking()` extension method. This will force EF to always use data from database instead of memory: var result = from x in context.ViewSet.AsNoTracking() select x; EF will not handle any automatic data refresh for you.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 4, "tags": "entity framework, view" }
Azure Functions Core Tools v3.0.2009 "func init" no longer creates project file I have removed the earlier version of Azure Function Core Tools and installed the version 3 by running `npm install -g azure-functions-core-tools@3` After the update i can create Azure functions v3 from both VS2019 and VS Code but CLI no longer creates the project file. Previously i was able to run `func init PROJECTNAME` and it was creating the full folder structure with .csproj file which i could use later on with VS Code or VS2019 but this is no longer working for me. I have NodeJs v12.14.0 I have func version 3.0.2009 I have azure client version 2.0.79 Here is the result when i issue func init `c:\temp>func init FunctionApp3` `Select a worker runtime: dotnet` `Writing c:\temp\FunctionApp3\.vscode\extensions.json` c:\temp No errors Am i missing something?
**Update:** Thanks to Murat Kazanova for his efforts. The problem still seems to be related to the npm installation, which is the similar as what I have encountered before. In order to make it easier for people who encounter this problem in the future to get rid of this problem, I post here other efforts made by Murat Kazanova. Besides trying npm reinstall, you should also try performed npm cleanup, reinstalled azure client tools and updated vs studio with azure tools. **Original Answer:** Please reinstall the function core tools and restart your computer. I face this problem before(cannot create the project I set, only create some json files and other files), but after that operate this problem disappear. Have a try on your side.:)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "azure functions" }
how to save file in another machine in the same network in c#? I have to save the uploaded document into another local machine. But I was not clear how to use impersonation in my code. I have used the following code. protected void btnSave_Click(object sender, EventArgs e) { int result = 0,result1=0; string attachmentpath = "C:\\Documents and Settings\\pr84528\\My Documents\\PRABU\\Tech\\Dot Net\\DocumentManager\\Attachments\\"; .................................................................................... .................................................................................... if(fuDocument.HasFile) fuDocument.SaveAs(attachmentpath + fuDocument.FileName); .................................................................................... .................................................................................... }
I think here is your solution. <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "c#, .net, impersonation, remote desktop" }
Problem with is_tax in WP_Query loop The code below is the 2nd of 4 loops in "page-balls.php". Everything else is working correctly. I'm trying to display a tennis ball graphic if the post being retrieved has a the term "tennis-ball" term. It's not working. Is this because the PAGE does not have the term TENNIS-BALL? How can I make this work correctly? <?php $args = array ( 'post_type' => 'balls', 'orderby' => 'menu_order', 'order' => 'ASC' ) ; $myQuery = new WP_Query( $args ) ; ?> <?php if ($myQuery->have_posts()) : while ($myQuery->have_posts()) : $myQuery->the_post(); ?> <?php if(is_tax( 'ball-types', 'tennis-ball' )) : ?> SHOW THE TENNIS BALL GRAPHIC <?php else : ?> SHOW THE PLACEHOLDER GRAPHIC <?php endif ; ?> <?php endif ; ?> <?php wp_reset_postdata() ; ?>
The codex on `is_tax`: > This Conditional Tag checks if a custom taxonomy archive page is being displayed. That is not the condition you want to check for. Take a look at the `has_term` function and use it like so: if( has_term( 'tennis-ball', 'ball-types', $post->ID ) ) { /* SHOW THE TENNIS BALL GRAPHIC */ } else { /* SHOW THE PLACEHOLDER GRAPHIC */ } And as an aside, remove some of the `<?php` opening and closing tags. They serve no purpose and simply make your code less legible.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp query" }
MySQL - Consider multiple rows with equal value in two columns as one row Let's say I have a table with the following data: Event_ID | Action_ID | Date_of_Action 1 | 1 | 2015-06-25 2 | 1 | 2015-06-25 3 | 1 | 2015-04-10 4 | 2 | 2015-05-11 I need to get the count of rows in this table with specific Action_ID's and display them, but I need to treat any rows with the same Action_ID AND Date_of_Action as 1 row(or 1 count). I want it to display: Count 1 | Count 2 | 2 | 1 I have tried this: SELECT SUM(IF(event.Action_ID = 1, 1, 0)) AS 'Count 1', SUM(IF(event.Action_ID = 2, 1, 0)) AS 'Count 2', ... GROUP BY event.Action_ID, event.Date_of_Action But my Output looked like this: Count 1 | Count 2 | 3 | 1 Any ideas?
I would start by getting distinct action_id and date pairs like this: SELECT DISTINCT action_id, date_of_action FROM myTable; Once you have that, you can get count using conditional aggregation: SELECT SUM(action_id = 1) AS 'count 1', SUM(action_id = 2) AS 'count 2' FROM( SELECT DISTINCT action_id, date_of_action FROM myTable) tmp; Here is an SQL Fiddle example.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "mysql, count, group by, sum, distinct" }
Identify Platform Browser in Ionic2 i am looking for a solution to identify the platform 'browser' i was hoping that there is a platform.is('browser') like for the other platforms ios, android or windows, but i could find nothing in the docu. the reason for this is that i am using firebase authentication wrapped in native login plugin if i am in an generated native app. but because i also want to offer the browser directly to login, for this i want to login by simple angularfire2 login method. i tried something like this: if ((!this.platform.is('ios') && !this.platform.is('android')) || this.platform.is('mobileweb')) { this.inBrowser = true; } so when i open on my android phone my page in chrome it still tries to use the native plugin login :( thanks in advance for any help!
Install cordova-plugin-device and check `device.platform`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "cordova, firebase, ionic2, cordova plugins, ionic3" }
Simply connected = path connected + 2nd condition I read on Wikipedia: > A topology space is called simply connected if these conditions are met: > > (1) it is path connected > > (2) _every path between two points can be continuously transformed (intuitively for embedded spaces, staying within the space) into any other such path **while preserving the two endpoints in question.**_ I don't understand the sentence in bold in #2. If I must preserve the two endpoints of my path as I transform it I wouldn't be able to convert it into any other path in the space that is **not** passing through those two original points. I am assuming that by "preserving end points" we mean we are preserving their locations on the space. This seems limiting and would not work as far as I can tell for e.g. a sphere which is supposed to be simply connected. What am I missing here?
Note that in this context, "any other such path" means "any other path **between the same two points** ". I hope that clears things up.
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "general topology, connectedness" }
Get the return code of a C program in my shell program Suppose I have a C program named `Foo.c` which is printing few things and returning a value named `rc` which I am executing in my shell program as follows : `foobar=$(Foo | tail -1)` Now, the variable foobar has the last printed value of the program `Foo`. But without disturbing this, I want to get the return code `rc` of the program in my shell program.
You can use "set -o pipefail" option. [root@myserver Test]# set -o pipefail [root@myserver Test]# ./a.out | tail -l [root@myserver Test]# echo $? 100 Here my program a.out returns 100. Or another options is to use pipestatus environment variable. You can read about it here. <
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 14, "tags": "c, bash, shell" }
VBA: Delete one row if values match I am trying to create a macro that looks for **"Total net** " and **"Program Operation net"** in column C. Once located, the macro compares the rows of these two cells and of their values match then row of **"Total Net"** get deleted. This is my code so far... Sub DeletingEmptyPages() Dim WS As Worksheet For Each WS In Sheets Dim Mystring As String Dim MystringII As String MystringII = "Total Net" Mystring = "Program Operating Net" Dim n As Long Dim nlast As Long Dim rw As Range Set rw = ActiveWorkbook.ActiveSheet.UsedRange.Rows nlast = rw.count For n = nlast To 9 Step -1 If (Column(c).Value = MystringII And Column(c).Value = Mystring) Then rw.Rows(n).Delete End If Next n Next WS End Sub
I suppose that when both strings exist in column "C", you want to compare if columns "A" and "B" are equal in both rows. You can use the following code and easily adapt it if more columns need to be compared on the matched rows: Sub Delete_DuplicateTotalNet() Dim WS As Worksheet, row1 As Long, row2 As Long For Each WS In Sheets With WS On Error Resume Next row1 = WorksheetFunction.Match("Total Net", .Columns("C"), 0) row2 = WorksheetFunction.Match("Program Operating Net", .Columns("C"), 0) If Err.Number <> 0 Then GoTo NextWS If .Range("A" & row1).Value = .Range("A" & row2).Value And _ .Range("B" & row1).Value = .Range("B" & row2).Value Then .Rows(row1).Delete End If End With NextWS: Err.Clear Next WS End Sub
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "vba, excel" }
How to start from storyboard and modal to MainWindow.xib? I have two projects, one starts from a storyboard and another is from `MainWindow.xib`. I want to combine them together, start from storyboard and click a button to launch the view of `MainWindow.xib`. What do I have to set? How should I modify the code? Please help, thanks a lot!!
You should leave your project with storyboard as is, i.e. configure `Main Interface` combobox with that `storyboard` and set there `Initial View Controller`. At the some point, when you want to present view controller from `MainWindow.xib`, you could put some code like that: MainWindow *mw = [[MainWindow alloc] initWithNibName:@"MainWindow" bundle:nil]; [self presentViewController:mw animated:YES completion:nil];
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "ios, objective c, iphone, storyboard, xib" }
Debugging on the remote cluster I have a program which works fine in a local cluster but not running properly when executing in on the remote cluster. I would like to know, what are the best and common ways of debugging a program running on a remote Flink cluster? Any help is appreciated!
There are several ways to debug a Flink application on a remote cluster. Since using a real debugger is complicated, I would first try to log as much as possible to find out the error. Another approach that could be helpful is using Flink's accumulators. With them, you can gather some statistics: For example when you have a filter, you can determine, how many elements passed the filter and so on. The last resort is attaching a debugger to one of the Flink TaskManager JVMs. Also check out my presentation on the topic: <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "apache flink" }
Resize fixed modal I have the following fiddle < I'm going to explain what I have know, and what I intent to achieve. **NOW** I have a fixed position modal in the middle of the page in a min-width and min-height ... that is for mobiles devices... all works ok... if you resize the page it's all fine. **What I need** Due to the min-width and min-height, the modal keeps its size, so I need that when the screen is bigger, the tourImage also increase its size. I try to use width: 80%; min-width:260px; This in order to resize the picture but didn't work. Any advice?
You could try this way. What you will get is that the width of the image won't overflow the container div. @media screen and (max-width:800px){ .tourImage{ position: relative; width: 80%; min-width: 260px; min-height: 340px; margin: 0 auto; background: #55acee; } .popover{ background:#fff; width: 80%; transform: translate(-50%, -50%); position: fixed;; top: 50% !important; left: 50% !important; padding: 0 20px; } } @media screen and (max-width:400px){ .popover{ width: auto; } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "html, css, resize" }
jQuery toggle children of div I have the following HTML code: <div class="dim"> Menu <div class='hidden'>submenu1</div> <div class='hidden'>submenu2</div> </div> <div class="dim"> Menu2 <div class='hidden'>submenu3</div> <div class='hidden'>submenu4</div> </div> class `hidden` has `display:none` I'm trying to get the toggle to work when I click on the word menu or menu2
$('.dim').click(function(){ $('.hidden', this).toggle(); // p00f }); Fiddle: < * * * ### Update Checks for `dim` element being clicked: $('.dim').click(function(event){ var isDim = $(event.target).is('.dim'); if(isDim){ //make sure I am a dim element $('.hidden', this).toggle(); // p00f } }); Fiddle: <
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 8, "tags": "javascript, jquery" }
Which file gradle.properties is higher priority? I have local and global gradle.properties, the global one is needed to configure the proxy, but it also contains other parameters, wondering what happens if for the same settings you specify different values, which of the files will be in priority or maybe they are How do they merge? my global gradle.properties systemProp.http.proxyHost=hostname systemProp.http.proxyPort=8080 systemProp.http.proxyPassword=password org.gradle.parallel=false my local gradle.properties android.useDeprecatedNdk=true org.gradle.daemon=true org.gradle.parallel=true org.gradle.jvmargs=-Xmx4096M For example, which `org.gradle.parallel` will be used?
According to the Gradle properties, the `gradle.properties` files are applied in the following order: 1. `gradle.properties` in project root directory. 2. `gradle.properties` in `GRADLE_USER_HOME` directory. 3. system properties, e.g. when `-Dgradle.user.home` is set on the command line. Because the properties in `GRADLE_USER_HOME` are applied after the ones in the project root, they override the ones defined in the project. Assuming that with global you mean the one in the `GRADLE_USER_HOME` directory and local the one in your project root, your value for `org.gradle.parallel` will be `false`.
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 14, "tags": "gradle, android gradle plugin, gradle.properties" }
Allow a button to give points FOR a certain amount of time in Android I am only seeing articles on how to do something after a certain amount of time, but I want to know how to do something FOR a certain amount of time in Android. public void buttonClick(View v) { currentUser.changeScore(10); TextView tv = (TextView) findViewById(R.id.score); tv.setText("Score: " + currentUser.getScore()); } I want to the user to be able to press the button and gain points for 10 seconds after an Event has occured. After those 10 seconds, I want the user to lose 10 points if the button is pressed.
It's simple. Every time your event happens, set a variable, like this: long positivePointEndTime = 0; // In your event handler... positivePointEndTime = System.currentTimeMillis() + 10000; // Then in the button click handler int scoreChange = System.currentTimeMillis() < positivePointEndTime ? 10 : -10; currentUser.changeScore(scoreChange); It's not like you're really wanting anything to _change_ on a regular basis during that interval - the event is just setting a new point in time as the boundary of when it's "good" to click the button. No need for a timer or anything like that. (For testability you may want to have a dependency-injected `Clock` type or something similar to provide the "current time" functionality, but the basic principle is the same.)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, android, button" }
How to recover an emptied file in Remix I am using Remix IDE on Chrome browser for developing smart contracts. Today during working on a file when I changed program tab and returned to it again, I found that all of the file contents has been deleted automatically. No Ctrl+Z, close and reopen and other tricks was useful. 1- Can anyone help me recover the emptied file? 2- Does Remix have any limitation in file size? Regards.
There is no solution for this problem. I have lost some of my important Solidity program files in both Chrome and Firefox. Finally I decided to use `remixd` service as a localhost server and use store my Solidity programs in my local file system.
stackexchange-ethereum
{ "answer_score": 1, "question_score": 5, "tags": "remix" }
Styling existing tabs look like radio buttons Working on a project that uses legacy code (javascript) and an ecommerece framework for logic which currently uses 'tabs'. The client decided they now want radio buttons instead of the tabs. The basic structure is ul > li where the li's are styled and act like tabs with an href and styling classes ect. Rather than trying to re-wire everything to function with a radio button, I am trying to find a way to style the tabs to look like radio buttons. Is it even possible?
I made a link to show you how to do it: <body> <ul> <li><div class="middle"></div></li> <li><div class="middle"></div></li> <li><div class="middle"></div></li> </ul> </body> li { display: inline-block; height: 20px; width: 20px; border: 1px solid black; border-radius: 50% } .middle { height: 10px; width: 10px; background: black; margin:5px; border-radius: 50%; visibility: hidden; } $(document).ready(function () { $('li').on('click', function () { $('.middle').css({ 'visibility': 'hidden' }) $(this).children().css({ 'visibility': 'visible' }); }); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, radio button" }
How to append a dataframe to another one (with the same column size) when the column names are different Is there a way to merge two dataframes with the same number of columns but with different names? The `concat`, `merge`, and `join` methods do not seem to work for this task. For example, I want to combine these two: #dataframe1: columnA | columnB 15 | 23 #dataframe2: columnC | columnD 12 | 29 Into this: #dataframe3: anyColumnName1 | anyColumnName1 15 | 23 12 | 29 Please note that I have **90 columns** in my case.
You could rename the columns of the second dataframe first. If they have the same number of columns then simply: `dataframe2.columns = dataframe1.columns` and then concat them.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, pandas, dataframe" }
Overriding default foreign key and local key in Eloquent relationships Laravel 5 I am confused about second and third arguments while defining eloquent relationships. public function phone() { return $this->hasOne('App\Phone', 'foreign_key', 'local_key'); } public function user() { return $this->belongsTo('App\User', 'foreign_key', 'other_key'); } I understand the second argument in both relationships, it is foreign key which will be same. However, I am confused about third argument about what it refers to? I have an assumption that this is the key to which foreign key refers so it would be same too in both relationships. I do not know whether I am right or wrong. Please elaborate the answer.
Your assumption is correct. Both arguments refer to the exact same two columns. Both `foreign_key` parameters are the foreign key column on the `phone` table. _(Without specifying anything that would be`user_id` in your case)_ `local_key` and `other_key` are the counterpart, the column the foreign key points to. In most cases that's also the primary key column of the other table. _(Without specifying anything that would be`id` in your case)_
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "eloquent, laravel 5.1" }
Is it better to use Labels instead of Sprites for pop up text I would like to pop up text when the user blasts some balls in my game. At the worst came I may need 70 pop ups at the same time. The pop up is basically the score earned for each ball popped. Right now I am using CCLabel for that. Would it be easier on the processing if I used sprites instead? I have a lot going on in the game and want to ease the load on the processor. Advice is much appreciated. Thanks
If you're using CCLabelBMFont, you shouldn't see much difference between that and using a Sprite. Using CCLabel would probably be a mistake and may present a noticeable difference between CCLabelBMFont and CCSprite.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "memory, cocos2d iphone, sprite, label" }
Не получается записать текст в файл С# Не записывает текст в файл=( Подскажите, пожалуйста, что не так? string CurrentDirectory = Directory.GetCurrentDirectory(); if (!System.IO.File.Exists(CurrentDirectory + @"\update.txt")) { File.Create(CurrentDirectory + @"\update.txt"); using (FileStream fstream = new FileStream(CurrentDirectory + @"\update.txt", FileMode.OpenOrCreate)) { string text = "hello!"; byte[] array = System.Text.Encoding.Default.GetBytes(text); fstream.Write(array, 0, array.Length); } }
Где-то здесь `using (FileStream fstream = new FileStream(CurrentDirectory + @"\update.txt", FileMode.OpenOrCreate))` вылетает исключение о том, что файл занят другим процессом? Это потому что здесь `File.Create(CurrentDirectory + @"\update.txt");` создаётся новый файл и без освобождения ресурсов следом к нему осуществляется новое обращение `new FileStream(CurrentDirectory + @"\update.txt", FileMode.OpenOrCreate)`. 1. После создания нового файла необходимо освобождать ресурсы так `File.Create(Файл).Dispose()` или же так `using (File.Create(Файл)) { }`. 2. В данном случае в этом `File.Create(CurrentDirectory + @"\update.txt")` нет необходимости, т.к. `FileStream` с параметром `FileMode.OpenOrCreate` в любом случае создаст файл на следующем шаге.
stackexchange-ru_stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c#" }
How to get openlayers 3 zoom control to show up on right side? By default the openlayers 3 zoom controls are on the top left. How can I move it to the top right? The API appears to return a broken link when going into options.
Using casading style sheets. .ol-zoom { right: 8px }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 12, "tags": "openlayers 3" }
How to retrieve the JSON object key which having numbered name I'm trying to pass a number of JSON objects from my server which have names appended with a number to differentiate each other. I am getting a problem while retrieving these objects. It is unable to append a number with its common name. Objects look like this: {"shareInfo":[{"uname1":"abc","uname2":"sds","uname3":"uuh",.....}]} I tried appending an `integer` variable to it. data.shareInfo[i].uname+''+i; But it is not reading the variable together. I mean it is not taking it like `uname0,uname1,...` Please anyone tell me how to append the number to retrieve the data, thanks.
`data.shareInfo[i]["uname" + i]` should work. It's worth noting that your example data only contains one array element in data.shareInfo, so what you might actually need is: `data.shareInfo[0]["uname" + i]` But I can't tell which would be correct from your test data.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, jquery, json" }