qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
4,322,649
> > Find the area under the graph of > $$ > f(t) = \frac{t}{(1+t^2)^a} > $$ > between $t=0$ and $t=x$ where $a>0$ and $a \neq 1$ is fixed, and evaluate the limit as $x \to \infty$. > > > Hello, for this question I tried using substitution but the different conditions like $t=0$ and $t=x$ confuse me. Especially what "$a$" is, since $a$ is positive and not equal $1$, I'm completely stuck there. Please explain how I would approach this question. I know substitution is neccesarly
2021/12/03
[ "https://math.stackexchange.com/questions/4322649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/971591/" ]
Hint: substitute $1 + t^2 = u$. If $t = 0$, what is $u$? If $t = x$, what is $u$? > > \begin{align} 1 + t^2 = u &\Rightarrow 2tdt = du\\ t = 0 &\Rightarrow u = 1+0^2 = 1\\ t = x &\Rightarrow u = 1+x^2 \end{align} > > > $a$ is a parameter, which you should consider as a fixed number.
231,208
If $T:\Bbb R^n \to\Bbb R^m$ (where $n\neq m$) is a linear transformation, can $T$ be both one to one and onto? My first instinct was it can, but after thinking about it, it seems the set will either be dependent or there would be a row without a pivot. Is there a way to prove this for all examples?
2012/11/06
[ "https://math.stackexchange.com/questions/231208", "https://math.stackexchange.com", "https://math.stackexchange.com/users/48357/" ]
It's a ready consequence of [Kernel Extension Theorem (for vector spaces)](http://en.wikipedia.org/wiki/Dimension_theorem#Kernel_extension_theorem_for_vector_spaces) that such a transformation must either fail to be one-to-one or fail to be onto. (You may have heard "kernel" referred to as "null space" instead.) If $n<m$, then since the image (range) of the transformation has dimension at most $n$, it can't be the whole space $\Bbb R^m$, and so fails to be onto, even if it's one-to-one (that is, has a kernel of dimension $0$). If $n>m$, then since the image of the transformation has dimension at most $m$ (as a subspace of $\Bbb R^m$), it follows that the kernel of the transformation has positive dimension, and to the transformation fails to be one-to-one, even if it's onto (that is, has an image of dimension $m$). If you'd rather think of things in terms of the matrix corresponding to the transformation, see the [Rank-Nullity Theorem](http://en.wikipedia.org/wiki/Rank-nullity_theorem).
5,850,142
I know .NET and Mono are binary compatible but given a set of source code, will csc and mcs produce the exact same 100% identical binary CLI executable? Would one be able to tell whether an executable was compiled with csc or mcs?
2011/05/01
[ "https://Stackoverflow.com/questions/5850142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343845/" ]
A lot of things are not fully defined in the spec, or are implementation-specific extensions. Examples of not-fully-specified: * the synchronisation semantics of field-like events; this is ***explicitly*** open to implementations in the ecma spec; it is stricty defined in the MS spec, but uses a different version in c# 4.0 which ***does not yet*** appear in the formal spec, IIRC * `Expression` construction (from lambdas); is simply "defined elsewhere" (actually, it isn't) Examples of implementation extensions: * P/Invoke * COM interface handling (i.e. how you can call `new` on an interface) So no: it is not guarantees to have the same IL, either between csc or [g]mcs - but even between different versions of csc. Even more: depending on debug settings, optimizations being enabled or not, and some compilation constants being defined (such as DEBUG or TRACE), the same compiler will generate different code.
331,365
I have a macOS 10.13 machine that is being used only for remote work, and has no need for printers. Printer Sharing is definitely turned off in System Preferences, and yet, `cupsd` is listening to a port: ``` # lsof -i :631 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME cupsd 427 root 5u IPv6 0xbb661a1308e1d70b 0t0 TCP localhost:ipp (LISTEN) cupsd 427 root 6u IPv4 0xbb661a130bee2d13 0t0 TCP localhost:ipp (LISTEN) ``` What is the appropriate way to turn off `cupsd`?
2018/07/17
[ "https://apple.stackexchange.com/questions/331365", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/6489/" ]
In the terminal... `sudo launchctl unload /System/Library/LaunchDaemons/org.cups.cupsd.plist` ...will unload cups. This stops the service. After that, `sudo launchctl remove /System/Library/LaunchDaemons/org.cups.cupsd.plist` ...will ensure that cups does not come back after a reboot. I don't know how OS X will react if you try to leave cups unloaded in the long term. Also, I am nearly certain that major (and likely some minor) OS updates will "correct the issue" and reload cups for you. So helpful. Last, you can check to see what services are currently running by using `sudo launchctl list`
17,407,435
There is a code which generate the file with one proc: ``` puts $fh "proc generate \{ fileName\} \{" puts $fh "[info body generateScriptBody]" puts $fh "\}" puts $fh "generate" close $fh proc generateScriptBody{} { source something1 source something2 ... } ``` In this case should I `source` inside proc or there are alternatives?
2013/07/01
[ "https://Stackoverflow.com/questions/17407435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892307/" ]
I don't understand what you are trying to do, but source within a proc is acceptable. If you are looking to write the whole proc into a file, take a look at `saveprocs` from the TclX package; it will help simplifying your code. ### Update Here is an example of using `saveprocs`: ``` package require Tclx # Generate a proc from body of one or more files set body [read_file something1] append body "\n" [read_file something2] proc generate {fileName} $body # Write to file saveprocs generate.tcl generate ``` In this case, I did away with all the `source` commands and read the contents directly into the proc's body.
21,521,410
I have an js object like ``` { a: 1, b: 2, c: 3 } ``` I wanted to stringify the above object using JSON.stringify with the same order. That means, the stringify should return me the strings as below, ``` "{"a":"1", "b":"2", "c":"3"}" ``` But it is returning me like the below one if my js object has too many properties say more than 500, ``` "{"b":"2", "a":"1", "c":"3"}" ``` Is there any option to get my js object's json string as in sorted in asc.
2014/02/03
[ "https://Stackoverflow.com/questions/21521410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/744534/" ]
If the order is important for you, don't use `JSON.stringify` because the order is not safe using it, you can create your JSON stringify using javascript, to deal with string values we have 2 different ways, first to do it using regexp an replace invalid characters or using `JSON.stringify` for our values, for instance if we have a string like `'abc\d"efg'`, we can simply get the proper result `JSON.stringify('abc\d"efg')`, because the whole idea of this function is to stringify in a right order: ``` function sort_stringify(obj){ var sortedKeys = Object.keys(obj).sort(); var arr = []; for(var i=0;i<sortedKeys.length;i++){ var key = sortedKeys[i]; var value = obj[key]; key = JSON.stringify(key); value = JSON.stringify(value); arr.push(key + ':' + value); } return "{" + arr.join(",\n\r") + "}"; } var jsonString = sort_stringify(yourObj); ``` If we wanted to do this not using `JSON.stringify` to parse the keys and values, the solution would be like: ``` function sort_stringify(obj){ var sortedKeys = Object.keys(obj).sort(); var arr = []; for(var i=0;i<sortedKeys.length;i++){ var key = sortedKeys[i]; var value = obj[key]; key = key.replace(/"/g, '\\"'); if(typeof value != "object") value = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); arr.push('"' + key + '":"' + value + '"'); } return "{" + arr.join(",\n\r") + "}"; } ```
74,435
What is the function of the two segnos in the following score? At the start of measure 7 there is a segno, and in measure 70 there is a second segno together with a Da Capo. In the following measure there is this indication (in Spanish): > > *Se toca otra vez la primera parte y luego la tercera* > > > Which translates as: > > "The first part is played again and then the third one" > > > [![Score of "Teresita - Valse"](https://i.stack.imgur.com/2cMTx.jpg)](https://i.stack.imgur.com/2cMTx.jpg) (see [here](https://drive.google.com/open?id=1EjN20nnXGzrgLUFGaxVaDpIBbuH1O34g) for larger image)
2018/09/06
[ "https://music.stackexchange.com/questions/74435", "https://music.stackexchange.com", "https://music.stackexchange.com/users/52590/" ]
This piece seems to have several mistakes in instructions and in notation. "The first part is played again and then the third one" doesn't seem to make sense. It's too vague. Also, the D.C. should be a D.S. al Fine. That makes more sense of the two segnos. There should logically be a Fine half way along the 5th line, the bar before the repeat. In this way, the format makes more logical sense - play the page from beginning to end, then do the repeat from half way through the 5th line, until the D.S. al Fine (beginning of second to bottom line), then from the sign (b.7) and finish half way through line 5. In notation, b.16 right hand should, I think, be the same as in b.32. Also, b.20 left hand should be the same as in b.19, and finally the 'B' in the left hand of the first bar in the final line should be a 'C'. That's my interpretation of what may have been meant in this little piece, anyway.
47,528,077
I found the pattern used by the Google places IOS SDK to be clean and well designed. Basically they follow what is presented on the following apple presentation: [Advanced User interface with Collection view](https://developer.apple.com/videos/play/wwdc2014/232/) (It start slide 46). This is what is implemented in their GMSAutocompleteTableDataSource. It us up to the datasource to define the state of the tableview. We link the tableview. ``` var googlePlacesDataSource = GMSAutocompleteTableDataSource() tableView.dataSource = googlePlacesDataSource tableView.delegate = googlePlacesDataSource ``` Then every time something change the event is binded to the datasource: ``` googlePlacesDataSource.sourceTextHasChanged("Newsearch") ``` The data source perform the query set the table view as loading and then display the result. I would like to achieve this from my custom Source: ``` class JourneyTableViewDataSource:NSObject, UITableViewDataSource, UITableViewDelegate{ private var journeys:[JourneyHead]?{ didSet{ -> I want to trigger tableView.reloadData() when this list is populated... -> How do I do that? I do not have a reference to tableView? } } override init(){ super.init() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } ... } ``` Any idea?
2017/11/28
[ "https://Stackoverflow.com/questions/47528077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/876087/" ]
Change this: ``` A* a; ``` to this: ``` ::A* a; ``` since `C` inherits from `B`, and `B` from `A`, thus you need the scope resolution operator to do the trick. Instead of starting at the local scope which includes the class parents, `::A` starts looking at the global scope because of the `::`. From the [Standard](http://open-std.org/JTC1/SC22/WG21/docs/papers/2015/n4567.pdf): > > **11.1.5 Acess Specifiers** > > > In a derived class, the lookup of a base class name will find the > injected-class-name instead of the name of the base class in the scope > in which it was declared. The injected-class-name might be less > accessible than the name of the base class in the scope in which it > was declared. > > >
70,333
I have a Sony VAIO VPCF22S1E. I just upgraded from 11.04 to 11.10 . While upgrading (on downloading packages step) I lost my internet connection and 2-3 minutes later it resumed. I continued to download packages. And finally, upgrading is completed. Now I'm using 11.10 . But when I log in to Ubuntu after 2 minutes the touchpad will be unresponsive. I can't use it or the integrated buttons. The **Disable touchpad while typing** option is turned off (suggested from [this answer](https://askubuntu.com/questions/66081/touchpad-gets-disabled-after-sometime-after-login/66142#66142)) but it did not solve the problem. How can I sure my packages downloaded and installed successfully? (As I said, I lost my connection while downloading packages) *PS: I can use USB mouse.* *PPS: I have tried `apt-get update` , `apt-get upgrade`*
2011/10/21
[ "https://askubuntu.com/questions/70333", "https://askubuntu.com", "https://askubuntu.com/users/17345/" ]
Here is a fix worked for first reboot but **now it's not working** : 1. Edit `/etc/default/grub` to include `GRUB_CMDLINE_LINUX=”i8042.nopnp”` 2. Run: `sudo update-grub` 3. Reboot.
352,352
I would like some input on some refactoring I am to do on a mobile backend (API). I have been tossed a mobile API which I need to refactor and improve upon, especially in the area of performance. One (of the many) place where I can improve the performance while also improve the architecture is how the backend currently deals with push notifications. Let me briefly describe how it currently works, and then how I intent to restructure it. This is how it works now. The example is about the user submitting a comment to a feed post: 1. The user clicks send in the mobile app. The app shows a spinner and meanwhile sends a request to the backend. 2. The backend receives the request and starts handling it. It inserts a row in the comments table, does some other bookkeeping stuff, and then for the affected mobile devices it makes a request to either the Apple Push Notification server or the Google Firebase Service (or both if the receiver has both an Android and an iPhone). 3. On success the backend returns a 200 to the mobile app. 4. Upon receiving status code 200 from the backend, the mobile app removes the spinner and updates the UI with the submitted comment. It is simple but the issue with the above as I see it is a) Currently this sample endpoint has too many responsibilities. It deals with saving a comment, and also with sending out push notifications to devices. b) The performance is not the best since the mobile app waits for the backend to both save a comment (which is pretty fast) and send a notification which requires a HTTP request (which can be anything from fast to slow). So my idea is to remove all about notifications from the backend, and host that in a separate backend app (you might call it a microservice). So what I am thinking is to do it like this: 1. The user clicks "Send" in the mobile app. The app shows a spinner and meanwhile sends a request to the main API backend. 2. The mobile app also sends of another HTTP request, this time to a notification service which is separate from the main API backend. This is kind of a fire and forget request. So the app does not wait for this in anyway, and it can be send in the background (in iOS using e.g. GCD). 3. The main backend receives the request about the comment, and starts handling it. It inserts a row in the comments table, perhaps does some other bookkeeping stuff, and then it returns the response to the mobile app. 4. The notification service receives the request about the comment, and inserts a row in a notification table (this is for historical reasons, e.g. to make an Activity view or something like that), and then puts a message on some queue (or on Redis). A separate job takes whatever is on the queue/Redis and handles it (this is where we actually send a request to Apple Push Notification Server and Googles Firebase Service). By not having the HTTP notification service do the talking with these external services it will be easier to scale the HTTP resources. 5. Upon receiving the 200 from the main backend, the mobile app removes the spinner and updates the UI with the submitted comment. Again note that the mobile app does not wait on the second request it send off (it's not like it can do anything if that fails anyway). So this is way more complex. But the main API backend is now only concerned actually saving the comment. The mobile app also needs to send two requests instead of just one, but it doesn't need to wait for the second request. So overall it should giver better performance I think. With regards to the notification service it could be simpler by not using a queue/Redis but just have the notification service call up Apple and Google with the push notifications. But I am thinking that by separating that out into a simple HTTP service that only does some basic bookkeeping stuff and putting stuff on a queue/Redis it can be fast and simple, and the separate job would then do the actual work of calling up Apple and Google. Does it makes sense? Or have I over complicated things? All comments appreciated.
2017/07/07
[ "https://softwareengineering.stackexchange.com/questions/352352", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/219850/" ]
An API is high level enough to expect it to do multiple things with a single action. If I have an endpoint that does a "Buy Product" then I would expect it to handle all of the transaction handling, logging, and updating balances rather than breaking them up into services the client needs to contact individually. You have the right idea of making the push notification a fire and forget operation, but it can be done with a single endpoint on your API. If you use a work queue just make two separate jobs and execute both: wait for one and forget the other.
5,638,321
In my program I'm executing given command and getting result (log, and exit status). Also my program have to support shell specific commands (i.e. commands which contains shell specific characters ~(tild),|(pipe),\*). But when I try to run `sh -c ls | wc` in my home directory via my program it failed and its exit status was 32512, also in stderr stream `"sh: ls | wc: command not found"` was printed. But the interesting thing is that the command `sh -c ls | wc` works correct if I run it in shell. What is the problem? Or more preferable how can I run shell specific commands via my program (i.ec which command with which parameters should I run)? The code part bellow is in child part after fork(). It executs the command. `tokenized_command` is `std::vector<std::string>` where in my case `"sh", "-c", "ls", "|", "wc"` are stored, also I have tried to store there `"sh", "-c", "\"ls | wc\""` but result is same. `command` is `char *` where full command line is stored. ``` boost::shared_array<const char *> bargv(new const char *[tokenized_command.size() + 1]); const char **argv = bargv.get(); for(int i = 0; i < tokenized_command.size(); ++i) { argv[i] = tokenized_command[i].c_str(); printf("argv[%d]: %s\n", i, argv[i]); //trace } argv[tokenized_command.size()] = NULL; if(execvp(argv[0], (char * const *)argv) == -1) { fprintf(stderr, "Failed to execute command %s: %s", command, strerror(errno)); _exit(EXIT_FAILURE); } ``` P.S. I know that using `system(command)` instead `execvp` can solve my problem. But `system()` waits until command is finished, and this is not good enough for my program. And also I'm sure that in implementation of `system()` one of exec-family functions is used, so the problem can be solved via `exec` as well, but I don't know how.
2011/04/12
[ "https://Stackoverflow.com/questions/5638321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509233/" ]
`execvp` takes a path to an executable, and arguments with which to launch that executable. It doesn't take bourne shell commands. `ls | wc` is a bourne shell command (among others), and it can't be broken down into the path to an executable and some arguments due to the use of a pipe. This means it can't be executed using `execvp`. To execute a bourne shell command using `execvp`, one has to execute `sh` and pass `-c` and the command for arguments. So you want to execute `ls | wc` using `execvp`. ``` char *const argv[] = { "sh", "-c", "ls | wc", // Command to execute. NULL }; execvp(argv[0], argv) ``` You apparently tried ``` char *const argv[] = { "sh", "-c", "ls", // Command to execute. "|", // Stored in called sh's $0. "wc", // Stored in called sh's $1. NULL }; ``` That would be the same as bourne shell command `sh -c ls '|' wc`. And both are very different than shell command `sh -c ls | wc`. That would be ``` char *const argv[] = { "sh", "-c", "sh -c ls | wc", // Command to execute. NULL }; ``` You seem to think `|` and `wc` are passed to the `sh`, but that's not the case at all. `|` is a special character which results in a pipe, not an argument. --- As for the exit code, ``` Bits 15-8 = Exit code. Bit 7 = 1 if a core dump was produced. Bits 6-0 = Signal number that killed the process. ``` 32512 = 0x7F00 So it didn't die from a signal, a core dump wasn't produced, and it exited with code 127 (0x7F). What 127 means is unclear, which is why it should accompanied by an error message. You tried to execute program `ls | wc`, but there is no such program.
27,097,703
> > Error: System.Net.Mail.SmtpException: Failure sending mail. ---> System.ArgumentException: The IAsyncResult object was not returned from the corresponding asynchronous method on this class. Parameter name: asyncResult at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result) --- End of inner exception stack trace --- > > > ``` private void DispatchMail(MailMessage message, MessageTrackerObject trackInfo) { SmtpClient mailClient = new SmtpClient(); mailClient.Host = ConfigurationManager.AppSettings[(Constants.FAXSETTINGS_SMTPSERVER)]; mailClient.Port = int.Parse(ConfigurationManager.AppSettings[(Constants.FAXSETTINGS_SMTPPORT)]); //mailClient.DeliveryMethod = SmtpDeliveryMethod.Network; NetworkCredential ntCredential = new NetworkCredential(); if (GetStaticSetting(Constants.APPCONFIG_KEY_MAILWINDOWSAUTH).ToLower() == "true") { //mailClient.UseDefaultCredentials = true; } else { ntCredential.UserName = GetStaticSetting(Constants.APPCONFIG_KEY_MAILUSERID); ntCredential.Password = GetStaticSetting(Constants.APPCONFIG_KEY_MAILPASSWORD); mailClient.Credentials = ntCredential; mailClient.UseDefaultCredentials = false; } mailClient.EnableSsl = GetStaticSetting(Constants.APPCONFIG_KEY_MAIL_SSL).ToLower() == "true"; mailClient.SendCompleted += new SendCompletedEventHandler(MailClient_SendCompleted); mailClient.SendAsync(message, trackInfo); //mailClient.Send(message); } private void MailClient_SendCompleted(object sender, AsyncCompletedEventArgs e) { string error = ""; MessageTrackerObject data = (MessageTrackerObject)e.UserState; string msg = string.Format("File: {0}", data.Info); try { foreach (string serial in data.Serials) { if (e.Cancelled) { error = e.Error != null ? String.Format(" #Error: {0}", e.Error.ToString()) : ""; string cancelled = string.Format("{0} Send canceled. {1}", msg, error); SetFaxStatus(serial, FaxStatus.Cancelled, cancelled); } else if (e.Error != null) { error = String.Format("{0} #Error: {1}", msg, e.Error.ToString()); SetFaxStatus(serial, FaxStatus.Error, error); } else { SetFaxStatus(serial, FaxStatus.Sent, string.Format("{0} Mail sent successfully.", msg)); } } //release resource data.Message.Dispose(); } catch (Exception ex) { } } ``` How can i avoid this error?
2014/11/24
[ "https://Stackoverflow.com/questions/27097703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3332414/" ]
Most probably the problem here is that the same instance of `MailMessage` is passed to `DispatchMail`. `MailMessage` is not thread-safe by design, and each `SmtpClient.SendAsync` is internally invoking `Message.BeginSend`. So, when several threads are attempting to send same `MailMessage`, there is a race condition when calling `Message.EndSend`. If `EndSend` is invoked by the same thread which called `BeginSend` - we are in luck. If not - exception from above is raised, > > The IAsyncResult object was not returned from the corresponding > asynchronous method on this class > > > Solution here is either to copy `MailMessage` for each call of `SendAsync`, or use `SendAsync` overload which accepts 5 parameters: ``` void SendAsync(string from, string recipients, string subject, string body, object token) ``` Edit: This exception is very easy to reproduce, to prove that MailMessage is not thread-safe. You may get several exceptions, `IAsyncResult` one from above, or `Item has already been added` when populating headers: ``` using System; using System.Net.Mail; using System.Threading.Tasks; class App { static void Main() { var mail = new MailMessage("[email protected]", "[email protected]", "Test Subj", "Test Body"); var client1 = new SmtpClient("localhost"); var client2 = new SmtpClient("localhost"); var task1 = client1.SendMailAsync(mail); var task2 = client2.SendMailAsync(mail); Task.WhenAll(task1, task2).Wait(); } } ```
60,248,125
I have this simple code: ``` $postCopy = $_POST['adminpanel']; array_walk($postCopy, function($v, $k) { return ''; }); ``` I did `var_dump` for `postCopy` before and after `array_walk` execution. In both `var_dump` executions, I get the same result: ``` array(2) { ["usefulinfo_countryfilescount"]=> string(1) "3" ["strageticoverviews_filesinpagecount"]=> string(1) "3" } ``` So it means that `array_walk` didn't execute correctly, because if it would- I'd get an array with `''` values...
2020/02/16
[ "https://Stackoverflow.com/questions/60248125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870867/" ]
You just forgot to pass argument by reference : ``` $postCopy = $_POST['adminpanel']; array_walk($postCopy, function(&$v, $k) { $v = ''; }); ```
54,338,297
How can I run a task from the command line for long-running jobs like reports from Jenkins in Spring Boot? I'm looking for something similar to Ruby on Rails Rake tasks. Rake tasks execute the code from the command line in the same application context as the web server so that you can re-use code. * I found [Spring Batch](https://spring.io/projects/spring-batch#overview) but it sounded more like [Resque](https://github.com/resque/resque). * I found [command line runners](https://therealdanvega.com/blog/2017/04/07/spring-boot-command-line-runner) but it said that they all run before the web server starts, so I can't *not* run it or only run one task. * I found [scheduled tasks](https://spring.io/guides/gs/scheduling-tasks/) which sounds *perfect*, but my app is load balanced with many instances so I would not want it running multiple times at once! I have a report where the query takes more than 30s to run, and generates a CSV file I would like to mail. I want it to run automatically each week with cron or Jenkins.
2019/01/24
[ "https://Stackoverflow.com/questions/54338297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148844/" ]
I hacked a solution. Suggestions welcome. ``` package com.example.tasks; @Component public class WeeklyReport implements CommandLineRunner { @Override public void run(String... args) throws Exception { Arrays.asList(args).stream().forEach(a -> System.out.println(a)); if (!(args.length > 0 && args[0].equals("-task report:weekly"))) return; System.out.println("weekly report"); System.exit(0); } ``` And running it from a 'cron' job with ``` $ mvn spring-boot:run -Drun.arguments="-task report:weekly" ``` <https://docs.spring.io/spring-boot/docs/1.5.19.RELEASE/reference/htmlsingle/#boot-features-command-line-runner> <https://www.baeldung.com/spring-boot-command-line-arguments> <https://therealdanvega.com/blog/2017/04/07/spring-boot-command-line-runner>
10,271,293
So I've been doing things with LINQ lately and I've been looking online for a complete list of all integrated LINQ keywords and i couldn't find any. These are some of the ones i know: ``` from in let group by into orderby where select ``` Are there any others that I don't know about? Where can I go to find a complete list of all the things possible with integrated LINQ?
2012/04/22
[ "https://Stackoverflow.com/questions/10271293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184746/" ]
You need to distinguish in your mind between the [*standard LINQ query operators*](http://msdn.microsoft.com/en-us/library/bb397896.aspx) and the operators that are supported in C# by [*query expressions*](http://msdn.microsoft.com/en-us/library/bb397676.aspx). There are far more of the former than the latter - and VB supports some of them in the language directly. For quite a bit of detail about all the different operators, and which query expression parts bind to them, you may want to read my [Edulinq blog post series](http://codeblog.jonskeet.uk/category/edulinq/). It's a reimplementation of LINQ to Objects for educational purposes, looking at how each operator behaves etc. [Part 41](http://codeblog.jonskeet.uk/2011/01/28/reimplementing-linq-to-objects-part-41-how-query-expressions-work/) is explicitly about query expressions, including a cheat sheet at the bottom.
29,108,950
I'm trying to draw text to a canvas with a certain alpha level and clip the text and draw a background color with it's own alpha level: ``` ctx.globalCompositeOperation = '...'; ctx.fillStyle = 'rgba(' + fgcolor.r + ', ' + fgcolor.g + ', ' + fgcolor.b + ',' + (fgcolor.a / 255.0) + ')'; ctx.fillText(String.fromCharCode(chr), x,y); ctx.globalCompositeOperation = '...'; ctx.fillStyle = 'rgba(' + bgcolor.r + ', ' + bgcolor.g + ', ' + bgcolor.b + ',' + (bgcolor.a / 255.0) + ')'; ctx.fillRect(x, y, chr_width, chr_height); ``` I've tried playing with globalCompositeOperation and beginPath but I have been unable to achieve the desired result. I would also like to avoid drawImage and off screen canvases as speed is a major concern.
2015/03/17
[ "https://Stackoverflow.com/questions/29108950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/806771/" ]
This function will convert RGBA colors to RGB: ``` function RGBAtoRGB(r, g, b, a, backgroundR,backgroundG,backgroundB){ var r3 = Math.round(((1 - a) * backgroundR) + (a * r)) var g3 = Math.round(((1 - a) * backgroundG) + (a * g)) var b3 = Math.round(((1 - a) * backgroundB) + (a * b)) return "rgb("+r3+","+g3+","+b3+")"; } ``` 1. Convert the background RGBA to RGB and fill the background with RGB. 2. Convert the foreground RGBA to RGB and fill the foreground text with RGB.
7,506,475
I am new to creating installers. Before used the Microsoft visual studio deployment package. Now trying inno setup, pretty awesome. I saw that Visual studio one wrote some registries when installed. Do I have to create Registries for my package too? I have a visual c# application and need to create a installer for my company. Main intention is to create a installer that will easily update the old one, but this is a first version of software we are going to release to customers. Much appreciated. I saw tutorials of Registry in internet, but the point of creating is the one that I don't understand.
2011/09/21
[ "https://Stackoverflow.com/questions/7506475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821332/" ]
You don't HAVE to write any registry entries unless your app requires them. Inno automatically creates the usual entries to allow uninstall from the Add/Remove programs applet. Inno will also automatically handle [upgrades](http://www.vincenzo.net/isxkb/index.php?title=Upgrades) with no special effort. If you have previously distributed the app using an MSI package, then you will either need to allow side by side installs (different folders, etc) or uninstall the previous version first. The article above has a sample of how to get the uninstall path.
20,788,467
I want to go to a specific section of my website when I click on the link in the menu bar for that section of the website, so you do not have to scroll through all the content, but to have links to the different sections. I've read that you can do this with jQuery and make an animation for it so that the page can smoothly go to that section of the website. Here's the **HTML** code: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script type="text/javascript" src="java.js"></script> <head> <link rel="stylesheet" href="css/style.css" type="text/css"/> <title>Test Website</title> <meta name="" content=""> <script type="text/javascript"> </script> </head> <body> <header> <div id="title"> <h1 class="headertext">My Test Website</h1> </div> <div id="menubar"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> </div> </header> <div class="hide"> </div> <div id="container"> <div id="leftmenu"> <ul> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> <li><a href="index.html">Homepage</a></li> </ul> <div id="triangle"></div> </div> <div id="content"> <h1>Contentpage</h1></br> Picture slideshow </br> </br> <div class="slider"> <img id="1" src="images/car1.jpg" border="0" alt="car1"/> <img id="2" src="images/car2.jpg" border="0" alt="car2"/> <img id="3" src="images/car3.jpg" border="0" alt="car3"/> <img id="4" src="images/car4.jpg" border="0" alt="car4"/> <img id="5" src="images/car5.jpg" border="0" alt="car5"/> </div><!--slider end--> <div class="shadow"></div> <div class="borderbottom"></div> </div><!--content div--> </div> </body> </html> ``` And here is the **CSS** code: ``` *{ margin: 0 auto 0 auto; text-align: left; color: #ffffff; } body{ margin: 0; text-align: left; font-size: 13px; font-family: arial, helvetica, sens-serif; color: #ffffff; width: 1200px; height: auto; background: #f4f4f4; } header { position: fixed; width: 100%; top: 0; background: rgba(0,0,0,.8); z-index: 10; } h1{ color: black; text-align: center; } .hide { position: fixed; width: 100%; top: 0; background: rgba(255,255,255,1); z-index:5; height: 123px; } .headertext{ margin-top: 15px; text-align: center; color: white; } #title{ font-size: 20px; margin: -10px 0 30px 0; width: 100%; height: 70px; border-top: 2px solid #000000; border-bottom: 2px solid #000000; } #menubar{ margin-top: 10px; float: left; clear: both; width: 100%; height: 20px; list-style: none; border-bottom: 2px solid #010000; } #menubar ul{ list-style: none; margin-top: -15px; text-align: center; } #menubar ul li{ list-style: none; display: inline; padding-right: 80px; } #menubar ul li a{ color: #ffffff; text-decoration: none; font-size: 15px; font-weight: bold; } #menubar ul li a:hover{ border-bottom: 2px solid #ffffff; } #container{ width: 1200px; height: 1400px; } #leftmenu{ position: fixed; margin-top: 123px; margin-left: 50px; padding-top: 20px; float: left; width: 160px; height: 350px; list-style: none; background: rgba(0,0,0,0.8); color: #ffffff; border-left: 2px solid #010000; border-right: 2px solid #010000; } #leftmenu ul li{ display: block; padding-bottom: 50px; } #leftmenu ul li a{ font-weight: bold; text-decoration: none; color: #ffffff; font-size: 15px; text-align: center; } #leftmenu ul li a:hover{ border-bottom: 2px solid #ffffff; transition: opacity .5s ease-in; opacity: 1; } #triangle{ margin-top: 12px; margin-left: -1px; width: 0px; height: 0; border-top: 80px solid rgba(0,0,0,0.8); border-left: 82px solid transparent; border-right: 82px solid transparent; } #content{ text-align: left; margin-left: 100px; width: 1000px; padding-top: 150px; padding-left: 160px; color: #000000; font-weight: bold; text-align: center; font-size: 15px; } .slider{ margin-top: 20px; width: 600px; height: 400px; overflow: hidden; margin: auto; border-radius: 10px; vertical-align: middle; } .shadow{ background-image:url(../images/shadow.png); background-repeat: no-repeat; background-position: top; width: 850px; height: 144px; vertical-align: middle; margin-top: -50px; } .slider img{ width: 600px; height: 400px; display: none; } .borderbottom{ border: 6px solid rgba(0,0,0,0.8); border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; width: 1000px; position: fixed; margin-top: 20px; } ```
2013/12/26
[ "https://Stackoverflow.com/questions/20788467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123507/" ]
If you have jQuery loaded you could try like this, no plugin required just jquery will do... HTML: ``` <div id="menubar"> <ul> <li><a href="#somediv">Homepage</a></li> <li><a href="#somediv">Homepage</a></li> <li><a href="#somediv">Homepage</a></li> ........all the menu items------- </ul> ``` JS: ``` $('#menubar ul li a').on('click',function(event){ var $anchor = $(this); $('html, body').animate({ scrollTop: $($anchor.attr('href')).offset().top + "px" }, 1500); event.preventDefault(); }); ``` This is the working [fiddle](http://jsfiddle.net/YJwTJ/3)
58,610,203
I try to limit access to a REST API using a JWT token using the `validate-jwt` policy. Never did that before. Here's my inbound policy (taken from the point **Simple token validation** [here](https://learn.microsoft.com/en-us/azure/api-management/api-management-access-restriction-policies?redirectedfrom=MSDN#ValidateJWT)): ``` <validate-jwt header-name="Authorization" require-scheme="Bearer"> <issuer-signing-keys> <key>{{jwt-signing-key}}</key> </issuer-signing-keys> <audiences> <audience>CustomerNameNotDns</audience> </audiences> <issuers> <issuer>MyCompanyNameNotDns</issuer> </issuers> </validate-jwt> ``` Using [this generator](http://jwtbuilder.jamiekurtz.com/) I created a claim (I'm not sure whether I understood issuer and audience correctly): ``` { "iss": "MyCompanyNameNotDns", "iat": 1572360380, "exp": 2361278784, "aud": "CustomerNameNotDns", "sub": "Auth" } ``` In the section **Signed JSON Web Token** I picked **Generate 64-bit key** from the combo box. The key that was generated I put in the place of **{{jwt-signing-key}}**. Now, I'm trying to call the API using Postman. I add an "Authorization" header, and as the value I put "Bearer {{ JWT created by the [linked generator](http://jwtbuilder.jamiekurtz.com/) }}". I get 401, JWT not present. What am I doing wrong?
2019/10/29
[ "https://Stackoverflow.com/questions/58610203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693915/" ]
According to my research, If you use HS256 signing algorithms, the key must be provided inline within the policy in the base64 encoded form. In other words, we must encode the key as base64 string. For more details, please refer to the [document](https://learn.microsoft.com/en-us/azure/api-management/api-management-access-restriction-policies#ValidateJWT) [![enter image description here](https://i.stack.imgur.com/ySPGw.png)](https://i.stack.imgur.com/ySPGw.png) My test steps are as below 1. Create Jwt token [![enter image description here](https://i.stack.imgur.com/6W6Vr.png)](https://i.stack.imgur.com/6W6Vr.png) [![enter image description here](https://i.stack.imgur.com/i1etp.png)](https://i.stack.imgur.com/i1etp.png) 2. Test a. If I directly provide the key in the policy, I get the 401 error [![enter image description here](https://i.stack.imgur.com/xebIY.png)](https://i.stack.imgur.com/xebIY.png) [![enter image description here](https://i.stack.imgur.com/6adLp.png)](https://i.stack.imgur.com/6adLp.png) b. If I encode the key as base64 string in the policy, I can call the api [![enter image description here](https://i.stack.imgur.com/3o9AB.png)](https://i.stack.imgur.com/3o9AB.png) [![enter image description here](https://i.stack.imgur.com/h5fcM.png)](https://i.stack.imgur.com/h5fcM.png)
70,102,930
I must to convert the 4 column to upper case with only one sed command. ``` user,gender,age,native_lang,other_lang 0,M,19,finnish,english swedish german 1,M,30,urdu,english 2,F,26,finnish,english swedish german 3,M,20,finnish,english french swedish 4,F,20,finnish,english swedish ``` This it's my best movement but change all columns. ``` sed -e 's/\(.*\)/\U\1/' ``` I really want understand the command, but I really lose myself why use" \ " or how to read it.
2021/11/24
[ "https://Stackoverflow.com/questions/70102930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16356062/" ]
You can use ```sh sed 's/^\(\([^,]*,\)\{3\}\)\([^,]*\)/\1\U\3/' # POSIX BRE sed -E 's/^(([^,]*,){3})([^,]*)/\1\U\3/' # POSIX ERE ``` See [an online demo](https://ideone.com/dGppHs): ```sh s='user,gender,age,native_lang,other_lang 0,M,19,finnish,english swedish german 1,M,30,urdu,english 2,F,26,finnish,english swedish german 3,M,20,finnish,english french swedish 4,F,20,finnish,english swedish ' sed 's/^\(\([^,]*,\)\{3\}\)\([^,]*\)/\1\U\3/' <<< "$s" ``` Output: ``` user,gender,age,NATIVE_LANG,other_lang 0,M,19,FINNISH,english swedish german 1,M,30,URDU,english 2,F,26,FINNISH,english swedish german 3,M,20,FINNISH,english french swedish 4,F,20,FINNISH,english swedish ``` *Details*: * `^` - start of string * `(([^,]*,){3})` - Group 1: three repetitions of any zero or more chars other than a comma and then a comma * `([^,]*)` - Group 3: zero or more chars other than a comma.
25,709,429
In my Qt app I'm trying to pass a large integer value from my C++ code to QML. In my C++ I have a Q\_PROPERTY(int ...), but apparently int sometimes isn't enough for my app and I get an overflow. Can I use long types or unsigned types in QML? How about dynamically sized int types? From the QML documentation all I could find was int with a range of "around -2000000000 to around 2000000000". Any help is appreciated! =)
2014/09/07
[ "https://Stackoverflow.com/questions/25709429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246924/" ]
I find your question interesting because it looks trivial initially, and though raises many points in the way to get an answer. I assume that you want to pass a 64 bit integer from C++ to QML. I explain later why. QML basic type for a 64 bit integer =================================== There is no 64 bit integral [QML basic type](http://doc.qt.io/qt-5/qtqml-typesystem-basictypes.html), therefore you cannot expect your C++ value to be converted and stored in such a non-existing QML type property. As stated in the documentation, Qt modules can extend the list of available types. We can even think of a future where we could add our own types, but not nowadays : > > Currently only QML modules which are provided by Qt may provide their > own basic types, however this may change in future releases of Qt QML. > > > One may think that having their application compiled in a 64 bit platform should do the job, but it won't change a thing. There is [a lot of answers](https://stackoverflow.com/questions/589575/what-does-the-c-standard-state-the-size-of-int-long-type-to-be) about this question. To make it obvious, here is a comparison of the results using a 32 bit and a 64 bit compiler on the same computer : On my computer (64 bit processor : Core i7) with a 64 bit system (Windows 7 64 bit) using a 32 bit compiler (mingw53), I've got ``` 4 = sizeof(int) = sizeof(long) = sizeof(int*) = sizeof(size_t) ``` I've put `size_t` to make it clear it cannot be used to denote a file size, it's not [its purpose](http://en.cppreference.com/w/cpp/types/size_t). With a 64 bit compiler (msvc2017, x64), on the same system : ``` 4 = sizeof(int) = sizeof(long) 8 = sizeof(int*) = sizeof(size_t) ``` Using a 64 bit compiler did not change `sizeof(int)`, so thinking of an `int` to be the same size of an `int*` is obviously wrong. In your case, it appears that you want to store a file size and that 32 bits weren't enough to represent the size of a file. So if we cannot rely on an `int` to do it, what type should be used ? File size type size =================== For now, I assumed that a 64 bit integer should be enough and the right way to store a file size. But is it true ? According to cplusplus.com, the type for this is [std::streampos](http://www.cplusplus.com/doc/tutorial/files/). If you look for details on cppreference.com you find that `std::streampos` is a specialization of `std::fpos` and a description of its *typical* implementation : > > Specializations of the class template `std::fpos` identify absolute > positions in a stream or in a file. Each object of type `fpos` holds the > byte position in the stream (typically as a private member of type > `std::streamoff`) and the current shift state, a value of type `State` > (typically `std::mbstate_t`). > > > And the actual type of a [std::streamoff](http://en.cppreference.com/w/cpp/io/streamoff) is *probably* a 64 bit signed integer : > > The type `std::streamoff` is a signed integral type of sufficient size > to represent the maximum possible file size supported by the operating > system. Typically, this is a `typedef` to `long long`. > > > In addition, in the same page, you can read that : > > a value of type `std::fpos` is implicitly convertible to `std::streamoff` (the conversion result is the offset from the beginning > of the file). > > > a value of type `std::fpos` is constructible from a value of type `std::streamoff` > > > Let's look at what we have, again depending on the 32 or 64 bit target platform. Using a 32 bit compiler I've got ``` 8 = sizeof(long long) = sizeof(std::streamoff) 16 = sizeof(std::streampos) ``` It shows that, obviously, more information than is currently necessary to know a file size is stored in a `std::streampos`. With a 64 bit compiler, on the same system : ``` 8 = sizeof(long long) = sizeof(std::streamoff) 24 = sizeof(std::streampos) ``` Value of `sizeof(std::streamoff)` did not change. It may have. In both cases, it had to be large enough in order to store a file size. You may want to use `std::streamoff` to store the file size on the C++ side. You cannot rely on it being 64 bit. Let's assume that one wants to take the risk of making the assumption that it is 64 bit, as shown in these examples : still remains the problem of passing it to the QML as a basic type and, maybe, to the Javascript engine. Nevertheless using a near-64 bit in QML ======================================= If you just need to display the size as a number in bytes, you'll need a text representation in the UI. You can stick with this idea, use a string, and forget about passing an integral value. If you need to do arithmetic on the QML side, using Javascript, you'll probably hit the [53 bit barrier](http://www.ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) of the Javascript `Number` unless you do not use the core language to do the arithmetic. Here, if you make the assumption that a file size cannot be greater than 2^53, then using a `double` could work. You have to know how `double` type is handled on your target platforms as stated in [this answer](https://stackoverflow.com/a/1848761/4706859), and if you're lucky enough, it will have the same ability to store with no loss a 53 bit integral value. You can manipulate it directly in Javascript after, and this is guaranteed to work, at least in ECMA 262 version 8. So is it OK, now ? Can we use doubles for any file size lower than 2^53 ? Well… Qt does not necessarily implement the latest specification of ECMAScript and uses [several implementations](http://doc.qt.io/qt-5/topics-scripting.html). In Webviews, it does use a [rather common implementation](https://doc.qt.io/qt-5/qtwebengine-3rdparty-v8-javascript-engine.html). In QML, it uses its own, undocumented, built-in Javascript engine, based on ECMA 262 version 5. This version of ECMA does not explicitely mention a value for which all smaller integral values are guaranteed to be stored in a `Number`. That does not mean it won't work. Even if it had been mentionned, the implementation is only *based on* the specification and does not claim for compliance. You may find yourself in the unlucky position to have it working for a long time, and then discover that it does not anymore, in a newer release of Qt. It looks like a lot of assumptions have to be made. All of them may be and may remain true during the whole life of the software based on it. So it is a matter of dealing with a risk. Is there a way to lower that risk for one that would want to? Not risking a bit of correctness for a few bits =============================================== I see two main paths : * not bothering with all this stuff at all. Using a double for instance, and doing whatever you want as long as it seems to work. If it's not working for cases that do not happen, why trying to handle them ? When it does not work, you'll deal with it. * trying to be rigorous, and to do it the more robust way. As far as I understand, a solution of this kind could be to keep all the file size arithmetics on the C++ side and passing only safe values to the QML side. For instance boolean values for testing and strings for displaying the value of the sizes (total size, remaining size, …). You do not need to worry about how many bits there is in anything. An hint : the [bittorent protocol](http://www.bittorrent.org/beps/bep_0003.html) uses strings to encode sizes. The problem not limited to QML properties ========================================= The same problem may arise if you use Javascript to manipulate integral values with a `Number` instance, and use it as argument to an `int` parameter of a QML signal. For instance, declaring a signal like this : ``` signal sizeChanged(var newSize) // Number class (maybe 53 bit) integral value possible ``` may handle cases that the following certainly cannot : ``` signal sizeChanged(int newSize) // 32 bit int limitation ``` An example of failure is to pass `(new Date()).getTime()`. It is the same limitation that is not restricted to C++ property interactions with QML.
12,964,240
So I've recently setup a LEMP server and have managed to work may way through some of the configurations. I'm now to the point where I can begin writing php scripts and building basic pages. Looking at the [php5-fpm wiki](http://php-fpm.org/wiki/Main_Page) there aren't any pages discussing any changes I should expect as far as php scripts and such are concerned, only installation/configuration settings. Is everything beyond the installation/configurations steps business as usual? From the point of view of a php developer what changes should I expect/make? How can best take advantage of the fpm version (in the php code, not module/system configurations)? I'm focused on comparing well-written php in both cases.
2012/10/18
[ "https://Stackoverflow.com/questions/12964240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558546/" ]
When I made the switch myself, I got to know a few perks about this kind of setup, such as APC file upload progress does not work out of the box (and you're better off using something else, such as nginx-progress-upload and/or JS File API); Some header names might have changed (prepending HTTP\_); and a new and very useful function called `fastcgi_finish_request`. For more information, though, look around the [PHP-FPM Manual](http://php.net/manual/en/install.fpm.php).
57,827,842
I have around 10k `.bytes` files in my directory and I want to use count vectorizer to get n\_gram counts (i.e fit on train and transform on test set). In those 10k files I have 8k files as train and 2k as test. ``` files = ['bfiles/GhHS0zL9cgNXFK6j1dIJ.bytes', 'bfiles/8qCPkhNr1KJaGtZ35pBc.bytes', 'bfiles/bLGq2tnA8CuxsF4Py9RO.bytes', 'bfiles/C0uidNjwV8lrPgzt1JSG.bytes', 'bfiles/IHiArX1xcBZgv69o4s0a.bytes', ............................... ...............................] print(open(files[0]).read()) 'A4 AC 4A 00 AC 4F 00 00 51 EC 48 00 57 7F 45 00 2D 4B 42 45 E9 77 51 4D 89 1D 19 40 30 01 89 45 E7 D9 F6 47 E7 59 75 49 1F ....' ``` I can't do something like below and pass everything to `CountVectorizer`. ``` file_content = [] for file in file: file_content.append(open(file).read()) ``` I can't append each file text to a big nested lists of files and then use `CountVectorizer` because the all combined text file size exceeds 150gb. I don't have resources to do that because `CountVectorizer` use huge amount of memory. I need a more efficient way of solving this, Is there some other way I can achieve what I want without loading everything into memory at once. Any help is much appreciated. All I could achieve was read one file and then use `CountVectorizer` but I don't know how to achieve what I'm looking for. ``` cv = CountVectorizer(ngram_range=(1, 4)) temp = cv.fit_transform([open(files[0]).read()]) temp <1x451500 sparse matrix of type '<class 'numpy.int64'>' with 335961 stored elements in Compressed Sparse Row format> ```
2019/09/06
[ "https://Stackoverflow.com/questions/57827842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11816060/" ]
You can build a solution using the following flow: 1) Loop through you files and create a set of all tokens in your files. In the example below this is done using Counter, but you can use python sets to achieve the same result. The bonus here is that Counter will also give you the total number of occurrences of each term. 2) Fit CountVectorizer with the set/list of tokens. You can instantiate CountVectorizer with ngram\_range=(1, 4). Below this is avoided in order to limit the number of features in df\_new\_data. 3) Transform new data as usual. The example below works on small data. I hope you can adapt the code to suit your needs. ``` import glob import pandas as pd import numpy as np from collections import Counter from sklearn.feature_extraction.text import CountVectorizer # Create a list of file names pattern = 'C:\\Bytes\\*.csv' csv_files = glob.glob(pattern) # Instantiate Counter and loop through the files chunk by chunk # to create a dictionary of all tokens and their number of occurrence counter = Counter() c_size = 1000 for file in csv_files: for chunk in pd.read_csv(file, chunksize=c_size, index_col=0, header=None): counter.update(chunk[1]) # Fit the CountVectorizer to the counter keys vectorizer = CountVectorizer(lowercase=False) vectorizer.fit(list(counter.keys())) # Loop through your files chunk by chunk and accummulate the counts counts = np.zeros((1, len(vectorizer.get_feature_names()))) for file in csv_files: for chunk in pd.read_csv(file, chunksize=c_size, index_col=0, header=None): new_counts = vectorizer.transform(chunk[1]) counts += new_counts.A.sum(axis=0) # Generate a data frame with the total counts df_new_data = pd.DataFrame(counts, columns=vectorizer.get_feature_names()) df_new_data Out[266]: 00 01 0A 0B 10 11 1A 1B A0 A1 \ 0 258.0 228.0 286.0 251.0 235.0 273.0 259.0 249.0 232.0 233.0 AA AB B0 B1 BA BB 0 248.0 227.0 251.0 254.0 255.0 261.0 ``` Code for the generation of the data: ``` import numpy as np import pandas as pd def gen_data(n): numbers = list('01') letters = list('AB') numlet = numbers + letters x = np.random.choice(numlet, size=n) y = np.random.choice(numlet, size=n) df = pd.DataFrame({'X': x, 'Y': y}) return df.sum(axis=1) n = 2000 df_1 = gen_data(n) df_2 = gen_data(n) df_1.to_csv('C:\\Bytes\\df_1.csv') df_2.to_csv('C:\\Bytes\\df_2.csv') df_1.head() Out[218]: 0 10 1 01 2 A1 3 AB 4 1A dtype: object ```
1,462,272
$x^2-(2+i)x+(-1+7i)=0$ I tried to solve it and I got stuck here: $x=(2+i)±\sqrt{\frac{7-24i}{2}}$
2015/10/03
[ "https://math.stackexchange.com/questions/1462272", "https://math.stackexchange.com", "https://math.stackexchange.com/users/276466/" ]
Firstly, you correctly found the discriminant: $$D = B^2 - 4AC = [-(2+i)]^2-4(-1+7i) = 7 - 24i.$$ Then: $$x\_{1,2} = \frac{-B\pm \sqrt{D}}{2A}=\frac{2+i\pm\sqrt{7-24i}}{2}.\tag{1}$$ But: $$\sqrt{7-24i}=\pm(4-3i).$$ Why? Let $\sqrt{7-24i} = z\implies z^2 = 7-24i$. If we let $z = a+bi \implies a^2-b^2 +2ab i = 7-24i $. Thus: $$\left\{ \begin{array}{l} a^2 - b^2 = 7\\ ab = -12 \end{array} \right. $$ Solving the above system in Reals, we get 2 pairs of solutions: $(a,b) = (4,-3)$ and $(a,b) = (-4,3)$. Both $z\_1 = 4-3i$ and $z\_2 = -4+3i$ satisfy the equation $z^2 = 7-24i$. No matter the choice we make for $\sqrt{27-4i}$ (either $4-3i$ or $-4+3i$), the solutions given by the quadratic formula will be the same, due to the "$\pm$ sign" in the numerator. Apply this to $(1)$ and you will get the result.
4,889,998
I have the following problem with excel. I want to increase a variable by one without using a function. So i mean without writing a "=" before my expression. Example: B1.c\_O2\_L\_y.Value(i) B1.c\_O2\_L\_y.Value(1) B1.c\_O2\_L\_y.Value(2) B1.c\_O2\_L\_y.Value(3) B1.c\_O2\_L\_y.Value(4) B1.c\_O2\_L\_y.Value(5) B1.c\_O2\_L\_y.Value(6) B1.c\_O2\_L\_y.Value(7) B1.c\_O2\_L\_y.Value(8) B1.c\_O2\_L\_y.Value(9) B1.c\_O2\_L\_y.Value(10) B1.c\_O2\_L\_y.Value(11) B1.c\_O2\_L\_y.Value(12) ....... I must do that for many expressions and for i > 500. So i can't do that by hand. I would be thankful for any advice.
2011/02/03
[ "https://Stackoverflow.com/questions/4889998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483859/" ]
How do you want to combine `dat1` and `dat2`? By rows or columns? I'd take a look at the help pages for `rbind()` (row bind) , `cbind()` (column bind), or`c()` which combines arguments to form a vector.
67,633,031
I currently have a table with a quantity in it. | ID | Code | Quantity | | --- | --- | --- | | 1 | A | 1 | | 2 | B | 3 | | 3 | C | 2 | | 4 | D | 1 | Is there anyway to get this table? | ID | Code | Quantity | | --- | --- | --- | | 1 | A | 1 | | 2 | B | 1 | | 2 | B | 1 | | 2 | B | 1 | | 3 | C | 1 | | 3 | C | 1 | | 4 | D | 1 | I need to break out the quantity and have that many number of rows. Thanks!!!!
2021/05/21
[ "https://Stackoverflow.com/questions/67633031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15989969/" ]
**Updated** Now we have stored the separated, collapsed values into a new column: ``` library(dplyr) library(tidyr) df %>% group_by(ID) %>% uncount(Quantity, .remove = FALSE) %>% mutate(NewQ = 1) # A tibble: 7 x 4 # Groups: ID [4] ID Code Quantity NewQ <int> <chr> <int> <dbl> 1 1 A 1 1 2 2 B 3 1 3 2 B 3 1 4 2 B 3 1 5 3 C 2 1 6 3 C 2 1 7 4 D 1 1 ``` **Updated** In case we opt not to replace the existing `Quantity` column with the collapsed values. ``` df %>% group_by(ID) %>% mutate(NewQ = ifelse(Quantity != 1, paste(rep(1, Quantity), collapse = ", "), as.character(Quantity))) %>% separate_rows(NewQ) %>% mutate(NewQ = as.numeric(NewQ)) # A tibble: 7 x 4 # Groups: ID [4] ID Code Quantity NewQ <int> <chr> <int> <dbl> 1 1 A 1 1 2 2 B 3 1 3 2 B 3 1 4 2 B 3 1 5 3 C 2 1 6 3 C 2 1 7 4 D 1 1 ```
46,013
I want to set the frame title as follows: * When the current buffer is visiting a file, show the full path name and the Emacs version. * When the current buffer has no file, then show the buffer name and the Emacs version. In my `init.el`, I put ``` (setq-default frame-title-format (concat (if (buffer-file-name) "%f" "%b") " - " (substring (emacs-version) 0 15))) ``` But here is the result:[![screenshot with the title containing a file name without the full path](https://i.stack.imgur.com/K8Vim.png)](https://i.stack.imgur.com/K8Vim.png) Why doesn't my code print the file name with the full path?
2018/11/15
[ "https://emacs.stackexchange.com/questions/46013", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/16006/" ]
Because you're setting `frame-title-format` to `"%b - GNU Emacs 26.1 "`. You can try the following instead ``` (setq frame-title-format `((buffer-file-name "%f" "%b") ,(format " - GNU Emacs %s" emacs-version))) ``` The following does the same but it probably does some unneeded work (that is, computing the version string) repeatedly ``` (setq frame-title-format (list '(buffer-file-name "%f" "%b") '(:eval (format " - GNU Emacs %s" emacs-version)))) ```
34,410,662
I have a service tax calculation in my page.For that i have to get the current service tax. Service Tax table is as follows ``` Date Percentage 2015-10-01 00:00:00.000 14 2015-11-15 06:12:31.687 14.5 ``` Say if the current date is `less than 2015-11-15` I will get the the value of `percentage` as `14` and if the current date is `equal to or greater than 2015-11-15` i should get the value of `percentage` as `14.5` . How can I implement this using `Linq`??
2015/12/22
[ "https://Stackoverflow.com/questions/34410662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/958396/" ]
You need to get all taxes which are lower and fetch only first after sorting: ``` Taxes .Where(t => t.Date < DateTime.Now) .OrderByDescending(t => t.Date) .First() ```
183,870
What's the difference between `.bashrc` and `.bash_profile` and which one should I use?
2010/09/02
[ "https://superuser.com/questions/183870", "https://superuser.com", "https://superuser.com/users/12461/" ]
Traditionally, when you log into a Unix system, the system would start one program for you. That program is a shell, i.e., a program designed to start other programs. It's a command line shell: you start another program by typing its name. The default shell, a Bourne shell, reads commands from `~/.profile` when it is invoked as the login shell. Bash is a Bourne-like shell. It reads commands from `~/.bash_profile` when it is invoked as the login shell, and if that file doesn't exist¹, it tries reading `~/.profile` instead. You can invoke a shell directly at any time, for example by launching a terminal emulator inside a GUI environment. If the shell is not a login shell, it doesn't read `~/.profile`. When you start bash as an interactive shell (i.e., not to run a script), it reads `~/.bashrc` (except when invoked as a login shell, then it only reads `~/.bash_profile` or `~/.profile`. Therefore: * `~/.profile` is the place to put stuff that applies to your whole session, such as programs that you want to start when you log in (but not graphical programs, they go into a different file), and environment variable definitions. * `~/.bashrc` is the place to put stuff that applies only to bash itself, such as alias and function definitions, shell options, and prompt settings. (You could also put key bindings there, but for bash they normally go into `~/.inputrc`.) * `~/.bash_profile` can be used instead of `~/.profile`, but it is read by bash only, not by any other shell. (This is mostly a concern if you want your initialization files to work on multiple machines and your login shell isn't bash on all of them.) This is a logical place to include `~/.bashrc` if the shell is interactive. I recommend the following contents in `~/.bash_profile`: ``` if [ -r ~/.profile ]; then . ~/.profile; fi case "$-" in *i*) if [ -r ~/.bashrc ]; then . ~/.bashrc; fi;; esac ``` On modern unices, there's an added complication related to `~/.profile`. If you log in in a graphical environment (that is, if the program where you type your password is running in graphics mode), you don't automatically get a login shell that reads `~/.profile`. Depending on the graphical login program, on the window manager or desktop environment you run afterwards, and on how your distribution configured these programs, your `~/.profile` may or may not be read. If it's not, there's usually another place where you can define environment variables and programs to launch when you log in, but there is unfortunately no standard location. Note that you may see here and there recommendations to either put environment variable definitions in `~/.bashrc` or always launch login shells in terminals. Both are bad ideas. The most common problem with either of these ideas is that your environment variables will only be set in programs launched via the terminal, not in programs started directly with an icon or menu or keyboard shortcut. ¹ For completeness, by request: if `.bash_profile` doesn't exist, bash also tries `.bash_login` before falling back to `.profile`. Feel free to forget it exists.
8,670,530
I am new to Javascript (and programming in general) and have been trying to get a basic grasp on working with the DOM. Apologies if this is a very basic mistake, but I looked around and couldn't find an answer. I am trying to use the appendChild method to add a heading and some paragraph text into the in the very basic HTML file below. ``` <html> <head> <title>JS Practice</title> </head> <body> <script src="script.js"></script> <div id = "main"> <h1>Simple HTML Page</h1> <p>This is a very simple HTML page.</p> <p>It's about as basic as they come. It has: </p> <ul> <li>An H1 Tag</li> <li>Two paragraphs</li> <li>An unordered list</li> </ul> </div> <div id="javascript"> </div> </body> </html> ``` Here is the js code: ``` var newHeading = document.createElement("h1"); var newParagraph = document.createElement("p"); newHeading.innerHTML = "New Heading!"; newParagraph.innerHTML = "Some text for a paragraph."; document.getElementById("javascript").appendChild(newHeading); document.getElementById("javascript").appendChild(newParagraph); ``` Running it causes an error: "Cannot call method 'appendChild' of null" Help? I can't figure out why this isn't working...
2011/12/29
[ "https://Stackoverflow.com/questions/8670530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1058180/" ]
Assuming this code is inside the `script.js` file, this is because the javascript is running before the rest of the HTML page has loaded. When an HTML page loads, when it comes across a linked resource such as a javascript file, it loads that resource, executes all code it can, and then continues running the page. So your code is running before the `<div>` is loaded on the page. Move your `<script>` tag to the bottom of the page and you should no longer have the error. Alternatively, introduce an event such as `<body onload="doSomething();">` and then make a `doSomething()` method in your javascript file which will run those statements.
12,207,541
I want parse something like a section entry in an \*.ini file: ``` line=' [ fdfd fdf f ] ' ``` What could be the sed pattern (???) for this line to split the ``` 'fdfd fdf f' ``` out? So: ``` echo "${line}" | sed -E 's/???/\1/g' ``` How can I describe all chars except `[[:space:]]`, `[` and `]` ? This doesn't work for me: `[^[[:space:]]\[]*` .
2012/08/31
[ "https://Stackoverflow.com/questions/12207541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1309041/" ]
When you use the `[[:space:]]` syntax, the outer brackets are normal "match one character from this list" brackets, the same as in `[aeiou]` but the inner brackets are part of `[:space:]` which is an indivisible unit. So if you wanted to match a single character which either belongs to the `space` class or is an `x` you'd use `[[:space:]x]` or `[x[:space:]]` When one of the characters you want to match is a `]`, it will terminate the bracketed character list unless you give it some special treatment. You've guessed that you need a backslash somewhere; a good guess but wrong. The way you include a `]` in the list is to put it first. `[ab]c]` is a bracketed list containing the 2 characters `ab`, followed by 2 literal-match characters `c]`, so it matches `"ac]"` or `"bc]"` but `[]abc]` is a bracketed list of the 4 characters `]abc` so it matches `"a"`, `"b"`, `"c"`, or `"]"`. In a negated list the `]` comes immediately after the `^`. So putting that all together, the way to match a single char from the set of all chars except the `[:space:]` class and the brackets is: ``` [^][:space:][] ``` The first bracket and the last bracket are a matching pair, even if you think it doesn't look like they should be.
40,164,277
I need to have my html attribute submit a form. My problem is that a normal button attribute is able to use the type="submit" and other attributes using role="button" don't do anything with the type. So how do I make it submit a form? If you can give me a script to do it, that would be fine too. (I don't know javascript myself) My current code: ``` <form action="myloc" method="post"> <div class="input-group col-lg-6"> <a type="submit" class="btn btn-default input-group-addon" role="button"> Search<span class="glyphicon glyphicon-search" aria-hidden="true"></span> </a> <input type="search" class="form-control" name="search" id="search" placeholder="Search"> </div> </form> ```
2016/10/20
[ "https://Stackoverflow.com/questions/40164277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5103780/" ]
If I understand you correctly you want to submit the form when you press the button using javascript? ``` <form id="test" action="myloc" method="post"> <div class="input-group col-lg-6"> <a type="submit" class="btn btn-default input-group-addon" role="button" onclick="document.getElementById('test').submit();"> Search<span class="glyphicon glyphicon-search" aria-hidden="true"></span> </a> <input type="search" class="form-control" name="search" id="search" placeholder="Search"> </div> </form> ``` Notice that what I did was to set an id ("test") on the form and then added an onclick event to the anchor element.
19,073,331
I'm looking for a way to change the first character of every word in a sentence form lowercase to uppercase. I already read the [following answer](https://stackoverflow.com/questions/1159343/convert-a-char-to-upper-case-using-regular-expressions-editpad-pro/1159389#1159389) but it doesn't work. I tried to use `\U` to replace the first letter as an uppercase letter. But it returns \U as the replacement, not the first letter. May someone take a look at <http://regexr.com?36h59> Thank you in advance!
2013/09/29
[ "https://Stackoverflow.com/questions/19073331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2827396/" ]
If text transformations are possible depends on the regexp implementation. Most standard implementations base off Perl regular expressions and do not support this. A lot of text editors however do provide some way of transformations as they do not have any other capabilities of processing a regular expression match. For example the answer in your linked question refers to an editor called “TextPad”. These transformations are often non-standard and can also differ a lot depending on what tool you use. When using programming languages however, you don’t really need those features built into the regular expression syntax, as you can easily store the match and do some further processing on your own. A lot language also allow you to supply a function which is then called to process every replacement individually. If you tell us what language you are using, we might be able to help you further. ### Some examples JavaScript: ``` > text = 'anleitungen gesundes wohnen'; > text.replace(/(\w+)/g, function(x) { return x[0].toUpperCase() + x.substring(1) }); 'Anleitungen Gesundes Wohnen' ``` Python: ``` >>> import re >>> text = 'anleitungen gesundes wohnen' >>> re.sub('(\w+)', lambda x: x.group(0).capitalize(), text) 'Anleitungen Gesundes Wohnen' ```
68,427,623
I have a database containing tickets. Each ticket has a unique number but this number is not unique in the table. So for example ticket #1000 can be multiple times in the table with different other columns (Which I have removed here for the example). ``` create table countries ( isoalpha varchar(2), pole varchar(50) ); insert into countries values ('DE', 'EMEA'),('FR', 'EMEA'),('IT', 'EMEA'),('US','USCAN'),('CA', 'USCAN'); create table tickets ( id int primary key auto_increment, number int, isoalpha varchar(2), created datetime ); insert into tickets (number, isoalpha, created) values (1000, 'DE', '2021-01-01 00:00:00'), (1001, 'US', '2021-01-01 00:00:00'), (1002, 'FR', '2021-01-01 00:00:00'), (1003, 'CA', '2021-01-01 00:00:00'), (1000, 'DE', '2021-01-01 00:00:00'), (1000, 'DE', '2021-01-01 00:00:00'), (1004, 'DE', '2021-01-02 00:00:00'), (1001, 'US', '2021-01-01 00:00:00'), (1002, 'FR', '2021-01-01 00:00:00'), (1005, 'IT', '2021-01-02 00:00:00'), (1006, 'US', '2021-01-02 00:00:00'), (1007, 'DE', '2021-01-02 00:00:00'); ``` Here is an example: <http://sqlfiddle.com/#!9/3f4ba4/6> What I need as output is the number of new created tickets for each day, devided into tickets from USCAN and rest of world. So for this Example the out coming data should be ``` Date | USCAN | Other '2021-01-01' | 2 | 2 '2021-01-02' | 1 | 3 ``` At the moment I use this two queries to fetch all new tickets and then add the number of rows with same date in my application code: ``` SELECT MIN(ti.created) AS date FROM tickets ti LEFT JOIN countries ct ON (ct.isoalpha = ti.isoalpha) WHERE ct.pole = 'USCAN' GROUP BY ti.number ORDER BY date SELECT MIN(ti.created) AS date FROM tickets ti LEFT JOIN countries ct ON (ct.isoalpha = ti.isoalpha) WHERE ct.pole <> 'USCAN' GROUP BY ti.number ORDER BY date ``` but that doesn't look like a very clean method. So how can I improved the query to get the needed data with less overhead? Ii is recommended that is works with mySQL 5.7
2021/07/18
[ "https://Stackoverflow.com/questions/68427623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/634698/" ]
You may logically combine the queries using conditional aggregation: ```sql SELECT MIN(CASE WHEN ct.pole = 'USCAN' THEN ti.created END) AS date_uscan, MIN(CASE WHEN ct.pole <> 'USCAN' THEN ti.created END) AS date_other FROM tickets ti LEFT JOIN countries ct ON ct.isoalpha = ti.isoalpha GROUP BY ti.number ORDER BY date; ```
9,842,494
So I have a fascinating problem. Despite the fact that I'm not manually or programmatically scrolling my view, my WebView is being automatically scrolled to after the data inside it loads. I've got a fragment in a viewpager. When I first load the pager, it works as expected and everything is shown. But once I "flip the page" the data loads and the WebView pops up to the top of the page, hiding the views above it, which is undesirable. Does anyone know how to prevent this from happening? My layout looks like such: ``` <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/background" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/article_title" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="2dp" android:text="Some Title" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="@color/article_title" android:textStyle="bold" /> <LinearLayout android:id="@+id/LL_Seperator" android:layout_width="fill_parent" android:layout_height="1dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@color/text" android:orientation="horizontal" > </LinearLayout> <WebView android:id="@+id/article_content" android:layout_width="match_parent" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:layout_height="wrap_content" /> <TextView android:id="@+id/article_link" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_marginTop="5dp" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:text="View Full Article" android:textColor="@color/article_title" android:textStyle="bold" /> </LinearLayout> </ScrollView> ``` I'm also not giving focus to anything. By default, it seems to automatically scroll to the WebView after it has loaded. How do I prevent this?
2012/03/23
[ "https://Stackoverflow.com/questions/9842494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43790/" ]
I had the same problem, after hours of trying several ideas, what finally worked for me was simply adding the `descendantFocusability` attribute to the ScrollView's containing LinearLayout, with the value `blocksDescendants`. In your case: ``` <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:descendantFocusability="blocksDescendants" > ``` Haven't had the problem reoccur since.
360,331
Is there a way to obtain a pdf file without figures and tables, while maintaining the figure numbers in the body text. Thank you very much
2017/03/25
[ "https://tex.stackexchange.com/questions/360331", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/105060/" ]
That picture looks like ``` \(\left(\frac{\partial U}{\partial T}\right)_V\). ```
2,080,245
I need to construct square matrices $A$ and $B$ such that $AB=0$ but $BA \neq 0$. I know matrix multiplication is not commutative, but I don't know how to construct such matrices. Thanks in advance. Edit: looking for some simple way
2017/01/02
[ "https://math.stackexchange.com/questions/2080245", "https://math.stackexchange.com", "https://math.stackexchange.com/users/369983/" ]
$A = \begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}$, $B = \begin{bmatrix} 0 & 0 \\ 1 & 0\end{bmatrix}.$ When thinking of examples try to think of most trivial ones like $O$, $I\_n$ etc. These are also kind of trivial right?
32,140,042
Is there a way to detect the SIM phone number on a mobile device while using Meteor? Moreover, what is the correct behavior to have and precautions to make to log users using their phone number (like in Whatsapp or Viber for example)? Thank you in advance.
2015/08/21
[ "https://Stackoverflow.com/questions/32140042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104373/" ]
You have two options: 1. Install Microsoft Windows SDK 2. Copy these files to the machine you are trying to build. take a look at these answers: [Task could not find "AxImp.exe"](https://stackoverflow.com/questions/5923258/task-could-not-find-aximp-exe) ["Task failed because AXImp.exe was not found" when using MSBuild 12 to build a MVC 4.0 project](https://stackoverflow.com/questions/21373792/task-failed-because-aximp-exe-was-not-found-when-using-msbuild-12-to-build-a-m) [Task failed because "AxImp.exe" was not found, or the correct Microsoft Windows SDK is not installed](https://social.msdn.microsoft.com/Forums/vstudio/en-US/e56fd9b3-dbea-4545-a5a5-f1af0e333ad7/task-failed-because-aximpexe-was-not-found-or-the-correct-microsoft-windows-sdk-is-not-installed?forum=tfsbuild)
8,243,134
How do I accomplish the following in C++, and what is doing such things called? ``` template <bool S> class NuclearPowerplantControllerFactoryProviderFactory { // if S == true typedef int data_t; // if S == false typedef unsigned int data_t; }; ```
2011/11/23
[ "https://Stackoverflow.com/questions/8243134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254704/" ]
By **specialization**: ``` template <bool> class Foo; template <> class Foo<true> { typedef int data_t; }; template <> class Foo<false> { typedef unsigned int data_t; }; ``` You can choose to make one of the two cases the primary template and the other one the specialization, but I prefer this more symmetric version, given that `bool` can only have two values. --- If this is the first time you see this, you might also like to think about *partial* specialization: ``` template <typename T> struct remove_pointer { typedef T type; }; template <typename U> struct remove_pointer<U*> { typedef U type; }; ``` --- As @Nawaz says, the easiest way is probably to `#include <type_traits>` and say: ``` typedef typename std::conditional<S, int, unsigned int>::type data_t; ```
40,636,004
suppose we have a table: MASTER\_X\_Y in the database. I want the syntax to run the query : ``` INSERT INTO MASTER_VARIABLE1_VARIABLE2 VALUES (.....); ``` where VARIABLE1 and VARIABLE2 have values X and Y respectively which have been selected from another table. Is this possible ? ( I have 38 possible combinations of X and Y and simply want to insert the selected data into the correct tables. Is there any other approach ? ) I am using oracle SQL 11g. This is the first time I am writing a PL/SQL procedure and I am not getting any straightforward answers. Thank you !
2016/11/16
[ "https://Stackoverflow.com/questions/40636004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5800086/" ]
Still need to test for the user hitting Cancel...This worked for me when hitting Cancel, or typing in 0, 1, or 11 ``` Prints: Dim NumberOfCopies As String NumberOfCopies = Application.InputBox("How many copies do you want to print? Must enter 0-10", Type:=2) If NumberOfCopies = "False" Or NumberOfCopies = "0" Then 'If user hits Cancel, NumberofCopies will be "False" Else If NumberOfCopies >= "11" Then MsgBox "Max to print is 10 copies" GoTo Prints Else ActiveSheet.PrintOut Copies:=NumberOfCopies End If End If ```
10,005,951
I want to load the list of the groups as well as data into two separate datatables (or one, but I don't see that possible). Then I want to apply the grouping like this: Groups ``` A B Bar C Car ``` Data ``` Ale Beer Bartender Barry Coal Calm Carbon ``` The final result after grouping should be like this. ``` *A Ale *B *Bar Bartender Barry Beer *C Calm *Car Carbon Coal ``` I only have a grouping list, not the levels or anything else. And the items falling under the certain group are the ones that do start with the same letters as a group's name. The indentation is not a must. Hopefully my example clarifies what I need, but am not able to name thus I am unable to find anything similar on google. The key things here are: ``` 1. Grouping by a provided list of groups 2. There can be unlimited layers of grouping ```
2012/04/04
[ "https://Stackoverflow.com/questions/10005951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167953/" ]
Since every record has it's children, the query should also take a father for each record. Then there is a nice trick in advanced grouping tab. Choosing a father's column yields as many higher level groups as needed recursively. I learnt about that in <http://blogs.microsoft.co.il/blogs/barbaro/archive/2008/12/01/creating-sum-for-a-group-with-recursion-in-ssrs.aspx>
12,169,718
Lets say I have an XML file: ``` <locations> <country name="Australia"> <city>Brisbane</city> <city>Melbourne</city> <city>Sydney</city> </country> <country name="England"> <city>Bristol</city> <city>London</city> </country> <country name="America"> <city>New York</city> <city>Washington</city> </country> </locations> ``` **I want it flattened to (this should be the final result):** ``` Australia Brisbane Melbourne Sydney England Bristol London America New York Washington ``` I've tried this: ``` var query = XDocument.Load(@"test.xml").Descendants("country") .Select(s => new { Country = (string)s.Attribute("name"), Cities = s.Elements("city") .Select (x => new { City = (string)x }) }); ``` But this returns a nested list inside `query`. Like so: ``` { Australia, Cities { Brisbane, Melbourne, Sydney }}, { England, Cities { Bristol, London }}, { America, Cities { New York, Washington }} ``` Thanks
2012/08/29
[ "https://Stackoverflow.com/questions/12169718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769083/" ]
[SelectMany](http://msdn.microsoft.com/en-us/library/bb534336.aspx) should do the trick here. ``` var result = XDocument.Load(@"test.xml") .Descendants("country") .SelectMany(e => (new [] { (string)e.Attribute("name")}) .Concat( e.Elements("city") .Select(c => c.Value) ) ) .ToList(); ```
17,646,509
I have a "why does it work that way?" question about garbage collection (any/all implementations: Java, Python, CLR, etc.). Garbage collectors deallocate an object when it is no longer in any scope; the number of references pointing to it is zero. It seems to me that a framework could deallocate as soon as the number of references reaches zero, but all implementations I've encountered wait a while and then deallocate many objects at a time. My question is, why? I'm assuming that the framework keeps an integer for each object (which I think Python does, because you have to call `PyINCREF` and `PyDECREF` when writing extension modules for it in C; presumably these functions modify a real counter somewhere). If so, then it shouldn't take any more CPU time to eliminate the object the moment it goes out of scope. If it takes x nanoseconds per object now, then it would take x nanoseconds per object later, right? If my assumption is wrong and there is no integer associated with each object, then I understand why garbage collection waits: it would have to walk the graph of references to determine the status of each object, and that calculation takes time. Such a method would consume less memory than the explicit reference-count method, but I'm astonished that it's quicker or is the preferred method for other reasons. It sounds like a lot of work. From a programming point of view, it would be nice if objects deallocated immediately after they go out of scope. Not only could we rely on destructors being executed when we want them to be (one of the Python gotchas is that `__del__` is not called at a predictable time), but it would become much easier to memory-profile a program. [Here's an example](https://stackoverflow.com/questions/7114661/why-does-java-wait-so-long-to-run-the-garbage-collector) of how much confusion this causes. To my mind, the benefits of programming in a deallocate-right-away framework are so great that there must be some good reason why all the implementations I've heard of wait before deallocating. What is that benefit? Note: if the walk over the graph of references is only needed to identify circular references (a pure reference count can't), then why not a hybrid approach? Deallocate objects as soon as their reference count hits zero and then also do periodic sweeps to look for circular references. Programmers working in such a framework would have a performance/determinism reason to stick to non-circular references as much as is feasible. It's often feasible (e.g. all data are in the form of JSON objects with no pointers to parents). Is this how any popular garbage collectors work?
2013/07/15
[ "https://Stackoverflow.com/questions/17646509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1623645/" ]
To start with, a point of terminology: "garbage collection" means different things to different people, and some GC schemes are more sophisticated than others. Some people consider reference counting to be a form of GC, but personally I consider "true GC" to be distinct from reference counting. With refcounts, there is an integer tracking the number of references, and you can trigger deallocation immediately when the refcount hits zero. This us how the CPython implementation works, and how most varieties of C++ smart pointers work. The CPython implementation adds a mark/sweep GC as a backup, so it's very much like the hybrid design you describe. But refcounting is actually a pretty terrible solution, since it incurs a (relatively) expensive memory write (plus a memory barrier and/or lock, to ensure thread safety) every time a reference is passed, which happens quite a lot. In imperative languages like C++ it's possible (just difficult) to manage memory ownership through macros and coding conventions, but in functional languages like Lisp it becomes well-nigh impossible, because memory allocation usually happens implicitly due to local variable capture in a closure. So it should come as no surprise that the first step toward a modern GC was invented for Lisp. It was called the "twospace allocator" or "twospace collector" and it worked exactly like it sounds: it divided allocatable memory (the "heap") into two spaces. Every new object was allocated out of the first space until it got too full, at which point allocation would stop and the runtime would walk the reference graph and copy only the live (still referenced) objects to the second space. After the live objects were copied, the first space would be marked empty, and allocation would resume, allocating new objects from the second space, until it got too full, at which point the live objects would be copied back to the first space and the process would start all over again. The advantage of the twospace collector is that, instead of doing `O(N)` work, where *N* is the total number of garbage objects, it would only do `O(M)` work, where *M* is the *number of objects that were* ***not garbage***. Since in practice, most objects are allocated and then deallocated in a short period of time, this can lead to a substantial performance improvement. Additionally, the twospace collector made it possible to simplify the allocator side as well. Most `malloc()` implementations maintain what is called a "free list": a list of which blocks are still available to be allocated. To allocate a new object, `malloc()` must scan the free list looking for an empty space that's big enough. But the twospace allocator didn't bother with that: it just allocated objects in each space like a stack, by just pushing a pointer up by the desired number of bytes. So the twospace collector was much faster than `malloc()`, which was great because Lisp programs would do a lot more allocations than C programs would. Or, to put it another way, Lisp programs needed a way to allocate memory like a stack but with a lifetime that was not limited to the execution stack -- in other words, a stack that could grow infinitely without the program running out of memory. And, in fact, Raymond Chen argues that that's exactly how people should think about GC. I highly recommend his series of blog posts starting with [Everybody thinks about garbage collection the wrong way](http://blogs.msdn.com/b/oldnewthing/archive/2010/08/09/10047586.aspx). But the twospace collector had a major flaw, which is that no program could ever use more than half the available RAM: the other half was always wasted. So the history of GC techniques is the history of attempts to improve on the twospace collector, usually by using heuristics of program behavior. However, GC algorithms inevitably involve tradeoffs, usually preferring to deallocate objects in batches instead of individually, which inevitably leads to delays where objects aren't deallocated immediately. **Edit:** To answer your follow-up question, modern GCs generally incorporate the idea of [generational garbage collection](http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29#Generational_GC_.28ephemeral_GC.29), where objects are grouped into different "generations" based on lifetime, and an object in one generation gets "promoted" to another generation once it's lived long enough. Sometimes a small difference in object lifetime (e.g. in a request-driven server, storing an object for longer than one request) can lead to a large difference in the amount of time it takes before the object gets deallocated, since it causes it to become more "tenured". You correctly observe that a true GC has to operate "beneath" the level of `malloc()` and `free()`. (As a side note, it's worth learning about how `malloc()` and `free()` are implemented -- they aren't magic either!) Additionally, for an effective GC, you either need to be conservative (like the Boehm GC) and never move objects, and check things that *might* be pointers, or else you need some kind of "opaque pointer" type -- which Java and C# call "references". Opaque pointers are actually great for an allocation system, since it means you can always move objects by updating pointers to them. In a language like C where you interact directly with raw memory addresses, it's never really safe to move objects. And there are multiple options for GC algorithms. The standard Java runtime contains no less than five collectors (Young, Serial, old CMS, new CMS, and G1, although I think I'm forgetting one) and each has a set of options that are all configurable. However, GCs aren't magic. Most GCs are just exploiting the [time-space tradeoff](https://en.wikipedia.org/wiki/Space%E2%80%93time_tradeoff) of batching work, which means that the gains in speed are usually paid for in increased memory usage (compared to manual memory management or refcounting). But the combination of increased program performance and increased programmer performance, versus the low cost of RAM these days, makes the tradeoff usually worth it. Hopefully that helps make things clearer!
31,984,699
I have a table with large amount of data and I need to get some information with only one query. Content of `PROCESSDATA` table: ``` PROCESSID | FIELDTIME | FIELDNAME | FIELDVALUE ------------------------------------------------------------------------- 125869 | 10/08/15 10:43:47,139000000 | IDREQUEST | 1236968702 125869 | 10/08/15 10:45:14,168000000 | state | Corrected 125869 | 10/08/15 10:43:10,698000000 | state | Pending 125869 | 10/08/15 10:45:15,193000000 | MsgReq | correctly updated ``` I need to get this result: ``` 125869 IDREQUEST 1236968702 state Corrected MsgReq correctly updated ``` So I made this kind of query: ``` SELECT PROCESSID, MAX(CASE WHEN FIELDNAME = 'IDREQUEST' THEN FIELDVALUE END) AS IDREQUEST MAX(CASE WHEN FIELDNAME = 'state' THEN FIELDVALUE END) AS state, MAX(CASE WHEN FIELDNAME = 'MsgReq' THEN FIELDVALUE END) AS MsgReq FROM PROCESSDATA WHERE FIELDNAME IN ('IDREQUEST', 'state', 'MsgReq') GROUP BY PROCESSID, FIELDNAME; ``` But I don't get exactly what I want: ``` 125869 IDREQUEST 1236968702 state Pending MsgReq correctly updated ``` I need to get the `FIELDVALUE` of a `FIELDNAME` based on `FIELDTIME`. In this example `FIELDNAME = 'state'` has two values `'Pending'` and `'Corrected'`, so I want to get `'Corrected'` because its `FIELDTIME` 10/08/15 10:45:14,168000000 > 10/08/15 10:43:10,698000000
2015/08/13
[ "https://Stackoverflow.com/questions/31984699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5061027/" ]
Use `MAX( ... ) KEEP ( DENSE_RANK FIRST ORDER BY ... )` to get the maximum of a column based on the maximum of another column: [SQL Fiddle](http://sqlfiddle.com/#!4/473c3f/1) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE PROCESSDATA ( PROCESSID, FIELDTIME, FIELDNAME, FIELDVALUE ) AS SELECT 125869, TO_TIMESTAMP( '10/08/15 10:43:47,139000000', 'DD/MM/YY HH24:MI:SS,FF9' ), 'IDREQUEST', '1236968702' FROM DUAL UNION ALL SELECT 125869, TO_TIMESTAMP( '10/08/15 10:45:14,168000000', 'DD/MM/YY HH24:MI:SS,FF9' ), 'state', 'Corrected' FROM DUAL UNION ALL SELECT 125869, TO_TIMESTAMP( '10/08/15 10:43:10,698000000', 'DD/MM/YY HH24:MI:SS,FF9' ), 'state', 'Pending' FROM DUAL UNION ALL SELECT 125869, TO_TIMESTAMP( '10/08/15 10:45:15,193000000', 'DD/MM/YY HH24:MI:SS,FF9' ), 'MsgReq', 'correctly updated' FROM DUAL UNION ALL SELECT 125870, TO_TIMESTAMP( '10/08/15 10:43:47,139000000', 'DD/MM/YY HH24:MI:SS,FF9' ), 'IDREQUEST', '1236968702' FROM DUAL UNION ALL SELECT 125870, TO_TIMESTAMP( '10/08/15 10:45:15,193000000', 'DD/MM/YY HH24:MI:SS,FF9' ), 'MsgReq', 'correctly updated' FROM DUAL ``` **Query 1**: ``` SELECT PROCESSID, MAX( CASE FIELDNAME WHEN 'IDREQUEST' THEN FIELDVALUE END ) KEEP ( DENSE_RANK FIRST ORDER BY CASE FIELDNAME WHEN 'IDREQUEST' THEN FIELDTIME END DESC NULLS LAST ) AS IDREQUEST, MAX( CASE FIELDNAME WHEN 'state' THEN FIELDVALUE END ) KEEP ( DENSE_RANK FIRST ORDER BY CASE FIELDNAME WHEN 'state' THEN FIELDTIME END DESC NULLS LAST ) AS state, MAX( CASE FIELDNAME WHEN 'MsgReq' THEN FIELDVALUE END ) KEEP ( DENSE_RANK FIRST ORDER BY CASE FIELDNAME WHEN 'MsgReq' THEN FIELDTIME END DESC NULLS LAST ) AS MsgReq FROM PROCESSDATA GROUP BY PROCESSID ``` **[Results](http://sqlfiddle.com/#!4/473c3f/1/0)**: ``` | PROCESSID | IDREQUEST | STATE | MSGREQ | |-----------|------------|-----------|-------------------| | 125869 | 1236968702 | Corrected | correctly updated | | 125870 | 1236968702 | (null) | correctly updated | ```
15,728
When I budget for me, I usually count savings part of the expenses. **Is it the correct way to do it?** Because of this, when I look at my budget at the end of the month, it feels like my expenses are a bit high.
2012/06/25
[ "https://money.stackexchange.com/questions/15728", "https://money.stackexchange.com", "https://money.stackexchange.com/users/4904/" ]
I have found it useful to have four (yes, four) categories in a budget, rather than the traditional two (income and expenses). This may not be the "correct" way to do it, but it makes sense to me. First, **income**. This one is a no-brainer and is needed in any budget. In this scheme income also includes money taken out of deferred-spending savings (see below). I don't consider money taken out of savings "income", however. Second, **expenses**. This is the money you actually *spent* in the given period (month, with most budgets, but if you are paid on a different schedule it may be bi-weekly, quarterly, or whatever else makes sense in your particular situation). Plain and simple whatever goes into "expenses" is money that is no longer available to you in any way shape or form. I'd put credit card spending into this category as well (treat it the same as debit card spending) but as long as you aren't carrying a balance, that's simply a matter of taste. I'd also put loan payments into this category since "getting the money back" then means taking out a new loan. Third, **deferred spending**. This category is for setting money aside for big-ticket items that you know are coming and which you either aren't sure exactly when they will turn into real expenses (money spent), or know when they will and they are simply too large to handle comfortably with the day-to-day cash flow. An example of the former might be a new car fund, and the latter might be something like my buying dog food about once every four months; the cost for such a batch is too large to handle comfortably within a single month's budget without making large adjustments elsewhere, so I set money aside each month and then use it every four months (or thereabouts). In this categorization, *setting the money aside* classifies as deferred spending, and *taking it back out* classifies as income. If done right, this category will trend toward zero over time, but may hold a substantial balance at times and will rarely or never actually *be at* zero. When you are just starting out, it may very well be negative unless you compensate by taking money from elsewhere. Note that some may refer to this category as targeted savings, which to me certainly is an overlapping term but does not carry quite the same meaning. Fourth, **savings**. This is long term savings and investments that are not earmarked for a particular purpose or the purpose for which it is earmarked is very far into the future. How you define "particular purpose" and "very far into the future" are really a matter of definition, here, and you will have to come up with distinctions that work for you. **The point is** to separate saving for the future (savings) from saving to cover upcoming expenses *that you have already decided on or committed to* (deferred spending). The deferred spending and savings categories can be further subdivided in much the same way as income and expenses, so you can keep track of the money going into your "new car" fund and your "travelling around the world" fund separately. The actual place where the money ends up is on your balance sheet, not the budget. (If you really want to keep track of your money, you will need both.) In the end, the budget's bottom line becomes **(income + money out of deferred spending) - (expenses + money into deferred spending + savings)**. Just like a regular income/expenses budget, this will be zero if your budget is balanced.
10,317,755
I am just curious to know if at all there is any technical/theoretical reasons for a windows NT service to be more stable that created with c++ rather than .Net application or vice versa. Actually I had two Nt Services one made with cpp and other with .Net application. I observe both as showing in start mode but I need to restart service created by .Net often(on average once every 2 days) to respond. When I tried to know about this strange behavior of .Net service some of my friends come up with answers related to OS internals and some say .Net was build like that. I am totally unaware of .Net platform so in finding the reason this forum is one of my attempt. Thanks Anil
2012/04/25
[ "https://Stackoverflow.com/questions/10317755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319048/" ]
You would probably gain some performance with C++ (if it is native) than with .NET, but this would be only during the startup. Once they are both up and running, there shouldn't be much of a difference. However, creating a service through native C++ (as far as I can remembe now) was really pain and it took quite a bit of time. With .NET it is much easier and faster. To be honest, I never had a need to create some super important high speed service. I have created quite a number of services in .NET and they successfully do their job. In these cases the business end result was more important than the actual performance. It is really all about your needs, but as someone said in the comment, the service will be as stable as the programmer wrote it. If you are more comfortable creating a service for controlling a nuclear reactor in .NET, do it in .NET. :-)
13,218,191
I have Tried number of available examples which helps to load contacts from phone. It works fine on emulator but when i try on real time mobile then it crashes. Can any one send me tested piece of code which is working flawless. then i can compare with my code. one failed code example. ``` Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null); if (phones.getCount() > 0) { while (phones.moveToNext()) { name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); } phones.close(); ``` Kindly help.
2012/11/04
[ "https://Stackoverflow.com/questions/13218191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642500/" ]
This is me playing around with this data structure and some template tomfoolery. At the bottom of all of this mess is accessing two flat arrays, one of them containing a tree of sums, the other containing a tree of carry values to propogate down later. Conceptually they form one binary tree. The true value of a node in the binary tree is the value in stored sum tree, plus the number of leaves under the node times the sum of all carry tree values from the node back up to the root. At the same time, the true value of each node in the tree is equal to the true value of each leaf node under it. I wrote one function to do both carry and sum, because it turns out they are visiting the same nodes. And a read sometimes writes. So you get a sum by calling it with an `increase` of zero. All the template tomfoolery does is do the math for where the offsets into each tree the nodes are, and where the left and right children are. While I do use a `struct`, the `struct` is transient -- it is just a wrapper with some pre calculated values around an offset into an array. I do store a pointer to the start of the array, but every `block_ptr` uses the exact same `root` value in this program. For debugging, I have some craptacular Assert() and Debug() macros, plus a trace nullary function that the recursive sum function calls (which I use to track the total number of calls into it). Once again, being needlessly complex to avoid global state. :) ``` #include <memory> #include <iostream> // note that you need more than 2^30 space to fit this enum {max_tier = 30}; typedef long long intt; #define Assert(x) (!(x)?(std::cout << "ASSERT FAILED: (" << #x << ")\n"):(void*)0) #define DEBUG(x) template<size_t tier, size_t count=0> struct block_ptr { enum {array_size = 1+block_ptr<tier-1>::array_size * 2}; enum {range_size = block_ptr<tier-1>::range_size * 2}; intt* root; size_t offset; size_t logical_offset; explicit block_ptr( intt* start, size_t index, size_t logical_loc=0 ):root(start),offset(index), logical_offset(logical_loc) {} intt& operator()() const { return root[offset]; } block_ptr<tier-1> left() const { return block_ptr<tier-1>(root, offset+1, logical_offset); } block_ptr<tier-1> right() const { return block_ptr<tier-1>(root, offset+1+block_ptr<tier-1>::array_size, logical_offset+block_ptr<tier-1>::range_size); } enum {is_leaf=false}; }; template<> struct block_ptr<0> { enum {array_size = 1}; enum {range_size = 1}; enum {is_leaf=true}; intt* root; size_t offset; size_t logical_offset; explicit block_ptr( intt* start, size_t index, size_t logical_loc=0 ):root(start),offset(index), logical_offset(logical_loc) {} intt& operator()() const { return root[offset]; } // exists only to make some of the below code easier: block_ptr<0> left() const { Assert(false); return *this; } block_ptr<0> right() const { Assert(false); return *this; } }; template<size_t tier> void propogate_carry( block_ptr<tier> values, block_ptr<tier> carry ) { if (carry() != 0) { values() += carry() * block_ptr<tier>::range_size; if (!block_ptr<tier>::is_leaf) { carry.left()() += carry(); carry.right()() += carry(); } carry() = 0; } } // sums the values from begin to end, but not including end! // ie, the half-open interval [begin, end) in the tree // if increase is non-zero, increases those values by that much // before returning it template<size_t tier, typename trace> intt query_or_modify( block_ptr<tier> values, block_ptr<tier> carry, int begin, int end, int increase=0, trace const& tr = [](){} ) { tr(); DEBUG( std::cout << begin << " " << end << " " << increase << "\n"; if (increase) { std::cout << "Increasing " << end-begin << " elements by " << increase << " starting at " << begin+values.offset << "\n"; } else { std::cout << "Totaling " << end-begin << " elements starting at " << begin+values.logical_offset << "\n"; } ) if (end <= begin) return 0; size_t mid = block_ptr<tier>::range_size / 2; DEBUG( std::cout << "[" << values.logical_offset << ";" << values.logical_offset+mid << ";" << values.logical_offset+block_ptr<tier>::range_size << "]\n"; ) // exatch math first: bool bExact = (begin == 0 && end >= block_ptr<tier>::range_size); if (block_ptr<tier>::is_leaf) { Assert(bExact); } bExact = bExact || block_ptr<tier>::is_leaf; // leaves are always exact if (bExact) { carry()+=increase; intt retval = (values()+carry()*block_ptr<tier>::range_size); DEBUG( std::cout << "Exact sum is " << retval << "\n"; ) return retval; } // we don't have an exact match. Apply the carry and pass it down to children: propogate_carry(values, carry); values() += increase * end-begin; // Now delegate to children: if (begin >= mid) { DEBUG( std::cout << "Right:"; ) intt retval = query_or_modify( values.right(), carry.right(), begin-mid, end-mid, increase, tr ); DEBUG( std::cout << "Right sum is " << retval << "\n"; ) return retval; } else if (end <= mid) { DEBUG( std::cout << "Left:"; ) intt retval = query_or_modify( values.left(), carry.left(), begin, end, increase, tr ); DEBUG( std::cout << "Left sum is " << retval << "\n"; ) return retval; } else { DEBUG( std::cout << "Left:"; ) intt left = query_or_modify( values.left(), carry.left(), begin, mid, increase, tr ); DEBUG( std::cout << "Right:"; ) intt right = query_or_modify( values.right(), carry.right(), 0, end-mid, increase, tr ); DEBUG( std::cout << "Right sum is " << left << " and left sum is " << right << "\n"; ) return left+right; } } ``` Here are some helper classes to make creating a segment tree of a given size easy. Note, however, that all you need is an array of the right size, and you can construct a block\_ptr from a pointer to element 0, and you are good to go. ``` template<size_t tier> struct segment_tree { typedef block_ptr<tier> full_block_ptr; intt block[full_block_ptr::range_size]; full_block_ptr root() { return full_block_ptr(&block[0],0); } void init() { std::fill_n( &block[0], size_t(full_block_ptr::range_size), 0 ); } }; template<size_t entries, size_t starting=0> struct required_tier { enum{ tier = block_ptr<starting>::array_size >= entries ?starting :required_tier<entries, starting+1>::tier }; enum{ error = block_ptr<starting>::array_size >= entries ?false :required_tier<entries, starting+1>::error }; }; // max 2^30, to limit template generation. template<size_t entries> struct required_tier<entries, size_t(max_tier)> { enum{ tier = 0 }; enum{ error = true }; }; // really, these just exist to create an array of the correct size typedef required_tier< 1000000 > how_big; enum {tier = how_big::tier}; int main() { segment_tree<tier> values; segment_tree<tier> increments; Assert(!how_big::error); // can be a static assert -- fails if the enum of max tier is too small for the number of entries you want values.init(); increments.init(); auto value_root = values.root(); auto carry_root = increments.root(); size_t count = 0; auto tracer = [&count](){count++;}; intt zero = query_or_modify( value_root, carry_root, 0, 100000, 0, tracer ); std::cout << "zero is " << zero << " in " << count << " steps\n"; count = 0; Assert( zero == 0 ); intt test2 = query_or_modify( value_root, carry_root, 0, 100, 10, tracer ); // increase everything from 0 to 100 by 10 Assert(test2 == 1000); std::cout << "test2 is " << test2 << " in " << count << " steps \n"; count = 0; intt test3 = query_or_modify( value_root, carry_root, 1, 1000, 0, tracer ); Assert(test3 == 990); std::cout << "test3 is " << test3 << " in " << count << " steps\n"; count = 0; intt test4 = query_or_modify( value_root, carry_root, 50, 5000, 87, tracer ); Assert(test4 == 10*(100-50) + 87*(5000-50) ); std::cout << "test4 is " << test4 << " in " << count << " steps\n"; count = 0; } ``` While this isn't the answer you want, it might make it easier for someone to write it. And writing this amused me. So, hope it helps! The code was tested and compiled on Ideone.com using a C++0x compiler.
8,431,133
I have an existing `SqlConnection conn;` in some controller (using `ASP.NET MVC3 + Razor`). Now, I would like to render a simple table depending on some SQL command. **The question is:** How to "bind" loaded data in Razor using `ViewBag`? Is it necessary to iterate row-after-row and produce `<tr>....</tr>` in Razor?
2011/12/08
[ "https://Stackoverflow.com/questions/8431133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/684534/" ]
There is no binding like this. And a simple for loop means it isnt much code either, example... ``` <table> @foreach(var row in Model.MyRows) { <tr> @foreach(var col in row.Columns) { <td>@(col.Value)</td> } </tr> } </table> ``` hope that gives you an idea anyway, and this way you get a lot more control over the style of your rendered table
57,446,980
I am trying to write a recursive function which returns a copy of a list where neighbouring elements have been swapped. For example, swapElements([2, 3, 4, 9]) would return [3, 2, 9, 4]. This is my code as of now: ``` def swapElements(mylist): if len(mylist) == 1: pass if len(mylist) == 2: mylist[0], mylist[1] = mylist[1], mylist[0] else: mylist[0], mylist[1] = mylist[1], mylist[0] swapElements(mylist[2:]) return mylist ``` When I run this function it only returns the list with the first two elements swapped, does anyone know why this function is not swapping any other elements other than the first two and how I could fix it?
2019/08/11
[ "https://Stackoverflow.com/questions/57446980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
> > Comparing two slices for missing element > > > I have two slices: `a []string`, `b []string`. `b` contains all the same > elements as `a` plus an extra. > > > For example, ``` package main import ( "fmt" ) func missing(a, b []string) string { ma := make(map[string]bool, len(a)) for _, ka := range a { ma[ka] = true } for _, kb := range b { if !ma[kb] { return kb } } return "" } func main() { a := []string{"a", "b", "c", "d", "e", "f", "g"} b := []string{"a", "1sdsdfsdfsdsdf", "c", "d", "e", "f", "g", "b"} fmt.Println(missing(a, b)) } ``` Output: ``` 1sdsdfsdfsdsdf ```
7,173,238
I having the page in that i have the gridview and page index changing also for every record i have a check box.on top of the page i have the imagebutton in that when i click that button i am redirecting it into another page in that page i have a back button which redirects to present page with checkbox and gridview. what should i do to retain to get the checkbox when ever i check or some thing else? This is gridview paging: ``` protected void ManageCalenderShift_PageIndexChanging(object sender, GridViewPageEventArgs e) { StoreOldValue(); EmployeeDetails.PageIndex = e.NewPageIndex; SortedBindDataToGrid(); PupulateoldCheckValue(); } private void StoreOldValue() { ArrayList categoryIDList = new ArrayList(); foreach (GridViewRow row in EmployeeDetails.Rows) { Label can_id = (Label)row.FindControl("UserACENumber"); bool result = ((CheckBox)row.FindControl("Chkgrid")).Checked; if (Session["CHECKED_ITEMS"] != null) categoryIDList = (ArrayList)Session["CHECKED_ITEMS"]; if (result) { if (!categoryIDList.Contains(can_id.Text)) categoryIDList.Add(can_id.Text); } else categoryIDList.Remove(can_id.Text); } if (categoryIDList != null && categoryIDList.Count > 0) Session["CHECKED_ITEMS"] = categoryIDList; } private void PupulateoldCheckValue() { ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"]; if (categoryIDList != null && categoryIDList.Count > 0) { foreach (GridViewRow row in EmployeeDetails.Rows) { Label can_id = (Label)row.FindControl("UserACENumber"); if (categoryIDList.Contains(can_id.Text)) { CheckBox myCheckBox = (CheckBox)row.FindControl("Chkgrid"); myCheckBox.Checked = true; } } } } ``` This is the redirect to another page code that goes to page1: ``` protected void imgView_Click(object sender, ImageClickEventArgs e) { StoreOldValue(); PupulateoldCheckValue(); Response.Redirect("page1.aspx?UserACENumber=" + (Server.UrlDecode(URLSecurity.Encrypt(UserContext.ACENumber)))); } ``` then in the "page1" i have back button which redirects to "page" aspx : ``` protected void imgimgBack_Click(object sender, ImageClickEventArgs e) { Response.Redirect("page.aspx?UserACENumber=" + (Server.UrlDecode(URLSecurity.Encrypt(UserContext.ACENumber)))); } ``` now my issue is: when i check any one checkbox in the "page.aspx" and i go click image button and redirects to "page1.aspx" and come back to current working "page.aspx" whatever the checkbox i have checked gets disappear.
2011/08/24
[ "https://Stackoverflow.com/questions/7173238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422570/" ]
I will answer my own question and give credit to Quentin, who commented on the question but did not write an answer (if you post the answer, I will select you as the correct answer). There is an HTML version: ``` <div class="g-plusone" data-size="medium"></div> ```
8,765,798
ok, my file have this structure. ``` <system.serviceModel> <services> <service name="ManyaWCF.ServiceManya" behaviorConfiguration="ServiceBehaviour"> <!-- Service Endpoints --> <!-- Unless fully qualified, address is relative to base address supplied above --> <endpoint address="" binding="webHttpBinding" contract="ManyaWCF.IServiceManya" behaviorConfiguration="web"> <!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically. --> </endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehaviour"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true" /> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="web"> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> ``` i got the same web.config in other wcf and worked like a champ, ofc with different folders and files. my folder structure is the following. ![enter image description here](https://i.stack.imgur.com/nTlwl.png) When i try to play it i get this, ``` Service This is a Windows © Communication Foundation. The metadata publishing for this service is currently disabled. If you access the service, you can enable metadata publishing by completing the following steps to modify the configuration file or web application: 1. Create the following service behavior configuration, or add the item to a configuration <serviceMetadata> existing service behavior: <behaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehaviors"> httpGetEnabled="true" <serviceMetadata /> </ Behavior> </ ServiceBehaviors> </ Behaviors> 2. Add the behavior configuration to the service: name="MyNamespace.MyServiceType" <service behaviorConfiguration="MyServiceTypeBehaviors"> Note: The service name must match the name of the configuration for the service implementation. 3. Add the following to end service configuration: binding="mexHttpBinding" contract="IMetadataExchange" <endpoint address="mex" /> Note: the service must have an http base address to add this. Here is an example of a service configuration file with metadata publishing enabled: <configuration> <system.serviceModel> <services> <! - Note: the service name must match the name of the configuration for the service implementation. -> name="MyNamespace.MyServiceType" <service behaviorConfiguration="MyServiceTypeBehaviors"> <! - Add the following end. -> <! - Note: the service must have an http base address to add this. -> binding="mexHttpBinding" contract="IMetadataExchange" <endpoint address="mex" /> </ Service> </ Services> <behaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehaviors"> <! - Add the following item to the service behavior configuration. -> httpGetEnabled="true" <serviceMetadata /> </ Behavior> </ ServiceBehaviors> </ Behaviors> </ System.serviceModel> </ Configuration> For more information about publishing metadata, see the following documentation: http://go.microsoft.com/fwlink/?LinkId=65455 (may be in English). ``` so, i only did 1 wcf and worked fine with same web.conif. My luck of exp and knowledge about this is killing me. Any clue? Thx in advance.
2012/01/06
[ "https://Stackoverflow.com/questions/8765798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/965856/" ]
As far as I know, you only need the endpoint with the `mexHttpBinding` if you want to expose the WSDL to clients. Visual Studio (or wcfutil.exe) needs the WSDL description to create the webservice client classes. After these webservice client classes are created, you shouldn't need to expose the WSDL anymore. **UPDATE:** The `<service>` element in your configuration file should look like this: ``` <service name="ManyaWCF.ServiceManya" behaviorConfiguration="ServiceBehaviour"> <endpoint address="" binding="webHttpBinding" contract="ManyaWCF.IServiceManya" behaviorConfiguration="web" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> ```
38,591,400
I am a Java developer (I often used Spring MVC to develop MVC web app in Java) with a very litle knowledge of PHP and I have to work on a PHP project that use **CodeIgniter 2.1.3**. So I have some doubts about how controller works in **CodeIgniter**. 1) In Spring MVC I have a controller class with some annoted method, each method handle a specific HTTP Request (the annotation defines the URL handled by the method) and return the name of the view that have to be shown. Reading the official documentation of **CodeIgniter** it seems me that the logic of this framework is pretty different: <https://www.codeigniter.com/userguide3/general/controllers.html#what-is-a-controller> So it seems to understand that in **CodeIgniter** is a class that handle a single URL of the application having the same name of the class name. Is it correct? So I have this class: ``` class garanzieValoreFlex extends CI_Controller { ..................................................... ..................................................... ..................................................... function __construct() { parent::__construct(); $this->load->helper(array('form', 'url')); $this->load->library(array('form_validation','session')); } public function reset() { $this->session->unset_userdata("datiPreventivo"); $this->load->view('garanziavalore/garanzie_valore_questionario_bootstrap',array()); } public function index() { $this->load->model('Direct'); $flagDeroga = "true" ; $this->session->userdata("flagDeroga"); $data = $this->session->userdata("datiPreventivo"); $this->load->model('GaranzieValoreFlexModel'); $data = $this->session->userdata("datiPreventivo"); $this->load->model('GaranzieValoreFlexModel'); $this->load->view('garanziavalore/index_bootstrap',$data); } public function back() { $this->load->model('Direct'); $flagDeroga = "true" ; $this->session->userdata("flagDeroga"); $data = $this->session->userdata("datiPreventivo"); $this->load->model('GaranzieValoreFlexModel'); //$this->load->view('garanziavalore/garanzie_valore_questionario_bootstrap',$data); $this->load->view('garanziavalore/index_tornaIndietro_bootstrap',$data); } ..................................................... ..................................................... ..................................................... } ``` So, from what I have understand, basically this controller handle only the HTTP Request toward the URL: **<http://MYURL/garanzieValoreFlex>**. So from what I have understand the method performed when I access to the previous URL is the **index()** that by this line: ``` $this->load->view('garanziavalore/index_bootstrap',$data); ``` show the **garanziavalore/index\_bootstrap.php** page that I found into the **views** directory of my prohect (is it a standard that have to be into the **views** directory?) Is it my reasoning correct? If yes I am loading the view passing to id also the **$data** variable that I think is the model containing the data that can be shown in the page, this variable is retrieved by: ``` $data = $this->session->userdata("datiPreventivo"); ``` What exactly does this line? The last doubt is related the other **back()** method that I have found in the previous controller: is it a method of **CodeIgniter** CI\_Controller class or something totally custom defined by the developer that work on this application before me?
2016/07/26
[ "https://Stackoverflow.com/questions/38591400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833945/" ]
The `GC.KeepAlive` method is [empty](http://referencesource.microsoft.com/#mscorlib/system/gc.cs,279). All it does is ensure that a particular variable is read from at that point in the code, because otherwise that variable is never read from again and is thus not a valid reference to keep an object alive. It's pointless here because the same variable that you're passing to `KeepAlive` *is* read from again at a later point in time - during the hidden `finally` block when `Dispose` is called. So, the `GC.KeepAlive` achieves nothing here.
28,115,526
I'm completely useless regarding databases, but currently I'm having to work with it. I need to make a query that compares date values between to different entries of my table. I have a query like this: ``` SELECT t1.serial_number, t1.fault_type, t2.fault_type FROM shipped_products t1 JOIN shipped_products t2 ON t1.serial_number=t2.serial_number WHERE ABS(DATEDIFF(t2.date_rcv,t1.date_rcv))<90; ``` But it's taking forever to run. Really, I left it running for 18 hours and it never stoped. Is this query correct? Is there a better, more clever way to do this? Thank you very much guys. BTW: I'll automate all the process with python scripts, so if you know of a better way to do this inside python without all the logic having to be inside the query, it would also help. EDIT: My question seems unclear, so I'll explain better what I need to do. I have a problem that sometimes products go to repair centers and are shipped back to clients as "No Deffect found". After that the client ship it againg to repair centers for they present the same issue. So i need a query to count how many products have been to repair centers twice in an interval of 90 days. The unic ID for each single product is its serial number, and that's why I'm searching for sereal number duplicates.
2015/01/23
[ "https://Stackoverflow.com/questions/28115526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1044735/" ]
Every record is going to match itself (in t1 and t2) in this join since the DateDiff will be the same and thus less than 90. Make sure you are not matching to the same record. If you have an ID field in your table you could do this: ``` SELECT t1.serial_number, t1.fault_type, t2.fault_type FROM shipped_products t1 JOIN shipped_products t2 ON t1.serial_number=t2.serial_number AND t1.ID <> t2.ID WHERE ABS(DATEDIFF(t2.date_rcv,t1.date_rcv))<90; ``` Also make sure you have a key on serial\_number.
34,041,384
I created a setup by Advanced Installer software for my program that I've written by c#. I installed my program on VMWare Windows7. When I try to run it this message is displayed: ![Class not registered](https://i.stack.imgur.com/efAyh.png)
2015/12/02
[ "https://Stackoverflow.com/questions/34041384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5394345/" ]
What if `monthNumber` is not between 1 and 12? In that case, `monthString` won't be initialized. You should give it some default value when you declare it : ``` String monthString = null; // or "" ```
7,032,562
I need to create a INNO Setup script that will allow me to have a dialog, where the user can type in a serial number, then I need to save the serial number they entered into the Windows registry. Also, if they don't enter a serial number, the next button needs to be disabled, so that they cannot proceed with the installation, if they do not enter a serial number. Any help would be greatly appriceated. Thanks!
2011/08/11
[ "https://Stackoverflow.com/questions/7032562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416056/" ]
Here's a stripped down sample of what I use in my scripts. Also, take a look at the InnoSetup docs for CheckSerial (http://www.jrsoftware.org/ishelp/topic\_setup\_userinfopage.htm). ``` ; Script generated by the Inno Setup Script Wizard. ; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! #define MyAppName "My Program" #define MyAppVersion "1.5" #define MyAppPublisher "My Company, Inc." #define MyAppURL "http://www.example.com/" #define MyAppExeName "MyProg.exe" [Setup] ; NOTE: The value of AppId uniquely identifies this application. ; Do not use the same AppId value in installers for other applications. ; (To generate a new GUID, click Tools | Generate GUID inside the IDE.) AppId={{6EAB4CDD-5D03-4EA1-BE97-7102D27CE955} AppName={#MyAppName} AppVersion={#MyAppVersion} ;AppVerName={#MyAppName} {#MyAppVersion} AppPublisher={#MyAppPublisher} AppPublisherURL={#MyAppURL} AppSupportURL={#MyAppURL} AppUpdatesURL={#MyAppURL} DefaultDirName={pf}\{#MyAppName} DefaultGroupName={#MyAppName} OutputBaseFilename=setup Compression=lzma SolidCompression=yes [Registry] Root: HKCU; Subkey: "Software\My Company"; Flags: uninsdeletekeyifempty Root: HKCU; Subkey: "Software\My Company\My Program"; Flags: uninsdeletekey Root: HKLM; Subkey: "Software\My Company"; Flags: uninsdeletekeyifempty Root: HKLM; Subkey: "Software\My Company\My Program"; Flags: uninsdeletekey Root: HKLM; Subkey: "Software\My Company\My Program\Settings"; ValueType: string; ValueName: "User"; ValueData: "{userinfoname}" Root: HKLM; Subkey: "Software\My Company\My Program\Settings"; ValueType: string; ValueName: "SN"; ValueData: "{userinfoserial}" [Languages] Name: "english"; MessagesFile: "compiler:Default.isl" [Tasks] Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked [Files] Source: "MyProg.exe"; DestDir: "{app}"; Flags: ignoreversion ; NOTE: Don't use "Flags: ignoreversion" on any shared system files [Icons] Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}" Name: "{commondesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon [Run] Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, "&", "&&")}}"; Flags: nowait postinstall skipifsilent [Code] function CheckSerial(Serial: String): Boolean; var sTrial : string; sSerial : string; begin sTrial := 'trial'; sSerial := lowercase(Serial); if (length(Serial) <> 25) AND (sTrial <> sSerial) then Result := false else Result := true; end; ```
53,514,700
Table is given as ``` Food ID | Food Review 1 | good Review 1 | good Review 1 | Bad Review 2 | good Review 2 | Bad Review 3 | Good Review ``` and the Output expected is ``` Food ID | Good Review | All Review | Acceptance score 1 | 2 | 3 | 2/3 ``` Acceptance score will be calculated as good Review/All Review Can anyone please help me with the query ?
2018/11/28
[ "https://Stackoverflow.com/questions/53514700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10715741/" ]
Instead of setting the style in each click, [toggle](http://api.jquery.com/toggleclass/) the class `$( "#toogle_menu" ).toggleClass( "toggled" )` and style this class in css ```js $("#toogle_menu").click(function() { $("#jy_nav_pos_main").slideToggle("slow"), $("#toogle_menu").toggleClass("toggled") }); ``` ```css .toggled { transform: rotate(-90deg); } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="nav nav-tabs row margin_auto" id="jy_nav_pos_main" role="tablist"> ...... </ul> <button id="toogle_menu" class="btn btn-light"> &raquo; </button> ```
8,377,312
What is the most direct way to convert a symlink into a regular file (i.e. a copy of the symlink target)? Suppose `filename` is a symlink to `target`. The obvious procedure to turn it into a copy is: ``` cp filename filename-backup rm filename mv filename-backup filename ``` Is there a more direct way (i.e. a single command)?
2011/12/04
[ "https://Stackoverflow.com/questions/8377312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462335/" ]
There is no single command to convert a symlink to a regular file. The most direct way is to use `readlink` to find the file a symlink points to, and then copy that file over the symlink: ``` cp --remove-destination `readlink bar.pdf` bar.pdf ``` Of course, if `bar.pdf` is, in fact, a regular file to begin with, then this will clobber the file. Some sanity checking would therefore be advisable.
1,475,551
I'm trying to use the pigeonhole principle to prove that > > if $S$ is a subset of the power set of the first $n$ positive integers, and if $S$ has at least $2^{n-1}+1$ elements, then $S$ must contain a pair of pairwise disjoint sets. > > > I've been playing around with a small set $\{1,2,3\}$ and I can see the theorem seems to be true in this case. But I can't see, for instance, how to construct the pigeonholes so that $\{2\}$ and $\{3\}$, for instance, end up in the same pigeonhole. I've been looking at which subsets of the power set the elements in $S$ do NOT contain, to no avail. Can someone give me a hint about which pigeonholes to look at? I'm adding this in response to the comments below: Demonstrate that it is possible for |S| (i.e., the number of subsets of {1, . . . , n} contained as elements of S ) to equal 2n−1 without any two elements of S being disjoint from each other. I can do this. This provides context.
2015/10/11
[ "https://math.stackexchange.com/questions/1475551", "https://math.stackexchange.com", "https://math.stackexchange.com/users/274450/" ]
Given $S \subseteq \mathcal{P}(n)$ with $|S| \ge 2^{n-1} + 1$, suppose $S$ does not contain a disjoint pair of sets. Let $T = \{n \setminus X \mid X \in S\}$. Then $S, T$ are disjoint subsets of $\mathcal{P}(n)$ having the same cardinality ($X \mapsto (n \setminus X)$ bijects $S \leftrightarrow T$), so: $$ \begin{align} |S \cup T| &= |S| + |T| \\ &= 2 |S| \\ &\ge 2(2^{n-1} + 1) \\ &= 2^n + 2 \end{align} $$ which can't be. This isn't quite a proof by pigenhole, but maybe it is if you squint.
52,694,129
Hi I'm currently working on a music cog for my bot and I'm trying to figure out how to allow the song requester to skip the song without having to use the vote. The music cog uses reactions to skip, stop, pause songs ect. The `requester` is the user who requested the song. Here is what I'm trying to do: ``` if control == 'skip': requester = self.requester if requester: vc.stop() await channel.send('Requester skipped the song,') else: await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8) if react.count >= 5: # bot counts as 1 reaction. vc.stop() await channel.send(':track_next: **Skipping...**', delete_after=5) ``` I'm having an issue mainly with defining the song requester `requester = self.requester` Here's snippet of the part of the code that defines requester: ``` class YTDLSource(discord.PCMVolumeTransformer): def __init__(self, source, *, data, requester): super().__init__(source) self.requester = requester self.title = data.get('title') if self.title is None: self.title = "No title available" self.web_url = data.get('webpage_url') self.thumbnail = data.get('thumbnail') if self.thumbnail is None: self.thumbnail = "http://ppc.tools/wp-content/themes/ppctools/img/no-thumbnail.jpg" self.duration = data.get('duration') if self.duration is None: self.duration = 0 self.uploader = data.get('uploader') if self.uploader is None: self.uploader = "Unkown" # YTDL info dicts (data) have other useful information you might want # https://github.com/rg3/youtube-dl/blob/master/README.md def __getitem__(self, item: str): """Allows us to access attributes similar to a dict. This is only useful when you are NOT downloading. """ return self.__getattribute__(item) @classmethod async def create_source(cls, ctx, search: str, *, loop, download=False): loop = loop or asyncio.get_event_loop() to_run = partial(ytdl.extract_info, url=search, download=download) data = await loop.run_in_executor(None, to_run) if 'entries' in data: # take first item from a playlist data = data['entries'][0] await ctx.send(f':notes: **{data["title"]} added to the queue.**') if download: source = ytdl.prepare_filename(data) else: return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']} return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author) @classmethod async def regather_stream(cls, data, *, loop): """Used for preparing a stream, instead of downloading. Since Youtube Streaming links expire.""" loop = loop or asyncio.get_event_loop() requester = data['requester'] to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False) data = await loop.run_in_executor(None, to_run) return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester) class MusicPlayer: """A class which is assigned to each guild using the bot for Music. This class implements a queue and loop, which allows for different guilds to listen to different playlists simultaneously. When the bot disconnects from the Voice it's instance will be destroyed. """ __slots__ = ('bot', '_guild', '_ctxs', '_channel', '_cog', 'queue', 'next', 'current', 'np', 'volume', 'buttons', 'music', 'music_controller', 'restmode') def __init__(self, ctx): self.buttons = {'⏯': 'rp', '⏭': 'skip', '➕': 'vol_up', '➖': 'vol_down', '': 'thumbnail', '⏹': 'stop', 'ℹ': 'queue', '❔': 'tutorial'} self.bot = ctx.bot self._guild = ctx.guild self._ctxs = ctx self._channel = ctx.channel self._cog = ctx.cog self.queue = asyncio.Queue() self.next = asyncio.Event() self.np = None self.volume = .5 self.current = None self.music_controller = None ctx.bot.loop.create_task(self.player_loop()) async def buttons_controller(self, guild, current, source, channel, context): vc = guild.voice_client vctwo = context.voice_client for react in self.buttons: await current.add_reaction(str(react)) def check(r, u): if not current: return False elif str(r) not in self.buttons.keys(): return False elif u.id == self.bot.user.id or r.message.id != current.id: return False elif u not in vc.channel.members: return False elif u.bot: return False return True while current: if vc is None: return False react, user = await self.bot.wait_for('reaction_add', check=check) control = self.buttons.get(str(react)) if control == 'rp': if vc.is_paused(): vc.resume() else: vc.pause() await current.remove_reaction(react, user) if control == 'skip': requester = self.requester if requester: vc.stop() await channel.send('Requester skipped the song,') else: await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8) if react.count >= 5: # bot counts as 1 reaction. vc.stop() await channel.send(':track_next: **Skipping...**', delete_after=5) if control == 'stop': mods = get(guild.roles, name="Mods") for member in list(guild.members): if mods in member.roles: await context.invoke(self.bot.get_command("stop")) return else: await channel.send(':raised_hand: **Only a mod can stop and clear the queue. Try skipping the song instead.**', delete_after=5) await current.remove_reaction(react, user) if control == 'vol_up': player = self._cog.get_player(context) vctwo.source.volume += 2.5 await current.remove_reaction(react, user) if control == 'vol_down': player = self._cog.get_player(context) vctwo.source.volume -= 2.5 await current.remove_reaction(react, user) if control == 'thumbnail': await channel.send(embed=discord.Embed(color=0x17FD6E).set_image(url=source.thumbnail).set_footer(text=f"Requested By: {source.requester} | Video Thumbnail: {source.title}", icon_url=source.requester.avatar_url), delete_after=10) await current.remove_reaction(react, user) if control == 'tutorial': await channel.send(embed=discord.Embed(color=0x17FD6E).add_field(name="How to use the music controller?", value="⏯ - Pause\n⏭ - Skip\n➕ - Increase Volume\n➖ - Increase Volume\n - Get Thumbnail\n⏹ - Stop & Leave\nℹ - Queue\n❔ - Display help for music controls"), delete_after=10) await current.remove_reaction(react, user) if control == 'queue': await self._cog.queue_info(context) await current.remove_reaction(react, user) ``` If anyone could help me an example of what I'm doing wrong would be awesome! Thanks.
2018/10/08
[ "https://Stackoverflow.com/questions/52694129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7307013/" ]
Add a salt key and do groupBy on your key and the salt key and later ``` import scala.util.Random val start = 1 val end = 5 val randUdf = udf({() => start + Random.nextInt((end - start) + 1)}) val saltGroupBy=skewDF.withColumn("salt_key", randUdf()) .groupBy(col("name"), col("salt_key")) ``` So your all the skew data doesn't go into one executor and cause the 2GB Limit. But you have to develop a logic to aggregate the above result and finally remove the salt key at the end. When you use groupBy all the records with the same key will reach one executor and bottle neck occur. The above is one of the method to mitigate it.
33,517,232
In my app I have a controller that takes a user input consisting of a twitter handle from one view and passes it along through my controller into my factory where it is sent through to my backend code where some API calls are made and ultimately I want to get an image url returned. I am able to get the image url back from my server but I have been having a whale of a time trying to append it another view. I've tried messing around with $scope and other different suggestions I've found on here but I still can't get it to work. I've tried doing different things to try and get the pic to be interpolated into the html view. I've tried injecting $scope and playing around with that and still no dice. I'm trying not to use $scope because from what I understand it is better to not abuse $scope and use instead `this` and a controller alias (`controllerAs`) in the view. I can verify that the promise returned in my controller is the imageUrl that I want to display in my view but I don't know where I'm going wrong. My controller code: ``` app.controller('TwitterInputController', ['twitterServices', function (twitterServices) { this.twitterHandle = null; // when user submits twitter handle getCandidateMatcPic calls factory function this.getCandidateMatchPic = function () { twitterServices.getMatchWithTwitterHandle(this.twitterHandle) .then(function (pic) { // this.pic = pic // console.log(this.pic) console.log('AHA heres the picUrl:', pic); return this.pic; }); }; }]); ``` Here is my factory code: ``` app.factory('twitterServices', function ($http) { var getMatchWithTwitterHandle = function (twitterHandle) { return $http({ method: 'GET', url: '/api/twitter/' + twitterHandle }) .then(function (response) { return response.data.imageUrl; }); }; return { getMatchWithTwitterHandle: getMatchWithTwitterHandle, }; }); ``` this is my app.js ``` var app = angular.module('druthers', ['ui.router']); app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('/', { url: '/', templateUrl: 'index.html', controller: 'IndexController', controllerAs: 'index', views: { 'twitter-input': { templateUrl: 'app/views/twitter-input.html', controller: 'TwitterInputController', controllerAs: 'twitterCtrl' }, 'candidate-pic': { templateUrl: 'app/views/candidate-pic.html', controller: 'TwitterInputController', controllerAs: 'twitterCtrl' } } }); }); ``` Here is the view where I want to append the returned image url ``` <div class="col-md-8"> <img class="featurette-image img-circle" ng-src="{{twitterCtrl.pic}}"/> </div> ```
2015/11/04
[ "https://Stackoverflow.com/questions/33517232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4699240/" ]
You find that convention in [Karma](http://karma-runner.github.io/0.13/dev/git-commit-msg.html) ``` <type>(<scope>): <subject> <body> <footer> ``` It can help for: * automatic generation of the changelog * simple navigation through git history (eg. ignoring style changes) Karma's convention include: > > Allowed `<type>` values: > > > * feat (new feature for the user, not a new feature for build script) > * fix (bug fix for the user, not a fix to a build script) > * docs (changes to the documentation) > * style (formatting, missing semi colons, etc; no production code change) > * refactor (refactoring production code, eg. renaming a variable) > * test (adding missing tests, refactoring tests; no production code change) > * chore (updating grunt tasks etc; no production code change) > > > Example `<scope>` values: > > > * init > * runner > * watcher > * config > * web-server > * proxy > * etc. > > > --- Note: a git commit message should not start with blank lines or empty lines. It is not illegal, but with git 2.10 (Q3 2016), such lines will be trimmed by default for certain operations. See [commit 054a5ae](https://github.com/git/git/commit/054a5aee6f3e8e90d96f7b3f76f5f55752561c59), [commit 88ef402](https://github.com/git/git/commit/88ef402f9c18dafee5c8b222200f8f984b17a73e), [commit 84e213a](https://github.com/git/git/commit/84e213a30a1d4a3835e23b2f3d6217eb74ea55f7), [commit 84e213a](https://github.com/git/git/commit/84e213a30a1d4a3835e23b2f3d6217eb74ea55f7) (29 Jun 2016), [commit 88ef402](https://github.com/git/git/commit/88ef402f9c18dafee5c8b222200f8f984b17a73e), [commit 84e213a](https://github.com/git/git/commit/84e213a30a1d4a3835e23b2f3d6217eb74ea55f7) (29 Jun 2016), [commit 84e213a](https://github.com/git/git/commit/84e213a30a1d4a3835e23b2f3d6217eb74ea55f7) (29 Jun 2016), and [commit 4e1b06d](https://github.com/git/git/commit/4e1b06da252a7609f0c6641750e6acbec451e698), [commit 7735612](https://github.com/git/git/commit/77356122443039b4b65a7795d66b3d1fdeedcce8) (22 Jun 2016) by [Johannes Schindelin (`dscho`)](https://github.com/dscho). (Merged by [Junio C Hamano -- `gitster` --](https://github.com/gitster) in [commit 62e5e83](https://github.com/git/git/commit/62e5e83f8dfc98e182a1ca3a48b2c69f4fd417ce), 11 Jul 2016) > > `reset --hard`: skip blank lines when reporting the commit subject > ------------------------------------------------------------------ > > > When there are blank lines at the beginning of a commit message, the > pretty printing machinery already skips them when showing a commit > subject (or the complete commit message). > > We shall henceforth do the > same when reporting the commit subject after the user called > > > ``` git reset --hard <commit> ``` > > `commit -C`: skip blank lines at the beginning of the message > ------------------------------------------------------------- > > > (that is when you take an existing commit object, and reuse the log message and the authorship information (including the timestamp) when creating the commit) > > Consistent with the pretty-printing machinery, we skip leading blank > lines (if any) of existing commit messages. > > > While Git itself only produces commit objects with a single empty line > between commit header and commit message, it is legal to have more than > one blank line (i.e. lines containing only white space, or no > characters) at the beginning of the commit message, and the > pretty-printing code already handles that. > > > `commit.c`: make [`find_commit_subject()`](https://github.com/git/git/blob/4e1b06da252a7609f0c6641750e6acbec451e698/commit.c#L393) more robust > ---------------------------------------------------------------------------------------------------------------------------------------------- > > > Just like the pretty printing machinery, we should simply ignore > blank lines at the beginning of the commit messages. > > > This discrepancy was noticed when an early version of the > `rebase--helper` produced commit objects with more than one empty line > between the header and the commit message. > > >
4,153,421
How can an Eclipse bundle (eg. within activator code) find the dependent Bundle instances at runtime? I would like to find the bundles that Eclipse has choosen to satisfy the dependency requirements, I do not want to interprete the manifest myself. An example: I would like to find all resources named "marker.txt" in all bundles on which my current bundle depends upon. Also the transitive dependencies. In order to accomplish this I need to be able to find all these bundles to begin with.
2010/11/11
[ "https://Stackoverflow.com/questions/4153421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4900/" ]
There is no easy way to determine the dependency. The best way is to go through the PackageAdmin interface. See the OSGi spec for PackageAdmin and getImportingBundles in particular: [http://www.osgi.org/javadoc/r4v42/org/osgi/service/packageadmin/ExportedPackage.html#getImportingBundles()](http://www.osgi.org/javadoc/r4v42/org/osgi/service/packageadmin/ExportedPackage.html#getImportingBundles%28%29) You need to determine for all installed bundles, which one exports one or more packages that your bundle is importing. The easiest way to achieve this is to call *PackageAdmin.getExportedPackages(Bundle bundle)* with bundles = *null*. This returns an array of all exported packages. You then need to iterate of this array and call *ExportPackage.getImportingBundles()*.
49,508
StackExchange uses "Tags" which I feel might be more geared towards a tech-savvy audience. For the mainstream users, do you think "Tags" works or would they understand "Topics" better?
2013/12/29
[ "https://ux.stackexchange.com/questions/49508", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/39300/" ]
Topic could be used, but it would be wrong. A topic is an information structure which has relations to other topics and is often governed by some kind of authority. Tags are a folksonomy driven information entity, which has no authority and is governed by all users. Everyone in a community participates in the creation of tags, which is the very core of Stackexchange sites. > > ...topic is used to describe the information structure, or pragmatic structure of a clause and how it coheres with other clauses... > > > Source: Wikipedia [Topic](http://en.wikipedia.org/wiki/Topic_%28linguistics%29) I think it would be wrong to use the wrong words for our labels. We're all here since we love to learn, the right way.
32,264,571
I am new to Elastic search . Please help me in finding the filter/query to be written to match the exact records using Java API. ``` Below is the mongodb record .I need to get both the record matching the word 'Jerry' using elastic search. { "searchcontent" : [ { "key" : "Jerry", "sweight" : "1" },{ "key" : "Kate", "sweight" : "1" }, ], "contentId" : "CON_4", "keyword" : "TEST", "_id" : ObjectId("55ded619e4b0406bbd901a47") }, { "searchcontent" : [ { "key" : "TOM", "sweight" : "2" },{ "key" : "Kruse", "sweight" : "2" } ], "contentId" : "CON_3", "keyword" : "Jerry", "_id" : ObjectId("55ded619e4b0406ccd901a47") } ```
2015/08/28
[ "https://Stackoverflow.com/questions/32264571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3440746/" ]
A [Multi-Match](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html) query is what you need to search across multiple fields. Below query will search for the word "jerry" in both the fields "searchcontent.key" and "keyword" which is what you want. ``` POST <index name>/<type name>/_search { "query": { "multi_match": { "query": "jerry", "fields": [ "searchcontent.key", "keyword" ] } } } ```
36,303,051
This is main.axml file. ``` `<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:minWidth="25px" android:minHeight="25px"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/myListView" /> </LinearLayout>` ``` And this is the MainActivity.cs file : protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); ``` // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); Glop = new List<string>(); Glop.Add("Tom"); Glop.Add("Dick"); Glop.Add("Harry"); Name = FindViewById<ListView>(Resource.Id.myListView); } ``` I am trying to create a Listview in Xamarin Android. I have changed the android Id to myListView and also have tried to rebuild the app but it still shows as an error . What should I do now ?
2016/03/30
[ "https://Stackoverflow.com/questions/36303051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6133463/" ]
Try rebuilding the app again and saving the main.axml file . * Build > Clean Solution * Build Solution
58,240,100
I have created a VCL Form containing multiple copies of a `TFrame`, each containing multiple `TLabel` components. The labels take up most of the area inside the frame, providing little exposed client area for selecting the frame specifically. The program must take action when the user selects a frame component and display specific text in the various label captions. The problem is that if the user clicks on one of the label components instead of an open area in the frame, the `OnClick` event is not triggered. How do I generate the frame's `OnClick` event if the user clicks anywhere within the frame?
2019/10/04
[ "https://Stackoverflow.com/questions/58240100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1040289/" ]
VCL tests a graphic (non windowed) control's response to mouse events before it decides if it is a valid target. You can use a specialized label then that modifies this response. Easiest would be to use an interposer class in your frame unit (if all the labels are expected to behave the same). ```delphi type TLabel = class(Vcl.StdCtrls.TLabel) protected procedure CMHitTest(var Message: TCMHitTest); message CM_HITTEST; end; TMyFrame = class(TFrame) ... end; ... procedure TLabel.CMHitTest(var Message: TCMHitTest); begin Message.Result := HTNOWHERE; end; ```
296,288
I have a requirement like below. If there aren't any payment methods, There is a text showing in payment page **No Payment method available.** under the path > > Magento\_Checkout\web\template\payment.html > > > My requirement here is to include a link after the text like below `No Payment method available.` **click here** to edit address. ==> It should be linked to customer account page How can this be achieved, I am not so good in `knockout.js` to bind the links in html pages. Please can anyone help me implement this functionality? Thanks!!
2019/11/20
[ "https://magento.stackexchange.com/questions/296288", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/80394/" ]
First of all, To update message in checkout payment step you need to update **payment.html** file and then, to pass custom link you need to create **mixin of payment.js** Follow below steps for add link in payment steps when no payment methods available : > > **1)** app/code/RH/CustomCheckout/view/frontend/requirejs-config.js > > > ``` var config = { map: { '*': { 'Magento_Checkout/template/payment.html': 'RH_CustomCheckout/template/payment.html' //override payment.html file } }, config: { mixins: { 'Magento_Checkout/js/view/payment': { 'RH_CustomCheckout/js/view/payment-mixin': true // Create mixin of payment.js to add custom link } } } }; ``` > > **2)** app/code/RH/CustomCheckout/view/frontend/web/template/payment.html > > > ``` <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <li id="payment" role="presentation" class="checkout-payment-method" data-bind="fadeVisible: isVisible"> <div id="checkout-step-payment" class="step-content" data-role="content" role="tabpanel" aria-hidden="false"> <!-- ko if: (quoteIsVirtual) --> <!-- ko foreach: getRegion('customer-email') --> <!-- ko template: getTemplate() --><!-- /ko --> <!--/ko--> <!--/ko--> <form id="co-payment-form" class="form payments" novalidate="novalidate"> <input data-bind='attr: {value: getFormKey()}' type="hidden" name="form_key"/> <fieldset class="fieldset"> <legend class="legend"> <span data-bind="i18n: 'Payment Information'"></span> </legend><br /> <!-- ko foreach: getRegion('beforeMethods') --> <!-- ko template: getTemplate() --><!-- /ko --> <!-- /ko --> <div id="checkout-payment-method-load" class="opc-payment" data-bind="visible: isPaymentMethodsAvailable"> <!-- ko foreach: getRegion('payment-methods-list') --> <!-- ko template: getTemplate() --><!-- /ko --> <!-- /ko --> </div> <div class="no-quotes-block" data-bind="visible: isPaymentMethodsAvailable() == false"> <!-- ko if: (!isPaymentMethodsAvailable()) --> <span data-bind="i18n: 'No Payment method available.'"></span> <b><a data-bind="i18n: 'click here', attr: { href: getCustomerAccountUrl() }" target="_new"></a></b> <span data-bind="i18n: 'to edit address.'"></span> <!-- /ko --> </div> <!-- ko foreach: getRegion('afterMethods') --> <!-- ko template: getTemplate() --><!-- /ko --> <!-- /ko --> </fieldset> </form> </div> </li> ``` > > **3)** app/code/RH/CustomCheckout/view/frontend/web/js/view/payment-mixin.js > > > ``` define([ 'jquery', 'underscore', 'uiComponent', 'ko', 'Magento_Checkout/js/model/quote', 'Magento_Checkout/js/model/step-navigator', 'Magento_Checkout/js/model/payment-service', 'Magento_Checkout/js/model/payment/method-converter', 'Magento_Checkout/js/action/get-payment-information', 'Magento_Checkout/js/model/checkout-data-resolver', 'mage/translate', 'mage/url' ], function ( $, _, Component, ko, quote, stepNavigator, paymentService, methodConverter, getPaymentInformation, checkoutDataResolver, $t, url ) { 'use strict'; var mixin = { getCustomerAccountUrl: function () { return window.checkoutConfig.customUrl; // Get URL from Block file } }; return function (target) { return target.extend(mixin); }; }); ``` To pass URL from **block/helper** ,You have to just override **getConfig()** function of **CompositeConfigProvider.php** file. > > **4)** app/code/RH/CustomCheckout/etc/frontend/di.xml > > > ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <!-- pass custom data to checkout page --> <type name="Magento\Checkout\Model\CompositeConfigProvider"> <arguments> <argument name="configProviders" xsi:type="array"> <item name="checkout_custom_payment_block" xsi:type="object">RH\CustomCheckout\Model\CustomConfigProvider</item> </argument> </arguments> </type> </config> ``` > > **5)** app/code/RH/CustomCheckout/Model/CustomConfigProvider.php > > > ``` <?php namespace RH\CustomCheckout\Model; use Magento\Checkout\Model\ConfigProviderInterface; class CustomConfigProvider implements ConfigProviderInterface { protected $customCheckout; public function __construct( \RH\CustomCheckout\Block\CustomBlock $customCheckout ) { $this->customCheckout = $customCheckout; } public function getConfig() { $config = []; $config['customUrl'] = $this->customCheckout->getCustomerAccountURL(); return $config; } } ``` > > **6)** app/code/RH/CustomCheckout/Block/CustomBlock.php > > > ``` <?php namespace RH\CustomCheckout\Block; class CustomBlock extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, array $data = [] ) { parent::__construct($context, $data); } public function getCustomerAccountURL() { return 'customer account url which you want to add'; } } ?> ``` --- If you want to add this custom URL into your theme's checkout **payment.html** file. Then, you just need to replace this below code in your html file. and no need to override payment.html file from **requirejs-config.js**. So, remove **payment.html** override code from **requirejs-config.js [Step 1]** if you want to access that data in your theme's checkout **payment.html** Replace this below div in your theme's **payment.html** file : **From :** ``` <div class="no-quotes-block" data-bind="visible: isPaymentMethodsAvailable() == false"> <!-- ko i18n: 'No Payment method available.'--><!-- /ko --> </div> ``` **To :** ``` <div class="no-quotes-block" data-bind="visible: isPaymentMethodsAvailable() == false"> <!-- ko if: (!isPaymentMethodsAvailable()) --> <span data-bind="i18n: 'No Payment method available.'"></span> <b><a data-bind="i18n: 'click here', attr: { href: getCustomerAccountUrl() }" target="_new"></a></b> <span data-bind="i18n: 'to edit address.'"></span> <!-- /ko --> </div> ``` --- **Output :** [![enter image description here](https://i.stack.imgur.com/EbjtC.png)](https://i.stack.imgur.com/EbjtC.png) Hope, It will helpful for you.
40,707,738
I'm using VueJS to make a simple enough resource management game/interface. At the minute I'm looking to activate the `roll` function every 12.5 seconds and use the result in another function. At the moment though I keep getting the following error: > > Uncaught TypeError: Cannot read property 'roll' of undefined(...) > > > I have tried: * `app.methods.roll(6);` * `app.methods.roll.roll(6);` * `roll.roll()` * `roll()` but can't seem to access the function. Anyone any ideas how I might achieve this? ``` methods: { // Push responses to inbox. say: function say(responseText) { console.log(responseText); var pushText = responseText; this.inbox.push({ text: pushText }); }, // Roll for events roll: function roll(upper) { var randomNumber = Math.floor(Math.random() * 6 * upper) + 1; console.log(randomNumber); return randomNumber; }, // Initiates passage of time and rolls counters every 5 time units. count: function count() { function counting() { app.town.date += 1; app.gameState.roll += 0.2; if (app.gameState.roll === 1) { var result = app.methods.roll(6); app.gameState.roll === 0; return result; } } setInterval(counting, 2500); ... // Activates the roll at times. } } ```
2016/11/20
[ "https://Stackoverflow.com/questions/40707738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3200485/" ]
> > You can access these methods directly on the VM instance, or use them in directive expressions. All methods will have their `this` context automatically bound to the Vue instance. > > > – [Vue API Guide on `methods`](https://v2.vuejs.org/v2/api/#methods) Within a method on a Vue instance you can access other methods on the instance using `this`. ``` var vm = new Vue({ ... methods: { methodA() { // Method A }, methodB() { // Method B // Call `methodA` from inside `methodB` this.methodA() }, }, ... }); ``` To access a method outside of a Vue instance you can assign the instance to a variable (such as `vm` in the example above) and call the method: ``` vm.methodA(); ```
41,759,273
I am converting html to pdf using jspdf library. i am facing two problems. 1. When i am using pagesplit: true ,it splits the page but the problem is half of data in li remains in first page and half comes in second page and so on. 2.in my image tag src link is not contains extension. It fetchs from url. For eg:"<http://pics.redblue.de/doi/pixelboxx-mss-55590672/fee_786_587_png>", but in pdf image not displaying. If i pass src link ends with extension it is displaying in pdf.But i am using not extension format. I searched much for both but didn't find any solution. Please help me ... Thanks in advance
2017/01/20
[ "https://Stackoverflow.com/questions/41759273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7125183/" ]
For your 2nd question: You can use base64 encoded images. It works with jspdf. To convert image into base64, check this: [How to convert image into base64 string using javascript](https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript)
1,589
I vacuum my carpet once a week, and I would like to vacuum under furniture (sofa, etc.) once a month instead of every six months. Is there a way to vacuum or clean under the furniture in some form or fashion? **Tried:** I can't move the furniture, because of the configuration (a lot of stuff needs to be moved). My vacuum is an upright, and the hose isn't that long. A blower *works*, but I would rather not fill a room with dust. Lifting the furniture up and vacuuming is okay, but it's a little tedious.
2014/12/11
[ "https://lifehacks.stackexchange.com/questions/1589", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/82/" ]
If you're not dead-set against moving the furniture, you could use [furniture sliders](http://rads.stackoverflow.com/amzn/click/B001WAK5UW) - on most carpets, they'll allow you to single-handed move even heavy pieces of furniture without undue effort, and can be left in place between vacuumings. That's not very hacky though, so... **Use a leaf blower** - even [inexpensive models](http://rads.stackoverflow.com/amzn/click/B000BOAY2Y) can exceed 150MPH and 200CFM, creating a fast-moving air current suitable for moving dust bunnies out of hard-to-reach places. If you don't have a leaf blower but your vacuum has a blower function, you can try that too - you probably won't get as much velocity, but for short carpets and small pieces of furniture it may suffice. Other options include air compressors and [power-washers](http://rads.stackoverflow.com/amzn/click/B002Z8E52Y). J. Musser notes that you should avoid gas-powered blowers, as the exhaust may prove dangerous in poorly-ventilated areas. Also, spilled gas can ruin your carpets. Once you've blown out the dust, just vacuum it up as you clean the rest of the carpet.
29,696,044
I've wrote a script to change a few CSS properties of a div. I've tried 2 methods I found on google but neither of them work. I've thoroughly read the examples and I don't know why this won't work. When there is less content in the `#rightsection` then there are images in the `#leftsection`, the `#rightsection` attaches to the bottom of the `#contentpage`. But if there is too much content in the `#rightsection`, the content overflows. So I want to change to `position:absolute` to `position:static` when there's a scroll detected upon overflow. I'm not really that good with JQuery so I'm hoping anybody of you would know the answer. If anybody does know, I'd appreciate it. ``` (function($) { $.fn.hasScrollBar = function() { return this.get(0).scrollHeight > this.height(); } //Method 1 if($("#rightsection").hasScrollBar()){ $('.rightsection1').css({ "position":"static", "margin":"-75px 0 0 150px" }); } //Method 2 if($("#rightsection").hasScrollBar()){ $('#rightsection').addClass("rightsection1"); $('#rightsection').removeClass("rightsection2"); } })(jQuery); ``` [JSFiddle](http://jsfiddle.net/2e1hcweq/4/) **Solution** I changed `(function($)` by `$(document).ready(function()` and now it works flawlessly.
2015/04/17
[ "https://Stackoverflow.com/questions/29696044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4373648/" ]
I have found the solution: the problem was that the sub name was the same as the module name. I didn't know it had to be different, but I hope someone will find this useful! Thanks for all the answers guys!
93,416
My S/PDIF digital output used to work fine - stereo, DD, DTS, etc. However after upgrading my Mythbuntu 9.10 64 bit install to use the Nvidia 190 driver, I lost my SPDIF audio. In trying to fix it I've tried dozens of things ranging from the typical to the far-fetched, but none of them have worked. Analog sound works fine, and "aplay -l" says my SPDIF device is right where it should be (see below). So the failure seems to be at a lower level than the typical alsa problem. Here is some info (I'll add more on request): * I believe I've covered all the common causes for this problem (S/PDIF disabled in alsamixer, etc.), but I could have missed something stupid so feel free to ask. * To try to simplify the problem, I've removed PulseAudio. (I've also tried the opposite - to get PulseAudio working - no dice.) * I upgraded to alsa 1.0.22.0 and then to 1.0.22.1. I played around with those and couldn't get it to work, so I reinstalled 1.0.20.0 from the mythbuntu 9.10 repository. Last night I compiled the Realtek linux driver, so I'm now running 1.0.21-r5.13rc9. * "aplay -l" output: card 0: Intel [HDA Intel], device 0: ALC889A Analog [ALC889A Analog] Subdevices: 1/1 Subdevice #0: subdevice #0 card 0: Intel [HDA Intel], device 1: ALC889A Digital [ALC889A Digital] Subdevices: 1/1 Subdevice #0: subdevice #0 * Ubuntu is using ALC889A, but I actually have an ALC885. I believe the same HDA driver is used for both, but just in case... * When the system boots, the Ubuntu boot sound coming out of the analog output sounds like it's playing 2 copies of the Ubuntu boot sound, staggered by a second or so. ??? (Maybe a clue to what's hosed? Is it launching some sound-related program multiple times?) * When I run "speaker-test -Dplughw:0,0 -c2" - I hear the pink noise * When I run "speaker-test -Dplughw:0,1 -c2" - I don't hear noise. * The red light at the end of the spdif cable lights up when I enable S/PDIF, turns off when I disable S/PDIF. The last three bullets plus the perfectly normal "aplay -l" results despite multiple ALSA versions and reinstallations are why I'm baffled. It used to work, I'm sure it can be made to work again, but I'm totally stuck at this point...
2010/01/09
[ "https://superuser.com/questions/93416", "https://superuser.com", "https://superuser.com/users/4698/" ]
I ignored the most basic, simplest rule of debugging: verify your basic assumptions. I assumed my A/V receiver couldn't be the problem because it was brand new, it was working fine before I upgraded the video driver (and it has nothing to do with the video driver), and I hadn't messed with any of its settings. So in all the hours I spent troubleshooting, I never verified that the receiver was still working with an optical input. Tonight I plugged the s/pdif from my Ubuntu system into the optical input for the CD, and it worked. My receiver had somehow scrambled the connection for the original optical input. I played with the receiver preferences (switching the input source to HDMI and then back to optical) and now it works again. Live and learn (again)...
15,867,391
My Caeser cipher works interactively in the shell with a string, but when I've tried to undertake separate programs to encrypt and decrypt I've run into problems, I don't know whether the input is not being split into a list or not, but the if statement in my encryption function is being bypassed and defaulting to the else statement that fills the list unencrypted. Any suggestions appreciated. I'm using FileUtilities.py from the Goldwasser book. That file is at <http://prenhall.com/goldwasser/sourcecode.zip> in chapter 11, but I don't think the problem is with that, but who knows. Advance thanks. ``` #CaeserCipher.py class CaeserCipher: def __init__ (self, unencrypted="", encrypted=""): self._plain = unencrypted self._cipher = encrypted self._encoded = "" def encrypt (self, plaintext): self._plain = plaintext plain_list = list(self._plain) i = 0 final = [] while (i <= len(plain_list)-1): if plain_list[i] in plainset: final.append(plainset[plain_list[i]]) else: final.append(plain_list[i]) i+=1 self._encoded = ''.join(final) return self._encoded def decrypt (self, ciphertext): self._cipher = ciphertext cipher_list = list(self._cipher) i = 0 final = [] while (i <= len(cipher_list)-1): if cipher_list[i] in cipherset: final.append(cipherset[cipher_list[i]]) else: final.append(cipher_list[i]) i+=1 self._encoded = ''.join(final) return self._encoded def writeEncrypted(self, outfile): encoded_file = self._encoded outfile.write('%s' %(encoded_file)) #encrypt.py from FileUtilities import openFileReadRobust, openFileWriteRobust from CaeserCipher import CaeserCipher caeser = CaeserCipher() source = openFileReadRobust() destination = openFileWriteRobust('encrypted.txt') caeser.encrypt(source) caeser.writeEncrypted(destination) source.close() destination.close() print 'Encryption completed.' ```
2013/04/07
[ "https://Stackoverflow.com/questions/15867391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/967818/" ]
``` caeser.encrypt(source) ``` into ``` caeser.encrypt(source.read()) ``` `source` is a file object - the fact that this code "works" (by not encrypting anything) is interesting - turns out that you call `list()` over the source before iterating and that turns it into a **list of lines in the file**. Instead of the usual result of `list(string)` which is a list of characters. So when it tries to encrypt each chracter, it finds a whole line that doesn't match any of the replacements you set. Also like others pointed out, you forgot to include plainset in the code, but that doesn't really matter. A few random notes about your code (probably nitpicking you didn't ask for, heh) * You typo'd "Caesar" * You're using idioms which are inefficient in python (what's usually called "not pythonic"), some of which might come from experience with other languages like C. + Those while loops could be `for item in string:` - strings already work as lists of bytes like what you tried to convert. + The line that writes to outfile could be just `outfile.write(self._encoded)` * Both functions are very similar, almost copy-pasted code. Try to write a third function that shares the functionality of both but has two "modes", encrypt and decrypt. You could just make it work over cipher\_list or plain\_list depending on the mode, for example * I know you're doing this for practice but the standard library includes [these functions](http://www.tutorialspoint.com/python/string_maketrans.htm) for this kind of replacements. Batteries included! **Edit**: if anyone is wondering what those file functions do and why they work, they call `raw_input()` inside a while loop until there's a suitable file to return. `openFileWriteRobust()` has a parameter that is the default value in case the user doesn't input anything. The code is linked on the OP post.
2,532,105
I'm having trouble with writing this sequence as a function of $n$ because it's neither geometric nor arithmetic. > > $$\begin{cases} > u\_{n+1} = \frac12 u\_{n} + 3\qquad \forall n \in \mathbb N\\ > u\_{0} = \frac13 > \end{cases}$$ > > >
2017/11/22
[ "https://math.stackexchange.com/questions/2532105", "https://math.stackexchange.com", "https://math.stackexchange.com/users/482160/" ]
Hint. Note that for some real number $a$ (which one?), $$u\_{n+1}-a = \frac12 \left(u\_{n}-a\right).$$ Hence, the sequence $(u\_n-a)\_n$ is of geometric type: $$u\_{n}-a=\frac12 \left(u\_{n-1}-a\right)=\frac{1}{2^2} \left(u\_{n-2}-a\right)=\dots =\frac{1}{2^{n}} \left(u\_{0}-a\right).$$
40,768,570
I am using python 3.4. I am able to run my python script without any problem. But While running my freezed python script , following error have appeared. I am able to freeze my script successfully too with cx\_freeze. ``` C:\Program Files (x86)\utils>utils.exe Traceback (most recent call last): File "C:\Python34\lib\site-packages\requests\packages\__init__.py", line 27, i n <module> from . import urllib3 File "C:\Python34\lib\site-packages\requests\packages\urllib3\__init__.py", line 8, in <module> from .connectionpool import ( File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 28, in <module> from .packages.six.moves.queue import LifoQueue, Empty, Full File "C:\Python34\lib\site-packages\requests\packages\urllib3\packages\six.py", line 203, in load_module mod = mod._resolve() File "C:\Python34\lib\site-packages\requests\packages\urllib3\packages\six.py", line 115, in _resolve return _import_module(self.mod) File "C:\Python34\lib\site-packages\requests\packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) ImportError: No module named 'queue' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 12, in <module> __import__(name + "__init__") File "C:\Python34\lib\site-packages\cx_Freeze\initscripts\Console.py", line 21, in <module> scriptModule = __import__(moduleName) File "utils.py", line 3, in <module> File "C:\Python34\lib\site-packages\requests\__init__.py", line 63, in <module> from . import utils File "C:\Python34\lib\site-packages\requests\utils.py", line 24, in <module> from ._internal_utils import to_native_string File "C:\Python34\lib\site-packages\requests\_internal_utils.py", line 11, in <module> from .compat import is_py2, builtin_str File "C:\Python34\lib\site-packages\requests\compat.py", line 11, in <module> from .packages import chardet File "C:\Python34\lib\site-packages\requests\packages\__init__.py", line 29, in <module> import urllib3 File "C:\Python34\lib\site-packages\urllib3\__init__.py", line 8, in <module> from .connectionpool import ( File "C:\Python34\lib\site-packages\urllib3\connectionpool.py", line 28, in <module> from .packages.six.moves.queue import LifoQueue, Empty, Full File "C:\Python34\lib\site-packages\urllib3\packages\six.py", line 203, in load_module mod = mod._resolve() File "C:\Python34\lib\site-packages\urllib3\packages\six.py", line 115, in _resolve return _import_module(self.mod) File "C:\Python34\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module __import__(name) ImportError: No module named 'queue' ``` Even tried installing package 'six' with no help. My setup.py is from cx\_Freeze import setup, Executable import requests.certs ``` setup( name = "utils" , version = "0.1" , description = " utils for accounts" , executables = [Executable("utils.py")], options = {"build_exe": {"packages": ["urllib", "requests"],"include_files":[(requests.certs.where(),'cacert.pem')]}}, ``` ) script imports following module ``` import requests import urllib.request import uuid import json import http.client from xml.dom import minidom ``` Any help will be highly appreciated. please see me as novice in python
2016/11/23
[ "https://Stackoverflow.com/questions/40768570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2678648/" ]
I had the same issues running on Ubuntu with Python 3.5. It seems that `cx_freeze` has problems with libraries that import other files or something like that. Importing `Queue` together with `requests` worked for me, so: ``` import requests from multiprocessing import Queue ``` And I don't think specifying `urllib` in `"packages": ["urllib", "requests"]` is necessary.
78,798
An API design is actually a programming question, but it can't be answered like "replace `=` by `==` on line 10". Moreover, the asking person has some idea how it should look like and has to start with presenting the idea, otherwise the answers would explore many different directions and not fit together. Starting with such a presentation makes the question appear like no question at all, so it collects closing votes. Maybe it's just a matter of how the question should be formulated? But I've read the FAQ and have no idea how to make it better. I'm curios if you can advice me. Maybe is SO not the right place for such questions? If so, I'd see it as a needless constraint. To be more concrete, this is the [question](https://stackoverflow.com/questions/4914774/better-regex-syntax-ideas), which lead me to this one. Please, spare me comments about whining. I'm old enough not to whine because of some critiques. I'm just asking how to solve a problem of mine.
2011/02/10
[ "https://meta.stackexchange.com/questions/78798", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/155925/" ]
I would say programmers.stackexchange.com This is from its FAQ (emphasis mine): * **Software engineering** * Developer testing * Algorithm and data structure concepts * **Design patterns** * **Architecture** * Development methodologies * Quality assurance * Software law * Programming puzzles * Freelancing and business concerns
12,751,936
I am trying to run a fairly simple count based on two MySQL tables but I can't get the syntax right. ``` Table_1 Table_2 Actor | Behavior | Receiver | | Behavior | Type_of_behavior | Eric a ann a Good Eric b ann b Bad Bob a Susan a Good Bob c Bob c shy ``` I want to `COUNT Table 1.Behavior` by `table_2.Type_of_behavior WHERE Table_1.Behavior = Table_2 Behavior` and `group by Table_1.Actor`. The syntax I've tried is below. I realize I could join the tables, but for other reasons I need them separate. ``` SELECT actor, JOIN Table_1, Table_2 COUNT(IF(Table_2.Type_of_behavior = "good", 1,0)) AS 'good' FROM Table_1.Behavior GROUP BY actor; ```
2012/10/05
[ "https://Stackoverflow.com/questions/12751936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1723683/" ]
What you have there is called a "template". As such, you are looking for a templating system. Assuming those quotes aren't actually in the string, the only template system I know capable of understanding that templating language is [String::Interpolate](http://search.cpan.org/perldoc?String%3a%3aInterpolate). ``` $ perl -E' use String::Interpolate qw( interpolate ); my $template = q!This is a string with hash value of $foo->{bar}!; local our $foo = { bar => 123 }; say interpolate($template); ' This is a string with hash value of 123 ``` If the quotes are part of the string, what you have there is Perl code. As such, you could get what you want by executing the string. This can be done using [`eval EXPR`](http://perldoc.perl.org/functions/eval.html). ``` $ perl -E' my $template = q!"This is a string with hash value of $foo->{bar}"!; my $foo = { bar => 123 }; my $result = eval($template); die $@ if $@; say $result; ' This is a string with hash value of 123 ``` I strongly recommend against this. I'm not particularly found of String::Interpolate either. [Template::Toolkit](http://search.cpan.org/perldoc?Template%3a%3aToolkit) is probably the popular choice for templating system. ``` $ perl -e' use Template qw( ); my $template = q!This is a string with hash value of [% foo.bar %]!."\n"; my %vars = ( foo => { bar => 123 } ); Template->new()->process(\$template, \%vars); ' This is a string with hash value of 123 ```
66,106,318
I've got something that bugs me : when somebody requests a route with an id greater than PHP\_INT\_MAX, the id is passed as a string to my controller, thus throwing a 500 error, as my controller's parameters are typed. For example, given I'm on a 64-bit system, PHP\_INT\_MAX's value is 2^63-1 (9223372036854775807). If I call my route with 9223372036854775808 (PHP\_INT\_MAX+1, which is still considered as an integer by the router), the kernel tries to send `9.2233720368548E+18` to my controller, hence the 500 error. I doubt there isn't any way to prevent that to happen, but I didn't find any way to catch this integer-now-string in order to throw a custom error and not the default 500 error I'm having. Edit: My ids aren't this big, but such an error has been triggered this week-end, alerting the on-call team for nothing. That's why I want to replace it by a 40X error.
2021/02/08
[ "https://Stackoverflow.com/questions/66106318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4834168/" ]
On your system `PHP_INT_MAX` has 19 digits. So you could add a route requirement to match only when id has 1-18 digits: ``` /** * @Route( * "/some/route/{id}", * requirements={"id"="\d{1,18}"} * ) */ public function yourAction(int $id) { ... } ``` More than 18 digits wouldn't match and result in a 404. But yes, you will "lose" capability to match ids > 999999999999999999 and < PHP\_MAX\_INT, and yes PHP\_MAX\_INT can vary. But this might just be good enough.
10,102,998
When I use emacs, I often meet some errors in my code. When there are some errors in my code, emacs ask me whether I want to "abort" or "terminate-thread". I want to know what the difference is between "abort" and "terminate-thread" in emacs. Which one should I choose that will be better? ![enter image description here](https://i.stack.imgur.com/82fN9.png)
2012/04/11
[ "https://Stackoverflow.com/questions/10102998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1326134/" ]
I don't think this question comes from Emacs. So please give us more information (OS in which you run Emacs, which processes you might be running within Emacs, what kind of error happens, where is the actual question displayed (within Emacs's minibuffer, or some popup dialog), ...
6,344,655
I'm consolidating 2 programs into one, and in 2 different files (I have many files), I have a typedef with the same name, different types though. These types will be used in completely different parts of the program and will never talk to each other, or be used interachangely. I can of cause just do a search replace in one of the files, but I was wondering if there is another solution to this. Something like binding a typedef to a specific file. Or making a typedef local to a class and it's subclasses. Thanks
2011/06/14
[ "https://Stackoverflow.com/questions/6344655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237472/" ]
You can encapsulate those `typedef` inside a `namespace`: ``` namespace N1 { typedef int T; } namespace N2 { typedef int T; } ``` And in whatever file you want to use first `typedef` simply declare: ``` using namespace N1; ``` same thing for the other one also.
49,237,821
I want to change values in a large amount of rows into something else. I open my data from a csv using pandas as follows: ``` import pandas as pd import numpy as np import os df = pd.read_csv('data.csv', encoding = "ISO-8859-") ``` I then slice my DF changing column names: ``` df1 = df['col 1', 'col 2', 'col 3' 'col 4', 'col 5'] ``` Remove useless column names: ``` df2 = df1.columns.str.strip('col') output: 1, 2, 3, 4, 5 a b a b c a c a a c b a c a b ``` Replace values so I can report from the data easier and replace useless answers. ``` df1 = df1.replace('c', None) df1 = df1.replace('a', 's') df1 = df1.replace('b', 'n') ``` Now my issues are, when I strip the columns my dataframes loses all of its values, and when I try to re-concat the new df into the previous one it didn't work. I'm not sure how to use the df.replace on multiple values, also when I run it in different strings and try to append/merge it into the current DF it doesn't really work. The output I'm after is: ``` output: 1, 2, 3, 4, 5 s n s n NaN n NaN s s NaN n s NaN s n ```
2018/03/12
[ "https://Stackoverflow.com/questions/49237821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9375102/" ]
You can pass your conditions to dict ``` df.replace({'c': None,'a':'s','b':'n'}) Out[164]: 1 2 3 4 5 0 s n s n None 1 s None s s None 2 n s None s n ```
4,490,158
I am getting suspicious that there is no need whatsoever for quantifiers in formal first-order logic. Why do we write $\forall x, P(x)$, when can simply write $P(x)$, assuming that we know that $x$ is a variable (as opposed to a constant). A similar question has been asked here: [Is the universal quantifier redundant?](https://math.stackexchange.com/questions/4088337/is-the-universal-quantifier-redundant), and a commenter states that the order of quantifiers matters. Indeed, the order of mixed quantifiers matters, but all existential quantifiers can be reformulated as universal quantifiers, so in fact the order does not matter. I'm struggling to think of a case where a quantifier provides essential information for a statement.
2022/07/10
[ "https://math.stackexchange.com/questions/4490158", "https://math.stackexchange.com", "https://math.stackexchange.com/users/923549/" ]
The problem with replacing $\exists$ with $\neg\forall\neg$ to not have to worry about the order of quantifiers becomes apparent if you actually try doing so and omitting the quantifiers. For instance, $\exists x P(x)$ becomes $\neg \forall x \neg P(x)$ and then you omit the quantifier to get $\neg\neg P(x)$. Wait, that's equivalent to just $P(x)$, which would mean $\forall xP(x)$ under your convention. So $\exists x P(x)$ turned into just $\forall xP(x)$, which isn't right! The problem here is that the order of negation and universal quantifiers matters. That is, $\forall x\neg P(x)$ is different from $\neg\forall x P(x)$ (so $\neg \forall x \neg P(x)$ is different from $\forall x \neg\neg P(x)$). If you omit universal quantifiers everywhere, you lose this distinction.
27,761,243
I have two divs that clicking to first dive cause toggle of second div. ``` #a{ border:1px solid red;width:400px;margin:50px;} #b{position:absolute;border:1px green solid; width:400px;top:150px;} ``` and ``` <div id="a">AAAAAAAAAAAA</div><div id="b">BBBBBB</div><div id="test" >Write Cordinates here</div> $("#a").click(function(){ var burasi = $(this).offset(); var tepe=burasi.top + $(this).outerHeight(true); var ici = $("#b"); ici.offset({top: tepe, left: burasi.left}); window.console.log({top: tepe, left: burasi.left} ); $("#test").html("top: "+tepe+", left: "+burasi.left); ici.fadeToggle("slow"); }) ``` [As here](http://jsfiddle.net/7hLypdnr/). When A would be clicked toggle is executed so good but when div B going to shown its coordinates be changed. How can I prevent it and make div B at same place?
2015/01/04
[ "https://Stackoverflow.com/questions/27761243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/596021/" ]
Read This <http://gabrieleromanato.name/jquery-bug-with-offsets-positioning-and-hidden-elements/> --- you can avoid that by run toggle before offset ``` $("#a").click(function(){ var burasi = $(this).offset(); var tepe=burasi.top + $(this).outerHeight(true); var ici = $("#b"); ici.fadeToggle("slow"); ici.offset({top: tepe, left: burasi.left}); $("#test").html("top: "+tepe+", left: "+burasi.left); }); ``` See [**DEMO**](http://jsfiddle.net/7hLypdnr/6/)
53,103,321
I want to convert .raw file to .jpg or .png using some plain python code or any module that is supported in python 2.7 in windows environment. I tried `rawpy`, PIL modules. But I am getting some attribute error(frombytes not found); because it is supported in Python3. Let me know if i am wrong.. In `rawpy` the RAW format is not supported. I need some module or some code that will change .raw to either png or jpeg.
2018/11/01
[ "https://Stackoverflow.com/questions/53103321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9305639/" ]
use PIL library ``` from PIL import Image im = Image.open("img.raw") rgb_im = im.convert('RGB') rgb_im.save('img.jpg') ```
29,887,232
I am trying to finish one activity from another. For that purpose I am having **only** the component name of that activity. How can i finish that ?
2015/04/27
[ "https://Stackoverflow.com/questions/29887232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627995/" ]
> > Question - is it not possible to ignore the apachehttpclient library provided by google and use a newer version of the library instead? > > > It is not. The [Apache HttpClient Android Port](http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html) can deployed along-side with the old version shipped with the platform. > > Why isnt this possible? > > > It is believed to be for security reasons.
22,998,699
> > Windows 7 - 64-bit > > > Git version: 1.7.9 > > > I don't have any problem with lightweight tag, but when trying Annotated git tag command under windows command console (DOS), I get the error as shown below: ``` c:\tempWorkingFolder\Tobedeleted\mastertemp\btc>git tag -a test_tag -f 'test_tag' fatal: too many params ``` Please help me with this issue. **Note**: both lightweight and annotated tags work fine under 32-bit windows command console (DOS). Thanks.
2014/04/10
[ "https://Stackoverflow.com/questions/22998699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3521095/" ]
I had the same issue, using double quotes instead of single quotes solved it: ``` git tag -a test_tag -f "test_tag" ```
169,692
I recently ran an encounter on a "restaurant boat" where my players had to obtain info from a noble on board. They successfully bluffed/bribed/sneaked their way on board. Certain areas of the ship were off limits to guest, such as the crew's quarter's, the captain's cabin, and the lower deck with rowers moving the ship along. My players found a somewhat quiet spot on deck. They proclaimed they wanted to sneak past the guests, who were busy with eating/socializing/etc., into the forbidden areas. One of them cast *pass without trace*, and I asked them to all roll for Stealth. No one got less than 19 on their Stealth check (after modifiers). They then proceeded to "sneak" past guests into the upper areas (not forbidden per se) and then further into "Staff Only" areas. How do I adjudicate this? Obviously, they pose as guests, no weapons or armor on, so they would just blend into the crowd and then, in an opportune moment, sneak past a door/curtain/rope barrier. But they are still moving in plain sight of at least a dozen NPCs. The NPCs can probably see them, but they do not *perceive* them. The same problem would arise for me if they wanted to escape someone following them in a dense marketplace or in a crowded tavern. How can you Hide/roll for Stealth in a crowd of - admittedly uninterested in you - NPCs?
2020/05/29
[ "https://rpg.stackexchange.com/questions/169692", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/56835/" ]
Stealth was most likely the wrong choice ======================================== Stealth implies that you are impossible to see. If you succeed on your stealth attempt, you are hidden, if you fail, you are not hidden. Your players aren't actually trying to be hidden, anybody can see them, they simply don't register them as *somebody who shouldn't be there*. Blending in with the crowd really shouldn't require a stealth check at all. It might, however, if you like, entail any of the following: * Persuasion: To get other guests to cooperate if they at some point figure out things are fishy. * Deception: To bluff their way past guards who are suspicious about the players actually being guests * Performance: Deception works great for pretending to be a guest when you are not, but performance could also work, depending on who you ask. None of these things require stealth, because you aren't trying to be unseen, you're trying to blend in. Stealth doesn't enter the ordeal until they actually try to go somewhere a normal guest would not be allowed. The moment they want to pass into Staff Only areas and the guards would react if a normal guest did that, then they have to actually use their stealth skill, and they would obviously have to do so in a way that makes sense, you can't stealth your way through a door in plain sight, regardless of how well you rolled. Blending into a crowd to escape from somebody else is a completely different thing than blending into a crowd to not stand out. Once your target no longer has line of sight to you, you can try to stealth. If you succeed, the target no longer knows where you are and you can keep moving in the crowd until they have direct line of sight of you again, at which point you are no longer hidden and the chase most likely continues. It's the difference between: "I need to hide in the crowd because I'm a wanted man and if I'm spotted they will arrest me!" and "I need to blend in because I don't want to look out of place and get asked questions by nosy guards."
70,597,841
I'm trying to make the text-info element display only when I hover over the container element using only CSS and no JS and it doesn't work, would love some advice. I was assuming it had something to do with the display flex instead of display block so I attempted that too, but it didn't help. Note that even without the hover, the text doesn't display on the page and I can't tell why. ```css body { color: #2f80ed; font-family: Avenir, Helvetica, Arial, sans-serif; margin: 0; display: flex; height: 100vh; } p { margin: 0; } .container { width: 520px; margin: auto; } .container img { width: 100%; } .text { width: 400px; margin: 0 auto; cursor: pointer; } .text-code { text-align: center; font-size: 120px; font-weight: 400; } .container:hover+.text-info { display: flex; } .text-info { display: none; text-align: center; font-size: 20px; font-weight: 400; opacity: 0; transition: opacity .4s ease-in-out; } footer { width: 100%; position: absolute; bottom: 30px; } footer p { margin: auto; font-size: 16px; } footer a { color: #2f80ed; } ``` ```html <div class="container"> <img src="empty-boxes.svg" alt="error" /> <div class="text"> <p class="text-code">404</p> <p class="text-info"> 404 is an error. </p> </div> </div> <footer> <p>Go back.</p> <a href="https://google.com"></a> </footer> ```
2022/01/05
[ "https://Stackoverflow.com/questions/70597841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16761342/" ]
``` import requests baseURL = "https://myurl.repl.co" x = requests.get(baseURL) print(x.content) ```
56,291
I'm not sure if commercial fish is inspected in any way. I know that most commercial fish is caught in nets, so I don't think that bait is used. When individuals go fishing, they use worms, flies, or non-kosher fish as bait. After they catch the fish and reel it in, before using the fish, do they need to inspect it for the bait? I doubt that it has been digested that quickly.
2015/03/10
[ "https://judaism.stackexchange.com/questions/56291", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/5275/" ]
The OU kashrus site writes <https://www.ou.org/torah/halacha/hashoneh-halachos/sat_08_25_12/> "46:43 Small worms are sometimes found in fish, in the brain, the liver, the intestines, the mouth and the gills. This is common in such fish as pike and herring. When this is common, one must check for them. Small insects can also be found on the outside of a fish, on or near the fins, in the mouth and behind the gills. One must also check these places and remove any such bugs." Although the stomach and intestines are normally gutted, if one were to try eating that area then it sounds like the worm bait would need to be removed.
20,558,153
I have a search button that goes into my database and searches on a name but when there are two entries for the same name it is only bringing me back one and i can't figure out why. Below is the code I am using now. ``` public boolean search(String str1, String username){//search function for the access history search with two parameters boolean condition = true; String dataSourceName = "securitySystem";//setting string datasource to the securitySystem datasource String dbUrl = "jdbc:odbc:" + dataSourceName;//creating the database path for the connection try{ //Type of connection driver used Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Connection variable or object param: dbPath, userName, password Connection con = DriverManager.getConnection(dbUrl, "", ""); Statement statement = con.createStatement();//creating the statement which is equal to the connection statement if (!(username.equals(""))){ PreparedStatement ps = con.prepareStatement("select * from securitysystem.accessHistory where name = ?");//query to be executed ps.setString(1, username);//insert the strings into the statement ResultSet rs=ps.executeQuery();//execute the query if(rs.next()){//while the rs (ResultSet) has returned data to cycle through JTable table = new JTable(buildTableModel(rs));//build a JTable which is reflective of the ResultSet (rs) JOptionPane.showMessageDialog(null, new JScrollPane(table));//put scrollpane on the table } else{ JOptionPane.showMessageDialog(null,"There has been no system logins at this time");// else- show a dialog box with a message for the user } } statement.close();//close the connection } catch (Exception e) {//catch error System.out.println(e); } return condition; } ```
2013/12/13
[ "https://Stackoverflow.com/questions/20558153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3073941/" ]
Matthias is spot on. A @Stateless annotated bean is an EJB which by default provides [Container-Managed-Transactions](http://docs.oracle.com/javaee/6/tutorial/doc/bncij.html). CMT will by default create a new transaction if the client of the EJB did not provide one. > > **Required Attribute** If the client is running within a transaction and > invokes the enterprise bean’s method, the method executes within the > client’s transaction. If the client is not associated with a > transaction, the container starts a new transaction before running the > method. > > > The Required attribute is the implicit transaction attribute for all > enterprise bean methods running with container-managed transaction > demarcation. You typically do not set the Required attribute unless > you need to override another transaction attribute. Because > transaction attributes are declarative, you can easily change them > later. > > > In the recent java-ee-7 [tuturial](http://www.oracle.com/technetwork/articles/java/jaxrs20-1929352.html) on jax-rs, Oracle has example of using EJBs (@Stateless). > > ... the combination of EJB's @javax.ejb.Asynchronous annotation and > the @Suspended AsyncResponse enables asynchronous execution of > business logic with eventual notification of the interested client. > Any JAX-RS root resource can be annotated with @Stateless or > @Singleton annotations and can, in effect, function as an EJB .. > > > Main difference between @RequestScoped vs @Stateless in this scenario will be that the container can pool the EJBs and avoid some expensive construct/destroy operations that might be needed for beans that would otherwise be constructed on every request.
67,425,200
HTML and inline JS code: ``` <a onclick='show(user)'>${user.firstName + " " + user.lastName}</a> ``` Inside this show function I am passing an object User which has 5-6 properties, but when I used debugger it is not showing me as an object. I also tried this , and this is showing be user as object in debugger but I am getting uncaught syntax error. ``` <a onclick='show(${user})'>${user.firstName + " " + user.lastName}</a> ``` I want to pass it as object so that i can utilise its properties. ```js const displayUsers = (users) => { const htmlString = users .map((user) => { debugger; return ` <li> <a onclick='show(user)'>${user.firstName + " " + user.lastName}</a> </li> `; }) .join(''); usersList.innerHTML = htmlString; console.log(users, 'list') // console.log(htmlString) }; function show(user) { alert(user); console.log( user.aonId); }; ```
2021/05/06
[ "https://Stackoverflow.com/questions/67425200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15856627/" ]
We can use transform here with groupby: ```py s = df["Business hours"].eq("Yes").groupby(df["Date"]).transform("Sum") df[s >= 7] ```
29,022,569
I've written a VB .Net program that does selective intensity pixel modification on graphic files. It's a lot faster than it was when I started (20 seconds vs 90 seconds), but the total time to process multiple images is still slow. I typically run 64 12 MP images, and it takes about 24 minutes to process them all. I thought that if I use multiple threads, each thread processing a subset of the total image set, I could speed things up, so I added multiple background workers. But when I run multiple threads from the program with Thread#.RunWorkerAsync(), the saved images are screwed up. Here's a "good" image, run in a single thread: <http://freegeographytools.com/good.jpg> And here's a typical example of the same image when two threads are running: <http://freegeographytools.com/bad.jpg> These results are essentially typical, but the "bad" image has a clean stripe near the bottom that looks correct; that doesn't normally appear on most images. Each thread calls its own subroutine with independent variables, so there should be no variable "cross-contamination". While these results were obtained with images saved as JPG, I've gotten the same results with images saved as TIF files. I've also tried separating the images into different directories, and processing each directory simultaneously, each with its own thread - same result. To modify pixels, I've used GetPixel/SetPixel to change the pixel value, and also used LockBits to modify the image in a byte array - results are the same for both methods. One thread good, two+ thread bad. I'm sure it's something obvious, but I can't figure it out. Suggestions would very much be appreciated.
2015/03/13
[ "https://Stackoverflow.com/questions/29022569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4665101/" ]
Change the image's cap insets to make the image fit the way you want: ``` UIImage *barButtonImage = [[UIImage imageNamed:@"ZSSBackArrow"] resizableImageWithCapInsets:UIEdgeInsetsMake(0,width,0,0)]; ``` This will keep the width of the image as your specified width. You may need to play with the numbers a bit to get it just right.
45,730,832
I am using **rxjs/Rx** in angular 2 to create a clock and making lap and Sprint time laps from it. The Code block is as follows: **HTML:** (app.component.html) ``` <div class="row"> <div class="col-xs-5"> <div class="row"> <div class="col-xs-6"> <h2>Lap Time</h2> <ul *ngFor="let lTime of lapTimes"> <li>{{lTime}}</li> </ul> </div> <div class="col-xs-6"> <h2>Sprint Time</h2> <ul *ngFor="let sTime of sprintTimes"> <li>{{sTime}}</li> </ul> </div> </div> </div> <div class="col-xs-5"> <h1>Current Time: {{timeNow}}</h1> <div> <button type="button" class="btn btn-large btn-block btn-default" (click)="onStart()">Start Timer</button> <button type="button" class="btn btn-large btn-block btn-default" (click)="onLoop()">Sprint and Lap</button> <button type="button" class="btn btn-large btn-block btn-default" (click)="onStop()">Stop Timer</button> </div> </div> </div> ``` **TypeScript:** (app.component.ts) ``` import { Component } from '@angular/core'; import { Observable, Subscription } from 'rxjs/Rx'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { sprintTimes: number[] = [0]; lapTimes: number[] = [0]; timeNow: number = 0; timer: Observable<any> = Observable.timer(0, 1000); subs: Subscription; onStart () { this.subs = this.timer.subscribe((value) => { this.tickerFunc(); }); // this.onLoop(); } onLoop () { this.onLap(); this.onSprint(); } onSprint () { this.sprintTimes.push(this.timeNow); } onLap () { this.lapTimes.push(this.timeNow - this.sprintTimes[this.sprintTimes.length - 1]); } onStop () { this.subs.unsubscribe(); } tickerFunc () { this.timeNow++; } } ``` This is allowing me to create a clocking functionality. But the **Rxjs/Rx** is insufficiently documented (Its hard for me to understand it via its documentation only). Is there any better way to do the work I'm doing here in angular? (The main purpose of mine here is: I want to conduct a online exam/ mock test.) When I'm pressing the Start Clock Button Twice, my clock is ticking as twice as fast. (I don't understand this behavior) Is there any other third part tool to make this easier? Sorry that my Type Script code is not properly Indented, I'm finding it hard to use the text editor. And also this is not a place to do homework.
2017/08/17
[ "https://Stackoverflow.com/questions/45730832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152976/" ]
After some digging and understanding in the doc, I found a working solution: ``` "mappings": { // ... "cartproduct": { "_parent": { "type": "product" }, "properties": { "productId": { "type": "keyword" }, // etc... } } } ``` And the search query: ``` { "query": { "has_parent": { "parent_type": "product", "query": { "term": { "enabled": true } } } }, "aggs": { "products": { "terms": { "field": "productId" } } } } ```
10,844,448
Is there a way to detect if the javascript see if there was a click, and if there was, it can do something? ``` function clickin() { var mouseDown = 0; document.body.onmousedown = function() { ++mouseDown; var alle = document.getElementsByClassName('box'); for (var i = 0; i < alle.length; i++) { value = "this.title='1'" alle[i].setAttribute("onmouseover", value); } document.body.onmouseup = function() { --mouseDown; var alle = document.getElementsByClassName('box'); for (var i = 0; i < alle.length; i++) { value = "0" alle[i].setAttribute("onmouseover", value); } } } }​ ```
2012/06/01
[ "https://Stackoverflow.com/questions/10844448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1418521/" ]
And the question is? You have already the code. Anyway, from my point of view, go for [jQuery](http://jquery.com/) and it's [mouse events](http://api.jquery.com/category/events/mouse-events/).
8,710,581
> > **Possible Duplicate:** > > [What is the difference between Managed C++ and C++/CLI?](https://stackoverflow.com/questions/2443811/what-is-the-difference-between-managed-c-and-c-cli) > > [What is CLI/C++ exactly? How does it differ to 'normal' c++?](https://stackoverflow.com/questions/6399493/what-is-cli-c-exactly-how-does-it-differ-to-normal-c) > > > I am in doubt of distinguishing between C++ and C++.NET. Is that right C++ is unmanaged code and C++.NET is managed code? I need to program for a project in C++. For better building the GUI, I would prefer to use C++.NET. I also have another plain C++ library (unmanaged C++ DLL file), will it be possible to use it as a normal DLL library in the C++.NET project?
2012/01/03
[ "https://Stackoverflow.com/questions/8710581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413174/" ]
> > Is that right C++ is unmanaged code and C++.NET is managed code. > > > There's no such thing as "C++.NET". There's C++/CLI, which is basically C++ with Microsoft extensions that allow you to write code targeting the .NET framework. C++/CLI code compiles to CLR bytecode, and runs on a virtual machine just like C#. I'll assume you're actually talking about C++/CLI. With respect to that, one can say standard C++ is unmanaged and C++/CLI is managed, but that's very much Microsoft terminology. You'll never see the term "unmanaged" used this way when talking about standard C++ unless in comparison with C++/CLI. Both standard C++ and C++/CLI can be compiled by the same Visual C++ compiler. The former is the default on VC++ compilers, while a compiler switch is needed to make it compile in latter mode. > > I need to program for a project in C++. For better building the GUI, I > would prefer to use C++.NET. > > > You can build GUI programs in C++ just as well as C++/CLI. It's just harder because there isn't a standard library in standard C++ for building GUI like the .NET framework has, but there are lots of projects out there like [Qt](http://qt.nokia.com/products/) and [wxWidgets](http://www.wxwidgets.org/) which provide a C++ GUI framework. > > I also have another plain C++ library (unmanaged C++ dll), will it be > possible to use it as a normal dll library in the C++.NET project? > > > Yes. It might take some extra work to deal with the different standard C++ data types and .NET data types, but you can certainly make it work.
180,579
If the caster is in the radius of a harmful area of effect, such as a fireball spell, will the illusory duplicates exist after damage is taken or will they be destroyed?
2021/02/09
[ "https://rpg.stackexchange.com/questions/180579", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/60697/" ]
### The spell description explicitly states only attacks can destroy a duplicate. The spell description of *mirror image* states: > > A duplicate can be destroyed only by an attack that hits it. It ignores all other damage and effects. > > > Area of effect spells such as *fireball* are “other damage and effects”, not attacks.
52,445,834
I'm trying to teach my test automation framework to detect a selected item in an app using opencv (the framework grabs frames/screenshots from the device under test). Selected items are always a certain size and always have blue border which helps but they contain different thumbnail images. See the example image provided. I have done a lot of Googling and reading on the topic and I'm close to getting it to work expect for one scenario which is image C in the example image. [example image](https://i.stack.imgur.com/CbclA.png) This is where there is a play symbol on the selected item. My theory is that OpenCV gets confused in this case because the play symbol is basically circle with a triangle in it and I'm asking it to find a rectangular shape. I found this to be very helpful: <https://www.learnopencv.com/blob-detection-using-opencv-python-c/> My code looks like this: ``` import cv2 import numpy as np img = "testimg.png" values = {"min threshold": {"large": 10, "small": 1}, "max threshold": {"large": 200, "small": 800}, "min area": {"large": 75000, "small": 100}, "max area": {"large": 80000, "small": 1000}, "min circularity": {"large": 0.7, "small": 0.60}, "max circularity": {"large": 0.82, "small": 63}, "min convexity": {"large": 0.87, "small": 0.87}, "min inertia ratio": {"large": 0.01, "small": 0.01}} size = "large" # Read image im = cv2.imread(img, cv2.IMREAD_GRAYSCALE) # Setup SimpleBlobDetector parameters. params = cv2.SimpleBlobDetector_Params() # Change thresholds params.minThreshold = values["min threshold"][size] params.maxThreshold = values["max threshold"][size] # Filter by Area. params.filterByArea = True params.minArea = values["min area"][size] params.maxArea = values["max area"][size] # Filter by Circularity params.filterByCircularity = True params.minCircularity = values["min circularity"][size] params.maxCircularity = values["max circularity"][size] # Filter by Convexity params.filterByConvexity = False params.minConvexity = values["min convexity"][size] # Filter by Inertia params.filterByInertia = False params.minInertiaRatio = values["min inertia ratio"][size] # Create a detector with the parameters detector = cv2.SimpleBlobDetector(params) # Detect blobs. keypoints = detector.detect(im) for k in keypoints: print k.pt print k.size # Draw detected blobs as red circles. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures # the size of the circle corresponds to the size of blob im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Show blobs cv2.imshow("Keypoints", im_with_keypoints) cv2.waitKey(0) ``` How do I get OpenCV to only look at the outer shape defined by the blue border and ignore the inner shapes (the play symbol and of course the thumbnail image)? I'm sure it must be do-able somehow.
2018/09/21
[ "https://Stackoverflow.com/questions/52445834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8937566/" ]
According to the documentation, `#pragma GCC unroll 1` is supposed to work, if you place it just so. If it doesn't then you should submit a bug report. Alternatively, you can use a function attribute to set optimizations, I think: ``` void myfn () __attribute__((optimize("no-unroll-loops"))); ```
67,806,380
I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this: ``` d = [{ "key1": "value1", "key2": { "key3": "value3", "key4": "NULL", "z": { "z1": "NULL", "z2": "zzz", }, }, "key5": "NULL" }, { "KEY": "NULL", "AAA": "BBB", }] ``` And I want to wipe out all keys that have **NULL** as value Like this: `[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]` I am using Python 3.9, so it is possible to use walrus operator.
2021/06/02
[ "https://Stackoverflow.com/questions/67806380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832490/" ]
Here is how you can do this with recursion: ``` def remove_null(d): if isinstance(d, list): for i in d: remove_null(i) elif isinstance(d, dict): for k, v in d.copy().items(): if v == 'NULL': d.pop(k) else: remove_null(v) d = [{ "key1": "value1", "key2": { "key3": "value3", "key4": "NULL", "z": { "z1": "NULL", "z2": "zzz", }, }, "key5": "NULL" }, { "KEY": "NULL", "AAA": "BBB", }] remove_null(d) print(d) ``` Output: ``` [{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}] ```
35,783,817
I am programming an application that is non-modal dialog based. I am using the Visual Studio resource editor to build the dialog and create the application. Everything is going great so far. However, I have reached a brick wall when it comes to handling keyboard input. My research has shown that windows captures keyboard input before it reaches the dialog callback procedure to implement the ability to move the focus using the keyboard. I created a bare bones dialog to test this and, when I have a dialog without any controls on it, everything works as I would expect it to. When I add a control, it stops working. Here is the code from the bare bones project: ``` #include <Windows.h> #include <CommCtrl.h> #include <tchar.h> #include "resource.h" INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); HWND dlghandle; int WINAPI _tWinMain(HINSTANCE hInst, HINSTANCE h0, LPTSTR lpCmdLine, int nCmdShow) { HWND hDlg; MSG msg; BOOL ret; hDlg = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_DIALOG1), 0, DialogProc, 0); ShowWindow(hDlg, nCmdShow); dlghandle = hDlg; while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) { if (ret == -1) return -1; if (!IsDialogMessage(hDlg, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; } INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_KEYDOWN: MessageBox(NULL, L"Test", L"Test", MB_OK); break; case WM_CLOSE: DestroyWindow(hDlg); break; case WM_DESTROY: PostQuitMessage(0); return 0; break; } return 0; } ``` What options do I have?
2016/03/03
[ "https://Stackoverflow.com/questions/35783817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1813678/" ]
The first place keyboard input appears is your message loop, so just check for the keypress you're looking for before passing it off to `IsDialogMessage()` / `TranslateMessage()` / `DispatchMessage()`. For example: ``` while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) { if (ret == -1) return -1; if (msg.message == WM_KEYDOWN && msg.wParam == 'Q') { // trap and handle the Q key no matter which control has focus } else if (!IsDialogMessage(hDlg, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } ``` If you wanted you could even wrap this in a function to make it neater, e.g.: ``` #define MYMSG_DOSOMETHING (WM_APP + 1) BOOL MyIsDialogMessage(HWND hDlg, MSG* pMsg) { if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'Q') { PostMessage(hDlg, MYMSG_DOSOMETHING, 0, 0); return TRUE; } return IsDialogMessage(hDlg, pMsg); } // then your message loop would be: while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) { if (ret == -1) return -1; if (!MyIsDialogMessage(hDlg, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } ```
36,278,293
I'm using `templateRest` to post `User` object to `Rest Server` but I encoutered the following error: > > Exception in thread "main" java.lang.NoClassDefFoundError: > com/fasterxml/jackson/core/JsonProcessingException at > edu.java.spring.service.client.RestClientTest.main(RestClientTest.java:33) > Caused by: java.lang.ClassNotFoundException: > com.fasterxml.jackson.core.JsonProcessingException at > java.net.URLClassLoader.findClass(Unknown Source) at > java.lang.ClassLoader.loadClass(Unknown Source) at > sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at > java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more > > > Here is the file `RestClientTest.java` ``` public class RestClientTest { public static void main(String[] args) throws IOException{ RestTemplate rt = new RestTemplate(); // System.out.println("Rest Response" + loadUser("quypham")); // URL url = new URL("http://localhost:8080/rest/user/create"); rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); rt.getMessageConverters().add(new StringHttpMessageConverter()); // Map<String,String> vars = new HashMap<String,String>(); User user = new User(); user.setUserName("datpham"); user.setPassWord("12345"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR,1960); user.setBirthDay(calendar.getTime()); user.setAge(12); String uri = new String("http://localhost:8080/rest/user/create"); User returns = rt.postForObject(uri, user,User.class); // createUser(user); System.out.println("Rest Response" + loadUser("datpham")); } ``` Here is the file `UserRestServiceController.java` ``` @Controller public class UserRestServiceController { @Autowired public UserDao userDao; @RequestMapping(value = "/rest/user/create",method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public void addUser(@RequestBody User user){ userDao.save(user); } ``` Here is the file pom.xml ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>edu.java.spring.service</groupId> <artifactId>springDAT-service</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>springDAT-service Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.1.0.Final</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>10.12.1.1</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>springMOTHER-service</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <skipTests>true</skipTests> <argLine>-Xmx2524m</argLine> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <fork>true</fork> <compilerArgs> <arg>-XDignore.symbol.file</arg> </compilerArgs> </configuration> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.3.0.M1</version> <configuration> <jvmArgs>-Xmx1048m -Xms536m -XX:PermSize=128m -XX:MaxPermSize=512m</jvmArgs> <reload>manual</reload> <systemProperties> <systemProperty> <name>lib</name> <value>${basedir}/target/spring-mvc/WEB-INF/lib</value> </systemProperty> </systemProperties> <scanIntervalSeconds>3</scanIntervalSeconds> <connectors> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <port>8080</port> <maxIdleTime>60000</maxIdleTime> </connector> </connectors> <contextPath>/</contextPath> <webAppSourceDirectory>${basedir}/src/main/webapp</webAppSourceDirectory> <webXml>${basedir}/src/main/webapp/WEB-INF/web.xml</webXml> <classesDirectory>${basedir}/target/classes</classesDirectory> </configuration> </plugin> </plugins> </build> </project> ``` I have browsed information on google, afterwards I have tried to add jackson 2.4 in pom.xml but didn't seem to work: ``` <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.0-rc3</version> </dependency> ```
2016/03/29
[ "https://Stackoverflow.com/questions/36278293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5957380/" ]
Add this : ``` <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> ``` You can replace `${jackson.version}` with any version you want,or just add `<jackson.version>2.x.x</jackson.version>`at top of your pom.xml p/s:Mine is version `2.7.3`
5,126,633
When I run rspec 2 with rails 3 I use ``` rake rspec ``` sometimes I'd like to use a different formatter, perhaps doc. ``` rake rspec --format doc ``` but unfortunately the option doesn't make it through to the rspec runner. How can I choose a different format when I run the command?
2011/02/26
[ "https://Stackoverflow.com/questions/5126633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162337/" ]
You can add default options to an .rspec file in the rails root folder. e.g. ``` --colour --format documentation ```