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
42,266,147
I am trying to get the XPath for `Search Results:`. However when I giving it `//span[@class='zeiss-font-Md aletssubtitle']` it's not detecting the text, it's detecting the span ``` <div class="col-xs-12"> <div class="col-xs-5" style="padding:0"> <div> <span class="zeiss-font-Md aletssubtitle" style="line-height:3.2"> Search Results : <label class="ACadmincount"> 1 Matching Results</label> </span> </div> </div> </div> ```
2017/02/16
[ "https://Stackoverflow.com/questions/42266147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7572947/" ]
You cannot use `XPath` with `selenium` to get text node like @Sunil Garg suggested (`//span[@class='zeiss-font-Md aletssubtitle']/text()`). It's syntactically correct `XPath` expression, but `selenium` doesn't support this syntax: > > selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//text()" is: [object Text]. It should be an > element. > > > It you want to get complete or partial text content of a particular element, you can use something like *Python* ``` span = driver.find_element_by_xpath("//span[@class='zeiss-font-Md aletssubtitle']") span.text # returns 'Search Results : 1 Matching Results' driver.execute_script('return arguments[0].childNodes[0].nodeValue.trim()', span) # returns 'Search Results :' ``` *Java* ``` WebDriverWait wait = new WebDriverWait(webDriver, 10); WebElement span = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[@class='zeiss-font-Md aletssubtitle']"))); String text = span.getText(); JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("return arguments[0].childNodes[0].nodeValue.trim()", span); ```
It's simple, you can try : ``` //*[text()='Search Results :'] ``` Hope this will help you.
893,112
I'm migrating from iptables to firewalld, using Centos 7. In the old times, I used to write the (permament) iptables rules in the `/etc/sysconfig/iptables` , which also served to place comments prepended by `#` (to remind us why we restricted this or that ip, etc). Now, it seems that the current (permanent) configuration is read from `/etc/firewalld/` files (especially `/etc/firewalld/zones/*.xml`). I guess I could add xml comments there, but it seems the good practice is not to edit those files directly but via `firewall-cmd` (no?). Hence, I'm not sure which is the standard or recommended way to add comments to the rules. Any suggestions? Edited: For the record, I've verified that xml comments do not survive `firewall-cmd` modifications.
2018/01/19
[ "https://serverfault.com/questions/893112", "https://serverfault.com", "https://serverfault.com/users/38966/" ]
Thinking it over, I'm finding this `firewalld-cmd` thing slightly silly. After all, XML configuration files are human editable. It makes little sense to me, having to learn an extra layer of commands (well, one command, but with [tons of arguments](http://www.firewalld.org/documentation/man-pages/firewall-cmd.html)) only to edit some simple and neat XML files (\*). I fell slightly stupid typing `firewall-cmd --permanent --zone=work --add-port=445/tcp` just for addding the following line to `/etc/firewalld/zones/work.xml` `<port protocol="tcp" port="445"/>` Hence, at least for now, and considering that the XML elements don't include comment attributes (there are [some](https://github.com/firewalld/firewalld/issues/194) [requests](https://github.com/firewalld/firewalld/issues/269) in that direction) I'm leaning towards the following strategy: just forget about `firewalld-cmd` (perhaps even delete it), edit the XML files yourself, and add XML comments freely. (\*) It's true that `firewalld-cmd` allows also to add dynamic (non permanent) rules. But I'd bet that that is not a very frequent scenario.
Although in the firewall-cmd man page, there is a section on Direct Options, that allow you to give parameters, so you could do something like: `firewall-cmd --direct --add-rule <table> <chain> <priority> <args> -c <some comment>` Although, as Michael Hampton said, probably not the best thing.
14,738,067
I'm a novice. I want to concatenate 3 fields (city, provinceName, countryName) from MySQL into comma separated strings and return the strings in JSON with "city" as the key. I can't get the strings and I can't construct them into complete text in JSON. My PHP is: ``` $fetch = mysql_query("SELECT DISTINCT city GROUP_CONCAT(DISTINCT city, stateProvinceName, countryName SEPARATOR ',') FROM neighborhoods WHERE countryAbbreviation='$countryAbbreviation' AND stateProvinceName IS NOT NULL ") or die(mysql_error()); while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)){ $row_array['city'] = $row['city']; array_push($return_arr,$row_array); } echo json_encode($return_arr); ``` When I test the query, it is not comma separated. Instead I get Quebec CityQuebecCanada. When I run the web site, the JSON response is only {"city":"Quebec City"}. The desired response is {"city":"Quebec City, Quebec, Canada"} - or in a general case, multiple "city" objects. What should I change. Please be specific. I don't follow general instructions well.
2013/02/06
[ "https://Stackoverflow.com/questions/14738067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/693756/" ]
A byte array is just a byte array. It's just got data in. How you *interpret* that data is up to you. What's the difference between a text file and a string, for example? Fundamentally, if your application needs to know how to interpret the data, you've got to put that into the protocol.
A byte array is just a byte array. However, you could make the original byte array include a byte that describes what type it is (assuming you are the originator of it). Then you find this descriptor byte and use it to make decisions.
8,035,513
I am developing app similar to restaurant locator or bank locator. I was looking through examples of `google places api`. But then I noticed `google local search` using this url <http://ajax.googleapis.com/ajax/services/search/local>. I want to know what is difference between two since both returns places based on lattitude and longitude supplied. Which one is best to use. Thanks in advance.
2011/11/07
[ "https://Stackoverflow.com/questions/8035513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/495906/" ]
[SqlCommand.ExecuteScalar](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx "SqlCommand.ExecuteScalar") ``` // setup sql command and sql connection etc first... int count = (int) cmd.ExecuteScalar(); ```
``` if (ds.Tables[0].Rows.Count > 0) { int i = Convert.ToInt32(ds.Tables[0].Rows[0]["colname"]); } ```
15,186,055
I have a class of which there may be many instances (on a mobile device), so I'm trying to minimize the size. One of my fields is a "DrawTarget" that indicates whether drawing operations are being ignored, queued to a path or drawn to the display. I would like it to take a single byte or less since there are only 3 possible values, but I would also like it to be friendly code so I don't have hard-coded numbers all over. One thought is to use an enum like: ``` public enum DrawTarget { Invisible, Path, Canvas } ``` But from what I read, a Java enum doesn't allow you to specify the memory layout -- I can't request that the enum values represent a byte-size value -- and I guess enum values end up being integer-sized values in Java. So I thought about maybe making an implicit conversion operator in the enum... is this possible in Java? Or is my best option to implement something like this within the enum: ``` public static DrawTarget fromValue(byte value) { switch (value) { case 0: return Invisible; case 1: return Path; default: return Canvas; } } ``` and then call DrawTarget.fromValue wherever I want to access the value? Or should I just create a single-byte class since apparently (from what I read in my research on this) enums are basically just special classes in Java anyway? ``` public class DrawTarget { public static final byte Invisible = 0; public static final byte Path = 1; public static final byte Canvas = 2; } ``` But how to I represent the value of an enum instance if I use that last solution? I still need a way to allow the "=" operator to accept one of the static fields of the class... like a conversion constructor or an assignment operator overload. I suspect, however, that any class object, being a reference type, will take more than a byte for each instance. Is that true?
2013/03/03
[ "https://Stackoverflow.com/questions/15186055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78162/" ]
> > and I guess enum values end up being integer-sized values in Java. > > > No, enums are always *classes* in Java. So if you have a field of type `DrawTarget`, that will be a reference - either to `null` or to one of the three instances of `DrawTarget`. (There won't be any more instances than that; it's not like a new instance of `DrawTarget` is created every time you use it.) I would go with the enum and then measure the memory usage - an enum is *logically* what you want, so take the normal approach of writing the simplest code that works and then *testing* the performance - rather than guessing at where bottlenecks might be. You *may* want to represent the value as a single byte when serializing, and then convert it back to the enum when deserializing, but other than that I'd stick with the enum type throughout your code if possible.
Your classes will only contain a reference to the enum. Only one instance of each enum will be created. Aside from that, consider using polymorphism to implement the drawing behavior. If the value of the enum is fixed, instantiate a different subclass for each object depending on its desired drawing behavior. If the value changes often, you could keep a reference to the desired drawing strategy in the object. Refer to an object with an empty draw() method for objects that should not be drawn. Etc.
11,189,545
I get the exception from the title when I run my app. What it does is it has a .txt file with words for a Hangman game and I think the exception is thrown when accessing the file. My file, cuvinte.txt is located into /assets/. Here is my code (i skipped the layout/xml part, which works fine): ``` public void onCreate() { // all the onCreate() stuff, then this: try { AssetManager am = this.getAssets(); InputStream is = am.open("cuvinte.txt"); InputStreamReader inputStreamReader = new InputStreamReader(is); BufferedReader b = new BufferedReader(inputStreamReader); String rand; while((rand=b.readLine())!=null){ cuvinte.add(rand); } } catch (IOException e) { Toast.makeText(this, "No words file", Toast.LENGTH_LONG).show(); e.printStackTrace(); } newGame(newG); } public void newGame(View view){ Random rand = new Random(); String stringCuvant = cuvinte.get(rand.nextInt(cuvinte.size())); cuvant.setText(""); System.out.println(stringCuvant); for(int i = 0; i< stringCuvant.length(); i++){ cuvant.append("_ "); } incercari.setText(valIncercari); } ``` The function newGame() is called both when the new game button is pressed and at the beginning of the activity, in the onCreate() function.
2012/06/25
[ "https://Stackoverflow.com/questions/11189545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048172/" ]
Using DataBinding and setting background to the `EditText` with resources from the drawable folder causes the exception. ```xml <EditText android:background="@drawable/rectangle" android:imeOptions="flagNoExtractUi" android:layout_width="match_parent" android:layout_height="45dp" android:hint="Enter Your Name" android:gravity="center" android:textColorHint="@color/hintColor" android:singleLine="true" android:id="@+id/etName" android:inputType="textCapWords" android:text="@={viewModel.model.name}" android:fontFamily="@font/avenir_roman" /> ``` **Solution** I just change the background from `android:background="@drawable/rectangle"` to `android:background="@null"` Clean and Rebuild the Project.
You are assigning a numeric value to a text field. You have to convert the numeric value to a string with: ``` String.valueOf(variable) ```
45,188,174
I am currently working in a form. I have some issue with multiple file upload validation. I have only one field in a form which allows multiple file upload. ``` <input type="file" name="file[]" multiple="multiple"> ``` And this is my validation, ``` $this->validate($request, [ 'file' =>'required', 'file.*' => 'required|mimes:pdf,jpeg,png |max:4096', ], $messages = [ 'mimes' => 'Only PDF, JPEG, PNG are allowed.' ] ); ``` The validation works perfectly but I am not able to display error messages in blade file. Here are my attempts. ``` @if($errors->has('file')) <span class="help-block"> <strong>{{$errors->first('file')}}</strong> </span> @endif ``` This is for displaying error if no file is uploaded. Suppose I have uploaded following files, ``` abc.jpg abc.html abc.pdf ``` When mimes type validation throws error I am not able to display error message. Here in this case, error is thrown as `$error->first(file.1)` since validation fails at index 1 This index can be any index according to files uploaded and `$error->first(file.*)` doesn't work as well. When I display all error after adding invalid files only from form, I've got these errors. ``` Only PDF, JPEG, PNG are allowed. The type field is required. The number field is required. The expiry date field is required. ``` Any one have idea about this. Any help is appreciated. Thanks,
2017/07/19
[ "https://Stackoverflow.com/questions/45188174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6708661/" ]
You can use check for the images. ``` $errors->has('file.*') ```
If anyone is still struggling with multiple file upload issues, here is a working solution for this: Validation Rules in Controller ============================== ``` $validated = $request->validate([ 'files.*' => 'mimes:pdf,jpeg,png|max:4096', 'files' => 'required', ], $messages = [ "files.required" => "You must upload atleast one file", "files.*.mimes" => "This file type is not allowed", "files.*.max" => "Max file size is 4Mb", ]); ``` And in blade view, display the errors like so ============================================= ```html <form action="{{ url('/multifile') }}" method="POST" enctype="multipart/form- data"> @csrf <div class="form-group"> <label>Select files</label> <input type="file" class="form-control-file @error('files') 'is-invalid' @enderror" name="files[]" multiple> @error('files') <span class="invalid-feedback d-block" role="alert"> <strong>{{ $message }}</strong> </span> @enderror @error('files.*') <span class="invalid-feedback d-block" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <button class="btn btn-secondary" type="submit">Submit</button> </form> ``` And if you are looking to show all the errors in blade view, (for all files being uploaded) you could consider using something like this in your blade view: ```html @if ($errors->any()) <div class="invalid-feedback d-block" role="alert"> <ul> @foreach (json_decode($errors) as $file_index => $error) <li> <strong>{{$file_index.': '}} <ul> @foreach ($error as $error_item) <li>{{$error_item}}</li> @endforeach </ul> </strong> </li> @endforeach </ul> </div> @endif ```
16,611,704
I'm trying to return the value of a checkbox to enable and disable a button. Making the checkbox is not a problem, the problem is the check box value always returns on. How should I get a value indicating if the checkbox is checked? HTML: ``` <form> <input type="checkbox" id="checkbox" /> <label>Do you agree </label><br /> <input type="button" value="Continue" id="button" disabled="disabled" /> </form> ``` Javascript: ``` $('#checkbox').change(function(){ var checkboxValue = $(this).val(); alert(checkboxValue); }); ```
2013/05/17
[ "https://Stackoverflow.com/questions/16611704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It seems that you need `checked` ``` var checkboxValue = this.checked; ```
A couple of things is going on here 1. the check box as is does not have a value 2. you should be checking to see if its checked or not try this ``` $('#checkBox').prop('checked'); ``` if its checked you should get back true and false if its not checked.
1,639,197
I'm looking at notes on the threshold for random 2-sat which is given as $r\_{2}^{\*}=1$. In the first part of proving the threshold they claim that a 2-sat formula is satisfiable if and only if the graph of implications does not contain a cycle containing a variable and it's negation. In the calculation it says the following "We will actually work with a slightly stronger sufficient condition, namely: the formula is satisfiable if it does not contain a bicycle, which is defined as follows." Definition 7.6: For $k ≥ 2$, a bicycle is a path $(u,w\_{1},w\_{2},...,w\_{k},v)$ in the graph of implications, where the $w\_{i}$’s are literals on distinct variables and $u, v ∈ \{w\_{i}, \overline{w}\_{i} : 1 ≤ i ≤ k\}$. I can understand the calculations they use given this fact, but can someone try and give an outline of why it's true that if the graph of implications of a 2-sat formula does not contain a cycle then the formula is satisfiable? Or equivalently if a forumula is not satisfiable then it contains a bicycle.
2016/02/03
[ "https://math.stackexchange.com/questions/1639197", "https://math.stackexchange.com", "https://math.stackexchange.com/users/154686/" ]
Let $C$ be a $2$-CNF formula. We prove that if $C$ is unsatisfiable then there is some variable $x$ such that $x$ is reachable from $\bar x$ and vice versa in the implication graph $G(C)$. The proof uses induction on the number $n$ of variables in $C$. **Base case.** If $n = 1$ then $C$ must contain clauses $x \vee x$ and $\bar x \vee \bar x$ and hence the edges $(x, \bar x), (\bar x, x)$ are in $G(C)$. **Inductive step.** Let $C$ has $n > 1$ variables. Choose some variable $t$ such that either $t$ is not reachable from $\bar t$ or vice versa (if there is no such variable then the statement holds). Assume the latter case and let $Q$ be the set of vertices reachable from $t$, we have $\bar t \notin Q$. If $q \in Q$ then $\bar q \notin Q$. For otherwise there are paths $P\_1$ and $P\_2$ from $t$ to $q$ and $\bar q$ respectively. By reversing $P\_2$ (using contraposition) we obtain a path from $q$ to $\bar t$ and hence we have a path from $t$ to $q$ to $\bar t$, that is $\bar t \in Q$, a contradiction. Let $V(Q)$ be the set of variables with $x \in Q$ or $\bar x \in Q$. Let $V(Q) = \{x\_1, \dots, x\_{|Q|}\}$. Define a mapping $v \colon V(Q) \to \{0, 1\}$ to be the (partial) assingment with $v(x\_i) = 1$ if $x\_i \in Q$ and $v(x\_i) = 0$ if $\bar x\_i \in Q$. This assignment $v$ satisfies all clauses $K$ having at least one variable in $V(Q)$. For assume $p \in V(Q)$. Let $K = p \vee q$, then $K$ is satisfied by $v$ since $v(p) = 1$. If $K = \bar p \vee q$, then we have $q \in Q$ since $K$ produces the edge $(p, q)$ in $G(C)$ and $p$ is reachable from $t$. So $v$ satisfies $K$ since $v(q) = 1$. Finally, denote by $C'$ the new $2$-CNF formula obtained from $C$ by the removal of all clauses containing a variable in $V(Q)$. Note the following: 1. $G(C')$ is a subgraph of $G(C)$. 2. $C'$ is unsatisfiable since $C$ is, while all removed clauses are satisfiable by $v$. 3. $C'$ has $n - |Q|$ variables (and $|Q| > 0$). Hence by the inductive hypothesis there is a variable $x$ in $C'$ such that $x$ is reachable from $\bar x$ and vice versa in $G(C')$ and hence (by 1.) the same holds for $G(C)$.
The implication graph tells you that 'if $x$ is false, then $y$ has to be true' to make some litteral true, and therefore the formula true. So if you have a bicycle, it means that you have a sequence of implications that say that for some $w\_i$, $w\_i$ has to be true and false to satisfy the formula. Since this is a contradiction the formula is unsatisfiable.
38,322,397
I need to display an image(bmp) in console window using C++ (Windows 10). Not display by characters, for that I already knew how, but show the image pixel by pixel the way ordinary images appears to be. And not by launch another application to show the image in another window, but right in the black console window. I've searched it all over the internet, but didn't seem to find a way to do it without using things like opencv. Is there a way to do it by myself, without opencv?
2016/07/12
[ "https://Stackoverflow.com/questions/38322397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5530828/" ]
Your hypothesis is wrong: in general a C++ (or C) program might not even be started from some "console window" (e.g. it might be started in "batch mode"). In particular, some C++ implementations may run on computers (such as Linux servers in data centers, which are the majority of the servers on Internet) without any screen (so without any console window). Most [top500](https://www.top500.org/) [supercomputers](https://en.wikipedia.org/wiki/Supercomputer) don't have screens you could access, but HPC software running on them (e.g. [Tripoli-4](http://www.cea.fr/energies/tripoli-4/tripoli-4)) is often coded in C++. And embedded computers (e.g. your [RaspberryPi](https://raspberrypi.org/)) can be programmed in standard C++ (e.g. C++11 or C++14) without any screen or console window (e.g. in 2020 using a recent [GCC](https://gcc.gnu.org/) compiler configured for [cross-compilation](https://en.wikipedia.org/wiki/Cross_compiler)) (even on Windows, which I don't know and never used, I am sure that there is some way to start programs -by configuring the computer to start some daemons or servers- before any "console window" exist) So you should define more precisely what your platform is. In general the answer could be platform and operating system specific. See also [OSDEV](https://osdev.org/) for examples of open source operating systems: [FreeBSD](https://freebsd.org/) is a famous one, and has a [GCC](http://gcc.gnu.org/) or [Clang](https://clang.llvm.org/) compiler capable of compiling your C++ application. I would strongly recommend using a portable graphical framework like [Qt](http://qt.io/) (in particular, because it makes your code more portable, if you code carefully). Of course you then requires your user to have it, or your distribute your code with Qt included. Consider also using [FLTK](https://fltk.org/) or [FOX](https://fox-toolkit.org/) or [SFML](https://www.sfml-dev.org/) toolkits. The [C++14](https://en.wikipedia.org/wiki/C%2B%2B14) standard (and C++11 and earlier versions) does not know about images or console windows, so (in general, without mentioning any platform or operating system) your question is meaningless. **Study also for inspiration the source code of existing open source programs or libraries coded in C++** (on [github](https://github.com/) or [gitlab](https://gitlab.com/)), such as the [fish](https://fishshell.com/) shell, [KDE](https://kde.org/), [GCC](https://gcc.gnu.org/), the [Clang static analyzer](https://clang-analyzer.llvm.org/) (and they both should be useful to you), [RefPerSys](http://refpersys.org/), etc etc....
Oh, simply by looking thru (or reverse engineering) the [caca](http://caca.zoy.org/browser/libcaca/trunk/caca/codec/import.c?rev=4876) code ;-) See [example use](http://www.howtogeek.com/howto/linux/stupid-geek-tricks-watch-movies-in-your-linux-terminal-window/).
1,070,813
I've searched around and not found anything quite like the issue I'm having. I have Windows 10 on an NVME drive and I want to install Ubuntu to a second SSD on the same system. I tried earlier and went through the basic install and it seemed successful - the machine booted to Ubuntu. I was expecting the GRUB menu screen and I didn't get it. Am I doing something wrong? Should I install ubuntu manually? If I set a timer to -1 on in `/etc/default/grub` then the GRUB menu will show up but still Windows 10 is not listed. If I hit `esc` on launch I get a `grub>` command interface, and by typing `exit` I get into Windows. I should note that my main display is 1440 and the Ubuntu install defaults to my 1080 display. Could that be an issue? Can't think it would be since GRUB doesn't care. How can I get the GRUB menu to appear on boot with options for Windows 10 and Ubuntu?
2018/08/31
[ "https://askubuntu.com/questions/1070813", "https://askubuntu.com", "https://askubuntu.com/users/865877/" ]
The problem is your if-condition is wrong. It does not do what you think it does. ``` if TouchpadOff=0; then ``` This runs `TouchpadOff=0` as a shell command, which creates a variable `$TouchpadOff` and assigns it the value `0`. As this should normally run successfully, the result is that the condition is always true. You'll have to call the `synclient` command and parse its output to check the state of the TouchpadOff property, like e.g. this way: ``` if [[ "$(synclient | grep 'TouchpadOff' | awk '{print $3}')" -eq 0 ]] ; then ``` This will run `synclient | grep 'TouchpadOff' | awk '{print $3}'`, which parses the output of `synclient` for a line containing "TouchpadOff" and returns the third column of that line. It's inside a command substitution `$( ... )`, so that whole part will be substituted with the output of the inner command. Then `[[ ... -eq 0 ]]` checks whether the substituted output is equal to 0 and makes that the condition for the if-statement.
`TouchpadOff=0` as a condition is interpreted as an assignment, so it's always true (unless the variable is readonly). Use numeric comparison: ``` if (( TouchpadOff == 0 )) ; then ```
15,158,863
The time command returns the time elapsed in execution of a command. If I put a "gettimeofday()" at the start of the command call (using system() ), and one at the end of the call, and take a difference, it doesn't come out the same. (its not a very small difference either) Can anybody explain what is the exact difference between the two usages and which is the best way to time the execution of a call? Thanks.
2013/03/01
[ "https://Stackoverflow.com/questions/15158863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870438/" ]
The Unix `time` command measures the whole program execution time, including the time it takes for the system to load your binary and all its libraries, and the time it takes to clean up everything once your program is finished. On the other hand, `gettimeofday` can only work inside your program, that is after it has finished loading (for the initial measurement), and before it is cleaned up (for the final measurement). Which one is best? Depends on what you want to measure... ;)
`time()` returns time since epoch in **seconds**. `gettimeofday():` returns: ``` struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; ```
5,317,320
I have never done regex before, and I have seen they are very useful for working with strings. I saw a few [tutorials](http://www.vogella.de/articles/JavaRegularExpressions/article.html) (for example) but I still cannot understand how to make a simple Java regex check for hexadecimal characters in a string. The user will input in the text box something like: `0123456789ABCDEF` and I would like to know that the input was correct otherwise if something like `XTYSPG456789ABCDEF` when return false. Is it possible to do that with a regex or did I misunderstand how they work?
2011/03/15
[ "https://Stackoverflow.com/questions/5317320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507512/" ]
Yes, you can do that with a regular expression: ``` ^[0-9A-F]+$ ``` Explanation: ``` ^ Start of line. [0-9A-F] Character class: Any character in 0 to 9, or in A to F. + Quantifier: One or more of the above. $ End of line. ``` --- To use this regular expression in Java you can for example call the `matches` method on a String: ``` boolean isHex = s.matches("[0-9A-F]+"); ``` Note that `matches` finds only an exact match so you don't need the start and end of line anchors in this case. See it working online: [ideone](http://ideone.com/o8Sop) You may also want to allow both upper and lowercase A-F, in which case you can use this regular expression: ``` ^[0-9A-Fa-f]+$ ```
May be you want to use the POSIX character class **`\p{XDigit}`**, so: `^\p{XDigit}+$` =============== Additionally, if you plan to use the regular expression very often, it is recommended to use a constant in order to avoid recompile it each time, e.g.: ```java private static final Pattern REGEX_PATTERN = Pattern.compile("^\\p{XDigit}+$"); public static void main(String[] args) { String input = "0123456789ABCDEF"; System.out.println( REGEX_PATTERN.matcher(input).matches() ); // prints "true" } ```
456,997
I'm having an issue **mounting a shared NAS drive that is hosted on a Windows 2000 server**. This is a drive that I'm certain I have access to, and I frequently access it from a Windows 7 machine and a Windows Server 2008 machine. Now, **I'm attempting to mount this drive from a RHEL7 machine**, but I'm having some issues. **What I've done:** ``` mkdir /mnt/neededFolder mount -t cifs //DNS.forMyDrive.stuff/neededFolder /mnt/neededFolder -o username=myUserId,password=myPassword,domain=myDomain ``` **What I expected:** I expected to be able to access the folder at */mnt/neededFolder* **What actually happened:** The error I'm receiving (partially shown in the subject line here) is ``` mount error(115): Operation now in progress Refer to the mount.cifs(8) manual page (e.g. man mount.cifs) ``` **What the log says:** **dmesg** output: ``` [1712257.661259] CIFS VFS: Error connecting to socket. Aborting operation. [1712257.662098] CIFS VFS: cifs_mount failed w/return code = -115 ``` We can all see that there is a connection issue, that is obvious. I know both machines are connected to the network. **What can I try next to get this drive mounted?** **EDIT:** It may be worth noting that I am able to ping the DNS name and the raw IP of the remote location that I am trying to mount.
2018/07/18
[ "https://unix.stackexchange.com/questions/456997", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/68573/" ]
Well, I had the same problem after I got windows 10 update 1809. The windows firewall was blocking the access. There is a predefined rule for inbound SMB conections that was not activated for private network. Funny thing: It seems to be activated for public networks....
Just replace the network path with the IP address of sharing device ![1](https://i.stack.imgur.com/itz2g.png)
400,209
Given a collection of random points within a grid, how do you check **efficiently** that they are all lie within a fixed range of other points. ie: Pick any one random point you can then navigate to any other point in the grid. To clarify further: If you have a 1000 x 1000 grid and randomly placed 100 points in it how can you prove that any one point is within 100 units of a neighbour and all points are accessible by walking from one point to another? I've been writing some code and came up with an interesting problem: Very occasionally (just once so far) it creates an island of points which exceeds the maximum range from the rest of the points. I need to fix this problem but brute force doesn't appear to be the answer. It's being written in Java, but I am good with either pseudo-code or C++.
2008/12/30
[ "https://Stackoverflow.com/questions/400209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
**New and Improved** ;-) Thanks to Guillaume and Jason S for comments that made me think a bit more. That has produced a second proposal whose statistics show a significant improvement. Guillaume remarked that the earlier strategy I posted would lose uniform density. Of course, he is right, because it's essentially a "drunkard's walk" which tends to orbit the original point. However, uniform random placement of the points yields a significant probability of failing the "path" requirement (all points being connectible by a path with no step greater than 100). Testing for that condition is expensive; generating purely random solutions until one passes is even more so. Jason S offered a variation, but statistical testing over a large number of simulations leads me to conclude that his variation produces patterns that are just as clustered as those from my first proposal (based on examining mean and std. dev. of coordinate values). The revised algorithm below produces point sets whose stats are very similar to those of purely (uniform) random placement, but which are guaranteed by construction to satisfy the path requirement. Unfortunately, it's a bit easier to visualize than to explain verbally. In effect, it requires the points to stagger randomly in a vaguely consistant direction (NE, SE, SW, NW), only changing directions when "bouncing off a wall". Here's the high-level overview: 1. Pick an initial point at random, set horizontal travel to RIGHT and vertical travel to DOWN. 2. Repeat for the remaining number of points (e.g. 99 in the original spec): 2.1. Randomly choose dx and dy whose distance is between 50 and 100. (I assumed Euclidean distance -- square root of sums of squares -- in my trial implementation, but "taxicab" distance -- sum of absolute values -- would be even easier to code.) 2.2. Apply dx and dy to the previous point, based on horizontal and vertical travel (RIGHT/DOWN -> add, LEFT/UP -> subtract). 2.3. If either coordinate goes out of bounds (less than 0 or at least 1000), reflect that coordinate around the boundary violated, and replace its travel with the opposite direction. This means four cases (2 coordinates x 2 boundaries): ``` 2.3.1. if x < 0, then x = -x and reverse LEFT/RIGHT horizontal travel. 2.3.2. if 1000 <= x, then x = 1999 - x and reverse LEFT/RIGHT horizontal travel. 2.3.3. if y < 0, then y = -y and reverse UP/DOWN vertical travel. 2.3.4. if 1000 <= y, then y = 1999 - y and reverse UP/DOWN vertical travel. ``` Note that the reflections under step 2.3 are guaranteed to leave the new point within 100 units of the previous point, so the path requirement is preserved. However, the horizontal and vertical travel constraints force the generation of points to "sweep" randomly across the entire space, producing more total dispersion than the original pure "drunkard's walk" algorithm.
Force the desired condition by construction. Instead of placing all points solely by drawing random numbers, constrain the coordinates as follows: 1. Randomly place an initial point. 2. Repeat for the remaining number of points (e.g. 99): 2.1. Randomly select an x-coordinate within some range (e.g. 90) of the previous point. 2.2. Compute the legal range for the y-coordinate that will make it within 100 units of the previous point. 2.3. Randomly select a y-coordinate within that range. 3. If you want to completely obscure the origin, sort the points by their coordinate pair. This will not require much overhead vs. pure randomness, but will guarantee that each point is within 100 units of at least one other point (actually, except for the first and last, each point will be within 100 units of *two* other points). As a variation on the above, in step 2, randomly choose *any* already-generated point and use it as the reference instead of the previous point.
29,320,798
I want to make jQuery shoot an action triggered by a click or pressed key only WHILE `input#show1` is checked. The way I tried it below seems to be the most simple way to check if the input is checked but it doesn't work somehow. Any help what I did wrong in my code is appreciated! ``` <script> if ($('input#show1').is(':checked')) { alert("show1 is checked"); } </script> <input type="radio" id="show1" name="group"> <label for="show1">Show</label> <input type="radio" id="hide1" name="group" checked> <label for="hide1">Hide</label> ```
2015/03/28
[ "https://Stackoverflow.com/questions/29320798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4551676/" ]
Two options here, either you execute the conditional check on DOM load or you check on change. You **have to** wait on the document to be loaded, which you can do by using a `$(document).ready()` call. Calling the function on `click` as mplungjan suggested will work as well, though I don't like it. You only want something to happen when the value changes from unchecked to checked, and not when it's checked and it's clicked again. Therefore you can use `change`. ``` $(document).ready(function () { function checker() { if ($('input#show1').is(':checked')) { alert("show1 is checked"); } } checker(); $('input#show1').change(checker); }); ``` This code will check the value on page load, and will also watch for changes a user makes. In [this fiddle](http://jsfiddle.net/BramVanroy/r042d1hz/), click "show". [In this one](http://jsfiddle.net/BramVanroy/r042d1hz/2/), the alert will show on page load because I added the check attribute to Show. --- Following your edit. -------------------- ``` $(document).ready(function () { $(document).keyup(function(e) { if (e.keyCode == 27 && $('input#show1').is(':checked')) { alert('Esc key pressed.'); } }); }); ``` See it in action [here](http://jsfiddle.net/BramVanroy/r042d1hz/4/). --- Another edit. ------------- ``` $(document).ready(function () { $(document).keyup(function(e) { if (e.keyCode == 27) { checker(); } }); $("#control").click(function() { checker(); }); function checker() { if ($('input#show1').is(':checked')) { alert("It's checked."); } else { console.log("Bummer, mate."); } } }); ``` Seet it in action [here](http://jsfiddle.net/BramVanroy/r042d1hz/6/).
`#show1` is not checked at all in your `HTML` markup. I assume you meant to check for `#hide1`. Also, you'd need to wrap your code around ``` jQuery(function($) { // same as doing $(document).ready(function() { if ($('input#hide1').is(':checked')) { alert("hide1 is checked"); } }); ``` To wait for the DOM to be ready. If you don't, the javascript code will be executed **before** the `<input/>` element is even created.
277,941
I want to give credit to all open source libraries we use in our (commercial) application. I thought of showing a HTML page in our about dialog. Our build process uses ant and the third party libs are committed in svn. What do you think is the best way of generating the HTML-Page? * Hard code the HTML-Page? * Switch dependency-management to apache-ivy and write some ant task to generate the html * Use maven-ant-tasks and write some ant task to generate the HTML * Use maven only to handle the dependencies and the HTML once, download them and commit them. The rest is done by the unchanged ant-scripts * Switch to maven2 (Hey boss, I want to switch to maven, in 1 month the build maybe work again...) * ... What elements should the about-dialog show? * Library name * Version * License * Author * Homepage * Changes made with link to source archive * ... Is there some best-practise-advice? Some good examples (applications having a nice about-dialog showing the dependencies)?
2008/11/10
[ "https://Stackoverflow.com/questions/277941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969/" ]
There are two different things you need to consider. First, you may need to identify the licenses of the third-party code. This is often down with a THIRDPARTYLICENSE file. Sun Microsystems does this a lot. Look in the install directory for OpenOffice.org, for example. There are examples of .txt and .html versions of such files around. Secondly, you may want to identify your dependencies in the About box in a brief way (and also refer to the file of license information). I would make sure the versions appear in the About box. One thing people want to quickly check for is an indication of whether the copy of your code they have needs to be replaced or updated because one of your library dependencies has a recently-disclosed bug or security vulnerability. So I guess the other thing you want to include in the about box is a way for people to find your support site and any notices of importance to users of the particular version (whether or not you have a provision in your app for checking on-line for updates).
Generating the page with each build would be wasteful if the libraries are not going to change often. Library versions may change, but the actual libraries don't. Easier to just create a HTML page would be the easiest way out, but that's one more maintenance head ache. Generate it once and include it with the package. The script can always be run again in case some changes are being made to the libraries (updating versions, adding new libraries).
182,186
I recently enrolled in a Master's program in electrical engineering at a public research university in the midwestern United States. I am currently focusing on power distribution and transmission, as it seems like there are only a small number of well-defined channels between such things and militarism (compared to, say, controls engineering). Unexpectedly, I was approached about a PhD opportunity by a mechanical engineering professor, and will be discussing the matter with him further. However, I am not really sure how to make known the sorts of projects and actors I will not work with. It is only fair to him that I be upfront about these things, but for a variety of reasons I am not really sure how to articulate my boundaries (a pre-condition for even considering his offer). In my mind, it would be quite reasonable to tell someone "I would not like to be involved in any project directly benefiting Defense, Aerospace, Surveillance, Autonomous Vehicles; those kinds of things" (adding "that stuff makes me uncomfortable", if necessary; I have no desire to discuss the matter or proselytize). This is somewhat euphemistic in that I try to avoid explicit "-isms", but paints a pretty clear picture of behavior I will not support, when presented together. That being said: * It's a pretty plainly political declaration, even if I try to be somewhat euphemistic and non-confrontational about it. Such things have a chance of offending the other party, but I don't think there's a real way to mitigate this. * I am worried about even *mentioning* these things, particularly over email, with foreign-born professors--especially Middle Eastern or Chinese professors (see, for example, [this NYT article](https://archive.is/qbP3p) on the "hunt"(!) for Chinese spies from Nov 2021. And it is not exactly a secret that various sectors of the US state keep close tabs on Middle Eastern groups/individuals). This latter point is of particular importance. There are a significant number of Middle Eastern and Chinese professors in the department. There's also plainly a well-exercised apparatus for surveilling and harassing ambiguously-defined "national enemies". So this is an essential consideration, since there are certainly people who will find my position to be radical. Consequently, it would be quite irresponsible for me to say such things if there is even a nonzero chance they would cause anyone else to receive undue attention. --- My concern applies more broadly than this particular PhD offer; there are a small number of other situations in which this information about myself is relevant: looking for research to contribute to, or trying to learn about employment prospects. It would also be untrue to say that I am *only* interested in electrical power, because I would be happy to contribute to any number of productive projects. It's conceivable that the conditions in the US simply aren't right at the moment for such things to be mentioned in these settings, and that my best course of action may just be to keep my nose down and focus solely on the electrical power industry. But after being approached specifically for my math background as a potentially-ideal PhD candidate for this professor's needs, I am tempted to see whether my horizon can be at all broadened.
2022/02/09
[ "https://academia.stackexchange.com/questions/182186", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153230/" ]
If you don't want to do military-related research, just say "I don't want to do military-related research." The basic reason will be obvious to anyone, and there are probably plenty of academics who feel the same way. If you think that even saying that phrase to a foreign-born professor will cause them some problem, I think you are probably worrying too much. > > "I would not like to be involved in any project directly benefiting Defense, Aerospace, Surveillance, Autonomous Vehicles; those kinds of things" > > > This is too long and confusing. Aerospace and autonomous vehicles research can be completely non-military.
If you have the freedom to choose the mode of conversation, let it be verbal. This would reduce the chances of your statements being misrepresented/used against you, especially at a later stage. It would also be nice to seek permission to express your (non) preference of topic before you actually state it. Doing so is both safe and courteous; you've allowed the professor the opportunity to deny it. If it's permitted, I would suggest being direct about the militarism aspect rather than couching it within sub-fields (the ones you mentioned are non-exclusive, and there could be non-military work within them). There is a finite chance that your preference would be considered naive; if probed, you should have a reasonably sound argument. I would suggest thinking along the lines of (a) whether non-military work that could be misused to be exploitative is more acceptable than any military work, and, (b) if you do obtain ground breaking results and realise their potential military use, how willing would you be to give up on them?
256,362
I've got a domain name, let's call it: iam.us (which it is not). Now, I want to be able to provide users the chance to buy THEIRNAME.iam.us domain names. 1. Is it legal? 2. Is it possible? If so, where do I start? What software? Does my ISP host it for me? 3. Why isn't everybody doing this? Thanks so much!
2011/04/06
[ "https://serverfault.com/questions/256362", "https://serverfault.com", "https://serverfault.com/users/16042/" ]
1. Yes, it is legal. 2. You're basically talking about opening your own DNS registry. At the very least you'd need a website (of course), some method of accepting payments (credit card, paypal, etc.), and nameserver software (BIND, NSD, djbdns, etc.) You could sell referrals only, leaving the registrant to set up their own authoritative DNS server, but you may want to consider selling a hosted DNS account as well. This means allowing people to do all their DNS configuration on your website and hosting the DNS on your nameservers. 3. Third-level domains are not nearly as popular as second-level domains. This might be of interest to you: <http://www.generic-nic.net/HOWTO/HOWTO-en>
1. Depends on your location mainly, and on the subdomain. You will find out when someone wants to buy disney.iam.us or apple.iam.us .... 2. Yes. With a server, a website to offer the domain and a DNS server. Ask your ISP if it complies with his TOS. 3. Plenty of people do, but few sites who wants to leave a professional impression will use it.
160,620
I recently started learning C# and am taking the opportunity to try and accelerate my introduction by helping the RubberDuck team ([Website](http://rubberduckvba.com/) and [GitHub Repo](https://github.com/rubberduck-vba/Rubberduck)). The full class code that I'm working on [can be found here](https://github.com/rubberduck-vba/Rubberduck/blob/dd0bb517d7a984bb42a4d0284d29d55e48288c05/RetailCoder.VBE/UI/Command/AddTestModuleCommand.cs). Its purpose is to create a Module in VBA that will allow unit testing. 1. Since `FakesFieldDeclarationFormat` and `AssertFieldDeclarationFormat` are used only once would it be better to move them to just above where they are fed into `DeclarationFormatFor`? 2. Would it be better to migrate `FolderAnnotation` into `TestModuleEmptyTemplate` since when `formattedModuleTemplate` is created that is ultimately what is happening? 3. Does anyone have any suggestions for improving the names? 4. Anything else that help improve the code and that may assist me in learning is welcome. The main code in question is below. ```cs private const string TestModuleEmptyTemplate = "'@TestModule\r\n{0}\r\n{1}\r\n{2}\r\n\r\n"; private const string FolderAnnotation = "'@Folder(\"Tests\")\r\n"; private const string FakesFieldDeclarationFormat = "Private Fakes As {0}"; private const string AssertFieldDeclarationFormat = "Private Assert As {0}"; private readonly string _moduleInit = string.Concat( "'@ModuleInitialize\r\n", "Public Sub ModuleInitialize()\r\n", $" '{RubberduckUI.UnitTest_NewModule_RunOnce}.\r\n", " {0}\r\n", " {1}\r\n", "End Sub\r\n\r\n", "'@ModuleCleanup\r\n", "Public Sub ModuleCleanup()\r\n", $" '{RubberduckUI.UnitTest_NewModule_RunOnce}.\r\n", " Set Assert = Nothing\r\n", " Set Fakes = nothing\r\n", "End Sub\r\n\r\n" ); private readonly string _methodInit = string.Concat( "'@TestInitialize\r\n" , "Public Sub TestInitialize()\r\n" , " '", RubberduckUI.UnitTest_NewModule_RunBeforeTest, ".\r\n" , "End Sub\r\n\r\n" , "'@TestCleanup\r\n" , "Public Sub TestCleanup()\r\n" , " '", RubberduckUI.UnitTest_NewModule_RunAfterTest, ".\r\n" , "End Sub\r\n\r\n" ); private const string TestModuleBaseName = "TestModule"; private string GetTestModule(IUnitTestSettings settings) { var assertType = string.Format("Rubberduck.{0}AssertClass", settings.AssertMode == AssertMode.StrictAssert ? string.Empty : "Permissive"); var assertDeclaredAs = DeclarationFormatFor(AssertFieldDeclarationFormat, assertType, settings); var fakesType = "Rubberduck.IFake"; var fakesDeclaredAs = DeclarationFormatFor(FakesFieldDeclarationFormat, fakesType, settings); var formattedModuleTemplate = string.Format(TestModuleEmptyTemplate, FolderAnnotation, assertDeclaredAs, fakesDeclaredAs); if (settings.ModuleInit) { var assertBinding = InstantiationFormatFor(assertType, settings); var assertSetAs = $"Set Assert = {assertBinding}"; var fakesBinding = InstantiationFormatFor(fakesType, settings); var fakesSetAs = $"Set Fakes = {fakesBinding}"; formattedModuleTemplate += string.Format(_moduleInit, assertSetAs, fakesSetAs); } if (settings.MethodInit) { formattedModuleTemplate += _methodInit; } return formattedModuleTemplate; } private string InstantiationFormatFor(string type, IUnitTestSettings settings) { const string EarlyBoundInstantiationFormat = "New {0}"; const string LateBoundInstantiationFormat = "CreateObject(\"{0}\")"; return string.Format(settings.BindingMode == BindingMode.EarlyBinding ? EarlyBoundInstantiationFormat : LateBoundInstantiationFormat, type); } private string DeclarationFormatFor(string declarationFormat, string type, IUnitTestSettings settings) { return string.Format(declarationFormat, settings.BindingMode == BindingMode.EarlyBinding ? type : "Object"); } ``` The final output for VBA: Early Binding: ```vbs Option Explicit Option Private Module '@TestModule '@Folder("Tests") Private Assert As Rubberduck.AssertClass Private Fakes As Rubberduck.IFake '@ModuleInitialize Public Sub ModuleInitialize() 'this method runs once per module. Set Assert = New Rubberduck.AssertClass Set Fakes = New Rubberduck.IFake End Sub '@ModuleCleanup Public Sub ModuleCleanup() 'this method runs once per module. Set Assert = Nothing Set Fakes = Nothing End Sub '@TestInitialize Public Sub TestInitialize() 'this method runs before every test in the module. End Sub '@TestCleanup Public Sub TestCleanup() 'this method runs after every test in the module. End Sub ``` Late Binding: ```vbs Option Explicit Option Private Module '@TestModule '@Folder("Tests") Private Assert As Object Private Fakes As Object '@ModuleInitialize Public Sub ModuleInitialize() 'this method runs once per module. Set Assert = CreateObject("Rubberduck.AssertClass") Set Fakes = CreateObject("Rubberduck.IFake") End Sub '@ModuleCleanup Public Sub ModuleCleanup() 'this method runs once per module. Set Assert = Nothing Set Fakes = Nothing End Sub '@TestInitialize Public Sub TestInitialize() 'this method runs before every test in the module. End Sub '@TestCleanup Public Sub TestCleanup() 'this method runs after every test in the module. End Sub ```
2017/04/13
[ "https://codereview.stackexchange.com/questions/160620", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/131748/" ]
Only targeting `_moduleInit` and `_methodInit` IMO the use of `string.Concat` with many parameters together with `\r\n` is hurting the readability a lot. How about using a `StringBuilder` instead like so ``` private readonly string _moduleInit = new StringBuilder(256) .AppendLine("'@ModuleInitialize") .AppendLine("Public Sub ModuleInitialize()") .AppendLine($" '{RubberduckUI.UnitTest_NewModule_RunOnce}.") .AppendLine(" {0}") .AppendLine(" {1}") .AppendLine("End Sub") .AppendLine() .AppendLine("'@ModuleCleanup") .AppendLine("Public Sub ModuleCleanup()") .AppendLine($" '{RubberduckUI.UnitTest_NewModule_RunOnce}.") .AppendLine(" Set Assert = Nothing") .AppendLine(" Set Fakes = Nothing") .AppendLine("End Sub") .AppendLine() .ToString(); ``` which is easier to read. Now you will also notice that the `Nothing` in `Set Fakes = Nothing` is cased correctly. For `_methodInit` this should be applied as well and you should decide if you want to use string interpolation `$` or not. You used it for `_moduleInit` but you didn't for `_methodInit`. If you have choosen a style, you should stick to it.
Personally, I would use large string literals for your `_moduleInit` and `_methodInit` values, as they are more visually alike to their expected output: ``` private readonly string _moduleInit = $@"'@ModuleInitialize Public Sub ModuleInitialize() '{RubberduckUI.UnitTest_NewModule_RunOnce}. {{0}} {{1}} End Sub '@ModuleCleanup Public Sub ModuleCleanup() '{RubberduckUI.UnitTest_NewModule_RunOnce}. Set Assert = Nothing Set Fakes = nothing End Sub "; private readonly string _methodInit = $@"'@TestInitialize Public Sub TestInitialize() '{RubberduckUI.UnitTest_NewModule_RunBeforeTest}. End Sub '@TestCleanup Public Sub TestCleanup() '{RubberduckUI.UnitTest_NewModule_RunAfterTest}. End Sub "; ``` The `{{}}` tells the interpolated string to output braces rather than attempt to perform a replacement, so it keeps the format placeholders intact, so that's no worry for the entire string being interpolated.
3,521,621
For an ecommerce site I want to generate a random coupon code that looks better than a randomly generated value. It should be a readable coupon code, all in uppercase with no special characters, only letters (A-Z) and numbers (0-9). Since people might be reading this out / printing it elsewhere, we need to make this a simple-to-communicate value as well, perhaps 8-10 characters long. Something like perhaps, ``` AHS3DJ6BW B83JS1HSK ``` (I typed that, so it's not really that random)
2010/08/19
[ "https://Stackoverflow.com/questions/3521621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425188/" ]
``` $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $res = ""; for ($i = 0; $i < 10; $i++) { $res .= $chars[mt_rand(0, strlen($chars)-1)]; } ``` You can optimize this by preallocating the `$res` string and caching the result of `strlen($chars)-1`. This is left as an exercise to the reader, since probably you won't be generating thousands of coupons per second.
Try this: ``` substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 10) ```
31,681,915
I have the following simple php code that gives me a result that I want to display. ``` $linkz= mysql_connect($host,$username,$password) or die(mysql_error()); mysql_select_db($db, $linkz); $sq_name= $_POST['unameTF']; $sq_pass= $_POST['passTF']; $sq_search= $_POST['searchTF']; if($sq_search=""||$sq_search=null) { echo "type something"; }else { $sql2= "SELECT * FROM sql_insert WHERE sq_name='$sq_search' "; $res= mysql_query($sql2, $linkz) or die(mysql_error()); } while($row=mysql_fetch_assoc($res)) } echo "$row[sq_name]"."<br/>"; } ``` This gives me a null result always(ie it doesn't give an error or dispay anything). It works fine when the if-else statement is removed meaning it just ``` $sql2= "SELECT * FROM sql_insert WHERE sq_name='$sq_search' "; $res= mysql_query($sql2, $linkz) or die(mysql_error()); ``` and no checking to see if its null. and also if I replace ``` $sql2= "SELECT * FROM sql_insert WHERE sq_name='$sq_search' "; ``` with ``` $sql2= "SELECT * FROM sql_insert WHERE sq_name='".$_POST['searchTF']."' "; ``` (even without removing the if-else statement) Can someone explain whats going on?
2015/07/28
[ "https://Stackoverflow.com/questions/31681915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4135250/" ]
The reason why it works without the `if()` statement is because you used assignment operators, rather than comparison operators causing the flow of your if statement to work like this: ``` if we can set $sq_search = "" ... we can! check that it's not a null-terminated value... that's good too! if we can set $sq_search = null ... we can! check that it's not a null-terminated value... it is, this answer is false do that else statement, compile the string, output will be: "SELECT * FROM sql_insert WHERE sq_name=''" ``` replace your if statement with this: ``` if($sq_search===""||is_null($sq_search)){ echo "type something"; } else { $sql2= "SELECT * FROM sql_insert WHERE sq_name='$sq_search' "; $res= mysql_query($sql2, $linkz) or die(mysql_error()); } ```
``` if ((!isset($_POST['searchTF'])) || (empty($_POST['searchTF'])) { echo "type something"; } else ```
36,584,501
I am using PassportJS to authenticate my node.js application. I'm using the WSFED/ADFS strategy. However, my `passport.serializeUser()` and `passport.deserializeUser()` functions are not working. They are not even called. The typical solution I have found is to add `app.use(passport.initialize())` and `app.use(passport.session())` AFTER `app.use(session())`, which I did so I'm not sure why `serializeUser()` and `deserializeUser()` are not being called. Here's my code: ``` var express = require('express'), app = express(), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), session = require('express-session'), passport = require('passport'), wsfedsaml2 = require('passport-wsfed-saml2').Strategy; //Middlewares passport.use('wsfed-saml2', new wsfedsaml2({ realm: 'https://localhost:3001', identityProviderUrl: 'https://some_company.org/adfs/ls/', thumbprint: '9.....4' }, function(profile, done) { console.log(profile); return done(null, new User(profile)); })); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } })); app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser(function(user, done) { console.log('In Serializer'); //does not print done(null, user); }); passport.deserializeUser(function(user, done) { console.log('In DeSerializer'); //does not print done(null, user); }); ``` Can someone help? Thanks in advance!
2016/04/12
[ "https://Stackoverflow.com/questions/36584501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1547174/" ]
Solved the same problem by removing `cookie: { secure: true }` HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set ``` app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, })); ```
Edited: I think you configured the passport strategy incorrectly. Looking at the docs, its looking like it should be: ``` passport.use(new wsfedsaml2({ realm: 'https://localhost:3001', identityProviderUrl: 'https://some_company.org/adfs/ls/', thumbprint: '9.....4' }, function(profile, done) { console.log(profile); return done(null, new User(profile)); })); ```
49,836,822
What I'm trying to achieve: when my mouse **is moving** then do this, but when it **stops moving** for like half a second then do that, but when it **starts to move again** then do that. This is my temporary jQuery: ``` $(document).ready(function() { $('.test').mouseenter(function(){ $(this).mousemove(function(){ $(this).css({ 'background-color' : '#666', 'cursor' : 'none' }); }); }); $('.test').mouseout(function(){ $(this).css({ 'background-color' : '#777', 'cursor' : 'default' }); }); }); ``` And I have absolutely no idea how to do that, basically my code does this: when you enter an element with a mouse and your mouse is moving inside that element then apply this CSS and when your mouse leaves the element then apply this CSS, but when mouse is inside that element and it stops moving for some period of time then do this <- I can't figure the last bit out.
2018/04/14
[ "https://Stackoverflow.com/questions/49836822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9421094/" ]
So I was just googling. This is the answer: ``` $(document).ready(function() { var countdown; $('.test').hover(function() { setTimeout(function(){ $('.test').css({ 'background-color' : '#666', 'cursor' : 'none' }); cursor(); }, 2000); }, function(e){ $('.test').css({ 'background-color' : '#777', 'cursor' : 'default' }); }); $('.test').mousemove(function() { $('.test').css({ 'background-color' : '#777', 'cursor' : 'default' }); cursor(); }); function cursor() { countdown = setTimeout(function() { $('.test').css({ 'background-color' : '#666', 'cursor' : 'none' }); }, 2000); } }); }); ```
This may deviate from your current code, but I think CSS is more appropriate here than JavaScript. ``` .test { background-color:#666; } .test:hover { background-color:#777; cursor:none; } ``` These lines of CSS should perform the exact same thing without the complication. Note that in your example, for every pixel the mouse moves, the css is set once more. And since you are not removing the event handler on mouse out, the event is actually ran multiple times.
60,034,420
I need to GREP second column (path name) from the text file. I have a text file which has a md5checksum filepath size . Such as: ``` ce75d423203a62ed05fe53fe11f0ddcf kart/pan/mango.sh 451b 8e6777b67f1812a9d36c7095331b23e2 kart/hey/local 301376b e0ddd11b23378510cad9b45e3af89d79 yo/cat/so 293188b 4e0bdbe9bbda41d76018219f3718cf6f asuo/hakl 25416b ``` the above is the text file, I used `grep -Eo '[/]' file.txt` but it prints only / , but i want the output like this: ``` kart/pan/mango.sh kart/hey/local yo/cat/so asuo/hakl ``` Lastly I have to use GREP.
2020/02/03
[ "https://Stackoverflow.com/questions/60034420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12724344/" ]
If you can live with spaces before and after, you can use: ``` grep -o "\s[[:alnum:]/]*\s" ``` If you need the spaces removed, you will need some zero-width look-ahead/look-behind which is only available with -P (perl regexes), if you have that you can use: ``` grep -Po "(?<=\s)[[:alnum:]/]+(?=\s)" ``` * `(?<=\s)` - look-behind to see if there is a space preceding the string, but not capture it * `(?=\s)` - look-ahead to see if there is a space after the match, but not capture it * `[:alnum:]` - match alpha numeric chars * `[[:alnum:]/]` - match alphanumeric chars and `/` * `+` - match one or more However, grep is not the right tool for this, cut/sed/awk are way better
When you are allowed to combine `grep` with other tools and your input file only has slashes in the second field, you can use ``` tr " " "\n" < file.txt | grep '/' ```
10,190,456
I've got an existing web application, that is installed on several machines. script clients and .net clients consume ".asmx" services through one machine, that routes all calls to other machines. Client ----> |Website \ Virtual directory(HttpHandler)| ----> |Other server \ real .asmx| I added a new .svc service that does the same functionality, and added a handler for it (directory's config): ``` <system.webServer> <handlers> <add name="MY_ASMX" verb="*" path="*.asmx" type="MY.AO.HttpProxy, Astea.AO.HttpProxy" resourceType="Unspecified" preCondition="integratedMode" /> <add name="MY_ASPX" verb="*" path="*.aspx" type="MY.AO.HttpProxy, Astea.AO.HttpProxy" resourceType="Unspecified" preCondition="integratedMode" /> <add name="MY_WSDL" verb="*" path="*.wsdl" type="MY.AO.HttpProxy, Astea.AO.HttpProxy" resourceType="Unspecified" preCondition="integratedMode" /> <add name="MY_SVC" verb="*" path="*.svc" type="MY.AO.HttpProxy, Astea.AO.HttpProxy" resourceType="Unspecified" preCondition="integratedMode" /> ``` while asmx request are routed fine, my new .svc on the end server does not get called, and even the Httphandler is skipped. if i call the .svc directly on the other machine it works. the error i get is: ``` WebHost failed to process a request. Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/26458746 Exception: System.Web.HttpException (0x80004005): The service '/Mysite/MyDirectory/settings.svc' does not exist. ---> System.ServiceModel.EndpointNotFoundException: The service '/Mysite/MyDirectory/settings.svc' does not exist. ``` I already tried the folowing 1. add "buildProviders" to compilation section that removes .svc 2. Click on MimeTypes and enter “.svc” and “application/octet-stream” and save 3. add a handler : nothing helps, http handler is not being called p.s. Im working with AppPool .net 4.0 Integrated
2012/04/17
[ "https://Stackoverflow.com/questions/10190456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355289/" ]
i solved it with workaround, incase somebody comes looking - chart and shapes are still not moving, but now i am assigning `TopLeftCell` property of chart and shape at runtime and forcing them to move, although now i have overhead of keeping its location.
I had the same problem and managed to fix it by unlocking the chart(s).
73,225,745
How would I work out the average of a range where it has to meet two requirements. In the example below, I would like to calculate the average 'Score' of all of the 'Type 1' results that are within August 2022. [![enter image description here](https://i.stack.imgur.com/6mkqK.png)](https://i.stack.imgur.com/6mkqK.png)
2022/08/03
[ "https://Stackoverflow.com/questions/73225745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19340264/" ]
try: ``` =AVERAGE(FILTER(C:C; YEAR(A:A)=2022; MONTH(A:A)=8; B:B="Type 1")) ``` or even `AVERAGEIFS` can be used
* Fix th date format first there is no August in your dates [![enter image description here](https://i.stack.imgur.com/TiNXn.png)](https://i.stack.imgur.com/TiNXn.png) > > To look like this > > > [![enter image description here](https://i.stack.imgur.com/dcAUM.png)](https://i.stack.imgur.com/dcAUM.png) Try this, or see [**Example**](https://docs.google.com/spreadsheets/d/1KiVwULl72RGV8uiyCyW0WLRN_vZv96QjeIW5K4LyoI0/edit?usp=sharing) ``` =IFERROR(AVERAGE(FILTER(E2:E, YEAR(B2:B)=2022, MONTH(B2:B)=8, C2:C="Type 1",D2:D=F5 )),0) ``` [![enter image description here](https://i.stack.imgur.com/AjEIj.png)](https://i.stack.imgur.com/AjEIj.png) > > To get Unique Names in cell `I2` > > > ``` =UNIQUE(D2:D) ```
9,363,146
This is how my code looks like: ``` int main() { int a[] = {1,23,5,56,7,5}; int *p2 = a; size = sizeof(a)/sizeof(a[0]); int *p1 = new int[size]; cout << "sizeof " << size << endl; int i = 0; while(p2 != a+size ) { *p1++ = *p2++; } cout << p1[1] << ' ' << p1[3]; return 0; } ``` `cout << p1[1] << ' ' << p1[3];` outputting me values which are not the same as in a[1] and a[3]. Can anyone explain me why this is happening ?
2012/02/20
[ "https://Stackoverflow.com/questions/9363146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/817810/" ]
You need to reset p1 to the begining of the initial array.
You should reset p1 before accessing elements: ``` int main() { int a[] = {1,23,5,56,7,5}; int *p2 = a; int size = sizeof(a)/sizeof(a[0]); int *p1 = new int[size]; cout << "sizeof " << size << endl; int i = 0; while(p2 != a+size ) { *p1++ = *p2++; } p1 -= size; cout << p1[1] << ' ' << p1[3]; return 0; } ```
1,018,176
Is $GL(n,\mathbb R)$ dense in $M(n,\mathbb R)$? I have proved it to be open,not closed,not connected but not sure about this property .How to do this?
2014/11/12
[ "https://math.stackexchange.com/questions/1018176", "https://math.stackexchange.com", "https://math.stackexchange.com/users/294365/" ]
Yes, $GL(n,\mathbb R)$ is dense in $M(n,\mathbb R)$. Using the determinant function $\det:M(n,\mathbb R)\rightarrow \mathbb R$, check that for small values of $\varepsilon$, the matrix $A+\varepsilon I\_n$ is invertible.
The way I like writing this is as follows: Consider $A\in M\_{n}(\mathbb R)$ and let $\varepsilon>0$. Let $\lambda \_1, \ldots, \lambda\_n$ be the eigenvalues of $A$. Take $\delta$ such that $0<\delta<\frac{\varepsilon}{n^{1/2}}$ and $\delta\neq \lambda\_j$ for every $j\in \{1, \ldots, n\}$. Define $$A\_\delta:=A-\delta I.$$ Then $A\_\delta$ is invertible. In fact, on the contrary, $$\det(A\_\delta)=\det(A-\delta I)=0$$ and therefore $\delta$ would be an eigenvalue of $A$, so that $\delta =\lambda\_j$ for some $j\in \{1, \ldots, n\}$. This contradicts the choice of $\delta$. Finally, $$d\_2(A, A\_\delta)=\|A-A\_\delta\|\_2=\|A-(A-\delta I)\|\_2=|\delta|\|I\|\_2=\delta {n^{1/2}}<\frac{\varepsilon}{n^{1/2}} n^{1/2}=\varepsilon.$$ I assumed here that your metric is induced by norm: $$\|A\|\_2=\left(\sum\_{i=1}^n \sum\_{j=1}^n a\_{ij}^2\right)^{1/2}.$$
27,294
Is there a way to set a keyboard shortcut to toggle layer visibility in Photoshop (CS3)?
2009/08/21
[ "https://superuser.com/questions/27294", "https://superuser.com", "https://superuser.com/users/7479/" ]
Mac = `command` + `,` toggles selected layer visibility Mac = `command` + `option` + `,` turns all layers' visibility on regardless of layer selection. PC = `ctl` + `,` PC = `ctl` + `alt` + `,`
I don't think Photoshop has a default hotkey for showing/hiding a certain layer. You can, however, create your own action to do this, and just bind it to a key.
28,033,504
I require a form that is hidden until the user clicks the button and only then the form will be visible, when the submit button is pressed the form would go back to being invisible. can anyone give me an idea on how implement this, i am assuming this would need to be done using php and ajax calls.
2015/01/19
[ "https://Stackoverflow.com/questions/28033504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552356/" ]
Try this <http://jsfiddle.net/ManikandanK/c477rone/1/> There are two things you need to correct. ``` ensureSingleActive: function(current) { if(current.get('isActive') ) { var previous= _.find(this.models, function(model) { return model != current && model.get('isActive') }); if (previous) { previous.set('isActive', false); } } } ``` When you are inside this function, already current model value is already set. so you dont need to set the value again. You missed to pass the value to set function. ``` this.model.set('isActive', true); ```
To expand on other answers, you could sidestep events and just call a method on your collection directly. In your view: ``` activate: function() { this.model.collection.setActive(this.model) } ``` And then in your collection: ``` setActive: function(model) { this.each( function(m) { m.set('selected', m === model) } } ``` Readable, slightly less performant, but shouldn't matter unless you're working with massive collections.
5,506,587
I am pretty much a new newbie when it comes to PHP, and have a problem that I need to solve, for a website that has to go live tomorrow. Basically I have been using a javascript upload script called 'uploadify' which had an option for the upload folder which was added to the script in the form: ``` 'folder' : '/songs/<?php echo $_SESSION["name"];?>', ``` I added the php echo to return the username from a PHP login, so it gets added to the path to the upload folder (each user has their own subfolder for uploading to). With the new version of the uploadify script, the folder option has been moved to a separate PHP file where it is now in the form: ``` $targetFolder = '/songs/'; ``` I need to find a way of adding the username variable to this line. I have tried using echo in various ways, and googled about, but it has stumped me, simple as it may be. If anyone could let me know how I construct this line I'd be very grateful. Time is of the essence, as they say... Thanks, Nick I thought I'd include all of the php involved in case this illuminates why the session var isn't available to uploadify.php. First there is this at the top of the index.php page: ``` <? require("log.php"); ?> ``` Which triggers log.php: ``` <? session_name("MyLogin"); session_start(); if($_GET['action'] == "login") { $conn = mysql_connect("","",""); // your MySQL connection data $db = mysql_select_db(""); //put your database name in here $name = $_POST['user']; $q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'"); if(mysql_num_rows($q_user) == 1) { $query = mysql_query("SELECT * FROM USERS WHERE login='$name'"); $data = mysql_fetch_array($query); if($_POST['pwd'] == $data['password']) { $_SESSION["name"] = $name; header("Location: http://monthlymixup.com/index.php"); // success page. put the URL you want exit; } else { header("Location: login.php?login=failed&cause=".urlencode('Wrong Password')); exit; } } else { header("Location: login.php?login=failed&cause=".urlencode('Invalid User')); exit; } } // if the session is not registered if(session_is_registered("name") == false) { header("Location: login.php"); } ?> ``` (I have removed MySql info from this) This then calls the login.php, which has this php at the top (followed by the html for the form): ``` <? session_name("MyLogin"); session_start(); session_destroy(); if($_GET['login'] == "failed") { print $_GET['cause']; } ?> ``` which includes session\_destroy();. Which I thought may be causing the problem, but I deleted this line, and the session var isn't passed to uploadify.php (and why would it be available to index.php it it is destroyed here?). uploadify.php currently looks like this: ``` <?php session_start() print_r($_SESSION); $targetFolder = '/songs/' . $_SESSION['name']; // Relative to the root if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder; $targetFile = rtrim($targetPath,'/') .'/'. $_FILES['Filedata']['name']; // Validate the file type $fileTypes = array('m4a','mp3','flac','ogg'); // File extensions $fileParts = pathinfo($_FILES['Filedata']['name']); if (in_array($fileParts['extension'],$fileTypes)) { move_uploaded_file($tempFile,$targetFile); echo '1'; } else { echo 'Invalid file type.'; } } ?> ``` The uploadify.php is referred to in jquery.uploadify.js. I think these are all the lines that are relevant: ``` uploader : 'uploadify.php', upload_url : settings.uploader, case 'uploader': swfuploadify.setUploadURL(settingValue); ```
2011/03/31
[ "https://Stackoverflow.com/questions/5506587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672147/" ]
Assuming you still have the session var to work with... ``` $targetFolder = '/songs/' . $_SESSION['name']; ```
You're looking for a [concatenation operator ('.')](http://php.net/manual/en/language.operators.string.php): ``` $targetFolder = '/songs/'.$_SESSION["name"].'/'; ```
29,158,346
I have the following matrix: ``` [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 2 1 3 5 1 [2,] 3 5 4 6 7 2 ``` I need to filter this matrix so that I remove the columns with duplicate elements in row 1, leaving behind only columns with the max value in row 2. So in this example, columns 1 & 6 of the input matrix need to be removed: ``` [,1] [,2] [,3] [,4] [1,] 2 1 3 5 [2,] 5 4 6 7 ``` Is there an easy way to do this in R? Thanks
2015/03/20
[ "https://Stackoverflow.com/questions/29158346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3294195/" ]
You could compute the maximum second-row values for each first-row element and then only keep columns where the second row is the max value for the element in the first: ``` (maxes <- tapply(mat[2,], mat[1,], max)) # 1 2 3 5 # 4 5 6 7 (mat2 <- mat[,maxes[as.character(mat[1,])] == mat[2,]]) # [,1] [,2] [,3] [,4] # [1,] 2 1 3 5 # [2,] 5 4 6 7 ``` If you expect to have ties for the maximum values in the second row and want to remove the duplicate columns, you can use `mat2[!duplicated(mat2[,1]),]` after these two commands.
You could use `ave` ``` res <- mat[,!!ave(mat[2,], mat[1,], FUN=function(x) x==max(x))] res # [,1] [,2] [,3] [,4] #[1,] 2 1 3 5 #[2,] 5 4 6 7 ``` **NOTE:** If there are ties in the dataset, you can remove those columns by ``` res[,!duplicated(split(res, col(res)))] ```
16,666,987
Is there a way to tell attribute to work only when used with static methods? `AttributeUsage` class does not seem to allow such specyfic usage. ``` [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] ```
2013/05/21
[ "https://Stackoverflow.com/questions/16666987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796078/" ]
No, there is no way to restrict this. However - you could use reflection at run-time to enforce this.
There is no such feature available in C# that allows you to restrict attribute usage based on a member's accessibility.
124,824
**How to invert colors of a picture on Mac?** I'm using macOS 10.13.
2019/05/22
[ "https://graphicdesign.stackexchange.com/questions/124824", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/13481/" ]
Absent photo manipulation software (such as Photoshop, GIMP, Affinity Photo, PixelMator, Luminar) on a Mac you can use the inbuilt OS application called Preview for a lot of basic image manipulation stuff, and even the Photos app has a ton of tone-mapping and histogram editing you can do - but I don't recall there being a simple inversion filter or tool there. However, I know that in the Quartz filters built into the OS core graphics there definitely is such a tool, and I think you can still easily access those tools with the Colour Profiler Utility. You might also look into Automator, which definitely allows access to that sort of thing absent specific software. But to be clear - absent the kinds of tools we here at **GD.SE** use routinely and are expert in, this question becomes less appropriate for us, as we're graphic designers here - you might consider moving this question to [<https://apple.stackexchange.com/questions]> if you're insisting on doing this with ***only*** the tools natively available in the Mac OS.
* Open the image in **Mac Preview** [![enter image description here](https://i.stack.imgur.com/tcqUC.png)](https://i.stack.imgur.com/tcqUC.png) * Go to menu Tools → Color Adjustment * Change the histogram extreme sliders position: move the shadow slider to the right and the light slider to the left [![enter image description here](https://i.stack.imgur.com/C6P7o.gif)](https://i.stack.imgur.com/C6P7o.gif) * Menu File → Save
98,808
I have a half-bath on the main floor of our house that is small and has only 3 electrical items in it: 1. Light above the sink (and corresponding light switch) 2. Fart fan (and corresponding light switch) 3. Two non-GFCI receptacles (one box, two plug-ins) next to the sink I understand that, by itself, this is against code and that those receptacles must be GFCI-protected. However, my house is new enough (~1995?) that I'm sure this has to be up to code but I don't know what GFCI switch actually controls this. My questions: 1. I understand a [device like this](http://rads.stackoverflow.com/amzn/click/B0014FNWJG) will prove that it is or is not protected. But how? 2. If it is protected, is there an easy way to find the device that protects it? (our circuit breaker box's labels are worse than useless b/c of how wrong the labels are) 3. If I find it's not protected, then I'm definitely going to replace it to protect it. Is it correct that I should replace it with a 15A box unless both my wiring and circuit breaker are proper for 20A? (Current receptacles are 15A judging by not having the horizontal "right-angle" hole.)
2016/09/06
[ "https://diy.stackexchange.com/questions/98808", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/11981/" ]
Step One, which I do for every home I occupy, is to do a thorough map of the circuit breakers by simple trial-and-error. Check every outlet, light, and wired appliance in the home. Print a nice list of what each breaker protects and tape it over the cryptic scribbles left by sparky. Here's [my Google sheet](https://docs.google.com/spreadsheets/d/1E2TcSYaczL3RLn4ZKfkM4AcuctLS3bvj6UjRIUYAeqU/edit?usp=sharing) for those who'd like it. I left my data in it as an example. Simply make a copy and replace the data with yours. I fold it down the middle, book-style, and tape it to the panel door at the fold so it fits nicely inside. 1. The device you link doesn't locate GFCI outlets, just the specific breaker you're on. I honestly don't know why a homeowner with just one residence to inspect would need it. 2. There are likely only a few GFCI outlets in your home. They're commonly located in bathrooms, kitchens, and garages, among other potentially wet areas. Try them one at a time and you'll get there. 3. If your outlets are not protected, but are on the same circuit, you should be able to simply replace the upstream outlet with a GFCI outlet and connect the downstream run to the LOAD side, thereby protecting the other outlet (and anything else downstream). A 20A outlet is at most a few dollars more than a 15A outlet, so it's probably worth going that route. It may be legal to use a 15A outlet, however. Our resident code geeks can tell us for sure.
While I understand things should be up to code, I wouldn't assume anything. A previous owner could have done anything they wanted. 1. The orange button causes a "ground fault" which should trip the GFCI if one exists. I'm not sure what happens if there is no GFCI installed. Also worth noting is you can get a [simple GFCI tester for around $10](http://rads.stackoverflow.com/amzn/click/B01AKX8L0M) 2. I don't know of an easy way... 3. Yes, you can use a 15 amp outlet. In fact you can use a 15 amp outlet on a 20 amp circuit as long as there are other outlets on that circuit. The logic being unless you have heavy equipment, you probably aren't plugging a 20 amp appliance into one outlet. [See this article for code details.](https://diy.stackexchange.com/questions/12115/is-using-15-amp-components-on-a-20-amp-breaker-against-code) Regarding #2 - if the wall that your bathroom outlets are on have other outlets on the other side, its possible that is where the GFCI is. For example, my parent's condo has a single non GFCI in the bathroom, but on the opposite side of that wall is their kitchen, which has the GFCI. Also, they make GFCI circuit breakers, so you may want to check your circuit box to see what you have. I'm not sure what the NEC requirement is for GFCI circuit breakers vs outlets in bathrooms.
313,402
I want to fetch the date when a data extension record was modified . I want to exclude all the records modified in last 15 days or DE itself if any of its record has been modified in last 15 days. I know this can be achieved using WS proxy SSJS but i am unable to find anything prudctive in SF documentation . I have also gone through Data extension Object properties . Can anyone help me with that how to do it?
2020/07/21
[ "https://salesforce.stackexchange.com/questions/313402", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/64445/" ]
Since Rahul's answer didn't address the border on mouse hover (and I was working on this anyway), I'm going to give you a second answer. Key points: * Per Rahul, you want to use the custom select event to set a `selected` property to `true` on the selected child component * Similarly, you can use [mouseover](https://www.w3schools.com/jsref/event_onmouseover.asp) and [mouseout](https://www.w3schools.com/jsref/event_onmouseout.asp) events to set a public property on your child components that indicates if the mouse is hovering over that component or not. * When a component is selected or moused over, you will want to iterate through your child components to make sure that A) the selected / hovered-over component has its relevant property set to `true` and B) all others have that property set to `false`. * You can use `slds-theme_inverse` or `slds-theme_alt-inverse` to easily give your div a dark background and white text (as long as you like the colors Salesforce chose) * You will probably want to use custom CSS to set the border. Something like `border: 2px solid #1589ee;`, probably (`#1589ee` is defined as Salesforce's [brand border color](https://www.lightningdesignsystem.com/design-tokens/#category-border-color) in Lightning Design System) * Borders have width to them. To avoid your components growing and shrinking as you add and remove the border, you'll want to make sure that un-moused-over components also have a border -- but a transparent one. Like this: `border: 2px solid transparent;` Here's a [Playground Link](https://developer.salesforce.com/docs/component-library/tools/playground/3ol-vTYDM/1/edit) with a working prototype. And here's another updated version of your code: Parent HTML ```html <template> <div class="container slds-p-around_large slds-scrollable_y slds-theme_shade"> <div class="slds-text-title_caps slds-text-title_bold slds-p-bottom_medium"> My Cases </div> <div> <template if:true={cases.data}> <lightning-layout class="slds-grid slds-grid_vertical" horizontal-align="left" > <template for:each={cases.data} for:item="currentcase"> <c-ma-case-list-item data-id={currentcase.Id} key={currentcase.Id} macase={currentcase} onselect={handleSelect} onmouseover={handleMouseover} onmouseout={handleMouseout} ></c-ma-case-list-item> </template> </lightning-layout> </template> </div> </div> </template> ``` Parent JS: ```js import { LightningElement, track, wire } from 'lwc'; import getCaseList from '@salesforce/apex/MA_CasesStore.getCaseList'; export default class MaMyCasesListView extends LightningElement { selectedCase; @wire(getCaseList) cases; handleSelect(event) { let caseId = event.detail; this.selectedCase = this.cases.data.find(c => c.Id === caseId); this.toggleListItems('selected', caseId); } handleMouseover(event) { this.toggleListItems('mouseIsOver', event.target.dataset.id); } handleMouseout(event) { event.target.mouseIsOver = false; } toggleListItems(property, caseId) { this.template.querySelectorAll('c-ma-case-list-item').forEach(item => { if (item.macase.Id === caseId) { item[property] = true; } else { item[property] = false; } }); } } ``` Child HTML ``` <template> <div class={divClass} onclick={handleClick} > <lightning-layout horizontal-align="left" class="slds-grid slds-grid_vertical slds-text-align--left" > <lightning-layout-item class="slds-text-align--left"> <b>{macase.Subject}</b> </lightning-layout-item> <lightning-layout-item class="slds-text-align--left slds-m-top_x-small"> <lightning-layout> <lightning-layout-item size="4"> {macase.Status} </lightning-layout-item> <lightning-layout-item> {macase.CaseNumber} </lightning-layout-item> </lightning-layout> </lightning-layout-item> </lightning-layout> </div> </template> ``` Child JS ```js import { LightningElement, api } from 'lwc'; export default class MaCaseListItem extends LightningElement { @api macase; @api selected; @api mouseIsOver; handleClick(event) { this.dispatchEvent(new CustomEvent('select', { detail: this.macase.Id })); } get divClass() { let cls = 'slds-p-around_small' if (this.selected) { cls += ' slds-theme_inverse'; } if (this.mouseIsOver) { cls += ' c-mouseover-border' } return cls; } } ``` Child CSS ```css div { border: 2px solid transparent; } .c-mouseover-border { border: 2px solid #1589ee; } ```
We use the event to send data from child to parent. Public attribute to send data from parent to child. Looks like you are trying to fire an event from parent to child which does not work. Instead, 1. You need to create a property on the case record to hold its selected state. 2. Then you need a public property on the child component which will be set from the parent component. 3. Now, when the div is clicked you need to fire an event from the child component to the parent. Which is you were doing right in your original code. 4. In the `select` event handler, you need to iterate all cases and set the selected attribute of the particular selected case. And that's it. Here is the code. Child JS -------- Define a public property to hold the selected attribute. ``` @api selected = false; handleClick(event) { const selectEvent = new CustomEvent('select', { detail: this.macase.Id }); // Fire the custom event this.dispatchEvent(selectEvent); } // Set the background color class if this attribute is true. get selectedClass(){ return this.selected ? 'slds-theme_alt-inverse' : ''; // you can use your custom class here. } ``` Child HTML ---------- Note how I have set the dynamic class to the div on line to. ``` <template> <div onclick={handleClick} class={selectedClass}> <lightning-layout class="slds-grid slds-grid_vertical slds-text-align--left"> <lightning-layout-item class="slds-text-align--left"> <b>{macase.Subject}</b> </lightning-layout-item> <lightning-layout-item class="slds-text-align--left slds-m-top_small"> <lightning-layout> <lightning-layout-item size="4">{macase.Status}</lightning-layout-item> <lightning-layout-item>{macase.CaseNumber}</lightning-layout-item> </lightning-layout> </lightning-layout-item> </lightning-layout> </div> </template> ``` --- Parent JS --------- Now mark the selected cases when event is fired from the child. ``` handleSelect(event) { const caseId = event.detail; this.cases.forEach(mycase => { if (mycase.Id === caseId) { mycase.selected = true; } else { mycase.selected = false; } }); } ``` [Live Playground](https://developer.salesforce.com/docs/component-library/tools/playground/aiElk5CPZ/4/edit) > > Note: As we are directly making changes to the wired result, you will > need to deep clone it using `this.cases = JSON.parse(JSON.stringify(data));`. Also, you will need to use wired function instead of property. > > >
869,945
I have an existing application which does all of its logging against log4j. We use a number of other libraries that either also use log4j, or log against Commons Logging, which ends up using log4j under the covers in our environment. One of our dependencies even logs against slf4j, which also works fine since it eventually delegates to log4j as well. Now, I'd like to add ehcache to this application for some caching needs. Previous versions of ehcache used commons-logging, which would have worked perfectly in this scenario, but as of [version 1.6-beta1](http://ehcache.sourceforge.net/changes-report.html#1.6.0-beta1) they have removed the dependency on commons-logging and replaced it with java.util.logging instead. Not really being familiar with the built-in JDK logging available with java.util.logging, is there an easy way to have any log messages sent to JUL logged against log4j, so I can use my existing configuration and set up for any logging coming from ehcache? Looking at the javadocs for JUL, it looks like I could set up a bunch of environment variables to change which `LogManager` implementation is used, and perhaps use that to wrap log4j `Logger`s in the JUL `Logger` class. Is this the correct approach? Kind of ironic that a library's use of built-in JDK logging would cause such a headache when (most of) the rest of the world is using 3rd party libraries instead.
2009/05/15
[ "https://Stackoverflow.com/questions/869945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
OCTOBER 2014 Since version 2.1 of log4j exists the component log4j-jul, which allows exactly this. Still, in case you are using log4j 1, it has to be possible to upgrade to log4j2 in order to use this approach. [JDK Logging Adapter](https://logging.apache.org/log4j/2.x/log4j-jul/index.html) [Class LogManager](https://logging.apache.org/log4j/2.x/log4j-jul/apidocs/org/apache/logging/log4j/jul/LogManager.html) [Migrate from log4j 1.x to log4j 2](https://logging.apache.org/log4j/2.x/manual/migration.html)
The slf4j site I believe has a bridge for passing java.util.logging events via slf4j (and hence to log4j). Yes, the SLF4J download contains jul-to-slf4j which I believe does just that. It contains a JUL handler to pass records to SLF4J.
140,354
I have a vector of desired values that I want to fit based in some generated predictors. The tricky part is that I wish to have the explicit formula. For example, giving the below input I would like to get the following formula Input: ``` Y=[1,2,3,6,7] X=[1,2,3,4,5;0,0,0,1,1] ``` Output: ``` Transf={'multiply',1,'transform',linear;... 'multiply',2,'transform',linear} Y=Transf(X) %which would be equal to: Y=1*X(1,:)+2*X(2,:) ``` This is a not so complicated linear regression. but generalizing it could give, log transforms, sin, cosin, roots, exponents. What software could I start with? Or how might I implement this?
2015/03/04
[ "https://stats.stackexchange.com/questions/140354", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/60211/" ]
In addition to nice answer by @DankMasterDan (+1), I would like to share further information on the topic. It seems that an approach that you're looking for is [symbolic regression](http://en.wikipedia.org/wiki/Symbolic_regression). It seems to be closely associated with and usually is implemented via *evolutionary algorithms*, such as the most popular *genetic programming* (GP). However, other approaches are also proposed, especially in relation to *analytical models* of physical systems. For example, see a paper by Shmidt and Lipson (2009), published in Science. By the way, [this small open source Java-based project](http://github.com/pkoperek/hubert) presents an implementation of the above-mentioned approach. In terms of **software**, available for *symbolic regression*, before I concentrate on my favorite open source solutions, I'd like to mention that *Eureqa* is definitely an interesting product, which [has grown from an open source project](http://www.ams.org/notices/201306/rnoti-p713.pdf). However it is quite expensive, as many commercial statistical or machine learning solutions, available on the market today. I will start a brief review of **open source solutions** with a *hybrid solution* [GPTIPS](http://sites.google.com/site/gptips4matlab), which is an open source plug-in software for commercial MATLAB. It is referred to by authors as a "symbolic data mining platform for MATLAB". Now, turning to a **full open source software**, we can find several IMHO very interesting solutions. A well-known language-agnostic (but still Python-based) system [SageMath](http://www.sagemath.org) offers symbolic regression functionality via [SymPy](http://www.sympy.org) Python library, which can also be used independently as well. Another very interesting comprehensive open source software system is .NET-based [HeuristicLab](http://dev.heuristiclab.com). While HeuristicLab is labeled "a framework for heuristic and evolutionary algorithms", it offers a much wider range of functionality beyond symbolic computations and evolutionary/GP solutions. In addition to already-mentioned SymPy libarary, **Python ecosystem** offers [DEAP](https://github.com/DEAP/deap) open source project, where DEAP abbreviation refers to Distributed Evolutionary Algorithms in Python. My brief analysis of open source software for symbolic regression and related solutions would be incomplete without mentioning what my favorite **R ecosystem** offers in that regard. An interesting R package for GP and symbolic regression is `rgp` ([available on CRAN](http://cran.r-project.org/web/packages/rgp)), which is referred to as "R genetic programming framework" (RGP). The RGP package is a part of a larger set of open source tools for symbolic computation in R, developed under the umbrella of a larger [Rsymbolic project](http://rsymbolic.org). There are also several optimization-focused GP packages (<http://cran.r-project.org/web/views/Optimization.html>), however it is highly unlikely that they offer symbolic regression functionality out-of-the-box, as RGP package does. **References** Schmidt, M., & Lipson, H. (2009). Distilling free-form natural laws from experimental data. *Science, 324*(5923), 81–85. doi:10.1126/science.1165893 Retrieved from <http://creativemachines.cornell.edu/sites/default/files/Science09_Schmidt.pdf>
I strongly prefer *Mathematica* for such tasks. Given data of the form $mydata = \{ \{ x\_1, y\_1 \}, \{ x\_2, y\_2 \}, ... \}$, one searches for the unknown parameters such as $a$, $b$, $c$, and $d$ in a non-linear function of your choice in this way: ``` NonlinearModelFit[mydata, {a + b x + c x^2 + d Sin[x]}, {a, b, c, d}, x] ``` The symbolic output is ``` FittedModel[2.8 + 1.075 x + .292 x^2 + 4.9 Sin[x]] ``` A plot of that nonlinear model and the data looks like this: ![enter image description here](https://i.stack.imgur.com/G0Aij.png) You can put in as many basis functions as you like, and some may be "fit" with $0$ coefficients and such. Of course, too, you need more data points than free parameters for your fit to be meaningful.
19,237,918
I just upgraded from cordova 3.0 to 3.1 and I'm still experiencing a very disturbing issue (which still exists when playing with KeyboardShrinksView preference). Whenever I'm focusing an element (input/textarea) which triggers the keyboard opening, the element gets hidden behind the keyboard and I need to scroll down (using webkit-overflow-scrolling for scrolling by the way) in order to see the element and its content. When KeyboardShrinksView is set to true the page won't even scroll, making it even worse. Any solutions in order to fix this issue? I've seen a few questions and bug reports but with no working solutions (or solutions at all). Playing with the "fullscreen" preference won't solve the problem.
2013/10/08
[ "https://Stackoverflow.com/questions/19237918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016659/" ]
Just had a very similar problem to this. Some of the hacks found on this site did work, but had nasty side effects (such as making a mess of scrolling or CSS layout). Finally came up with a brand new stupid hack. Viewport meta tag: ``` <meta name="viewport" content="initial-scale=1, maximum-scale=1, width=device-width" /> ``` JavaScript run after load: ``` document.body.style.height = screen.availHeight + 'px'; ``` And that's it. Works on iOS 7 and I have ***no idea why***.
I think the issue here originates from Framework7. ``` document.body.style.height = window.outerHeight + 'px'; ``` The above code placed in my index.js file worked like charm.
69,566
To expand on the title, I'm building a pair of 3 way speakers and, to make them more compact, I'm planning on facing the sub woofer to the sides or rear. I'd expect to use them in small venues (pubs, clubs). I know it's an ambiguous question and it will depend on the room, but will the direction of the sub woofer have any impact at all, and would there be any real draw back in pointing the sub woofer to the sides or rear compared to front facing? Should I point the ports in the same direction as the sub woofer? If the majority of answers revolve about the unknown conditions, I'll give it a go and see how they turn out.
2018/04/04
[ "https://music.stackexchange.com/questions/69566", "https://music.stackexchange.com", "https://music.stackexchange.com/users/49455/" ]
It's somewhat dependent on what the speakers are for. One assumes p.a., for vocals. That will mean there's no great need, in smaller venues, for sub-woofers anyway. If it's for the whole band, a disco or suchlike, then sub-woofers are generally a separate entity in my experience in small venues. Mounting them in the same cabinets as other speakers makes the cabs heavier. And more bulky. In smaller venues one sub will be sufficient anyway, and since it's not directional, it could go centre stage. As far as ports go, face them the same way as the speaker itself, and face the whole lot forward, so the sound from it goes out the same as the rest of the p.a., rather than be reflected from side or back of stage. Right now, we have no clue as to the size of drivers intended. 12", 15", maybe 18" will make the cab pretty big anyway, with all the other stuff. Possible re-think?
I would say you need to be more specific about what you mean by "subwoofer" to get a proper answer here. Are we talking about a 10" speaker? A 12" speaker? 15"? 18"? Below a certain frequency, sounds are unidirectional. There's a Wikipedia article on [directional sound](https://en.wikipedia.org/wiki/Directional_sound). There's also a [reddit asking 'At what frequency does sound become too directional for a sub?'](https://www.reddit.com/r/audiophile/comments/1nymj2/at_what_frequency_does_sound_become_too/). Various forums including [Ars Technica](https://arstechnica.com/civis/viewtopic.php?f=6&t=437545) also address this issue. Generally speaking, high frequences are more directional and easily absorbed by walls, fabric, human bodies, etc. Low frequencies penetrate cloud, shadow, earth and flesh. The intensity of your low-frequency sounds from your speakers is more likely to be affected by your 3 sound sources being out of phase and possibly the proximity of your bass source to a wall. Speakers tend to give off a stronger bass signal when they are placed right up against the wall because you don't have wave reflections bouncing back at your speakers to cause phase cancellation. My Mackie 824 speakers have a switch on the back for bass roll off depending on their placement relative to their enclosing space. A [diagram printed on the back](https://i.ytimg.com/vi/urAV1NVmeXM/maxresdefault.jpg) to help elucidate how to set the switch. It's worth noting that some subwoofers are *down-firing* -- meaning the speaker just aims at the floor. [Here's an article about down-firing vs front-firing](https://audiophilereview.com/subwoofers/subwoofers-front-firing-or-down-firing.html) that you may find useful. Generally speaking, you want all your three sound sources as close to each other as possible and *firing in the same direction* to reduce phase cancellation as much as possible. Obviously, they should also be wired in-phase. This might be tricker than you think and you may want to experiment with the polarity of your wiring to make sure they aren't working against each other. If it was me, I'd say you should try and get them all pointing the same direction, but if the subwoofer is limited to sounds below 100Hz or so, you can probably worry about it less. EDIT: I just remembered I used to have a book on [Building Speaker Enclosures](https://rads.stackoverflow.com/amzn/click/B000S5HOZQ) from radio shack. You could pick up a copy super cheap.
22,475,135
When calling 'exit', or letting my program end itself, it causes a debug assertion: [![Debug Assertion Failed](https://i.stack.imgur.com/K4B5B.png)](https://i.stack.imgur.com/K4B5B.png) . Pressing 'retry' doesn't help me find the source of the problem. I know that it's most likely caused by memory being freed twice somewhere, the problem is that I have no clue where. The whole program consists of several hundred thousand lines which makes it fairly difficult to take a guess on what exactly is causing the error. Is there a way to accurately tell where the source of the problem is located without having to comb line for line through the code? The callstack doesn't really help either: [![Callstack](https://i.stack.imgur.com/Ifh4r.png)](https://i.stack.imgur.com/Ifh4r.png) .
2014/03/18
[ "https://Stackoverflow.com/questions/22475135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879228/" ]
It wasn't working because the carousel is using overflow, and the tooltips exceeded its margins.
carousel-inner sets overflow to hidden. You can disable it, however your content (content inside de inner div) needs to use fixed width Add this to your CSS header ``` carousel-inner { overflow: visible; } ```
6,684,585
How can I pull a data from any a web site through webrequest in c#? e.g price of the product in www.xxx.com Thanks,
2011/07/13
[ "https://Stackoverflow.com/questions/6684585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769829/" ]
The "prescribed" way of doing this is passing the [`TaskScheduler`](http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.aspx) instance from [`TaskSheduler::FromCurrentSynchronizationContext`](http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.fromcurrentsynchronizationcontext.aspx) to [`ContinueWith`](http://msdn.microsoft.com/en-us/library/dd321307.aspx) that you want to ensure executes on the WPF dispatcher thread. For example: ``` public void DoSomeLongRunningOperation() { // this is called from the WPF dispatcher thread Task.Factory.StartNew(() => { // this will execute on a thread pool thread }) .ContinueWith(t => { // this will execute back on the WPF dispatcher thread }, TaskScheduler.FromCurrentSynchronizationContext()); } ```
I don't think that you should directly update the ViewModel directly from a background thread either. I write a lot of Silverlight apps and I like to use the MVVMLight toolkit to implement the MVVM pattern. In MVVM, sometimes you need to have the ViewModel "affect" the View, which you cannot do directly because the ViewModel doesn't have a reference to the View. In these scenarios, MVVMLight has a Messenger class that allows us to "listen" for Messages in the View and "notify" from the ViewModel. I believe you should use the Messenger class in your scenario. Here is a link with sample code: <http://chriskoenig.net/2010/07/05/mvvm-light-messaging/>
22,287,060
How can I change what I am using which is javascript alert to use a jQuery UI / dialog. I have been trying to change my script over to use a dialog with no success. I want to use something better than alert to create the popup for my calendar. So I was thinking of a dialog but if there is something better I would be interested it also. This is my fullcalendar code ``` $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, eventClick: function(calEvent, jsEvent, view) { alert('Name: ' + calEvent.title + '\n' + "Start Date/Time: " + $.fullCalendar.formatDate(calEvent.start, 'dd-MM-yyyy hh:mm:ss TT') + '\n' + 'End Date/Time: ' + $.fullCalendar.formatDate(calEvent.end, 'dd-MM-yyyy hh:mm:ss TT') + '\n' + 'Address: ' + calEvent.address1 + '\n' + 'Apt/Suite: ' + calEvent.address2 + '\n' + 'City/Sate/Zip: ' + calEvent.city + ' ' + calEvent.state + ' ' + calEvent.zip + '\n' + 'Home Phone: ' + calEvent.hphone + '\n' + 'Cell Phone: ' + calEvent.cphone + '\n' + 'Work Phone: ' + calEvent.wphone + '\n' + 'Email: ' + calEvent.email + '\n' + 'Order Number: ' + calEvent.ordern); }, events: "json_events.php", loading: function(bool) { if (bool) $('#loading').show(); else $('#loading').hide(); } }); }); ``` This is how I send my json code to the calendar > > $events = array(); foreach($db->query("SELECT \* FROM `signings` WHERE > `pid` = '$pid' AND `done`= 0") as $row) { > > > > ``` > $title = $row['fname']." ".$row['lname']; > $eventsArray['id'] = $row['id']; > $eventsArray['ordern'] = $row['ordern']; > $eventsArray['title'] = $title; > //$eventsArray['url'] = "eventinfo.php?id=$id"; > $eventsArray['start'] = $row['signstart']; > $eventsArray['end'] = $row['signend']; > $eventsArray['address1'] = $row['street1']; > $eventsArray['address2'] = $row['street2']; > $eventsArray['city'] = $row['city']; > $eventsArray['state'] = $row['state']; > $eventsArray['zip'] = $row['zip']; > $eventsArray['hphone'] = $row['hphone']; > $eventsArray['cphone'] = $row['cphone']; > $eventsArray['wphone'] = $row['wphone']; > $eventsArray['email'] = $row['email']; > $eventsArray['allDay'] = ""; > $eventsArray['color'] = "#7B1616"; > $eventsArray['textColor'] = "#FFFFFF"; > > $events[] = $eventsArray; } > > ``` > > echo json\_encode($events); > > >
2014/03/09
[ "https://Stackoverflow.com/questions/22287060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3326386/" ]
the '+' character is a meta-character used to formulate regular expressions. If you wish to refer to it literally you need to escape it. The same goes with several other characters like `'.', '*', '[', ']'`, etc. ``` if (msg[1].contains("+")){ numeros = msg[1].split("\\+"); // this should work } ``` You might want to read [oracle's documentation](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html) on regular expressions for more information.
You need to escape `+` in your regular expression. `+` in regular expression is used to denote 'one or more of the preceding element' and you have no preceding element, hence the error. ``` numeros = msg[1].split("\\+"); ```
11,492,895
I'm currently working on a project out of a text book and I've had an obscure problem with a while loop. The code from the text book is as follows; ``` while(getImage().getWidth(applet) <= 0); double x = applet.getSize().width/2 - width()/2; double y = applet.getSize().height/2 - height()/2; at = AffineTransform.getTranslateInstance(x, y); ``` I've never seen a while loop declared with a semi-colon on the end, so I interpreted my code to be the standard; ``` while(getImage().getWidth(applet) <= 0) { double x = applet.getSize().width/2 - width()/2; double y = applet.getSize().height/2 - height()/2; at = AffineTransform.getTranslateInstance(x, y); } ``` Can someone please explain the difference between the two? I changed my code to be like the first and my program worked just fine, however I don't understand the difference.
2012/07/15
[ "https://Stackoverflow.com/questions/11492895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1298736/" ]
A semicolon is an empty statement. You can use it when evaluating the continuation condition of your `while` loop has a side effect: the loop will produce a chain of side effects that invalidate the loop condition upon completion, or run forever. For example, if `getImage()` gets you a new image every time you call it, the loop will continue until the returned image has width that is `<= 0`. Here is a simple example of using a `while` loop to find the first character after `a` in a string: ``` int pos = 0; String s = "quick brown fox jumps over the lazy dog"; while (i != s.length() && s.charAt(i++) != 'a') ; ``` Since reading code like that may be confusing, it is typical to place the semicolon on a separate line, indented as a loop statement.
The semicolon is the end of the while loop in the first example. It's sometimes useful to have a single-line loop like that, but it's also a common mistake. If it's intentional, then it looks like maybe this code is waiting for another thread to change the width of the applet in question. This isn't a great way to do something like that.
44,467,910
When I run this code the output of **D** comes out as the value of **C**. Is it because I call for a float and it just takes the most recent float in the memory? ``` #include <stdio.h> int main() { int a=3/2; printf("The value of 3/2 is : %d\n", a ); float b=3.0/2; printf("The value of 3/2 is : %f\n", b ); float c=7.0/2; <------- printf("The value of 3/2 is : %f\n", c ); int d=3.0/2; printf("The value of 3/2 is : %f\n", d ); <------- return 0; } ``` --- ``` The value of 3/2 is : 1 The value of 3/2 is : 1.500000 The value of 3/2 is : 3.500000 The value of 3/2 is : 3.500000 ```
2017/06/09
[ "https://Stackoverflow.com/questions/44467910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8122862/" ]
> > I try it by detect the base `height` of my element at first and use it to work with `transition`, because the `transition` need `height` to work . > > > ```js var box = document.getElementById("box"); var button = document.getElementById("button"); var expanded = true; var height = box.offsetHeight; box.style.height = height+"px"; button.addEventListener('click', function() { if (expanded) { box.style.height = 0; expanded = false; } else { box.style.height = height+"px"; expanded = true; } }); ``` ```css #box { margin-top: 20px; border: 1px solid black; background-color: #4f88ff; width: 300px; transition: height 0.25s; overflow: hidden; } ``` ```html <button id="button"> Click </button> <div id="box"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. </div> ```
Try this: ``` var box = document.getElementById("box"); var button = document.getElementById("button"); //get your dynamic div's height: var clientHeight = document.getElementById('box').clientHeight; var expanded = true; //define max-height property your div before collapse it. //otherwise it collapse without transition. box.style.maxHeight = clientHeight+"px"; button.addEventListener('click', function() { if (expanded) { box.style.maxHeight = 0; expanded = false; } else { //set height box.style.maxHeight = clientHeight+"px"; expanded = true; } }); ``` You can use `.scrollHeight` or `.offsetHeight` instead of `.clientHeight` depends on the situation. Check this comment for detailed info about these properties: <https://stackoverflow.com/a/22675563/7776015>
35,993,810
I have been experiencing something while calculating with floats which I do not understand, maybe somebody can explain the difference between these two operations and the results: ``` for var i = 10; i < 20; i++ { //Assuming i = 11 var result1:Float = Float(i/10) //equals 1 var result2:Float = Float(i)/10 //equals 1.1 } ``` I stumbled upon that because I expected result1 to return 1.1 and spent some time searching for the mistake until I understood the syntax must be like for result2 Is it because in Float(i/10) the inner operation (i/10) will always return an integer before it gets converted to a Float? Any explanation appreciated
2016/03/14
[ "https://Stackoverflow.com/questions/35993810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2548205/" ]
Your intuition is right, `i/10` where `i: Int` will **always** return an integer. It is then converted to a floating point number, but `Float(1) == 1`. The second statement converts `10` to a Float implicitly before performing the division, hence return `1.1`
Just an addendum, you can also get result2 with: ``` var result3 = Float(i/10.0) ``` Also an FYI, C style for loops are [going away in Swift 3.0](https://github.com/apple/swift-evolution/blob/master/proposals/0007-remove-c-style-for-loops.md)
35,953,938
Hi so I've been looking into this for a while and nothing I've tried has worked. Forgive me for asking this again, but I cannot replace a new line with a space in powershell ``` $path = "$root\$filename" Get-Content $path | % $_.Replace "`r`n"," " | Set-Content "$root\bob.txt" -Force ``` This is one of the many things I've tried just looking around on this site. I'm using powershell v3
2016/03/12
[ "https://Stackoverflow.com/questions/35953938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2763391/" ]
A couple of issues here. First, the way you are calling Get-Content, the strings sent down the pipe will never have a newline in them. That's because the default way Get-Content works is to split the file up on newline and output a string for each line. Second, your Foreach command requires {} around the replace command. Try this: ``` Get-Content $path -Raw | Foreach {$_ -replace "`r`n",' '} | Set-Content $root\bob.txt -Force ``` The `-Raw` parameter instructs `Get-Content` to read the file contents in as a single string. This will preserve the `CRLFs`.
Try this: ``` $NewStr = ""; Get-Content $Path -Raw | ForEach {$NewStr += "$_ "} $NewStr | Set-Content DestinationPath -Force ```
1,134,746
I have the following in .screenrc ``` # I want to use Vim's navigation keys bind h focus down bind t focus up ``` I would like to be able to move by `Ctrl-A t` to a next window, while by `Ctrl-A h to the previous window. However, the above mappings do not work anymore for me. **How can you move between windows in Screen?**
2009/07/16
[ "https://Stackoverflow.com/questions/1134746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54964/" ]
``` bind h prev bind t next ```
If you start screen then type Ctrl-A ?, you'll see the help page, which lists next [n] and prev [p]. I believe that binding to next and prev instead of focus will do what you want.
57,577,092
I am trying to develop an app which plays audio and includes the function to change audio devices. My only problem is when I try to use the `setSinkId()` function, it gives me a DOMException AbortError with the message 'The operation could not be performed and was aborted'. I have tried the exact same code in the latest version of Chrome and it allows me to set the sinkId without any issues. Here's my code: ``` var promise = audio.setSinkId(deviceID); promise.then(function(result) { console.log('Audio output device sink ID is ' + deviceID); }, function(e) { console.log('Error: ' + e.name + ' - ' + e.message); }); ``` I have tryed passing the `AudioOutputDevices` parameter through the `enableBlinkFeatures` when I setup the browser window but this doesn't make and difference.
2019/08/20
[ "https://Stackoverflow.com/questions/57577092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4788795/" ]
I feel your pain and I had the same question during my development. I didn't solve it in straight way. I can only suggest to check a few things regarding your source HTML element reference. 1) Is the `srcObject` set correctly? Before first time use `setSinkId()`, check if ``` audio.srcObject = stream; ``` 2) Check if `setSinkId()` event is not interrupted by `pause()`, `play()` or `load()` events. Remember that `setSinkId()` is a promise. ``` await audio.setSinkId(selectedId); audio.play(); ``` Hope it helps.
Maybe it's related to this old-reported issue. It's been on hold for years. <https://bugs.chromium.org/p/chromium/issues/detail?id=697877> Remember that for getting visibility on chromium, you should “Start" it with your Google account to help to the Chromium team to understand its importance.
12,599,505
I'm trying to create a backup from PostgreSQL database, but getting the following error: pg\_dump: No matching schemas were found I'm logged in as root and running the command pg\_dump -f db.dump --format=plain --schema=existing\_schema --username=userx --host=localhost databasename 1. I logged in with userx to psql and tried \dt - this gave me information, that schema with name existing\_schema is public. 2. I checked \l to see that databasename is the database name. 3. Password is correct, otherwise I could not access psql. 4. Localhost is correct, checked from running processes. Tried the ip-address of the server also, but in this case pg\_admin gave an error about the host address. Output of \dl: ``` List of relations Schema | Name | Type | Owner --------+-------------------------------------+-------+------- public | existing_schema | table | userx ```
2012/09/26
[ "https://Stackoverflow.com/questions/12599505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565682/" ]
You can try with back slash and double quote as metioned [here](http://postgresql.nabble.com/pg-dump-t-quot-Table-quot-for-cmd-exe-td5731755.html). ``` sudo -u postgres pg_dump -v Database_Name -t "\"Table_Name\"" ```
``` \dn list out all the schema in the database ``` if you want to dump only schema , [refer](https://stackoverflow.com/questions/12564777/schema-only-backup-and-restore-in-postgresql/12564792#12564792)
97,969
I use this command: yum install apache2-mpm-worker with no success. Searching on google also not found Thanks.
2009/12/29
[ "https://serverfault.com/questions/97969", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
Uncomment the httpd.worker line in /etc/sysconfig/httpd: ``` # The default processing model (MPM) is the process-based # 'prefork' model. A thread-based model, 'worker', is also # available, but does not work with some modules (such as PHP). # The service must be stopped before changing this variable. # #HTTPD=/usr/sbin/httpd.worker ``` Cheers
I've done that and restarted apache. I do an httpd -l and it only shows the prefork.c not the worker.c . I have checked the sbin directory and know for a fact the httpd.worker file exists. ANy other ideas?
7,172,725
I have a EF4.1 class X and I want to make copy of that plus all its child records. X.Y and X.Y.Z Now if I do the following it returns error. The property 'X.ID' is part of the object's key information and cannot be modified. ``` public void CopyX(long ID) { var c = db.Xs.Include("Y").Include("W").Include("Y.Z").SingleOrDefault(x => x.ID == ID); if (c != null) { c.ID = 0; c.Title = "Copy Of " + c.Title; for (var m = 0; m < c.Ys.Count; m++) { c.Ys[m].ID = 0; c.Ys[m].XID=0-m; for (var p = 0; p < c.Ys[m].Zs.Count; p++) { c.Ys[m].Zs[p].XID = 0 - m; c.Ys[m].Zs[p].ID = 0 - p; } } for (var i = 0; i < c.Ws.Count; i++) { c.Ws[i].ID = 0 - i; c.Ws[i].XID = 0; } db.Entry<Content>(c).State = System.Data.EntityState.Added; db.SaveChanges(); } } ``` Or Is there other way of making copy of entity objects. NOTE: there are multiple properties in each W,X,Y,Z.
2011/08/24
[ "https://Stackoverflow.com/questions/7172725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/467425/" ]
You need to make correct deep copy of the whole entity graph - the best way is to serialize the original entity graph to memory stream and deserialize it to a new instance. Your entity must be serializable. It is [often used with DataContractSerializer](http://blog.vascooliveira.com/how-to-duplicate-entity-framework-objects/) but you can use binary serialization as well.
I use Newtonsoft.Json, and this awesome function. ``` private static T CloneJson<T>(T source) { return ReferenceEquals(source, null) ? default(T) : JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source)); } ```
66,566,889
I have a function xyz() which returns an `tuple<std::string, double>`. When I call this function individually, I can do the following: ``` auto [tresh, loss] = xyz(i); ``` This results in no error, but if I want to use the xyz() function in an if else block, then I can not use the `tresh` and `loss` variables anymore in the following code. Example: ``` if (boolX) { auto [tresh, loss] = xyz(i); } else { auto [tresh, loss] = xyz(j); } std::cout << tresh << std::endl; ``` I also tried to initialise the tresh and loss variable before the if else block and remove the `auto`, but this gives the following error: `Expected body of lambda expression` How to resolve this?
2021/03/10
[ "https://Stackoverflow.com/questions/66566889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7657749/" ]
Depending on the exact code, you could replace with a ternary ``` auto [tresh, loss] = boolX ? xyz(a) : xyz(b); std::cout << tresh << std::endl; ```
You can use a lambda for it: ``` auto [tresh, loss] = [&boolX, &i, &j](){ if (boolX) { return xyz(i); } else { return xyz(j); } }(); std::cout << tresh << std::endl; ```
60,736,380
I hope you got the question from the title itself. After migrating I can select multiple fields from that many to many field in django admin page but when I click on save it saves in the admin page of django but when I check the postgresql database everything that is not many to many field saves but the table lacks many to many field column.
2020/03/18
[ "https://Stackoverflow.com/questions/60736380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13081289/" ]
There are no many-to-many connections in Postgres, nor other SQL databases as far as I know. These connections are generally made thru a third table (called thru-table sometimes), connecting values from two tables. Django does this behind the scenes for you. You should find the third table in the database. There are default names for them and you can choose a name too.
If you check the database in graphical interfaces such as pgadmin or in the terminal, you will see that none of the databases show the many-to-many relationship, but in practice everything is in order and working. This could be because you can't change it through tools like pgadmin, and the reason of many-to-many relationships are null = True by default is probably because you can't change them in user interfaces.
15,879
In Aperture 3, at the beginning of the Import process, one can select/check or unselect/uncheck images one by one. But it requires the mouse. In the Viewer view, during that selection process, I can go to the next image easily using the keyboard, with the `->` key, but what is the way to uncheck an image using the keyboard? (ie without having to click on the checkbox with the mouse) **Edit** Since I'm here, and in order not to create another question: is there a way to have the Undo to work *only* on the current image, being viewed in preview? (the default for multiple undoes, is to perform the undoes even on previously edited images (not shown during the undo) - very confusing/dangerous)
2011/06/13
[ "https://apple.stackexchange.com/questions/15879", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/7163/" ]
Safari will show what the developper of the given website provides as alternative content for browsers (user agents) that do not support Flash. In many cases this is just nothing or the hint to download Flash player plugin. Youtube videos are played by the built-in youtube app of iOS.
There is a Youtube app built in which does not require flash. It probably makes use of HTML5 markup.
48,293,307
I need to compare two arrays containing a list of names and a list of selected indices. I need to get as a result another array with names of just the indices given. How could achieve this? I am trying using `foreach` but I get doubled values. ``` let selectedIndices = [1, 3, 7, 10] let namesArray = ["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "jjj", "kkk", "lll", "mmm"] finalArray = ["bbb", "ddd", "hhh", "lll"] ```
2018/01/17
[ "https://Stackoverflow.com/questions/48293307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2075848/" ]
Here is how to get that done: If you are using cli, <https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html> Get the object with the version you want. Then perform a put object for the downloaded object. <https://docs.aws.amazon.com/cli/latest/reference/s3api/put-object.html> Your old S3 object will be the latest object now. AWS S3 object is immutable and you can only put and delete. Rename is GET and PUT of the same object with a different name. Hope it helps.
No. However, to protect against this in the future, you can enable versioning on your bucket and even configure the bucket to prevent automatic overwrites and deletes. [![enter image description here](https://i.stack.imgur.com/gYwyz.png)](https://i.stack.imgur.com/gYwyz.png) To enable versioning on your bucket, visit the Properties tab in the bucket and turn it on. After you have done so, copies or versions of each item within the bucket will contain version meta data and you will be able to retrieve older versions of the objects you have uploaded. Once you have enabled versioning, you will not be able to turn it off. EDIT (Updating my answer for your updated question): You can't version your objects in this fashion. You are providing each object a unique Key, so S3 is treating it as a new object. You are going to need to use the same Key for each object PUTS to use versioning correctly. The only way to get this to work would be to GETS all of the objects from the bucket and find the most current date in the Key programmatically. EDIT 2: <https://docs.aws.amazon.com/AmazonS3/latest/dev/RestoringPreviousVersions.html> To restore previous versions you can: > > One of the value propositions of versioning is the ability to retrieve > previous versions of an object. There are two approaches to doing so: > > > Copy a previous version of the object into the same bucket **The copied > object becomes the current version of that object and all object > versions are preserved.** > > > Permanently delete the current version of the object When you delete > the current object version, you, in effect, turn the previous version > into the current version of that object. > > >
12,371
Movie super-heroes are commonly shown to be fearless. In *Dark Knight Rises*, fearlessness is discussed directly: ``` Blind Prisoner: You do not fear death. You think this makes you strong. It makes you weak. Bruce Wayne: Why? Blind Prisoner: How can you move faster than possible, fight longer than possible without the most powerful impulse of the spirit: the fear of death. Bruce Wayne: I do fear death. I fear dying in here, while my city burns, and there's no one there to save it. Blind Prisoner: Then make the climb. Bruce Wayne: How? Blind Prisoner: As the child did. Without the rope. Then fear will find you again. ``` Is the fear of death the most powerful impulse of the spirit for Batman in *Dark Knight Rises*, or superheroes in other films? Is there a philosophical understanding of fear and in particular fear of death that supports the idea and development of the superhero?
2013/07/05
[ "https://movies.stackexchange.com/questions/12371", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/5315/" ]
I would argue the answer to this is no; fear of death may be a powerful impulse of the spirit but to say it is the **MOST** powerful does not satisfy reason (which is the basis of philosophy), and facing the fear of death is not enough to explain the power of the superhero. 1. **A bit of logic…** When faced with a statement of absolute (MOST powerful impulse), one only has to find an example where this is not true to disprove it. In the news we hear stories of [people who gave their life for others](http://www.myfoxdetroit.com/story/19479052/army-hero-dies-after-taking-bullets-for-girl) or [for a greater cause](http://www.telegraph.co.uk/news/worldnews/asia/afghanistan/5146667/Taliban-shoot-dead-female-politician-who-fought-for-womens-rights.html). History records the stories of [martyrs](http://news.bbc.co.uk/2/hi/uk_news/129587.stm) who put a cause above their own lives. Armies are full of soldiers prepared to give their own life in service for their country. We can conclude from this that sometimes other impulses outweigh the impulse to save oneself. In fact, Bruce Wayne is arguably less motivated by fear of his own death than he is by his belief that he is the only one who can save the city. 2. **Nolan’s scene seems to support the statement, but…** In this scene, Bruce Wayne increases his fear of death by removing the safety net of the rope, and draws strength from the increased fear, which allows him to succeed (audience cheers and walks away convinced that the prisoner was right). Indeed, if you know you have only one chance to succeed at something, and you believe absolutely in the need to succeed (Wayne felt he was the only one who could save the city, so his survival was imperative), then that fear *could* increase focus and success. If we follow this to its logical conclusion, however, it suggests that whenever Bruce Wayne/ Batman faces a challenge, he can increase his power by removing his safety nets – weapons, tools, protection. If the fear of one’s death is the most powerful impulse of the spirit, does it follow that increasing the fear increases one’s resolve/strength/power? Would a naked Batman, whose fear would be the greatest, be most powerful? 3. **The philosophical view of fear of death…** Ancient philosophers such as [Epicurus](http://www.ancientl.com/philosophy/fear-of-death-and-epicurean-philosophy/) and [Socrates](http://blog.talkingphilosophy.com/?p=6848) argued that death is nothing and fear of it is illogical (Socrates you may remember was sentenced to death and chose not to escape prison when given the opportunity, instead facing death in line with his views). Nolan’s view is probably closest to [Thomas Hobbes](http://www.jstor.org/discover/10.2307/191224?uid=3739920&uid=2129&uid=2&uid=70&uid=4&uid=3739256&sid=21102510017727), who argued that the fear of a *violent* death was the most powerful force in human life. This isn’t quite the same as just fearing the end of life. (I am not finding writings by other philosophers that differ much from these views – perhaps someone else will add some other research.) 4. **Philosophy as applied to Batman and superheroes…** If fear of death is not the greatest impulse for Bruce Wayne, what is? In his book, [*Superheroes and Philosophy: Truth, Justice, and the Socratic Way*](http://books.google.com/books?id=efpm5Wcb_OgC&printsec=frontcover&dq=Superheroes%20and%20Philosophy%3a%20Truth,%20Justice,%20and%20the%20Socratic%20Way&hl=en&sa=X&ei=nf_WUY2DPYm49QSbuoDADQ&ved=0CC0Q6AEwAA), Tom Morris theorizes that rather than fear of death, our deepest fear is fear of our own power. The superhero faces the fear of embracing his power, and when we humans look up to the superhero, it is not fearlessness in the face of death that we seek to emulate, it is the courage to embrace our own power to achieve the most noble pursuit we are capable of in any given moment. It is the fear of embracing an ideal so absolutely that we would willingly risk our life for it. Another interesting read on the subject is [*Batman and Philosophy: The Dark Knight of the Soul*](http://books.google.com/books?id=hf5f3r38P1cC&printsec=frontcover&dq=Batman%20and%20Philosophy%3a%20The%20Dark%20Knight%20of%20the%20Soul&hl=en&sa=X&ei=av_WUcCvH4r29gT034GwDg&ved=0CDUQ6AEwAA) (Mark D White and Robert Arp). It posits that Batman’s primary motivation is deontological – Bruce Wayne does what he does in promise to his parents. He always keeps his promise, and it is his resolve that his enemies fear most. It is his resolve that is the source of his strength, not his fears. It his resolve that allowed him to climb out of the pit. The book offers a fairly thorough discussion of Batman, his virtuous hatred, his role in the process of justice, his origins and ethics, issues of identity, and his connection to existentialism and Taoism.
> > Is the fear of death the most powerful impulse of the spirit for Batman in *Dark Knight Rises* > > > No. Bruce Wayne ends up showing us his humanity in many ways, including a few of his fears, in this movie. However, considering that he fights and puts himself in harm's way as he does, a fear of death is not one of his fears. Although he trusts the technology behind his gear, and the design behind the technology, a fear of death would hamper his ability to perform his death-defying stunts and acrobatics. > > Is the fear of death the most powerful impulse of the spirit superheroes in other films > > > I suppose that one could argue that Tony Stark is kept alive by the magnet in his chest that he improved and maintains because he has a fear of death, and that the creation of his suit in the first Iron Man movie was also because he feared dying (being killed) in that cave. Of course, he wanted to do a lot of damage on the way out, and he feared that Stark Industry weapons would continue to be used against American troops and innocent civilians... but that's a different fear. However, I don't believe that the Green Lantern is motivated by a fear of death at all. I don't believe Superman in any of his movie incarnations is motivated by a fear of death. I **know** the Hulk isn't motivated by a fear of death. I suspect that a fear of losing his sense of humor is the most powerful motivating factor in Spiderman's life. In general, I believe that motivations, or what drives the Individual Superheroes, are as different and individual to each Hero as the Heroes are themselves. I mean, X-Men aren't quite Superheroes in the same sense that Batman, Superman, and Spiderman... but you can definitely say that a fear of death is not in Wolverine's mental bag of tricks. > > Is there a philosophical understanding of fear and in particular fear of death that supports the idea and development of the superhero? > > > Again, it depends on the Superhero. In the case of Green Lantern, the understanding and study of fear is **integral** to the development of the entire Green Lantern Corps. Fear had it's own color (Yellow) and got a ring, was the motivation behind a Supervillan, etc. Fear in general, and specific fears, don't play as much of a part in many of the Superman movies... although Superman giving up his power to settle down with Lois Lane *might* have been out of fear of turning her to mush during some Supersex. Probably not though. The development of Doctor Manhattan was not born of a fear of death. He pretty much started out as dead, or believing himself dead. As he once said, reconstituting himself from scattered atoms was the first thing he figured out how to do. You can say that there is typically a *moral* message in each Superhero storyline, and that there is a moral struggle each Superhero faces. However, you can't globally say that all superheroes struggle with a fear of death. Some would welcome it at one time or another. I'm sure Bruce Banner wished more than a few times early on that he could die rather than become the Hulk... until he got some kind of handle on it. But with the Hulk, the story is definitely more about Rage and dealing with it properly, than it is about fear and the fear of death. **Edit** It is important to note that Bruce Wayne's statement... > > I do fear death. I fear dying in here, while my city burns, and there's no one there to save it. > > > ... is more a fear of being impotent (in being able to save Gotham) than an actual fear of death. I mean, I realize he says the words "I do fear death, I fear dying here" but taken alone out of context, you miss what it is he actually fears, which is the death of Gotham, not the death of Bruce Wayne or the death of Batman.
47,948,555
My header is devided in 3 sections: `left`, `center` and `right`. The `left` section is empty. In the `center` section I have my page title and in the `right` section I placed an "Account" link with an icon next to it. The link contains the word ACCOUNT and an icon. the icon is somehow pushed to the top and leaves a blank space below it next to the word. I want them both in one line and on the same hight. How can I achieve this? I added a red background to make the problem better understandable. ```css html { height: 100%; box-sizing: border-box; overflow: hidden; } *, *:before, *:after { box-sizing: inherit; overflow: inherit; } body { background-color: #f5f5f5; margin: 0; padding: 0; position: relative; height: 100%; } #in { width: 1000px; margin-left: auto; margin-right: auto; height: 100%; } /* ------------------------------------------------------------------------ */ /* -------------------------------- HEADER -------------------------------- */ /* ------------------------------------------------------------------------ */ header { background-color: #131b23; border-bottom: 6px solid #0f151a; text-align: center; left: 0; top: 0; width: 100%; height: 170px; box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23); z-index: 99; } #left { background-color: green; width: 20%; position: absolute; height: 164px; } #center { background-color: red; width: 60%; margin-left: auto; margin-right: auto; height: 100%; position: absolute; left: 20%; right: 20%; height: 164px; } #right { background-color: blue; width: 20%; height: 100%; position: absolute; right: 0; height: 164px; } #heading { font-size: 60px; display: block; margin-bottom: -7px; margin-top: 15px; } .accountlink { font-family: "Helvetica"; text-decoration: none; font-weight: 800; color: #ffffff; font-size: 13px; letter-spacing: 1px; text-transform: uppercase; background-color: red; position: absolute; right: 30px; top: 15px; } .navigationicon { position: relative; width: 24px; margin: 0; padding: 0; top: 50%; bottom: 50%; } ``` ```html <header> <div id="left"> </div> <div id="center"> <h1 id="heading">My Page</h1> </div> <div id="right"> <a class="accountlink" href="login.html">Account <img class="navigationicon" src="https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/user_male2-512.png"></a> </div> </header> ```
2017/12/22
[ "https://Stackoverflow.com/questions/47948555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8315609/" ]
You can convert the `Counter` objects to `frozenset`s, which are hashable and can be put in a set themselves for linear savings on the `in` check: ``` from collections import Counter counters = set() no_duplicates = [] for sub_list in all_subsets: c = frozenset(Counter(sub_list).items()) if c not in counters: counters.add(c) no_duplicates.append(list(sub_list)) ``` Doing this with a dict comprehension also looks cool: ``` no_duplicates = list( {frozenset(Counter(l).items()): l for l in all_subsets}.values()) ```
Why you are using any external module and why making it too complex when you can do it in just few lines of code: ``` data_=[[], [1, 2, 2], [1], [2], [2], [1, 2], [1, 2], [2, 1], [2, 2]] dta_dict={} for j,i in enumerate(data_): if tuple(sorted(i)) not in dta_dict: dta_dict[tuple(sorted(i))]=[j] else: dta_dict[tuple(sorted(i))].append(j) print(dta_dict.keys()) ``` output: ``` dict_keys([(1, 2), (), (1,), (2, 2), (1, 2, 2), (2,)]) ``` if you want list instead of tutple : ``` print(list(map(lambda x:list(x),dta_dict.keys()))) ``` output: ``` [[1, 2], [], [1], [2, 2], [1, 2, 2], [2]] ```
467,554
I'm currently reading a book on optics, and have encountered a curious section: > > $$\nu = \nu'\sqrt{1-\frac{u^2}{c^2}} = \nu'\left(1-\frac{u^2}{2c^2}+\ldots\right)$$ > > > This is the formula for the *transverse Doppler shift*, giving the frequency change when the relative motion is at right angles to the direction of observation. The transverse Doppler shift is a second-order effect and is **therefore very difficult to measure.** It has been verified by using the Mossbauer effect with gamma radiation from radioactive atoms. > > > What about this specific effect makes it difficult to measure? I understand that the text says it is because it is a second-order effect, but it's not clear to me why that makes a correction term so much more difficult to observe. Is there a good elucidation on the reasons behind this?
2019/03/20
[ "https://physics.stackexchange.com/questions/467554", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/-1/" ]
I think it is a combination of the relative sizes of $v/c$ versus $v^2/c^2$ combined with the requirement to make sure a tangential velocity has no confusing radial component with a high level of precision throughout the measurement. I suppose ideally you want something moving in a perfect circle and emitting radiation towards the centre. If the tangential velocity is $v\_t$, then to isolate the transverse shift, you need to know any radial component to much better than $v\_t^2/c^2$. As an example. If I have an emitter moving at $3\times 10^4$ m/s, then the transverse Doppler effect is of order $10^{-8}$ compared with a "normal" Doppler effect of $10^{-4}$. Thus any radial motion must be eliminated (or characterised) to much better than 1 part in $10^4$ to isolate the transverse shift.
The transverse Doppler actually doesn't exist, it is the "relativisic" Doppler Effect that occurs at all angles, which is caused by a slowing down of emission processes by motion in the gravitational field of the earth, which has nothing to do with some kind of time dilatation. There is no need to measure the transverse Doppler Effect at 90 degrees, but if you do it, it is difficult, because the emission angle permanently changes, if measured directly perpendicular to a moving light source.
18,459,515
I want to insert data from an array. Below is an example situation. I grab all my friends available in friends list (fb) and store them in an array. Now I want to insert their data ( `name, fbid, birthday` ) into a table. Currently I'm doing this using a for loop below is an example code. ``` <?php $friendsname = $_POST['name']; $friendsfbid = $_POST['fbid']; $friendsbday = $_POST['birthday']; for($i<0;count($friendsfbid);$i++){ $sql_query = "INSERT INTO table (fbid, name, birthday) VALUES ('$friendsfbid[$i]','$friendsname[$i]','$friendsbday[$i]') ON DUPLICATE KEY UPDATE fbid='$friendsfbid[$i]', name='$friendsname[$i]', birthday='$friendsbday[$i]'"; } ?> ``` Now if I have 300 friends this will loop 300 times. The more number of friends the more time its going to take to process the data. Is there a way to avoid this or to increase the performance of the code. ? Using PHP with mySQL
2013/08/27
[ "https://Stackoverflow.com/questions/18459515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2555660/" ]
Please See this query hope this will be improve our code and speed. Avoid doing SQL queries within a loop A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once. ``` foreach ($userList as $user) { $query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")'; mysql_query($query); } ``` Instead of using a loop, you can combine the data into a single database query. ``` $userData = array(); foreach ($userList as $user) { $userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")'; } $query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData); mysql_query($query); ```
``` $sql = ''; foreach($friendsfbid as $key => $value){ $sql .= INSERT INTO table (fbid, name, birthday) VALUES ('$value[$key]','$friendsname[$key]','$friendsbday[$key]') ON DUPLICATE KEY UPDATE fbid='$value[$key]', name='$friendsname[$key]', birthday='$friendsbday[$key]'"; } mysql_query($sql); ``` You can stack your sql INSERTs into string and then run them by calling query function only once. That should speed the process up.
25,544,348
I've started learning how to use PHPUnit. However, I'm facing a problem which I have no clue how to solve. I have a folder called `lessons` and inside there is a `composer.json` which I installed PHPUnit with. The output resulted in a folder called `vendor` and a sub-folder called `bin` which has the phpunit file in it. In the `cmd` I typed: `cd c:/xampp/htdocs/lessons/vendor/bin`. Now the cmd folder sets to the same folder as phpunit. I've created a directory in `lessons` which I called `tests` (`lessons/tests`) which I store all of my tests in. I've created a file called `PracticeTest.php` with a very simple test script in it. When I go back to the `cmd` and type `phpunit tests` I get `cannot open file tests.php` When I try to type `phpunit PracticeTest` I get `cannot open file PracticeTest.php`. When I try `phpunit tests/PracticeTest` (with `.php` or without) I get the same error that the file could not be opened. My suspicious that it has something to do with that face that the `cmd` is pointing at the `lessons/vendor/bin` directory, but I'm not sure if it is really the problem or how to fix it. just to arrange the paths: * `lessons\vendor\bin\` * `lessons\tests\` * `lessons\tests\PracticeTest.php` Thanks in advance!
2014/08/28
[ "https://Stackoverflow.com/questions/25544348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972768/" ]
I was getting the same, but if you type `phpunit` then tab you will see what directory you are in and it should autosuggest. Then navigate to your test file.
I have created a phpunit.bat in the root folder of my project containing ``` @ECHO OFF SET BIN_TARGET=%~dp0/vendor/phpunit/phpunit/phpunit php "%BIN_TARGET%" %* ``` Now it works.
395,396
My notes say that the ordinals $\omega + 1, \omega + 2, ... , 2 \omega, ... , 3 \omega, ... \omega^2, ... $ are all countable, and hence have cardinality equal to $\omega = \aleph\_\mathbb{0}$. So I was wondering if it's fair to say that every ordinal has cardinality no greater than $\aleph\_\mathbb{0}$? Alternatively, I guess it's possible that that the sequence of infinite ordinals listed above, does not include some of the ordinals with a cardinality greater than the naturals.. but I wasn't sure.
2013/05/18
[ "https://math.stackexchange.com/questions/395396", "https://math.stackexchange.com", "https://math.stackexchange.com/users/78274/" ]
A hint to start you off. Take all the countable ordinals, ordered in size. Ask: are they *well-ordered*? if so, ask: What is the order-type of *that* sequence of objects? Is it an ordinal? Must it be bigger than any countable ordinal?
(In ZFC) by Cantor's theorem, $2^{\aleph\_{0}}=\vert \mathcal{P}(\omega)\vert> \vert \omega\vert=\aleph\_{0}$, so that $\vert P(\omega)\vert (\approx \mathbb{R})$ is an uncountable cardinal and therefore an uncountable (limit) ordinal (here $2^{\aleph\_{0}}$ is cardinal exponentiation). The claim that $2^{\aleph\_{0}}=\aleph\_{1}$, i.e that the least cardinal strictly greater than $\aleph\_{0}$ is $2^{\aleph\_{0}}$, is known as *Continuum Hypothesis*.
11,864,926
This is probably something very basic and simple, and I'm probably just googling for the wrong terms, but hopefully someone here can help me. (I'm still a beginner to programming, which is probably obvious from this question.) I'm looking for a way to access variables from strings. Like this: ``` A1 = {} B1 = {} C1 = {} mylist = ["A","B","C"] for blurb in mylist: blurb1.foo() ``` Right now I'm using if/elif-constructions in such cases: ``` if blurb == "A": A1.foo() elif blurb == "B": B1.foo() elif blurb == "C": C1.foo() ``` That works, but surely there's a more elegant way of doing it? Thanks for any help! Lastalda --- Edit2: trying to clarify again (sorry for not being very coherent before, it's hard for me to get this across): **I would like to create and access objects from strings.** So if i have a function that returns a string, I want to create e.g. a list using this string as the list name, and then do stuff with that list. ``` x = foo() # foo returns a string, e.g. "A" # create list named whatever the value of x is # in this case: A = [] ``` Isn't there anything more elegant than preparing lists for all possible outcomes of x and using long elif constructions or dictionaries? Do I have to use eval() in that case? (I'm hesitant to use eval(), as it's considered dangerous.) I hope it's finally clear now. Any help still appreciated!
2012/08/08
[ "https://Stackoverflow.com/questions/11864926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1413513/" ]
use `eval()`. example: ``` A1 = [] B1 = [] C1 = [] mylist = ["A","B","C"] for blurb in mylist: eval("%s1.append(blurb)" % blurb) print A1,B1,C1 >>> ['A'] ['B'] ['C'] ``` and for your code it can be: ``` for blurb in mylist: eval("%s1.foo()" % blurb) ```
I looks like you simply want a dictionary and to look it up rather than run a bunch of checks. ``` dict_look_up = {'A' : A1, 'B' : B1, 'C' : C1} try: dict_look_up[blurb].foo() except KeyError: #whatever on item not found ``` `try/except` blocks are incredibly important in Python (better to ask for forgiveness than permission), so if you're learning I recommend using them from the get go.
15,338,191
Here is my PHP code. In this I am creating a table and Populating data by pulling it from the database. I am printing two rows. In the second table row I have written "Hello There". My understanding of .hide() function makes me belief that it should be hidden on page display. But its not happening so? ``` <table> <thead> <tr> <th>All Courses</th> <th>Center</th> <th>Batch</th> <th>Click for Info</th> </tr> </thead> <tbody> <?php if($batch_query != null){ $i = 0; foreach($batch_query->result_array() as $row){ $val = "'".$row['course_id'].",".$row['center_id'].",".$row['batch_id']."'"; echo "<tr>"; echo "<td>".$row['course_name']."</td>"; echo "<td>"."<button id= \"btn_number_$i\" class='btn info toggler' >Info <i class='icon-arrow-down'></i></button>"."</td>"; echo "</tr>"; echo "<tr class='info_row'>Hello There!!</tr>"; $i++; } } ``` In the code I am creating two rows and initially I want to set the display property of second row to none by using jQuery hide method. Here is my jQuery code in between the script tag on the same page: ``` $(function(){ console.log('Hello World!!');// Just to test whether the code is being reached or not. $('.info_row').hide(); }); ``` But this hide() function does not seem to be working. The whole string "Hello there" remains on the page. What could be the reason for this ?
2013/03/11
[ "https://Stackoverflow.com/questions/15338191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1590011/" ]
I have found out a way may be its not the best one but some how I am getting a fast parsing. ``` NSData * fileData = [[NSData alloc] initWithContentsOfURL:url]; xmlParser = [[NSXMLParser alloc] initWithData:[self removeElements:fileData]]; [xmlParser setDelegate:objUtil]; success = [xmlParser parse]; ``` I ahve ceated a method `removeElements:fileData`, which accepts NSData and returns the same, with the required result(bY trimming the xml string). ``` - (NSData*) removeElements :(NSData*)data { NSMutableString * strFromData = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSRange startRange = [strFromData rangeOfString:@"<xs:schema"]; NSRange endRange = [strFromData rangeOfString:@"<diffgr"]; [strFromData replaceCharactersInRange: NSMakeRange(startRange.location,endRange.location - startRange.location) withString: @""]; NSLog(@"%@",strFromData); NSData *retData = [strFromData dataUsingEncoding:NSUTF8StringEncoding]; return retData; } ``` Thanks to all the friends who took out time of their busy works to help me :)
Try to use [TBXML](http://www.tbxml.co.uk/TBXML/TBXML_Free.html) parsing Library for iOS.This is a DOM Parser easy to use. You can find parser comparison here : [Ray Wenderlich Blog](http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project)
126
As I see people's reputations rapidly grow, and become frustrated because it seems impossible to get to a question first, I can't help but wonder if there is manipulation/cheating going on. After all, this would be expected Internet behavior. How do we know that people don't manipulate their reputations by using fake profiles and/or conspire with groups of friends? Surely this *IS* a problem you are aware of, surely it *HAS* been done, and I wonder to what extent? Are there discussions about this? Has anyone been caught? Does this site care? Or is this something that is of little concern? **RESPONSE TO ALL:** Thank you all for your feedback ;p. When I posted this, I must confess to some ignorance about how reputations were built. Sure, that ignorance could have been remedied prior to posting, but what fun would that be? Specifically, as Igor pointed out first, these sites encourage one to answer their own questions, and reps are more about how many people find your answers useful, even if it's an answer to your own question. However, as Ange seconded, there is an overall feeling here that I was expressing. That is that new comers are often discouraged. It's so hard to get started. And if you think you've written a great answer, somebody has done it better. It's extremely humbling. Those of us in small fields like reversing probably aren't used to much socializing, so let's just say it will take an ego adjustment. Is there anything that can be done to make these sites more friendly to the new comer? I don't know. I haven't come up with anything yet. ***We all need to remain excited about our work and hobbies, and therefore 'showing off' has some definite utility***. It does get harder and harder to do so in this forever critical society. So easy to be a critic ;p. Meanwhile, I'm composing a series of question/answers for myself. P.S. Did you guys really need to downvote this that many times? ;p
2013/04/08
[ "https://reverseengineering.meta.stackexchange.com/questions/126", "https://reverseengineering.meta.stackexchange.com", "https://reverseengineering.meta.stackexchange.com/users/1563/" ]
No, **I don't think** there's a reputation manipulation going on here. You have to remember that the site is barely three weeks old and less than one week in public beta. There aren't that many questions posted, so every new question gets a lot of attention and it's not unusual that they get good answers reasonably quickly. The hypothetical behavior you describe is called [sock puppetting](https://meta.stackexchange.com/questions/tagged/sock-puppets) and it's a [serious violation of the rules](https://meta.stackexchange.com/questions/164690/gaming-the-system-or-am-i-just-paranoid). If you suspect specific users of this behavior you should [flag them](https://meta.stackexchange.com/q/24560/211127) and the moderators will investigate. And yes, some peoples are really "*sitting there, waiting for questions all day*". You can do it yourself by subscribing to an RSS feed of [all questions](https://reverseengineering.stackexchange.com/feeds) or [specific tags](https://reverseengineering.stackexchange.com/feeds/tag/windows). I do it myself, though I'll probably unsubscribe from the all-inclusive feed if it becomes too much. On StackOverflow I subscribe to a few selected tags. With around 5 questions per day it's not a huge burden so far. If you'd like to learn how to gain reputation yourself, see answers to this post with recommendations: * **[Six simple tips to get Stack Overflow reputation fast](https://meta.stackexchange.com/a/17250/211127)** Post from Jon Skeet, one of the highest rep SO users: * **[Answering technical questions helpfully](http://msmvps.com/blogs/jon_skeet/archive/2009/02/17/answering-technical-questions-helpfully.aspx)** See also: [**How secure is Stack Exchange's reputation?**](https://security.stackexchange.com/questions/13664/how-secure-is-stack-exchanges-reputation)
It sounds like the end result is quickly getting in-depth, well-formatted responses to questions, so I don't see this as a bad thing. I think the purpose of reputation is to incentivise good, fast answers, so everything is working to plan. SE actually encourages answering your own questions. I'm not sure if people are posting using dummy accounts, but even if they were it seems unlikely that it's harmful to the community. I also think that your time-estimates are a bit off. Most of my answers take no more than 45 minutes to write, and I'll leave the main page open, so I see new questions as they pop up. (I have a lot of free time, and I really like the site.) A lot of the questions, especially popular ones, are pretty trivial, so a large amount of the user-base don't need to do any research to answer it, they just start writing. As well as this, a lot of users are active on other SE sites, so they know the formatting well - it's not really an obstacle. If there's evidence that people are using dummy accounts or collusion to manipulate votes in their favour, then that would be harmful to the site, and should definitely be considered, but it seems improbable.
950,136
I'm new to JQuery. I have a ``` <div id='field1'> </div> ``` I'm referring to it twice in my code. But at each time it refers to the same 1st reference. E.g. I'm changing the `DIV` content initially with the value ``` $("#field1").change(function (){alert('hi')}); ``` After some piece of code inside one another click function I'm having ``` $("#field1").change(function(){alert('again')}); ``` When I want to make use of the second change function with some other content, the first change function is called. How can I stop the first change being called and only the second one to be called? But this second one refers to the first one. How can i rectify this? I've even used `$(this)` in my second change. [Same Ajax called twice..JQuery](https://stackoverflow.com/questions/950037/same-ajax-called-twice-jquery)
2009/06/04
[ "https://Stackoverflow.com/questions/950136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/79980/" ]
If you mean you have two DIVs with the same ID, that's actually invalid HTML. IDs should be unique per-document.
I think jQuery when using ID's, only ever returns one element. If you must use the same selector name (which as Rytmis correctly stated, using multiple ID's with the same name is invalid HTML), then changing to a class selector would be best. You can then use the **:eq()** functionality in jQuery To target your first div you could use: ``` jQuery('.field:eq(0)') ``` and then to target your second div use: ``` jQuery('.field:eq(1)') ``` Remember they come back as an array so 0 = first, 1 = second, etc...
47,789
When should you use generator expressions and when should you use list comprehensions in Python? ``` # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ```
2008/09/06
[ "https://Stackoverflow.com/questions/47789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
[John's answer](https://stackoverflow.com/a/47792/4518341) is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: ``` def gen(): return (something for something in get_some_stuff()) print gen()[:2] # generators don't support indexing or slicing print [5,6] + gen() # generators can't be added to lists ``` Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension. Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.
Sometimes you can get away with the *tee* function from [itertools](https://docs.python.org/3/library/itertools.html), it returns multiple iterators for the same generator that can be used independently.
14,274,274
So I using access database(\*mdb). This my code and success to connect: ``` $db['test']['hostname'] = 'Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\blabla.mdb'; $db['test']['username'] = ''; $db['test']['password'] = ''; $db['test']['database'] = 'Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\blabla.mdb'; $db['test']['dbdriver'] = 'odbc'; $db['test']['dbprefix'] = ''; $db['test']['pconnect'] = TRUE; $db['test']['db_debug'] = TRUE; $db['test']['cache_on'] = FALSE; $db['test']['cachedir'] = ''; $db['test']['char_set'] = 'utf8'; $db['test']['dbcollat'] = 'utf8_general_ci'; $db['test']['swap_pre'] = ''; $db['test']['autoinit'] = TRUE; $db['test']['stricton'] = FALSE; ``` And now I want to using accessdb from other computer. This accessdb(\*mdb) has been shared and I make map network drive(Z:). So I was change hostname and database but its failed: ``` $db['test']['hostname'] = 'Driver={Microsoft Access Driver (*.mdb)};DBQ=Z:\blabla.mdb'; $db['test']['database'] = 'Driver={Microsoft Access Driver (*.mdb)};DBQ=Z:\blabla.mdb'; ``` And I try this to: ``` $db['test']['hostname'] = 'Driver={Microsoft Access Driver (*.mdb)};DBQ=\\10.0.0.107\share\blabla.mdb'; $db['test']['database'] = 'Driver={Microsoft Access Driver (*.mdb)};DBQ=\\10.0.0.107\share\blabla.mdb'; ``` But it still error: ``` Unable to connect to your database server using the provided settings. Filename: D:\folder\folder\system\database\DB_driver.php Line Number: 124 ``` and even i try to connect with php and this is the result [php using msaccess](https://stackoverflow.com/questions/14313154/php-using-msaccess)
2013/01/11
[ "https://Stackoverflow.com/questions/14274274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599703/" ]
I found this thread for a similar problem: <http://ellislab.com/forums/viewthread/93160/>. Says you should try loading loading the odbc driver manually from your controller: ``` $this->load->database(); $this->db->dbdriver = “odbc”; ``` It also says that for some reason the database config is not available in the odbc driver: > > system/database/drivers/odbc/odbc\_driver.php > > > So you may also have to go in there and load the database config manually.
Have you checked read/write access to that file? If your php app is running on IIS, then your IIS' user account will need to have read/write permissions to that file, not the user account you use to login to your computer.
128,405
> > **Possible Duplicate:** > > [Should deleted/closed questions count towards 6 questions in 24 hours rule?](https://meta.stackexchange.com/questions/113957/should-deleted-closed-questions-count-towards-6-questions-in-24-hours-rule) > > [6 questions per day including deleted questions?](https://meta.stackexchange.com/questions/125829/6-questions-per-day-including-deleted-questions) > > > I have posted 6 questions in past 24 hours, but have deleted one. Although currently, it doesn't count, and just thinks that 6 still have been asked. As far as I understand, question limit is introduced initially to prevent people "asking everything they have a question about". This constraint would encourage person asking to only submit good, really important questions. But in my case I've asked all that is important to me. Questions are considered by me to all be of a good quality. The one that was not - got removed immediately. The system should not think I've asked 6, and should take into consideration the removed question count on my opinion. What you think?
2012/04/06
[ "https://meta.stackexchange.com/questions/128405", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/175200/" ]
The limit is to prevent spamming the community with questions and not making progress independently. If we allowed deleted questions not to count **people could just delete the oldest one and continue in a loop**, effectively having no throttle at all. As soon as you got the answer you wanted, it'd encourage deletion of the question for those users. We don't want to encourage this, it wastes the community's time to some degree and creates many duplicates, annoying those living in whatever tags you're focusing on. That 6th question *should* count, you used the community's time looking at and answering it. Deleted questions are not our goal. Answering *your* question is not our direct goal either... answering a question others can find later and get benefit from, *that's* our goal. Deleting your questions once you're done with them, when they can help others later is explicitly discouraged.
This has been discussed before on numerous occasions. It doesn't matter whether you deleted a question or not. The value of StackOverflow is primarily for the entire community, and not for any one user. It is *highly* unlikely that you can research, compose, write examples for, and eventually maintain more than six valuable questions in one day. Perhaps the questions are important to *you* because you want a quick solution to a complicated design task (going by some of your past questions), but in the vast majority of cases, such rapid-fire questions are of little value to the site and the community.
98,503
One of my customers uses a Citrix server to allow their employees access to my MSACCESS application. I was curious about how I would go about hosting a Citrix server for some of my smaller customers who don't have IT departments. Any resources or thoughts are appreciated.
2009/12/31
[ "https://serverfault.com/questions/98503", "https://serverfault.com", "https://serverfault.com/users/30473/" ]
You could do a simple 2 server setup with a gateway at the edge with the Citrix Secure Ticketing running, then having a terminal server behind it servicing the app requests. Or, just go with a Citrix hosting solution, like [THIS.](http://www.redplaid.com/citrix_hosting.html)
Well depends on what you need, but for simple scenarios even vanilla remote desktop services can be enough.
573,274
Here is my code: ``` #define A 16777216.0 #define B 30.0 #define C 6990.51 #define D 1.0 #define Pulse_relation_ThetaAZ (A*B)/(360.0*C) #define StopFreqAZAUX (((D*1.0*Pulse_relation_ThetaAZ))/(D*1.0))*50.0+52 printf("%ld",StopFreqAZAUX); ``` This code be compiled by Keil but the value of StopFreqAZAUX is strange. what is my mistake? Edited: The value of StopFreqAZAUX is number between 100 to 500 with a float number for example 100.5, I convert to integer to remove floating part ( for example 100). But the value of StopFreqAZAUX is so high (for example 24\*e8 or ...)
2021/06/28
[ "https://electronics.stackexchange.com/questions/573274", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/269511/" ]
C is very much not strongly typed. When you say `printf("%ld", foo);`, you are telling the printf function "here is a mess of bits which you should *interpret as an integer*". You're telling the compiler "Make a string containing `%ld` and shove its address onto the stack. Then shove `foo` onto the stack. Then call printf." Nowhere in that chain is anything that independently tells printf function what type `foo` actually is. Under the hood, printf is defined something like `int printf(char * format, ...);` The `...` means you can stick anything on there (search on 'varargs' for more information). As pointed out, most modern compilers will see that you're using a known library function, they'll interpret the string and they'll flag you if `foo` is the wrong type. But (A) the compiler will usually just issue a warning, so if you're in the habit of ignoring warnings it won't help, and (B), *most* and *modern* leaves out quite a few compilers, especially ones targeting embedded systems.
The incorrect output of `printf` is expected. It is the result of a mismatch between the format-specifier `%ld` and the argument `StopFreqAZAUX`. After pre-processing, `StopFreqAZAUX` becomes a constant-literal of type `double`. However, the `%ld` format specifier tells `printf` to retrieve the argument as a `long signed int`. Thus the incorrect output. To fix it, use ``` printf ("%f", StopFreqAZAUX); ``` You may also cast explicitly ``` printf ("%f", (double) StopFreqAZAUX); ```
18,264,944
This may be a bug or just my bad coding. I've built a website using twitter bootstrap 2.3.\* and found no problem, especially for the responsive function. The problem came up when I tried to switch into bootstrap 3.RC-2 which was latest stable release (according to [Wikipedia](http://en.wikipedia.org/wiki/Twitter_Bootstrap)). I have also tried with the examples contained in the download, and had the same result when I tried to resize the viewport. Please have a look at <http://bootply.com/69863> for the example, and try to resize window browser then click render view, and try to expand menu and scroll the page. My real question is how do I make the fixed navbar static when in mobile (collapsible) view?
2013/08/16
[ "https://Stackoverflow.com/questions/18264944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1707829/" ]
Additionally to what Bass Jobsen has mentioned, for a better usability on mobile, the following CSS snippet removes the "sub-scrolling" on the navigation bar and removes the top margin which is there due to the large screen fixed navbar: ``` @media (max-width: 767px) { .navbar-fixed-top { position: relative; top: auto; } .navbar-collapse { max-height: none; } body { margin: 0; } } ```
For responsive and fixed navbar use this piece of code: ``` <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button"class="navbar-toggle collapsed" data-toggle="collapse" data-target="ID-name or class_name" aria-expanded="false"> <span class="sr-only">toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> ``` Then wrap your code under this div... ``` <div class="collapse navbar-collapse" id="ID name or class name"> ... </div> ``` **NOTE**- \*ID name or Class name should be same in both the places ``` For id= "# id_name" For className id=".class_name" ```
17,309,808
@H2CO3 this is my main code : ``` #pragma OPENCL EXTENSION cl_ amd_ printf : enable #define PROGRAM_FILE "matvec.cl" #define KERNEL_FUNC "matvec_mult" #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #ifdef MAC #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif int main() { cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; cl_int i,err; cl_int length = 512; cl_program program; FILE *program_handle; char *program_buffer; size_t program_size; cl_kernel kernel; size_t work_units_per_kernel; float mat_a[length], mat_b[length]; cl_mem mat_a_buff, mat_b_buff, res_buff; cl_event timing_event; cl_ulong time_start, time_end , read_time; //******************************************************************** // making matrix a & b for(i=0; i<length; i++) { mat_a[i] = i ; mat_b[i] = i +1; } //******************************************************************** clGetPlatformIDs(2, &platform, NULL); clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1 , &device, NULL); context = clCreateContext(NULL, 1, &device, NULL,NULL, &err); program_handle = fopen(PROGRAM_FILE, "r"); fseek(program_handle, 0, SEEK_END); program_size = ftell(program_handle); rewind(program_handle); program_buffer = (char*)malloc(program_size + 1); program_buffer[program_size] = '\0'; //******************************************************************* // !!!!!!!!! reading buffer : fread(program_buffer, sizeof(char), program_size,program_handle); //******************************************************************* fclose(program_handle); program = clCreateProgramWithSource(context, 1,(const char**)&program_buffer,&program_size,&err); free(program_buffer); clBuildProgram(program, 0 , NULL , NULL , NULL , NULL); // !!! Creating & Queueing Kernel : //********************************************************************************* kernel = clCreateKernel(program , KERNEL_FUNC , &err); queue = clCreateCommandQueue(context, device , CL_QUEUE_PROFILING_ENABLE , &err); //********************************************************************************* mat_a_buff = clCreateBuffer(context, CL_MEM_READ_ONLY |CL_MEM_COPY_HOST_PTR, sizeof(float)*4, mat_a, &err); mat_b_buff = clCreateBuffer(context, CL_MEM_READ_ONLY |CL_MEM_COPY_HOST_PTR, sizeof(float)*4 , mat_b, &err); res_buff = clCreateBuffer(context, CL_MEM_WRITE_ONLY,sizeof(float)*4, NULL, &err); // !!! Setting Kernel Arguments : clSetKernelArg(kernel, 0, sizeof(cl_mem), &mat_a_buff); clSetKernelArg(kernel, 0, sizeof(cl_mem), &mat_b_buff); clSetKernelArg(kernel, 1, sizeof(cl_mem), &res_buff); work_units_per_kernel = 512; // !!! Parallelism with clEnqueueNDRangekernel structure //********************************************************************************************** clEnqueueNDRangeKernel(queue, kernel, 1, NULL,&work_units_per_kernel, NULL, 0, NULL, &timing_event); //********************************************************************************************** //******************** Profilling : ***************************** clGetEventProfilingInfo(timing_event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL); clGetEventProfilingInfo(timing_event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL); read_time = time_end - time_start; printf("The average time is : %lu\n", read_time); //********************************************************************************************* clReleaseMemObject(mat_a_buff); clReleaseMemObject(mat_b_buff); clReleaseMemObject(res_buff); clReleaseKernel(kernel); clReleaseCommandQueue(queue); clReleaseProgram(program); clReleaseContext(context); return 0; } ``` but although the cl\_ulong is the unsigned long , the printf with %lu flag does not act . this is the error code line : (format %lu expects argument of type long unsigned int but argument 2 has type cl\_ulong[-Wformat]) so i don't know what is the problem and why printf does't work properly ???
2013/06/26
[ "https://Stackoverflow.com/questions/17309808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2125747/" ]
On the cl\_platform.h header installed on my machine, i found that cl\_ulong is define as: ``` typedef uint64_t cl_ulong; ``` So I guess you could try to printf as suggested [here](https://stackoverflow.com/questions/9225567/how-to-print-a-int64-t-type-in-c). BTW, I don't know if you use the pragma for something else in your code, but the printf you are using here is the regular C one since it is the host side code. So no need for the pragma in this specific case. Moreover since OpenCL 1.2, the printf is part of the built-in functions making obsolete the extension from AMD and therefore the pragma statement.
As one of the other answers mentioned, the [sizes of OpenCL scalar data types](https://www.khronos.org/registry/OpenCL/sdk/1.2/docs/man/xhtml/scalarDataTypes.html) are a constant number of bits: ``` DATA TYPE | BITS =========================== cl_char / cl_uchar | 8 cl_short / cl_ushort | 16 cl_int / cl_uint | 32 cl_long / cl_ulong | 64 ``` However, since you [can't assume the size of a `long`](https://stackoverflow.com/a/35844670/477563) on a given system, using `%llu` or `%lu` would be **incorrect**. --- That said, C and C++ have the [`inttypes.h` header](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/inttypes.h.html), which defines macros for printing fixed-sized integer values. The *printing* macros are in the form **`PRI[format][size]`**: * **`[format]`** is one of: `d` - signed, `u` - unsigned, `o` - octal, `x` - hex * **`[size]`** is the integer size in bits (`8`, `16`, `32`, or `64`) For example: `PRIu64` is used to print a 64-bit unsigned integer and `PRIx32` is used to print a 32-bit integer in hex. **Note:** These macros only define the "specifier" section of a `printf` variable, not the `%` marker. When you use them in a program, it needs to look like `printf("X = %" PRIu32 "\n", x);` --- Putting the above together, we end up with the following: ``` DATA TYPE | FORMAT =================== cl_char | PRId8 cl_uchar | PRIu8 cl_short | PRId16 cl_ushort | PRIu16 cl_int | PRId32 cl_uint | PRIu32 cl_long | PRId64 cl_ulong | PRIu64 ``` Of course, if you'd rather print the integer in octal you would use `o` instead of `d` or `u`. Likewise, if you wanted the integer in hex, you would use `x` instead.
28,192,426
so my codes are: ``` <?php $date2=date('Y', strtotime('+1 Years')); for($i=date('Y'); $i<$date2+5;$i++){ echo '<option>'.$i.'-'.$date2.'</option>'; } ?> ``` the output is ``` 2015-2016 2016-2016 2017-2016 2018-2016 2019-2016 ``` I want the output goes like this: ``` 2015-2016 2016-2017 2017-2018 2018-2019 2019-2020 ``` Any ideas? And i'm trying to put it on a dropbox then save it to my database.
2015/01/28
[ "https://Stackoverflow.com/questions/28192426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4041288/" ]
Change your code following way- ``` <?php $date2=date('Y', strtotime('+1 Years')); for($i=date('Y'); $i<$date2+5;$i++){ echo '<option>'.$i.'-'.($i+1).'</option>'; } ?> ```
This worked really well for me. ```php $years = range('2015', date('Y'), 1); foreach($years as &$year) { $year = $year . '-' . ($year + 1); } ``` This outputs an array of years from the set year until the current year.
67,472,625
I have images that need to be cropped to perfect passport size photos. I have thousands of images that need to be cropped and straightened automatically like this. If the image is too blur and not able to crop I need it to be copied to the rejected folder. I tried to do using haar cascade but this approach is giving me only face. But I need a face with a photo-cropped background. Can anyone tell me how I can code this in OpenCV or any? ``` gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faceCascade = cv2.CascadeClassifier( cv2.data.haarcascades + "haarcascade_frontalface_default.xml") faces = faceCascade.detectMultiScale( gray, scaleFactor=1.3, minNeighbors=3, minSize=(30, 30) ) if(len(faces) == 1): for (x, y, w, h) in faces: if(x-w < 100 and y-h < 100): ystart = int(y-y*int(y1)/100) xstart = int(x-x*int(x1)/100) yend = int(h+h*int(y1)/100) xend = int(w+w*int(y2)/100) roi_color = img[ystart:y + yend, xstart:x + xend] cv2.imwrite(path, roi_color) else: rejectedCount += 1 cv2.imwrite(path, img) ``` **Before** [![enter image description here](https://i.stack.imgur.com/t4ETP.jpg)](https://i.stack.imgur.com/t4ETP.jpg) [![enter image description here](https://i.stack.imgur.com/Zh8QV.jpg)](https://i.stack.imgur.com/Zh8QV.jpg) [![enter image description here](https://i.stack.imgur.com/q2kKu.jpg)](https://i.stack.imgur.com/q2kKu.jpg) **After** [![enter image description here](https://i.stack.imgur.com/urngO.jpg)](https://i.stack.imgur.com/urngO.jpg) [![enter image description here](https://i.stack.imgur.com/qS1q4.jpg)](https://i.stack.imgur.com/qS1q4.jpg) [![enter image description here](https://i.stack.imgur.com/xTvgs.png)](https://i.stack.imgur.com/xTvgs.png)
2021/05/10
[ "https://Stackoverflow.com/questions/67472625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10496449/" ]
Here is one way to extract the photo in Python/OpenCV by keying on the black lines surrounding the image. Input: [![enter image description here](https://i.stack.imgur.com/ocZ0f.jpg)](https://i.stack.imgur.com/ocZ0f.jpg) ``` - Read the input - Pad the image with white so that the lines can be extended until intersection - Threshold on black to extract the lines - Apply morphology close to try to connect the lines somewhat - Get the contours and filter on area drawing the contours on a black background - Apply morphology close again to fill the line centers - Skeletonize to thin the lines - Get the Hough lines and draw them as white on a black background - Floodfill the center of the rectangle of lines to fill with mid-gray. Then convert that image to binary so that the gray becomes white and all else is black. - Get the coordinates of all non-black pixels and then from the coordinates get the rotated rectangle. - Use the angle and center of the rotated rectangle to unrotated both the padded image and this mask image via an Affine warp - (Alternately, get the four corners of the rotated rectangle from the mask and then project that to the padded input domain using the affine matrix) - Get the coordinates of all non-black pixels in the unrotated mask and compute its rotated rectangle. - Get the bounding box of the (un-)rotated rectangle - Use those bounds to crop the padded image - Save the results import cv2 import numpy as np import math from skimage.morphology import skeletonize # read image img = cv2.imread('passport.jpg') ht, wd = img.shape[:2] # pad image with white by 20% on all sides padpct = 20 xpad = int(wd*padpct/100) ypad = int(ht*padpct/100) imgpad = cv2.copyMakeBorder(img, ypad, ypad, xpad, xpad, borderType=cv2.BORDER_CONSTANT, value=(255,255,255)) ht2, wd2 = imgpad.shape[:2] # threshold on black low = (0,0,0) high = (20,20,20) # threshold thresh = cv2.inRange(imgpad, low, high) # apply morphology to connect the white lines kernel = np.ones((5,5), np.uint8) morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel) # get contours contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = contours[0] if len(contours) == 2 else contours[1] # filter on area mask = np.zeros((ht2,wd2), dtype=np.uint8) for cntr in contours: area = cv2.contourArea(cntr) if area > 20: cv2.drawContours(mask, [cntr], 0, 255, 1) # apply morphology to connect the white lines and divide by 255 to make image in range 0 to 1 kernel = np.ones((5,5), np.uint8) bmask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)/255 # apply thinning (skeletonizing) skeleton = skeletonize(bmask) skeleton = (255*skeleton).clip(0,255).astype(np.uint8) # get hough lines line_img = np.zeros_like(imgpad, dtype=np.uint8) lines= cv2.HoughLines(skeleton, 1, math.pi/180.0, 90, np.array([]), 0, 0) a,b,c = lines.shape for i in range(a): rho = lines[i][0][0] theta = lines[i][0][1] a = math.cos(theta) b = math.sin(theta) x0, y0 = a*rho, b*rho pt1 = ( int(x0+1000*(-b)), int(y0+1000*(a)) ) pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) ) cv2.line(line_img, pt1, pt2, (255, 255, 255), 1) # floodfill with mid-gray (128) xcent = int(wd2/2) ycent = int(ht2/2) ffmask = np.zeros((ht2+2, wd2+2), np.uint8) mask2 = line_img.copy() mask2 = cv2.floodFill(mask2, ffmask, (xcent,ycent), (128,128,128))[1] # convert mask2 to binary mask2[mask2 != 128] = 0 mask2[mask2 == 128] = 255 mask2 = mask2[:,:,0] # get coordinates of all non-zero pixels # NOTE: must transpose since numpy coords are y,x and opencv uses x,y coords = np.column_stack(np.where(mask2.transpose() > 0)) # get rotated rectangle from coords rotrect = cv2.minAreaRect(coords) (center), (width,height), angle = rotrect # from https://www.pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python/ # the `cv2.minAreaRect` function returns values in the # range [-90, 0); as the rectangle rotates clockwise the # returned angle trends to 0 -- in this special case we # need to add 90 degrees to the angle if angle < -45: angle = -(90 + angle) # otherwise, just take the inverse of the angle to make # it positive else: angle = -angle # compute correction rotation rotation = -angle - 90 # compute rotation affine matrix M = cv2.getRotationMatrix2D(center, rotation, scale=1.0) # unrotate imgpad and mask2 using affine warp rot_img = cv2.warpAffine(imgpad, M, (wd2, ht2), flags=cv2.INTER_CUBIC, borderValue=(0,0,0)) rot_mask2= cv2.warpAffine(mask2, M, (wd2, ht2), flags=cv2.INTER_CUBIC, borderValue=(0,0,0)) # get coordinates of all non-zero pixels # NOTE: must transpose since numpy coords are y,x and opencv uses x,y coords2 = np.column_stack(np.where(rot_mask2.transpose() > 0)) # get bounding box x,y,w,h = cv2.boundingRect(coords2) print(x,y,w,h) # crop rot_img result = rot_img[y:y+h, x:x+w] # save resulting images cv2.imwrite('passport_pad.jpg',imgpad) cv2.imwrite('passport_thresh.jpg',thresh) cv2.imwrite('passport_morph.jpg',morph) cv2.imwrite('passport_mask.jpg',mask) cv2.imwrite('passport_skeleton.jpg',skeleton) cv2.imwrite('passport_line_img.jpg',line_img) cv2.imwrite('passport_mask2.jpg',mask2) cv2.imwrite('passport_rot_img.jpg',rot_img) cv2.imwrite('passport_rot_mask2.jpg',rot_mask2) cv2.imwrite('passport_result.jpg',result) # show thresh and result cv2.imshow("imgpad", imgpad) cv2.imshow("thresh", thresh) cv2.imshow("morph", morph) cv2.imshow("mask", mask) cv2.imshow("skeleton", skeleton) cv2.imshow("line_img", line_img) cv2.imshow("mask2", mask2) cv2.imshow("rot_img", rot_img) cv2.imshow("rot_mask2", rot_mask2) cv2.imshow("result", result) cv2.waitKey(0) cv2.destroyAllWindows() ``` Padded Image: [![enter image description here](https://i.stack.imgur.com/evdWK.jpg)](https://i.stack.imgur.com/evdWK.jpg) Threshold Image: [![enter image description here](https://i.stack.imgur.com/1brwe.jpg)](https://i.stack.imgur.com/1brwe.jpg) Morphology cleaned Image: [![enter image description here](https://i.stack.imgur.com/3cpkH.jpg)](https://i.stack.imgur.com/3cpkH.jpg) Mask1 Image: [![enter image description here](https://i.stack.imgur.com/MGXtB.jpg)](https://i.stack.imgur.com/MGXtB.jpg) Skeleton Image: [![enter image description here](https://i.stack.imgur.com/8yp88.jpg)](https://i.stack.imgur.com/8yp88.jpg) (Hough) Line Image: [![enter image description here](https://i.stack.imgur.com/tKxgP.jpg)](https://i.stack.imgur.com/tKxgP.jpg) Floodfilled Line Image - Mask2: [![enter image description here](https://i.stack.imgur.com/cCZ7N.jpg)](https://i.stack.imgur.com/cCZ7N.jpg) Unrotated Padded Image: [![enter image description here](https://i.stack.imgur.com/LdvXs.jpg)](https://i.stack.imgur.com/LdvXs.jpg) Unrotated Mask2 Image: [![enter image description here](https://i.stack.imgur.com/zFXBT.jpg)](https://i.stack.imgur.com/zFXBT.jpg) Cropped Image: [![enter image description here](https://i.stack.imgur.com/526o3.jpg)](https://i.stack.imgur.com/526o3.jpg)
### The Concept 1. Process each image to enhance the edges of the photos. 2. Get the 4 corners of the photo of each processed image by first finding the contour with the greatest area, getting its convex hull and approximating the convex hull until only 4 points are left. 3. Warp each image according to the 4 corners detected. ### The Code ``` import cv2 import numpy as np def process(img): img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_blur = cv2.GaussianBlur(img_gray, (1, 1), 1) img_canny = cv2.Canny(img_blur, 350, 150) kernel = np.ones((3, 3)) img_dilate = cv2.dilate(img_canny, kernel, iterations=2) return cv2.erode(img_dilate, kernel, iterations=1) def get_pts(img): contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cnt = max(contours, key=cv2.contourArea) peri = cv2.arcLength(cnt, True) return cv2.approxPolyDP(cv2.convexHull(cnt), 0.04 * peri, True) files = ["1.jpg", "2.jpg", "3.jpg"] width, height = 350, 450 pts2 = np.float32([[width, 0], [0, 0], [width, height], [0, height]]) for file in files: img = cv2.imread(file) pts1 = get_pts(process(img)).squeeze() pts1 = np.float32(pts1[np.lexsort(pts1.T)]) matrix = cv2.getPerspectiveTransform(pts1, pts2) out = cv2.warpPerspective(img, matrix, (width, height))[5:-5, 5:-5] cv2.imshow(file, out) cv2.waitKey(0) cv2.destroyAllWindows() ``` ### The Output I placed each output next to each others to fit in one image: [![enter image description here](https://i.stack.imgur.com/RV0m6.jpg)](https://i.stack.imgur.com/RV0m6.jpg) ### The Explanation 1. Import the necessary libraries: ``` import cv2 import numpy as np ``` 2. Define a function, `process()`, that takes in a BGR image array and returns the image processed with the [Canny edge detector](https://docs.opencv.org/3.4/da/d22/tutorial_py_canny.html) for more accurate detection of the edges of each photo later. The values used in the function can be tweaked to be more suitable for other images if needed: ``` def process(img): img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_blur = cv2.GaussianBlur(img_gray, (1, 1), 1) img_canny = cv2.Canny(img_blur, 350, 150) kernel = np.ones((3, 3)) img_dilate = cv2.dilate(img_canny, kernel, iterations=2) return cv2.erode(img_dilate, kernel, iterations=1) ``` 3. Define a function, `get_pts()`, that takes in a processed image and returns 4 points of the convex hull of the contour with the greatest area. In order to get 4 points out of the convex hull, we use the [`cv2.approxPolyDP()`](https://docs.opencv.org/3.4/d3/dc0/group__imgproc__shape.html#ga0012a5fdaea70b8a9970165d98722b4c) method: ``` def get_pts(img): contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cnt = max(contours, key=cv2.contourArea) peri = cv2.arcLength(cnt, True) return cv2.approxPolyDP(cv2.convexHull(cnt), 0.04 * peri, True) ``` 4. Define a list, `files` containing the names of each file you want to extract the photos from, and the dimensions you want the resulting images to be, `width` and `height`: ``` files = ["1.jpg", "2.jpg", "3.jpg"] width, height = 350, 450 ``` 5. Using the dimensions defined above, define a matrix for each of the 4 soon-to-be detected coordinated to be mapped to: ``` pts2 = np.float32([[width, 0], [0, 0], [width, height], [0, height]]) ``` 6. Loop through each filename, read each the file into a BGR image array, get the 4 points of the photo within the image, use the [`cv2.getPerspectiveTransform()`](https://docs.opencv.org/4.5.2/da/d54/group__imgproc__transform.html#ga20f62aa3235d869c9956436c870893ae) method to get the solution matrix for the warping, and finally warp the photo portion of the image with the solution matrices using the [cv2.warpPerspective()](https://docs.opencv.org/4.5.2/da/d54/group__imgproc__transform.html#gaf73673a7e8e18ec6963e3774e6a94b87) method: ``` for file in files: img = cv2.imread(file) pts1 = get_pts(process(img)).squeeze() pts1 = np.float32(pts1[np.lexsort(pts1.T)]) matrix = cv2.getPerspectiveTransform(pts1, pts2) out = cv2.warpPerspective(img, matrix, (width, height))[5:-5, 5:-5] cv2.imshow(file, out) ``` 7. Finally, add a delay and after that destroy all the windows: ``` cv2.waitKey(0) cv2.destroyAllWindows() ```
19,751
My provider told me that they cannot give us a separate IP address for a separate website. I understand that they could give us one where an existing address absolutely cannot be reused, like if we had a second virtual server, or required SSL. Having browsed around, it seems that this isn't really up to them, and is imposed "from above", leading me to wonder if this applies to all hosts in the US. If this is not so, please could you recommend a good webhost with servers in the US which are happy to issue several IP addresses without requiring extra virtual servers? P.S. I *could* get a separate virtual server for this, but that seems daft. It doesn't save any IP addresses whatsoever, and only wastes extra electricity in the process...
2011/09/16
[ "https://webmasters.stackexchange.com/questions/19751", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/5119/" ]
[Hostgator's policy on IPs](http://support.hostgator.com/articles/pre-sales-policies/can-i-get-unlimited-dedicated-ips) is: > > Due to the global shortage of IPv4 addresses, although there is no > limit on the number you may have, we are now required to request > justification for dedicated IP address requests. > > > With the exception of the Business hosting package, the only > acceptable justification for a dedicated IP address on any account > type that we can accept at this time is for use with an SSL > certificate. > > > (And their business package only allows for one unjustified IP anyway). Despite their use of the word *required*, I really doubt they were *forced* (by, say, ARIN) to ration IP addresses to any specific user, it's just a business decision. Most hosting companies are allocated fixed-size blocks of [IPv4](http://en.wikipedia.org/wiki/IPv4#Address_space_exhaustion)s, and when those run out, they can't get any more (until [IPv6](http://en.wikipedia.org/wiki/Ipv6), anyway). Like it or not, **[IPv4](http://en.wikipedia.org/wiki/IPv4#Address_space_exhaustion)s are now a scarce resource**, and companies are charging accordingly. It may cost more than you want to pay, but that's business, sorry...
Contray to what @Bruce Harris & @Cyclops suggest, there are policies in place limiting companies in how they use and allocate to its users IPv4 addresses. As of February, IANA has no more /8 IP pool to allocate to regional RIR, and as of April for the Asia Pacific region APNIC has run out of freely allocated IPs, with RIPE NCC (Europe, Middle East & part of Central Asia) being expected to run out next. In the case of American (US, Canada & Caribbean), ARIN tightened how much and how often an ISP can request new IPs when IANA ran out, and also enforced more stringent reviews to ensure efficient utilization. The effect of this are passed down to hosting companies and in turn end users. Any companies who in this day and age freely assign dedicated IP without good reason will simply find it impossible to request more from their ISP/RIR when they run out even if their respective ISP/RIR still has some left. Do you really want to be with a company who can't get you additional IP even if you really need it (for SSL say) because they've given all their allocation away freely and as a result are denied any new ones?
29,385,648
I keep getting '$scope is not defined' console errors for this controller code in AngularJS: ``` angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles', function($scope, $routeParams, $location, Authentication, Articles){ $scope.authentication = Authentication; } ]); $scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE var article = new Articles({ title: this.title, content: this.content }); article.$save(function(response) { $location.path('articles/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; ``` Where in my AngularJS MVC files should I be looking at to find problems with the $scope not being defined properly?
2015/04/01
[ "https://Stackoverflow.com/questions/29385648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/743623/" ]
For others who land here from Google, you'll get this error if you forget the quotes around `$scope` when you're annotating the function for minification. Error ----- ``` app.controller('myCtrl', [$scope, function($scope) { ... }]); ``` Happy Angular ------------- ``` app.controller('myCtrl', ['$scope', function($scope) { ... }]); ```
Check scope variable declared after controller defined. Eg: ``` var app = angular.module('myApp',''); app.controller('customersCtrl', function($scope, $http) { //define scope variable here. }); ``` Check defined range of controller in view page. Eg: ``` <div ng-controller="mycontroller"> //scope variable used inside these blocks <div> ```
7,186,282
When I SELECT a Geometry column with `AsText()`, the returned value is truncated to 8193 bytes. This looks like a bug to me, but I'd like to post here first to see if I'm missing anything with the way prepared statements work under MySQLi. Are there any settings I'm overlooking here? Chances are I either I'm Doing It Wrong, or there is a setting I don't know about. All test cases below except the first truncate the `geom` field to 8193 bytes. I'm pulling my hair out trying to determine the cause of this. PHP Version: `PHP 5.3.3-7 with Suhosin-Patch (cli) (built: Jan 5 2011 12:52:48)` MySQL Version: `mysql Ver 14.12 Distrib 5.0.32, for pc-linux-gnu (i486) using readline 5.2` ```php <?php $con = new mysqli(HOST, USER, PASS, DB); $con->query("DROP TABLE IF EXISTS `mytable`"); $con->query("CREATE TABLE `mytable` (`text` TEXT , `geom` GEOMETRY)"); for ($i = 0; $i < 1300; ++$i) { $points[] = "$i $i"; } $wkt = "LINESTRING(" . implode(',', $points) . ")"; $con->query("INSERT INTO `mytable` (`text`,`geom`) VALUES ('$wkt', GeomFromText('$wkt'))"); /* CASE #1 */ echo "With store_result(), no string function on `text`:\n"; $stmt = $con->prepare('SELECT `text`, ASTEXT(`geom`) FROM `mytable`'); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($text, $geom); $stmt->fetch(); $stmt->close(); echo " Text is ".strlen($text)." bytes, Geom is ".strlen($geom)." bytes\n"; unset($text); unset($geom); /* CASE #2 */ echo "With store_result(), left(`text`,10791):\n"; $stmt = $con->prepare('SELECT LEFT(`text`,10791), ASTEXT(`geom`) FROM `mytable`'); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($text, $geom); $stmt->fetch(); $stmt->close(); echo " Text is ".strlen($text)." bytes, Geom is ".strlen($geom)." bytes\n"; unset($text); unset($geom); /* CASE #3 */ echo "With store_result(), only the `geom` column:\n"; $stmt = $con->prepare('SELECT ASTEXT(`geom`) FROM `mytable`'); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($geom); $stmt->fetch(); $stmt->close(); echo " Text is ".@strlen($text)." bytes, Geom is ".strlen($geom)." bytes\n"; unset($text); unset($geom); /* CASE #4 */ echo "Without store_result(), no string function on `text`:\n"; $stmt = $con->prepare( 'SELECT `text`, ASTEXT(`geom`) FROM `mytable`'); $stmt->execute(); $stmt->bind_result($text, $geom); $stmt->fetch(); $stmt->close(); echo " Text is ".strlen($text)." bytes, Geom is ".strlen($geom)." bytes\n"; ?> ``` Expected Result: ``` With store_result(), no string function on `text`: Text is 10791 bytes, Geom is 10791 bytes With store_result(), left(`text`,10791): Text is 10791 bytes, Geom is 10791 bytes With store_result(), only the `geom` column: Text is 0 bytes, Geom is 10791 bytes Without store_result(), no string function on `text`: Text is 10791 bytes, Geom is 10791 bytes ``` Here is my actual result when running the above: ``` With store_result(), no string function on `text`: Text is 10791 bytes, Geom is 10791 bytes With store_result(), left(`text`,10791): Text is 10791 bytes, Geom is 8193 bytes With store_result(), only the `geom` column: Text is 0 bytes, Geom is 8193 bytes Without store_result(), no string function on `text`: Text is 10791 bytes, Geom is 8193 bytes ```
2011/08/25
[ "https://Stackoverflow.com/questions/7186282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9867/" ]
It's probably because **$stmt** is not getting un/reset like the other values. It's always returns consistent data when you call it the first time ;)
This issue went away when PHP was upgraded to 5.3.8.
541,504
**How i solved it:** all possible non-distinct groups $(a,b,c)$ are, $a = 0 \Rightarrow (b,c) = (0,13)(1,12)(2,11)(3,10)(4,9)(5,8)(6,7)$ $a = 1 \Rightarrow (b,c) = (1,11)(2,10)(3,9)(4,8)(5,7)(6,6)$ $a = 2 \Rightarrow (b,c) = (2,9)(3,8)(4,7)(5,6)$ $a = 3 \Rightarrow (b,c) = (3,7)(4,6)(5,5)$ $a = 4 \Rightarrow (b,c) = (4,5)$ Thus, $7^{13}$ can be written as product of $3$ natural numbers in $7+6+4+3+1 = 21$ ways. Though this gives the required solution, it takes time and is a lengthy way. Is there an alternate method to tackle such problems? (May be by using the "bars and stars" method with some adjustments? I tried but failed to get the correct answer that way.) Please help me out and share your method! Thanks a lot!
2013/10/27
[ "https://math.stackexchange.com/questions/541504", "https://math.stackexchange.com", "https://math.stackexchange.com/users/103571/" ]
If you consider different orders equivalent, so that $7^87^37^2$ is considered the same as $7^27^37^8$, you are asking about the number of [partitions](http://en.wikipedia.org/wiki/Partition_%28number_theory%29) of $13$ into $3$ parts, while the stars-and-bars answers give you the number of [compositions](http://en.wikipedia.org/wiki/Composition_%28number_theory%29) of $13$ into $3$ parts. In the partition page, it states that the number of partitions of $n$ into $1,2,3$ parts is the nearest integer to $\frac {(n+3)^2}{12}$, here $21$. As you area are allowing $0$, which means you include $1$ or $2$ parts, that is your answer.
In this case, you are distributing 13 into a + b +c. This can be done by 15C2. But 15C2 i.e 105 will be considering 1 case more than one time because it will give you ordered pairs or solutions. So, you have to subtract redundant pairs. You cant do that by dividing it by 3! as every single pair is not present 6 times. For ex - (a,a,b) is present only 3 times. So remove all these cases and we will be left with only (a,b,c) pairs. (13C2 - 3\*7)/3! This will give you unordered pair of (a,b,c). Now add 7 pairs which we have removed from them. (13C2 - 3\*7)/3! + 7 = 21
171,357
I was looking at some VivaAerobús flight ticket and read that one may check in up to ten days prior to the flight departure: [![enter image description here](https://i.stack.imgur.com/88DGu.png)](https://i.stack.imgur.com/88DGu.png) (And the seat can be chosen when purchasing the ticket: "free regular seat selection" in the screenshot). What's the point of checking-in several days before a flight? --- **Closevoters**: the ability to check in early is part of the more expensive flight ticket option, therefore I wonder whether there exists some objective reason to check in early. It's not an opinion-based question.
2021/12/21
[ "https://travel.stackexchange.com/questions/171357", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/1810/" ]
One big one: Many airlines use time of check in as a tie-breaker when it comes to issuing upgrades or clearing stand by lists. Source: worked at an airline, and [quora](https://www.quora.com/Why-should-or-shouldnt-you-check-into-a-flight-early-as-in-online-24-hours-before-your-flight-leaves-Are-there-any-real-reasons-to-do-it-Any-downsides).
For me it's good because I can check-in while I'm thinking about it. It's just a bit more convenient and gets it out of the way.
17,038,558
when i am using `#define` function,I observe something bizarre. In the below code if I gave `i` value as `'10'` from input `i` got the output as `132`. However if I declare `i=10` by commenting 10,12 and 13 lines then my output is `144`. can anyone explain me how this is happening? thanks in advance ``` #include <iostream> using namespace std; #define Double(X) X*X int main() { //int i=10; int i; cout<<"Enter the i values:" <<endl; cin>>i; cout<<"Values is:"<<Double(++i)<<endl; return 0; } ```
2013/06/11
[ "https://Stackoverflow.com/questions/17038558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2413497/" ]
What you have is undefined behaviour. You `Double(++i)` is changed to `++i * ++i`, when you compile you code.
Macro's have subtleties. What your macro does is: `Double(++i) -> ++i*++i` in your case 11\*12 or 12\*11
33,597,949
I'm using the Bandsintown api to grab upcoming concert dates based on which artists a user is following on my site and where the user is located. Right now I'm having trouble iterating over a multidimensional array of data that I get back as a response. **The Goal** To iterate through an array of arrays and then grab an artists' name to display it on my view. I'm able to grab the data I want with the following code inside my controller: ``` class CalendarController < ApplicationController require 'uri' def index @user = current_user @hash_version_array = [] @user.follows.each do |follow| response = HTTParty.get("http://api.bandsintown.com/artists/#{URI.escape(follow.artist_name)}/events/search.json?api_version=2.0&app_id=el_proyecto_de_la_musica&location=use_geoip") @hash_version = JSON.parse(response.body) @hash_version_array << @hash_version end @hash_version_array end def show end end ``` the code above produces the following results inside of my @hash\_version\_array (click [here](https://gist.github.com/jlquaccia/db6f0086cfa33aee9888) for the results, easier to show through a gist on github) I get stuck when trying to iterate over @hash\_version\_array to grab each artist's name. **Attempt 1** ``` [9] pry(#<CalendarController>)> @hash_version_array.each do |sub_array| [9] pry(#<CalendarController>)* sub_array.each do |artist| [9] pry(#<CalendarController>)* artist["artists"]["name"] [9] pry(#<CalendarController>)* end [9] pry(#<CalendarController>)* end ``` Results in ``` TypeError: no implicit conversion of String into Integer from (pry):96:in `[]' ``` **Attempt 2** ``` [8] pry(#<CalendarController>)> @hash_version_array.each do |sub_array| [8] pry(#<CalendarController>)* sub_array.each do |artist| [8] pry(#<CalendarController>)* artist["artists"].each do |artist| [8] pry(#<CalendarController>)* artist["name"] [8] pry(#<CalendarController>)* end [8] pry(#<CalendarController>)* end [8] pry(#<CalendarController>)* end ``` Results in the same value I got for @hash\_version\_array to begin with
2015/11/08
[ "https://Stackoverflow.com/questions/33597949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3534558/" ]
You can dynamically add new asp:image objects to the form1. ``` Image img = new Image(); img.ImageUrl = dr["Image_Path"].ToString(); img.AlternateText = "Test image"; form1.Controls.Add(img); ```
The problem is in this statement: ``` Image.ImageUrl = Convert.ToString(dr["Image_Path"]); ``` What does this statement do? It assigns **each** `image path` value to **only one** `Image.ImageUrl`. So, the `Image.ImageUrl` will hold the last assigned `image path`. The result is only one picture will be displayed. This is **not** what you want. What you want is: show all pictures --> assign **each** `image path` to **each** `Image.ImageUrl` --> **dynamically create the `Image` and add it to the form**. So, instead of writing that statement, you should do something like: ``` Image img = new Image(); img.ImageUrl = dr["Image_Path"].ToString(); img.AlternateText = "Test image"; form1.Controls.Add(img); ``` The code is **not tested**. Just focus on the idea. You can do it like this, or use the `repeater`, or your own way, it's up to you. Feel free to ask me if you find something unclear :)
59,074,948
I write a programe in JavaScript where I want to add file "tables.js". There are many tables saved in this file.I want to validate the data in each table. How can I save each of these tables as a separate variable? var people = ...; var city = ... Part of tables.js file below. ``` { people: [{ id: 1, name: 'Bob', lastName: 'Asdfg' }, { id: 2, name: 'Carl', lastName: 'Qwerty' }], city: [{ id: 1, name: 'Prague', size: 'M', continent:'Europe' }, { id: 1, name: 'London', size: 'XL', continent:'Europe' }] } ``` I have tried `JSON.parse` so far but unfortunately I can't split this file into separate tables.
2019/11/27
[ "https://Stackoverflow.com/questions/59074948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12447160/" ]
I had the same issue. I had follow the instructions to change the default machine folder to the same path as the one set for environment variable for VAGRANT\_HOME Open VirtualBox Go to File -> Preferences In the General tab, change the Default Machine Folder path to an existing path. Run vagrant up again
you can check PATH below,if has blank or special character, change it. 1. Vagrant install PATH 2. VirtualBox install PATH 3. $VAGRANT\_HOME PATH 4. VirtualBox default Virtual Machine location PATH Also, free enough space $VAGRANT\_HOME and VirtualBox default Virtual Machine location
9,746,683
As the title suggests, I'm having trouble understanding exactly what a pointer is and why they're used. I've searched around a bit but still don't really understand. I'm working in Objective-C mainly, but from what I've read this is really more of a C topic (so I added both tags). From what I understand, a variable with an asterisks in front points to an address in memory? I don't quite understand why you'd use a pointer to a value instead of just using the value itself. For example: ``` NSString *stringVar = @"This is a test."; ``` When calling methods on this string, why is it a pointer instead of just using the string directly? Why wouldn't you use pointers to integers and other basic data types? Somewhat off topic, but did I tag this correctly? As I was writing it I thought that it was more of a programming concept rather than something language specific but it does focus specifically on Objective-C so I tagged it with objective-c and c.
2012/03/17
[ "https://Stackoverflow.com/questions/9746683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1004162/" ]
> > I don't quite understand why you'd use a pointer to a value instead of > just using the value itself. > > > You use a pointer when you want to refer to a specific instance of a value instead of a copy of that value. Say you want me to double some value. You've got two options: * You can tell me *what* the value is: "5": "Please double 5 for me." That's called passing *by value*. I can tell you that the answer is 10, but if you had 5 written down somewhere that 5 will still be there. Anyone else who refers to that paper will still see the 5. * You can tell me *where* the value is: "Please erase the number I've written down here and write twice that number in its place." That's called passing *by reference*. When I'm done, the original 5 is gone and there's a 10 in its place. Anyone else who refers to that paper will now see 10. Pointers are used to *refer to* some piece of memory rather than *copying* some piece of memory. When you pass by reference, you pass a pointer to the memory that you're talking about. > > When calling methods on this string, why is it a pointer instead of just using the string directly? > > > In Objective-C, we *always* use pointers to refer to objects. The technical reason for that is that objects are usually allocated dynamically in the heap, so in order to deal with one you need it's address. A more practical way to think about it is that an object, by definition, is a *particular instance* of some class. If you pass an object to some method, and that method modifies the object, then you'd expect the object you passed in to be changed afterward, and to do that we need to pass the object by reference rather than by value. > > Why wouldn't you use pointers to integers and other basic data types? > > > Sometimes we *do* use pointers to integers and other basic data types. In general, though, we pass those types by value because it's faster. If I want to convey some small piece of data to you, it's faster for me to just give you the data directly than it is to tell you where you can find the information. If the data is large, though, the opposite is true: it's much faster for me to tell you that there's a dictionary in the living room than it is for me to recite the contents of the dictionary.
> > > > `NSString *stringVar = @"This is a test.";` > > > When calling methods on this string, why is it a pointer instead of just using the string directly? > This is a fairly existential question. I would posit it this way: what ***is*** the string if not its location? How would you implement a system if you can't refer to objects somehow? By name, sure... But what is that name? How does the machine understand it? The CPU has instructions that work with operands. "Add x to y and store the result here." Those operands can be registers (say, for a 32-bit integer, like that `i` in the proverbial `for` loop might be stored), but those are limited in number. I probably don't need to convince you that some form of memory is needed. I would then argue, how do you tell the CPU where to find those things in memory if not for pointers? > You: "Add x to y and store it in memory." > > CPU: OK. Where? > > You: Uh, I dunno, like, where ever ... At the lowest levels, it doesn't work like this last line. You need to be a bit more specific for the CPU to work. :-) So really, all the pointer does is say "the string at X", where X is an integer. Because in order to do something you need to know where you're working. In the same way that when you have an array of integers `a`, and you need to take `a[i]`, `i` is meaningful to you somehow. How is that meaningful? Well it depends on your program. But you can't argue that this `i` shouldn't exist. In reality in those other languages, you're working with pointers as well. You're just not aware of it. Some people would say that they prefer it that way. But ultimately, when you go down through all the layers of abstraction, you're going to need to tell the CPU what part of memory to look at. :-) So I would argue that pointers are necessary no matter what abstractions you end up building.
16,855,648
I have a question about how best to check if a service is still running. First a bit of clarification. The service I have is a C# application which can either be run from the command line or can be run as a Windows Service. The function of the service is to check for changes to a remote 3rd party data source and process those changes before adding them to our own local data store. I want to be able to identify when the service has stopped functioning for whatever reason, and notify somebody when this happens as automatically as possible. This needs to happen regardless of whether the service is being run as a Windows Service or from the command line. I have already considered monitoring the local data store for changes and notifying when changes haven't happened for a set amount of time, however this has proven to be a little too inconsistent, because the frequency of changes to the 3rd party data source is variable, which means that a prolonged lack of changes doesn't necessarily indicate that the service has stopped working, it could just be that there are no changes! Are there any suggestions about how I might go about monitoring this? Anyone got any experience working with something similar? Thanks, M **Edit 1** Just to give a rough idea of how the service works: The 3rd party service raises events when new/updated data is available so my service sits and waits for these events to be raised and processes the data returned in the raised event. Therefore this is why it's tricky to identify when there's "no changes" rather than "service crashed". **Edit 2** I think I need to be a little clearer: The main reason for this monitoring is to notify a user about a potential issue either with the service or with the connection to the 3rd party service. The service itself is single threaded and has proper exception handling and logging. Chances are this service is going to be run on a server somewhere so if there are any problems with the service and it stops updating our local data store for whatever reason the service needs to notify someone.
2013/05/31
[ "https://Stackoverflow.com/questions/16855648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422671/" ]
you might want to consider something like a 'heartbeat': [Heartbeat activity for Windows Service](https://stackoverflow.com/questions/9013737/heartbeat-activity-for-windows-service) But your main consideration should be working out why your service should be able to stop/hang? All exceptions need to be caught, and at the very worst case, reset your service to its start state after a short wait to prevent CPU maxing. Windows itself has a variety of methods to help also: ``` Start > Run > Services.msc > Right Click Service > Properties > Recovery Options ``` If you design your application to properly use exceptions and handle them appropriately, you shouldn't ever have a problem with your service 'hanging for some reason'. **Additional:** Is there no way for you do determine the difference between "no work required" and a hang?
you can use **ServiceController** class in .net to monitor services. I faced the same problem in one of my projects. I used the below approach to monitor the my service. * First thing, i logged all the informations,errors from my service to event viewer in a standard format like this **custom-eventid|datetime|message** * Then i created one more notification service which will listen to the event viewer for the particular events,reads the message from the event entry * if the event entry falls in the event viewer it will send mail notification through smtp * if you are not provided with the smpt then go for windows application which listen to the events and shows message using baloon or message box
24,013,974
I have written a stored procedure to check the how transaction working in stored procedure. Is this correct? How can I check this is correct or not? What I want to do is if second table data not deleted ; both the table data should not be delete. ``` CREATE PROCEDURE DeleteDepartment ( @DepartmentID int ) AS BEGIN TRANSACTION DELETE FROM Employees WHERE DepartmentID = @DepartmentID IF @@ERROR <> 0 BEGIN -- Rollback the transaction ROLLBACK -- Raise an error and return RAISERROR ('Error in deleting employees in DeleteDepartment.', 16, 1) RETURN END DELETE FROM Departments WHERE DepartmentID = @DepartmentID IF @@ERROR <> 0 BEGIN -- Rollback the transaction ROLLBACK -- Raise an error and return RAISERROR ('Error in deleting department in DeleteDepartment.', 16, 1) RETURN END COMMIT ```
2014/06/03
[ "https://Stackoverflow.com/questions/24013974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3230466/" ]
``` CREATE PROCEDURE DeleteDepartment ( @DepartmentID int ) AS BEGIN TRY BEGIN TRANSACTION DELETE FROM Employees WHERE DepartmentID = @DepartmentID --Test Code Start --For testing purpose Add an Insert statement with passing value in the identity column. declare @table1 as table(ID Identity(1,1),Test varchar(10)) insert into @table1(ID, Test) Values(1,'Failure Test') --Test Code end DELETE FROM Departments WHERE DepartmentID = @DepartmentID COMMIT TRANSACTION END TRY BEGIN CATCH ROLLBACK TRANSACTION RETURN ERROR_MESSAGE() END CATCH ``` First things first, `Commit transaction` appears ahead of `Rollback Transaction` And to test if the transactions work, what you can do is, try adding an `INSERT` statement in the query between 2 delete statements and try adding value for the identity column in it. So that the first delete is successful, but transaction fails. Now you can check if the first delete is reflected in the Table or not.
COMMIT is supposed to be before ROLLBACK. and i advice using try/catch blocks it should look like something like this ``` BEGIN TRY declare @errorNumber as int BEGIN TRANSACTION --do 1st statement IF @@ERROR<>0 BEGIN SET @errorNumber=1 END --do 2nd statement IF @@ERROR<>0 BEGIN SET @errorNumber=2 END COMMIT END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK END CATCH ```
68,889,663
I tried this code but it doesn't work. This is my Html code ``` <div class="left-container1"> <button class="ui button " value="right" id="answer1">yes</button> <button class="ui button " value="wrong" id="answer2">no</button></div> </div> <div class="navigation-controllers "> <button onclick="displayAnswer1()" class="ui button next " id="next" >next</button> </div> ``` and this my JavaScript code ``` var button1 = document.getElementById("answer1"); var button2 = document.getElementById("answer2"); function displayAnswer1() { if (button1.click == true){ location.href="./2_2.html"; }; if (button2.click == true){ location.href="./2_1.html"; } ; } ``` I want when I click the next button, it will redirect to the page based on the chosen "Yes" or "No" button. How to solve this issue?
2021/08/23
[ "https://Stackoverflow.com/questions/68889663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15172308/" ]
I am not an Redis expert but from what I can see: ``` kubectl describe pod red3-redis-master-0 ... Bad file format reading the append only file: make a backup of your AOF file, then use ./redis-check-aof --fix <filename> ... ``` Means that your appendonly.aof file was corrupted with invalid byte sequences in the middle. How we can proceed if redis-master is not working?: * Verify `pvc` attached to the `redis-master-pod`: ``` kubectl get pvc NAME STATUS VOLUME redis-data-red3-redis-master-0 Bound pvc-cf59a0b2-a3ee-4f7f-9f07-8f4922518359 ``` * Create new `redis-client pod` wit the same `pvc` `redis-data-red3-redis-master-0`: ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: redis-client spec: volumes: - name: data persistentVolumeClaim: claimName: redis-data-red3-redis-master-0 containers: - name: redis image: docker.io/bitnami/redis:6.2.3-debian-10-r0 command: ["/bin/bash"] args: ["-c", "sleep infinity"] volumeMounts: - mountPath: "/tmp" name: data EOF ``` * Backup your files: ``` kubectl cp redis-client:/tmp . ``` * Repair appendonly.aof file: ``` kubectl exec -it redis-client -- /bin/bash cd /tmp # make copy of appendonly.aof file: cp appendonly.aof appendonly.aofbackup # verify appendonly.aof file: redis-check-aof appendonly.aof ... 0x 38: Expected prefix '*', got: '"' AOF analyzed: size=62, ok_up_to=56, ok_up_to_line=13, diff=6 AOF is not valid. Use the --fix option to try fixing it. ... # repair appendonly.aof file: redis-check-aof --fix appendonly.aof # compare files using diff: diff appendonly.aof appendonly.aofbackup ``` Note: > > [As per docs](https://redis.io/topics/persistence): > > > **The best thing to do is** to **run the redis-check-aof utility, initially without the --fix option**, then understand the problem, jump at the given offset in the file, **and see if it is possible to manually repair the file**: the AOF uses the same format of the Redis protocol and is quite simple to fix manually. **Otherwise it is possible to let the utility fix the file** for us, **but in that case all the AOF portion from the invalid part to the end of the file may be discarded**, **leading to a massive amount of data loss if the corruption happened to be in the initial part of the file**. > > > In addition as described in the comments by [@Miffa Young](https://stackoverflow.com/questions/68889647/redis-pod-failing/68902852#comment121826920_68902852) you can verify where your data is stored using `k8s.io/minikube-hostpath provisioner`: ``` kubectl get pv ... NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM pvc-cf59a0b2-a3ee-4f7f-9f07-8f4922518359 8Gi RWO Delete Bound default/redis-data-red3-redis-master-0 ... kubectl describe pv pvc-cf59a0b2-a3ee-4f7f-9f07-8f4922518359 ... Source: Type: HostPath (bare host directory volume) Path: /tmp/hostpath-provisioner/default/redis-data-red3-redis-master-0 ... ``` Your redis instance is failing down because your `appendonly.aof` is malformed and stored permanently under this location. You can ssh into your vm: ``` minikube -p redis ssh cd /tmp/hostpath-provisioner/default/redis-data-red3-redis-master-0 # from there you can backup/repair/remove your files: ``` Another solution is to install this chart using new name in this case new set of pv,pvc for redis StatefulSets will be created.
* I think your redis is not quit Gracefully , so the AOF file is in a bad format [What is AOF](https://redis.io/topics/persistence) * you should repair aof file using a initcontainer by command (./redis-check-aof --fix .) ``` apiVersion: apps/v1 kind: StatefulSet metadata: annotations: meta.helm.sh/release-name: test-redis meta.helm.sh/release-namespace: test generation: 1 labels: app.kubernetes.io/component: master app.kubernetes.io/instance: test-redis app.kubernetes.io/managed-by: Helm app.kubernetes.io/name: redis helm.sh/chart: redis-14.8.11 name: test-redis-master namespace: test resourceVersion: "191902" uid: 3a4e541f-154f-4c54-a379-63974d90089e spec: podManagementPolicy: OrderedReady replicas: 1 revisionHistoryLimit: 10 selector: matchLabels: app.kubernetes.io/component: master app.kubernetes.io/instance: test-redis app.kubernetes.io/name: redis serviceName: test-redis-headless template: metadata: annotations: checksum/configmap: dd1f90e0231e5f9ebd1f3f687d534d9ec53df571cba9c23274b749c01e5bc2bb checksum/health: xxxxx creationTimestamp: null labels: app.kubernetes.io/component: master app.kubernetes.io/instance: test-redis app.kubernetes.io/managed-by: Helm app.kubernetes.io/name: redis helm.sh/chart: redis-14.8.11 spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - podAffinityTerm: labelSelector: matchLabels: app.kubernetes.io/component: master app.kubernetes.io/instance: test-redis app.kubernetes.io/name: redis namespaces: - tyk topologyKey: kubernetes.io/hostname weight: 1 initContainers: - name: repair-redis image: docker.io/bitnami/redis:6.2.5-debian-10-r11 command: ['sh', '-c', "redis-check-aof --fix /data/appendonly.aof"] containers: - args: - -c - /opt/bitnami/scripts/start-scripts/start-master.sh command: - /bin/bash env: - name: BITNAMI_DEBUG value: "false" - name: REDIS_REPLICATION_MODE value: master - name: ALLOW_EMPTY_PASSWORD value: "no" - name: REDIS_PASSWORD valueFrom: secretKeyRef: key: redis-password name: test-redis - name: REDIS_TLS_ENABLED value: "no" - name: REDIS_PORT value: "6379" image: docker.io/bitnami/redis:6.2.5-debian-10-r11 imagePullPolicy: IfNotPresent livenessProbe: exec: command: - sh - -c - /health/ping_liveness_local.sh 5 failureThreshold: 5 initialDelaySeconds: 20 periodSeconds: 5 successThreshold: 1 timeoutSeconds: 6 name: redis ports: - containerPort: 6379 name: redis protocol: TCP readinessProbe: exec: command: - sh - -c - /health/ping_readiness_local.sh 1 failureThreshold: 5 initialDelaySeconds: 20 periodSeconds: 5 successThreshold: 1 timeoutSeconds: 2 resources: {} securityContext: runAsUser: 1001 terminationMessagePath: /dev/termination-log terminationMessagePolicy: File volumeMounts: - mountPath: /opt/bitnami/scripts/start-scripts name: start-scripts - mountPath: /health name: health - mountPath: /data name: redis-data - mountPath: /opt/bitnami/redis/mounted-etc name: config - mountPath: /opt/bitnami/redis/etc/ name: redis-tmp-conf - mountPath: /tmp name: tmp dnsPolicy: ClusterFirst restartPolicy: Always schedulerName: default-scheduler securityContext: fsGroup: 1001 serviceAccount: test-redis serviceAccountName: test-redis terminationGracePeriodSeconds: 30 volumes: - configMap: defaultMode: 493 name: test-redis-scripts name: start-scripts - configMap: defaultMode: 493 name: test-redis-health name: health - configMap: defaultMode: 420 name: test-redis-configuration name: config - emptyDir: {} name: redis-tmp-conf - emptyDir: {} name: tmp updateStrategy: rollingUpdate: partition: 0 type: RollingUpdate volumeClaimTemplates: - apiVersion: v1 kind: PersistentVolumeClaim metadata: creationTimestamp: null labels: app.kubernetes.io/component: master app.kubernetes.io/instance: test-redis app.kubernetes.io/name: redis name: redis-data spec: accessModes: - ReadWriteOnce resources: requests: storage: 8Gi volumeMode: Filesystem ```
17,056,374
How to check if a string contains version in numberic/decimal format in shell script for eg we have 1.2.3.5 or 2.3.5 What if we do not have a constraint on the number of characters we have in here. It could x.x.x.x or x.x as well.
2013/06/12
[ "https://Stackoverflow.com/questions/17056374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057351/" ]
Using [*bash regular expressions*](http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/x13357.html): ``` echo -n "Test: " read i if [[ $i =~ ^[0-9]+(\.[0-9]+){2,3}$ ]]; then echo Yes fi ``` This accepts `digits.digits.digits` or `digits.digits.digits.digits` Change `{2,3}` to shrink or enlarge the acceptable number of `.digits` (or `{2,}` for "at least 2") * `^` means beginning of string * `[0-9]+` means at least one digit * `\.` is a dot * `(...){2,3}` accepts 2 or 3 of what's inside the `()` * `$` means end of string
And if you're truly restricted to the Bourne shell, then use *expr*: ``` if expr 1.2.3.4.5 : '^[0-9][.0-9]*[0-9]$' > /dev/null; then echo "yep, it's a version number" fi ``` I'm sure there are solutions involving awk or sed, but this will do.
70,549,444
Hello everyone and happy new year, I had learned on this site to create dictionaries to prepare sections of lists from a property of an object, for example: ``` struct Lieu: Identifiable, Hashable { var id = UUID().uuidString var nom: String var dateAjout = Date() var img: String var tag: String var tag2: String var tag3: String } ``` Preparation of the dictionary with "tag" as key: ``` private var lieuxParTag: [String: [Lieu]] { Dictionary(grouping: listeDeLieux) { lieu in lieu.tag } } private var lieuxTags: [String] { lieuxParTag.keys.sorted(by: <) } ``` Then in the view, it was quite simple: ``` ForEach (lieuxTags, id: \ .self) {tag in Section (header: Text (tag)) { ScrollView (.horizontal, showsIndicators: true) { LazyHStack { ForEach (lieuxParTag [tag]!) {Place in Text (place.name) } } } } ``` But how to make sections if **"Lieu"** contains tag property like this: ``` var tags: [String] ``` And in this table I integrate all the tags of a **"Lieu"** for example : ``` Lieu(nom: Paris, tags: ["tour eiffel", "bouchons"]) ``` Thanks for your help.
2022/01/01
[ "https://Stackoverflow.com/questions/70549444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17809663/" ]
Use `read_csv`: ``` >>> pd.read_csv('E:/Tabledata.csv', squeeze=True).tolist() ['DimCurrency', 'DimOrganization', 'DimProduct', 'DimProductCategory', 'DimProductSubcategory', 'DimPromotion'] ``` Or you can simply use: ``` lines = [line.strip() for line in open('E:/Tabledata.csv').readlines()][1:] ```
seems like the content you need is in index column so do this after import data into dataframe. ``` list(df1.index) ``` output: ['DimCurrency', 'DimOrganization', 'DimProduct', 'DimProductCategory', 'DimProductSubcategory', 'DimPromotion']
139,238
I had a 160 GB hard disk with Windows XP. Then I installed Ubuntu 11.10 64bit. But I didn't knew anything about disk partition. After installation, I only have C drive with 20 GB in xp and about 40 GB in Ubuntu. I have The Ubuntu in a DVD. How do I remove it and get all the space back in Windows XP without losing XP?
2012/05/19
[ "https://askubuntu.com/questions/139238", "https://askubuntu.com", "https://askubuntu.com/users/64595/" ]
This solution will seem to be worked until you reboot your computer. **Do not try it.** --> I realised that; that will probably remove grub and Windows will not be able to understand nor rewrite mbr data for "sure". That means you will lose both OS. > > Open your XP. > > > write `diskmgmt.msc` to "Run" > > > Find your linux partition and delete it. > > > Right click on C: partition. And select the option helps you include > the empty space in your disk. > > > Hope This Helps. Tried on Windows 7. > > >
There are 2 ways you can use: 1. Download a trial of Acronis Disk Director, boot from the CD and increase the size of your partitions. [To download go here and click on free trial](http://www.acronis.eu/homecomputing/products/diskdirector/) 2. Keep Ubuntu installed after you change the partition sizes, and boot from the XP CD, choose repair console and once you get to the command prompt type `fixboot c:` (if c: is you xp boot drive) and that will make XP boot again. If you want to get rid of Ubuntu, delete the Ubuntu partition from the Acronis CD, and then use the `fixboot` command. Let me know if more help is needed.
46,204,112
I am unable to understand why tensorflow maxpooling with my parameters. When performed a maxpool with `ksize=2` and `strides=2` i get the following output with both `padding SAME` and `padding VALID` ``` input : (?, 28, 28, 1) conv2d_out : (?, 28, 28, 32) maxpool2d_out : (?, 14, 14, 32) ``` But when I try to perfrom maxpool with `ksize=3` and `strides=1`, I get the following output: ``` input : (?, 28, 28, 1) conv2d_out : (?, 28, 28, 32) maxpool2d_out : (?, 28, 28, 32) PADDING SAME maxpool2d_out : (?, 26, 26, 32) PADDING VALID ``` maxpool with `ksize=2` and `strides=2` using `padding SAME` should have produced the output `maxpool2d_out : (?, 28, 28, 32)` Is there something I missed out on how max pooling with padding works? `**CODE**==`[*python\_*](http://codepad.org/IwxshYr1)
2017/09/13
[ "https://Stackoverflow.com/questions/46204112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275815/" ]
Problem you're facing is `MainViewModel.CurrentDateTime` only gets notified when you assign `MainViewModel.DateTimeModel`, not when `DateTimeModel`'s properties change. [This is a known Fody limitation](https://github.com/Fody/PropertyChanged/issues/179) and a guy [here found a walkaround](https://github.com/Fody/PropertyChanged/issues/179#issuecomment-236719923) that allows you to notify on subproperty changes like so: ``` public class MainViewModel : ViewModelBase, INotifyPropertyChanged { // ... snip ... [DependsOn(nameof(DateTimeModel))] [DependsOn("DateTimeModel.CurrentDateTime")] public DateTime CurrentDateTime => DateTimeModel.CurrentDateTime; } ``` But I think it's far more elegant to drop the `MainViewModel.CurrentDateTime` and bind to `MainViewModel.DateTimeModel` directly ``` <TextBlock Text="{Binding DateTimeModel.CurrentDateTime}"/> ``` This requires changing `DateTimeModel` to property as suggested by [mm8](https://stackoverflow.com/q/46204099/7034621): ``` public DateTimeModel DateTimeModel { get; } ```
Raise the `PropertyChanged` event for the `CurrentDateTime` of the `MainViewModel` that you bind to whenever the `PropertyChanged` event of the `DateTimeModel` is raised: ``` public class MainViewModel : ViewModelBase, INotifyPropertyChanged { public DateTimeModel DateTimeModel; [DependsOn(nameof(DateTimeModel))] public DateTime CurrentDateTime => DateTimeModel.CurrentDateTime; public MainViewModel() { DateTimeModel = new DateTimeModel(); DateTimeModel.PropertyChanged += (s, e) => { Debug.WriteLine("DateTime PropertyChanged"); this.RaisePropertyChanged(nameof(CurrentDateTime)); //<--- }; } #region Events public event PropertyChangedEventHandler PropertyChanged; #endregion } ``` Or you could `DateTimeModel` a property in the `MainViewModel` class: ``` public DateTimeModel DateTimeModel { get; private set; } ``` ...and bind directly to the `CurrentDateTime` property of the `DateTimeModel`: ``` <TextBlock Text="{Binding DateTimeModel.CurrentDateTime}"/> ```
47,356,453
I want to schedule a python function to run everyday at a certain time for a list of customers with different timezones. This is basically what I want to do: ``` import schedule import time def job(text): print("Hello " + text) def add_job(user_tz, time, text): schedule.every().day.at(time).do(job(text)) # the above adds all jobs at local time, I want to use different timezones with these def run_job(): while(1): schedule.run_pending() time.sleep(1) if __name__=='__main__': add_job('America/New_York', "12:00", 'New York') add_job('Europe/London', "12:00", 'London') run_job() ``` I am using this for posting/receiving some stuff using flask and an external API. Celery or heroku scheduler or something heavy is not what I am looking for, something lightweight and pythonic for debian(or nix) env would be ideal. I have looked into [scheduler](https://schedule.readthedocs.io/en/stable/index.html), [tzcron](https://tzcron.readthedocs.io/en/latest/basic-usage.html) and [APScheduler](https://pypi.python.org/pypi/APScheduler/), but could not figure out how we would be able to use them with timezones. Also I tried using crontab but could not figure out how to add jobs at run time, since I want to be able to add/remove jobs using the above mentioned functions at runtime as well. I have some experience with python, but its my first problem with timezones and I dont know much about this, so please feel free to enlighten me if there is something I missed or if there is any other way of doing it. Thanks!
2017/11/17
[ "https://Stackoverflow.com/questions/47356453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8872639/" ]
The arrow library is great for this, and much simpler than the standard date/time (imo). [arrow docs](http://arrow.readthedocs.io/en/latest/). ``` import arrow from datetime import datetime now = datetime.now() atime = arrow.get(now) print(now) print (atime) eastern = atime.to('US/Eastern') print (eastern) print (eastern.datetime) 2017-11-17 09:53:58.700546 2017-11-17T09:53:58.700546+00:00 2017-11-17T04:53:58.700546-05:00 2017-11-17 04:53:58.700546-05:00 ``` I would change your "add\_job" method modify all of my incoming dates to a standard time zone (utc for example).
The described problem sounds like the [scheduler library](https://gitlab.com/DigonIO/scheduler) for python provides a solution out of the box that requires no further customization by the user. The scheduler library is designed so that jobs can be scheduled in different timezones, it is irrelevant with which timezone the scheduler is created and in which independent timezones the jobs are scheduled. *Disclosure: I'm one of the authors of the scheduler library* For demonstration, I have adapted an [example](https://python-scheduler.readthedocs.io/en/latest/pages/examples/timezones.html) from the [documentation](https://python-scheduler.readthedocs.io/en/latest/index.html) to the question: ```py import datetime as dt from scheduler import Scheduler import scheduler.trigger as trigger # Create a payload callback function def useful(): print("Very useful function.") # Instead of setting the timezones yourself you can use the `pytz` library tz_new_york = dt.timezone(dt.timedelta(hours=-5)) tz_wuppertal = dt.timezone(dt.timedelta(hours=2)) tz_sydney = dt.timezone(dt.timedelta(hours=10)) # can be any valid timezone schedule = Scheduler(tzinfo=dt.timezone.utc) # schedule jobs schedule.daily(dt.time(hour=12, tzinfo=tz_new_york), useful) schedule.daily(dt.time(hour=12, tzinfo=tz_wuppertal), useful) schedule.daily(dt.time(hour=12, tzinfo=tz_sydney), useful) # Show a table overview of your jobs print(schedule) ``` ```tex max_exec=inf, tzinfo=UTC, priority_function=linear_priority_function, #jobs=3 type function due at tzinfo due in attempts weight -------- ---------------- ------------------- ------------ --------- ------------- ------ DAILY useful() 2021-07-20 12:00:00 UTC-05:00 1:23:39 0/inf 1 DAILY useful() 2021-07-21 12:00:00 UTC+10:00 10:23:39 0/inf 1 DAILY useful() 2021-07-21 12:00:00 UTC+02:00 18:23:39 0/inf 1 ``` Execute jobs using a simple loop: ```py import time while True: schedule.exec_jobs() time.sleep(1) # wait a second ``` Edit: An [asyncio example](https://python-scheduler.readthedocs.io/en/latest/pages/examples/asyncio.html) is available in the doc too.
13,015,698
It appears that there is no API call to calculate the width (in pixels) of a text string in Java FX 2.2. There have been suggestions of workarounds on other forums, but my efforts to create or find any code that returns the width of a String, either using the default font or otherwise, have failed. Any help would be appreciated.
2012/10/22
[ "https://Stackoverflow.com/questions/13015698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066408/" ]
I tried this: ``` Text theText = new Text(theLabel.getText()); theText.setFont(theLabel.getFont()); double width = theText.getBoundsInLocal().getWidth(); ``` and it seems to be working fine.
``` Bounds bounds = TextBuilder.create().text(text).font(font).build().getLayoutBounds(); double width=bounds.getWidth(); double height=bounds.getHeight(); ```
44,806,032
I am trying to optimize my stored procedure. When I look at the query plan, I can see tablescan on tempcompany is showing 97 percent. I am also seeing the following message Missing index (Impact 97) : Create Non Clustered Index on #tempCompany I have already set non clustered indexes. Could somebody point out what the problem is ``` if object_id('tempdb..#tempCompany') is not null drop table #tempCompany else select fp.companyId,fp.fiscalYear,fp.fiscalQuarter,fi.financialperiodid, fi.periodEndDate, fc.currencyId,fp.periodtypeid,ROW_NUMBER() OVER (PARTITION BY fp.companyId, fp.fiscalYear, fp.fiscalQuarter ORDER BY fi.periodEndDate DESC) rowno into #tempCompany from ciqFinPeriod fp inner join #companyId c on c.val = fp.companyId join ciqFinInstance fi on fi.financialperiodid = fp.financialperiodid join ciqFinInstanceToCollection ic on ic.financialInstanceId = fi.financialInstanceId left join ciqFinCollection fc on fc.financialCollectionId = ic.financialCollectionId left join ciqFinCollectionData fd on fd.financialCollectionId = fc.financialCollectionId where fp.periodTypeId = @periodtypeId and fi.periodenddate >= @date --and fp.companyId in (select val from @companyId) CREATE NONCLUSTERED INDEX id_companyId2 on #tempCompany(companyId,fiscalYear,fiscalQuarter,financialperiodid,periodEndDate,currencyId,periodtypeid,rowno) if object_id('tempdb..#EstPeriodTbl') is not null drop table #EstPeriodTbl else select companyId,fiscalYear,fiscalQuarter,financialPeriodId,periodenddate,currencyId, periodtypeid,rowno into #EstPeriodTbl from #tempCompany a where a.rowno = 1 order by companyid, periodenddate CREATE NONCLUSTERED INDEX id_companyId3 on #EstPeriodTbl(companyId,periodenddate,fiscalYear,fiscalQuarter,currencyId,financialPeriodId,rowno) Execution Plan ``` [![enter image description here](https://i.stack.imgur.com/0kVwD.png)](https://i.stack.imgur.com/0kVwD.png)
2017/06/28
[ "https://Stackoverflow.com/questions/44806032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4607841/" ]
Well, firstly what is wrong is you have a ETIMEDOUT error coming from your email call. Are you sure you have all the parameters correct? Secondly use Promises, rather than callback style, and catch the rejection. Like this, ``` smtpTransport .sendMail(...) .then(success => console.log('success: ', success)) .catch(error => console.log('error: ', error)) ```
Maybe is a rejection from GMail, Try Login in to: [https//www.google.com/setti ngs/security/lesssecureapps](https://www.google.com/settings/security/lesssecureapps) and TURN ON "*Access for less secure apps*". Or use OAuth.
239,116
[This question was asked on [MSE](https://math.stackexchange.com/questions/1788107/on-a-parallelizable-manifold-is-there-always-a-frame-satisfying-x-i-x-j-0), but got no answers, I thought it could be more appropriate here] Let $M$ be a parallelizable manifold. 1. Is there always a global frame $(X\_i)$ such that $[X\_i,X\_j]=0$ for all $i,j$ ? 2. If the answer is no, what kind of obstruction there is to find such a frame ? and what kind of general (topological ?) condition on $M$ makes it possible to find such a frame ?
2016/05/17
[ "https://mathoverflow.net/questions/239116", "https://mathoverflow.net", "https://mathoverflow.net/users/89425/" ]
Suppose that $M$ is compact, such a frame exists implies that the commutative group $R^n$ acts transitively on it, this implies that $M$ is a torus. But a compact Lie group is parallelizable, so that is not always possible.
On a compact manifold, you have a global frame such that $[X\_i, X\_j]=0$ if and only if your manifold is the torus. Starting from dimension 3, there are parallelisable manifolds different from the torus, possibly the simplest example is $S^3$. Indeed, the flows of the vector fields generate an action of $R^n$ on the manifold, the manifold is therefore $R^n$ quotient by the stabilisor, and the stabilisor is a discrete subgroup of $R^n$ which preserves the vector fields and is therefore a lattice.
20,835,534
I was trying to declare a function pointer that points to any function that returns the same type. I omitted the arguments types in the pointer declaration to see what error will be generated. But the program was compiled successfully and executed without any issue. Is this a correct declaration? Shouldn't we specify the arguments types? ``` #include <stdio.h> #include <stdlib.h> void add(int a, int b) { printf("a + b = %d", a + b); } void (*pointer)() = &add; int main() { add(5, 5); return 0; } ``` Output: ``` a + b = 10 ```
2013/12/30
[ "https://Stackoverflow.com/questions/20835534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727656/" ]
Empty parentheses within a type name means unspecified arguments. Note that this is an obsolescent feature. > > ### C11(ISO/IEC 9899:201x) §6.11.6 Function declarators > > > The use of function declarators with empty parentheses (not prototype-format parameter > type declarators) is an obsolescent feature. > > >
`void (*pointer)()` explains function pointed have unspecified number of argument. It is not similar to `void (*pointer)(void)`. So later when you used two arguments that fits successfully according to definition.
58,867,869
I tried to run `create-react-app myapp` and everytime it throws an error I tried to clean the cache by `npm cache clean --force` but it didn't fix the problem ``` internal/modules/cjs/loader.js:638 throw err; ^ Error: Cannot find module './node' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15) at Function.Module._load (internal/modules/cjs/loader.js:562:25) at Module.require (internal/modules/cjs/loader.js:692:17) at require (internal/modules/cjs/helpers.js:25:18) at Object.<anonymous> (D:\Design\react\myapp\node_modules\browserslist\index.js:8:11) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) Aborting installation. node has failed. ``` My node version v10.17.0 My npm version 6.11.3
2019/11/14
[ "https://Stackoverflow.com/questions/58867869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4054689/" ]
I was presenting the same problem, until I realized that I had an instance of create-react-app installed globally, apparently this generates a kind of conflict, I solved it as follows: * Check the npm folder in the following path: C:/Users/username/AppData/Roaming/npm I noticed that in this npm folder I had executable files of create-react-app. So I deleted all the npm folder and also uninstall node and reinstalled it and that solved my problem. I hope this is useful for you.
This is because the create-react-app is not fully deleted from global packages, so to delete it completely `goto 'C:\Users\YOUR_USERNAME\AppData\Roaming\npm'` and **delete** the **create-react-app.cmd** file [Picture showing which file to delete](https://i.stack.imgur.com/PukkI.png)
973,586
I was disappointed to find that Array.Clone, Array.CopyTo, and Array.Copy can all be beat by a simple 3-line manually coded for(;;) loop: ``` for(int i = 0; i < array.Length; i++) { retval[i] = array[i]; } ``` Say the base case for performing an operation a few million times on an array of some predetermined size takes 10 seconds. Using Array.Clone before each operation is abysmal extending that time to 100 seconds. Using Array.CopyTo and Array.Copy takes only about 45 seconds. The loop above takes only about 20 seconds. (Forget the subjective argument of whether this makes a difference in the real world, because in the real world it's arguably just as simple to code a 3-line for(;;) loop as to look up the documentation for the Array class.) I'm just wondering why the performance is so much different. In good old C, the simplest library function, memcpy() performs about the same as a manual for(;;) loop like the one above, and I'm wondering if there's some other array copy function in .NET that's implemented as such a nice simple for(;;) without whatever abstractions are getting in the way of Array.Clone, Array.CopyTo, and Array.Copy.
2009/06/10
[ "https://Stackoverflow.com/questions/973586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your test may have a wrinkle. A quick look with [Reflector](http://www.red-gate.com/products/reflector/) shows Array.Copy uses an externed implementation (Array.CopyTo ultimately uses the same call): ``` [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] internal static extern void Copy( Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable); ``` This opens up the possibility of memory copying versus item-by-item copying. My own test in Release mode, with an int[1000000] - randomly populated, clocks the loop at 468750 ticks and Array.Copy at 312500 ticks. Not a huge difference, but still faster as [weiqure](https://stackoverflow.com/users/67011/weiqure) noted. You may want to tweak your test to make sure there aren't other factors effecting the result. [This post](http://waldev.blogspot.com/2008/05/efficiently-copying-items-from-one.html) makes a similar observation with Object arrays.
You didn't mention how large the array being copied was. Perhaps the JIT doesn't specialize Array.Copy and Array.Clone for each type of array, the way it does for generic types. Consequently, the first thing these methods would have to do is examine the array to determine: is it a reference type or a value type, and if it's a value type, how large is each entry? If I'm right, copying a small array ten million times would result in these checks being unnecessarily repeated ten million times. On the other hand, copying a one-million element array could be faster than a hand-coded loop because Array.Copy might employ optimizations for large arrays. Notably, in your hand-coded loop ``` for(int i = 0; i < array.Length; i++) { retval[i] = array[i]; } ``` the JIT will optimize away the range check for array[i] because it recognizes that i is always in-range; but it probably won't remove the range check for retval[i], even if it can be easily proven to be in-range too. Since it is probably written in native code, Array.Copy can avoid these checks. Besides that, Array.Copy might use loop unrolling, and for large byte arrays might copy one machine word at a time. But I'm just conjecturing. I don't know how to find out what Array.Copy actually does.
62,913,826
*This is my first post to the coding community, so I hope I get the right level of detail in my request for help!* Background info: I want to repeat (loop) command in a df using a variable that contains a list of options. While the series '*amenity\_options*' contains a simple list of specific items (let's say only four amenities as the example below) the df is a large data frame with many other items. My goal is the run the operation below for each item in the '*amenity\_option*' until the end of the list. ``` amenity_options = ['cafe','bar','cinema','casino'] # this is a series type with multiple options df = df[df['amenity'] == amenity_options] # this is my attempt to select the the first value in the series (e.g. cafe) out of dataframe that contains such a column name. df.to_excel('{}_amenity.xlsx, format('amenity') # wish to save the result (e.g. cafe_amenity) as a separate file. ``` Desired result: I wish to loop step one and two for each and every item available in the list (e.g. cafe, bar, cinema...). So that I will have separate excel files in the end. Any thoughts?
2020/07/15
[ "https://Stackoverflow.com/questions/62913826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13848258/" ]
I would recommend `not exists` rather than `not in`; it is `null`-safe, and usually more efficient: ``` select count(distinct charging_id) from billingdb201908 b where b.cdr_type = 'gprso' and not exists (select 1 from cbs_chrg_id_aug a where a.chargingid = b.chargingid) ```
There are two dangers with `not in` when the subquery key may contain nulls: 1. If there actually is a null value, you may not get the result you were expecting (as you have found). The database is actually correct, even though nobody in the history of SQL has ever expected this result. 2. Even if all key values are populated, if it is possible for the key column to be null (if it is not defined as `not null`) then the database has to check in case there is a null value, so queries are limited to inefficient row by row filter operations, which can perform disastrously for large volumes. (This was true historically, although these days there is a [Null-aware anti-join](http://structureddata.org/2008/05/22/null-aware-anti-join/) and so the performance issue may not be so disastrous.) ```sql create table demo (id) as select 1 from dual; select * from demo; ID ---------- 1 ``` ```sql create table table_with_nulls (id) as ( select 2 from dual union all select null from dual ); select * from table_with_nulls; ID ---------- 2 ``` ```sql select d.id from demo d where d.id not in ( select id from table_with_nulls ); no rows selected ``` ```sql select d.id from demo d where d.id not in ( select id from table_with_nulls where id is not null ); ID ---------- 1 ``` The reason is that `1 <> null` is `null`, not `false`. If you substitute a fixed list for the `not in` subquery, it would be: ``` select d.id from demo d where d.id not in (2, null); ``` which is really the same thing as ``` select d.id from demo d where d.id <> 2 and d.id <> null; ``` Obviously `d.id <> null` will never be true. This is why your `not in` query returned no rows.