qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
7,053,355
So here is my problem: I have an AppDelegate with a navigationController: ``` [self.window addSubview:navigationController.view]; ``` In there i put an presendModalViewController: ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[self navigationController] presentModalViewController:passwordViewController animated:YES]; ``` } I want an PasswordView which takes the Password and tells the UIView in the NavigationController that he can begin his work with catching information from the internet, with a nice MBProgressHUD Loading View. I tried to build up an Delegate but it does´t work because the instance of my UIView is build up in the Navigation controller. I there a way to tell my UIView which is in my NavigationController that Password was given and back that the Password was right und say back with: ``` [self.parentViewController dismissModalViewControllerAnimated:YES]; ``` to remove this View? There is an App named iOutbank which has what I want to assume...
2011/08/13
[ "https://Stackoverflow.com/questions/7053355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/719261/" ]
You can use [`all()`](https://docs.python.org/3/library/functions.html#all) with a [generator expression](https://docs.python.org/3/reference/expressions.html#generator-expressions): ``` >>> all(x in dct for x in ('foo', 'bar', 'qux')) False >>> all(x in dct for x in ('foo', 'bar', 'baz')) True >>> ``` It saves you a whopping 2 characters (but will save you a lot more if you have a longer list to check).
``` all(x in dct for x in ('foo','bar','baz')) ```
315,004
I am in the process of getting rid of `gnome-keyring` as an SSH agent. Things that I have done ======================= * Searched the internet for hours. * Changed stuff and restarted, often. * Finally just `rm`-ed all the autostart stuff related to SSH. That last thing magically worked as there is **no more** the socket for the agent there: ``` /run/user/[uid]/keyring/ssh ``` Problem ======= The remaining problem is that **in spite** of my obtaining the wonderful aforementioned result, **something** in `gnome-keyring` still insists on setting `SSH_AUTH_SOCK` to the **now** *non-existing* socket above. It's like zombies, these things never die. Question ======== What is setting that variable and where is it done? Pitfalls ======== * I am **not** asking how I can reset that variable to another value. * I am **not** asking how I can set that value system-wide or in a shell configuration file. * I am **not** asking for some init-script voodoo incantations to freeze, set, reset, unset or replace anything. * I am **not** asking for advice on how to uninstall the thing: I still need it for my passwords and it seems to be the most integrated and polished password manager in Gnome. I want that thing disabled as it should be.
2016/10/07
[ "https://unix.stackexchange.com/questions/315004", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/192872/" ]
*(OP's environment is not known, so the paths given here are those found on my Ubuntu machine)* Where does gnome-keyring set SSH\_AUTH\_SOCK? --------------------------------------------- To answer the main question in title, SSH\_AUTH\_SOCK is set by gnome-keyring in `/usr/share/upstart/sessions/gnome-keyring-ssh.conf` with the following command: ``` initctl set-env --global SSH_AUTH_SOCK=$SSH_AUTH_SOCK ``` Quoting the `initctl` manual: > > `initctl set-env VARIABLE[=VALUE]` > > > Adds or updates a variable in a job environment table. Variables set in this way will apply to all the subsequently-starting processes for a job. > > > `-g`, `--global` > > > Operate on the global job environment table and all existing running job environment tables. > > > Where does SSH\_AUTH\_SOCK come from in the first place? -------------------------------------------------------- The `initctl` command above is conditioned to the fact that the environment variable SSH\_AUTH\_SOCK already exists. So, is it a chicken and egg situation? What sets it? SSH\_AUTH\_SOCK is initially set by the original ssh-agent which is started at the very beginning of the X session. Quoting the manual: > > A UNIX-domain socket is created and the name of this socket is stored in the `SSH_AUTH_SOCK` environment variable. The socket is made accessible only to the current user. > > > BUT, what the gnome-keyring's ssh component does is to substitute itself to the existing ssh-agent. Therefore it overwrites SSH\_AUTH\_SOCK with its own socket `/run/user/.../keyring-.../ssh` so that applications talk to it, and not to ssh-agent. How to disable it ----------------- Now, let's answer the last sentence "I want that thing disabled". What the OP wants is to disable the overwriting of SSH\_AUTH\_SOCK by the ssh component in gnome-keyring. They want to get back the "true" SSH\_AUTH\_SOCK variable initially set by ssh-agent. The ssh component is started by the same startup script mentioned above (`/usr/share/upstart/sessions/gnome-keyring-ssh.conf`) but at one condition: the string `X-GNOME-Autostart-enabled=false` must not be found in either of these files: * (system-wide conf) `/etc/xdg/autostart/gnome-keyring-ssh.desktop` * (user conf) `~/.config/autostart/gnome-keyring-ssh.desktop` Therefore, if you want to disable it, all you have to do is add a line `X-GNOME-Autostart-enabled=false` to one of these files, preferably the one in your HOME directory.
<https://wiki.archlinux.org/index.php/GNOME/Keyring#Disable_keyring_daemon_components> > > If you wish to run an alternative SSH agent (e.g. ssh-agent or gpg-agent, you need to disable the ssh component of GNOME Keyring. To do so in an account-local way: > > > > ``` > mkdir ~/.config/autostart > cp /etc/xdg/autostart/gnome-keyring-ssh.desktop ~/.config/autostart/ && > echo 'Hidden=true' >> ~/.config/autostart/gnome-keyring-ssh.desktop > > ``` > > Then log out. > > > Lightly editted, removing apparently useless use of `printf`
237
I always feel that I should buy a Canon lens for my Canon camera, and Sigma would just be a cheap knock-off. Is that the case?
2010/07/15
[ "https://photo.stackexchange.com/questions/237", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/93/" ]
My wife and I own three Sigma lenses: the "bigma" (50-500mm), my 17-70mm f/2.8-4, and her 30mm f/1.4 prime. We absolutely love them, for their respective strengths: * Noone touches the Bigma for range. Yes, it's soft. Yes, it's unbelievably big and heavy. But it's a disturbingly versatile lens. * The 30mm is [incredibly sharp](http://www.flickr.com/photos/erica_marshall/sets/72157603817722933/), and f/1.4 is something you just have to use to understand why you want it. * My 17-70mm is a great compromise lens; it's almost always attached to my camera, and I switch off when I have a particular need. And, quite frankly, it's tough to touch Sigma on price. As with all things, they have their good lenses and their bad lenses (just like Canon); be sure to check sites like [photozone.de](http://www.photozone.de/) for quality tests before plunking down your money.
My experience is that some of the primes are on a par with their Canon equivalents - the 24mm f/1.8 and the 180mm macro are really good. The AF is always much slower. I find the colour cast different to the Canon L lenses - which are consistent with each other in my experience - but haven't found this to be a problem.
352,697
Every depiction I have seen shows the Eclipse path of totality travel Eastward from Oregon. Why Doesn't the path travel Westward from South Carolina as the Earth rotates Eastward? Shouldn't the Totality follow the Path of the Sun?
2017/08/19
[ "https://physics.stackexchange.com/questions/352697", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/165188/" ]
The answer posted by Sammy Gerbil is quite wrong. The passage of the eclipse from west to east has nothing to do with the sun overtaking the moon in the sky. Sammy does correctly point out that, as viewed from above, the moon is circling the earth in a counterclockwise direction. And that means it is travelling from west to east. It is in fact travelling quite fast: about 2200 mph in fact (relative to a fixed earth), as you can verify by some simple computations. And that is also how fast its shadow is traveling. The rotation of the earth however, being in the same direction, tends to counteract the motion of the shadow, by around 800 mph at the latitude of the eclipse. So the effective speed of the shadow across North America was close to 1400 mph, from west to east. There is a very good animation of this on the Wikipedia website from which you can see at once that I have calculated this correctly: <https://en.wikipedia.org/wiki/Solar_eclipse_of_August_21,_2017> EDIT: interesting that if you could rev the earth up to reduce the day to 11 hours, then the totality of an eclipse could last almost all day.
As Earth orbits the Sun, the Sun appears to move to the east against the background stars by about 1°/day --- completing its apparent route around the ecliptic in about 365 days. As the Moon orbits the Earth, the Moon appears to move to the east against the background stars by about 12°/day --- completing its apparent route around the sky in about 30 days. During a solar eclipse, the Moon "overtakes" the Sun against the background stars, traveling from the Sun's west side to its east side over the course of roughly 1/12 day = 2 hours. When you are observing totality, people to your west have seen totality already, but people to your east have not seen totality yet. Earth's rotation, which causes the Sun, the Moon, and all the stars to move from east to west at a rate of approximately 360°/day, is a distraction. Think instead about the apparent motion of the Sun and Moon compared to the distant background stars.
1,829,013
I'm having trouble understanding what the purpose of the `virtual` keyword in C++. I know C and Java very well but I'm new to C++ From wikipedia > > In object-oriented programming, a > virtual function or virtual method is > a function or method whose behavior > can be overridden within an inheriting > class by a function with the same > signature. > > > However I can override a method as seen below without using the `virtual` keyword ``` #include <iostream> using namespace std; class A { public: int a(); }; int A::a() { return 1; } class B : A { public: int a(); }; int B::a() { return 2; } int main() { B b; cout << b.a() << endl; return 0; } //output: 2 ``` As you can see below, the function A::a is successfully overridden with B::a without requiring `virtual` Compounding my confusion is this statement about virtual destructors, also from wikipedia > > as illustrated in the following example, > it is important for a C++ base class > to have a virtual destructor to ensure > that the destructor from the most > derived class will always be called. > > > So `virtual` also tells the compiler to call up the parent's destructors? This seems to be very different from my original understanding of `virtual` as "make the function overridable"
2009/12/01
[ "https://Stackoverflow.com/questions/1829013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357024/" ]
> > As you can see below, the function A::a is successfully overridden with B::a without requiring virtual > > > It may, or it may not work. In your example it works, but it's because you create and use an `B` object directly, and not through pointer to `A`. See [C++ FAQ Lite, 20.3](http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.3). > > So virtual also tells the compiler to call up the parent's destructors? > > > A virtual destructor is needed if you delete a pointer of base class pointing to an object of derived class, and expect both base and derived destructors to run. See [C++ FAQ Lite, 20.7](http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7).
Say you instantiated B but held it as an instance of an A: ``` A *a = new B(); ``` and called function a() whose implementation of a() will be called? If a() isn't virtual A's will be called. If a() was virtual the instantiated sub class version of a() would be called regardless of how you're holding it. If B's constructor allocated tons of memory for arrays or opened files, calling ``` delete a; ``` would ensure B's destructor was called regardless as to how it was being held, be it by a base class or interface or whatever. Good question by the way.
31,709,075
I'm doing a conditional search of part of a dataset that has multiple NA values within each row. Something like this (a preview).. ``` time1 time2 time3 time4 slice1 slice2 slice3 slice4 pt1 1 3 NA NA NA 1 3 5 pt2 NA 1 3 5 5 2 2 4 ``` I want to do some conditional searching which applies a condition (comparing whether one column within a row is larger than another) for each row. I want to find all the rows (pt's) where a variable column (e.g. time1) is smaller than the corresponding column (e.g. slice 1). ``` all.smaller<-subset(patientdata, time1>slice1 & time2>slice2 & time3>slice3 & time4>slice4, na.rm=TRUE, select=c(1)) ``` When I use this code (on a larger expanded table of this format), it only returns the rows without any NAs, where all the values are added in. This makes sense given the use of '&'. My question is: Is there a way to find which rows fit my conditional search that ignores the NA's but only returns the rows where in all the column variables where values are provided, it searches whether time1>slice1, time2>slice2 etc.? Any help is appreciated. Thanks.
2015/07/29
[ "https://Stackoverflow.com/questions/31709075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5065420/" ]
From [here](http://tldp.org/LDP/abs/html/x9644.html) - > > Within a script, running a command in the background with an ampersand (&) > may cause the script to hang until ENTER is hit. This seems to occur with > commands that write to stdout. > > > You should try redirecting your output to some file (or null if you do not need it), maybe `/dev/null` , if you really do not need the output. ``` nohup /path/to/program > /dev/null & ```
Why don't you trying using a separate thread? Wrap up your process into something like ``` def run(my_arg): my_process(my_arg) thread = Thread(target = run, args = (my_arg, )) thread.start() ``` Checkout join and lock for more control over the thread execution. <https://docs.python.org/2/library/threading.html>
13,913,923
As output I have for `Range("H" & temp).Cells` : ``` 234 0 (Empty) 2 ``` I want to convert it into `long` or `int`, because it's a text value. So I did ``` Range("H" & temp).Cells = CInt(Range("H" & temp).Cells) ``` It works perfectly for 234, 0 and 2 but when the cell is empty it shows me error. What should I do? I want the empty cell to be taken as 0, of course using VBA macro.
2012/12/17
[ "https://Stackoverflow.com/questions/13913923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1847877/" ]
If you need to do this in formula, you can use this: IF(IFERROR(VALUE(A1)); 0; A1)
``` Sub t() Dim colNum As Long colNum = Range("H1").Column 'please coustomize which column For i = 1 To 4 'Please customize the row range Cells(i, colNum).Value = CLng(Cells(i, colNum).Value) 'blank --> 0 Cells(i, colNum).NumberFormat = "0.00" 'also changes the numberFormat Next i End Sub ```
758,158
I am trying to use $f(x)=x^3$ as a counterexample to the following statement. If $f(x)$ is strictly increasing over $[a,b]$ then for any $x\in (a,b), f'(x)>0$. But how can I show that $f(x)=x^3$ is strictly increasing?
2014/04/17
[ "https://math.stackexchange.com/questions/758158", "https://math.stackexchange.com", "https://math.stackexchange.com/users/133993/" ]
You want to show that the function $f(x) = x^3$ is strictly increasing on $\mathbb{R}$. Maybe you can just use the definition. That is, let $a < b$. Assume that $0<a$ (you can do the other cases I am sure). Let $h = b - a < 0$. You want to show that $f(a) < f(b)$. So $$\begin{align} f(a) = a^3 &= (b - h)^3\\ &= b^3 - 3b^2h +3 bh^2 - h^3 \\ &<b^3 \\ &= f(b). \end{align} $$ This is clear since $h > 0$, so $-3b^2h + 3bh^2 = -3hb(b - h) = -3hba < 0$. --- All that said, you could, of course just use $f(x) = x$ as a counter example.
Here is an intuitive proof that could be made rigorous using Lebesgue measure. Start with $x>0$. Place a cube with edge length $x$ so that it has three faces on the coordinate planes in three-dimensional space and two corners at $(0,0,0)$ and at $(x,x,x)$. Then $f(x)=x^3$ is the volume of the cube. Strict monotonicity of $f$ is a consequence of the volume being strictly bigger for a strictly bigger cube. To incorporate negative values of $x$, argue with the fact that $f$ is odd.
324,042
I would like to print a number of 256-bit long hashes in hexadecimal (so 64 characters, I'm skipping the usual "0x" without white spaces or punctuation) in line and using a monospaced font. So, I first went for \texttt, which does not hyphenate my strings. I saw some questions with interesting answers, such as [How to get long \texttt sections to break](https://tex.stackexchange.com/questions/299/how-to-get-long-texttt-sections-to-break) and [Automatic linebreak on specific character](https://tex.stackexchange.com/questions/66583/automatic-linebreak-on-specific-character) but those both define linebreak for a specific character and I would find ugly to use their trick for each of the 16 characters of hexadecimal without some sort of natural loop. Is there a way to define a command such that the text inside will be typed as texttt but break on any character or, even better, a standard way to typeset long hexadecimal strings that takes this issue into account? MWE: ``` \documentclass{article} \newcommand{\hash}[1]{\texttt{#1}}%In a perfect world, this would be changed to allow linebreaks anywhere in #1 \begin{document} SHA-256 is a hash function with a 256-bit long output: \hash{d270f747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15} \end{document} ```
2016/08/09
[ "https://tex.stackexchange.com/questions/324042", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/80719/" ]
There is already a package for this: ``` \documentclass{article} \usepackage{seqsplit} \newcommand{\hash}[1]{{\ttfamily\seqsplit{#1}}} \begin{document} SHA-256 is a hash function with a 256-bit long output: \hash{d270f747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/vNxle.png)](https://i.stack.imgur.com/vNxle.png)
Solution Making TeX Treat Characters like Words =============================================== This works, but has the limitation that denoted characters do not work. e.g. using hexidecimal (`\char"02C6`) or octal notation. ``` \documentclass{article} \def\hash#1{\xscan#1\relax}% calls xscan which looks ahead one token, #1 \def\xscan{\afterassignment\xxscan\let\token= }% assign single token to \token and call \xxscan \def\xxscan{% \ttfamily% set font style \ifx\token\relax\ttfamily\else%test for end-of-line or end of group and switch to ttfamily \ifcat\token\space% \token% token is catcode 10 \spaceskip=.5em% remove glue from space for fixed-width space \xspaceskip=.5em% remove glue from space for fixed-width space \else% \token\hskip 0pt plus 1sp minus 1sp % add glue to any non-catcode 10 (space) \fi \expandafter\xscan% feed next token to \xscan, which is effectively a recursive call \fi} \begin{document} SHA-256 is a hash function with a 256-bit long output: \hash{d270f747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15} %SHA-256 is a hash function with a 256-bit long output: \hash{d270f\char"02C6\relax747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15}% \char" denoted char syntax not supported \end{document} ``` Related: [How can I make LaTeX to recognize spaces in my macro (catcode 10)?](https://tex.stackexchange.com/q/316329/13552) Solution Using Intercharacter Tokens ==================================== ``` \XeTeXinterchartokenstate=1 % turn them on \XeTeXinterchartoks 0 0 = {\penalty0\relax}#1} % use insert token ``` This is my preferred solution if using TeX Live 2017 and using `xelatex`. This has the advantage that it supports the original capabilities of `\texttt`-it should-like denoted characters (see comments under David Carlisle's answer). ``` \documentclass{article} \newcommand{\hash}[1]{\texttt{\XeTeXinterchartokenstate=1\XeTeXinterchartoks 0 0 = {\penalty0\relax}#1}}%In a perfect world, this would be changed to allow linebreaks anywhere in #1 \begin{document} SHA-256 is a hash function with a 256-bit long output: \hash{d270f747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15} SHA-256 is a hash function with a 256-bit long output: `\hash{d270f\char"02C6\relax747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15}` \end{document} ```
39,390,445
`New` operator is often confusing for me, and using it can lead to memory leaks if I forget to use `delete`. Every time I have to allocate an array of objects without knowing its length at compile time, I just use `std::vector`. What is the point of using `new`? Also, why would I need to use `new` operator to allocate space for just one single instance of an object?
2016/09/08
[ "https://Stackoverflow.com/questions/39390445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4746978/" ]
For normal use of dynamic arrays in most code, use `std::vector`. This is clearly the default and prevents many issues. However, when you know what you are doing and you want some performance gain in special cases, you might want to see whether `new` or `malloc` could help you. Preferrably, you make a new specialized container, so people can keep on using it as a normal container. Or even better you could try making an allocator for an existing container. As you probably noticed, this takes some time and probably needs debugging, so unless there's an actual need, stick with the standard containers and for dynamic arrays, this is `std::vector`.
I think your question is related to two things: 1. The usage of new operator: I just want to make one example. Managing memory with "new" and "delete" gives the programmer control of the program. Some program languages have Garbage Collection, but we don't know when GC will work, which causes uncertainty. However, with systems requiring low latency, this uncertainty will cause trouble. 2. With "vector", we don't have to create dynamic arrays with new which is good and causes less bugs. Actually it is good to use vector instead of dynamic arrays. But I don't think the usage of vector is conflict with the use of new. It onlye creates a situation you can avoid use new. 3. Please check the concept of RAII. It's useful for learning C++.
15,398,499
After users registration I sent an email to activate the account, but user can log in even the account have not been activated. How can I validate if users account in activated? ``` if (Auth::attempt(array('email' => $email, 'password' => $password))) { // Success login } else { // Login fail } ```
2013/03/13
[ "https://Stackoverflow.com/questions/15398499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/833394/" ]
``` if (Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1))) { // The user is active, not suspended, and exists. } ``` [Authenticating Users](http://laravel.com/docs/security#authenticating-users) In Laravel 5.3 you might want to overwrite `Illuminate\Foundation\Auth\AuthenticatesUsers`'s `credentials` method in your App\Http\Controllers\Auth\LoginController to add `'active' => 1`.
Send a link to the users email with a secret key, the key has to be unique, such as a hash of their email address with your application secret key as a salt. Have an endpoint that this link points to which checks that the link is valid using the procedure I mentioned above. If the key you generate matches the one in the email link then you can validate their account and redirect them to the login page.
108,156
I am maintaining a legacy cygwin (with GNU tar v1.21) system and a legacy Solaris 9 system. The configuration of the Solaris 9 system is fixed and cannot be upgraded (i.e. I can't install gnu tar for Solaris). I am trying to create a tarball on the cygwin system that can extracted on the Solaris 9 system but unfortunately the directory structure (which is also fixed and cannot be renamed) plus file names exceed 100 characters and I've run into the [Great Tar Wars](http://www.gnu.org/software/tar/manual/html_chapter/Formats.html#SEC138) of the last millennium. There is a large (conservative) userbase on the Solaris system so a solution that uses Solaris tar is preferred. Here are the errors I'm experiencing. Creating the tar on cygwin: ``` $ tar -cf dir.tar dir ``` or ``` $ tar -c --posix -f dir.tar dir ``` Gives the following on Solaris: ``` $ tar -xif dir.tar tar: directory checksum errors ``` And the file names in dir are truncated. (i.e. ignoring checksum errors doesn't help) How do I create a tarball with long pathnames using GNU tar that can be extracted by Solaris tar? Edit #2: Unable to use Schily Tar (star) ---------------------------------------- It appears that Joerg Schilling has been able to emulate the Solaris 7/8/9 tar format and provides a `suntar` option to create a Solaris tarball using [star](http://linux.die.net/man/1/star). Unfortunately `star` is not available on cygwin. :( Edit #1: Using --format=posix gives errors when extracting ---------------------------------------------------------- Errors when extracting --format=posix gnu tarballs using pax on Solaris 9 On cygwin: ``` $ ls example/this_is_a_path_name_greater_than_one_hundred_characters/when_combined_with_this_file_name_which_is_also_rather_long.txt | wc -m 128 $ tar -c --format=posix -f example.tar example ``` On Solaris: ``` $ pax -r -f example.tar pax: ./PaxHeaders.4440/example : Unknown filetype pax: example/PaxHeaders.4440/this_is_a_path_name_greater_than_one_hundred_characters : Unknown filetype pax: example/this_is_a_path_name_greater_than_one_hundred_characters/PaxHeaders.4440/when_combined_with_t : Unknown filetype ``` Similar errors are given when extracting using Solaris tar.
2014/01/07
[ "https://unix.stackexchange.com/questions/108156", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/56096/" ]
Solaris tar and GNU tar have different interpretations of posix but both support ustar, which in turn [supports long(ish) pathnames](http://www.gnu.org/software/tar/manual/html_node/Formats.html#SEC132 "supports long pathnames"). Using GNU tar on cygwin: ``` $ tar -c --format=ustar -f dir.tar dir ``` This creates a tarball which is happily extracted on Solaris 9 without errors. Perhaps not a universal solution but one that fits the constrained solution space. Looks like the 80s were useful after all!
[GNU tar formats](http://www.gnu.org/software/tar/manual/html_section/Formats.html#SEC132) suggests `tar -c --format=posix` or `tar -c --format=pax` is the only way to create a portable tar file containing path names longer than 255 characters. The [Solaris tar man page](http://docs.oracle.com/cd/E19683-01/816-0210/6m6nb7mmp/index.html) doesn't mention supporting that format, but the [Solaris pax man page](http://docs.oracle.com/cd/E19683-01/816-0210/6m6nb7mgs/index.html) does. So first, I'd try to create the archive on your Cygwin (or Linux) system using `tar -c --format=posix -f dir.tar dir`, and to extract it on your Solaris system using `pax -r -x pax -f dir.tar`, or likely just `pax -r -f dir.tar`. Alternatively, if you have `cpio` installed on both systems, it seems like the `crc` format supports 1,023 character paths on both systems. That would look something like `find -L dir | cpio -o -H crc > dir.cpio` to create and `cpio -i -d < dir.cpio` to extract it. Finally, you could try adding the `-i` flag to ignore directory checksum errors when extracting on Solaris, e.g. `tar -x -i -f dir.tar`. [Checksumming problems](http://www.gnu.org/software/tar/manual/html_section/Portability.html#SEC147) says this can be needed if any of the file names in the tar archive are non-ASCII. Other reading: * [Making tar archives more portable](http://www.gnu.org/software/tar/manual/html_section/Portability.html) * [Comparison of tar and cpio](http://www.gnu.org/software/tar/manual/html_section/cpio.html)
944
[*Ars Goetia*](https://en.wikipedia.org/wiki/Lesser_Key_of_Solomon#Ars_Goetia) is a well-known book about demonology written in Mediaeval Latin. I'm having trouble analyzing the grammatical structure of the title. *Ars* is a feminine noun in the singular nominative form. *Goetia* looks like it is feminine and in the singular nominative form. However, I'm not sure how it relates grammatically to *Ars.* I looked up the entry for [*ars*](http://www.perseus.tufts.edu/hopper/text?doc=Perseus%3Atext%3A1999.04.0059%3Aentry%3Dars) in Lewis and Short, and it seems to say that it is generally modified by an adjective (e.g. *ars gymnastica*) or a noun in the genitive case (e.g. *ars disserendi*). *Goetia* is obviously not a genitive form, but I also wouldn't think it would be used as an adjective: it's a loanword from the Greek noun *γοητεια* (I would expect the corresponding adjective to be something like *Goeticus*/*-um*/*-a*). To me, it seems like it is an appositive noun. Am I right? If so, are there examples of this construction being used with *ars* in Classical Latin? And are there any differences in meaning, or other reasons to use the title *Ars Goetia* instead of *Ars Goetiae* or *Ars Goetica*? One reason I suspect the author intentionally used an appositive noun after *ars* here is because a few of the other books in the Lesser Key of Solomon also seem to be titled this way, such as "Ars Theurgia-Goetia" and "Ars Almadel." But there is also a book that seems to have the structure with an adjective, the "Ars Paulina."
2016/05/26
[ "https://latin.stackexchange.com/questions/944", "https://latin.stackexchange.com", "https://latin.stackexchange.com/users/9/" ]
I'd say *goetia* is clearly a noun, as you say. Some points to consider: 1. Nouns are sometimes used as adjectives: *victor exercitus* -- the victorious army (A&G, § 321 c); 2. There was some confusion as to what this word actually referred to. See, e.g., Du Cange's entry: > > Getia, *Maleficiorum doctrina*. Glossae antiq. Forte pro γοητεία, [vel forte a Geta mago celeberrimo, quem diu in AEgypto commoratum fuisse narrat Strabo lib. 7. Papias editus et MS. habet: *Gethia, maleficiorum doctrina, Gheticus, Thracus.* Vide *Gitta*.] {The entry on *gitta* refers to *praestigiae per manuum invocationem, maleficia*.} > > > And then there's Augustine, who contrasts it with theurgy (both under 'magic') in [*Civ.* 10.9](http://www.thelatinlibrary.com/augustine/civ10.shtml) (or, as in Jensen's [1475 edition](https://archive.org/stream/augustinidecivitatedei00jensuoft#page/n233/mode/2up)): > > Fiebant autem simplici fide atque fiducia pietatis, non incantationibus et carminibus nefariae curiositatis arte compositis, quam uel **magian** uel detestabiliore nomine **goetian** uel honorabiliore **theurgian** uocant, qui quasi conantur ista discernere et inlicitis artibus deditos alios damnabiles, quos et maleficos uulgus appellat (hos enim ad **goetian** pertinere dicunt), alios autem laudabiles uideri uolunt, quibus theurgian deputant; cum sint utrique ritibus fallacibus daemonum obstricti sub nominibus angelorum. > > > 3. Medieval authors sometimes like to give a 'Greek' flavour to their titles, especially when they are writing something esoteric. But even 'conventional' authors sometimes couldn't resist Anselm's *Monologion* and *Prosologion* come to mind, for example.
As you say, γοητεία “sorcery, witchcraft” is a noun. Apparently some mediaeval Latinist mistook it for the feminine singular nominative of an adjective. Classical Latin does have words like “musica” as a synonym for “ars musica”, so it could be that someone thought you could equate “goetia” with “ars goetia”, but this could only work if goetia were an adjective. Which it is not.
280,767
I found something for videos, which looks like this. ``` ffmpeg -i * -c:v libx264 -crf 22 -map 0 -segment_time 1 -g 1 -sc_threshold 0 -force_key_frames "expr:gte(t,n_forced*9)" -f segment output%03d.mp4 ``` I tried using that for an audio file, but only the first audio file contained actual audio, the others were silent, other than that it was good, it made a new audio file for every second. Does anyone know what to modify to make this work with audio files, or another command that can do the same?
2016/05/03
[ "https://unix.stackexchange.com/questions/280767", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/79979/" ]
To split a big audio file into a set of tracks with varying lengths, you can use the following command: ``` # -to is the end time of the sub-file ffmpeg -i BIG_FILE -acodec copy -ss START_TIME -to END_TIME LITTLE_FILE ``` For example, I broke up a single .opus file of the Inception Original Soundtrack into sub-files using this text file containing start, end, name: ``` 00:00:00 00:01:11 01_half_remembered_dream 00:01:11 00:03:07 02_we_built_our_own_world 00:03:07 00:05:31 03_dream_is_collapsing 00:05:31 00:09:14 04_radical_notion 00:09:14 00:16:58 05_old_souls 00:16:58 00:19:22 06 00:19:22 00:24:16 07_mombasa 00:24:16 00:26:44 08_one_simple_idea 00:26:44 00:31:49 09_dream_within_a_dream 00:31:49 00:41:19 10_waiting_for_a_train 00:41:19 00:44:44 11_paradox 00:44:44 00:49:20 12_time ``` I wrote this short `awk` program to read the text file and create `ffmpeg` commands from each line: ```bash { # make ffmpeg command string using sprintf cmd = sprintf("ffmpeg -i inception_ost.opus -acodec copy -ss %s -to %s %s.opus", $1, $2, $3) # execute ffmpeg command with awk's system function system(cmd) } ``` Here is a more detailed `python` version of the program called `split.py`, where now both the original track file *and* the text file specifying sub-tracks are read from the command line: ```py import sys import subprocess def main(): """split a music track into specified sub-tracks by calling ffmpeg from the shell""" # check command line for original file and track list file if len(sys.argv) != 3: print("usage: split <original_track> <track_list>") exit(1) # record command line args original_track = sys.argv[1] track_list = sys.argv[2] # create a template of the ffmpeg call in advance cmd_string = "ffmpeg -i {tr} -acodec copy -ss {st} -to {en} {nm}.opus" # read each line of the track list and split into start, end, name with open(track_list, "r") as f: for line in f: # skip comment and empty lines if line.startswith("#") or len(line) <= 1: continue # create command string for a given track start, end, name = line.strip().split() command = cmd_string.format(tr=original_track, st=start, en=end, nm=name) # use subprocess to execute the command in the shell subprocess.call(command, shell=True) return None if __name__ == "__main__": main() ``` You can easily build up more and more complicated `ffmpeg` calls by modifying the command template and/or adding more fields to each line of the track\_list file.
Great python script by @isosceleswheel, I've just used it, but I made some modification of my own, so you can name the tracks with spaces. Line 18 -> cmd\_string = 'ffmpeg -i {tr} -acodec copy -ss {st} -to {en} "{nm}".opus' "{nm}", quotes, to take entire string as literal. Line 28 -> start, end, name = line.strip().split(" ", 2) It will consider only the first 2 spaces as string separation and take the rest as one entire string (the third). i.e. 00:00:00(start), 00:01:11(end), 01 Half Remembered Dream(name) With these modifications, you could name rename the music names as such: 00:00:00 00:01:11 01 Half Remembered Dream 00:01:11 00:03:07 02 We Built Our Own World 00:03:07 00:05:31 03 Dream Is Collapsing
45,836,075
How to change or replace text under div, tag, row with JS. Here is the code: ``` $(document).ready(function() { $("div .row .col-sm-4").each(function() { if ($(this).text() == "Registrant ID:") { $(this).text().replace("Registrant Number:"); } }); }); ``` HTML Code Here : ``` <div class="row"> <div class="col-sm-4">Registrant ID:</div> </div> ``` I am using javascript here, it seems to have no effect.
2017/08/23
[ "https://Stackoverflow.com/questions/45836075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8384919/" ]
Try like this. ```js var data = { "questions": { "0": { "0": "17", "1": "12" }, "1": { "0": "22", "1": "34" }, "2": { "0": "52", "1": "61" } } } console.log(data.questions["0"]); console.log(data.questions["0"]["0"]); console.log(data.questions["0"]["1"]); ```
You get the result without `Object.keys`. ```js var data = { questions: { 0: { 0: "17", 1: "12" }, 1: { 0: "22", 1: "34" }, 2: { 0: "52", 1: "61" } } }; console.log(data.questions[0]); // { 0: "17", 1: "12" } console.log(data.questions[0][0]); // 17 console.log(data.questions[0][1]); // 12 ``` For searching a value's path of keys, you could use an iterative and recursive approach by checking all keys and objects. ```js function findValue(object, value) { var p; Object.keys(object).some(function (k) { var t; if (object[k] === value) { p = [k]; return true; } if (object[k] && typeof object[k] === 'object' && (t = findValue(object[k], value))) { p = [k].concat(t); return true; } }); return p; } var data = { questions: { 0: { 0: "17", 1: "12" }, 1: { 0: "22", 1: "34" }, 2: { 0: "52", 1: "61" } } }; console.log(findValue(data, '17')); console.log(findValue(data, '34')); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
22,638,468
I have this code ``` if (ScalarReturned is DBNull) { xCount = 0; } else { xCount = (Int32)ScalarReturned; } ``` which works great but was just wanting to convert to an inline IF -- I tried below but get multiple compile errors. Can someone assist with this? ``` if (ScalarReturned is DBNull) ? xCount = 0 : xCount = (Int32)ScalarReturned; ```
2014/03/25
[ "https://Stackoverflow.com/questions/22638468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2954053/" ]
Do this: ``` xCount = ScalarReturned is DBNull || ScalarReturned == null ? 0 : (Int32)ScalarReturned; ``` How it works: Ternary operator acts a bit like function. Only thing here is, you don't need `return` keyword. In plain English: Assign 0 to xCount if it satisfies first condition `ScalarReturned is DBNull || ScalarReturned`, else assign what is after `:`
The ternary operator works as follows: ``` condition ? true result : false result xCount = (Int32)((ScalarReturned is DBNull || ScalarReturned == null) ? 0 : ScalarReturned); ```
17,417,256
I want to display div on page load e.g."campaign-alert", but I am not able to do this . This is sample code : ``` <div id="popup"> <div id="campaign-alert" style="display:none;"> . . . </div> </div> ``` I have tried this way as well : ``` document.getElementById('campaign-alert').style.display=""; document.getElementById('campaign-alert').style.display="block"; ``` Can anybody help me in this ?
2013/07/02
[ "https://Stackoverflow.com/questions/17417256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2527554/" ]
Try this. It will help you. Using Jquery ``` $(document).ready(function () { $("#campaign-alert").show(); }); ``` Using JavaScript ``` window.onload = function () { document.getElementById("campaign-alert").style.display = "block"; }; ```
You shaould try it using onload() **HTML:** ``` <body onload="load()"> <div id="popup"> <div id="campaign-alert" style="display:none;"> . . . </div> </div> </body> ``` **Javascript:** ``` function load(){ document.getElementById('campaign-alert').style.display="block"; } ```
109,810
I was wondering what and why you would choose to be able to make a database that can support no more than 100 users with no more than 10 using it at once with a Visual Studio 2008 C# Windows Form front end to access it by. I have to access the database over a network connection, not just on the local machine. I also need to define where the database is found at run-time in the code as opposed to the "Data Source" view in Visual Studio. If my question needs reframing or is not understood, let me know and I will adjust. Part of my problem is I am not sure even how to ask the right question, much less what the answer is.
2008/09/20
[ "https://Stackoverflow.com/questions/109810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19802/" ]
I would probably go with Sql Server Express, it's free and works well with .NET. Assuming your schema is not changing at runtime you can probably still use the design time data source features in Visual Studio. The connection information is stored in the app.config file which you can update after the app is deployed to point to a different database. You can also develop a class that gets the connection info from somewhere else as well and just use that when you need to open a database connection.
I'm not sure I totally get what you are asking, Matt, but I can tell you that I developed a series of apps written with VS 2008 and we used a MySQL DB for it. While I'm definitely not a DB guru at this point, I've not had many issues with using MySQL. Perhaps if you rephrase your question, we can provide better answers.
55,207,940
``` import pandas as pd df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0') d= df.loc[df.isnull().sum(axis=1)>5] d.dropna(axis=0,inplace=True) print(round(100*(1-df.count()/len(df)),2)) ``` i m getting output as ``` Ord_id 0.00 Prod_id 0.00 Ship_id 0.00 Cust_id 0.00 Sales 0.24 Discount 0.65 Order_Quantity 0.65 Profit 0.65 Shipping_Cost 0.65 Product_Base_Margin 1.30 dtype: float64 ``` but the output is ``` Ord_id 0.00 Prod_id 0.00 Ship_id 0.00 Cust_id 0.00 Sales 0.00 Discount 0.42 Order_Quantity 0.42 Profit 0.42 Shipping_Cost 0.42 Product_Base_Margin 1.06 dtype: float64 ```
2019/03/17
[ "https://Stackoverflow.com/questions/55207940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11143510/" ]
Try this way: ``` df.drop(df[df.isnull().sum(axis=1)>5].index,axis=0,inplace=True) print(round(100*(1-df.count()/len(df)),2)) ```
This works: ``` import pandas as pd df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0') df = df[df.isnull().sum(axis=1)<5] print(df.isnull().sum()) ```
42,972,575
I am using two `TextView`s to show contact name and company name, one below another with the use of DataBinding technique. Company name is optional field, so it can disappear. **1.** I have been using such method in **item\_contact.xml** : ``` <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <import type="android.view.View"/> <variable name="info" type="com.myproject.objects.InfoObject"/> </data> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="70dp"> <TextView android:id="@+id/item_contact_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="32dp" android:layout_marginStart="32dp" android:layout_centerVertical="true" android:text='@{info.getAccountName() == null ? info.getName() : String.format(@string/item_meeting_time_period, info.getName(), info.getAccountName() )}' android:textSize="16sp" android:textColor="@color/black" /> <include layout="@layout/bottom_line_divider" /> </RelativeLayout> </layout> ``` **strings.xml**: ``` <string name="item_meeting_time_period" translatable="false">%1$s\n%2$s</string> ``` So the strings were just one below another. But now I need to change the `textSize` and `textColor` of the second row. In this case I need to use two TextViews and the current solution I am using is to center in `LinearLayout`. **2.** Second solution with two TextViews. my **item\_contact.xml** : ``` <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <import type="android.view.View"/> <variable name="info" type="com.myproject.objects.InfoObject"/> </data> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="70dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <TextView android:id="@+id/item_contact_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="32dp" android:layout_marginStart="32dp" android:text="@{info.getName()}" android:textSize="16sp" android:textColor="@color/black" /> <TextView android:id="@+id/item_contact_accountName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="32dp" android:layout_marginStart="32dp" android:layout_marginTop="5dp" android:text="@{info.getAccountName()}" android:textColor="@color/gray" android:textSize="12sp" android:textAppearance="@android:style/TextAppearance.DeviceDefault.Widget.ActionMode.Subtitle" android:visibility="@{info.getAccountName().isEmpty() ? View.GONE : View.VISIBLE}" android:background="@color/blue" /> </LinearLayout> <include layout="@layout/bottom_line_divider" /> </RelativeLayout> ``` But in this case if the second `TextView` is `Gone` than the first TextView still will render on the top of the `LinearLayout` as it suppose that the second view can be `Visible`. **QUESTION:** What is the solution to make first TextView be centralized vertically if the second TextView invisible and both of them be centralized if the second TextView visible?
2017/03/23
[ "https://Stackoverflow.com/questions/42972575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6026222/" ]
Ok, summing up. Finally I have finished everything and it is working as I wanted, so if there is only one `TextView` visible than it is centralized verticaticaly, or if there are both `TextView`s visible, both of them are centered. **item\_contact.xml** : ``` <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <import type="android.view.View"/> <variable name="info" type="fi.lunni.mobileadvisor.ui.objects.InfoObject"/> <variable name="handler" type="fi.lunni.mobileadvisor.ui.adapters.ContactsAdapter"/> </data> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="70dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" android:gravity="center_vertical" > <TextView android:id="@+id/item_contact_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="32dp" android:layout_marginStart="32dp" android:text="@{info.getName()}" android:textSize="16sp" android:textColor="@color/black" android:layout_gravity="@{info.getAccountName().length() > 0 }" /> <TextView android:id="@+id/item_contact_accountName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="32dp" android:layout_marginStart="32dp" android:layout_marginTop="5dp" android:text="@{info.getAccountName()}" android:textColor="@color/gray" android:textSize="12sp" android:textAppearance="@android:style/TextAppearance.DeviceDefault.Widget.ActionMode.Subtitle" android:visibility="@{info.getAccountName().length() > 0 ? View.VISIBLE : View.GONE }" /> </LinearLayout> <include layout="@layout/bottom_line_divider" /> </RelativeLayout> ``` And a function in a separate class **BindingAdapters.java** : ``` @BindingAdapter("android:layout_gravity") public static void setLayoutGravity(TextView view, boolean belowViewExists){ if(view.getId() == R.id.item_contact_name){ Log.d(TAG, "setLayoutVertical() " + belowViewExists); if(!belowViewExists) { final LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams(); layoutParams.gravity = Gravity.CENTER_VERTICAL; layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT; view.setLayoutParams(layoutParams); } } } ```
This is a perfect case for using [ConstraintView](https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html). Its support for "missing" views is much better.
48,928,330
When I try any kubectl command, it always returns: ```text Unable to connect to the server: EOF ``` I followed these tutorials: > > <https://kubernetes.io/docs/tasks/tools/install-kubectl/> > > > <https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/> > > > But they have not helped me. According to the first link, by default, kubectl configuration is located at ```text ~/.kube/config ``` But in that path I don't have anything. I don't know if this is causing the issue. Other thing is when I try to check the kubectl configuration: ```text M:.kube candres$ kubectl cluster-info Kubernetes master is running at http://localhost:8080 To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'. Unable to connect to the server: EOF M:.kube candres$ kubectl cluster-info dump Unable to connect to the server: EOF ``` The versions I have installed are: Kubernetes - kubectl ```text M:.kube candres$ kubectl version Client Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.3", GitCommit:"X", GitTreeState:"clean", BuildDate:"2018-02-09T21:51:06Z", GoVersion:"go1.9.4", Compiler:"gc", Platform:"darwin/amd64"} Unable to connect to the server: EOF ``` Minikube ```text M:.kube candres$ minikube version minikube version: v0.25.0 ``` Docker: ```text M:.kube candres$ docker version Client: Version: 17.12.0-ce API version: 1.35 Go version: go1.9.2 Git commit: X Built: Wed Dec 27 20:03:51 2017 OS/Arch: darwin/amd64 Server: Engine: Version: 17.12.0-ce API version: 1.35 (minimum version 1.12) Go version: go1.9.2 Git commit: X Built: Wed Dec 27 20:12:29 2017 OS/Arch: linux/amd64 Experimental: true ``` Does anyone know how to resolve this?
2018/02/22
[ "https://Stackoverflow.com/questions/48928330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7288685/" ]
After Minikube is started, **kubectl** is configured automatically. ``` minikube start Starting local Kubernetes cluster... Kubernetes is available at https://192.168.99.100:8443. Kubectl is now configured to use the cluster. ``` You can verify and validate the cluster and context with following commands. ``` kubectl config view ```
Check your VPN security as well as your anti virus internet security. in case it is ON then we have to make it off. and it worked for me after that. Try it out this also.
6,273,293
I swear I've seen people add multiple background images to an element using the :after selector. For whatever reason, I can't get it to work. What am I doing wrong? Can anyone point me to a working example? ``` #el li { background:url(image1.jpg) top center;} #el li:after { background:url(image2.jpg) bottom center;} ``` Thanks!
2011/06/08
[ "https://Stackoverflow.com/questions/6273293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586706/" ]
`:before` and `:after` always need the following: ``` { content: ''; } ```
You can do it, but I've never tried. `:after` seems to create an inline-like element after your element. You can try adding this CSS (no idea if it works): ``` display: block; position: relative; top: -200px; height: 200px; width: 200px; ```
3,210,133
I am not sure how to find the $x$ values of $2\cos(2x)-2\sin(x)=0$. I am trying to find the absolute values of $f(x)=2\cos(x)+\sin(2x)$ in the range$[0, \frac{\pi}{2}]$. I have differentiated $f(x)$ to produce $2\cos(2x)-2\sin(x)$, but I am unsure how to find the zeros of the function since I cannot think of a value of $x$ that would make both sine and cosine equal 0. $$\frac{d}{dx} 2\cos(x)=[0 \cdot \cos(x)] + [2 \cdot -\sin(x)]=-2\sin(x)$$ $$\frac{d}{dx}\sin(2x)= \cos(2x) (2)=2\cos(2x)$$ $$\frac{d}{dx}2\cos(x)+\sin(2x)=2\cos(2x)-2\sin(x)$$
2019/05/01
[ "https://math.stackexchange.com/questions/3210133", "https://math.stackexchange.com", "https://math.stackexchange.com/users/601849/" ]
You don't need any calculus to do this: $$ 0=2\cos(2x)-2\sin(x) = 2(\cos^2x -\sin^2x -\sin x) = 2(1-\sin x - 2\sin^2x). $$ which is a quadratic equation (substitute $y=\sin x$).
**Hint**: Rewrite the equation as $\;\cos(2x)=\cos \bigl(\frac\pi 2-x\bigr)$. Then use that $$\cos\alpha=\cos\beta\iff \alpha\equiv\pm\beta \pmod{2\pi}.$$
58,006,255
My application is in final stages and we have not implemented autofocus on input tags. Now we have a requirement where we wish to put focus on first input tag in each of the page. There are lot of pages/forms in my application, so using ViewChild in each component can be a tedious task. Hence I'm looking for some way from which I can write some code at one place and it triggers focus on first input on whatever page is loaded. Can anyone suggest some way to do this?
2019/09/19
[ "https://Stackoverflow.com/questions/58006255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I came up with a method decorator which would do what you want. That is, if you don't mind to import this function to all pages. You would then simply attach this decorator to the `AfterViewInit` life cycle, like so: ```ts @setFocus() ngAfterViewInit() { } ``` The decorator function would then search after the first input field found and if found, set focus to that element: ```ts export function setFocus(): MethodDecorator { return function (target: Object, key: string, descriptor: PropertyDescriptor) { descriptor.value = function (...args: any[]) { const ele = document.getElementsByTagName("INPUT")[0] as HTMLElement; if (ele) { ele.focus(); return; } } } } ``` **[STACKBLITZ](https://stackblitz.com/edit/angular-nsqims?file=src%2Fapp%2Fapp.component.ts)**
you can use tabindex property of HTML element with tabindex="1" will receive focus first eg: see:<https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex> :<https://developer.paciellogroup.com/blog/2014/08/using-the-tabindex-attribute/> NB: Be careful using tabindex as it imposes a tab order on the content that bears no resemblance to the expected tab order.
9,559
If it is even possible, what would the Goldilocks zone be like - in fact is such a system even possible of holding life - around a binary black hole? Could it have planets orbiting it? EDIT 1: Oh well, no star no life. So now, how would it look like if there is a star that orbits the binary black hole system? Would there be a Goldilocks zone? Would it be stable? Taking note that the planet will still be orbiting the binary black hole and not orbiting the sun.
2015/02/03
[ "https://worldbuilding.stackexchange.com/questions/9559", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/6429/" ]
**Would there be a goldilocks zone?** Probably around the star, but *not* in the way of the black holes. **Would it be stable?** No, I don't think it would. Black holes are massive(read:*heavy*), as are stars. All massive objects produce gravity and are affected by gravity. All three would interact in a rather chaotic mess, as would every planet in orbit around them. What you're describing will fall under into the category of [n-body problems](http://en.wikipedia.org/wiki/N-body_problem). The maths is a little heavy (pun intended), but the crux of it is that stable solutions are few and far-between. Your star may *currently* be orbiting the black hole, it won't be for long!
A black hole would act gravitationally towards an orbiting mass in the same way as a regular star would. Depending on the binary formation, quasi-stable orbits are possible around a binary system, even if one of the main centers of gravitational influence in the system is a black hole. The planet would have to be a survivor of the original super-large star (and the subsequent hyper-violent explosion) or a captured stray world. All heat would have to come from the live stellar companion, so Goldilocks calculations would have to be done in reference to that. Your current specification is too vague for me to be of more help.
1,319,476
This is a question related to another posted question: The answer to the following question "Find all solutions to: $e^{ix}=i$" is as follows: "Euler's formula: $e^{ix}=\cos(x)+i\sin(x)$, so: $ \cos x+i\sin x=0+1⋅i$ compare real and imaginary parts $\sin(x)=1$ and $\cos(x)=0$ $x=\frac{(4n+1)π}2$, $n∈$ (W stands for set of whole number W={0,1,2,3,.......,n})." My question: Where does $x=\frac{(4n+1)π}2$, $n∈$ come from? My steps: 1. $\cos(x) + i\sin(x) = 0 + i(1)$ 2. $\cos(x) = i(1 - \sin(x))$ 3. ... 4. how does $x=\frac{(4n+1)π}2$ follow?
2015/06/10
[ "https://math.stackexchange.com/questions/1319476", "https://math.stackexchange.com", "https://math.stackexchange.com/users/247098/" ]
I always find it easier to use a fixed method, and I thought you might find this explanation easier, so I'm posting it. Start by putting everything into exponential form. Now $i = e^{\frac{i\pi}{2}}$. You can derive this from $e^{i\pi} = -1$ and taking square roots on both sides. Now note that for *any* $\theta$, $e^{i\theta} = e^{i(\theta + 2k\pi)}, k \in \mathbb{Z}$, and this is because $e^{2k\pi i} = 1$. Essentially, this can be viewed as the periodicity of the exponential form. To compute general solutions or roots, you would be well-advised to include this term so that you don't miss any solutions. Hence you can now write $i = e^{i(\frac{\pi}{2} + 2k\pi)} = e^{i\pi\frac{4k+1}{2}}$ Note that the final step is just an algebraic rearrangement of the exponent. You can now immediately solve the equation by taking logs of both sides, i.e. $e^{ix} = e^{i\pi\frac{4k+1}{2}}\\ \implies x = \pi\frac{4k+1}{2}$ which is essentially the required form.
**Hint:** * $i$ is **a point on the unit circle**. * $e^{ix}$ is *also* **a point on the unit circle**, lying *x* radians away from $(1,0)$, in trigonometric or counterclockwise direction. So, to answer a question with a question, What is the position of $i$ on the unit circle, and How many radians away from $(1,0)$ does it lie, in trigonometric or counterclockwise direction ?
19,620,051
I have an HTML page that contains a table. The table is dynamically generated from a database on the server side. I would like the width of the table to determine the width of the entire page. That is, other block elements above and below the table should take on the same width as the table. I do not want to use fixed widths. I prefer a pure css solution but if fudging things with JavaScript is the only way, then so be it. I need fairly wide browser support. I tried using a `div` with `display: inline-block` around the table and the other block elements. The idea was to have the `div` "shrink to fit" around the table and thereby set the width of the other elements. This did not work and I think it's because the `div` does not know which of the elements inside should be the "master", determining the width for the other elements. **Edit**: Added a fiddle: <http://jsfiddle.net/5Z3ru/>. In this example, I would like the paragraph above the table to be the same width as the table (not the other way around). I do not want to use a fixed width for the table or paragraph. **Edit 2**: Conceptually, what I am looking for can be imagined as if the table is rendered alone in a separate document. Then, the rendered table is inserted into a new document and the width of the rendered table is used for setting the width of the new document. So, nothing in the final document affected the rendering of the table, and the table width becomes the only factor in deciding the width of the final document.
2013/10/27
[ "https://Stackoverflow.com/questions/19620051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442006/" ]
* Lets call the initially rendered width of the `wrap` as X. * `wrap`, when initially rendered and without any width specified, will automatically fill all available horizontal space on the screen available to it. In this case, the entire width of the document. Therefore, in this case, X = 100% of the document. * You *cannot* make X less than 100% without specifying a new width (aside from methods that are of no use here). * Using CSS, you can make the `table` the only deciding factor to the expansion of `wrap`, as it will naturally expand to include a table that grows beyond X. * To make the `wrap` shrink below X, to a dynamic value (the natural width of the `table`) you will have to use Javascript. This will mean that the document will load, *then* the table width is ascertained (`var w = $( "table" ).width()`), *then* that width is applied to `wrap` (`$("#wrap").css("width":w)`).
What about set tablels with relative? ``` table{ width:100%; } ``` Made a [fiddle](http://jsfiddle.net/spSSC/1/) with a fixed body width and a table inside with 100% width.
37,038,258
I'm building an HTML webpage that contains the following content: > > In order to proceed, please enter this code: GJBQTCXU > > > "GJBQTCXU" is a code comprised of a string of letters; however, screen readers attempt to pronounce this as a single word. How can I stop them from attempting to pronounce this nonsensical word and instead get it to read one letter at a time: "G J B Q T C X U". As clarification, I'm building this page so that screen readers automatically do the right thing. I know that users can choose to have their reader pronounce each letter at a time, but I don't want my users to have to take any additional steps.
2016/05/04
[ "https://Stackoverflow.com/questions/37038258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174719/" ]
try using CSS letter-spacing property - ``` <div>G J B Q T C X U</div> div { letter-spacing:-1.9px; } ``` example: <http://codepen.io/stevef/pen/grZGBP>
I feel like the real answer to this is: ``` <div aria-label="G J B Q T C X U">GJBQTCXU</div> ```
36,992,018
I have a folder with images in that I need re-naming. Currently the files are like this: ``` C:\Images\Today\4714\IMG_2342.jpg C:\Images\Today\4714\IMG_2343.jpg C:\Images\Today\4714\IMG_2344.jpg C:\Images\Today\4714\IMG_2345.jpg ``` And I need them to be like this: ``` C:\Images\Today\4714\4714_1.jpg C:\Images\Today\4714\4714_2.jpg C:\Images\Today\4714\4714_3.jpg C:\Images\Today\4714\4714_4.jpg ``` How can I do this in powershell please?
2016/05/02
[ "https://Stackoverflow.com/questions/36992018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4647684/" ]
If you know that no files named `4714_X.jpg` exist already, you can easily do this with a for loop: ``` $Files = Get-ChildItem C:\Images\Today\4714\ *.jpg for($i = 0; $i -lt $Files.Count; $i++) { Rename-Item $Files[$i].FullName -NewName "4714_$i.jpg" } ```
try this ``` dir C:\Images\Today\4714\ *.jpg | ? {$_.name -NotMatch "^$($_.directory.name)"} | % {ren $_.fullname $($_.name -replace 'img(?=_)', $_.directory.name)} ```
16,390
As a webmaster in charge of a tiny site that has a forum, I regularly receive complains from users that both the internal search engine and that external searches (like when using Google) are totally polluted by my users' signatures (they're using long signatures and that's part of the forum's experience because signatures makes a lot of sense in my forum). So basically I'm seeing two options as of now: 1. Rendering the signature as a picture and when a user click on the "signature picture" it gets taken to a page that contains the real signature (with the links in the signature etc.) and that page is set as being non-crawlable by search engine spiders). This would consume some bandwidth and need some work (because I'd need an HTML renderer producing the picture etc.) but obviously it would solve the issue (there are tiny gotchas in that the signature wouldn't respect the font/color scheme of the users but my users are very creative with their signatures anyway, using custom fonts/colors/size etc. so it's not that much of an issue). 2. Marking every part of the webpage that contains a signature as being non-crawlable. However I'm not sure about the later: is this something that can be done? Can you just mark specific parts of a webpage as being non-crawlable?
2011/07/04
[ "https://webmasters.stackexchange.com/questions/16390", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/8785/" ]
> > Marking every part of the webpage that contains a signature as being > non-crawlable. > > > You can use the directive **[nosnippet](https://developers.google.com/search/docs/advanced/robots/robots_meta_tag#nosnippet)**: > > Do not show a text snippet or video preview in the search results for > this page. A static image thumbnail (if available) may still be > visible, when it results in a better user experience. This applies to > all forms of search results (at Google: web search, Google Images, > Discover). > > > If you don't specify this directive, Google may generate a text > snippet and video preview based on information found on the page. > > > E.g.: ``` <p>This text can be shown in a snippet <span data-nosnippet>and this part would not be shown</span>.</p> <div data-nosnippet>not in snippet</div> <div data-nosnippet="true">also not in snippet</div> <div data-nosnippet="false">also not in snippet</div> <!-- all values are ignored --> <div data-nosnippet>some text</html> <!-- unclosed "div" will include all content afterwards --> <mytag data-nosnippet>some text</mytag> <!-- NOT VALID: not a span, div, or section --> ``` For an understanding of Google's hidden text policy, check the Google Guide **[Hidden text and links](https://developers.google.com/search/docs/advanced/guidelines/hidden-text-links)**.
No, there is no way to prevent robots crawling parts of pages. It's a whole page or nothing. The snippets in Google's search results are usually taken from the *meta description* on the page. So you could make Google show a specific part of the page by putting that in the meta description tag. With user-generated content it's difficult to get good snippets, but taking the first post of the thread would probably work. The only other way I can think of is to use Javascript. Something like paulmorriss suggested *may* work, but I think search engines would still index the content if it's in the HTML. You could remove it from the HTML, store it in Javascript string, then add it back on page load. This gets a bit complex, though. Finally, one thing to keep in mind: if Google is showing user's signatures in their snippets, it has decided that is the part most relevant to the user's query.
53,705,708
I've written a code which looks at projectile motion of an object with drag. I'm using odeint from scipy to do the forward Euler method. The integration runs until a time limit is reached. I would like to stop integrating either when this limit is reached or when the output for ry = 0 (i.e. the projectile has landed). ``` def f(y, t): # takes vector y(t) and time t and returns function y_dot = F(t,y) as a vector # y(t) = [vx(t), vy(t), rx(t), ry(t)] # magnitude of velocity calculated v = np.sqrt(y[0] ** 2 + y[1] **2) # define new drag constant k k = cd * rho * v * A / (2 * m) return [-k * y[0], -k * y[1] - g, y[0], y[1]] def solve_f(v0, ang, h0, tstep, tmax=1000): # uses the forward Euler time integration method to solve the ODE using f function # create vector for time steps based on args t = np.linspace(0, tmax, tmax / tstep) # convert angle from degrees to radians ang = ang * np.pi / 180 return odeint(f, [v0 * np.cos(ang), v0 * np.sin(ang), 0, h0], t) solution = solve_f(v0, ang, h0, tstep) ``` I've tried several loops and similar to try to stop integrating when ry = 0. And found this question below but have not been able to implement something similar with odeint. solution[:,3] is the output column for ry. Is there a simple way to do this with odeint? * [Does scipy.integrate.ode.set\_solout work?](https://stackoverflow.com/questions/26738676/does-scipy-integrate-ode-set-solout-work)
2018/12/10
[ "https://Stackoverflow.com/questions/53705708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10770669/" ]
Also try ``` df1 * t(C) # F1 F2 F3 #1 2.0 2.0 2.0 #2 5.0 5.0 5.0 #3 16.0 16.0 16.0 #4 4.5 4.5 4.5 ``` --- When we try to multiply data frames they must be of the same size. ``` df1 * C ``` > > error in Ops.data.frame(df1, C) : > ‘\*’ only defined for equally-sized data frames > > > `t()` turns `C` into a matrix, i.e. a vector with dimension attribute of length 4. This vector gets recycled when we multiply it with `df1`. What would also work in the same way (and might be faster than transposing `C`): ``` df1 * C$C ``` or ``` df1 * unlist(C) ```
Another solution is `sweep(df1, 1, C$C, `*`)`, which means "sweep out" the statistic represented by `C$C` from each column of `df1` by multiplication.
13,996,181
If I add a font into my FTP for my website, when I am adding in my font, where do I put it in the FTP and how do I use the font with HTML or CSS ?
2012/12/21
[ "https://Stackoverflow.com/questions/13996181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1922317/" ]
You can upload the font where ever you want it, you just need to link to the right location. Please see exmaple below for font faces in CSS. ``` @font-face{ font-family:'Your Font Name'; src:url(http://www.example.com/fonts/YourFont.otf); } ```
I personally recommend use the [Font Squirrel Fontface generator](http://www.fontsquirrel.com/fontface/generator) for that. You will get something like: ``` /* @Fontface */ @font-face { font-family: 'Yourfont'; src: url('fonts/yourfont.eot'); src: url('fonts/yourfont.eot?#iefix') format('embedded-opentype'), url('fonts/yourfont.woff') format('woff'), url('fonts/yourfont.ttf') format('truetype'), url('fonts/yourfont.svg#Yourfont') format('svg'); font-weight: normal; font-style: normal; } ``` Using this way you will get a valid option to IE, Chrome, Opera, Firefox and Safari. Later you can use this font like a normal font, using ``` div.heading { font-family: 'Yourfont', (othersifyouwant); } ```
1,319,135
I am running Ubuntu 20.04.2, an up until today my samba file server was running great. Today However I cant access my main folder. (I am connecting through a windows 10 PC) It says: ``` Windows cannot access \\192.168.0.43\admin You do not have permission... Contact an admin ``` Just one folder, I can access all the rest. Here is a list of things I have tried: * Creation a new user, with full permissions * sudo chown -R admin /samba * Restarting the samba service * Restarting the server * Trying a different PC * Making a new user for just that folder (still cant access that folder) I have never had this issue before, and it is just one folder, I was using it yesterday, and merely edited some text documents. I cant figure out what is wrong for the life of me, I welcome any suggestions. Thanks! EDIT: [Now I cant access the samba share at all and I get this error I have never seen before. No other devices are connected to, and I have restarted the smdb service... again](https://i.stack.imgur.com/tmtQ0.png) EDIT2: Now the error above is gone, I can see my folders again, but I still cant access the one, and I get that need permission error that I posted originally. (and I did nothing) This is ridiculous. Why today....
2021/02/25
[ "https://askubuntu.com/questions/1319135", "https://askubuntu.com", "https://askubuntu.com/users/1186269/" ]
Since your motherboard does in fact have an Ethernet port, I think it is a driver issue. This site may help: [no WiFi and Ethernet connection on msi gaming edge wifi. Where and how do I install the drivers if possible](https://askubuntu.com/questions/1299842/no-wifi-and-ethernet-connection-on-msi-gaming-edge-wifi-where-and-how-do-i-inst) and so might these: <https://bbs.archlinux.org/viewtopic.php?id=258479> <https://forums.linuxmint.com/viewtopic.php?f=150&t=327043> However,on the MSI website there do not seem to be any driver downloads for Linux. The links above may be your best bet, and may provide the best help for your query and issue. I hope this helps!
Here seems to have solved it with the mystery for the driver location not stated. A search on that model lead to the third link. [no WiFi and Ethernet connection on msi gaming edge wifi. Where and how do I install the drivers if possible](https://askubuntu.com/questions/1299842/no-wifi-and-ethernet-connection-on-msi-gaming-edge-wifi-where-and-how-do-i-inst) <https://www.google.com/search?client=firefox-b-d&q=Realtek%C2%AE+RTL8125B+2.5G+LAN+linux+driver> <https://www.realtek.com/en/component/zoo/category/network-interface-controllers-10-100-1000m-gigabit-ethernet-pci-express-software>
59,877,207
I'm trying to set an array of components styles directly from the store, so that when the store changes, the design of each component changes too. I store a set of links in my Vuex store like this: ``` links: [ {id: 1, text: 'Banana is a test', design: {color: 'red', 'background-color': 'blue', padding: '51px', margin: '5px', 'border-width' : '10px', 'border-color': 'blue', 'font-weight' : 600, font: 'Arial'}}, {id: 2, text: 'This is a test', design: {color: 'red', 'background-color': 'blue', padding: '20px', margin: '10px', 'border-width' : '10px', 'border-color': 'green', 'font-weight' : 600, font: 'Arial'}}, {id: 3, text: 'Monkey is a test', design: {color: 'red', 'background-color': 'blue', padding: '5px', margin: '5px', 'border-width' : '10px', 'border-color': 'green', 'font-weight' : 600, font: 'Arial'}}, ] ``` and this is how I try to render them ``` <a v-for="link in links" :key=link.id :href="link.destination" :id=link.id :style="link.design"> {{link.text}} </a> ``` the trouble is, when the design objects changes in the Vuex store, the links styles are not subsequently updated as I would expect. In my Vue component I've tried getting the links in different ways, assuming this would change the reactivity. Currently I get them using a computed method like so: ``` computed: { getLinks: function() { return this.$store.state.links } }, ``` but whenever I change the value of a background-color, say from 'blue' to 'red', I have to reload the page to see the change. Do I need to force a rerender of the page everytime I call my mutation? This is my mutation for reference: ``` setSelectedItemDesign (state, payload ) { state.selectedItem.design[Object.keys(payload)[0]] = Object.values(payload)[0] } ``` and I'd call it from my component like this: ``` this.$store.commit('setSelectedItemDesign', {'background-color' : this.rgbaValue}) ```
2020/01/23
[ "https://Stackoverflow.com/questions/59877207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9447776/" ]
I was having the same problem for a while, if anyone is experiencing a case scenario where onClick is needed on the labels here's how I solved it: ``` componentDidMount () { //get the DOM elements of the labels , classes may vary so check in dev tools. const labels = document.querySelectorAll('.apexcharts-text.apexcharts-yaxis-label') // you'll get NodeList so iterate & add click event listeners labels.forEach(item => { item.addEventListener('click', event => { // do whatever onClick console.log(event.target) }) }) } ```
Today (6 may 2022), there is a specific event for this, e.g. ``` legendClick: function(chartContext, seriesIndex, config) { // get the id of the chart-element to get the specific chart (I have multiple charts on a page) console.log('chartConfigId', chartContext.el.id.split("-")[2]); console.log('seriesIndex', seriesIndex); } ```
6,449,834
I'm building an application in which I am using Socket Programming in Java using TCP. When the server side Firewall is running, I am unable to connect to the server. So how can I make a check in Java that the Firewall is running and tell the server administrator he should turn it off.
2011/06/23
[ "https://Stackoverflow.com/questions/6449834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/689853/" ]
The only guaranteed way of doing it is to actually try establishing a connection to the host:port. But again, if you are unable to connect, you can't say that its because of firewall, it could be because of server being actually down. So you can't really tell with conformity that the firewall is turned on.
@Suraj is right. If you cannot to specific TCP port you do not know whether the host is unavailable, no one is listening to the port or firewall blocks you. But there is a trick that helps in 90% of cases. Typically firewall configuration has exceptions like HTTP:80, ICMP etc. So, you can try to connect to your port. If it works, you are done. Otherwise try to perform any other connection to the host (HTTP, ICMP etc.) If you managed to do this firewall blocked you. Otherwise probably the host is unreachable.
24,917,700
I was wondering if there is an equivalent way to add a row to a Series or DataFrame with a MultiIndex as there is with a single index, i.e. using .ix or .loc? I thought the natural way would be something like ``` row_to_add = pd.MultiIndex.from_tuples() df.ix[row_to_add] = my_row ``` but that raises a KeyError. I know I can use .append(), but I would find it much neater to use .ix[] or .loc[]. here an example: ``` >>> df = pd.DataFrame({'Time': [dt.datetime(2013,2,3,9,0,1), dt.datetime(2013,2,3,9,0,1)], 'hsec': [1,25], 'vals': [45,46]}) >>> df Time hsec vals 0 2013-02-03 09:00:01 1 45 1 2013-02-03 09:00:01 25 46 [2 rows x 3 columns] >>> df.set_index(['Time','hsec'],inplace=True) >>> ind = pd.MultiIndex.from_tuples([(dt.datetime(2013,2,3,9,0,2),0)],names=['Time','hsec']) >>> df.ix[ind] = 5 Traceback (most recent call last): File "<pyshell#201>", line 1, in <module> df.ix[ind] = 5 File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing.py", line 96, in __setitem__ indexer = self._convert_to_indexer(key, is_setter=True) File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing.py", line 967, in _convert_to_indexer raise KeyError('%s not in index' % objarr[mask]) KeyError: "[(Timestamp('2013-02-03 09:00:02', tz=None), 0L)] not in index" ```
2014/07/23
[ "https://Stackoverflow.com/questions/24917700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820991/" ]
You have to specify a tuple for the multi-indexing to work (AND you have to fully specify all axes, e.g. the `:` is necessary) ``` In [26]: df.ix[(dt.datetime(2013,2,3,9,0,2),0),:] = 5 In [27]: df Out[27]: vals Time hsec 2013-02-03 09:00:01 1 45 25 46 2013-02-03 09:00:02 0 5 ``` Easier to reindex and/or concat/append a new dataframe though. Generally setting (with this kind of enlargement), only makes sense if you are doing it with a small number of values. As this makes a copy when you do this.
**Update since `.ix` is deprecated**: Use `[DataFrame.loc][1]` instead: ```py # say you have dataframe x x Out[78]: a b time indA indB a i 0.0 NaN 2018-09-12 b j 1.0 2.0 2018-10-12 c k 2.0 3.0 2018-11-12 f NaN NaN NaT d i 5.0 NaN NaT x.loc[('a','k'),:] = (3.5,6,pd.NaT) x Out[80]: a b time indA indB a i 0.0 NaN 2018-09-12 b j 1.0 2.0 2018-10-12 c k 2.0 3.0 2018-11-12 f NaN NaN NaT d i 5.0 NaN NaT a k 3.5 6.0 NaT ```
31,357,532
I have a text file which is like this ```none count="4" data1 data2 data3 Data1 Data2 Data3 ``` I need to search for the string `count` and take its value (4) and print the next 3 lines count(4) times. The output in the file should be ``` data1 data2 data3 data1 data2 data3 data1 data2 data3 data1 data2 data3 Data1 Data2 Data3 ``` I tried this Perl code ``` while ( <FILE> ) { $n = 3 if ( $_ =~ /count="4"/ ) { print FILE if ($n-- > 0) x 4; } ``` But it's not working.
2015/07/11
[ "https://Stackoverflow.com/questions/31357532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5105871/" ]
You can try something like this: ``` #!/usr/bin/perl use strict; use warnings; my $count = 0; while (my $line = <DATA>){ if ($line =~ /count="(\d+)"/ and $1){ $count = $1; next; } if ($count){ print $line; $count--; } } __DATA__ count="2" a b c d count="1": e f g count="3" h i j k l ```
you can give file/input at `@data` ``` #!/usr/bin/perl use strict; use warnings; my @data = qw /count="4" data1-1 data2-1 data3-1 Data1 Data2 Data3/; my $repeat_line = 3; foreach (@data) { if ( /count="(\d+)"/ ) { for ( 1..$1 ) { for my $no1 ( 1..$repeat_line ) { print $data[$no1],"\n"; } } } } for my $no ($repeat_line..scalar(@data)) { if(defined $data[$no+1]){ print $data[$no+1],"\n"; } } ``` output ``` data1-1 data2-1 data3-1 data1-1 data2-1 data3-1 data1-1 data2-1 data3-1 data1-1 data2-1 data3-1 Data1 Data2 Data3 ```
33,407,448
The new default Navigation Drawer Activity template in Android Studio [![enter image description here](https://i.stack.imgur.com/kP4ZR.png)](https://i.stack.imgur.com/kP4ZR.png) defines its titles and icons in a menu file `activity_main_drawer` like this: ``` <group android:checkableBehavior="single"> <item android:id="@+id/nav_camara" android:icon="@drawable/ic_action_emo_cool" android:title="Import" /> <item android:id="@+id/nav_gallery" android:icon="@android:drawable/ic_menu_gallery" android:title="Gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@android:drawable/ic_menu_slideshow" android:title="Slideshow" /> ... ``` The first item in my example uses a red icon: [![enter image description here](https://i.stack.imgur.com/iTjR6.png)](https://i.stack.imgur.com/iTjR6.png) but when I run the app, the color of the icon remains black.I have tested this for blue, green, yellow and purple icons, but the result is the same. [![enter image description here](https://i.stack.imgur.com/BlJsx.png)](https://i.stack.imgur.com/BlJsx.png) I read somewhere that the toolbar should use `ThemeOverlay.AppCompat.Dark.ActionBar` and my app already uses this in the `styles.xml` file: ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> ``` Initially I thought this had something to do with Android Studio's cache feature so I invalidated cache and restarted Android Studio with no luck.
2015/10/29
[ "https://Stackoverflow.com/questions/33407448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2058547/" ]
In my case, I was having a style ``` <style name="MyToolbarStyle" parent="Theme.AppCompat"> <item name="actionOverflowButtonStyle">@style/ActionButtonOverflowStyle</item> <item name="drawerArrowStyle">@style/DrawerArrowStyle</item> </style> <style name="ActionButtonOverflowStyle"> <item name="android:color">@color/colorPrimary</item> </style> <style name="DrawerArrowStyle"> <item name="android:color">@color/colorPrimary</item> </style> ``` and have applied the theme to the Appbar layout, so programatically chaining color didn't work. So, **try removing any styles that you applied**, in case you are not able to change the color of the icon and then try the above given solutions.
This works for me for changing icon color from the menu xml file which you drag in the `app:menu` attribute of the `NavigationView` widget. Use `app:iconTint` attribute to set the icon color. ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/..." android:icon="@drawable/ic_person_black_24dp" android:title="..." app:iconTint="#FFEB3B" /> <item android:id="@+id//..." android:icon="@drawable/ic_settings_black_24dp" android:title="..." app:iconTint="#FFEB3B" /> <item android:id="@+id//..." android:icon="@drawable/logout" android:title="..." app:iconTint="#FFEB3B"/> </menu> ```
1,366,848
When a web server responds to `HttpWebRequest.GetResponse()` with HTTP 304 (Not Modified), `GetResponse()` thows a `WebException`, which is so very weird to me. Is this by design or am I missing something obvious here?
2009/09/02
[ "https://Stackoverflow.com/questions/1366848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60188/" ]
The way to avoid this `System.WebException` is to set [AllowAutoRedirect](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect%28v=vs.110%29.aspx) property to `false`. This disables the automatic redirection logic of the `WebRequest`. It seems to be broken for 304 redirection requests, as it is not a real redirection in the strictest sense. Of course that means that the other redirection requests `3xx` have to be handled manually.
I also came across to this issue with code: ``` try { ... var webResponse = req.GetResponse(); ... } catch (WebException ex) { Log.Error("Unknown error occured", ex); //throw; } ``` And it appears that if Remote Server returns 304 status it must be passed to Browser by throwing this error or returning custom 304 so the Browser could return cached response. Otherwise you will probably get empty Response from the Remote Server. So in my case for normal behaviour with correct Cache handling it should be like: ``` try { ... var webResponse = req.GetResponse(); ... } catch (WebException ex) { if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotModified) throw; Log.Error("Unknown error occured", ex); } ```
24,809,196
I have 2 Stateless EJBs StatelessA and StatelessB, both of them have interceptors InterceptorA and InterceptorB respectively. Also, StatelessB has Asynchronous methods. Something like this: ``` @Stateless @Interceptors(InterceptorA.class) public class StatelessA{... @Stateless @Asynchronous @Interceptors(InterceptorB.class) public class StatelessB{... ``` When calling a method on StatelessA, it calls several StatelessB methods and returns a value. I am trying to develop 2 interceptors to store the total time and the subtotal times of StatelessB calls, this is the objective of the interceptors. I need to do it so InterceptorA can see the detail of InterceptorB data, so I store only a value in the DB, containing the total time (of SLSB A) and the subtotal times (of SLSB B). I tried using a ThreadLocal variable (containing a list of times, something like long[]), which works fine if StatelessB is not asyncrhonous. The problem is that when it is asynchronous, the variable is not available, since it is running in a different thread (AFAIK). I also tried injecting EJBContext or using the InvocationContext, but none of them works. Can someone point me out what other alternatives do I have? Thanks in advance.
2014/07/17
[ "https://Stackoverflow.com/questions/24809196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1580636/" ]
I was thinking this over and over, and arrived to a solution, which is using the security context to pass data. The solution involves using the only data propagated in an asynchronous invocation, as specified in EJB 3.1: > > **4.5.4 Security** Caller security principal propagates with an asynchronous method invocation. Caller security principal propagation > behaves exactly the same for asynchronous method invocations as it > does for synchronous session bean invocations. > > > In JBoss, one can access the security context and use a data map in it to pass the values from InterceptorA to InterceptorB, as follows: In InterceptorA: ``` SecurityContext securityContext = SecurityContextAssociation.getSecurityContext(); securityContext.getData().put("interceptorAData",data); ``` In InterceptorB: ``` SecurityContext securityContext = SecurityContextAssociation.getSecurityContext(); securityContext.getData().get("interceptorAData"); ``` I tested it and it works great in JBoss EAP 6.1. This solution implies couplig the interceptor to the server implementation (JBoss AS), but the principle works for other servers. The advantage is that it decouples the application logic from the interceptors, which was the first objective. I appreciate any comments.
Would it work to store the information you need in an @Entity object and then use the @PersistenceContext annotation to inject an EntityManager into the beans to persist and find the data? Something like: ``` @PersistenceContext EntityManager entityManager; ... method() { MyEntityTimer met = new MyEntityTimer(getCurrentTime(), id); entityManager.persist(met); } ... elsewhere: MyEntityTimer met = entityManager.find(MyEntityTimer.class, id); ``` and: ``` @Entity @Table(name = "TABLE") public class MyEntityTimer { @Id @Column(name = "ID") private int id; ... } ```
4,424,158
The firebug console has various panels that can keep track of a lot of information. The net panel keeps track of almost all network traffic and reports various pieces of information on that traffic, e.g. headers, latency, request parameters, etc. What I would like to do is access all this information programatically from the javascript panel because I have a script that needs to know if there is a request in progress. I haven't found any documentation on how the various panels interoperate or if they are even aware of each other. I need to make the script as generic as possible so tying the script to the code on the page is not desirable because the script would not operate on other pages because of minor quirks like function names not being the same.
2010/12/12
[ "https://Stackoverflow.com/questions/4424158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165198/" ]
Check out firebug plugin [NetExport](http://www.softwareishard.com/blog/netexport/) Edit: [Here is the source code:](http://code.google.com/p/fbug/source/browse/#svn/netexport/branches/netexport0.7) Also this source code may interest you [tracingconsole](http://code.google.com/p/fbug/source/browse/#svn/extensions/tracingconsole/branches/tracingconsole0.5)
Well as far as I know, the only way to really "know" about in-flight XMLHttpRequests is to explicitly "remember" them in the code. It's like timeouts and interval timers - if your code doesn't hang on to a handle, it's lost. If the pages in question do everything via jQuery or some other framework, then it might be possible to worm into that code and leverage whatever's done to track ajax work, but exactly how you'd do that would depend on the framework. It might help your progress if you were to explain more about what it is you want to achieve with this technique. In other words, while what you asked about directly may not be possible, it might be possible to find another way to do whatever it is you want.
25,268,800
I'm having an issue in Angular where I have a controller that gets data from a service. The controller gets the data from the service but it only returns the last element. See this jsfiddle for an example: <http://jsfiddle.net/c1104q9b/> HTML: ``` <div ng-app="myApp"> <div ng-controller="MessageController"> <ul> <li ng-repeat="message in messageData">{{message.title}} - {{message.message}}</li> </ul> </div> </div> ``` JAVASCRIPT: ``` var app = angular.module('myApp', []); app.service('messageService', function () { // private data var data= [ { id: 1, title: 1, message: 'some new message1', id: 2, title: 2, message: 'some new message2', id: 3, title: 3, message: 'some new message3', id: 4, title: 4, message: 'some new message4', id: 5, title: 5, message: 'some new message5', id: 6, title: 6, message: 'some new message6', id: 7, title: 7, message: 'some new message7', id: 8, title: 8, message: 'some new message8' } ]; return { getMessages: function () { // Expose private data return data; }, addMessage: function (title, message) { // Public function that modifies private data var currentIndex = data.length + 1; data.push({ id:currentIndex, title: title, message: 'added a new message ' + message }) }, deleteMessage: function (id) { // Public function that modifies private data var oldMessages = data; data = []; angular.forEach(oldMessages, function(message){ if (message.id !== id) data.push(message); }); } }; }); app.controller('MessageController', ['$scope', 'messageService', function($scope, messageService) { $scope.messageData = messageService.getMessages(); //messageService.addMessage('some title', 'some new message'); $scope.addMessage = function (title, message) { if (title != ''){ messageService.addMessage(title, message); }; }; $scope.deleteMessage = function (id) { // }; }]); ```
2014/08/12
[ "https://Stackoverflow.com/questions/25268800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227083/" ]
The method when() is not part of your class MyClass. It's part of the class Mockito: ``` Mockito.when(test.getUniqueId()).thenReturn(43); ``` or, with a static import: ``` import static org.mockito.Mockito.*; ... when(test.getUniqueId()).thenReturn(43); ```
you are trying to get when from the mocked class. You need to do something like: ``` ... MyClass test = Mockito.mock(MyClass.class); Mockito.when(test.getUniqueId()).thenReturn(43); ... ```
21,104,514
I'm trying to do something pretty simple with powershell and xml but haven't a bit of trouble. Basically I'm trying to take the following xml... and sort the machine elements by name. Then put them back into the XML so that I can save back to a file. Sorting seems to be working if output the $new object however, during the replacechild it's complaining "Cannot convert argument "0", with value: "System.Object[]" for "ReplaceChild" to type "System.Xml.XmlNode" : "Cannot convert the "System.Object[]" to type "System.Xml.XmlNode". If I do a Get-Member on both $orig and $new they both say they are of type XMLElement which I believe inherits from XMLNode. What am I missing guys? Driving me nuts. Thanks for your help! ``` <company> <stuff> </stuff> <machines> <machine> <name>ca</name> <b>123</b> <c>123</c> </machine> <machine> <name>ad</name> <b>234</b> <c>234</c> </machine> <machine> <name>be</name> <b>345</b> <c>345</c> </machine> </machines> <otherstuff> </otherstuff> </company> [xml]$xml = (get-content Company.xml) [XmlNode]$orig = $xml.Company.Machines [XmlNode]$new = ($orig.Machine | sort Name ) $xml.Company.ReplaceChild($new, $orig) ```
2014/01/14
[ "https://Stackoverflow.com/questions/21104514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810969/" ]
There are various problems here. One is that your `sort` returns a list of xml elements rather than a single xml element. Another problem is that it returns the original xml elements rather than copies, so any manipulation of the xml DOM that you do using them will also affect the result. Here's a simple way to get what you want. Sort in *reverse* order, and then insert each node in turn in front of the others. Each time you insert a node from the result of the sort it will automatically remove it from the original set of node: ``` [xml]$xml = @" <company> <stuff> </stuff> <machines> <machine> <name>ca</name> <b>123</b> <c>123</c> </machine> <machine> <name>ad</name> <b>234</b> <c>234</c> </machine> <machine> <name>be</name> <b>345</b> <c>345</c> </machine> </machines> <otherstuff> </otherstuff> </company> "@ [System.Xml.XmlNode]$orig = $xml.Company.Machines $orig.Machine | sort Name -Descending | foreach { [void]$xml.company.machines.PrependChild($_) } $xml.company.machines.machine ``` Edit: The pipeline can also be written with an ascending sort (as David Martin pointed out), and you can reduce typing by using the node in the variable: ``` $orig.Machine | sort Name | % { [void]$orig.AppendChild($_) } ```
The reason this doesn't work is that $xml.Company.Machines is a single XmlElement. To get the collection of machine elements, you need to use $xml.Company.Machines.Machine, so this is the one you want to sort. However, the ReplaceChild method doesn't take a collection, so I'm guessing you'll have to remove all children and then append them back in the order you want them. Something like the following should work fine: ``` [xml]$xml = Get-Content .\Company.xml $machines = $xml.company.machines $orderedMachineCollection = $machines.machine | Sort Name $machines.RemoveAll() $orderedMachineCollection | foreach { $machines.AppendChild($_) } | Out-Null ```
18,859,086
Here's an example of the issue at hand: A product costs 81.25 (that is price including 20% VAT, in other words, 81.25 is equal to 67.71+13.54). I've set the price calculations to the best of my belief (from Extensions->Order Totals) and within Shopping Cart, we'd see the following break-down: A table of the product with thumbnail, description, quantity, price: and last cell says 81.25. Below that: * **Sub-total:** 67.71 (that is price without VAT) * **+20% VAT:** 13.54 (that is the VAT, achieved through Taxes) * **-10% Discount:** -8.13 (all products over $50 receive 10% discount, that is, 10% off of 81.25) * **TOTAL:** 73.12 Unfortunately, our customers are very sensitive to VAT, so the calculation should break-down to: * **-10% discount:** 8.12 (that is 10% off the full price of 81.25) * **Sub-total:** 60.94 (that would be the full price,81.25, minus the 10% discount or 8.12 first and excluding the 20% VAT second) * **+20% VAT:** 12.19 * **TOTAL:** 73.12 As you can see, the Total is the same, but the VAT is different. I've tried a different Total Order from the OpenCart admin, but if I start with Discount, it does not have a previous value to discount in the first place and returns 0. A possible theoretical solution in my mind, perhaps if Total could be duplicated somehow, renamed and inserted hidden in the very first position (so that it would equal 81.25 at the beginning, then discount etc.) that might work. I would really appreciate your ideas.
2013/09/17
[ "https://Stackoverflow.com/questions/18859086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2788421/" ]
`"!"` is a string, you want to compare against a character: `'!'`.
You can't compare `"!"` and `'!'`. I suggest using `rbegin()` to address the last character: ``` text2.append(text.begin(), text.end()); switch(*text.rbegin()) { case '!': case '?': case ':': text2.append(". "); break; } getline(cin, text); if(text.empty()) { cout << "End of session" << endl; break; } ```
62,133,735
Tried to understand the solution for Codility NailingPlanks. Link for the Problem: <https://app.codility.com/programmers/lessons/14-binary_search_algorithm/nailing_planks/> > > You are given two non-empty arrays A and B consisting of N integers. > These arrays represent N planks. More precisely, A[K] is the start and > B[K] the end of the K−th plank. > > > Next, you are given a non-empty array C consisting of M integers. This > array represents M nails. More precisely, C[I] is the position where > you can hammer in the I−th nail. > > > We say that a plank (A[K], B[K]) is nailed if there exists a nail C[I] > such that A[K] ≤ C[I] ≤ B[K]. > > > The goal is to find the minimum number of nails that must be used > until all the planks are nailed. In other words, you should find a > value J such that all planks will be nailed after using only the first > J nails. More precisely, for every plank (A[K], B[K]) such that 0 ≤ K > < N, there should exist a nail C[I] such that I < J and A[K] ≤ C[I] ≤ > B[K]. > > > Link for the solution: <https://github.com/ZRonchy/Codility/blob/master/Lesson12/NailingPlanks.java> ``` import java.util.Arrays; class Solution { public int solution(int[] A, int[] B, int[] C) { // the main algorithm is that getting the minimal index of nails which // is needed to nail every plank by using the binary search int N = A.length; int M = C.length; // two dimension array to save the original index of array C int[][] sortedNail = new int[M][2]; for (int i = 0; i < M; i++) { sortedNail[i][0] = C[i]; sortedNail[i][1] = i; } // use the lambda expression to sort two dimension array Arrays.sort(sortedNail, (int x[], int y[]) -> x[0] - y[0]); int result = 0; for (int i = 0; i < N; i++) {//find the earlist position that can nail each plank, and the max value for all planks is the result result = getMinIndex(A[i], B[i], sortedNail, result); if (result == -1) return -1; } return result + 1; } // for each plank , we can use binary search to get the minimal index of the // sorted array of nails, and we should check the candidate nails to get the // minimal index of the original array of nails. public int getMinIndex(int startPlank, int endPlank, int[][] nail, int preIndex) { int min = 0; int max = nail.length - 1; int minIndex = -1; while (min <= max) { int mid = (min + max) / 2; if (nail[mid][0] < startPlank) min = mid + 1; else if (nail[mid][0] > endPlank) max = mid - 1; else { max = mid - 1; minIndex = mid; } } if (minIndex == -1) return -1; int minIndexOrigin = nail[minIndex][1]; //find the smallest original position of nail that can nail the plank for (int i = minIndex; i < nail.length; i++) { if (nail[i][0] > endPlank) break; minIndexOrigin = Math.min(minIndexOrigin, nail[i][1]); // we need the maximal index of nails to nail every plank, so the // smaller index can be omitted **** if (minIndexOrigin <= preIndex) // **** return preIndex; // **** } return minIndexOrigin; } } ``` I don't understand Line 99-102, marked with `****`, of the solution. My question is: If `minIndexOrigin <= preIndex` , then it will use `preIndex`, but how if the `preIndex` doesn't nail the current plank ? Is there a bit mistake with the solution ?
2020/06/01
[ "https://Stackoverflow.com/questions/62133735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11610073/" ]
<https://app.codility.com/demo/results/trainingR7UKQB-9AQ/> Its a 100% solution. The planks are zipped into (begin, end) pairs and sorted which supports a binary search. For each nail, that nail is used to remove as many planks as possible before failing the search. When the Array of planks is empty the index of the current nail can be returned representing the count of nailed used. O((N + M) \* log(M)) All code is here, <https://github.com/niall-oc/things/blob/master/codility/nailing_planks.py> ``` def find_plank(nail, planks): """ planks is an array of pairs (begin, end) for each plank. planks is sorted by start position of planks """ if not planks: return -1 # empty planks BEGIN_IDX = 0 END_IDX = 1 lower = 0 upper = len(planks)-1 while lower <= upper: mid = (lower + upper) // 2 if planks[mid][BEGIN_IDX] > nail: upper = mid - 1 elif planks[mid][END_IDX] < nail: lower = mid + 1 else: # nail hits plank[mid] return mid # return this plank id so we can pop the plank return -1 def solution(A, B, C): """ Strategy is to sort the planks first. Then scan the nails and do the following. For each nail perform a binary search for a plank. if plank found then pop plank then search again until the nail hits no more planks. The plank list should diminish until it hits zero meaning we have found the minimum number of nails needed If any planks remain then return -1 100% https://app.codility.com/demo/results/trainingR7UKQB-9AQ/ """ if max(B) < min(C) or max(C) < min(A): return -1 # no nail can hit that plank planks = sorted(zip(A,B)) for i in range(len(C)): nail = C[i] p_idx = find_plank(nail, planks) # print(f'idx{i} nail at pos {nail}, matched {p_idx}, in {planks}') while p_idx > -1: del planks[p_idx] p_idx = find_plank(nail, planks) # print(f'idx{i} nail at pos {nail}, matched {p_idx}, in {planks}') if not planks: # print('NO PLANKS', i+1) return i+1 # the index of the nail that removed the last plank. return -1 # else we couldn't remove all planks ```
This is the summary of the entire algorithm. I think who understands it won't have any question in mind. **What we are doing?** 1- Order the nails without losing their original indexes. 2- For each plank, find the min nail value that can nail the plank by using binary search. 3- Find each nail's min original index between min nail value and the end position of the plank, and take the minimum of these min original indexes. 4- Return the maximum of the min nailing original index of each plank. **Why we are doing it?** 1- We don't want to search entire array to find the min index. The original order of the index is what is asked, so we need to store it. 2- We need to find the minimum nail value to limit the number of possible original index needed to be checked. Binary search is required to find the minimum value in logarithmic time complexity. 3- We need to find the original indexes of the candidate nails. The first candidate can be the min nail value, and the last candidate can be the end position of the plank. That's why we check the original indexes only in this interval. 4- We find the min original index of nail for each plank. But the answer will be the maximum of these min indexes since the question asks the index of the last nail we use, when we finish nailing each plank.
18,961,332
This is a two part question: 1. I am using the resolve property inside $stateProvider.state() to grab certain server data before loading the controller. How would I go about getting a loading animation to show during this process? 2. I have child states that also utilise the resolve property. The problem is that ui-router seems to want to finalise **all** resolves before loading *any* controller. Is there any way I can get the parent controllers to load once their resolves have been resolved, without having to wait for all the child resolves? An answer to this will likely also solve the first problem.
2013/09/23
[ "https://Stackoverflow.com/questions/18961332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277697/" ]
How about adding content to the div that will be filled by ui-router once the properties have resolved? In your `index.html` ``` <div ui-view class="container"> Loading.... </div> ``` The user will now see "Loading..." while the properties are resolved. Once everything is ready the content will be replace by ui-router with your apps content.
My idea is to walk the path on state graph between transitioning states on `$stateChangeStart` and collect all involved views. Then every `ui-view` directive watches if corresponding view is involved in transition and adds `'ui-resolving'` class on it's element. The [plunker](http://plnkr.co/edit/YZwGnHfIkSRxOlci8DHm) demo introduces two root states: `first` and `second`, the latter has two substates `second.sub1` and `second.sub2`. The state `second.sub2` also targets `footer` view that belongs to its grandparent.
44,177,869
The installation of Workload Scheduler agent component fails during the step **Start up IBM Workload Scheduler** showing the following message: > > **tebctl-tws\_cpa\_agent\_agt94 agent not installed properly** > > >
2017/05/25
[ "https://Stackoverflow.com/questions/44177869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8002777/" ]
I have solved the issue, the code below hope to help some 1 Swift : ``` @IBAction func uploadimages(_ sender: Any) { Alamofire.upload( multipartFormData: { multipartFormData in var count = 1 for img in self.imagesdata{ let imgdata = UIImageJPEGRepresentation(img, 0.5) // the name should be as array other wise want work multipartFormData.append(imgdata!,withName: "image[]", fileName: "image\(count).jpg", mimeType: "image/jpeg") count += 1 } }, to: "http://localhost/maarathtest/MAPI/img_upload.php", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .failure(let encodingError): print(encodingError) } } ) } ``` PHP code sample : ``` <?php $response = array(); if (empty($_FILES["image"])) { $response['File1'] = "NOFILE"; }else { //$filename = uniqid() . ".jpg"; // loop through files array from IOS app foreach ($_FILES["image"]["tmp_name"] as $index => $tmp_name) { $filePath = "images/" . basename($_FILES["image"]["name"][$index]); if (move_uploaded_file($tmp_name, $filePath)) { // Images are stored in file path , do what ever is needed $response['filepath'][$index] = $filePath; } $response['status'] = "Success"; } } echo json_encode($response); ?> ```
Use this below code to upload multiple images to your server. I've put this in a method that takes in `NSMutableArray` of `UIImage` objects and their corresponding names in another array. You could change `NSMutableArray` to Swift Array if you want. After successful upload, the completion handler will get called and would return a mapped object based on your response: **Code:** ``` public func executeMultipleImageUpload<T: Mappable>(type: T.Type, url: String, parameters: Dictionary<String, String>, images: NSMutableArray?, names: [String], view: UIView, completion: @escaping(_ result: DataResponse<T>?)-> Void) { //Calling Alamofire Upload method here... Alamofire.upload(multipartFormData: { multipartFormData in // This is first param, the part data itself if images == nil || images?.count == 0 { print("There are no images to upload..!!") } else { //Append image data from array of images to multipart form data var count = 1 for image in images! { if let imageData = UIImageJPEGRepresentation(image as! UIImage, 0.76) { multipartFormData.append(imageData, withName: names[count - 1], fileName: names[count - 1], mimeType: "image/jpeg") } count += 1 } } //We are encoding the parameters to be sent here in the multipart as well.. for (key, value) in parameters { multipartFormData.append((value.data(using: .utf8))!, withName: key) }}, to: url, method: .post, headers: ["": ""], //This is second param (to:) encodingCompletion: { encodingResult in // This is third param (encodingCompletion:) switch encodingResult { case .success(let upload, _, _): upload.response { [weak self] response in guard self != nil else { return } debugPrint(response) }.validate().responseObject{ (response: DataResponse<T>) in completion(response) } case .failure(let encodingError): print("error:\(encodingError)") } }) } ```
4,134
I found a way how to add tabs to magento product view, through XML layouts with add tab, where every tab is actually a one phtml template (So I can set description, and attributes in example and retrieve that templates to show in tabs). What I would like to do is to show every attribute as one tab. I suppose I should separate my attributes in separate phtml templates, and then call it in xml. Can someone point me what should the PHP for retrieving attributes be alike? Also how should the XML reference for adding new attribute be alike? I am using 1.7, and my attributes are normal one. Thanks in advance.
2013/05/28
[ "https://magento.stackexchange.com/questions/4134", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/2212/" ]
You can create a setup script which grabs all product attribute sets. Iterate through the attributes which belong to each set, create a group for each attribute, and then set the attribute to that group. *Viola*, solved. Cannot imagine why you would want to do this though.
very short version: As the tabs are part of the product view, we can get the current product via ``` $product = Mage::registry('product') ``` then you should be able to get attributes with something like this: ``` $product->getAttributeText('attributeName') ```
2,652,135
I have captured total desktop using CPP, COM and DirectShow. But how can I capture particular window only?
2010/04/16
[ "https://Stackoverflow.com/questions/2652135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318390/" ]
Another differentiator is that CDI is very Java EE oriented. It provides a mechanism to **glue** the different **Java EE subsystems** together. Ie. By annotating a bean with `@Named("book")`, the bean becomes known in the unified EL (Expression Language) as '`book`'. Then you can use it in a JSF page for instance: ``` <h:outputLabel value="Book title:" for="bookTitle"/> <h:outputText id="bookTile" value="#{book.title}"/> ```
I have used Guice in an AWS Lambda serverless application. AWS recommends using Guice or Dagger over Spring in a Lambda function. See [AWS Lambda best practices](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html) The primary reason is that Guice and Dagger are smaller frameworks and have faster start up time, which is essential in Lambda. Although the OP hasn't mentioned Spring, both Spring and CDI/weld are meant for enterprise level applications, which often require additional features that these frameworks provide. Hence for smaller applications, which only require DI, Guice or Dagger would be optimal.
41,019,686
How do I fill a `CAShapeLayer()` with a gradient and on an angle of 45 degrees? For example, in **Image 1**, the below code draws a square and fills the layer blue (`UIColor.blueColor().CGColor`). But, how do I fill it with a gradient on a 45 degree angle from blue to red like in **Image 2** (i.e. `UIColor.blueColor().CGColor` to `UIColor.redColor().CGColor`)? **Code:** ``` let path = UIBezierPath() path.moveToPoint(CGPoint(x: 0, y: 0)) path.addLineToPoint(CGPoint(x: 0, y: 100)) path.addLineToPoint(CGPoint(x: 100, y: 100)) path.addLineToPoint(CGPoint(x: 100, y: 0)) path.closePath() let shape = CAShapeLayer() shape.path = path.CGPath shape.fillColor = UIColor.blueColor().CGColor ``` [![Solid-color square next to square with gradient](https://i.stack.imgur.com/otWcv.png)](https://i.stack.imgur.com/otWcv.png)
2016/12/07
[ "https://Stackoverflow.com/questions/41019686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4806509/" ]
Why not use `CAGradientLayer` which has `startPoint` and `endPoint` properties. You can do: ``` import UIKit import PlaygroundSupport let frame = CGRect(x: 0, y: 0, width: 100, height: 100) let view = UIView(frame: frame) PlaygroundPage.current.liveView = view let path = UIBezierPath(ovalIn: frame) let shape = CAShapeLayer() shape.frame = frame shape.path = path.cgPath shape.fillColor = UIColor.blue.cgColor let gradient = CAGradientLayer() gradient.frame = frame gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor] gradient.startPoint = CGPoint(x: 0, y: 1) gradient.endPoint = CGPoint(x: 1, y: 0) gradient.mask = shape view.layer.addSublayer(gradient) ``` [![enter image description here](https://i.stack.imgur.com/GkIbX.jpg)](https://i.stack.imgur.com/GkIbX.jpg) Note: Added a bezier path for a circle, because it would work without the mask for the square.
I think it's ``` shape.startPoint = CGPoint(x: 1.0, y: 0.0) shape.endPoint = CGPoint(x: 0.0, y: 1.0) ``` , which is the first color at the bottom-right to the second color at the top-left. If you want the first color at the top-right and second color at the bottom-left, then you should have ``` shape.startPoint = CGPoint(x: 1.0, y: 1.0) shape.endPoint = CGPoint(x: 0.0, y: 0.0) ``` First color at top-left, second color at bottom-right ``` shape.startPoint = NSMakePoint(x: 0.0, y: 1.0) shape.endPoint = NSMakePoint(x: 1.0, y: 0.0) ``` first color at bottom-left, second color at top-right ``` shape.startPoint = CGPoint(x: 0.0, y: 0.0) shape.endPoint = CGPoint(x: 1.0, y: 1.0) ```
31,974,243
I am using Visual Studio Express 2013 for Web, I am attempting to create a new controller in my asp.net MVC application. I am using Entity Framework 5 with code first (.NET 4.5). I want Visual Studio to create the template for me - However, every time I try to create the controller I get the following error message: > > There was an error running the selected code generator: 'unable to > retrieve metadata for 'CII.Domain.Password'. unable to load the > specified metadata resource > > >
2015/08/12
[ "https://Stackoverflow.com/questions/31974243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5216986/" ]
Raising to a power is a relatively quick operation, even using big integers (it takes logarithmic time, excluding the cost of big integer arithmetic). But printing a number is a relatively slow operation (it takes quadratic time). So in your first problem printing the result takes a long time. In your second problem the result is 1, so the time is spent making the calculation, which is fast. On my computer, the first problem takes a little bit less than 2 seconds, then spends several seconds printing the result, and the second problem takes a little bit less than double that, then immediately prints 1.
In Common Lisp you have the `time` macro: ```lisp (time (progn (expt 123456 123456) 1)) ; Real time: 0.578002 sec. ; Run time: 0.577577 sec. ; Space: 733816 Bytes ; GC: 1, GC time: 0.007143 sec. ; ==> 1 (time (progn (princ (expt 123456 123456)) 1)) ; a whole lot of numbers ...6 ; Real time: 59.980278 sec. ; Run time: 59.017193 sec. ; Space: 8490376 Bytes ; GC: 4, GC time: 0.033218 sec. ; ==> 1 ``` The differemnces between these are the producing of the the numbers in a human readable and decimal manner and getting it out on the slow console. The second should use about double the time of the first expression: ```lisp (time (/ (expt 123456 123456) (expt 123456 123456))) ; Real time: 1.120879 sec. ; Run time: 1.11894 sec. ; Space: 1728656 Bytes 1 ``` Indeed it does.. How about just printing the result of the first expression: ```lisp (let ((value (time (expt 123456 123456)))) (time (princ value)) 1) ; Real time: 0.584907 sec. (pretty much the same time calculating the result) ; Run time: 0.584398 sec. ; Space: 733816 Bytes ; GC: 1, GC time: 0.020312 sec. ; lots of digits ...56 ; Real time: 59.803486 sec. about the same time it took printing it last time ; Run time: 58.414997 sec. ; Space: 2514768 Bytes ; GC: 1, GC time: 0.002712 sec. ; ==> 1 ``` I don't think I need to repeat this in Scheme. Console is slow, arithmetic in CL and Scheme is fast, even with bignums. **EDIT** I actually did make a script and redirected it to a file and it took around the same amount of time. Thus most of the time is used to convert the bignum into human readable chars and not actually getting it out on the console. If it was the console redirecting it to a file would drastically speed up the whole process.
14,168,030
I know my code is bad and unsafe and everything but I just want it to overall work before I start making changes. So i am making a little basic shop, and I want it to check the user to see if he has the right amount of money, and if he does, subtract the amount of money the item costs and give him the item, if he does not have the right amount, I want it not to subtract any and not give him the item and echo that he cannot afford the item. I tried to do it with no success so I deleted most of the code and was hoping to get a little help here. This is what I still have. if I take out the if statement it will minus the the money and add the item, but I need the restrictions on it. I am very new to all of this so any help is appreciated :) ``` $sql23 = "SELECT * FROM users WHERE username='".$_SESSION['username']."')"; $result = mysql_query("SELECT * FROM users WHERE username='".$_SESSION['username']."'"); while($row = mysql_fetch_array($result)){ echo $row['money']; if (isset($_POST['pokeball'])) { if ($row['money'] >= 2000) { echo "You have bought a pokeball!" ; mysql_query("UPDATE users SET money=money-2000 WHERE username = '".$_SESSION['username']."'") or die(mysql_error()); mysql_query("UPDATE users SET pokeball=pokeball+1 WHERE username = '".$_SESSION['username']."'") or die(mysql_error()); } else { echo "You can't afford a pokeball!"; } } } ```
2013/01/05
[ "https://Stackoverflow.com/questions/14168030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908445/" ]
As you've pointed out your code is not great, however in answer to your actual question/problem. As the whole thing hinges on one if statement, everything that is suppose to happen should be inside that if statement. ``` $sql23 = "SELECT * FROM users WHERE username='".$_SESSION['username']."')"; $result = mysql_query("SELECT * FROM users WHERE username='".$_SESSION['username']."'"); while($row = mysql_fetch_array($result)){ echo $row['money']; if (isset($_POST['pokeball'])) { if ($row['money'] >= 2000) { echo "You have bought a pokeball!" ; mysql_query("UPDATE users SET money=money-2000 WHERE username = '".$_SESSION['username']."'") or die(mysql_error()); mysql_query("UPDATE users SET pokeball=pokeball+1 WHERE username = '".$_SESSION['username']."'") or die(mysql_error()); } else { echo "You can't afford a pokeball!"; } } ``` } Also note mysql\_query is depreciated and should be replaced with mysqli\_query : <http://php.net/manual/en/mysqli.query.php>
``` <?php $playermoney = mysql_query("SELECT * FROM users WHERE username = '".$_SESSION['username']."'") or die(mysql_error()); if (isset($_POST['pokeball'])) { if ($row['money'] >= 2000) { echo "You have bought a pokeball!" ; mysql_query("UPDATE users SET money=money-2000,pokeball=pokeball+1 WHERE username = '".$_SESSION['username']."'") or die(mysql_error()); } else { echo "You can't afford a pokeball!"; } ?> ```
40,627,447
There are simple filter from shared library ```js .filter('minutes2hm', function () { return function (min, apply) { if (apply === false) { return min; } var h = Math.floor(min / 60).toString(); min = (min - (h * 60)).toString(); return '' + '00'.substring(0, 2 - h.length) + h + ':' + '00'.substring(0, 2 - min.length) + min; }; ``` And html ```html <th>{{minutes-125 | minutes2hm: false}}</th> --> 125 <th>{{minutes-125 | minutes2hm: true}}</th> --> 02:05 ``` I want move true|false to user settings ```html <th>{{minutes-125 | minutes2hm}}</th> ``` ```js .filter('minutes2hm', function () { return function (min) { if (USERSettings.apply === false) { return min; } ... }; ``` Which way is best practics for * save user settings * use user setting in filters which allow share filter code beetween project in result?
2016/11/16
[ "https://Stackoverflow.com/questions/40627447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534802/" ]
If shared filter is in use in different places then first of all create second custom filter with **different name**, next get user settings from service ( filters can use dependency injections ), and last one - call "old" filter in custom filter by `$filter` service, example usage: ``` app.filter('userMinutes2hm', function($filter,$userSettings) { return function(min) { return $filter('minutes2hm')(min,$userSettings.apply); //use filter in filter with param from service } }); ``` PS. I see that You have global variable `USERSettings`, it is wrong practice, create some service for user settings ( `$userSettings` ) like I showed above. --- Summary: best practice is to use service with global settings instead of global variables outside angular. Services are singletons so can also store/save data, if You want to store data permanently then service can use for example localStorage for that.
Why you using this below code? and what is the Use of the below code? ``` if (apply === false) { //and if (USERSettings.apply === false) return min; } ``` If you won't use filter, then don't call the filter on your `<th>`. Why you need pass `true|False` So if you remove that code, then your `<th>` and result should be looks like this ``` <th>{{minutes-125 </th> --> 125 <th>{{minutes-125 | minutes2hm}}</th> --> 02:05 ``` and filter code looks like ``` .filter('minutes2hm', function () { return function (min) { var h = Math.floor(min / 60).toString(); min = (min - (h * 60)).toString(); return '' + '00'.substring(0, 2 - h.length) + h + ':' + '00'.substring(0, 2 - min.length) + min; }; ```
8,306,170
I have this program which worked find in my college lab, but when I run it at my home it gives different result ``` #include <stdio.h> int main(int argc, char* argv[]) { const int size=100; int n, sum=0; int* A = (int*)malloc( sizeof(int)*size ); for (n=size-1; n>0; n--) A[n] = n; for (n=0;n<size; n++) sum += A[n]; printf ("sum=%d\n", sum); return 0; } ``` I'm expecting `4950` as result but I keep getting different result like `112133223`. Why is this happening ?
2011/11/29
[ "https://Stackoverflow.com/questions/8306170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070616/" ]
You never assign a value to A[0] - the first loop ends to quickly. However you do include this unassigned value in the summation.
`A[0]` is undefined: `for (n=size-1; n>0; n--)` should be `for (n=size-1; n>=0; n--)`
49,669,049
My code to resize images is : ``` from PIL import Image ratio = 0.2 img = Image.open('/home/user/Desktop/test_pic/1-0.png') hsize = int((float(img.size[1])*float(ratio))) wsize = int((float(img.size[0])*float(ratio))) img = img.resize((wsize,hsize), Image.ANTIALIAS) img.save('/home/user/Desktop/test_pic/change.png') ``` what i have tried is: The different options other than `.ANTIALIAS` <https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize> Adding the parameter `quality` when saving `img.save('/home/user/Desktop/test_pic/change.png',quality=95)` Converting to rgb `img = img.convert("RGB").resize((wsize,hsize), Image.ANTIALIAS)` the thing is my images are full of small texts in the original image so really need a good outcome when they're resized to be able to process them further or even read them.
2018/04/05
[ "https://Stackoverflow.com/questions/49669049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9533220/" ]
Masking with `0xFF` reduces any negative values into the range 0-255. This is reasonable if, for example, your platform's `char` is an 8-bit signed type representing ISO-8859-1 characters, and your `wchar_t` is representing UCS-2, UTF-16 or UCS-4. --- Without this correction (or something similar, such as casting to `unsigned char` or `std::byte`), you would find that characters are sign-extended when promoted to the wider type. Example: 0xa9 (`©` in Unicode and Latin-1, -87 in signed 8-bit) would become `\uffa9` instead of `\u00a9`. --- I think it's clearer to convert the `char` to an `unsigned char` - that works for any size char, and conveys the intent better. You can change that expression directly, or create a `codecvt` subclass that gives a name to what you're doing. Here's how to write and use a minimal `codecvt` (for narrow → wide conversion only): ``` #include <codecvt> #include <locale> #include <string> class codecvt_latin1 : public std::codecvt<wchar_t,char,std::mbstate_t> { protected: virtual result do_in(std::mbstate_t&, const char* from, const char* from_end, const char*& from_next, wchar_t* to, wchar_t* to_end, wchar_t*& to_next) const override { while (from != from_end && to != to_end) *to++ = (unsigned char)*from++; from_next = from; to_next = to; return result::ok; } }; std::wstring convert(const std::string& input) { using codecvt_utf8 = std::codecvt_utf8<wchar_t>; try { return std::wstring_convert<codecvt_utf8>().from_bytes(input); } catch (std::range_error&) { return std::wstring_convert<codecvt_latin1>{}.from_bytes(input); } } ``` ``` #include <iostream> int main() { std::locale::global(std::locale{""}); // UTF-8: £© おはよう std::wcout << convert(u8"\xc2\xa3\xc2\xa9 おはよう") << std::endl; // Latin-1: £© std::wcout << convert("\xc2\xa3\xa9") << std::endl; } ``` Output: ```none £© おはよう £© ```
It looks like on conversion failure the code tries its own conversion by just copying the `string` into a `wstring` char for char. The `& 0FF` is meant to "clean" any values higher than 255 to fit in the (extended) ASCII table. This is a no-op however because `input[i]` returns `char` and `sizeof(char) == 1` which would mean that 255 is the maximum value anyway (In the case of `CHAR_BIT == 8` and `char == unsigned char`). The equivalent would just be to copy them over right away using the constructor: ``` std::wstring result(input.begin(), input.end()); ```
67,133
I have a relationship like this: Class Student Lookup on Student Contact Student Master-Detail on Student I want to create a visualforce page to create new Class and on the same page add Student to the class. I created a controller extension of Class's controller. I am now stuck on adding student for the class. I have several requirements here: 1.I want to add a lookup field to add student to the class. (However, I'm on the parent object and how can I add this lookup field?) 2.I want to be able to create new student on the page. Is there a way to do this? 3.I want to be able to add students by importing a file containing student ids. Is there a way to do this? Appreciated!
2015/02/22
[ "https://salesforce.stackexchange.com/questions/67133", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/11923/" ]
You are not able to add students as you are using a master detail relationship on student with contact. So for adding a student u should also add the contact id in the master detail relationship of contact. Example. ``` Class__C cl = new Class__c(); Student__C std = new Student__c(); Contact con = new Contact(); //Add all the class information then insert the class insert cl; //Add all the information of contact and create a new contact insert con; //Add all the information of Student and then.... std.contact = con.id; std.class__c = cl.id; insert std; ```
It's worth spending some time with *[Visualforce in Practice](http://www.developerforce.com/guides/Visualforce_in_Practice.pdf)*. The book has a whole section on creating "wizards" in Visualforce. The gist of the situation is that you're going to want to pass a few page references around to step your user through the process of creating a class then adding students.
15,959,544
I'm having an issue getting my model.destroy method to work properly in backbone. This is my function ``` deleteEvent: function(){ var self = this; var check = confirm("Are you sure you want to remove record " + this.model.get("ticket_id")); if (check == true){ this.model.id = this.model.get('session_id'); this.model.destroy({ wait: true, success: function(model, response, options){ console.log(options); console.log(response); self.$el.remove(); }, error: function(model, xhr, response){ console.log("ERROR:"); console.log(model); console.log(xhr); console.log(response); } }); } else return; }, ``` The model looks like this: ``` vkapp.EventRecordModel = Backbone.Model.extend({ urlRoot: '/user_event', idAttribute:"_id", defaults: { "ticket_id": '', "start": '', "end": '' }, validate: function(attrib){ //This is only called when setting values for the model, not on instantiation if (attrib.ticket_id == null) alert("no ticket number"); if (attrib.start == undefined) alert("no start time"); if (attrib.end == null) alert("no end time"); if (attrib.start > attrib.end) alert("start can't be before the end time."); } ``` }); And this is what the route looks like in my sinatra. ``` delete '/user_event/:session_id' do user_event = ProjectTimer.get(:session_id => params[:session_id]) user_event.destroy end ``` I am not sure why I am getting an error return.
2013/04/11
[ "https://Stackoverflow.com/questions/15959544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272207/" ]
You need to set `paragraphy` and `linebreaks` settings like this : ``` $('#redactor').redactor({ linebreaks: true, paragraphy: false }); ```
``` $("#editor").redactor({ pasteBeforeCallback: function (html) { return html.replace(/<p>\s*<\/p>/g, " "); } }); ```
78,334
Given two polynomials `f,g` of arbitrary degree over the integers, your program/function should evaluate the first polynomial in the second polynomial. `f(g(x))` (a.k.a. the *composition* `(fog)(x)` of the two polynomials) ### Details Builtins are allowed. You can assume any reasonable formatting as input/output, but the input and output format should match. E.g. formatting as a string ``` x^2+3x+5 ``` or as as list of coefficients: ``` [1,3,5] or alternatively [5,3,1] ``` Furthermore the input polynomials can be assumed to be fully expanded, and the outputs are also expected to be fully expanded. ### Examples ``` A(x) = x^2 + 3x + 5, B(y) = y+1 A(B(y)) = (y+1)^2 + 3(y+1) + 5 = y^2 + 5y + 9 A(x) = x^6 + x^2 + 1, B(y) = y^2 - y A(B(y))= y^12 - 6y^11 + 15y^10 - 20y^9 + 15y^8 - 6y^7 + y^6 + y^4 - 2 y^3 + y^2 + 1 A(x) = 24x^3 - 144x^2 + 288x - 192, B(y) = y + 2 A(B(y)) = 24y^3 A(x) = 3x^4 - 36x^3 + 138x^2 - 180x + 27, B(y) = 2y + 3 A(B(y)) = 48y^4 - 96y^2 ```
2016/04/23
[ "https://codegolf.stackexchange.com/questions/78334", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
TI-Basic 68k, 12 bytes ====================== ``` a|x=b→f(a,b) ``` The usage is straightforward, e.g. for the first example: ``` f(x^2+3x+5,y+1) ``` Which returns ``` y^2+5y+9 ```
[PARI/GP](http://pari.math.u-bordeaux.fr/), 19 bytes ==================================================== ``` (a,b)->subst(a,x,b) ``` which lets you do ``` %(x^2+1,x^2+x-1) ``` to get > > %2 = x^4 + 2\*x^3 - x^2 - 2\*x + 2 > > >
59,906,505
Need a PowerShell regular expression pattern to delete left behind folders that were extracted by windows patches from root of C drive ``` c:\0260cbbd38dbbbea2543f8 c:\096ea4b36d877b65dc6c c:\0cf52cad06ab7b5cfe2b4042c8 c:\0d90c7a3bdd67a5212aa527bc49b c:\0e2180b528a8c152566816291c2252 c:\1050411ef7c0228177 c:\120dc98c3c427148e0e847 c:\1266b191a6041be04da921 c:\134f4bae5dcd171cba9d795c c:\163037d9459286ec00226ecba86c6b c:\19c5e16d96cff11fb276 c:\1a45ab7c977d005fa74016 c:\1ce14958a6b03c4fbdd0aa7595 c:\1d4dd4b97f3bc25610224b794970 c:\1e8dca560de070e9c7ce5ea666b1a2 c:\225f0c8c83d4680dcaf7f3 c:\27d0be422124c8e6895f55a2d92e6b45 c:\27e73ccf209a2d26b918bae979003e62 c:\2cbfba046b23288dda36b27681 c:\2d19c1e6f0c6d79a27f11258ed5a c:\3368da3dec9eaf0c1bd2aa3e c:\3572040545b171d83e9a8edbc517 c:\3651fe9fb1a4d98c8752b834c823fb c:\37bc2d84450d0712ba434ab58b9be3b5 c:\397ede84503ab8705c61 c:\39b805b4909ca6ab7444 c:\3c3c48d33d8849a8738b547e9a c:\3c4b849f11f1f97e739d91f23f c:\406699ef4baa3836e6 c:\430dca3d98c1433dbb06c41b c:\438f43589bf4d2e91de92257 c:\442b9d9e1f12d6527a355fbb94 c:\444fc210df5624fc57ed431b41 c:\4e80466bc0bd9a225a1d0c6c49eda3 c:\513f6e8fd2ec94ee80e1 c:\527c723b1c15e5ad1777f0 c:\52c8c81ce00ef83612bea8 c:\52cf084fe6416eac75251f c:\53bcd710184608538ed626f9 c:\5555c66e2524b093ccde17168dc2 c:\576e7da4ab59dff0a4fc453bd09ce380 c:\58af12fd0051615253 c:\595108cb19dd9e45343e c:\5c0519db74ebb86fa611ca76a2 c:\5c18f69a206888d586d0d6bfe1 c:\5dad9ce7201f38aca9fd6fbc63f3 c:\64cf5b2b98e7bfd45bf258b06e c:\66a725a452271ff883431f2dd7b0f1 c:\68b4cee980651b3fbc c:\718c43ef809499044a3c c:\734073c2f7eda3b4c38a19e0 c:\737a421b02032d614a7a1c45 c:\74edd213e1fe718df94032a51d c:\781f57f5ac41af00be c:\7af4485cc5429456445957 c:\7d2d566780048cba452b03c6b263 c:\7fe3e7297a62e48255533539033ee50c c:\8228bc4c03fd5b2f1ebb24 c:\83ad2f96485c40340a2cd782 c:\88a6f42b17c78a0638 c:\88fd60c16b19a0cf73 c:\8a588e86a91e3ca897f542 c:\8acdfcd173abff9029beb5 c:\8b9e7e1b322c408d340970f0 c:\8ff8bb90108d7627eb1267d09ba0fb55 c:\90b7703a90a2c24c7b c:\93d276f9dc924a406a6ed01b c:\9c7ef323ec48ed5587661b4693 c:\a1eb22f89d6a07c904db c:\a47813cc369c82be7143f47185 c:\a49ce62ce9ce98096931d23c51 c:\a61924dfd4704703d5e39c5281d29e c:\a63849d1d3bbd85790ee4a01299bd6 c:\a753ff49744ccadded681251d331d35f c:\ad975367f3e001f51a14c9908b23 c:\b0face991a3ad869ca c:\b82598682fc78f9305 c:\ba8a744c5b959384186bc4 c:\babdd0ba0a07d3c9223cef c:\bc0b82ac0babb98b8342350bc8 c:\bdc2d2f2f3bc01003a91fe0e1459 c:\c0fae0409a0b10ea75 c:\c1180e96da82fae50747 c:\c4f0fd540da02906b56741b3c9 c:\ca7f59e621d33ce834ba0d c:\cd19f0d28269630b2a63986edd91 c:\d486081e034c03d07b7fdc7d25 c:\d4f6b9fd6bf99442f9ccf0dae3 c:\d557a9f6fa2474f0d1622c381b03 c:\d571c66922d2adca2707b43c4d91 c:\d628ab789f80774608696b5ab49702 c:\d78bc5349052849aaca6eea917eb6f97 c:\db7cbb79e4cec11e0750e59c c:\db7d5b6b5ea0efe9b7bcf9cf c:\de2be517ad36995b3045c5288bd68f c:\e0a72cd7cc448809cb c:\e196772ec200ace6dcbd c:\ea3a0fea3bdf080ee65b60 c:\ec1b70f46f6fe0088a451a1662 c:\f04ab325c03a1380ca c:\f3f4d3bf0fb6fdc477c13c99 c:\f43507f18e2024ffdb8ad2b189 c:\f54ce6242b345e5cf3946c98f585 c:\f65be2c2b3f903d1e8b82942fd5e8f c:\f7f6d21a696415c6b8b2869988dee5f6 c:\fbe5089abb1a64e9b560ac32 c:\ffeb5928a51b311728428591da5683e2 ``` this gets me all that start with the number, but need a more solid pattern, as well as the one that starts with the letter to make sure I'm not accidently deleting other windows directories without using exclusion filter ``` gci c:\ | ? {$_.name -match '^[^a-zA-Z].*'} ```
2020/01/25
[ "https://Stackoverflow.com/questions/59906505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11104335/" ]
here is a slightly different way to determine if the dir name is a hexadecimal string. [*grin*] what it does ... * creates a list of dirinfo items you will need to get that via `Get-ChildItem` with the appropriate selectors to get only directories. * iterates thru the list * checks to see if the string contains ONLY hexadecimal chars note that i added 3 items with invalid chars - the 2nd, 4th, and 6th items. * write out an "is/is not" message the code ... ``` # fake reading in a list of directories # in real life, use Get-ChildItem -Directory $InStuff = @( [System.IO.DirectoryInfo]'c:\0260cbbd38dbbbea2543f8' [System.IO.DirectoryInfo]'c:\zzz096ea4b36d877b65dc6c' [System.IO.DirectoryInfo]'c:\0cf52cad06ab7b5cfe2b4042c8' [System.IO.DirectoryInfo]'c:\0d90c7a3bdd67-q-w-r-t' [System.IO.DirectoryInfo]'c:\0e2180b528a8c152566816291c2252' [System.IO.DirectoryInfo]'c:\1050_411ef7c0228177' [System.IO.DirectoryInfo]'c:\120dc98c3c427148e0e847' ) foreach ($IS_Item in $InStuff) { $IsHex = $IS_Item.Name -match "[a-f0-9]{$($IS_Item.Name.Length)}" if ($IsHex) { Write-Host ('{0} _is_ a hexadecimal string.' -f $IS_Item) } else { Write-Warning (' {0} is not a hexadecimal string.' -f $IS_Item) } } ``` i leave it to you to write the deletion code. [*grin*]
To find **all** folders with names contaning only hexadecimal characters (only digits 0..9 and letters a..f): ``` Get-ChildItem -Path 'C:\' -Directory -Force | Where-Object { $_.Name -match '^[a-f\d]+$' } ``` To find only those starting with a digit: ``` Get-ChildItem -Path 'C:\' -Directory -Force | Where-Object { $_.Name -match '^[\d][a-f\d]+$' } ``` To find only those starting with a letter a..f: ``` Get-ChildItem -Path 'C:\' -Directory -Force | Where-Object { $_.Name -match '^[a-f][a-f\d]+$' } ``` Hope that helps The regex `-match` operator works case-insensitive, so no need to use `[a-fA-F]` P.S. Since you also tagged this question with `PowerShell-2.0`, for versions below 3.0, there is no `-Directory` switch and you need to specify this in the `Where-Object` clause like: ``` Get-ChildItem -Path 'C:\' -Force | Where-Object { $_.PSIsContainer -and $_.Name -match '^[a-f][a-f\d]+$' } ```
7,123,666
I have a table that I'm styling with CSS. Yes I know, tables are bad and all that. I want the "grid" of TD's to all have the height of the row they are positioned in. <http://jsfiddle.net/p87Bv/1/> You'll see if they have varying content, they look all jumbled up! Would prefer not to use Javascript.
2011/08/19
[ "https://Stackoverflow.com/questions/7123666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/852025/" ]
tables are not automatically bad. tables are perfect for displaying tabular data... even though that doesn't seem to be what you are doing. move the style from the div to the table cell...check out my updated fiddle for some CSS changes. i think you could remove the divs from the markup now that they aren't being used for anything via CSS <http://jsfiddle.net/p87Bv/5/>
It's hard to understand your question. Maybe you can clarify - is this what you're looking for? Also notice how the overflowing text is in a scrollable div - more on that later. Link: <http://jsfiddle.net/ZFHUm/> If it is, it's as simple as adding the height CSS property. Also, it's always good to address the text overflow, especially in this manner, in case the text inside the table row (div) is larger than the div itself. Add these to the 'table td div' property to achieve the affect in the new fiddle: ``` height:200px; /* or whatever height you'd like them to be */ overflow:auto; /* makes all overflowing text have a scrollbar */ ```
57,841,303
![1](https://i.stack.imgur.com/QsJc9.png) How to change the red conatiner after pressing the continue button? In place of red container a new container should be formed having text field as phone number and other things should be as it is. Only red container is needs to be changed.
2019/09/08
[ "https://Stackoverflow.com/questions/57841303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12037323/" ]
Put your sub query into temp table : ``` DECLARE @tdate DATETIME = '2019-09-01 00:00:00.000' SELECT holdingNo into #TmpholdingNo FROM [db_land].[dbo].tbl_bill WHERE year(date_month) = YEAR(@tdate) AND MONTH(date_month) = MONTH(@tdate) AND ( update_by IS NOT NULL OR ispay = 1 ) SELECT c.id AS clid, h.id AS hlid, h.holdinNo, c.cliendID, c.clientName, h.floor, h.connect_radius FROM [db_land].[dbo].tbl_client AS c INNER JOIN [db_land].[dbo].tx_holding AS h ON c.id = h.clid WHERE h.status = 1 AND h.connect_radius IS NOT NULL AND c.status = 1 AND h.type = 'Residential' AND h.holdinNo NOT IN (SELECT holdingNo from #TmpholdingNo) drop table #TmpholdingNo ```
give a try try this: ``` select main.* from (SELECT c.id AS clid, h.id AS hlid, h.holdinNo, c.cliendID, c.clientName, h.floor, h.connect_radius FROM [db_land].[dbo].tbl_client AS c INNER JOIN [db_land].[dbo].tx_holding AS h ON c.id = h.clid WHERE h.status = 1 AND h.connect_radius IS NOT NULL AND c.status = 1 AND h.type = 'Residential')main left join (select holdingNo from (SELECT holdingNo, update_by, ispay FROM [db_land].[dbo].tbl_bill WHERE year(date_month) = YEAR(@tdate) AND MONTH(date_month) = MONTH(@tdate))bill1 where update_by IS NOT NULL OR ispay = 1)bill2 on main.holdinNo = bill2.holdinNo where bill2.holdinNo is null ```
35,651,567
I have a string array of the same primitive type (don't know what). I need to convert that into the corresponding type. Is there any way if I pass a string and get the primitive type of the data if any in that string. Consider the string is supposed to be having a primitive type or it is treated as String For e-g ``` "5.2" - double "5" - int (most related) "s" - char ``` So that, if it is double, i can parse using `Double.parseDouble`
2016/02/26
[ "https://Stackoverflow.com/questions/35651567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5678086/" ]
No, that is not possible. For example this input: ``` 5 ``` * This could be an **int** * But it could also be a **byte**, **short** or **long** * It could as well be a **float** or a **double** * It could even be a **char** The only thing we know about it is, that it is probably not a **boolean**. --- You could of course also try to parse your string like this: ``` public static void main(String[] args) { checkType("5.2"); checkType("5"); checkType("s"); } protected static void checkType(String input) { System.out.println(input); try { byte result = Byte.parseByte(input); System.out.println("could be interpreted as byte "+result); } catch (NumberFormatException e) { System.out.println("not an byte"); } try { short result = Short.parseShort(input); System.out.println("could be interpreted as short "+result); } catch (NumberFormatException e) { System.out.println("not an short"); } try { int result = Integer.parseInt(input); System.out.println("could be interpreted as int "+result); } catch (NumberFormatException e) { System.out.println("not an int"); } try { long result = Long.parseLong(input); System.out.println("could be interpreted as long "+result); } catch (NumberFormatException e) { System.out.println("not an long"); } try { float result = Float.parseFloat(input); System.out.println("could be interpreted as float "+result); } catch (NumberFormatException e) { System.out.println("not an float"); } try { double result = Double.parseDouble(input); System.out.println("could be interpreted as double "+result); } catch (NumberFormatException e) { System.out.println("not an double"); } try { boolean result = Boolean.parseBoolean(input); System.out.println("could be interpreted as boolean "+result); } catch (NumberFormatException e) { System.out.println("not a boolean"); } if (input.length() == 1) { System.out.println("could be interpreted as character "+input); } else { System.out.println("not a character"); } System.out.println(); } ``` For the given examples, it outputs: ``` 5.2 not an byte not an short not an int not an long could be interpreted as float 5.2 could be interpreted as double 5.2 could be interpreted as boolean false not a character 5 could be interpreted as byte 5 could be interpreted as short 5 could be interpreted as int 5 could be interpreted as long 5 could be interpreted as float 5.0 could be interpreted as double 5.0 could be interpreted as boolean false could be interpreted as character 5 s not an byte not an short not an int not an long not an float not an double could be interpreted as boolean false could be interpreted as character s ```
Java Strings are abstractions for characters and see nothing but characters. The String itself does not know what kind of representations are inside of it, other than that it is all a homogeneous(exclusive to) collection of characters. If you are being mislead by the "+" operator. This operator condenses what you are *concatenating* to the object, and as the object is concatenated, it is converted to a string of characters, so your data is indeed lost. You will need to analyze the string yourself to decide if it contains information meaningful to you and extract it. It is possible to create your own string that is capable of storing such information, but it bloats the construct, since you rarely need to use such features, and they may as well be used externally. It would be more helpful to post what you are trying to accomplish instead of abstract possibility claim. To which the answer is yes, you can do that, but the string will not help you do it, you will need to parse the string yourself. See "<http://asciivalue.com/>" to see that any string you enter essentially hides away this data almost exclusively(as well as a terminating 0 usually). If it had to store the data you are asking in your question, it would be too expensive to store.
46,822
I came across the following problem: > > Show that if $x$ and $y$ are real numbers with $x <y$, then there exists an irrational number $t$ such that $x < t < y$. > > > We know that $y-x>0$. By the Archimedean property, there exists a positive integer $n$ such that $n(y-x)>1$ or $1/n < y-x$. There exists an integer $m$ such that $m \leq nx < m+1$ or $\displaystyle \frac{m}{n} \leq x \leq \frac{m+1}{n} < y$. This is essentially the proof for the denseness of the rationals. Instead of $\large \frac{m+1}{n}$ I need something of the form $\large\frac{\text{irrational}}{n}$. How would I get the numerator?
2011/06/22
[ "https://math.stackexchange.com/questions/46822", "https://math.stackexchange.com", "https://math.stackexchange.com/users/12378/" ]
**Suggestion**: I expect that you can use the fact that $\sqrt{2}$ is irrational. From the denseness of the rationals, you know that there is a non-zero rational $r$ such that $$\frac{x}{\sqrt{2}} <r <\frac{y}{\sqrt{2}}.$$ Now it's essentially over. (I almost forgot to insist that $r$ be non-zero!)
One way to show this would be to use the fact that the rationals are countable, whereas the interval $(x,y)$ is uncountable (these facts must be proven, though), and therefore $(x,y)$ must contain some irrational number $t$, which will satisfy $x<t<y$.
206,820
I would like to either prevent or handle a `StackOverflowException` that I am getting from a call to the `XslCompiledTransform.Transform` method within an `Xsl Editor` I am writing. The problem seems to be that the user can write an `Xsl script` that is infinitely recursive, and it just blows up on the call to the `Transform` method. (That is, the problem is not just the typical programmatic error, which is usually the cause of such an exception.) Is there a way to detect and/or limit how many recursions are allowed? Or any other ideas to keep this code from just blowing up on me?
2008/10/15
[ "https://Stackoverflow.com/questions/206820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27109/" ]
By the looks of it, apart from starting another process, there doesn't seem to be any way of handling a `StackOverflowException`. Before anyone else asks, I tried using `AppDomain`, but that didn't work: ``` using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading; namespace StackOverflowExceptionAppDomainTest { class Program { static void recrusiveAlgorithm() { recrusiveAlgorithm(); } static void Main(string[] args) { if(args.Length>0&&args[0]=="--child") { recrusiveAlgorithm(); } else { var domain = AppDomain.CreateDomain("Child domain to test StackOverflowException in."); domain.ExecuteAssembly(Assembly.GetEntryAssembly().CodeBase, new[] { "--child" }); domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => { Console.WriteLine("Detected unhandled exception: " + e.ExceptionObject.ToString()); }; while (true) { Console.WriteLine("*"); Thread.Sleep(1000); } } } } } ``` If you do end up using the separate-process solution, however, I would recommend using `Process.Exited` and `Process.StandardOutput` and handle the errors yourself, to give your users a better experience.
You can read up this property every few calls, `Environment.StackTrace` , and if the stacktrace exceded a specific threshold that you preset, you can return the function. You should also try to replace some recursive functions with loops.
492,115
what is the proper contour for $$\int\_{-\infty}^{\infty}\frac{e^z}{1+e^{nz}}dz:2\leq n$$ I tried with rectangle contour but the problem which I faced how to make the contour contain all branches point because $1+e^{nz}=0$ for every $z=\frac{2k+1}{n}$ :$k\in Z$ ,or how to avoid them
2013/09/12
[ "https://math.stackexchange.com/questions/492115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/58529/" ]
Set $w=nz$, then your integral is equal to $\displaystyle\frac{1}{n}\int\_{\mathbb R}\frac{e^{w/n}}{1+e^w}\,dw=\frac{I}{n}$. Now, for $M>0$ big, consider the following rectangle contour: $$t\_1\in[-M,M],\\ M+t\_2i,\,t\_2\in[0,2\pi],\\t\_3+2\pi i,\,t\_3\in[M,-M],\\-M+t\_4i,t\_4\in[2\pi,0].$$ On the second line, $$|I|\leq\int\_0^{2\pi}\left|\frac{e^{M/n+ti/n}}{1+e^{M+ti}}\right|\,dt\leq\int\_0^{2\pi}\frac{e^{M/n}}{|e^{M+ti}|-1}\,dt\leq2\pi\frac{e^{M/n}}{e^M-1},$$ which goes to $0$ as $M\to\infty$. Similarly for the fourth line. On the third line, we get $$-\int\_{-M}^M\frac{e^{t/n+2\pi i/n}}{1+e^{t+2\pi i}}\,dt\to-e^{2\pi i/n}I,$$ as $M\to\infty$. Now, the residue on $\pi i$ is equal to $-e^{\pi i/n}$, so you have that $$I(1-e^{2\pi i/n})=-2\pi ie^{\pi i/n}\Rightarrow I=\frac{2\pi i}{e^{\pi i/n}-e^{-\pi i/n}}=\frac{\pi}{\sin(\pi/n)},$$ therefore your integral is equal to $\displaystyle\frac{\pi/n}{\sin(\pi/n)}$.
Here is another solution for diversity. In your integral, let $x\mapsto\log x$, so it becomes $$\int\_{0}^\infty \frac{dz}{1+z^n}=\frac{1}{n}\int\_{0}^\infty \frac{z^{1/n-1}\,dz}{1+z}$$ The latter integral can be solved with a keyhole contour (and this avoids the branch cut along $\mathbb R^+$), as the integrand disappears around $\infty$. The residue at $-1$ equals $$b= e^{i\pi(1/n-1)}$$ where we use the principal branch of $\log$. As the argument increases by $2\pi$, the integrand multiplies by $e^{2\pi i (1/n-1)}$ $$\left(1-e^{2\pi i (1/n-1)}\right)\int\_{0}^\infty \frac{z^{1/n-1}\,dz}{1+z}=2\pi i e^{i\pi(1/n-1)}\implies \int\_{0}^\infty \frac{z^{1/n-1}\,dz}{1+z} = \pi \csc\left(\frac \pi n\right)$$ Multiplying this by $1/n$, we obtain the value: $$\frac{\pi}{n\sin\left(\frac{\pi}{n}\right)}$$
26,847,594
I have a multi-project (Android) build with library *L*, app *A*, and examples *E1*, *E2*, *E3* (and possibly more). The directory layout is: ``` root (contains `settings.gradle` and `build.gradle`) | +- A (contains `build.gradle`) | +- L (contains `build.gradle`) | +- examples | +- E1 (contains `build.gradle`) | +- E2 (contains `build.gradle`) | +- E3 (contains `build.gradle`) ``` *A* depends on *L*, and each *E<n>* also depends on *L* (but not on *A*). The examples are stored in `examples/E<n>` subdirectories, and each example has its own `build.gradle` file. *A*, *L* and the example projects are included from the root's `settings.gradle` file (there is no `settings.gradle` file in `examples/`). As all examples are independent of each other, I'd like to build them all in parallel without specifying each of them separately on the command line. Instead, I'd like to be able to simply write something like `./gradlew examples` from the root directory to do that. I could create `task examples(dependsOn: E1:assembleDebug, E2:assembleDebug, E3:assembleDebug)`, but that does not scale well if new examples are added. I could probably also hook `tasks.whenAdded`and then modify the `examples` project's dependencies, but that does not seem to be very clean. So, is there an elegant way to create a task that just builds other tasks from a certain subdirectory in parallel? It seems there's also a [group that a project can belong to](http://www.gradle.org/docs/current/dsl/org.gradle.api.Project.html#org.gradle.api.Project:group), so a simple way to build all projects of a given group in parallel would also be fine.
2014/11/10
[ "https://Stackoverflow.com/questions/26847594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127485/" ]
This work work me: add this dependency in your maven pom file ``` <dependency> <groupId>org.graylog2</groupId> <artifactId>gelfj</artifactId> <version>1.1.13</version> </dependency> ``` and these lines in your log4j.properties ``` # Define the graylog2 destination log4j.appender.graylog2=org.graylog2.log.GelfAppender log4j.appender.graylog2.graylogHost=192.168.243.23 log4j.appender.graylog2.port=12201 log4j.appender.graylog2.originHost=loggenerator-server-ip log4j.appender.graylog2.layout=org.apache.log4j.PatternLayout log4j.appender.graylog2.additionalFields={'environment': 'DEV', 'application': 'MyAPP'} log4j.appender.graylog2.extractStacktrace=true log4j.appender.graylog2.addExtendedInformation=true log4j.appender.graylog2.facility=gelfappender-test ```
Look in `catalina.out` (usually located under `tomcat/logs`) for error messages related to Gelf
18,678,853
I tried cloning my repository which I keep in my [Ubuntu One](https://en.wikipedia.org/wiki/Ubuntu_One#Features) folder to a new machine, and I got this: ``` cd ~/source/personal git clone ~/Ubuntu\ One\ Side\ Work/projects.git/ Cloning into 'projects'... done. fatal: unable to read tree 29a422c19251aeaeb907175e9b3219a9bed6c616 ``` So I tried looking at the many other questions like this that have been asked here and most of them say to run `git fsck --full` and then I get this when I try that. ``` cd ~/Ubuntu\ One\ Side\ Work/projects.git git fsck --full Checking object directories: 100% (256/256), done. Checking objects: 100% (447/447), done. broken link from commit 235ae1f48701d577d71ebd430344a159e5ba4881 to commit 984c11abfc9c2839b386f29c574d9e03383fa589 broken link from tree 632a9cf0ef9fccea08438b574e2f1c954f4ff08b to blob 25a742dff0a403b2b3884f2ffddf63eb45721fac broken link from tree 632a9cf0ef9fccea08438b574e2f1c954f4ff08b to blob dd4e97e22e159a585b20e21028f964827d5afa4e broken link from tree 632a9cf0ef9fccea08438b574e2f1c954f4ff08b to tree 29a422c19251aeaeb907175e9b3219a9bed6c616 broken link from tree 632a9cf0ef9fccea08438b574e2f1c954f4ff08b to tree 8084e8e04d510cc28321f30a9646477cc50c235c broken link from tree 774b5b4157b4caae1c6cad96c8eaf5d4eba2c628 to blob a0daa0c1567b55d8de2b4d7a3bc010f58c047eab broken link from tree 774b5b4157b4caae1c6cad96c8eaf5d4eba2c628 to blob e9052d35bfb6d30065b206fc43f4200a04d5281b broken link from tree 774b5b4157b4caae1c6cad96c8eaf5d4eba2c628 to blob 1a3a5e4dd2502ac121c22f743c4250e254a94eeb broken link from tree 4aa336dc1a5838e8918e03b85580069d83f4ad09 to tree 8cc55ec952dc192a233e062201d1e7e873ac3db0 broken link from tree e5674a91a53e15575a1f3bf5786bc5cc719fb483 to blob 4a994e1e7bb7ce28dcec98bad48b9a891d7dec51 broken link from tree e5674a91a53e15575a1f3bf5786bc5cc719fb483 to blob ac033bf9dc846101320c96a5ce8aceb8c96ec098 broken link from tree 252ab84542264e1589576b6ee51e7a31e580a0e2 to tree 2069041cd5950e529e2991d37b7290ec021d90d4 broken link from tree 2d4964aa4d4f5d8c7228518ce72ef6a63f820c6d to blob d83690e1b9a6bdd8a08754b38231799acefcb2ab broken link from tree c7192e82fc581bd6448bda1a25e8729bdac5f4ff to blob 30d54d47ae82add1917ca173d42e58b396df580b broken link from tree 7c66306901fc71389623286936cef172d4ffe408 to blob bc7e05d705401273b1df4e939de0f540597c0931 broken link from tree 0940f5fd227d4c84d6e6749d872db50a4522ae3a to tree 923767594ac22023e824948d65622fe5b407d1a1 broken link from tree 8eadcd2a971e8357d24f0d80f993d2963452209f to blob 2598bde3dc8cb80ee49510b8159344004b88645f broken link from tree ffa302dd0d969172ef23caeefe856ab2f57a4e4d to blob d6925fa431be1ac585bf9a481e98f75107a6e6fb broken link from tree 7045b8870a49ce30a2027537a96d73d162bda773 to blob 25688652dea26f61f576ca1b52b9d1a18fbfd01d broken link from tree 37e4705d34bd440ce681ae32ae9a180a13256d72 to tree 246f564d4cee53339b8a4244f3173b61caa518eb missing blob d6925fa431be1ac585bf9a481e98f75107a6e6fb missing blob ac033bf9dc846101320c96a5ce8aceb8c96ec098 missing tree 29a422c19251aeaeb907175e9b3219a9bed6c616 missing tree 8084e8e04d510cc28321f30a9646477cc50c235c missing blob 30d54d47ae82add1917ca173d42e58b396df580b missing tree 8cc55ec952dc192a233e062201d1e7e873ac3db0 missing blob e9052d35bfb6d30065b206fc43f4200a04d5281b dangling tree 4b26e95db542c72ac4a22ec25abe38fb2de79752 missing blob d83690e1b9a6bdd8a08754b38231799acefcb2ab missing blob 25a742dff0a403b2b3884f2ffddf63eb45721fac missing tree 923767594ac22023e824948d65622fe5b407d1a1 missing blob 25688652dea26f61f576ca1b52b9d1a18fbfd01d missing blob 2598bde3dc8cb80ee49510b8159344004b88645f dangling tree 3a683869f1bb0c1634de75700c316b3b36570dbd dangling blob 4098d30843380d798a811f1aa9a02994f0dbbb27 missing tree 2069041cd5950e529e2991d37b7290ec021d90d4 missing blob 4a994e1e7bb7ce28dcec98bad48b9a891d7dec51 missing blob 1a3a5e4dd2502ac121c22f743c4250e254a94eeb missing blob a0daa0c1567b55d8de2b4d7a3bc010f58c047eab dangling tree 6c7b5162aa7a303fa3fe8dc393c5da564e309521 missing commit 984c11abfc9c2839b386f29c574d9e03383fa589 missing blob bc7e05d705401273b1df4e939de0f540597c0931 missing blob dd4e97e22e159a585b20e21028f964827d5afa4e missing tree 246f564d4cee53339b8a4244f3173b61caa518eb dangling commit a01f5c1e5315dc837203d6dee00d3493be9c5db9 ``` That looks really bad. When I do a `git log | head` I get this ``` git log | head error: Could not read 984c11abfc9c2839b386f29c574d9e03383fa589 fatal: Failed to traverse parents of commit 235ae1f48701d577d71ebd430344a159e5ba4881 commit 2fb0d2d0643b445440f01b164f11ee9ee71fca48 Author: christopher <christopher@christopher.christopher> Date: Wed Aug 7 15:51:42 2013 -0400 finishing chapter 7 ``` Other questions here have said to look at `./git/refs/heads/master`. It's a bare repo and `refs/heads/` exists but `refs/heads/master` does not. HEAD in the bare repository says `ref: refs/heads/master` though. `packed-refs` does say this though ``` # pack-refs with: peeled 2fb0d2d0643b445440f01b164f11ee9ee71fca48 refs/heads/master ``` Still other questions have suggested running `git reflog` and no output shows up when I run that. So I really have no idea what to do here. What strategy should be taken? Is it possible to reset head to this last commit on Aug 7? Doing a `git log` and going to the bottom of the screen output shows this: ``` commit 996e03b949aea176238e3c7a8452700bbb987ac9 Author: christopher <christopher@christopher> Date: Wed Jul 3 23:00:44 2013 -0400 many many changes error: Could not read 984c11abfc9c2839b386f29c574d9e03383fa589 fatal: Failed to traverse parents of commit 235ae1f48701d577d71ebd430344a159e5ba4881 ``` That seems to be preventing the Git prune from working.
2013/09/07
[ "https://Stackoverflow.com/questions/18678853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/444763/" ]
**git-repair** (`sudo apt install git-repair`) with a few additional commands worked for me: 0. Create a backup copy of your corrupted repository. 1. Delete broken references: `find .git/refs -size 0 -delete -print` 2. Repair repository from remote(s): `git-repair --force` 3. Clean up dangling commits: `git gc --prune=now` 4. Fetch the latest state from remote: `git fetch` Optionally switch to *master* and reset it to *origin/master*: `git checkout master` `git reset --hard origin/master` Verify with *git fsck*: `git fsck`
I wanted to add this as a comment under [Zoey Hewil's awesome answer](https://stackoverflow.com/a/46604551/5669462) above, but I don't currently have enough rep to do so, so I have to add it here and give credit for her work :P If you're using [Poshgit](https://github.com/dahlbyk/posh-git) and are feeling *exceptionally* lazy, you can use the following to automatically extract your URL from your Git configuration and make an easy job even easier. Standard caveats apply about testing this on a copy/backing up your local repository first in case it blows up in your face. ``` $config = get-content .git\config $url = $config -match " url = (?<content>.*)" $url = $url.trim().Substring(6) $url move-item -v .git .git_old; git init; git remote add origin "$url"; git fetch; git reset origin/master --mixed ```
71,925,642
I'm building a script that downloads a file from a URL and then executes it, but for some reason when I debug the script, it throws an error like: System.ComponentModel.Win32Exception: 'An error occurred trying to start process "" with working directory "". The process cannot access the file because it is being used by another process.' Here is my code: ``` using System.Net.Http; using System.IO; using System.Diagnostics; String myUserName = Environment.UserName; var httpClient = new HttpClient(); var responseStream = await httpClient.GetStreamAsync("http://exampleurl.com/examplefile.exe"); using var fileStream = new FileStream("C:/Users/"+myUserName+"/examplefile.exe", FileMode.Create); responseStream.CopyTo(fileStream); System.Threading.Thread.Sleep(10000); // sleeping waiting until download completes string str = @"C:/Users/"+myUserName+"/examplefile.exe"; Process process = new Process(); process.StartInfo.FileName = str; process.Start(); ```
2022/04/19
[ "https://Stackoverflow.com/questions/71925642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15070023/" ]
``` yarn add react@17.0.2 ``` Downgrade react 18 to react 17
In my case I ended up removing the `react-hot-loader` and `hot-loader/react-dom` dependencies and its related Webpack config. Since both of them only support till react-dom v17 which doesn’t have the new useSyncExternalStorage hook.
63,737
Is there a plugin (for any browser) anyone can recommend? An app? It seems like all browsers got rid of this easy resource tracking feature (Chrome too).
2012/09/12
[ "https://apple.stackexchange.com/questions/63737", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/28957/" ]
You can see still browse resources in the web inspector. ![](https://i.stack.imgur.com/TRtIF.png) To download a file, you can copy the URL from the right sidebar, paste it on the location bar, and press ⌥↩. The web inspector can be shown by pressing ⌥⌘I if you've enabled showing the develop menu in the advanced preferences.
Maybe you can try Firebug for Firefox.
29,970,892
I designed an application for android (I used android studio), which actually has an embedded web site, which was made by me in php. The first screen of the application is a login. I would like to know how I can do to make the system to remember the user name and password, as happens in most of the android applications.
2015/04/30
[ "https://Stackoverflow.com/questions/29970892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178303/" ]
You can ignore the platforms and plugins directories as long as you haven't added any custom code in them. When adding plugins and platforms add --save to the command. e.g. ``` cordova platform add ios@3.8.0 --save ``` or ``` cordova plugin add cordova-plugin-device --save ``` This will save a record of the plugins and platforms you use to your config.xml file. When you run `cordova prepare` or `cordova build` all of your plugins and platforms listed in config.xml will be installed if they haven't been already. You can also specify a platform in prepare and build. So if you are on your Mac, you can check out the git repository and run `cordova prepare ios` to install just the ios platform and plugins.
I followed these steps: * create cordova project * add platforms * add plugins Before build project, I commit and push generated files. After I build project and check for new files generated. I got these to add in .gitignore: /platforms/android/gradlew.bat /platforms/android/build /platforms/android/gradle /platforms/android/libs /platforms/android/gradlew.bat /platforms/android/CordovaLib/build /platforms/android/.gradle
38,807
I'm currently writing a novel with 3-4 character POVs in it - two male, two female. Each have different upbringings, different cultural backgrounds, different professions, different motivators and driving factors - in short, how the characters think, the entire worldview, it changes from chapter to chapter. So how do I change my writing to reflect the character voice, when it is just my voice as the writer, bleeding through all of them? Also, how *does* the writing style change? Between male and female POVs, between different professions? Do male tend to use more stilted sentences than female characters? How does the voice change in, say, a warrior, as compared to a mathematician or a linguist?
2018/09/10
[ "https://writers.stackexchange.com/questions/38807", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/33045/" ]
How do the people speaking around you, wherever you are, speak differently? How do your favorite authors give characters different voices? Here are a few ways your characters might differ: * Different vocabularies * Different sentence lengths and complexities * Different speeds * Verbosity vs brevity * Some think before they speak, while others speak their immediate, unfiltered thoughts * Some use metaphors, some are more direct and clear * Some talk about higher issues, others about concrete details * Some are storytellers, others talk about ideas and hypotheticals Those are just off the top of my head, before my morning caffeine.
It is critical that you **use** *different* FONTS for each person "unless not practical". Different font sizes are especially effective. HEY CHARACTER 1, WHAT TIME IT IS? *oh hello 2 that is a secret*
30,659,682
I have this script and its triggering just when i click first time on textbox: ``` var day = parseInt($("#day_birthdate").val(), 10); jQuery('input#day_birthdate').bind('input propertychange', function () { if (day >= 1 || day <=31) { jQuery(this).css({ 'background': 'green' }); } else { jQuery(this).css({ 'background': 'red' }); } }); ``` I have this textbox: ``` @Html.TextBoxFor(m => m.Register.Day, new { id = "day_birthdate", @class = "form-control", mask = "99", @placeholder = "dd" }) ``` When i click on textbox its triggering but for first time value is NaN and its red but when i put some number its nots triggering anymore...so i need to change this somehow so when user type numbers between 1 and 31 to get green textbox.Any help?
2015/06/05
[ "https://Stackoverflow.com/questions/30659682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511325/" ]
set on top html tag `ng-app ="scopeExample"`
``` function HelloCntl($area) { $area.test= 'Demo'; } <div ng-controller="MyController"> Your name: <input type="text" ng-model="test"/> <hr/> Hello {{test|| "Demo"}}! </div> ``` You Can Try This Code I check this code is properly working and i am also using this code =========================================================================================
54,093,132
I'm searching a way to use scheduled tasks in a reactive API. I know that it uses the thread pool so it's not very compatible with the webflux components. Do you have an equivalent to do the job?
2019/01/08
[ "https://Stackoverflow.com/questions/54093132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694403/" ]
You may try to use `Schedulers.immediate()` inside `@Scheduled` method: ``` doWork() .subscribeOn(Schedulers.immediate()) .subscribe() ``` As a consequence tasks run on the thread that submitted them.
Webflux has it's own scheduler, and I gues this way should do it: ``` Disposable schedulePeriodically(Runnable task, long initialDelay, long period, TimeUnit unit); ```
40,926,635
I'm running Nightwatch after launching a child process that starts up my local servers. Nightwatch runs the tests, they complete successfully, and the browser windows all close, but the `nightwatch` process continues to run after printing the message "OK. 10 total assertions passed.". I thought it may have something to do with how I'm watching events on the `nightwatch` process, but as far as I can tell I am watching all events that would indicate Nightwatch is exiting. The method `shutdown()` in `runner.js` is never called. How do I get Nightwatch to terminate when the tests finish? **Update** If I remove the last test in `sign-in.js` then Nightwatch exits as expected. **runner.js** ``` import spawn from 'cross-spawn' // 1. start the dev server using production config process.env.NODE_ENV = 'testing' let servers function shutdown (result) { console.log('HERE', result) try { // Passing a negative PID to kill will terminate all child processes, not just the parent if (servers) process.kill(-servers.pid) } catch (e) { console.error('Unable to shutdown servers, may need to be killed manually') } if (result) { console.error(result) process.exit(1) } else { process.exit(0) } } function watch (child) { child.on('close', shutdown) child.on('disconnect', shutdown) child.on('error', shutdown) child.on('exit', shutdown) child.on('uncaughtException', shutdown) } try { servers = spawn('yarn', ['run', 'dev-all'], { cwd: '..', stdio: 'inherit', detached: true }) watch(servers) // 2. run the nightwatch test suite against it // to run in additional browsers: // 1. add an entry in test/e2e/nightwatch.conf.json under "test_settings" // 2. add it to the --env flag below // or override the environment flag, for example: `npm run e2e -- --env chrome,firefox` // For more information on Nightwatch's config file, see // http://nightwatchjs.org/guide#settings-file var opts = process.argv.slice(2) if (opts.indexOf('--config') === -1) { opts = opts.concat(['--config', 'e2e/nightwatch.conf.js']) } if (opts.indexOf('--env') === -1) { opts = opts.concat(['--env', 'chrome']) } var runner = spawn('./node_modules/.bin/nightwatch', opts, { stdio: 'inherit' }) watch(runner) watch(process) } catch (error) { shutdown(error) } ``` **nightwatch.conf.js** ``` require('babel-register') var config = require('../../frontend/config') // http://nightwatchjs.org/guide#settings-file module.exports = { src_folders: ['e2e/specs'], output_folder: 'e2e/reports', custom_assertions_path: ['e2e/custom-assertions'], selenium: { start_process: true, server_path: 'node_modules/selenium-server/lib/runner/selenium-server-standalone-3.0.1.jar', host: '127.0.0.1', port: 4444, cli_args: { 'webdriver.chrome.driver': require('chromedriver').path } }, test_settings: { default: { selenium_port: 4444, selenium_host: 'localhost', silent: true, globals: { devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port) } }, chrome: { desiredCapabilities: { browserName: 'chrome', javascriptEnabled: true, acceptSslCerts: true } }, firefox: { desiredCapabilities: { browserName: 'firefox', javascriptEnabled: true, acceptSslCerts: true } } } } ``` **sign-in.js** (one of the tests) ``` import firebase from 'firebase-admin' import uuid from 'uuid' import * as firebaseSettings from '../../../backend/src/firebase-settings' const PASSWORD = 'toomanysecrets' function createUser (user) { console.log('Creating user', user.uid) let db = firebase.database() return Promise.all([ firebase.auth().createUser({ uid: user.uid, email: user.email, emailVerified: true, displayName: user.fullName, password: PASSWORD }), db.ref('users').child(user.uid).set({ email: user.email, fullName: user.fullName }), db.ref('roles').child(user.uid).set({ instructor: false }) ]) } function destroyUser (user) { if (!user) return console.log('Removing user', user.uid) let db = firebase.database() try { db.ref('roles').child(user.uid).remove() } catch (e) {} try { db.ref('users').child(user.uid).remove() } catch (e) {} try { firebase.auth().deleteUser(user.uid) } catch (e) {} } module.exports = { 'Sign In links exist': browser => { // automatically uses dev Server port from /config.index.js // default: http://localhost:8080 // see nightwatch.conf.js const devServer = browser.globals.devServerURL browser .url(devServer) .waitForElementVisible('#container', 5000) browser.expect.element('.main-nav').to.be.present browser.expect.element('.main-nav a[href^=\'https://oauth.ais.msu.edu/oauth/authorize\']').to.be.present browser.expect.element('.main-nav a[href^=\'/email-sign-in\']').to.be.present browser.end() }, 'Successful Sign In with Email shows dashboard': browser => { const devServer = browser.globals.devServerURL firebase.initializeApp(firebaseSettings.appConfig) let userId = uuid.v4() let user = { uid: userId, email: `${userId}@test.com`, fullName: 'Test User' } createUser(user) browser.url(devServer) .waitForElementVisible('.main-nav a[href^=\'/email-sign-in\']', 5000) .click('.main-nav a[href^=\'/email-sign-in\']') .waitForElementVisible('button', 5000) .setValue('input[type=text]', user.email) .setValue('input[type=password]', PASSWORD) .click('button') .waitForElementVisible('.main-nav a[href^=\'/sign-out\']', 5000) .end(() => { destroyUser(user) }) } } ``` After the tests complete successfully, I see the following: ``` grimlock:backend egillespie$ ps -ef | grep nightwatch 501 13087 13085 0 1:51AM ttys000 0:02.18 node ./node_modules/.bin/nightwatch --presets es2015,stage-0 --config e2e/nightwatch.conf.js --env chrome ```
2016/12/02
[ "https://Stackoverflow.com/questions/40926635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1696044/" ]
I was not explicitly closing the Firebase connection. This caused the last test to hang indefinitely. Here's how I am closing the connection after doing test cleanup: ``` browser.end(() => { destroyUser(user).then(() => { firebase.app().delete() }) }) ``` The `destroyUser` function now looks like this: ``` function destroyUser (user) { if (!user) return Promise.resolve() let db = firebase.database() return Promise.all([ db.ref('roles').child(user.uid).remove(), db.ref('users').child(user.uid).remove(), firebase.auth().deleteUser(user.uid) ]) } ```
In my case (nightwatch with vue/vuetify) after each test like so: ``` afterEach:function(browser,done){ done(); } ```
3,791,903
Using python 2.6.5, I can use the `with` statement without calling `from __future__ import with_statement`. How can I tell which version of Python supports `with` without specifically importing it from `__future__`?
2010/09/25
[ "https://Stackoverflow.com/questions/3791903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446929/" ]
`__future__` features are self-documenting. Try this: ``` >>> from __future__ import with_statement >>> with_statement.getOptionalRelease() (2, 5, 0, 'alpha', 1) >>> with_statement.getMandatoryRelease() (2, 6, 0, 'alpha', 0) ``` These respectively indicate the first release supporting `from __future__ import with_statement` and the first release to support it without using `from __future__`. Also, read this: ``` >>> import __future__ >>> help(__future__) ```
From the doc: ``` New in version 2.5. ```
50,142,154
I cross checked everything SHA-1 is also correct as well as the packagename i am using real android device but still this error is showing. `onVerificationFailed com.google.firebase.auth.FirebaseAuthException: This app is not authorized to use Firebase Authentication. Please verifythat the correct package name and SHA-1 are configured in the Firebase Console. [ App validation failed. Is app running on a physical device? ] at com.google.firebase.auth.api.internal.zzce.zzb(Unknown Source) at com.google.firebase.auth.api.internal.zzdf.zza(Unknown Source) at com.google.firebase.auth.api.internal.zzdg.run(Unknown Source) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6095) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)` here are the screenshots for SHA-1: [![SHA-1 from android studio](https://i.stack.imgur.com/PHkTe.png)](https://i.stack.imgur.com/PHkTe.png) [![Firebase app settings](https://i.stack.imgur.com/peraT.png)](https://i.stack.imgur.com/peraT.png) [![my package name](https://i.stack.imgur.com/DmHBT.png)](https://i.stack.imgur.com/DmHBT.png) my package name above
2018/05/02
[ "https://Stackoverflow.com/questions/50142154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5404432/" ]
I had the same issue recently. If Your app was on the play store,I would have told you to add the SHA-1 provided by play store as well. But since it is just a debug mode.Make sure you have the recent SHA-1 as it can change based on some factors.
This issue only happened to my OPPO phone. I guess some Chinese phone manufactories root Android system so the phone is detected as a simulator? Anyway, cope SHA-1 from google play to firebase works with me. You can find google play SHA-1 from Google Play Console -> Release management -> App signing. [![Where you can find signing SHA-1 from google play](https://i.stack.imgur.com/xGD6P.png)](https://i.stack.imgur.com/xGD6P.png) Just copy those SHA-1 to firebase. For Firebase console. Go to "Project settings". You can find the place to paste SHA-1 from google play. [![enter image description here](https://i.stack.imgur.com/3A2zG.png)](https://i.stack.imgur.com/3A2zG.png)
12,674,219
I have a table that holds survey data, two data points are Ethnicity and Flavor\_Pref. The Flavor\_Pref hold an integer 1, 2, 3,4,5. 1 = Dislike Very Much, 5 Like Very Much. ``` Ethnicity Flavor_Pref African American 3 Caucasian 2 Asian 4 Hispanic 1 African American 3 Caucasian 4 Asian 5 Hispanic 2 African American 4 Caucasian 1 Asian 4 Hispanic 2 African American 3 Caucasian 2 Asian 2 Hispanic 1 ``` I want run a query to get 4 columns, one for each Ethnic group. Each group has a different number of responses. This is what I'm working on: I get over 1M results.... I only have 400 surveys. ``` select AA.Flavor_Pref as AA,H.Flavor_Pref as H,C.Flavor_Pref AS C, A.Flavor_Pref AS A from (SELECT ETHNICITY,Flavor_Pref FROM FLAVORS WHERE ETHNICITY = 'AFRICAN AMERICAN')AS AA CROSS JOIN (SELECT ETHNICITY,Flavor_Pref FROM FLAVORS WHERE ETHNICITY = 'HISPANIC') AS H CROSS JOIN (SELECT ETHNICITY,Flavor_Pref FROM FLAVORS WHERE ETHNICITY = 'CAUCASIAN') AS C CROSS JOIN (SELECT ETHNICITY,Flavor_Pref FROM FLAVORS WHERE ETHNICITY = 'ASIAN' ) AS A ``` What I'm looking for is: In this case there are fewer Hispanic results, so nothing is reported. ``` African Americans Hispanic Caucasian Asian 3 1 2 4 3 2 4 5 4 2 1 5 . . . . . . . . . . . . 3 2 4 2 1 1 ```
2012/10/01
[ "https://Stackoverflow.com/questions/12674219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516801/" ]
the implementation is such that we have to implement listener to get signal strength of current cell, i have wrote the listener and stopped the listener at first read and then kept in variable. no any other way
I tried to use the "Hazmat" code, but unfortunately does not work on my device (Samsung S3 mini Android 4.1.2). It seems that some phones from Samsung have problems with this feature and nobody from Samsung cares. [Also other Samsung models have similar problem](http://forum.xda-developers.com/showpost.php?p=18846375&postcount=12): Samsung Galaxy SI -> no problems Samsung Galaxy SII -> no strength and no refresh Samsung Galaxy Tab 10.1 -> no strength and no refresh Samsung Galaxy Note -> no strength and no refresh (Android Versions: 2.3.3, 2.3.4, 2.3.5, 3.1) Also reported [here](https://code.google.com/p/android/issues/detail?id=18336) and [here](http://developer.samsung.com/forum/thread/can-not-read-signal-strength-on-galaxy-sii-and-other-samsung-devices/77/129957). Conclusion: Be aware that a lot of **Samsung devices don´t work properly with this function!** I am not aware of any workaround for it. Samsung makes our apps unreliable.
7,182,264
I have a common unit that does some logging to GExperts Debugger and/or OutputDebugString. I am going to use it in a console app, so I want it to be able to output to stdout via `writeln()`. The main executable has {$APPTYPE CONSOLE} already, but I don't think that'll help me here. The logging routine will be called from several places: 1. the main console app, which will link to a BPL, 2. from another BPL that "requires" the first bpl, and..... 3. from a DLL that statically links the unit. The BPLs and DLL will be built with no visibility to the {$APPTYPE CONSOLE} directive, so I can't use IFDEF conditional compilation. The BPL and DLL need to be able to go either way, depending whether the main app is a regular winapp or console app. One ugly solution that occurred to me is to use the name of the executable. ex: ``` if (UpperCase(ExtractFileName(ParamStr(0))) = 'MYCONSOLEAPP.EXE') then ... ``` But I hate to do that, as I could have other console apps... I'd rather just have a magic function AmIAConsoleApp : boolean; Is there anything like that? I'm using Delphi2005 on this project. Update: I see that I'm kind of a duplicate of [this question](https://stackoverflow.com/questions/744693/how-do-i-detect-if-im-running-in-the-console), but I'd like to survey the Delphi folks to see if there's a better approach.
2011/08/24
[ "https://Stackoverflow.com/questions/7182264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289135/" ]
Call `GetStdHandle(Std_Output_Handle)`. If it succeeds and returns zero, then there is no console to write to. Other return values indicate that a console is attached to the process, so you can write to it (although the console may not be the most desirable place to log messages in a console program since they'll interfere with the normal output). Something like this: ``` function IAmAConsoleApp: Boolean; var Stdout: THandle; begin Stdout := GetStdHandle(Std_Output_Handle); Win32Check(Stdout <> Invalid_Handle_Value); Result := Stdout <> 0; end; ```
Use constructor injection to inject a logger at the time you create the instance. [Here's a simple example.](http://www.nickhodges.com/post/Getting-Giddy-with-Dependency-Injection-and-Delphi-Spring-4-%E2%80%93-Dependency-Injection-Basics.aspx) Your proposed solution of testing whether the app is a console app works for only those two scenarios. The constructor injection solution is scarcely any more code and works anywhere you need output.
15,608,203
I ran the following script using `php.exe`: ``` preg_replace('#(?:^[^\pL]*)|(?:[^\pL]*$)#u','',$string); ``` or its equivalent: ``` preg_replace('#(?:^[^\pL]*|[^\pL]*$)#u','',$string); ``` If `$string="S"` or `$string=" ذذ "` it works, if `string='ذ'` it yields `�` that is incorrect , and if `string='ذذ'` PHP crashes. But it works in 4.4.0 - 4.4.9, 5.0.5 - 5.1.6 versions. What is wrong ? **See**: <http://3v4l.org/T3rpV> --- ``` <?php $string='دد'; echo preg_replace('#(?:^[^\pL]*)|(?:[^\pL]*$)#u','',$string); ``` > > Output for 5.4.0 - 5.5.0alpha6 > > > > ``` > Process exited with code 139. > > ``` > > Output for 5.2.0 - 5.3.22, 5.5.0beta1 > > >   > > > Output for 4.4.0 - 4.4.9, 5.0.5 - 5.1.6 > > > > ``` > دد > > ``` > > Output for 4.3.11, 5.0.0 - 5.0.4 > > > > ``` > Warning: preg_replace(): Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X at offset 7 in /in/T3rpV on line 3 > > ``` > > Output for 4.3.0 - 4.3.10 > > > > ``` > Warning: Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X at offset 7 in /in/T3rpV on line 3 > > ``` > >
2013/03/25
[ "https://Stackoverflow.com/questions/15608203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/752603/" ]
maybe this will help : > > these properties are usualy only available if PCRE is compiled with > "--enable-unicode-properties" > > > <http://docs.php.net/manual/en/regexp.reference.unicode.php#96479>
From looking at the expression itself, there are two things that could be improved: 1. The `*` multipliers aren't very useful; why would you want to replace a potentially empty match with an empty string? In fact, running this on my system yields `NULL` from the `preg_replace()` operation. 2. The memory groups can be merged together. This is the code after applying both improvements: ``` $string = 'ﺫﺫ'; var_dump(preg_replace('#(?:^[^\pL]+|[^\pL]+$)#u', '', $string)); // string(4) "ﺫﺫ" ``` [**3v4l results**](http://3v4l.org/lF95R) If you're just looking for a multibyte trim function (supported from 4.3.0 onwards): ``` $string=' دد'; var_dump(preg_replace('#(?:^\s+|\s+$)#u', '', $string)); ``` [**3v4l results**](http://3v4l.org/ZBXoX)
8,506,442
What is the algorithm can be used to resolve the following classification problem? We have Multi-touch screen, user that can touch it with two or three fingers simultaneously. 1. After user touches screen, we remember initial positions of his fingers. Each fingers gets a group of coordinates from the device. 2. When user moves fingers we should track movements of his fingers. The problem is that when fingers move close to each other. How to determine which points to which finger belongs? I know this is a some kind of classification problem. What is an algorithm can be used to approach this problem?
2011/12/14
[ "https://Stackoverflow.com/questions/8506442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/603019/" ]
One problem is to start with reports of N locations at time t and reports of N locations at time t+1 and work out that position 1 at time t is the same finger as position 3 at time t+1. The military have looked at this sort of thing a lot, often under the name of data fusion. One approach is to write down a cost of associating position i at time t with position j at time t+1 and then find the permutation with minimum total cost - this is an instance of the <http://en.wikipedia.org/wiki/Assignment_problem>. If the device in fact reports two fingers very close together as one, you have a more complex problem - but you surely don't have many different positions to consider, so you should be able to e.g. try various ways of treating one position report as two different reports and then pick the highest scoring possibility.
Solving the assignment problem is overkill for this, given that you are trying to assign three points to three fingers. Even if you are trying to assign five points to five fingers, you are better off using a brute force approach to figuring out the optimal configuration of points to fingers. Note that for three fingers and three points, there are only six possible unique assignments of fingers to points. So it's best to just calculate the cost of each assignment configuration and choose the one with least cost. However, I think this is missing the point of your question. The tricky part is not the assignment process itself, but choosing a decent "cost" function for each possible assignment. If the cost function doesn't take account of prior finger-point assignments, then there's an equal cost to assigning any finger to any point and so you lack any "continuity" where fingers are assigned to the same moving point. So your goal is to ensure your assignment models 'real life'. The approach I suggest is this: Define a physical model for the movement of fingers. A very simple model would be a momentum model where each finger is independent of each other and is assumed to have some inertia. If a finger moves dx,dy in one frame, you would expect it to move dx,dy in the second frame. This gives you an expectation value for where you expect the finger to be next. Now you can define the cost of assigning a finger to a point as some function of the distance between the location of the actual point registered and where you expected it to be. Sum up the costs for each finger-point assignment and find the configuration with lowest cost. Now, if you want to be more sophisticated, all you have to do is use a more sophisticated model. Perhaps you don't want to assume fingers move independently. You might want to expect some correlation between the finger movements. In which case, refine the model, calculate the new point expectations and calculate the cost of the assignment as before.
1,165,384
So I'm starting to hear more and more about [Web Workers](http://ejohn.org/blog/web-workers/). I think it's absolutely fantastic, but the question I haven't seen anyone really tackle so far is how to support older browsers that do not yet have support for the new technology. The only solution I've been able to come up with so far is to make some sort of wrapper around the web worker functionality that would fall back to some crazy timer based solution that would simulate multi-threaded execution. But even in that case, how does one detect whether web workers is a supported feature of the browser currently executing the javascript? Thanks!
2009/07/22
[ "https://Stackoverflow.com/questions/1165384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]
Here's what John Resig said [replying to a comment on his blog](http://ejohn.org/blog/web-workers/#comment-386781) > > I thought about this - but it'll be tricky. You would have to make your processing code use setTimeout/setInterval from the start (this code would end up working in both a worker and on a normal web site). So while the result would be slightly slower for worker-enabled browsers at least it would work in both cases. > > >
I had the funny problem that my task without Web Worker support was too slow in Firefox (unresponsive script), but fast enough in all other modern browsers. With Web Workers it worked in all browsers except Opera (10.50) which doesn't support Web Workers at all, but Opera worked fine without them. So I wrote a WorkerFacade that uses the Web Worker API when available or fakes the API with some minor additions to the actual Worker JS. You can find [WorkerFacade as a gist on GitHub](http://gist.github.com/462880). Worked well for me, might help someone else, too.
420,605
I can't for the life of me figure this out. I feel like i'm missing some crucial detail about how batteries work. Imagine two batteries connected in series, like this: ``` Circuit <= -(Battery A)+ <= -(Battery B)+ <= Circuit ``` **As far as I've studied, this is what happens:** 1. The negative side of Battery B has a surplus of electrons, while the positive side of Battery A has a "normal" concentration of electrons. Since electrons repel each other, they kinda push themselves to Battery A. (I am imagining a tube with one side filled with "elastic" balls tightly packed and the other side with elastic balls but not pressed together. The balls get pushed until they are all at an equal "pressure"). 2. A number of electrons constantly reach the positive end of Battery A with a "force" of x Volts. In practical terms, the electrons are colliding with the battery with a higher intensity. For some reason, this causes the electrons coming out of the negative end of Battery A to have a "force" of 2x Volts. **I don't understand why.** Is it because there is now two times more free electrons at the negative end of Battery A? And thus the difference between this end and Battery B is two times the normal? 3. The electrons get pushed again to the positive end of Battery B. From what I understand, the material in the battery "absorbs" them and releases a free electron on the negative end of Battery B. **Please avoid using water analogies.** I specifically want to know what happens at the atomic, per-electron level. I don't care much about the differences between each battery. If possible, pick a battery type you prefer or just talk about batteries in general (characteristics shared by all batteries).
2018/08/01
[ "https://physics.stackexchange.com/questions/420605", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/202938/" ]
**Chemistry and Physics of Batteries in Series** > > What happens at the atomic level inside a cell when putting two batteries in series? > > > **Short Answer:** **Characteristics of a single cell vs. two cells in series:** (i.e., compare the voltage, current, $E$ field, stored energy, power, charge, and operating time in a circuit with the same resistive load.): * Twice the voltage, due to the summation of voltages with two cells in series (i.e., twice the $E$ field acting on a resistive load through the conductor). * Twice the current with the same load, due to the doubled voltage. * Twice the reaction rate at both the anode and cathode in all cells in series. * Twice the rate of $\mathrm{H^+}$ ion migration from the anode to cathode to maintain charge neutrality at both anode and cathode. * Twice the rate of battery charge depletion. When the current doubles and the charge capacity of each cell is unchanged, the duration of flow is reduced to half. * Within the circuit with series batteries: the same current flows through all the current elements. (Electron current flows through the circuit elements: originating in the outer anode, travels through the conductor, load, outer cathode, inner anode, and finally neutralized at by the inner cathode reaction). * Within the electrolytes of the cells in series, the magnitude of ion flow rate is the same as the current flow rate through the electrolytes of both cells, ($\text{cell}\_1$ and $\text{cell}\_2$). > > What force drives current through the electrolyte and conductor between the cells in series? > > > * Ultimately, the sum of the battery cell voltages drives current through the cells, but its action is indirect. The terminal battery voltages drive current through the load, but ion migration and reaction potentials are responsible for driving current within the batteries. * The doubled voltage of two batteries in series drive twice the current through the load. * This increased current draws more electrons off the outer anode and conducts it through the load to the outer cathode. (Note: the outer anode and outer cathode refer to the external electrodes of the two cells in series. And obviously, the terms "inner anode" and "inner cathode" refer to the terminals connected between batteries in series.) * The increased rate of removal of electrons from the outer anode, and delivery to the outer cathode, disturbs the equilibrium state of the reactions in both the outer anode and outer cathode, resulting in the production of more electrons by the anode reaction, and the consumption of more electrons by the cathode reaction. * The disturbance of equilibrium state of the outer anode and outer cathode is communicated to the inner anode and inner cathode of the series cells by charge accumulation around the terminals. The charge attraction between ions in the electrolyte results in an ion migration between terminals. The increased current and ion flow results in the adjustment of the rate of reaction. Eventually, the current transient dampens, and the same current flows through the whole circuit (conductors, load, and cells in series), thereby meeting and matching the current flow through the load. **Long Answer:** *Battery Chemistry Example: (single cell)* * Circuit: resistive load, one cell, lead-acid battery, open circuit. * The voltage of a single cell is $2.05\ \mathrm V=1.60\ \mathrm V+0.36\mathrm V$ * The anode half-cell oxidation reaction is: $\mathrm{Pb+SO\_4^{2-}\to PbSO\_4+2e^-}$ * The cathode half-cell reduction reaction is: $\mathrm{PbO\_2+SO\_4^{2-}+2e^-+4H^+\to PbSO\_4+H\_2O}$ * *Anode electrolyte Reaction:* $\mathrm{H^+}$ and $\mathrm{SO\_4^{2-}}$ ions migrate as needed to maintain charge neutrality. $\mathrm{SO\_4^{2-}}$ ions are removed from the electrolyte by the anode reaction with $\mathrm{Pb}$. Two electrons are left on the anode, resulting in a net positive charge in the electrolyte around the anode. The excess $\mathrm{H^+}$ ions migrate toward the cathode, where $\mathrm{O\_2^{2-}}$ ions react with $\mathrm{H^+}$ ions to produce $\mathrm{H\_2O}$, which neutralizes the net charge in the electrolyte. * *Why does the anode reaction stop in an open circuit?* The anode reaction spontaneously proceeds and liberates electrons, which accumulate on the surface of the anode. $\mathrm{H^+}$ ions in solution are attracted to the electrons on the anode, effectively creating a net positively charged ion layer covering the entire anode. This positive layer of $\mathrm{H^+}$ ions attracts $\mathrm{SO\_4^{2-}}$ ions from the electrolyte, but they cannot penetrate the $\mathrm{H^+}$ ion layer to react with the $\mathrm{Pb}$. When the battery circuit is closed, current flows and the excess electrons on the plate move to the cathode, the $\mathrm{H^+}$ ion layer disperses, and the $\mathrm{SO\_4^{2-}}$ ions migrate to the $\mathrm{Pb}$ plate and react. * *Cathode electrolyte reaction:* the overall reaction is: $\mathrm{4H^+O^{2-}\to2H\_2O}$. This reaction neutralizes, a) $\mathrm{2H^+}$ from the anode, b) $\mathrm{2H^+}$ from the cathode, with c) $\mathrm{O^{2-}}$ from the cathode, d) resulting in $\mathrm{H2O}$. * *Electrolyte current:* Electrons flow from anode to cathode through a conductor, but there is also charge movement in the electrolyte by ion migration where $\mathrm{H^+}$ ions migrate from anode to cathode. A big picture view of battery charge movement is 1) electrons move from anode to cathode through a conductor, and 2) those electrons combine with $\mathrm{H^+}$ ions at the cathode. The battery maintains overall net electric charge neutrality, but internally the anode and cathode are reservoirs of separated positive and negative charge, both on the terminals and in the electrolyte. The charge differential between terminals produces the associated $E$ field potential energy gradient, which is utilized to perform work. The battery converts the electrostatic-bond energy of one atomic/molecular species into another lower energy species. The energy is converted into an $E$ field by creating a charge separation scenario, which produces electric charge neutrality in the electrolyte. However, the reaction sequence is more complex than that. The cathode releases $\mathrm{O^{2-}}$ from the $\mathrm{PbO\_2+SO\_4^{2-}+2e^-}$ reaction, the $\mathrm{H^+}$ ions react with the $\mathrm{O^{2-}}$ and convert it to water. If the $\mathrm{H^+}$ had reacted with a free electron at the cathode, it would have formed $\mathrm{H\_2}$ gas. * *Series Cell Electrostatics and Electrochemistry:* The same chemical reactions occur in the individual cells whether in a circuit as a single cell or in series. The difference is the amount of current drawn by the series batteries vs. the single cell through the same resistive load. An electrical potential is generated by the half-cell reactions composing a battery. The anode and cathode reactions generate an open circuit potential, which results in a current flow proportional to the voltage when the circuit is closed. When cells are placed in series, the voltage of the two cells adds, resulting in a doubled $E$ field in the space surrounding the batteries. As a result, the higher voltage across the load draws twice the current. This current/rate of electron removal doubles the rate of reaction in the cells. Thus, because the voltage is (essentially) constant from a single battery the controlling factor in current flow is the load (lower resistance, higher current). But, if batteries were placed in series and the load was kept constant, the current would double and the reaction rate would double because the voltage had doubled. *Single Cell Example: Lead-Acid battery, $10\ \mathrm{Ah}$ charge* * Load $R=4.1\ \mathrm\Omega$ * Voltage $V=2.05\ \mathrm V$ * Total stored charge $q\_\text{total} = 10\ \mathrm{Ah} =10\ \mathrm{C/s}\times3\,600\ \mathrm{s/h}\times1\ \mathrm h=36\,000\ \mathrm C$ * Current flow $I=V/R=2.05\ \mathrm V/4.1\ \mathrm\Omega=0.5\ \mathrm A$ * Operating time $q\_\text{total}/I=36\,000\ \mathrm C/0.5\ \mathrm A=72\,000\mathrm s=72\,000/3\,600=20\ \mathrm h$ * Power consumption: $P=IV=0.5\ \mathrm A\times2.05\ \mathrm V=1.025\ \mathrm W$ * Total energy storage: $\Delta E=P\times\Delta t=1.025\ \mathrm W\times20\ \mathrm h=20.5\ \mathrm{Wh}$ * Total energy storage: $\Delta E=IV\times\Delta t=V\times(I\cdot\Delta t)=2.05\ \mathrm V\times10\ \mathrm{Ah}=20.5\ \mathrm{Wh}$ *Series Cell Example: Lead-Acid battery, $10\ \mathrm{Ah}$ per cell, same load* * Load $R=4.1\ \mathrm\Omega$ (i.e. same circuit, but with two cells in series) * Voltage $V=2.05\ \mathrm V+2.05\ \mathrm V=4.1\ \mathrm V$ * Total charge storage = $q\_\text{total}=10\ \mathrm{Ah}=36\,000\ \mathrm{As}=36\,000\ \mathrm C$ (Note: Full discharge after delivering $36\,000\ \mathrm C$ of charge. Both batteries have stored $36\,000\ \mathrm C$ each, but the discharge of one cell passes its electrons from the anode of one the the cathode of the second. Thus, the discharge of 36K coulombs depletes both batteries at the same time.) * Current flow: $I=V/R=4.1\ \mathrm V/4.1\ \mathrm\Omega=1\ \mathrm A$ * Operating time = $q\_\text{total}/I=36\,000\ \mathrm C/1\ \mathrm A=36\,000\ \mathrm s=10\ \mathrm h$ * Power delivery/consumption: $P=IV=1\ \mathrm A\times4.1\ \mathrm V=4.1\ \mathrm W$ * Total energy storage: $\Delta E=P\times\Delta t=4.1\ \mathrm V\times10\ \mathrm{Ah}=41.0\ \mathrm{Wh}$ * Total energy storage: $\Delta E=IV\times\Delta t=V\times(I\cdot\Delta t)=4.1\ \mathrm V\times10\ \mathrm{Ah}=41.0\ \mathrm{Wh}$ **Battery Principles:** **Conservation of Charge:** The above single battery contains $10\ \mathrm{Ah}$ of charge, which equals $36\,000\ \mathrm C$. This is the total amount of charge that the battery can deliver as current. Batteries in series, both deplete their electron stores at the same time because all current flows through both batteries. In a closed circuit, at the anode, the reactants react and generate excess electrons. At the cathode, the reactants react with electrons to create products. This proceeds spontaneously and generates a state of electron deficiency at the cathode. The reaction cannot proceed without an outside source of electrons. When electrons conduct from the anode to the cathode, they satisfy the cathode's need for electrons, allowing the cathode reaction to proceed as fast as the electrons are supplied (with limits at upper limits that compete with the maximum reaction rate). When all the reactants at the anode or cathode have reacted to become products is spent, as the battery can no longer supply electrons to, or accept electrons from, the load. The increased current from a series battery source depletes the battery's charge-store twice as fast. The benefit of a higher voltage is a hotter resistor, brighter incandescent lamp, faster DC motor... **Conservation of Energy** The [total energy](https://electronics.stackexchange.com/questions/256426/battery-life-calculation-parallel-vs-series) available to deliver by cells in series is the sum of the stored energy of the individual cells. As per the above examples: a single cell with $10\ \mathrm{Ah}$ of charge has $2.05\ \mathrm V\times10\ \mathrm{Ah}=20.5\ \mathrm{Wh}$ of stored electrical potential energy. Two identical cells in series have $41\ \mathrm{Wh}$ of stored electrical potential energy. Comparing the two circuits: a series battery doubles the voltage and current, resulting in 4 times the power consumption. Thus, even though a circuit with two cells in series holds two times the stored energy, the power consumption increases by four times, resulting in half the battery life. Conversion into any other form of energy satisfies the principle of energy conservation. **Energy Conversion:** As a battery discharges, it converts electrical potential energy into various types of energy in the load. Common conversions of electrical energy include heat, kinetic energy, or gravitational, electrical, and magnetic potential energy. Examples of the types of circuit loads include a resistor (thermal energy), motor (kinetic energy, gravitational potential, electrical potential, magnetic potential), an inductor/electromagnet ($B$ field potential energy), or a capacitor ($E$ field potential energy). **Battery terminal reactions:** In the Lead-Acid battery, before reaction, energy is stored as potential energy by the charge attraction between the chemical reactants at each of the terminals. * *Anode $\mathrm{e^-}$ liberation:* $\mathrm{Pb\_{(s)}}$ and $\mathrm{SO\_4{^{2-}}\_{(aq)}}$ are in metal-electrolyte contact, and will spontaneously react to form $\mathrm{PbS{O\_4}\_{(s)}}$ and $2$ extra electrons. The positive oxidation potential of this half-cell reaction is $+1.69\ \mathrm V$. The positive potential indicates the reaction proceeds spontaneously at room temperature. The reactants attract and react because of electrostatic forces, such as energetically favorable orbital bonding. * *Anode $\mathrm{H^+}$ Shielding:* After $\mathrm{Pb}$ and $\mathrm{SO\_4^{2-}}$ react, the liberated electrons accumulate on the anode, creating a negative $E$ field. The surface electrons attract a layer of $\mathrm{H^+}$ ions. This stops the anode $\mathrm{Pb+SO\_4^{2-}}$ reaction very quickly. The $\mathrm{H^+}$ ion layer bonds with the $\mathrm{SO\_4^{2-}}$ ions preventing them from migrating close enough to the $\mathrm{Pb}$ to react. For the reaction to proceed on the anode, the electrons must be removed. When a conductor connects anode and cathode, electrons flow from a place of excess to a place of deficiency. As the electrons leave the anode, the anode reaction resumes. * *Anode Energy Transfer Sequence:* All energy begins as reactant bond-energy and is converted into another form of energy by the load: 1) Batteries store energy as the bond energy of reactants. The reactants have more bonding energy than the products, so breaking the stronger bonds and remaking weaker bonds mobilizes energy. That energy can be used to convert into other types of energy. An electrostatic force between reactants draws them to react. 2) In an open circuit battery, a small number of the anode half-cell reactions proceed spontaneously to completion at any moment, resulting in the production of excess electrons, which give the battery its characteristic voltage (in combination with its other half-reaction at the cathode. 3) At the anode, the energy differential between the old bonds within the reactants and new bonds within the products is converted to a concentration of free electrons and an associated $E$ field. 4) The anode's $E$ field adds to the cathode's $E$ field (with its electron deficiency), creating a net total $E$ field which permeates the space around the battery. The $E$ field drives electrons as a current through the high permittivity conductor to a load. 5) Passage of current through a load converts current into another form of energy. * *Cathode Reaction:* the equivalent but opposite process of reaction proceeds at the cathode (i.e., reduction of reactants). The free energy is positive for the bonding of $\mathrm{PbO\_2+SO\_4^{2-}+H^++2e^-}$ to produce $\mathrm{PbSO\_4+H\_2O}$, which means this reaction will proceed spontaneously at STP. The reactants require electrons to proceed, and it does so to a small extent, creating a positive $E$ field since the cathode is now electron deficient after the reactant conversion to products consumed electrons. Note, this reaction requires electrons to complete. Even when the circuit is open, a small number of reactants scavenge loosely bound electrons from other atoms or ions. Reaction sequesters those electrons in neutral end products, which results in an electron deficit, a net positive charge on the cathode, and an associated positive $E$ field. The electron deficiency at the cathode is the other half of the battery, which creates a net positive charge and adds to the $E$ field created by the negative charge on the anode. **Current Flow through the Series Batteries:** Batteries in series increase the voltage and current through the load. The current passing through the load also passes through every cell in series. Each cell contributes an $E$ field to the total $E$ field of the batteries in series. And, the sum of the individual $E$ fields drives the current through the load. The outer anode and cathode initially supply the electron source and sink. But, after a transient period, the rate of reaction at every anode and cathode in series equilibrates, and the same current flows through all the cells in series. **Ion migration in the electrolyte of a Lead-Acid battery:** In the lead-acid battery, both anode and cathode reactions produce the same neutral compound, $\mathrm{PbSO\_4}$. In the process, both anode and cathode consume $\mathrm{SO\_4^{2-}}$ ions from solution. At the anode, the reaction leaves a net positive charge in the electrolyte, which is carried by the $\mathrm{H^+}$ ions. - At the cathode, the consumption/bonding of $\mathrm{SO\_4^{2-}}$ with $\mathrm{PbO\_2}$ results in the accumulation of a negative charge in the electrolyte. This is because the reaction of $\mathrm{PbO\_2}$ with $\mathrm{SO\_4^{2-}}$ and $\mathrm{2e^-}$ results in the liberation of $\mathrm{O\_2^{2-}}$. The negative charge in the electrolyte around the cathode attracts the $\mathrm{H^+}$ ions, from the anode, resulting in the reaction of $\mathrm{4H^+}$ ions with one $\mathrm{O\_2^{2-}}$ ion to produce $\mathrm{2H\_2O}$. Thus, in lead-acid batteries, charge neutrality in the electrolyte solution surrounding the solution is maintained by the migration of unpaired $\mathrm{H^+}$ ions from the anode to cathode. **Battery as Capacitor:** The battery acts as a capacitor when in an open circuit. Opposite charges populate the anode and cathode, and this charge differential is separated by a thin dielectric layer of $\mathrm{H^+}$ and $\mathrm{SO\_4^{2-}}$ ions surrounding the anode. This dielectric layer disperses when current flows through a conductor from the anode to the cathode. Conduction removes the excess electrons from the anode, thereby breaking the ionic bond between the $\mathrm{H^+}$ and $\mathrm{SO\_4^{2-}}$ ions. Dispersal of the $\mathrm{H^+}$ layer around the anode enables $\mathrm{SO\_4^{2-}}$ ions to flow past the previously impermeable $\mathrm{H^+}$ ion layer. * *Difference between a battery and capacitor:* The comparison between a capacitor and battery is incomplete. When in an open circuit, the two behave as charge-storing devices, with both storing charge on either side of a dielectric. The battery has two modes: 1) open circuit: the capacitor and battery configuration are comparable, and 2) closed circuit, the dielectric disperses, and the battery becomes a charge differential generator, using bond-energy liberation from reactants to create products with a differential concentration of charge. * *[Capacitive, Field, and Power Flow effects](http://amasci.com/elect/poynt/poynt.html):* in the air around a battery and conductor. The open circuit voltage across a battery's terminals acts as an air dielectric capacitor. The charge between terminals polarizes the dielectric of the air/space, producing a small displacement current until charged. However, a conductor is also a capacitor (in the most general sense of the word) since a conductor has a dielectric constant. Placing a conductor between a battery' terminals produces a large displacement current. The Electric Displacement Field is a capacitive effect, causing polarization of the metallic dielectric. The current flowing through the conductor is an attempt by the battery voltage to charge the dielectric of the metal. Since the dielectric constant is so large, the electric displacement field is essentially unlimited. Therefore, the current in the circuit is limited by the resistance of the load, rather than the electric permittivity of the conductor. * *Electric Permittivity and Conductivity:* The conductor provides a high electric permittivity $\epsilon\_\text{conductor}$ path for the $E$ field to act. The equivalent circuit to the conductor is a huge capacitor in series with a tiny resistor. The massive electric permittivity $\epsilon\_\text{conductor}$ of the metallic conductor provides insignificant capacitive impedance. The current flow of a conductor is not similar to the high-velocity trajectory of particle accelerator. Rather, current flow through a conductor is like an atomic executive pendulum, with the microscopic motion of individual electrons at the anode transmitting the repulsive force of their incremental change in proximity from electron to electron from the anode to the cathode. The conductor is a capacitor with a dielectric constant so high that the size of the capacitor is infinite (for practical purposes), as the capacitive effects of a conductor are significant only at high frequencies. At low frequencies/DC, the equivalent size of the conductor-capacitor is so large that it will never fully charge. * *Electric Displacement Field [$D$](https://en.wikipedia.org/wiki/Electric_displacement_field):* A conductor provides a high electrical permittivity path in which the electric field [$E$](https://en.wikipedia.org/wiki/Electric_field) acts (units: volt/meter = newton/coulomb) act on charge to exert a force on electrical charge. The $E$ field of a battery polarizes the dielectric between the plates of a capacitor. The electric permittivity of the vacuum of space is a measure of the capacitance of space and is denoted as $\epsilon\_0$ and is $8.85\times10^{-12}\ \mathrm{F/m}$). Vacuum is the smallest possible electric permittivity and all other materials are expressed as a ratio, a multiple of $\epsilon\_0$. An $E$ field acting in a space with $\epsilon\_0)$ will have a electric displacement field $D=\epsilon\_0E$, which has units of $\mathrm{C/m^2}$. The $\epsilon\_\text{air}$ is approximately equal to vacuum permittivity, and that permittivity is very low, so minimal charge is stored on the terminals. However, in a conductor, the $\epsilon\_\text{conductor}$ is large, which means that for any given $E$ field the electric displacement field (in $\mathrm{C/m^2}$) will be large, and the closed circuit current through a conductor alone is very high. In a series connection of two cells, the $E\_\text{series}$ field is double the electric potential of a single cell, hence drives and double the current. **Forces acting inside series cells:** Placing two lead-acid cells in series doubles the voltage, and hence doubles the current across the load. That same current will pass through the conductor between the two cells in series, and the ions in the electrolyte of both cells will likewise conduct charge at the same rate. All of the cathodes accept electrons to complete the $\mathrm{PbO\_2+SO\_4^{2-}+2e^-+4H^+\toPbSO\_4+2H\_2O}$ reaction. And, all the anodes generate electrons in the $\mathrm{Pb+SO\_4^{2-}\toPbSO\_4+2e^-}$ reaction. * Two batteries in series will draw twice the current through the same load. The higher current increases the demand for electrons from the anode and increases the supply of electrons to the cathode. * The increased demand for electrons at the anode removes electrons from the products side of the reaction, accelerating the anode reaction, causing it to liberate more electrons at a rate commensurate with demand. The anode supplies current at the rate demanded by the energy consumption rate at the anode for the reaction voltage. * The increased supply of electrons at the cathode supplies more electrons to the reactant side of the reaction, allowing it to increase its reaction rate by producing more products. The increased current causes the cathode reaction to increase its rate of consumption. * *Consider the chemical reactions acting at the inner anode and inner cathode of the batteries in series.* (Note: the terms "inner anode" and "inner cathode" refer to the terminals which make contact between the cells.) * Placing a second cell in series, the voltage across the load increases, which doubles the current through the load. The increased current draws away the excess electrons, which disperses the $\mathrm{H^+}$ ion layer, which allows $\mathrm{SO\_4^{2-}}$ to react with the $\mathrm{Pb}$ at a greater rate, and increases the concentration of $H^+$ ions. The positive charge around the anode draws $\mathrm{O\_2^{2-}}$ ions to migrate from the inner cathode to the outer anode. By increasing the concentration of reactants, by Le Chatlier's principle, the cathode reaction is driven toward products, making the inner cathode more positive, and drawing electrons from the inner anode, which increases its reaction rate, and draws $\mathrm{O\_2^{2-}}$ ions from the outer cathode in the same way as the outer anode. * And, at the outer cathode, electrons arrive from the outer anode through the load, resulting in a current of electrons which supplies the outer cathode with electrons to for its reaction. * In sequence, the increased voltage increases the current flow through the load, which draws off electrons from the outer anode and supplies them to the cathode, which increases the rate of reaction at both the outer anode and outer cathode. In turn, the outer anode affects the inner cathode reaction, and the outer cathode affects the inner anode, both via the modification of the migration rate of ions, which in turn changes the reaction rate at the inner anode and cathode. **Summary:** With the higher voltage delivered by cells in series, the load draws an increased current. The reaction rate at the anode increases the current supplied in response. As current arrives at the cathode, the cathode reaction rate increases. The inner anode and inner cathode follow the lead of the outer anode and cathode, increasing their reaction rates - influenced by ion migration in the electrolytes of the two cells. After a short transient, the systems reach a steady state where the reaction rates at all anodes and cathodes match the current demand at the load.
One way to think of this is as follows: for your two-battery system with the batteries in series, the positive terminal of battery "A" doesn't know or care what voltage the negative terminal of battery "B" is presenting to it. All battery "A" is going to do is pull electrons out of its positive terminal, lift them to a potential that is N volts greater than this (where N is the battery's rated voltage) and present them to its negative terminal. In practice, this means that the voltages of batteries in series are linearly additive.
2,064,701
Let $\lim\_{n \to \infty} a\_n = a$. Then $\lim\_{n \to \infty} \frac {a\_1 + ... +a\_n} {n} = a $ How one can prove it?
2016/12/19
[ "https://math.stackexchange.com/questions/2064701", "https://math.stackexchange.com", "https://math.stackexchange.com/users/375772/" ]
Take any $E$ satisfying the Carathéodory condition. Consider first the case where $m^\*(E)$ is finite. The general case can be deduced by splitting $E$ into countably many pieces of finite outer measure. 1. Note that any open set of finite measure can be approximated by an elementary set, that is, if $U$ is open of finite measure we can find for any $\varepsilon>0$ an elementary set $A$ with $m(U\triangle A)<\varepsilon$. (This is an easy consequence of countable additivity and the fact that any open set is a countable union of intervals.) Deduce that the Carathéodory condition also works for open sets of finite measure in place of elementary sets. 2. Choose any $\varepsilon>0$ and an open set $U$ such that $U\supseteq E$ and $m(U)<m^\*(E)+\varepsilon$ (you have this more or less by definition of outer measure). By Carathéodory, we have $$ m^\*(E\cap U)+m^\*(U\setminus E)=m(U),$$ but $E\cap U=E$, so in fact $$ m^\*(E)+m^\*(U\setminus E)=m(U)<m^\*(E)+\varepsilon,$$ and, since $m^\*(E)$ is finite, we obtain $$ m^\*(U\setminus E)<\varepsilon.$$
I know that this is an old post but the existing answers don't seem to use the 'restricted' version of Caratheodory. Pick an open set such that $m^\*(O)\leq m^\*(E) + \epsilon$ for some $\epsilon > 0$. $$m^\*(O)=\color{red}{ \Sigma m^\*(B\_n) \geq \Sigma(m^\*(B\_n \cap E) + m^\*(B\_n-E))}\geq m^\*(\cup B\_n\cap E)+m^\*(\cup B\_n-E)\\=m^\*(E)+m^\*(O-E)$$ This leads to $$m^\*(E)+\epsilon \geq m^\*(O)=m^\*(E)+m^\*(O-E)$$ Or $$\epsilon \geq m^\*(O-E)$$ We have not even used the Caratheodory criterion for elementary sets. We have only used them for boxes. We have used the fact that open sets are just disjoint, countable boxes and the countable subadditivity of outer measure. **The place where Caratheodory criterion is used is highlighted in red.**
87,141
I'm trying to get the description of a table in oracle because I need to know what foreign keys does it have and which tables they refer to. I'm using desc but all I get is "ORA-00900: invalid SQL statement" Any idea why? Thanks.
2014/12/29
[ "https://dba.stackexchange.com/questions/87141", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/55043/" ]
I suspect that you did not execute this command with sqlplus. Not every sql program can handle the `desc` command. You can either use sqlplus or get the table definition with the following SQL command: ``` SELECT dbms_metadata.get_ddl (object_type, object_name, owner) FROM all_objects WHERE owner = '<owner>' AND object_name LIKE '<whatever_table>%'; ``` This will give you the complete table definition with all column definitions.
The statement is not recognized as a valid SQL statement. This error can occur if the Procedural Option is not installed and a SQL statement is issued that requires this option (for example, a CREATE PROCEDURE statement). You can determine if the Procedural Option is installed by starting SQL\*Plus. If the PL/SQL banner is not displayed, then the option is not installed. you action should be Correct the syntax or install the Procedural Option.
2,863,925
Let $(A\_\*,\partial )$ and $(B\_\*,\partial' )$ be chain complexes, $f:A\_\*\to B\_\*$ a chain map and suppose that the map $f\_\*$ it induces on homology is an isomorphism. The mapping cone $(C\_\*,D)$ is defined by $C\_n=A\_{n-1}\oplus B\_n$ and $D\_n(a\_{n-1},b\_n)=(-\partial\_{n-1}a\_{n-1},f\_{n-1}(a\_{n-1})+\partial'\_n b\_n).$ Now, define $A\_n^+=A\_{n-1}.$ Then, using the maps $i:b\mapsto (0,b)$ and $p:(a,b)\mapsto a$, there arises in the usual way, the long exact sequence $$ \cdots \rightarrow H\_{n+1}(C)\overset{p\_\*}\rightarrow H\_{n+1}(A^+)\overset{f\_\*}\rightarrow H\_n(B)\overset{i\_\*}\rightarrow H\_n(C)\overset{p\_\*}\rightarrow H\_n(A^+)\rightarrow \cdots $$ Then, $H\_n(C)$ is trivial for all $n$. The proof is easy (but hadn't occurred to me, ugh.) I wanted to do it using the basic facts about the chain complexes involved, to get an idea of how they work. There is a proof from scratch of essentially the same thing [here](https://math.stackexchange.com/questions/1645714/f-induces-an-isomorphism-in-homology-iff-the-mapping-cone-of-f-is-contra/1645731#comment5907907_1645731) but I think I found a problem with it, and made a comment there. I would appreciate feedback on my comment there as well as on my attempt here at a from scratch proof, which follows. What I have so far (dropping the subscripts and primes on the differentiation operators): Let $(a,b)\in Z\_{n}(C).$ Then, by exactness, we have have the following: $1).\ p\_\*([(a,b)]=[a]\Rightarrow a\in Bd\_{n}A^+$ and $2).\ i\_\*([b])=[(0,b)]\Rightarrow (0,b)\in Bd\_{n}C.$ So, there is an $a'\in A\_n$ and a pair $(a'',b')\in C\_{n+1}$ such that $3).\ \partial a'=a$ and $4).\ (-\partial a'',f(a'')+\partial b')=(0,b).$ Combining these facts we get $(a,b)=(a,0)+(0,b)=(-\partial (a'+a''),f(a'')+\partial b').$ If I could show that either $f(a')=0$ or $\partial a'=0$, I would then have $(a,b)\in Bd\_nC,$ which is what I want.
2018/07/26
[ "https://math.stackexchange.com/questions/2863925", "https://math.stackexchange.com", "https://math.stackexchange.com/users/138929/" ]
That is probably not the answer you are looking for, but here is a proof using model category theory. Somehow, it says that this is a result not about chain complexes per se, and it is a motivation not to dive into chain complexes details. In any model category $\mathcal C$, the mapping cone $C\_f$ of $f:X\to Y$ is defined as the homotopy pushout of $\ast \overset !\gets X \overset f\to Y$. Computing homotopy pushout in a model category goes as follow: take a cofibrant replacement $X'\overset q\to X$ of $X$. Factor $fq$ as $pi$ with $p$ acyclic fibration and $i$ cofibration. Factor $!q$ as $p'i'$ with $p'$ acyclic fibration and $i'$ cofibration. Then take the ordinary pushout of $\bullet \overset {i'} \gets X' \overset i \to \bullet$. This is summed up in the following diagram: [![enter image description here](https://i.stack.imgur.com/VO345.png)](https://i.stack.imgur.com/VO345.png) In particular, $q,p,p'$ are weak equivalences, so if $f$ is also a weak equivalence, we get that $i$ is an acyclic fibration. It follows that its pushout $j$ also is such. In the end, we have a commutative triangle: [![enter image description here](https://i.stack.imgur.com/D5tYo.png)](https://i.stack.imgur.com/D5tYo.png) where $p'$ and $j$ both are weak equivalences, which yields that $C\_f \to \ast$ is also a weak equivalence. Otherwise put, $C\_f$ is contractible. --- If you play that proof in your favorite model structure on chain complexes for which weak equivalences are the quasi-isomorphisms, you get the result you wanted.
Assuming your question is why $C$ has trivial homology: $f\_\*$ is an isomorphism, so $p\_\*$ and $i\_\*$ must both be zero maps.
141,725
Inspired by [a bug](https://tio.run/##S9ZNT07@/z9TJ8s6TSM5I7FIq1izujwjMydVA8RKyy/SyLI1M7XOsrE0tM7S1tbUKra1zbIvKMrMK0nTUNMqBgpZQXlKCkqa1gWlJcUaSkBGbe3/3MTMPA2gIRpKUZER4WGhIcFBgQH@fr4@3l6eHu5uri7OTo4glf8B) in a solution to [this challenge](https://codegolf.stackexchange.com/q/141372/61563), your challenge is to produce this exact text: ``` ZYXWVUTSRQPONMLKJIHGFEDCBA YXWVUTSRQPONMLKJIHGFEDCBA XWVUTSRQPONMLKJIHGFEDCBA WVUTSRQPONMLKJIHGFEDCBA VUTSRQPONMLKJIHGFEDCBA UTSRQPONMLKJIHGFEDCBA TSRQPONMLKJIHGFEDCBA SRQPONMLKJIHGFEDCBA RQPONMLKJIHGFEDCBA QPONMLKJIHGFEDCBA PONMLKJIHGFEDCBA ONMLKJIHGFEDCBA NMLKJIHGFEDCBA MLKJIHGFEDCBA LKJIHGFEDCBA KJIHGFEDCBA JIHGFEDCBA IHGFEDCBA HGFEDCBA GFEDCBA FEDCBA EDCBA DCBA CBA BA A ``` * The first line will have 25 spaces, then the alphabet backwards starting from the 26th letter (`ZYXWVUTSRQPONMLKJIHGFEDCBA`), then a newline. * The second line will have 24 spaces, then the alphabet backwards starting from the 25th letter (`YXWVUTSRQPONMLKJIHGFEDCBA`), then a newline. * ... * The last (26th) line will have no spaces, then the alphabet backwards starting from the 1st letter (`A`), then a newline. Additional rules: * Your program may use any allowed output methods. * One trailing newline and/or one leading newline is allowed. * There must be one newline between lines containing the letters, no more. * The letters must be all uppercase. As with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest submission wins. Good luck! Leaderboard: ```js var QUESTION_ID=141725,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ```css body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ```
2017/09/05
[ "https://codegolf.stackexchange.com/questions/141725", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/61563/" ]
[Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ========================================================== ``` ØAµ⁶ṁḊ;ṚµƤṚY ``` [Try it online!](https://tio.run/##y0rNyan8///wDMdDWx81bnu4s/Hhji7rhztnHdp6bAmQivz/HwA "Jelly – Try It Online") ``` ØAµ⁶ṁḊ;ṚµƤṚY Main Link ØA "ABC...XYZ" Ƥ For each prefix, µ⁶ṁḊ;Ṛµ Monadic Link ⁶ ' ' ṁ (with automatic repetition) molded to the shape of Ḋ All but the first letter of the input (repeat - 1) ; With the input appended to it Ṛ reversed Y Join on newlines Ṛ Flip upside down ``` -3 bytes thanks to miles
[Husk](https://github.com/barbuz/Husk), 15 bytes ================================================ ``` mṠ+ȯR' ←Lhṫ…"ZA ``` [Try it online!](https://tio.run/##ASAA3/9odXNr//9t4bmgK8ivUicg4oaQTGjhuavigKYiWkH//w "Husk – Try It Online") -5 thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb). Still a newb :p
142,866
I've seen dozens of articles on NFTs, and not comprehended a single one. So when someone [made an NFT of the first Twitter posting](https://decrypt.co/60437/tron-ceo-justin-sun-bids-1000000-for-the-first-ever-tweet), I didn't understand how that would be a means to generate any sort of financial return. Even if the *copyright* on the posting was sold, it was too short to copyright, and the news articles about the NFT quoted the post. This is even more true for [today's article](https://finance.yahoo.com/news/russia-hermitage-museum-partners-binance-151424977.html) about NFTs corresponding to Leonardo da Vinci and Van Gogh paintings, which are entirely public domain. (Unless there's some scheme afoot to retroactively lock up all of humanity's heritage.. hope not..) The inference I'm guessing at is that NFT is something like Bitcoin, only the proof of work is in trying to round up the author or present owner of some obscure work and getting them to sign a piece of paper? But how is that even *scarce*? If tomorrow I said that I'm issuing Non Comprehensible Tokens and start mailing out unique digital codes for each species or exoplanet or chapter of the Bible, would I be making money the exact same way? Do the NFTs even have a value, or are they just a written excuse for wealthy people to hand each other money for reasons only they understand? Interim comment: I've seen a huge response and many thought-provoking ideas, but I still don't think we've reached the full answer. To me the most striking observation so far was Kevin's comparison to an artwork consisting of [a (replaceable) banana taped to a wall](https://en.wikipedia.org/wiki/Comedian_(artwork)). I think Jamesqf's answer of conspicuous consumption may be the start of something. And Damian Yerrick's description of [other rights bundled with an NFT](https://www.usatoday.com/story/entertainment/movies/2021/04/15/kevin-smith-auctioning-new-film-nft-killroy-here/7244602002/) may give a good hint. David Jacobsen runs with that a little by pointing out the NFT issuers aren't nobodies (though they also certainly aren't da Vinci and Van Gogh). I'll add my suspicion that comparisons involving the "[Million Dollar Homepage](https://en.wikipedia.org/wiki/The_Million_Dollar_Homepage)" or naming rights could be fertile. This may be a means of buying publicity, some of which is preloaded in the abundant news coverage; I don't know if there are other terms to the NFT sales to ensure that purchasers will be prominently credited in museums. The field still seems open for someone to give a new and more persuasive answer.
2021/07/27
[ "https://money.stackexchange.com/questions/142866", "https://money.stackexchange.com", "https://money.stackexchange.com/users/110867/" ]
The other answers so far have missed an important point. As with a lot of expensive art, the object itself is almost beside the point. What's really at work is status seeking. By spending a lot of money on some "art object", even ones that most of us would throw out with the trash, you demonstrate that you: a) have lots of money b) have the "taste" necessary to be accepted into the society that values that sort of thing This is explained in much more detail in the book ["The $12 Million Stuffed Shark"](https://us.macmillan.com/books/9780230620599).
They are valuable because people value them. The same way that people like to own other trinkets that have no particular use. In many cases, people like to "own" something, even if that thing can easily be copied. As an analogy, would you rather have a Van Gogh painting, or a *really good* copy of a Van Gogh painting? If you don't care then NFTs aren't for you. Most people would rather have the original painting. NFTs are the way to say "I own the original version of this tweet, all the others are just copies".
1,008,430
Why doesn't my iis Server pick up changes to local code? I've changed both css/js files and changed some images but iis just doesn't update anything on the website. I've tried restarting the website and refreshing it on the iis manager but nothing changes. However when i edit the web.config file it detects it automatically. Why is this? and how can I let the iis server website know that I have changed local files.
2020/03/26
[ "https://serverfault.com/questions/1008430", "https://serverfault.com", "https://serverfault.com/users/565585/" ]
Are you using any kind of CDN that has the page cached? If so, you can purge the cache of that URL. Also test if the changes update when you use Private Browsing/Incognito Mode on your browser. If this shows the updated page, then it is your browser cache that needs to be cleared. But to really solve the problem, you'll want to version the JS page. <https://stackoverflow.com/questions/1011605/clear-the-cache-in-javascript>
I think the problem is your browser cache. For Chrome and Firefox you can try `Ctrl`+`F5` to force refresh the page. Failing that press `Ctrl`+`Shift`+`Del` and clear the cache.
389,981
I am diving in the domain driven design (DDD) and while I go more deeply in it there are some things that I don't get. As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.). What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for. Doing those calculations inside the Domain Layer and working with a lot of sets in it is like throwing away the SQL technology. Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen. Is that a pitfall of the DDD pattern?
2019/04/08
[ "https://softwareengineering.stackexchange.com/questions/389981", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/333103/" ]
If you've ever been on a project where the organization paying to host the application decides that the database layer licenses are too expensive, you'll appreciate the ease of which you can migrate your database/data storage. All things considered, *while this does happen, it doesn't happen often*. You can get the best of both worlds so to speak. If you consider performing the complex functions in the database an optimization, then you can use an interface to inject an alternate implementation of the calculation. The problem is that you have to maintain logic in multiple locations. **Deviating from an architectural pattern** When you find yourself at odds with implementing a pattern purely, or deviating in some area, then you have a decision to make. A pattern is simply a templated way to do things to help organize your project. At this point take time to evaluate: * Is this the right pattern? (many times it is, but sometimes it's just a bad fit) * Should I deviate in this one way? * Just how far have I deviated so far? You'll find that some architectural patterns are a good fit for 80-90% of your application, but not so much for the remaining bits. The occasional deviation from the prescribed pattern is useful for performance or logistical reasons. However, if you find that your cumulative deviations amount to a good deal more than 20% of your application architecture, it's probably just a bad fit. If you choose to keep going with the architecture, then do yourself a favor and document where and why you deviated from the prescribed way of doing things. When you get a new enthusiastic member on your team, you can point them to that documentation which includes the performance measurements, and justifications. That will reduce the likelihood of repeat requests to fix the "problem". That documentation will also help disincentivize rampant deviations.
One of the possible ways to solve this dilemma is to think of SQL as of an assembly language: you rarely, if at all, code directly in it, but where performance matters, you need to be able to understand the code produced by your C/C++/Golang/Rust compiler and maybe even write a tiny snippet in assembly, if you cannot change the code in you high level language to produce desired machine code. Similarly, in realm of databases and SQL, various SQL libraries (some of which are [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)), e.g. [SQLAlchemy](https://en.wikipedia.org/wiki/SQLAlchemy) and Django ORM for Python, [LINQ](https://en.wikipedia.org/wiki/Language_Integrated_Query) for .NET, provide higher level abstractions yet use generated SQL code where possible to achieve performance. They also provide some portability as to the used DB, possibly having different performance, e.g. on Postgres and MySQL, due to some operations using some more optimal DB-specific SQL. And just as with high level languages, it is critical to understand how SQL works, even if it is just to rearrange the queries done with above mentioned SQL libraries, to be able to achieve desired efficiency. P.S. I would rather make this a comment but I do not have sufficient reputation for that.
14,181,744
I'm trying to display a custom yes/no product attribute only if "yes" is selected. Here's my code so far: ``` <?php $freeship = Mage::getModel('catalog/product')->load($this->getProduct()->getId())->getAttributeText('free_shipping_discount'); if ($freeship == "yes") echo '<span class="free-ship">FREE SHIPPING</span>'; ?> ``` It doesn't produce errors but it doesn't display anything either. Any suggestions? Thanks
2013/01/06
[ "https://Stackoverflow.com/questions/14181744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1906850/" ]
You should have something like: ``` CELERYBEAT_SCHEDULE = { 'proc': { "task": "tasks.processing", "schedule": timedelta(seconds=60), }, } ``` in your `celeryconfig.py` or in django's settings.py See full documentaion here <http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html>
Check your system time-zone if is the same as Django time zone. For Django: Change it from settings file. For linux operating system: change it like that: `ln -s /usr/share/zoneinfo/America/Chicago /etc/localtime`
60,037,706
Hi I am working on laravel project , I have to check about user's permission when he trying to access one page , my problem is after I created Permission middle ware , and add it in the kernel.php , it checking about permissions for all route even I did not call it in any route . I don't want to apply this middleware on all route , just some of it . this is my permission middleware's code ``` namespace App\Http\Middleware; use Closure; use Session; use App\Rules; use Illuminate\Support\Facades\Route; use URL; class Permissions { public function handle($request, Closure $next) { $rolename=Session::get('rule_name') ; $route = $request->path(); $hasPermission = Rules::where('rule_name', 'superadmin')->where('allowed_pages', 'like', '%' . $route . '%') ->first(); if (empty($hasPermission)) { echo 'Unauthorized.<a href="' . URL::to('/admin') . '">Go Back</a>'; die(); } } } } ``` and this is my route file ``` Route::resource('Login', 'LoginController')->name('index','Login'); Route::resource('Backup', 'BackupController')->name('index','Backup'); ``` as you see I did not apply the middleware on these tow route , but the middleware is working with these tow routes this is my kernel code ``` protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, 'Permissions' => \App\Http\Middleware\Permissions::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; ``` I want to run this middleware only by route like this ``` Route::group(['middleware' => 'permissions'], function () { Route::resource('Backup', 'BackupController')->name('index','Backup'); } ``` thank you for advance best regards
2020/02/03
[ "https://Stackoverflow.com/questions/60037706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8376370/" ]
I understand the problem as you want the most recent value for all countries, as the country can repeat in the table(?): ``` select distinct t1.DAY, t1.COUNTRY, t1.VALUE FROM day_test t1 inner join day_test t2 on t1.day in (select max(day) from day_test t3 where t1.country = t3.country ) and t1.country = t2.country ``` I tested it and it works.
You can use the following query: Just replace the `TABLE_NAME` with the name of your table. ``` SELECT COUNTRY, VALUE, MAX(DATE) AS "MostRecent" FROM TABLE_NAME GROUP BY COUNTRY; ```
11,996,005
I'm trying to paste my query results from Mgmt Studio to Excel, but for whatever reason the columns in Mgmt Studio are concatenated into a single column when pasted into Excel. This doesn't happen to any of my colleagues and we couldn't find any settings for changing this. Any ideas?
2012/08/16
[ "https://Stackoverflow.com/questions/11996005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149945/" ]
I have solved this problem in my SSMSBoost add-in for SSMS: it has possibility to export grid as native OpenXMLSpreadsheet, which can be easily "understood" by excel. As "bonus" to solution of your problem you will also see that even datatypes are preserved, so no problems anymore with conversion of dates to text or text to numbers... Check it out.
I get this too and in the past i would shut down excel. I realized after a while that every day i do text to columns for a specific spreadsheet and i change the delimiter to other /. When i change it back to tab, it works fine.
47,484,838
I am making a timer as part of my app. I followed a tutorial, and made some modifications to the program to better suit my needs. However, when I run the app, I get the default value of the timerTextView (defined in xml), or just random numbers. What is going wrong? **Update**: Here is the coomplete code for the activity: ``` public class Main7Activity extends AppCompatActivity { private TextView countDownText; private CountDownTimer countDownTimer; //private long timeLeftInMilliseconds = 1000*60*60*24*7*1; public TextView textView3; public TextView textView4; public TextView textView5; public TextView textView6; public long timeLeftInMilliseconds; //private int daysToGo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main7); textView3 = (TextView) findViewById(R.id.testText); textView4 = (TextView) findViewById(R.id.testText2); textView5 = (TextView) findViewById(R.id.testText3); textView6 = (TextView) findViewById(R.id.testText4); //textView3.setText(Integer.toString(Main6Activity.progress2)); Calendar now = Calendar.getInstance(); textView3.setText("LMP date : " + Main6Activity.textView.getText()); int currentDayOfYear = now.get(Calendar.DAY_OF_YEAR); //Day of year is the LMP date now.set(Calendar.DAY_OF_YEAR, Main6Activity.progress2); int lmpDate = now.get(Calendar.DAY_OF_YEAR); //Day of year is due date now.add(Calendar.DAY_OF_YEAR, 7*40); textView4.setText("Due Date: " + now.get(Calendar.DATE) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.YEAR)); int dueDate = now.get(Calendar.DAY_OF_YEAR); if (dueDate < 365 && lmpDate > 82){ dueDate = dueDate + (365); } if (lmpDate<82 && lmpDate>49){ dueDate = dueDate + lmpDate; } if (lmpDate<50) { textView5.setText("Congratulations on Delivery"); } else { textView5.setText(Integer.toString(dueDate)); } //textView5.setText(now.getTime().toString()); //int currentDayOfYear = Calendar.DAY_OF_YEAR; int daysToGo = dueDate - currentDayOfYear; textView6.setText(Integer.toString(daysToGo)); timeLeftInMilliseconds = 1000*60*60*24*daysToGo; countDownText = (TextView) findViewById(R.id.weeks); startTimer(); } public void startTimer(){ countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) { @Override public void onTick(long millisUntilFinished) { timeLeftInMilliseconds = millisUntilFinished; updateTimer(); } @Override public void onFinish() { } }.start(); } public void updateTimer(){ int weeks = (int) timeLeftInMilliseconds / 604800000; int days = (int) (timeLeftInMilliseconds % 604800000) / 86400000; //int hours = (int) (timeLeftInMilliseconds % 86400000) / 3600000; //int minutes = (int) (timeLeftInMilliseconds % 3600000) / 60000; int seconds = (int) (timeLeftInMilliseconds % 60000) / 1000; String timeLeftText; timeLeftText = ""; if (weeks < 10) timeLeftText += "0"; timeLeftText += weeks; timeLeftText += ":"; if (days < 10) timeLeftText += "0"; timeLeftText += days; //timeLeftText += ":"; //if (hours < 10) timeLeftText += "0"; //timeLeftText += hours; //timeLeftText += ":"; //timeLeftText += minutes; //timeLeftText += ":"; if (seconds < 10) timeLeftText += "0"; timeLeftText += seconds; countDownText.setText(timeLeftText); } public void editInfo(View v){ Intent intent = new Intent(Main7Activity.this, Main6Activity.class); startActivity(intent); } ``` } I also need the timer to run in the background. Will this code do that? Thanks.
2017/11/25
[ "https://Stackoverflow.com/questions/47484838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8555405/" ]
It looks that [Microsoft has neglected this topic](https://connect.microsoft.com/SQLServer/feedback/details/234143/populate-has-default-value-in-sys-parameters) and there is no trivial way to find parameters default values and even if a default value is present or not on a specific parameter: > > As we all know, T-SQL stored procedure parameter defaults are not > stored in sys.parameters, all\_parameters, and system\_parameters. They > are also not exposed through sp\_sproc\_columns, sys.columns, or > sp\_procedure\_params\_rowset. > > > Feedback from Microsoft: > > As posted by Tibor Karaszi, BOL document that "SQL Server only > maintains default values for CLR objects in this catalog view; > therefore, this column has a value of 0 for Transact-SQL objects. To > view the default value of a parameter in a Transact-SQL object, query > the definition column of the sys.sql\_modules catalog view, or use the > OBJECT\_DEFINITION system function." > > > We dont store even the bit that indicating parameter is of default > value in Yukon. > > > I have tested the first code snippet [in this answer](https://stackoverflow.com/a/15786683/2780791) and it seems to work for your simple example: ``` SELECT data3.name , [default_value] = REVERSE(RTRIM(SUBSTRING( data3.rtoken , CASE WHEN CHARINDEX(N',', data3.rtoken) > 0 THEN CHARINDEX(N',', data3.rtoken) + 1 WHEN CHARINDEX(N')', data3.rtoken) > 0 THEN CHARINDEX(N')', data3.rtoken) + 1 ELSE 1 END , LEN(data3.rtoken) ))) FROM ( SELECT data2.name , rtoken = REVERSE( SUBSTRING(ptoken , CHARINDEX('=', ptoken, 1) + 1 , LEN(data2.ptoken)) ) FROM ( SELECT data.name , ptoken = SUBSTRING( data.tokens , token_pos + name_length + 1 , ISNULL(ABS(next_token_pos - token_pos - name_length - 1), LEN(data.tokens)) ) FROM ( SELECT sm3.tokens , p.name , name_length = LEN(p.name) , token_pos = CHARINDEX(p.name, sm3.tokens) , next_token_pos = CHARINDEX(p2.name, sm3.tokens) FROM ( SELECT sm2.[object_id] , sm2.[type] , tokens = REVERSE(SUBSTRING(sm2.tokens, ISNULL(CHARINDEX('SA', sm2.tokens) + 2, 0), LEN(sm2.tokens))) FROM ( SELECT sm.[object_id] , o.[type] , tokens = REVERSE(SUBSTRING( sm.[definition] , CHARINDEX(o.name, sm.[definition]) + LEN(o.name) + 1 , ABS(CHARINDEX(N'AS', sm.[definition])) ) ) FROM sys.sql_modules sm WITH (NOLOCK) JOIN sys.objects o WITH (NOLOCK) ON sm.[object_id] = o.[object_id] JOIN sys.schemas s WITH (NOLOCK) ON o.[schema_id] = s.[schema_id] WHERE o.[type] = 'P ' AND s.name + '.' + o.name = 'dbo.Sample1' ) sm2 WHERE sm2.tokens LIKE '%=%' ) sm3 JOIN sys.parameters p WITH (NOLOCK) ON sm3.[object_id] = p.[object_id] OUTER APPLY ( SELECT p2.name FROM sys.parameters p2 WITH (NOLOCK) WHERE p2.is_output = 0 AND sm3.[object_id] = p2.[object_id] AND p.parameter_id + 1 = p2.parameter_id ) p2 WHERE p.is_output = 0 ) data ) data2 WHERE data2.ptoken LIKE '%=%' ) data3 ``` However, it is really ugly for a task that one expects to be easily queryable from system views.
I implemented Alexei's brilliant solution, but one of my variables, and a comment on a parameter both had the word 'class' in it and I couldn't for the life of me figure out why it broke. I finally realized that the word 'class' has 'AS' in it. So the key to avoiding that situation is to differentiate the AS keyword denoting the beginning of the body of the sp from random AS strings in the parameter section. I found a way that works for me, and might work for others. It relies on the fact that the AS keyword is on its own line prededed by CHAR(13) + CHAR(10) and succeeded by CHAR(13) + CHAR(10). So I modified these two lines: ``` , tokens = REVERSE(SUBSTRING(sm2.tokens, ISNULL(CHARINDEX(CHAR(10) + CHAR(13) + 'SA' + CHAR(10) + CHAR(13), sm2.tokens) + 2, 0), LEN(sm2.tokens))) , tokens = REVERSE(SUBSTRING( sm.[definition] , CHARINDEX(o.name, sm.[definition]) + LEN(o.name) + 1 , ABS(CHARINDEX(CHAR(13) + CHAR(10) + N'AS' + CHAR(13) + CHAR(10), sm.[definition])) ) ```
282,101
I have to store some amount of data for analytical purposes. * The data source produces 2TB data per month. * Data is collected on a monthly basis (not real-time). * Data is fully structured. * There are 100+ different columns of data. * Availability of SQL is important. * Engineer/developer resources are limited. I planned to use Postgres (probably with column-oriented extension), however, it would not be feasible for such data amounts (more than 20TB per year). I also made a research on Hadoop/Spark, however, it looks like a bit massive solution (considering, that the data is fully structured). I don't consider cloud-based solutions, as well as expensive ones (preferably, free-licence) . Would you be so kind to suggest, which data storage to use for big amounts of structured data for analytical purposes?
2020/12/24
[ "https://dba.stackexchange.com/questions/282101", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/220335/" ]
Aside from the recommendations made by Danielle and J.D., I suggest you examine how the data is represented and the frequency. For example, if the data is transmitted in a JSON or XML format, which is handy for transmission and processing, the size will be large (e.g. a numeric string vice a float or an int). Also, string identifiers (e.g. serial number, credit card number) can be made into PK/FK relationships that could save space. Your data sampling frequency may be higher than what is realistically usable. For example, if you get weather data at 10 samples/sec but your analysis only has 1 hour resolution, you have a lot more weather data than you can use. Perhaps resampling the data to a lower frequency (e.g average and standard deviation, low-pass filter) and storing that might be a better solution. You can always archive the raw data--archival storage for a years worth of data is not very expensive.
How many rows of data is generated in a month of 2 TB of data? In a year's time, how many months back will still be queried? In 5 years, how many years back of data needs to still be queried?...in 10 years, and in 20 years? What's the most amount of months (or rows of data) that will need to be queried at one time? What type of analytics will need to be done, quantitative (aggregative and arithmetic based), or more qualitative? These are just a subset of all the important questions to weigh when deciding a database solution, especially at the scale of data you're trying to plan for. Unfortunately there's no direct answer to "which database system should you choose" because there are many factors. And to be honest, most of them can handle even the scale of data you're talking about. PostgreSQL should be able to handle that much data (though I haven't personally worked with it on that scale yet, but from my research and understanding). I know Microsoft SQL Server definitely can handle a data warehouse at that scale (again depending on your specific use cases based on the questions above), as I have worked with one not far off from it, and the analytical queries we ran took seconds to process. Although throwing money at hardware isn't the primary recommended solution to a database's performance problems (proper schema design, index design, and process design will go the longest of ways) I would say it does help and is worth considering making sure your non-Cloud based server has decent hardware behind it. NVMe's go a long way these days in terms of improving generally the biggest hardware bottleneck (the disk). Having a decent amount of RAM and CPUs will be helpful too. (E.g. in the Microsoft SQL Server data warehouse I mentioned above, we had 32 GB of RAM and an 8 Core CPU. It probably could've benefitted from doubling both of those, but worked quite well as is too.) The other benefits of Microsoft SQL Server (though other database systems probably have some sort of equivalent) is you can setup an [AlwaysOn Availability Group](https://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/overview-of-always-on-availability-groups-sql-server?view=sql-server-ver15) to ensure constant uptime through redundancy. It's easy to setup and you can also query off your replicas as way to horizontally shard the load when querying the data.
1,409,548
I have the following connection string, and you will notice "Provider's.Tests", notice the single quote, how do I enter this in to the web.config to make it valid? ``` <connectionStrings> <clear/> <add name="Provider" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Projects\Provider's.Tests\app_data\db.mdf";Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/> </connectionStrings> ```
2009/09/11
[ "https://Stackoverflow.com/questions/1409548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58309/" ]
I don't think its the `Provider's` that is the problem, It is the double quotes around the path. Try to just remove it so it says `AttachDbFilename=C:\Projects\Provider's.Tests\app_data\db.mdf;` If it is important in the connection string to have it, try encoding it: `AttachDbFilename=&quot;C:\Projects\Provider's.Tests\app_data\db.mdf;&quot;`
You should encode both the quotation marks and apostropes. Quotation marks (") are encoded using `&quot;` and apostrophes (') are encoded using `&apos;`. The main issue here is the quotation marks, it might still work without encoding the apostrophes as you use quotation marks around the values. ``` <connectionStrings> <clear/> <add name="Provider" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=&quot;C:\Projects\Provider&apos;s.Tests\app_data\db.mdf&quot;;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/> </connectionStrings> ```
9,626,059
Obviously, window.onbeforeunload has encountered its fair share of problems with Chrome as I've seen from all the problems I've encountered. What's the most recent work around? The only thing I've got even close to working is [this](https://stackoverflow.com/questions/4802007/window-onbeforeunload-not-working-in-chrome): ``` window.onbeforeunload = function () { return "alert" }; ``` However, if I substitute return "alert" with something like alert("blah"), I get nothing from Chrome. I saw in [this question](https://stackoverflow.com/questions/6790854/window-onbeforeunload-not-working-in-chrome) that Google purposefully blocks this. Good for them... but what if I want to make an AJAX call when someone closes the window? In my case, I want to know when someone has left the chatroom on my website, signalled by the window closing. I want to know if there's a way to either (a): fix the window.onbeforeunload call so that I can put AJAX in there or (b): get some other way of determining that a window has closed in Chrome
2012/03/08
[ "https://Stackoverflow.com/questions/9626059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/872150/" ]
As of Chrome 98.0.4758.109 and Edge 100.0.1185.29, Chromium has not met the standard. There is a [bug report](https://bugs.chromium.org/p/chromium/issues/detail?id=866818) filed, but the [review](https://chromium-review.googlesource.com/c/chromium/src/+/1154225) is abandoned. [Test with StackBlitz!](https://stackblitz.com/edit/web-platform-txmlss?file=script.js) * Chrome requires returnValue to be a non-null value whether set as the return value from the handler or by reference on the event object. * The [standard states](https://html.spec.whatwg.org/multipage/browsing-the-web.html#beforeunloadevent) that prompting can be controlled by canceling the event or setting the return value to a [non-null value](https://html.spec.whatwg.org/multipage/webappapis.html#events). * The standard states that authors should use Event.preventDefault() instead of returnValue. * The [standard states](https://html.spec.whatwg.org/multipage/browsing-the-web.html#unloading-documents) that the message shown to the user is not customizable. ```js window.addEventListener('beforeunload', function (e) { // Cancel the event as stated by the standard. e.preventDefault(); // Chrome requires returnValue to be set. e.returnValue = ''; }); window.location = 'about:blank'; ```
Here's a more straightforward approach. ``` $(window).on('beforeunload', function() { return "You should keep this page open."; }); ``` The returned message can be anything you want, including the empty string if you have nothing to add to the message that Chrome already shows. The result looks like this: ![enter image description here](https://i.stack.imgur.com/clEqf.png)
45,365,658
Why is it necessary to run 'npm install' when I already have all the dependence in node\_module folder. After running 'npm install' successfully on my machine, I want to setup same project on another machine, why do I require run 'npm install' again when I already have downloaded all the dependence in node\_module folder?
2017/07/28
[ "https://Stackoverflow.com/questions/45365658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2810015/" ]
First of all I want to inform you 2 things: * As your project depend on some packages (node\_modules), same as some packages are dependent on other packages. * when we install some package with command `npm install package -g` then -g will install it in global folder which can be accessed by any project. by using -g, package is not added to node\_modules. Now here is answer of your problem. There might be possible that some dependencies of packages are installed as global on one machine and not on other one. This can happen as developers work on many project on same machine and might be they have installed global packages. So in this case you need to execute `npm install` command.
`npm install` extract all your dependencies from your package.json, download it and save them in your node\_modules folder. You don't need to run npm install again and again if you already have installed all your dependencies locally. When ever you installs a new dependency you run `npm install <package-name> --save` and why `--save` for the first time? because it adds the new installed dependency on your package.json. We never push node\_modules to our git repo only the updated package.json is pushed to repo. In that case if a new person pulls your code from the repo he is only going to run `npm install` and all the dependencies mentioned on your package.json will going to available on his project locally. Thats a small intro about why we use package.json hope it helps.
23,569,056
Can someone explain to me why `ArrayIndexOutOfBoundsException` is a run-time exception instead of a compile-time error? In obvious cases when the indexes are negative or greater than the array size, I don't see why it cannot be a compile-time error. Edited: especially when the size of the array and even the indexing is known at compile time, for example `int[] a = new int[10]; a[-1]=5;` This should be a compilation error.
2014/05/09
[ "https://Stackoverflow.com/questions/23569056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2824271/" ]
The size of the arrays may be defined only at runtime (for instance, the simplest case, if the size of an array depends on the user input). Therefore it would be impossible to check at compile time for such kind of exceptions, by checking the accesses of an array without actually know its bounds (size).
As well as agreeing with the fact that array size can't be checked at compile time, I want to add another note on the limit of the size of an array, which is expected to be in the range of primitive `int`: ``` // This compiles, because the size evaluates to an integer. int[] array = new int[Integer.MAX_VALUE + 1]; // This doesn't compile. int[] array = new int[Long.MAX_VALUE]; ``` And this error is because of `length` field (`int`) of arrays which are special Java objects.
532,634
Suppose a rocket at rest turns on its jet and is now moving with kinetic energy $\frac12 mv^2$ in the lab frame. Suppose the efficiency was maximum so that exactly $\frac12mv^2$ of chemical energy was just converted to this kinetic energy. Energy is conserved, obviously. Now suppose I stay in the rocket's frame. In this frame, the rocket stays at rest but now the whole universe, say with mass $M\gg m$, is now moving towards me with energy $\frac12 Mv^2$. Energy was clearly not conserved in this frame. Presumably this is because it is an accelerating frame, and energy is only conserved in inertial frames. But my intuition says that as the acceleration approaches zero, the results should be the same as in an inertial frame. However, it is easy to check that this huge energy violation persists for arbitrarily small accelarations and at arbitrarily short times. What is wrong with my thinking?
2020/02/23
[ "https://physics.stackexchange.com/questions/532634", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/212603/" ]
> > What is wrong with my thinking? > > > There are a couple of points where you make key errors. The first (and least important) is here: > > Suppose the efficiency was maximum so that exactly $\frac{1}{2}mv^2$ of chemical energy was just converted to this kinetic energy. > > > This is not possible for a rocket that begins at rest because it does not simultaneously conserve momentum. For a rocket at rest, at that moment, all of the power goes into the KE of the exhaust, not the rocket. Even assuming no waste of any kind, the only time that 100% of the KE goes into the rocket is at the moment that the speed of the rocket equals the exhaust velocity. In general, for a constant $\Delta PE$ of the chemical potential energy in the fuel the $\Delta KE$ of the rocket depends strongly on the speed of the rocket. > > In this frame, the rocket stays at rest but now the whole universe, say with mass ≫, is now moving towards me with energy $\frac{1}{2}Mv^2$. Energy was clearly not conserved in this frame. Presumable this is because it is an accelerating frame, and energy is only conserved in inertial frames. But my intuition says that as the acceleration approaches zero, the results should be the same as in an inertial frame. However, it is easy to check that this huge energy violation persists for arbitrarily small accelarations and at arbitrarily short times. > > > In the rocket frame the universe is subject to a fictitious gravitational acceleration $g$. So if the universe falls through this fictitious gravity field for a time $t$ then the velocity of the universe is $v=gt $. So we can write the KE of the universe as $\frac{1}{2}M(gt)^2$. If we expand that to first order in $t$ we get $0+O(t^2)$ and if we expand that to first order in $g$ we get $0+O(g^2)$. Therefore your intuition is correct. Since you didn’t post your math it is impossible to know what led to the mistake, but at least in this case you are correct to intuit that as the time or the acceleration go to 0 so does the energy violation. Be aware, if the acceleration is constant in time then it is possible to make a potential energy in this frame and recover conservation of energy. The universe falls through the gravitational field losing PE and gaining KE, thus conserving energy. That only works if the acceleration is constant.
In an inertial frame, you should not see chemical energy being converted into kinetic energy. If you do, then you are also experiencing acceleration, and you will not be in an inertial frame.
14,604,733
I've been through the various answers here with this one already, but none give an answer that actually works. The core issue (obviously) is that DateTime hasn't any concept of NULL, so the usual ``` string dateValue = myReader.IsDBNull (4) ? null : myReader.GetDateTime(4) ; ``` doesn't work. I've tried ``` DateTime? nextDue = myReader.GetDateTime(3) == DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3) ; ``` but that gives ``` Operator '==' cannot be applied to operands of type 'System.DateTime' and 'System.DBNull' ``` Changing to ``` DateTime? nextDue = myReader.GetDateTime(3) = DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3) ; ``` produces ``` Cannot implicitly convert type 'System.DBNull' to 'bool' ``` I ended up changing the SQL to not output NULL values, but I'd still like to crack this one, as it will be useful elsewhere
2013/01/30
[ "https://Stackoverflow.com/questions/14604733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971352/" ]
Firstly Your syntax here: ``` DateTime? nextDue = myReader.GetDateTime(3) = DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3) ; ``` id wrong. Should be: ``` DateTime? nextDue = myReader.GetDateTime(3) == DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3) ; ``` Secondly you could use: ``` DateTime? nextDue = myReader.IsDBNull(3) ? null : (DateTime?)myReader.GetDateTime (3) ; ```
try ``` DateTime? nextDue = myReader.GetValue(3) == DBNull.Value ? null : (DateTime?)myReader.GetDateTime (3); ```