text
stringlengths
64
89.7k
meta
dict
Q: Flux Transfer of Current also involved in Autotransformer? In Isolated Transformer, the primary and secondary are separated yet when there is a demand for current in the secondary, the primary can produce current and transfer it via fluxes. I understood this a bit although I'd appreciate it if someone can share a youtube video of the principle because of this finding I had where when I used gaussmeter to measure the magnetic field, there was no difference between no load and with load as if the magnetic field was already maximum at the start. Does this also occur in Autotransformer? I'm asking this because when I used a gaussmeter to measure magnetic field of an autotransformer, the no load and load magnetic field was the same. I was expecting the magnetic field to increase with load because there is more current and in an autotransformer, the secondary is just tap of different point of the continuous wire.. unless it's the same principle as the nonlocal flux transfer in isolated transformer? How? A: Do this thought experiment: take a normal transformer. Connect the non-dot wire of the secondary to the dot wire of the primary. You now have an autotransformer. So yes, the mechanism is the same. I suspect that the reason your flux readings don't change is because you were not reading the flux inside the core. Even if you were able to do so, in a reasonably efficient transformer that's operating even remotely normally* the magnetizing flux is going to remain substantially the same. * "remotely normally" in this context means it's not bursting into flames.
{ "pile_set_name": "StackExchange" }
Q: How I could host the html documentation of my API to be browseable online in GitHub? I wonder if exists a free online service for developers where to host the contents of a library's API documentation, I mean the index.html and all the files that composes a html documentation. This is the documentation that I will host with the intention to be browseable online: http://www.mediafire.com/download/244x2i13vtp6j1d/Web.rar My current projects are hosted in GitHub, and one person told me that I could host the html documentation using GitHub-Pages, but I think can't, I already created a page using the GitHub-Pages for my repository but seems only can be a single and simple html page with no chance to do/upload what I require, anyways, I'm not totally sure. If with github-pages isn't possible to do, then I'll look for a free service alternative that offers a guided way to this, instead of registering in a free web-hosting to create your domain then access the admin panel then upload the files then blah blah blah... A: Who says you can't have more than one page on your GHub Pages? Make a new file, for instance called api.html or api.txt or whatever you want. On this new page, you can include a download link for your rar. Add a <a href="mypage.html"> in your index.html. Style it however you want, and people can go through.
{ "pile_set_name": "StackExchange" }
Q: Automating file transfer using Bash scripts in SSH on my new server from old server How can I connect to a remote host using SSH and create one Bash script to copy all files and folder from my old server to my new server for backup every day? A: Set up key-based ssh authentication First, you need to generate a ssh key. On the machine you're connecting from, run: $ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/vidarlo/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/vidarlo/.ssh/id_rsa. Your public key has been saved in /home/vidarlo/.ssh/id_rsa. The key fingerprint is: SHA256:/jxfxiWiao0m7YG9MiHgXBFKoo7kJcgTOrPtAZNtpVg [email protected] The key's randomart image is: +---[RSA 2048]----+ |..E o. | |=B.+. | |@==. . | |=O= . | |o=oo S . . .| | .o.. .+ . o o | | . ..o+o. + | | + =*o o | | B+ oo. | +----[SHA256]-----+ [~]$ Just press enter when asked; the default locations and no passphrase is OK. This will generate a private and public key. Next step is to copy the public key to the remote server, so that it can be used. ssh-copy-id can be used for this: $ ssh-copy-id user@host /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/vidarlo/.ssh/id_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys user@host's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'user@host'" and check to make sure that only the key(s) you wanted were added. At this stage you should be able to run ssh user@host, and get logged in without entering a password. Backup job You want a simple scp. This is bad for several reasons: You don't get any history. If a file is overwritten by mistake, and you do not discover it before the next backup job, scp will happily overwrite the content. You have to copy all the content every night. You don't get a status report. If a backup job does not finish in time, you risk having two backup jobs writing to the same content. But, anyway. This can be done, as long as you're aware of the caveats. Use crontab -e to edit your users crontab. Insert a line like this: 0 5 * * * /usr/bin/scp "/path/to/backup" "user@remote:/path/to/store/backups" This command will run nightly at 05:00. This can be changed if you desire. The explanation of the fields is as follows: minutes, 0-60. 0 means run it at xx:00, * means run it every minute hours, 0-23. 02 means 02:xx. * means every hour. Day of month, 1-31. * means every day. Month, 1-12. * is every month Day of Week, 1-7.
{ "pile_set_name": "StackExchange" }
Q: I anticipate slowness in this algorithm to check for vowels The speed of the following alorithm would be determined by the number of words in the sentance and the number of characters in each word. I believe this is O(N^2)? or worse. private bool CheckForNoVowels(string sentence) { foreach (string word in sentence.Split(' ')) foreach (char c in word) if (!vowels.Contains(c)) return true; } Is there some sort of secret string.HasVowel Bill Gates is hiding from me? Is there a better, more efficient way to search for this. Thank you. intent I am trying to determine if the string is a company or a name, I assume if there is a word with no vowels, it is an abreviation or an acronym and that it is a company. A: Regex.IsMatch(sentence, "[aoeui]"); A: No, it's perfectly good. It would be considered O(N) in the total number of characters in the input. I can't imagine this would be the performance bottleneck in your app - but you should use profiling to check for sure. A: I'm not sure what its internal implementation is (it is marked with [MethodImpl(MethodImplOptions.InternalCall) and its algorithm doesn't appear to be documented) , but I would try the string.IndexOfAny method. Reports the index of the first occurrence in this instance of any character in a specified array of Unicode characters. Return Value: The zero-based index position of the first occurrence in this instance where any character in anyOf was found; -1 if no character in anyOf was found. Do note that: The search for anyOf is case-sensitive. This method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar value are the same. To perform a culture-sensitive search, use the CompareInfo.IndexOf method. Example: char[] vowels = { 'a', 'e', 'i', 'o', 'u' }; bool hasVowel = word.IndexOfAny(vowels) != -1; Off-topic, I don't understand why your code is splitting the sentence into words and then looking at every character in every word for a vowel. The split doesn't really seem to accomplish anything.
{ "pile_set_name": "StackExchange" }
Q: NSView subclass for NSMenuItem I want to create a subview of NSView and link it to a MenuView.xib. I'll have: - MenuView.m - MenuView.h - MenuView.xib in xcode I created my xib and set as customclass my 'MenuView'. Now I would like to add my new view programmatically via a command like this: NSView *vv = [[MenuView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)]; NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:@"title" action:nil keyEquivalent:@""]; [newItem setView:vv]; but I just see an empty space without any content. How can I tell the class MenuView.m to render with the MenuView.xib file? Is that wrong? Thanks. A: Use an NSViewController, it's designed for loading views from a nib file. In your nib file, set NSViewController as the class of File's Owner and then set the view outlet of File's Owner so that it points to your view in the nib. Then you can just do this: NSViewController* viewController = [[NSViewController alloc] initWithNibName:@"YourNibName" bundle:nil]; YourCustomView* view = [viewController view]; //this loads the nib [viewController release]; //do something with view
{ "pile_set_name": "StackExchange" }
Q: How to "flatten" the structure with the TABLE expression I have a VARRAYS TYPE wanted to "flatten" the structure with the TABLE expression. The example data CREATE OR REPLACE TYPE ARIS.NUMBER_VARRAY_5 AS VARRAY (5) OF NUMBER NOT NULL; CREATE TABLE ARIS.TEST_2 ( DATE_START DATE, DATE_END DATE, O3 ARIS.NUMBER_VARRAY_5, CATEGORY NUMBER ) SET DEFINE OFF; Insert into TEST_2 (DATE_START, DATE_END, O3, CATEGORY) Values (TO_DATE('01/01/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('01/05/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), NUMBER_VARRAY_5(281.25,-9999,291.5,310.5,298.75), NULL); Insert into TEST_2 (DATE_START, DATE_END, O3, CATEGORY) Values (TO_DATE('01/02/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('01/06/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), NUMBER_VARRAY_5(-9999,291.5,310.5,298.75,300.75), NULL); COMMIT; using the SQL statement select O3.* from test_2 t, table(t.o3) O3 I can get the result COLUMN_VALUE 281.25 -9999 291.5 310.5 298.75 -9999 291.5 310.5 298.75 300.75 The question is how I get the results like DATE_START DATE_END 03.VALUE1 03.VALUE2 03.VALUE3 03.VALUE4 03.VALUE5 01/01/2005 01/05/2005 281.25 -9999 291.5 310.5 298.75 01/02/2005 01/06/2005 -9999 291.5 310.5 298.75 300.75 A: Try This, SELECT * FROM ( select t.Date_start, t.Date_end, row_number() OVER ( PARTITION BY DATE_START, DATE_END ORDER BY ROWNUM) rn, O3.* from test_2 t, table(t.o3) O3 ) PIVOT ( MAX(column_value) FOR rn in ( 1 as "03.VALUE1", 2 as "03.VALUE2", 3 as "03.VALUE3", 4 as "03.VALUE4", 5 as "03.VALUE5" ) ) ;
{ "pile_set_name": "StackExchange" }
Q: How to bind selector to method inside NSObject In the macOS swiftui project I have the following code import Cocoa import SwiftUI @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! var statusItem: StatusItem = StatusItem() func applicationDidFinishLaunching(_ aNotification: Notification) { } @objc public func statusBarButtonClicked(sender: NSStatusBarButton) { let event = NSApp.currentEvent! if event.type == NSEvent.EventType.rightMouseUp { print("Right click! (AppDelegate)") } else { print("Left click! (AppDelegate)") } } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } } import Cocoa class StatusItem : NSObject { private let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) override init() { super.init() self.item.button?.title = "title" self.item.button?.action = #selector(self.statusBarButtonClicked(sender:)) self.item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp]) } @objc public func statusBarButtonClicked(sender: NSStatusBarButton) { let event = NSApp.currentEvent! if event.type == NSEvent.EventType.rightMouseUp { print("Right click! (NSObject)") } else { print("Left click! (NSObject)") } } } But when I click NSStatusBarButton it prints "Left click! (AppDelegate)" and "Right click! (AppDelegate)" to console. Why does it happen? And how to make it call statusBarButtonClicked method defined in StatusItem class? A: Setting the button's action is only one half of what you need to do. You also need to specify a target. Add self.item.button?.target = self and I believe you will get the result you are looking for. What's happening is action specifies the selector to invoke and target specifies the object on which to invoke it.
{ "pile_set_name": "StackExchange" }
Q: Download whole directories in Python SimpleHTTPServer I really like how I can easily share files on a network using the SimpleHTTPServer, but I wish there was an option like "download entire directory". Is there an easy (one liner) way to implement this? Thanks A: I did that modification for you, I don't know if there'are better ways to do that but: Just save the file (Ex.: ThreadedHTTPServer.py) and access as: $ python -m /path/to/ThreadedHTTPServer PORT BPaste Raw Version The modification also works in threaded way so you won't have problem with download and navigation in the same time, the code aren't organized but: from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import threading import SimpleHTTPServer import sys, os, zipfile PORT = int(sys.argv[1]) def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do. """ path = self.translate_path(self.path) f = None if self.path.endswith('?download'): tmp_file = "tmp.zip" self.path = self.path.replace("?download","") zip = zipfile.ZipFile(tmp_file, 'w') for root, dirs, files in os.walk(path): for file in files: if os.path.join(root, file) != os.path.join(root, tmp_file): zip.write(os.path.join(root, file)) zip.close() path = self.translate_path(tmp_file) elif os.path.isdir(path): if not self.path.endswith('/'): # redirect browser - doing basically what apache does self.send_response(301) self.send_header("Location", self.path + "/") self.end_headers() return None else: for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): path = index break else: return self.list_directory(path) ctype = self.guess_type(path) try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = open(path, 'rb') except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return f def list_directory(self, path): try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import cgi, urllib """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ try: list = os.listdir(path) except os.error: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) f = StringIO() displaypath = cgi.escape(urllib.unquote(self.path)) f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">') f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath) f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath) f.write("<a href='%s'>%s</a>\n" % (self.path+"?download",'Download Directory Tree as Zip')) f.write("<hr>\n<ul>\n") for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / f.write('<li><a href="%s">%s</a>\n' % (urllib.quote(linkname), cgi.escape(displayname))) f.write("</ul>\n<hr>\n</body>\n</html>\n") length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() return f Handler = SimpleHTTPServer.SimpleHTTPRequestHandler Handler.send_head = send_head Handler.list_directory = list_directory class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" if __name__ == '__main__': server = ThreadedHTTPServer(('0.0.0.0', PORT), Handler) print 'Starting server, use <Ctrl-C> to stop' server.serve_forever() A: Look at the sources, e.g. online here. Right now, if you call the server with a URL that's a directory, its index.html file is served, or, missing that, the list_directory method is called. Presumably, you want instead to make a zip file with the directory's contents (recursively, I imagine), and serve that? Obviously there's no way to do it with a one-line change, since you want to replace what are now lines 68-80 (in method send_head) plus the whole of method list_directory, lines 98-137 -- that's already at least a change to over 50 lines;-). If you're OK with a change of several dozen lines, not one, and the semantics I've described are what you want, you could of course build the required zipfile as a cStringIO.StringIO object with the ZipFile class, and populate it with an os.walk on the directory in question (assuming you want, recursively, to get all subdirectories as well). But it's most definitely not going to be a one-liner;-). A: There is no one liner which would do it, also what do you mean by "download whole dir" as tar or zip? Anyway you can follow these steps Derive a class from SimpleHTTPRequestHandler or may be just copy its code Change list_directory method to return a link to "download whole folder" Change copyfile method so that for your links you zip whole dir and return it You may cache zip so that you do not zip folder every time, instead see if any file is modified or not Would be a fun exercise to do :)
{ "pile_set_name": "StackExchange" }
Q: Meno's paradox - Did Socrates contradict himself? [Source:] Meno then proffers a paradox: "And how will you inquire into a thing when you are wholly ignorant of what it is? Even if you happen to bump right into it, how will you know it is the thing you didn't know?" Socrates rephrases the question, which has come to be the canonical statement of the paradox: "[A] man cannot search either for what he knows or for what he does not know[.] He cannot search for what he knows--since he knows it, there is no need to search--nor [1.] for what he does not know, for he does not know what to look for." After witnessing the example with the slave boy, Meno tells Socrates that he thinks that Socrates is correct in his theory of recollection, to which Socrates replies, “I think I am. I shouldn’t like to take my oath on the whole story, but one thing I am ready to fight for as long as I can, in word and act—that is, that we shall be better, braver, and more active men [2.] if we believe it right to look for what we don’t know...” It has been argued variously that this implies Socrates is skeptical regarding knowledge or that he is a pragmatist. It also prepares us for the subsequent discussion of knowledge by hypothesis. In [1.], Socrates says that you can't seek what you don't know, because you don't know what to seek. Yet in [2], he does believe in seeking what you don't know. So do [1] and [2] conflict? A: No implication is given that searching for what he does not know is the only way to add knowledge. Socrates statement and Meno's paradox only implies that we will not know we learned something we didn't know. It does not refute the possibility that we could learn something without realizing it. His second statement suggests that the act of looking for what we don't know has a positive effect, but does not directly state that we will know what we know. It merely states that he strongly believes (but cannot prove) that we shall be better men if we consider it "right" to look for what we don't know. He states that he believes we will be better if we go in that direction, even if we don't "know" what it provides us. It would thus be valid to synthesize from Socrates statements that true knowledge always sneaks up on us, and better, braver, more active men seek to put themselves in a position such that true knowledge sneaks up on them easier.
{ "pile_set_name": "StackExchange" }
Q: Updating dataframe with rows of variable size in Pandas/Python I have imported an excel sheet into a dataframe in Pandas. The blank values were replaced by 'NA's. What I want to do is, for each of the row values, replace them based on indices of a dictionary or dataframe. df1 = pd.DataFrame( {'c1':['a','a','b','b'], 'c2':['1','2','1','3'], 'c3':['2','NA','3','NA']},index=['first','second','third','last']) >>> df1 c1 c2 c3 first a 1 2 second a 2 NA third b 1 3 last b 3 NA and I want to replace the values in each row according to the indices of another dataframe (or dict). df2=pd.DataFrame( {'val':['v1','v2','v3']},index=['1','2','3']) >>> df2 val 1 v1 2 v2 3 v3 Such that the output becomes >>> out c1 c2 c3 first a v1 v2 second a v2 NA third b v1 v3 last b v3 NA How would you do this through Pandas and/or Python? One way to do it would be to search row by row, but maybe there is an easier way? Edit: Importantly, performance becomes an issue in my real case since I am dealing with a 'df1' whose size is 4653 rows × 1984 columns. Thank you in advance A: One way would be stack + replace + unstack combo: df1.stack().replace(df2.val).unstack() A: Original answer s = df1.squeeze() df2.replace(s) replace is very, very slow. For a larger data set like you have check the following example which is done over 30 million values (more than your 10 million values) in about 20 seconds. The lookup Series contains 900k values from 0 to 1 million. 'map' is much, much faster. The only issue with map is that it replaces a value not found with missing so you will have to use fillna with the original DataFrame to replace those missing values. n = 10000000 df = pd.DataFrame({'c1':np.random.choice(list('abcdefghijkl'), n), 'c2':np.random.randint(0, 1000000, n), 'c3':np.random.randint(0, 1000000, n)}) s = pd.Series(index=np.random.choice(np.arange(1000000), 900000, replace=False), data=np.random.choice(list('adsfjhqwoeriouzxvmn'), 900000, replace=True)) df.stack().map(s).unstack().fillna(df) You can also do this which is running faster on my data but your data is very wide so it might be slower df.apply(lambda x: x.map(s)).fillna(df) And on a DataFrame similar to yours, I am getting 6s to complete. df = pd.DataFrame(np.random.randint(0, 1000000, (5000, 2000))) df.stack().map(s).unstack().fillna(df)
{ "pile_set_name": "StackExchange" }
Q: Deleting duplicate reference to remote Git repo (without deleting the repo) I currently have 2 references to the same remote Github repo. Both references have the same remote URL, so when I do git remote -v I get: myrepo https://github.com/<user ID>/myrepo (fetch) myrepo https://github.com/<user ID>/myrepo (push) origin https://github.com/<user ID>/myrepo (fetch) origin https://github.com/<user ID>/myrepo (push) I want to delete the myrepo remote reference without deleting the remote repo. So I want to end up with the following when I do git remote -v: origin https://github.com/<user ID>/myrepo (fetch) origin https://github.com/<user ID>/myrepo (push) I wasn't sure if git remote remove myrepo will delete the remote repo or just the reference to it. A: git remote rm myrepo is what you're looking for. It will not delete the remote repository but just your local reference to it.
{ "pile_set_name": "StackExchange" }
Q: Number formatting axis labels in ggplot2? I'm plotting a fairly simple chart using ggplot2 0.9.1. x <- rnorm(100, mean=100, sd = 1) * 1000000 y <- rnorm(100, mean=100, sd = 1) * 1000000 df <- data.frame(x,y) p.new <- ggplot(df,aes(x,y)) + geom_point() print(p.new) Which works, but ggplot2 defaults to scientific notation that is inappropriate for my audience. If I want to change the x-axis label format by entering: p.new + scale_x_continuous(labels = comma) I get: Error in structure(list(call = match.call(), aesthetics = aesthetics, : object 'comma' not found What am I doing wrong? I note that the language changed recently from "formatter" to "labels". Perhaps I'm misreading the man page? Edit: I was indeed misreading the man page Need to load library(scales) before attempting this. A: One needs to load library(scales) before attempting this.
{ "pile_set_name": "StackExchange" }
Q: F# compiler keep dead objects alive I'm implementing some algorithms which works on large data (~250 MB - 1 GB). For this I needed a loop to do some benchmarking. However, in the process I learn that F# is doing some nasty things, which I hope some of you can clarify. Here is my code (description of the problem is below): open System for i = 1 to 10 do Array2D.zeroCreate 10000 10000 |> ignore printfn "%d" (GC.GetTotalMemory(true)) Array2D.zeroCreate 10000 10000 |> ignore // should force a garbage collection, and GC.Collect() doesn't help either printfn "%d" (GC.GetTotalMemory(true)) Array2D.zeroCreate 10000 10000 |> ignore printfn "%d" (GC.GetTotalMemory(true)) Array2D.zeroCreate 10000 10000 |> ignore printfn "%d" (GC.GetTotalMemory(true)) Array2D.zeroCreate 10000 10000 |> ignore printfn "%d" (GC.GetTotalMemory(true)) Console.ReadLine() |> ignore Here the output will be like: 54000 54000 54000 54000 54000 54000 54000 54000 54000 54000 400000000 800000000 1200000000 Out of memory exception So, in the loop F# discards the result, but when I'm not in the loop F# will keep references to "dead data" (I've looked in the IL, and apparently the class Program gets fields for this data). Why? And can I fix that? This code is runned outside Visual Studio and in release mode. A: The reason for this behavior is that the F# compiler behaves differently in the global scope than in local scope. A variable declared at global scope is turned into a static field. A module declaration is a static class with let declarations compiled as fields/properties/methods. The simplest way to fix the problem is to write your code in a function: let main () = Array2D.zeroCreate 10000 10000 |> ignore printfn "%d" (GC.GetTotalMemory(true)) Array2D.zeroCreate 10000 10000 |> ignore printfn "%d" (GC.GetTotalMemory(true)) // (...) Console.ReadLine() |> ignore main () ... but why does the compiler declare fields when you're not using the value and just ignore it? This is quite interesting - the ignore function is a very simple function that is inlined when you use it. The declaration is let inline ignore _ = (). When inlining the function, the compiler declares some variables (to store the arguments of the function). So, another way to fix this is to omit ignore and write: Array2D.zeroCreate 10000 10000 printfn "%d" (GC.GetTotalMemory(true)) Array2D.zeroCreate 10000 10000 printfn "%d" (GC.GetTotalMemory(true)) // (...) You'll get some compiler warnings, because the result of expression is not unit, but it will work. However, using some function and writing code in local scope is probably more reliable.
{ "pile_set_name": "StackExchange" }
Q: How to split on ( not a value ) followed by ( a value )? I have this code here: var fields = row.split(/regex goes here/); I want to split row on each occurrence of | but not *| How do I write this simple regular expression. I thought there was a not character of sorts but I can't seem to find a good reference right now. I know I need to escape the special character | like this \|..but how do I add the not part? Likely I will just switch my markup to |* instead of *| and than I can this form I found on MDN - match x only if not followed by y. x(?!y) I'm testing here: http://www.regexpal.com/ Found a good reference here http://www.regular-expressions.info/reference.html https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp#Special_characters_in_regular_expressions A: Don't split() on the delimiter. Just .match() everything between delimiters: var fields = row.match(/(?:\*\||[^|])*/g); Explanation: (?: # Match either \*\| # *| | # or [^|] # any character except | )* # Repeat as needed
{ "pile_set_name": "StackExchange" }
Q: Why isn't my database being created in ASP.NET MVC4 with EF CodeFirst I've been following along with a tutorial by Julie Lerman about using EF CodeFirst to generate the database from code. I'm using MVC4 and working with the default controllers. All I want to do is generate the database. However, in her tutorial, she's working with a console application and calling a create_blog method in her Main function. The create_blog function does the work of creating the database as the name suggests. In my Global.asax, I have this: Database.SetInitializer(new CIT.Models.SampleData()); This is my SampleData class: public class SampleData : CreateDatabaseIfNotExists<Context> { protected override void Seed(Context context) { base.Seed(context); new List<Software> { new Software { Title = "Adobe Creative Suite", Version = "CS6", SerialNumber = "1234634543", Platform = "Mac", Notes = "Macs rock!", PurchaseDate = "2012-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Adobe" }}}, new Software { Title = "Apple iLife", Version = "2012", SerialNumber = "123463423453", Platform = "Mac", Notes = "Macs still rock!", PurchaseDate = "2012-11-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "81st Street" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Apple" }}}, new Software { Title = "Microsoft Office", Version = "2012", SerialNumber = "12346231434543", Platform = "PC", Notes = "Macs really rock!", PurchaseDate = "2011-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Microsoft" }}} }.ForEach(s => context.Software.Add(s)); } } I get no errors when I compile. I just get no database. I looked in my App_Data and all that's there is the default database. I have a dbContext that is getting called because when I had errors in it, they pointed to that file. Do I need to have some kind of create method that is called when the site first compiles? A: SetInitializer only sets the initializer strategy and the strategy is executed the first time you access the database. Try adding the following after calling SetInitializer using (var context = new Context()) { context.Database.Initialize(true); }
{ "pile_set_name": "StackExchange" }
Q: Using VLOOKUP in an array formula on Google Spreadsheets Effectively I want to give numeric scores to alphabetic grades and sum them. In Excel, putting the LOOKUP function into an array formula works: {=SUM(LOOKUP(grades, scoringarray))} With the VLOOKUP function this does not work (only gets the score for the first grade). Google Spreadsheets does not appear to have the LOOKUP function and VLOOKUP fails in the same way using: =SUM(ARRAYFORMULA(VLOOKUP(grades, scoresarray, 2, 0))) or =ARRAYFORMULA(SUM(VLOOKUP(grades, scoresarray, 2, 0))) Is it possible to do this (but I have the syntax wrong)? Can you suggest a method that allows having the calculation in one simple cell like this rather than hiding the lookups somewhere else and summing them afterwards? A: I still can't see the formulae in your example (just values), but that is exactly what I'm trying to do in terms of the result; obviously I can already do it "by the side" and sum separately - the key for me is doing it in one cell. I have looked at it again this morning - using the MATCH function for the lookup works in an array formula. But then the INDEX function does not. I have also tried using it with OFFSET and INDIRECT without success. Finally, the CHOOSE function does not seem to accept a cell range as its list to choose from - the range degrades to a single value (the first cell in the range). It should also be noted that the CHOOSE function only accepts 30 values to choose from (according to the documentation). All very annoying. However, I do now have a working solution in one cell: using the CHOOSE function and explicitly listing the result cells one by one in the arguments like this: =ARRAYFORMULA(SUM(CHOOSE(MATCH(D1:D8,Lookups!$A$1:$A$3,0), Lookups!$B$1,Lookups!$B$2,Lookups!$B$3))) Obviously this doesn't extend very well but hopefully the lookup tables are by nature quite fixed. For larger lookup tables it's a pain to type all the cells individually and some people may exceed the limit of 30 cells. I would certainly welcome a more elegant solution!
{ "pile_set_name": "StackExchange" }
Q: Looking for a HIERARCHY of math subjects If you were to "map" mathematics onto a tree structure where the top is "Mathematics", and then below it the different branches, then sub-branches, etc. What do you suggest is a good structure, for educational purposes? The idea is this - if I have a student learning a topic, then all I would have to do is look at all the sub-branches (and theirs) below that topic in the tree, to represent everything the student needs to know. I'm certain there will be overlaps, but I'm okay with this - looking for some insight on this, or relevant articles. If you think that such a hierarchy does not even exist, please let me know what you think the right structure is for educational purposes, and if you know where to find it. Many thanks! A: (1) Here is Margie Hale's tree: (2) And here is Gaspard Sagot's hierarchy:
{ "pile_set_name": "StackExchange" }
Q: Removing rows from dataframe whose first letter is in lowercase I have a dataframe like - FileName PageNo LineNo EntityName 1 17743633 - 1 TM000002 69 Ambuja Cement Limited 2 17743633 - 1 TM000003 14 Vessel Name 3 17743633 - 1 TM000003 12 tyre Chips (Shredded Tyres) 4 17743633 - 1 TM000006 22 ambuja Cement Limited 5 17743633 - 1 TM000006 28 Binani Cement Limited I have to remove those rows from the datframe in which EntityName column's first letter is lowercase. i.e I have to retain values that start with a upper case. I have used to methods till now - df['EntityName'] = map(lambda x: x[0].isupper(), df['EntityName']) but it is giving NaN values. another thing that i tried was regex. df['EntityName'] = df['EntityName'].str.replace('^[a-z]+$','') but it is showing no effect. another one was - qw = df.EntityName.str[0] df = df[qw.isupper()] but it is showing error - 'Series' object has no attribute 'isupper' Can someone suggest me the correct code snippet or any kind of hint? A: First select first letter by indexing and then check isupper or islower and filter by boolean indexing: df = df[df['EntityName'].str[0].str.isupper()] #for working with NaN and None #df = df[df['EntityName'].str[0].str.isupper().fillna(False)] Or: df = df[~df['EntityName'].str[0].str.islower()] #for working with NaN and None df = df[~df['EntityName'].str[0].str.islower().fillna(False)] Or use str.contains with regex - ^ is for match first value of string: df = df[df['EntityName'].str.contains('^[A-Z]+')] Solution if no NaNs in data is list comprehension: df = df[[x[0].isupper() for x in df['EntityName']]] More general solution working with empty strings and NaNs is add if-else: mask = [x[0].isupper() if isinstance(x,str) and len(x)>0 else False for x in df['EntityName']] df = df[mask] print (df) FileName ... EntityName 1 17743633 - 1 ... Ambuja Cement Limited 2 17743633 - 1 ... Vessel Name 5 17743633 - 1 ... Binani Cement Limited
{ "pile_set_name": "StackExchange" }
Q: Does this question deserve to be in the Review Audit List? Is this question a Good Question and qualified to be in Review Audit list? This question does not: Specify which RDBMS or Database is in use, so Proper database tags are missing Show any search effort Include already tried code I failed on this review in First Posts Review queue. I think, this question does not deserve to be in Review Audit List. Its in Review Audit list, based on UP-VOTES, but it should be based on content also. A: As @Brad Larson mentioned in comment that it seems upvotes comes to this question lately when OP add bounty regardless the question's quality. Then after upvotes this question becomes eligible to display in review audit list, and that's the starting of some unusual review audits where question have no quality. I've personally been seeing huge spikes in voting for questions with bounties lately, often without any relationship to their quality. Something about their visibility has changed in a way that's driving a ton of votes to anything with a bounty. It's led to a number of odd audit cases like this. – Brad Larson♦ Jul 26 at 22:05 So just down-vote and close the question is the only way to get rid of this type of review audits right now.
{ "pile_set_name": "StackExchange" }
Q: Dynamic url not generated currently for lat and Long android I have generated Current location value and i am passing it to the URL dynamically. I am getting value of Latitude and 'Longitude' in my Logcat. but dynamic URl for LatLongUrl is not generated currently. Log.d(String.valueOf(mLastLocation.getLatitude()),"Latitude"); Log.d(String.valueOf(mLastLocation.getLongitude()),"Longitude"); //urlJsonObj = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.2150756,72.8880545&radius=500&type=hospital&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg"; urlJsonObj = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+String.valueOf(mLastLocation.getLatitude()+","+String.valueOf(mLastLocation.getLongitude()+"&radius=500&type=hospital&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg"; Log.d(urlJsonObj,"LatLongUrl"); Logcat displaying as bellow in which value of Latitude and 'Longitude' generated but dynamic URl for LatLongUrl is not generated currently. 04-20 15:00:45.477 3209-3209/com.example.chaitanya.nearbyplace D/21.225225225225223: Latitude 04-20 15:00:45.477 3209-3209/com.example.chaitanya.nearbyplace D/72.8905100797212: Longitude [ 04-20 15:00:45.477 3209: 3209 D/https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.225225225225223&radLatLongUrl Updated quetion i have update code as bellow. but its still not generateed URL properly. String Latitude = String.valueOf(mLastLocation.getLatitude()); String Longitude = String.valueOf(mLastLocation.getLongitude()); urlJsonObj = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+Latitude+","+Longitude+"&radius=500&type="+TypeName+"&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg"; Log.d(urlJsonObj,"LatLongUrl"); in Logcat [ 04-20 15:24:57.826 23415:23415 D/https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.225225225225223,72.LatLongUrl A: Replace your line with this String urlJsonObj = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + new BigDecimal(mLastLocation.getLatitude()).toString() + "," + new BigDecimal(mLastLocation.getLongitude()).toString() + "&radius=500&type=hospital&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg";
{ "pile_set_name": "StackExchange" }
Q: Not set cookie overwriting method parameter So, I have a method that converts the timezone into another: public function timeZoneConverter($from, $to = "America/New_York", $outputformat){ $time = new DateTime($from, new DateTimeZone('America/New_York')); $time->setTimezone(new DateTimeZone($to)); return $time->format($outputformat); } I give the $to parameter value from a cookie like this: $calendar->timeZoneConverter($episode->air_date, $_COOKIE['timezone'], "Y-m-d H:i:s") But if the cookie is not set, the $to parameter returns NULL, although I set "America/New_York" to default Why? Is the null value of the cookie overwriting it? I can hard code it like this: if($to == null){ $to = "America/New_York"; } But this seems kinda stupid. A: That's what you'd have to do. Passing null to an optional parameter will not cause PHP to fall back to the default value, it'll just use the passed null. Besides, it doesn't make sense to put optional parameters in the middle of required parameters list. It's not possible to pass the required parameter $outputformat without passing some value to $to. You could remove the default value, and use the short coalescing syntax for handling the null case: $time->setTimezone(new DateTimeZone($to ?: 'America/New_York'));
{ "pile_set_name": "StackExchange" }
Q: Pester not mocking function that is dot-sourced I'm using Pester to test a PowerShell script that dot-sources another script. When I try to mock the function that is dot-sourced, Pester refuses to use the mocked version. I'm having the same problem when I try to source the function by using adding it to a .psm1 file and using Import-Module instead of dot-sourcing. Here's an example that replicates the problem I'm having. All 3 files are in the same folder. Foo.ps1 Function Invoke-Foo{ 'Cantelope' } Bar.ps1 function Invoke-Bar { . .\foo.ps1 Invoke-foo } Bar.tests.ps1 $here = Split-Path -Parent $MyInvocation.MyCommand.Path $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' . "$here\$sut" . .\Foo.ps1 Describe "Bar" { It "Mocks Foo" { Mock Invoke-Foo {'Banana'} Invoke-Bar | should be 'Banana' } } After mocking Invoke-Foo, the result should be 'Banana', but the result is: Describing Bar [-] Mocks Foo 36ms Expected string length 6 but was 9. Strings differ at index 0. Expected: {Banana} But was: {Cantelope} -----------^ 9: Invoke-Bar | should be 'Banana' at <ScriptBlock>, C:\Users\geinosky\Desktop\PingTest\Bar.tests.ps1: line 9 How can I get Pester to correctly work with the dot-sourced function? A: Invoke-Bar explicitly dot-sources Invoke-Foo from a file and then invokes it. The dot-sourced function hides other defined Invoke-Foo, including mocked. If we remove . .\foo.ps1 from Invoke-Bar then the Pester mock works, we get "Banana". If then we remove the mock then all works, i.e. all commands are found, but we get "Cantelope". In other words, if you want Invoke-Foo to be mockable then do not dot-source it in Invoke-Bar. Invoke-Bar should assume Invoke-Foo is pre-defined (the original or mocked) and just use it.
{ "pile_set_name": "StackExchange" }
Q: Wait for Ajax call in function to end, THEN return object to an outside variable I want to use JavaScript asynchronous, as it was intended. I want to assign the recieved data/objects to as many variables as I'll need (DataModel01, DataModel02, DataModel03 and so on). The idea is that my need for API data change all the time, and I want to only have to define once where to get the data (API endpoint), and in what local variable/object to store it. The way I'm doing it, it returns the object with recieved data from the fetchDataJSON() function. However, how do I make the return wait for the Ajax to finish? I've tried several things, including timers and callbacks, and nothing works at all. I saw the other questions regarding ajax and async, and generally it was suggested to use callbacks. So I believe I might be offtrack, but I need a hand to figure out a way to deal with this gracefully. Do I really need to mess with timers and ugly solutions like that? function fetchDataJSON(endpointUrl) { var returnObj = []; // Ajax call $.ajax({ type: "GET", url: endpointUrl, dataType: 'json', async: true, success: updateData, error: handleError }); function updateData(data) { returnObj = data; } function handleError(XHR, message, error) { console.log("Failed XHR"); } return returnObj; // Return JSON object } var DataModel01 = fetchDataJSON( "http://mydata.com/endpoint/sweetjson" ); var DataModel02 = fetchDataJSON( "http://mydata.com/endpoint/somethingelse" ); EDIT: I found a working solution now, yihar. I've marked the answer by Karman as accepted, as it was the one closest to the solution. My final solution, which was also inspired by a coworker, is as follows: var DataModel01 = []; var DataModel02 = []; function fetchDataJSON(endpointUrl, callbackWhenDone) { // Ajax call $.ajax({ type: "GET", url: endpointUrl, dataType: 'json', async: true, success: updateData, error: handleError }); function updateData(data) { callbackWhenDone(data); } function handleError(XHR, message, error) { console.log("Failed XHR"); } } fetchDataJSON( "http://mydata.com/endpoint/sweetjson", function(newData) { DataModel01 = newData; } ); fetchDataJSON( "http://mydata.com/endpoint/somethingelse", function(newData) { DataModel02 = newData; } ); A: function fetchDataJSON(endpointUrl, callback) { function updateData(data) { returnObj = data; callback(returnObj) } fetchDataJSON( "http://mydata.com/endpoint/sweetjson", getJson ); enter code here function getJson(returnObj) { //do work with returnObj }
{ "pile_set_name": "StackExchange" }
Q: Error while creating a table from the values of two tables I am new to sql. I was just trying to create and store data into a table from the values of two tables 1 st table has UserName. 2nd table has password. So, I have written a sql query with gets both values from two tables and display it in a single table. Create table tablename as select T1.username, T2.Password from Table1.T1, Table2.T2 where T1.UserId = T2.UserId; Here in both tables UserId is common. I am getting error while executing this statement. The error is InCorrect Syntax. Error is near SELECT statement. Can you help me Please, Thanks in advance A: SQL Server does not support CREATE TABLE AS. Instead, use INTO: select T1.username, T2.Password into tablename from Table1.T1 join Table2.T2 on T1.UserId = T2.UserId; Notice that I also fixed your join syntax. Although the use of commas in the FROM clause does not generate an error, it should.
{ "pile_set_name": "StackExchange" }
Q: QML TableView rowDelegate styleData.row not defined I am trying to create a custom row delegate for a TableView. according to the Documentation, the rowDelegate should have access to a property called styleData.row. However, when I'm try to access this property, it is undefined. I used the debugger to check whats inside the styleData, and the row is missing: My code is very simple: TableView { width: 500//DEBUG height: 300//DEBUG model: ListModel { ListElement { lectureName: "Baum1" } ListElement { lectureName: "Baum2" } ListElement { lectureName: "Baum3" } ListElement { lectureName: "Baum4" } } rowDelegate: HeaderRowDelegate {//simply a Rectangle with an in property called "modelRow" id: rowDelegate modelRow: { var data = styleData; return data.row; } } TableViewColumn { id: c1 role: "lectureName" title: "TEST" } } A: You don't have to assign it yourself: as the HeaderRowDelegate component is assigned to the rowDelegate property of the TableView, your component has already access to the styleData.row property. Here's an example: main.qml import QtQuick 2.4 import QtQuick.Layouts 1.1 import QtQuick.Controls.Styles 1.2 import QtQuick.Controls 1.3 ApplicationWindow { id: app title: qsTr("Test") width: 800 height: 600 TableView { width: 500//DEBUG height: 300//DEBUG model: ListModel { ListElement { lectureName: "Baum1" } ListElement { lectureName: "Baum2" } ListElement { lectureName: "Baum3" } ListElement { lectureName: "Baum4" } } rowDelegate: RowDel {} TableViewColumn { id: c1 role: "lectureName" title: "TEST" } } } Now the row delegate, RowDel.qml import QtQuick 2.4 Rectangle { id: rowDel color: "blue" height: 60 readonly property int modelRow: styleData.row ? styleData.row : 0 MouseArea { anchors.fill: parent onClicked: { console.log("[!] log: " + modelRow); } } } The important thing here is that you can reference styleData.row directly from your component (obliviously as long as you use this precise component as a row delegate). As an example, if you click on each tableview row, you should see the correct row number displayed in the console log: qml: [!] log: 0 qml: [!] log: 1 qml: [!] log: 2 qml: [!] log: 3
{ "pile_set_name": "StackExchange" }
Q: how to choose a random secret key for ECDH I am a beginner, I can understand the basics of ECC and elliptic curve, i can't find where I missed to understand. But I have a great doubt in ECDH regarding below. Could any of you please clarify for me? I will ask with the help of an example. Example: Let $G=(1,3)$ be the generator point with order $n=18$ for an elliptic curve $E(13,24)\bmod29$. I want to calculate Public key for both Alice and Bob. Now Let the secret key of Alice be $A=5$ and of Bob be $B=7$ (such that the scalar which is multiplying with $G$ should be less than the order $n$ of the generator point). Now the public key of Alice is $P_A=A\cdot G=5\cdot G=5(1,3)=(19,7)$ and the public key of Bob is $P_B=B\cdot G=7\cdot G=7(1,3)=(15,6)$ Now after transmitting the public key mutually, the parties have to calculate the shared secret key. The shared key of Alice is $S_A=A\cdot P_B=5(15,6)=(23,1)$ and the shared key of Bob is $S_B=B\cdot P_A=7(19,7)=\mathcal O$(Point at infinity). The shared secret supposed to be the same. But I am getting the point at infinity instead of $(23,1)$. How to overcome this? My doubt is,if this is the case how can the sender and receiver get the shared key in ECDH? If not, kindly quote where I did mistake here and in what i misunderstood? A: What curve are you considering, in what field, using what addition formulas? From the data you provided, I assume you are talking about the curve of the form $y^2 = x^3 + 24x + 13$, in the field $\mathbb{Z}_{29}$ of the integer modulo $29$, because then your generator $G=(1,3)$ is effectively on the curve: $$1 + 24+ 13 \equiv 9=3^2 \pmod{29}.$$ And the public points you computed, $(19,7)$ and $(15,6)$ are effectively on the curve and correspond to the correct values. Now, simple addition formulas for such a curve would be, given two points $P=(x_1,y_1)$ and $Q=(x_2,y_2)$, that we sum together into $R=(x_3,y_3)=P+Q$: $$ x_3= \left(\frac{y_2-y_1}{x_2-x_1}\right)^2-x_1-x_2 $$ $$ y_3=-y_1+\left(\frac{y_2-y_1}{x_2-x_1}\right)(x_1-x_3) $$ But those are not always working, most notably not if $x_1=x_2$, so we need another formula for point doubling, given $P=(x_1,y_1)$ and $R=(x_2,y_2)=2P$, we have that: $$ x_2=\left(\frac{3x_1^2+24}{2y_1}\right)^2 -2x_1 $$ $$ y_2=\left(\frac{3x_1^2+24}{2y_1}\right)(x_1-x_2)-y_1$$ and even this would only work if $y_1\neq 0$. Remark that on that regard, Wikipedia currently forgets to precise that there are such cases where the formulas cannot be used. Now, you have a mistake in your latest computation: you want to take $P_A=(19,7)$ and multiply by 7 using those two formulas, so: $$\begin{align} 2P_A&=(4,17) &\text{doubling}\\ 3P_A&=2P_A+P_A=(0,19) &\text{addition}\\ 4P_A&=2(2P_A)=(1,3) &\text{doubling}\\ 7P_A&=4P_A+3P_A=(23,1) &\text{addition}\end{align}$$ So as you can see, $7(19,7)\neq\mathcal{O}$ as you computed, but it really works and is equal to $(23,1)$. Note that there exist complete formulas for such curves, see for example this paper, so that you can have just one formulas to do everything.
{ "pile_set_name": "StackExchange" }
Q: Question on AJAX Library (like DWR) I have a web app which uses AJAX library (DWR) to get data dynamically i.e. as user clicks on some table items, it dynamically gets details for that item by making a DWR call...It actually gets the complete HTML code as string for the table (Actually in the background, a Java method does the processing and returns the HTML string)...So the usage is like this; someDWRObj.someJavaMethod(someData,callBackFunction); I am sure MOST of you would say that this is NOT at all a GOOD practice.. So my question is, is DWR an outdated technology, what are the replacements for DWR technology (more specifically to implement what i am trying to do above) ? Can DOJO do what DWR does ? All the questions assume that I'll be using Java in the middle tier.. Thank you. A: If you are writing if from scratch again then you could consider some existing frameworks like GWT or Vaadin. If not, then I guess you could just use a REST web services on the server side exposing your existing functionality using REST with JSON objects and on the client side (html page) you can parse JSON data with JQuery to suit your needs.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between symbols? I checked that :xyz == 'xyz' is false. But we can call functions inside rails with :index or 'index'. Please clear my wonder. A: :xyz and 'xyz' are indeed different. That does not contradict with the fact that a method can take either type of argument. For example, Array#* can take a String or Integer as an argument: ["a", "b"] * "foo" # => "afoob" ["a", "b"] * 2 # => ["a", "b", "a", "b"] but that does not mean that "foo" is the same as 2. And if you follow the logic you are implying, it would mean that all objects in Ruby are the same. A: I checked that :xyz == 'xyz' is false. But we can call functions inside rails with :index or 'index'. Please clear my wonder. There is nothing mysterious about this. Symbol#== is a method just like any other method. The person who wrote it, wrote it in such a way that it returns false. She could have written it to return true or return 42 or format your harddisk, but she decided to return false. Rails methods are methods just like any other method. The person who wrote them, wrote them in such a way that accepts either Symbols or Strings. She could have written them to accept only Symbols or only Strings or to accept only Strings on even days of the week, only Strings on odd days of the week, and only Integers during a full moon, but she decided to accept both Strings and Symbols. The developers who write Rails and the developers who write Ruby are free to do in their methods whatever they want, just like you are free to do whatever you want in methods you write. You can write a method that accepts Strings, you can write a method that accepts Symbols, you can write a method that accepts both, you can write a method that accepts neither. It's your choice, just like it is the choice of the Rails and Ruby developers. It implies absolutely nothing about the relationship between Symbols and Strings. A: :xyz is a symbol. A symbol is an instance of the class Symbol. "xyz" is a string. A string is not a Symbol. Therefore, :xyz=='xyz' is not true. Because the instance of Symbol that is :xyz is not equivalent to the instance of String xyz.
{ "pile_set_name": "StackExchange" }
Q: What is purpose of reset.css & text.css in 960 Grid CSS? I'm newbie to 960 Grid CSS & I found in some tutorial's that I need to use reset.css & text.css Can anyone explain actual purpose of these two files? A: Eric Meyer's CSS Reset (http://meyerweb.com/eric/tools/css/reset/)is a very popular example, and one I use fairly religiously. Like @Jared points out, it "overrides the browser's typical style behavior". What that should mean to you (as it does me) is that regardless of browser, all of my input fields will have the same margin, padding, borders, etc. All of my <p> tags will have behave the same - they've all been "reset" to take on NO default style based on the browser rendering the page....I have to tell EVERYTHING how to look, behave, etc. I have no idea what text.css is - unless that's a separate CSS file for all of my @font-face usage, which is what I do (and would recommend to anyone). HTH
{ "pile_set_name": "StackExchange" }
Q: WIX-Installer MSI Publisher Unknown How to provide publisher Name for MSI installer which is developed using WIX Installer? While installing my .msi installer it's showing unknown publisher, how to provide a name for publisher?Is it possible to do this within WIX? If so kindly help me how to implement this using WIX installer. A: I think you are looking to avoid the security warning that is displayed when someone installs your setup. For this you would need to sign the setup with your certificate and a private key. You can try to do this by following the steps explained in the following links: How to Digitally Sign Microsoft Files Signing .MSI and .EXE files Everything you need to know about Authenticode Code Signing Assuming you are looking for a publisher name in the control panel Programs and Features. You could use the Manufacturer attribute in your Product tag. <Product Id="PUT-YOUR-GUID" Manufacturer="PublisherName" Name="ProductName" UpgradeCode="PUT-YOUR-GUID" Version="1.0.0"> A: Using WiX's in-built tool insignia is fairly straight-forward. Here's the steps to do code-sign a WiX MSI: Set up the signtool as a batch file in my PATH so that I can call it and change it easily. I'm running Windows 10 and so my "signtool.bat" looks like this: "c:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe" %* Set up insignia as a batch file in my PATH too so you can change it with new WiX builds as they come. My "insignia.bat" looks like this: "C:\Program Files (x86)\WiX Toolset v3.10\bin\insignia.exe" %* Sign my MSI in a post-build event (MSI Project -> Properties -> Build Events) by calling this: signtool sign /f "c:\certificates\mycert.pfx" /p cert-password /d "Your Installer Label" /t http://timestamp.verisign.com/scripts/timstamp.dll /v $(TargetFileName) Further notes and thoughts: I have also signed the application (I think) by just doing Project Properties -> Signing and enabling click-once manifests, selecting the certificate and checking the Sign the assembly option. Here's my similar answer on how to do the same but for a bootstrap bundle: using insignia to sign WiX MSI and bootstrap bundle
{ "pile_set_name": "StackExchange" }
Q: Can I get the access mode of a `FILE*`? I have to duplicate a FILE* in C on Mac OS X (using POSIX int file descriptors all the way is unfortunately out of question), so I came up with the following function: static FILE* fdup(FILE* fp, const char* mode) { int fd = fileno(fp); int duplicated = dup(fd); return fdopen(duplicated, mode); } It works very well, except it has that small ugly part where I ask for the file mode again, because fdopen apparently can't determine it itself. This issue isn't critical, since basically, I'm just using it for stdin, stdout and stderr (and obviously I know the access modes of those three). However, it would be more elegant if I didn't have to know it myself; and this is probably possible since the dup call doesn't need it. How can I determine the access mode of a FILE* stream? A: You can't, but you can determine the mode for the underlying file descriptor: int fd = fileno(f); int accmode = fcntl(fd, F_GETFL) & O_ACCMODE; You can then choose an appropriate mode to pass to fdopen based on whether accmode is O_RDONLY, O_WRONLY, or O_RDWR.
{ "pile_set_name": "StackExchange" }
Q: CSS not linked to HTML page Good morning guys, I am playing around building a small website. In the html I have my link to my CSS file but for some reason the CSS is not being shown on the page. The link tag looks as follows: <link rel="stylesheet" href="./styles/style.css" type="text/css"> The site does not contain any styles that I have built. Am I doing something wrong here? A: Folder Structure 1 index.html styles (folder) style.css If this the folder structure then your link tag should be <link rel="stylesheet" href="styles/style.css" type="text/css" /> Folder Structure 2 index.html style.css If your folder structure is like the above then the link tag should be <link rel="stylesheet" href="style.css" type="text/css" /> Folder Structure 3 HTML (folder) index.html styles (folder) style.css If your folder structure is like above then the link tag should be <link rel="stylesheet" href="../styles/style.css" type="text/css" /> This might help you. For any error check the browser console.
{ "pile_set_name": "StackExchange" }
Q: SWIFT URLResponse no output // Google Maps PI I build an little task in SWIFT-XCode where I am trying to fetch and print some JSON Data, but the console doesn´t show me any error´s or result. Maybe someone can help me with the problem?. Here´s my code: let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(lat),\(long)&destination=\(lat+auflong),\(long+auflat)&key=**************") let task = URLSession.shared.dataTask(with: url!) { (data:Data?, response:URLResponse?, error:Error?) in if let data = data { do { // Convert the data to JSON let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] if let json = jsonSerialized, let url = json["url"], let explanation = json["explanation"] { print(url) print(explanation) } } catch let error as NSError { print(error.localizedDescription) } } else if let error = error { print(error.localizedDescription) } } task.resume() A: If you debug-step through the code, you see the result in the debug area: watch area. In my test (using incorrect co-ordinates), when I put a breakpoint at the line starting `let jsonSerialized = '..., return 3 dictionary keys: status error_message routes But you were expecting url and explantion... If you change the inner like: let jsonSerialized = ... if let json = jsonSerialized { print(json) if let url = json["url"], let explanation = json["explanation"] { print(url) print(explanation) } } } catch ... you'll be able to print the returned json. (Replaced some code with ... for easy reading.) My output: ["status": REQUEST_DENIED, "error_message": The provided API key is invalid., "routes": <__NSArray0 0x600000003910>( ) ]
{ "pile_set_name": "StackExchange" }
Q: saxon: using fn:doc() in a query parameter Why can't I use fn:doc in a "query parameter using xpath"? The document parameter is working fine: saxon -q:test.xq +foo=foo.xml But this gives me the error "Unrecognized option: foo.xml" saxon -q:test.xq ?foo=doc("foo.xml") A: It's probably your shell. Different shells vary in their handling of special characters, but the quotes probably need escaping (with backslashes), or you could do saxon -q:test.xq "?foo=doc('foo.xml')"
{ "pile_set_name": "StackExchange" }
Q: Populate a dropdown inside an include PHP I have an index.php which calls the DB connection and populates the page. If a condition is met an include will be called upon with a dropdown list. I am unable to populate this dropdown, it gives me no error just a blank screen. index.php: <?php require_once('db_connection.php'); if($_GET["cat"] === "contact"){ include ('includes/contact.php'); } else{ include ('includes/route.php'); } ?> contact.php: <?php $sql = "SELECT * FROM dropdown_town"; $result = $dbhandle->query($sql); $town = $result->fetch_assoc(); while ($row = mysql_fetch_array($town)) { echo "<option value='" . $row['zip'] . "'>" . $row['townname'] . " </option>"; } ?> My DB has a table called dropdown_town with the columns ID, zip and townname I only posted the PHP code here as the rest of the page runs ok A: Do the following changes in your contact.php You forgot yo write select and directly write option because of that you got the blank page. <?php $sql = "SELECT * FROM dropdown_town"; $result = $dbhandle->query($sql); echo "<select name="selectboxname">"; while ($row = mysql_fetch_array($result)) { echo "<option value='" . $row['zip'] . "'>" . $row['townname'] . " </option>"; } echo "</select>"; ?>
{ "pile_set_name": "StackExchange" }
Q: How can I check programmatically if a drive is subject to system restore feature in windows? As the title tells, I need a programmatic way to find out if a particular disk drive is subject to System Restore in Windows. You may see this information in Control Panel/System/System protection tab. I'm developing a security-related app for windows, and it is crucial that some of its internal files are present strictly in a single copy. I'd like to prevent this files from being inadvertently copied/backed up by windows. Or at least to warn the user of the ensuing security risk. I know of the HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToBackup but it doesn't solve the problem because it is used only at the restore phase, and the file contents is still present in the backup storage. There is also HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore, but it doesn't contain information about subject disks, at least I don't see it. Any clues are greatly appreciated. A: System restore is managed by the Volume Shadow Copy api. You need to call the QueryVolumesSupportedForDiffAreas method and inside the returned IVssEnumMgmtObject will be a VSS_DIFF_VOLUME_PROP structure which will tell you if any storage area is reserved in the m_llVolumeTotalSpace parameter. Alternatively you could parse the output of the vssadmin list shadowstoragecommand , or its equivalent in Powershell/WMI by exploring the Get-CimClass -ClassName *shadow command. These commands correspond to wmiobjects and the wmi api which may be easier to use and more accessible depending on your background and programming environment. Also consider using the FilesNotToSnapshot instead of FilesNotToBackup. It is the one used for VSS/System Restore. You should read this document on its usage and also an api that lets you exclude files, and take note particularly about the cases where it might not work as you intend.
{ "pile_set_name": "StackExchange" }
Q: How to debug droplets using AppleScript Just 3 lines of script to be able to test a droplet application without leaving applescript editor set fich to POSIX file "/Appli/conv2spct.app" as string tell application "Finder" to open POSIX file "/Users/yourusername/Desktop/somefile" using application file fich If there are errors in your droplet a display dialog will be opened by the script editor applescript A: Here's a pragmatic alternative using do shell script, which potentially allows you to specify multiple file arguments: do shell script "open -a /Appli/conv2spct.app ~/Desktop/somefile1 ~/Desktop/somefile2" The above paths happen not to need quoting (escaping) for the shell, but when using variables to specify the file paths, it's best to use quoted form of (to pass multiple arguments, apply quoted form of to each): do shell script "open -a " & quoted form of fileappli & " " & quoted form of fileargument
{ "pile_set_name": "StackExchange" }
Q: Alert on with Javascript I have a table on my JSP file that show my products and on every row I have a button that delete this data: <body> <table> <tr> <td>ID</td> <td>Name</td> <td>Value</td> <td>Quantity</td> <td>Total</td> </tr> <c:forEach var="product" items="${list}"> <tr> <td>${product.id}</td> <td>${product.name}</td> <td>R$${product.value}</td> <td>${product.quantity}</td> <td>R$${product.quantity * product.value}</td> <td><a href="showProduct?id=${product.id}">Edit</a></td> <td><a href="deleteProduct?id=${product.id}">Delete</a></td> </tr> </c:forEach> </table> <br><br> <a href="newProduct">New product</a> </body> I wish to create an alert when I click on Delete button. I know that I have to use javascript, but, how can I after click on "Ok" redirect to my controller deleteProduct ? I tried something like this: <script> if (confirm('Do you really want to delet this product?')) { ??? } else { alert('The product was not deleted'); } </script> Thanks! A: Here is my solution function confirmDelete(aProductID){ if (confirm('Do you really want to delet this product?')) { document.location.href='deleteProduct?id='+aProductID; } else { alert('The product was not deleted'); } } <body> <table> <tr> <td>ID</td> <td>Name</td> <td>Value</td> <td>Quantity</td> <td>Total</td> </tr> <c:forEach var="product" items="${list}"> <tr> <td>${product.id}</td> <td>${product.name}</td> <td>R$${product.value}</td> <td>${product.quantity}</td> <td>R$${product.quantity * product.value}</td> <td><a href="showProduct?id=${product.id}">Edit</a></td> <td><a href="#1" onclick="confirmDelete(${product.id})">Delete</a></td> </tr> </c:forEach> </table> <br><br> <a href="newProduct">New product</a> </body>
{ "pile_set_name": "StackExchange" }
Q: Show that two points from four are at a distance $\leq \sqrt{3}$ in an equilateral triangle. In a given equilateral triangle of sides length $3$, we locate 4 points. Prove that there are two of them are located at a distance less or equal to $\sqrt{3}$. I arranged the four points in this configuration: As the picture shows, I proved that if tree points are located in the triangle vertexes and the fourth point lies in the intersection of the medians, the distance $P_1P4=P_2P_4=P_3P_4=\sqrt{3}$. I tried to argue with the hinge theorem and it sort of make sense, but this is not a proof. Can anyone help me how can I approach to this problems proof ? and How can I show that this case is the general one ? or isn't it ? A: Your lines partition the triangle into three "kites". By pigeon-hole, one kite must contain at least two points. The kites are contained within disks of diameter $\sqrt 3$ (thanks to Thales), hence two points in the same kite cannot be further apart than $\sqrt 3$.
{ "pile_set_name": "StackExchange" }
Q: Angular ui-select multiple clean ng-model value I am trying to use the ui-select and the component is cleaning my array. Example: {{ vm.staff_hotels }} <ui-select multiple ng-model="x" theme="bootstrap"> <ui-select-match placeholder="Not selected">{{$item.name}}</ui-select-match> <ui-select-choices repeat="hotel.id as hotel in vm.hotels | filter: {active: true} | filter: $select.search"> <div ng-bind-html="hotel.name | highlight: $select.search"></div> </ui-select-choices> </ui-select> My variable "vm.staff_hotels" value on screen is [1,2]. {{ vm.staff_hotels }} <ui-select multiple ng-model="vm.staff_hotels" theme="bootstrap"> <ui-select-match placeholder="Not selected">{{$item.name}}</ui-select-match> <ui-select-choices repeat="hotel.id as hotel in vm.hotels | filter: {active: true} | filter: $select.search"> <div ng-bind-html="hotel.name | highlight: $select.search"></div> </ui-select-choices> </ui-select> but, if I use the variable in ng-model my value change to [null,null]. A: I just need to update the version of my ui-select. I used to use version 0.10.0 I updated to version 0.11.2 Just a bug!
{ "pile_set_name": "StackExchange" }
Q: how to apply gvim regular expressions to multiple files How to apply regular expressions to multiple files in gvim ? A: I am going to assume "apply regular expressions", means use a substitution via :s over many files. Vim does not come with an "all-in-one" native project-wide find & replace command. Instead it is typically a two step process: Collect locations/files/buffers/windows/tabs Apply a command over the collection with a *do command Arg list The arg list is simply a list of files. You can populate it when you start Vim, e.g. vim *.txt or via :args once Vim has started. :args *.txt :argdo %s/foo/bar/g | w Quickfix/Location List The quickfix (& location list) are simply a list of locations, e.g. file, line, column. You can populate these lists with many commands, e.g. :vimgrep, :grep, :make, :cexpr, etc. Use :cdo to run a command over each location. :cfdo will run a command over each file in the list. :vimgrep /foo/ **/*.txt :cfdo %s/foo/bar/g | w Many people like to use :grep as you can customize the 'grepprg' to use a fast grep alternative, e.g The Silver Searcher, ripgrep, ack. I would also recommend mapping :cnext & :cprev. Buffers You can run a command on all opened buffers with :bufdo. Use :ls to see what buffers you have open. :bufdo %s/foo/bar/g | w Windows Can run a command over all windows in a the current tab page with :windo. This is helpful to do diff'ing via :windo diffthis. :windo %s/foo/bar/g | w Tabs Run a command over all tabs via :tabdo. :tabdo %s/foo/bar/g | w Assorted tips Some thoughts for better find & replace workflows. Use the e flag to prevent :s from stopping when no match can be found. May want to build your search pattern ahead of time then use :s//{replacment} to avoid typing out the pattern again. Look into using traces.vim to give a visual feedback for substitutions. As with all project-wide substitutions it is best to use some sort of version control (e.g. git, mercurial, svn) in case something goes terribly wrong. Personally, I typically use quickfix list for most of my multiple file substitutions. I use :grep with ripgrep for fast project searching. For more help see: Related Vimcasts episodes: Project-wide find and replace Search multiple files with :vimgrep Using :argdo to change multiple files Also see: :h :s :h :bar :h arglist :h :argdo :h quickfix :h :cdo :h :grep :h :vimgrep :h 'grepprg' :h buffer :h :bufdo :h window :h :windo :h tabpage :h :tabdo A: try opening all files in tab mode i.e gvim -p file1 file2 ..... then do :tabdo
{ "pile_set_name": "StackExchange" }
Q: Magnitude of instantaneous velocity vs speed Magnitude of instantaneous velocity = $|dr/dt|$ but this is not always equal to $ds/dt$ where ds is the infinitesimally small change in distance in the interval $dt$ Which one is speed? A: For both you are only travelling an infinitesimal amount. The difference between $\Delta r$ and $\Delta s$ goes away as $\Delta$ becomes smaller. In this case it's $ds$ and $dr$ which is the limit where they become equal. You can look at your drawing and imagine as you decrease r and s, the space between the line $dr$ and the arc of the circle will keep getting smaller until at an infinitesimally small value they are the same.
{ "pile_set_name": "StackExchange" }
Q: Android app crashes unexpectedly I am new to Android developement and had recently started on a project to get WiFi SSID, BSSID and MAC address. However, the app crashed unexpectedly immediately after opening it. The error log in Android Studio says that: FATAL EXCEPTION: main Process: com.example.android.wifi, PID: 3875 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.wifi/com.example.android.wifi}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2993) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3248) at ... Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at android.app.Activity.findViewById(Activity.java:2277) at com.example.android.wifi.MainActivity.<init>(MainActivity.java:16) at ... My java file can be found at http://www.yikjin.ga/MainActivity.java There were no syntax errors recorded by Android Studio. Thanks in advance! A: From your error is seems you are trying to get the View inside the constructor of your class or you are calling findViewById() outside. com.example.android.wifi.MainActivity.<init>(MainActivity.java:16) Move those code to onCreate() method after calling setContentView() Update: Change TextView viewWifiSSID = (TextView) findViewById(R.id.network); TextView viewWifiBSSID = (TextView) findViewById(R.id.bssid); TextView viewWifiMAC = (TextView) findViewById(R.id.mac); to TextView viewWifiSSID; TextView viewWifiBSSID; TextView viewWifiMAC; and add the following to onCreate() after setContentView() viewWifiSSID = (TextView) findViewById(R.id.network); viewWifiBSSID = (TextView) findViewById(R.id.bssid); viewWifiMAC = (TextView) findViewById(R.id.mac);
{ "pile_set_name": "StackExchange" }
Q: PHP get continue date next month and get price loan every month with interest pay on first month I'm continuing with my previous question. Now I need to set loan every month with price value. The price value is get from totalLoan * 5% Example: Total loan = 4,000,000 IDR format Total month loan = 4 Interest = 5% So We get, IDR 4,200,000 Now I need to set the interest 5% bill in the first month. To be like this: 28-Apr-2019 - 1,200,000 28-May-2019 - 1,000,000 28-Jun-2019 - 1,000,000 28-Jul-2019 - 1,000,000 And the PHP like this below so far: $totalLoan = "4000000"; $interest= "5"; //<-- 5% $loan = 4; $fixedDateEveryMonth = 28; $start = new DateTime(date('Y-m-') . $fixedDateEveryMonth); for($i = 1; $i <= $loan; $i++) { $start->add(new DateInterval("P1M")); $dateLoan = $start->format('Y-m-d'); echo $dateLoan." = ".$priceLoan; //<-- assume } How to do that? A: You could try this. It computes the loan instalments as the totalLoan divided by the number of loan periods, then adds the total interest (totalLoan * interest / 100) to the first instalment; resetting the instalment value after the first payment: $totalLoan = "4000000"; $interest= "5"; //<-- 5% $loan = 4; $instalment = $totalLoan / $loan; $priceLoan = $instalment + $totalLoan * $interest / 100; $fixedDateEveryMonth = 28; $start = new DateTime(date('Y-m-') . $fixedDateEveryMonth); for ($i = 1; $i <= $loan; $i++) { $start->add(new DateInterval("P1M")); $dateLoan = $start->format('Y-m-d'); echo "$dateLoan - " . number_format($priceLoan, 0) . "\n"; $priceLoan = $instalment; } Output: 28-Apr-2019 - 1,200,000 28-May-2019 - 1,000,000 28-Jun-2019 - 1,000,000 28-Jul-2019 - 1,000,000 Demo on 3v4l.org
{ "pile_set_name": "StackExchange" }
Q: appharbor not deploying static content I just started hosting a web application on AppHarbor, and i configured it to listen to my github repository commits. After each commit, I see on AppHarbor the build running the tests, and deploying, but when i go to my app page, hosted on AppHarbor I don't see any images, and the js scripts are missing. I can actually see them in the github source, but when I download the package from AppHarbor, they seem to be missing from my 'static' folder... Anyone else run into this problem ?... Any possible causes for this ?... A: I solved the problem - The reason this was happening because the content wasn't being copied to the output directory. I don't know exactly how AppHarbor build there Deployment scripts, but I changed the Copy To Output Directory option value to Copy Always and this solved the problem. (The Build Action was already set to Content)
{ "pile_set_name": "StackExchange" }
Q: Changing background-image of div via click on another div First of all my code can be found here in total. http://jsfiddle.net/yfukm8kh/1/ The part I'm having problems with is the following. var changePic = function (direction, id, array) { var intID = parseInt(id); var intDir = parseInt(direction); if (intID > 0) { intID = intID + intDir; currentID = intID; alert(array[intID].link); $('#lightbox').css("background-image", array[intID].link); } else if (intID == 0 && intDir == 1) { intID = intID + intDir; currentID = intID; alert(array[intID].link); $('#lightbox').css("background-image", array[intID].link); } }; What I want this function to do is changing the background-image of the div id=lightbox to one with the URL in the array I'm giving the function. However when I click on the sidebars the whole <div id=lightbox>is removed again as if I had clicked on the div itself() and not on the sidebar. However if I put an alert inside the function it shows that the event was triggered and at least some code inside the function was executed. I'm now assuming that when I click on the sidebar I'm triggering two events, the one that would change the background-image and one that removes the lightbox again. Is there any way to prevent the underlying div from "listening" to the click? Also, please correct me if I'm using any terms incorrectly or my posting etiquette is off. I'm new to all of this and would appreciate the input from experienced users. Thanks a lot. A: you have to stop event propagation using stopPropagation() in the side bar events: event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. Code: $(document).on('click', '#leftBar', function (event) { event.stopPropagation(); changePic(-1, currentID, activeArray); }); $(document).on('click', '#rightBar', function (event) { event.stopPropagation(); changePic(1, currentID, activeArray); }); UPDATED FIDDLE: http://jsfiddle.net/yfukm8kh/3/ You should read about Event Bubbling and Propagation
{ "pile_set_name": "StackExchange" }
Q: Excluding elements contained within another element with CSS or XPath Here's a chunk of XML: <xml> <section> <element>good</element> <section class="ignored"> <element>bad</element> </section> </section> </xml> It's easy enough to select all elements, or all elements inside a section.ignored: @doc.css('element').text => "goodbad" @doc.css('section.ignored element').text => "bad" But how do I select all elements that are not inside section.ignored? This doesn't work: @doc.css('section:not(.ignored) element').text => "goodbad" ...because that actually means "all elements that are contained in any section that is not ignored", including the top-level section that wraps everything else! Additional twist: unlike the simplified sample above, the real XML I have to deal with is nested to arbitrary depth, including sections within the ignored section(s). And yes, I could just substract the bad array from the full array in Ruby and call it a day, but I'd prefer a pure CSS solution (or, if you must, XPath) if possible. A: how do I select all elements that are not inside section.ignored ? Use this XPath expression: //element[not(ancestor::section[@class='ignored'])] This selects any element named element that doesn't have an ancestor named section, the string value of whose class attribute is the string "ignored" . XSLT - based verification: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/"> <xsl:copy-of select= "//element[not(ancestor::section[@class='ignored'])]"/> </xsl:template> </xsl:stylesheet> When this transformation is applied on the provided XML document: <xml> <section> <element>good</element> <section class="ignored"> <element>bad</element> </section> </section> </xml> the above XPath expression is evaluated and all (in this case just one) selected nodes are copied to the output. The wanted, correct result is produced: <element>good</element>
{ "pile_set_name": "StackExchange" }
Q: The truth of Nyonyon Theorem Let $s= ab$ be a semiprime number. Then the Nyonyon Theorem states that $s+a$, $s+b$, $s+a+b$ are not all coprime to three. (In other words: there exist no $s= ab$ semiprimes such that $s+a$, $s+b$ and $s+a+b$ are coprime to three.) I've checked plenty of numbers, and I think Nyonyon Theorem is absolutely true, but I don't understand why this phenomena happens. Can someone explain/proof to me why this thing happens ? A: If $s$ is coprime to $3$, then both $a,b$ are coprime to $3$. We have three possibilities. If $a \equiv b \equiv 1 \pmod 3$, then $s \equiv 1 \pmod 3$ and so $s + a + b$ is divisible by $3$. If $a \equiv 1 \pmod 3$ and $b \equiv 2 \pmod 3$, then $s \equiv 2 \pmod 3$ and so $s + a$ is divisible by $3$. (Similarly if the roles of $a,b$ are reversed). If $a \equiv b \equiv 2 \pmod 3$, then $s \equiv 1 \pmod 3$ and $s + a$ and $s + b$ are divisible by $3$. This proves the theorem. $\diamondsuit$ A: If none of $$ab+a,\quad ab+b,\quad ab+a+b $$ are divisible by three, then none of $$ a(b+1),\quad b(a+1),\quad (a+1)(b+1)-1 $$ are divisible by three. So $a,b\not\in\{0,2\}\pmod{3}$, that implies $a\equiv b\equiv 1\pmod{3}$. But in such a case: $$ (a+1)(b+1)-1 \equiv 2\cdot 2-1\equiv 0\pmod{3}.$$
{ "pile_set_name": "StackExchange" }
Q: How do I count the occurences of the values in each row of a joined table? I am creating a database for a hotel system using sql developer and oracle 11g and I need to print the first_name, last_name, email and how many times each person (email) visited the hotel. I therefore need to count how many times email occurs in the booking table. I have 2 tables to join: Customer: first_name last_name phone address town email postcode Booking: Date_ room occupants arrival_time nights paid email_ I wish to display first_name, last_name, email, COUNT(email) How can I do this? A: SELECT first_name, last_name, customer.email, visits FROM customer JOIN (SELECT email_, COUNT(*) AS visits FROM bookings GROUP BY email_) v ON customer.email = v.email_
{ "pile_set_name": "StackExchange" }
Q: ZSH setopt PROMPT_SUBST not working I'm trying to get customize my zsh prompt and want to evaluation a function with git commands every time my prompt is generated. I'm using setopt PROMPT_SUBST, but it doesn't seem to be working. This is my zshrc: setopt PROMPT_SUBST autoload -U colors && colors # Enable colors # Show Git branch/tag, or name-rev if on detached head parse_git_branch() { echo "PARSING GIT BRANCH" (git symbolic-ref -q HEAD || git name-rev --name-only --no-undefined --always HEAD) 2> /dev/null } prompt() { echo -n "%/" echo "$(git status)" } PS1="$(prompt)" And this is my output of setopt: interactive login monitor nonomatch promptsubst shinstdin zle A: You need to delay calling prompt until the prompt is displayed; do that by using single quotes: PS1='$(prompt)' A better idea, though, is to define a function that sets PS1, then add that function to the precmd_functions array so that it is executed prior to displaying each prompt. prompt () { PS1="%/$(git status)" } precmd_functions+=(prompt)
{ "pile_set_name": "StackExchange" }
Q: How find this $\int_{1}^{2}f^2(x^2)dx+5\int_{2}^{3}f(x^2)dx+7\int_{3}^{4}f(x)dx=\dfrac{1871}{30}$ Determine all function $f:R\to R$ for which $$\int_{1}^{2}(f(x^2))^2dx+5\int_{2}^{3}f(x^2)dx+7\int_{3}^{4}f(x)dx=\dfrac{1871}{30}$$ show that $$f(x)=x?$$ because we easy to find this follow value $$\int_{1}^{2}x^4dx+5\int_{2}^{3}x^2dx+7\int_{3}^{4}xdx=\dfrac{1871}{30}$$ also can see:http://www.wolframalpha.com/input/?i=%5Cint_%7B1%7D%5E%7B2%7Dx%5E4dx%2B5%5Cint_%7B2%7D%5E%7B3%7Dx%5E2dx%2B7%5Cint_%7B3%7D%5E%7B4%7Dxdx My try: since $$\int_{3}^{4}f(x)dx=2\int_{\sqrt{3}}^{2}uf(u^2)du$$ and I can't This problem is creat by Mihaly Bencze. I can solve follow this problem $$\int_{0}^{1}f(x)dx=\dfrac{1}{3}+\int_{0}^{1}f^2(x^2)dx$$ then $$f(x)=\sqrt{x}$$ solution:note $$\int_{0}^{1}x^2dx=\dfrac{1}{3},\int_{0}^{1}f(x)=\int_{0}^{1}2tf(t^2)dt$$ then $$0=\int_{0}^{1}[f^2(x^2)-2xf(x^2)+x^2]dx=\int_{0}^{1}[f(x^2)-x]^2dx$$ so $$f(x^2)=x\Longrightarrow f(x)=\sqrt{x}$$ But for my problem,I can't.Thank you A: It is quite possible to determine all polynomials that satisfy the given integral equation. Let $p_n(x)= a_0+a_1 x+\cdots a_n x^n = \sum_{k=0}^n a_k x^k$. Substituting in we get $$\int_1^2 \left(\sum_{k=0}^n a_k x^{2k} \right)^2 dx+5 \int_2^3 \sum_{k=0}^n a_k x^{2k}dx+7\int_3^4 \sum_{k=0}^n a_k x^k dx=\frac{1871}{30}.$$ Now it is a matter of choosing your $n$, expanding, integrating and explicitly writing down the equation. For $n=0$ we get (as mentioned in my comment) $$a_0^2+12a_0=1871/30.$$ For $n=1$ we first get $$\int_1^2 (a_0^2+2a_0a_1x^2+a_1^2x^4) dx + 5\int_2^3 (a_0 + a_1 x^2) dx+7 \int_3^4 (a_0+a_1x)dx = \frac{1871}{30},$$ or after integrating and collecting terms, $$a_0^2 + 2a_0a_1 (8-1)/3+a_1^2 (32-1)/5+5a_0+5a_1(27-8)/3+7a_0+7a_1(16-9)/2 = 1871/30$$ or $$a_0^2+a_0a_1 \frac{14}{3}+a_1^2 \frac{31}{5}+12 a_0 + \left(\frac{19\cdot 5}{3} + \frac{49}{2} \right) a_1 = \frac{1871}{30}.$$ Setting $a_0=0$ we verify that $$\frac{31}{5}+\frac{19\cdot 5}{3} + \frac{49}{2} = \frac{1871}{30}$$ so that $f(x)=x$ is a solution. But if you look closely you'll see there is another $f(x)=cx$ satisfying the equation. Let's go to Taylor series and assume that $f(x) = \sum_{k=0}^n a_k x^k$ is analytic with radius of convergence $R>9$. Then computing $$\int_1^2 \left(\sum_{k=0}^\infty a_k x^{2k} \right)^2 dx+5 \int_2^3 \sum_{k=0}^\infty a_k x^{2k}dx+7\int_3^4 \sum_{k=0}^\infty a_k x^k dx=\frac{1871}{30}$$ and using the Cauchy product, $$ \sum_{k=0}^\infty \left[ \int_1^2 \sum_{j=0}^k a_j a_{k-j} x^{2k} dx+5 \int_2^3 a_k x^{2k}dx+7\int_3^4 a_k x^k dx \right]=\frac{1871}{30}$$ and rearranging and integrating finally gives $$ \sum_{k=0}^\infty \left[ \sum_{j=0}^k a_j a_{k-j} \frac{2^{2k+1}-1}{2k+1} + a_k \left(5 \cdot \frac{3^{2k+1}-2^{2k+1}}{2k+1} + 7 \cdot \frac{4^{k+1}-3^{k+1}}{k+1}\right)\right]=\frac{1871}{30}.$$ We see from this that if a sequence $a_n$ satisfies the above constraint and if $a_k \geq 0$ for all $k$, then $a_k$ must diminish at least exponentially faster than $1/9^k$. So in this case satisfying the constraint implies that the function is analytic with radius of convergence greater than or equal to 9. Staring at the expression, you should eventually convince yourself that this is true regardless of the sign of $a_n$ (use the condition that difference of partial sums go to zero). Because of this required decay, you might even be able to show, by picking the first $n$ coefficients, that for any analytic function $g$ there is another function $f$ as close as you like to $g$ (in the supremum norm) such that $f$ satisfies the constraint. This might be a hogwash, though, but, achille hui's comment does also give a suggestion of something of this sort. Note that his answer does not assume continuity or smoothness of $f$. However, I'll leave proving or disproving that to another day.
{ "pile_set_name": "StackExchange" }
Q: Can ESB/BPM allow to totally get rid of coding apart from wrapping webservices? In a big company I work for, a very (costfull) ESB has been bought, the purpose is to be able to align with business goal quickly by resusing legacy infrastructure wrapping them with webservices, that is to say no more coding needed. Are ESB/BPM now really mature enough for that because it's now more than 10 years old or is it just an other vendor promise ? A: Almost certainly just a vendor promise. If this becomes a reality for your company, they'll be the first to be so lucky! This is the same sales job being done again and again for over a dozen years now (remember 4GLs?). Most companies find the reality is that 1) it takes far more effort to install, integrate the ESB/BPM tool than they were led to believe, 2) only the most trivial changes can be made with the tool - it still takes coders to perform any meaningful process change / addition, 3) whenever the ESB/BPM tool vendor upgrades their tool, it's a huge effort to upgrade and be eligible for support (look into the history of any of these tools and what pains shops go through to upgrade, particularly Webmethods and BEA/Oracle's products over the years), 4) support services are expensive and rarely provide help (I know of companies that have paid for premium support who have filed dozens of tickets only to have one or two of them resolved by the idiots on the phone before someone in-house finally found the solution / work-around themselves.
{ "pile_set_name": "StackExchange" }
Q: Doctrine Entity Listener in Symfony 2.6 According to How to use Doctrine Entity Listener with Symfony 2.4? it should be pretty simple to setup the entity listener feature in Symfony. Unfortunately, my listener nevers gets called and I don't know why. I've checked the compiler pass of the doctrine bundle and also the DefaultEntityListenerResolver class. My listener is gets passed to the register method and should be available then. The resolve method on the other hand seems to be never called. Here is my service definition: insite.entity.listener.page_node: class: NutCase\InSiteBundle\Entity\PageNodeListener tags: - { name: doctrine.orm.entity_listener } Here is my listener: namespace NutCase\InSiteBundle\Entity; use Doctrine\ORM\Event\LifecycleEventArgs; class PageNodeListener { public function prePersist( PageNode $node, LifecycleEventArgs $event ) { die("okay"); } } And here my yaml for the entity: NutCase\InSiteBundle\Entity\PageNode: type: entity table: page_node repositoryClass: NutCase\InSiteBundle\Entity\PageNodeRepository fields: title: type: string length: 255 nullable: false segment: type: string length: 255 nullable: false url: type: string length: 255 nullable: false root: type: boolean nullable: false hidden: type: boolean nullable: false I've added an "entityListeners" entry to the YAML, since I thought this one is missing: entityListeners: - PageNodeListener // Also tried the full namespace Which only leads to the following error whenever I try to load a PageNode entity: [Symfony\Component\Debug\Exception\ContextErrorException] Warning: Invalid argument supplied for foreach() Any suggestions? A: I just found the code which parses the YAML and also the entityListeners key: YamlDriver. Since I failed to find any documentation for the YAML configuration of this key, I had to check the code, which leads me to the answer that the correct YAML markup for entity listeners should be: Your\Entity\Namespace: entityListeners: Path\To\Your\Listener: ~ In case that you want to map specific methods to specific events, you should use: Your\Entity\Namespace: entityListeners: Path\To\Your\Listener: prePersist: [methodOnYourListener] Guess the question would be needles if there were any documentation for that. I also like to point out that you don't have to register your listeners as a service. The class name in the YAML mapping of the entity is actually enough to get it running, since the DefaultEntityListenerResolver will create an instance if there is none yet. You only need to register the listener as a service if you have other dependencies, like the security context for example.
{ "pile_set_name": "StackExchange" }
Q: Django reverse and url default instead of NoReverseMatch Is it possible to set up a default URL which will be used whenever a reverse match cannot be found? The idea is that if in production there is a typo, I would like to display something akin to a 404 or a descriptive error page, instead of getting a NoReverseMatch exception. A: The templatetag url raise a Exception. You can see in the code: https://code.djangoproject.com/browser/django/trunk/django/templatetags/future.py#L117 But, you can create other templatetag (copy and paste 90%), that does not raise anything and "display something akin to a 404 or a descriptive error page, instead of getting a NoReverseMatch exception."
{ "pile_set_name": "StackExchange" }
Q: Choosing an application server for web application development My manager has asked me to suggest an application server for web application development work. What are the factors that needs to be considered before we select any application server for web application development in Java J2EE development? If I select one now and IN future and I want to change to some other application server, is that minimum effort to change? A: Apache Tomcat and Jetty are the two most popular web containers. Tomcat is the reference implementation of a Java servlet container, Jetty is a little bit faster and more lightweight. I personally favor Jetty, but you can't go wrong with either of them. A little comparison of the two can be found here. Generally the migration of an application between web containers is fairly easy - only some configurations needs to be changed, but nothing in the source code(which is not always the case with full blown enterprise application servers).
{ "pile_set_name": "StackExchange" }
Q: In a class room setting, why do people look at you when you are asking a question? Picture this scenario: You are a student enrolled in a large class You arrived slightly late to the class, so you are sitting at the back of the class You raise your hands to ask the teacher a question. As you speak, you observe that the entire class turn their body sideways to look at you, even the students who are sitting in the front row. You feel self-conscious Three thoughts are now going through your mind: What are "ears" for, again? It must be really uncomfortable and awkward to twist your body like that. What is the incurred "loss" if the other students did not look at you and simply listened? Can some expert chime in the reasoning as to why students have to look at you when they are listening? Could this be some sort of form of peer pressure? Could the act of looking help to localize the sound (or synthesize the information) in some way? Do we look so we can prejudge? For example, if we see that the asker/speaker is another professor, we pay more attention to the question as it might be more sophisticated than asked by a student. A: Well, your ears are shaped in a way that is optimized for sound sources in front of you, so it could be that. But my non-expert bet is that probably they're using gaze to signal that they're paying attention. The signal is not just to you "I'm following what you're saying" but to everyone else as well, "hey, check out what's going on over there" creating joint attention that coordinates the group in thinking about your question. This might be uncomfortable for you (although it's probably a compliment that you're worth paying attention to), but the general mechanism of having super-obvious cues to attention and a predisposition to follow them to create joint attention is a very effective way of coordinating social behavior. This is so fundamentally human that most people take it for granted, but that doesn't stop academics from studying it. You could maybe try something like Pfeiffer, U. J., Vogeley, K., & Schilbach, L. (2013). From gaze cueing to dual eye-tracking: novel approaches to investigate the neural correlates of gaze in social interaction. Neuroscience & Biobehavioral Reviews, 37(10), 2516-2528. or Brooks, A. M. M. R. (2017). Eyes wide shut: The importance of eyes in infant gaze-following and understanding other minds. In Gaze-Following (pp. 229-254). Psychology Press. ...if you really want a deep-dive into this.
{ "pile_set_name": "StackExchange" }
Q: Insert rows within a DataFrame, based on certain conditions I have a dataframe, 'df' and I want to insert rows based on conditions within df itself. Each 'ID' value must have a corresponding entry for both drinktypes (Beer & Wine). I'd like to say if any ID entry does not have a Beer Type for instance, add row With DrinkType equal to Beer and Drink equal to 'Not Stated'. Similarly, if Beer has been stated for an ID value but not Wine, then add row with Wine under Drink Type and Drink equal to 'Not Stated'. I'd like df to look like df1. df: ID DrinkType Drink 130 Beer Fosters 130 Wine Rose 130 Beer Budweiser 102 Beer Fosters 120 Wine Pinot Grigot 120 Beer Budweiser 99 Wine Coke 75 Beer Carling 75 Beer Fosters df1: ID DrinkType Drink 130 Beer Fosters 130 Wine Rose 130 Beer Budweiser 102 Beer Fosters 102 Wine Not Stated 120 Wine Pinot Grigot 120 Beer Budweiser 99 Wine Coke 99 Beer Not Stated 75 Beer Carling 75 Beer Fosters 75 Wine Not Stated A: Function to insert row in the dataframe at particular index def Insert_row_(row_number, df, row_value): #Slice the upper half of the dataframe df1 = df[0:row_number] # Store the result of lower half of the dataframe df2 = df[row_number:] # Inser the row in the upper half dataframe df1.loc[row_number]=row_value # Concat the two dataframes df_result = pd.concat([df1, df2]) # Reassign the index labels df_result.index = [*range(df_result.shape[0])] # Return the updated dataframe return df_result Let's create a row which we want to insert index = 2 item_insert = ['Beer','NotStated'] if row_number > df.index.max()+1: df[index]=row_value else: # Let's call the function and insert the row # at the second position df = Insert_row_(2, df, row_value) print(df) insert any row at last find max index of current dataframe df[s]=rowvalue or we can use pd.concat(df,df1)
{ "pile_set_name": "StackExchange" }
Q: APNS: Failed to validate certificate chain for courier.sandbox.push.apple.com - didRegisterForRemoteNotificationWithDeviceToken is not being called I've implemented apns in my applicaton and it was working till yesterday without any problem. Today suddenly it stopped working and the following method is not being called: -(void) application:(UIApplication) applicaton didRegisterForRemoteNotificationWithDeviceToken:(nonnull NSData *) deviceToken; I didn't find any valid reason. My iOS version is 9.3.2; In device log I see the following error message: Failed to validate certificate chain for courier.sandbox.push.apple.com I factory reset the device but it didn't work. Interestingly, the apns works on my other device with same iOS version. More interestingly, on the same device my another Test Push Application (same code copy and pasted) works fine. Does anybody have any idea to solve this issue? Thanks in advance. A: Similar issue happened to me today as well on 3 test phones, all running iOS 9.3.2. One is an iPhone5 and the other is an iPhone 6. The following insights may help avoid the problem, until fixed: I saw that the problem only occur when signing the app with a development certificate. On production environment everything seemed to work as expected (both for regular APNS and for VoIP APNS). The problem is reproducible only on one of our apps. A different app, even if signed as development, worked as expected (i.e. didRegisterForRemoteNotificationWithDeviceToken was called by the system). The problem was not reproducible when testing the problematic app on an iOS 8.4.1 phone, both for regular APNS and for VoIP APNS. Update for July 20, 2016: It seems that this was a temporary issue in APNS Sandbox environment, everything went back to normal today.
{ "pile_set_name": "StackExchange" }
Q: Upgrading from 5.2.2 to 6.4.2 (yum install VS yum update) Need to perform upgrade on 3-nodes ES clusters and writing test script before putting it to playbook. Anyone updated ES with yum update instead of install (OS AWS RHEL 7.2) ??? Here's the install script, I will be grateful for your comments: #Installing from the RPM repository #Create a file called elasticsearch.repo in the /etc/yum.repos.d/ directory for RedHat based distributions, #DO UPGRADE #In the terms of ordering, update first the master nodes, then data nodes, then load-balancing/client nodes. #Disable Shard reallocation curl -XPUT localhost:9200/_cluster/settings -d '{ "transient" : { "cluster.routing.allocation.enable" : "none" } }' #Shutdown the instance: curl -XPOST 'http://localhost:9200/_cluster/nodes/_local/_shutdown' sudo systemctl stop elasticsearch sudo yum update elasticsearch sudo systemctl start elasticsearch #Enable shard re-allocation: curl -XPUT localhost:9200/_cluster/settings -d '{ "transient" : { "cluster.routing.allocation.enable" : "all" } }' #Watch cluster go from yellow state to green with: curl -X GET http://localhost:9200/_cat/health?v // monitors the overal cluster state curl -X GET http://localhost:9200/_cat/nodes?v // verify that the new node joined the cluster curl -X GET http://localhost:9200/_cat/shards?v // see shards being started, initialized and relocated #Repeat for the next node. Kind Regards, P. A: The answer is yes. YUM UPDATE will upgrade the ES the the LATEST version. Make sure you have: 1) updated the /etc/yum.repos.d/elasticsearch.repo to the latest 6.x version 2) all indexes have been created with version lateter than 5.x (if not they have to be reindexed) curl -X GET http://host_ip:9200/index_name/_settings?pretty\&human Kind Regards, P.
{ "pile_set_name": "StackExchange" }
Q: Dialog doesnt display properly without aero i have a application i have been making a for a while now using C++/Win32 and when i create my first dialog it shows up weird when i dont have aero enabled or i am not using windows 7/8. here is a screenshot of what it looks like: This is my last resort, as i have no idea why this is doing it. It only happens to the first dialog i make, after the user logs in the rest of the dialogs are fine. It works just fine with aero. here is my dialog resource script IDI_MAINDLG DIALOGEX 0,0,195,54 CAPTION "Absolute Hacks Loader" FONT 8,"MS Shell Dlg",400,0,1 STYLE WS_VISIBLE|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|DS_CENTER|DS_MODALFRAME|DS_SHELLFONT EXSTYLE WS_EX_TRANSPARENT|WS_EX_TOPMOST|WS_EX_DLGMODALFRAME BEGIN CONTROL "Login",IDI_LOGIN_BTN,"Button",WS_CHILDWINDOW|WS_VISIBLE|WS_TABSTOP|BS_DEFPUSHBUTTON,156,12,33,15 CONTROL "",IDI_USER_TEXT,"Edit",WS_CHILDWINDOW|WS_VISIBLE|WS_TABSTOP|ES_CENTER,45,6,104,13,WS_EX_CLIENTEDGE CONTROL "Username:",IDC_STATIC,"Static",WS_CHILDWINDOW|WS_VISIBLE|WS_GROUP,3,6,39,12 CONTROL "Password:",IDC_STATIC,"Static",WS_CHILDWINDOW|WS_VISIBLE|WS_GROUP,3,24,33,9 CONTROL "",IDI_PASS_TEXT,"Edit",WS_CHILDWINDOW|WS_VISIBLE|WS_TABSTOP|ES_AUTOHSCROLL|ES_PASSWORD|ES_CENTER,45,24,104,12,WS_EX_CLIENTEDGE CONTROL "Remember me",IDI_REMEMBER,"Button",WS_VISIBLE|WS_TABSTOP|BS_AUTOCHECKBOX,135,42,57,9 CONTROL "Coded By DaRk_NeSs",IDC_STATIC,"Static",WS_CHILDWINDOW|WS_VISIBLE,3,42,75,9 END A: I wanted to leave a comment asking you why you have WS_EX_TRANSPARENT in the EXSTYLE, but I don't have enough reputation points for that, so I'll just have to make this into an answer. Try leaving out WS_EX_TRANSPARENT. I wrote a little program with a dialog box and the dialog box looked very strange with WS_EX_TRANSPARENT and normal without it.
{ "pile_set_name": "StackExchange" }
Q: Answer awarded bounty but not accepted as an answer. Bounty not added to reputation I've answered a question with a bounty. Ultimately the question author found out the solution by himself, posted it and accepted that answer. But they decided to award my answer a bounty for my effort and help. Unfortunately, the bounty has not been added to my reputation. Here is the question in case: django-filter messing around with empty field What am I missing? A: It actually has been added to your reputation: FWIW, bounties are completely independent from accepting an answer.
{ "pile_set_name": "StackExchange" }
Q: Radiation by a transparent body We know that the rate of radiation is proportional to the surface area offthe emitting body. However, this is true for an opaque body. When considering a transparent body, will the radiation still be proportional to the surface area? Or, will it be proportional to the volume of the body which seems more likely to me? (I am assuming that the material is ideally transparent to all wavelengths) Also, taking it a bit further say if a (transparent) sphere having sphereicaly symmetric temperature distribution maintained constantly by some hypothetical arrangement how should the amount of radiation emitted be calculated? A: A perfectly transparent sphere will not emit any electromagnetic radiation (this could happen if we consider a blob of cold dark matter, for example). However, there are cases like optically thin plasmas where radiation is released and each photon unlikely to be captured by another particle before it escapes. In particular, there is thermal Bremsstrahlung where free electrons and ions in a plasma will radiate energy like $P_{br} \propto n_e n_i \sqrt{T}$ where $n_e,n_i$ is the number density of electrons and ions. The total emissions will be proportional to the volume rather than the surface area as long as the density is low enough that there is not too much self-absorption; as density increases the spectrum becomes more blackbody-like. If the sphere is maintained at constant temperature the best way of estimating the radiation is to measure how much energy is being put into the sphere per unit of time to maintain the disequilibrium. In more realistic cases like astrophysicists looking at intergalactic plasmas they use the shape of the spectrum to estimate parameters like temperature and density and then estimate the total power from that.
{ "pile_set_name": "StackExchange" }
Q: Add more data to state whilst keeping original (React) I have an app that get data from an API as a page. I've added functionality to get the next page of the data and set it to state. I want to be able to get the next pages data but rather than replace the state I want to add the next page value. Here is the code const TopRatedPage = () => { const [apiData, setApiData] = useState([]); const [isLoading, setLoading] = useState(false); const [pageNumber, setPageNumber] = useState(1); const { results = [] } = apiData; useEffect(() => { setLoading(true); fetchTopRatedMovies(pageNumber).then((data) => setApiData(data)); setLoading(false); }, [apiData, pageNumber]); return ( <div className='top-rated-page-wrapper'> <h1>TopRatedPage</h1> {isLoading ? <h1>Loading...</h1> : <MovieList results={results} />} <button onClick={() => { setPageNumber(pageNumber + 1); }}> MORE </button> </div> ); I've tried setApiData(...apiData,data) but it gives error, apiData is not iterable. Here is the data returned Object { page: 1, total_results: 5175, total_pages: 259, results: (20) […] } To clarify I want to be able to allow user to click button that adds more API data to state and display more. A: Updated to reflect the shape of the object returned by your api call. One way to handle this, as demonstrated below, is to replace the page metadata (page, total_results, total_pages) in your component's state with the info from latest api call, but append the results each time. If you don't care about the paging information you could just drop it on the floor and store only the results, but keeping it around lets you display paging info and disable the 'load more' button when you get to the end. Displaying the current page and total pages might not make sense given that you're just appending to the list (and thus not really "paging" in the UI sense), but I've included it here just to provide a sense of how you might use that info if you chose to do so. The key thing in the snippet below as it relates to your original question is the state merging: const more = () => { fetchTopRatedMovies(page + 1) .then(newData => { setData({ // copy everything (page, total_results, total_pages, etc.) // from the fetched data into the updated state ...newData, // append the new results to the old results results: [...data.results, ...newData.results] }); }); } I'm using spread syntax to copy all of the fields from newData into the new state, and then handling the results field separately because we want to replace it with the concatenated results. (If you left the results: [...data.results, ...newData.results] line out, your new state would have the results field from newData. By specifying the results field after ...newData you're replacing it with the concatenated array. Hope this helps. /* Your api returns an object with the following shape. I don't know what the individual results entries look like, but for our purposes it doesn't really matter and should be straightforward for you to tweak the following code as needed. { page: 1, total_results: 5175, total_pages: 259, results: [ { title: 'Scott Pilgrim vs. The World', year: 2010, director: 'Edgar Wright' }, { title: 'Spiderman: Into the Spider-Verse', year: 2018, director: ['Bob Persichetti', 'Peter Ramsey', 'Rodney Rothman'] }, { title: 'JOKER', year: 2019, director: 'Todd Phillips' }, ]; } */ const {useState} = React; // simulated api request; waits half a second and resolves with mock data const fetchTopRatedMovies = (page = 0) => new Promise((resolve) => { // 5 is arbitrary const numPerPage = 5; // generate an array of mock results with titles and years const results = Array.from( {length: numPerPage}, (_, i) => ({ title: `Movie ${(page - 1) * numPerPage + i}`, year: Math.floor(Math.random() * 20) + 2000 }) ); // 16 is arbitrary; just to show how you can disable // the 'more' button when you get to the last page const total_results = 16; // the return payload const data = { page, total_results, total_pages: Math.floor(total_results / numPerPage), results } setTimeout(() => resolve(data), 500); }); const Demo = () => { const [data, setData] = useState({ page: 0, results: [] }); const more = () => { fetchTopRatedMovies(page + 1) .then(newData => { setData({ // copy everything (page, total_results, total_pages, etc.) // from the fetched data into the updated state ...newData, // append the new results to the old results results: [...data.results, ...newData.results] }); }); } // pull individual fields from state const {page, results, total_results, total_pages} = data; // are there more pages? (used to disable the button when we get to the end) const hasMore = page === 0 || (page < total_pages); return ( <div className='wrapper'> <div> {total_pages && ( <div> <div>Page: {page} of {total_pages}</div> <div>Total: {total_results}</div> </div> )} <button disabled={!hasMore} onClick={more}>More</button> <ul> {results.map(m => ( <li key={m.title}>{m.title} - ({m.year})</li> ))} </ul> </div> <div> <h3>component state:</h3> <pre>{JSON.stringify(data, null, 2)}</pre> </div> </div> ); }; ReactDOM.render( <Demo />, document.getElementById('demo') ); /* purely cosmetic. none of this is necessary */ body { font-family: sans-serif; line-height: 1.6; } .wrapper { display: flex; background: #dedede; padding: 8px; } .wrapper > * { flex: 1 1 50%; background: white; margin: 8px; padding: 16px; } h3 { margin: 0; } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.0/umd/react-dom.production.min.js"></script> <div id="demo" />
{ "pile_set_name": "StackExchange" }
Q: Add menu itens in Commerce Kickstart administrative toolbar I have worked with default Commerce Kickstart 2 toolbar menu, and I really liked. But now I installed a new module, Commerce Feeds, and I can not access it because there aren't menu entries in toolbar. Is there a way to add menu entries like the one I need in Commerce Kickstart 2 toolbar menu, or I have to back to Drupal 7 administrative toolbar? A: You're able to modify the Commerce Kickstart 2 admin menu from this path: /admin/structure/menu/manage/management It's a normal menu created during installation called "Management".
{ "pile_set_name": "StackExchange" }
Q: .htaccess file mod_rewrite redirecting to parent directory instead of sub-directory when file names are same in both directories I am accessing the root directory via domain-A.com and a sub-directory via domain-B.com All redirects are working properly for domain-B.com except those that are having same names for instance if root directory contains a file called abc.html and subdirectory also contains the file abc.html in that case accessing domain-B.com/abc.html shows the contents of domain-A.com/abc.html but the url remains the same i.e. domain-B.com/abc.html I would like to know how can this be resolved. I am using Ubuntu and these are the settings that I have made for various file I have already enabled mod_rewrite using sudo a2enmod rewrite .htaccess - path /var/www/html # Do not change this line. RewriteEngine on # Change domain.com to be your primary main domain. http://domain-b.com/ RewriteCond %{HTTP_HOST} ^(www.)?domain-b.com$ # Change 'subfolder' to be the folder you want to redirect request to. RewriteCond %{REQUEST_URI} !^/domain-b/ # Don't change this line. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Change 'subfolder' to be the folder you want to use for your primary domain. RewriteRule ^(.*)$ /domain-b/$1 [L] # Change domain.com to be your primary domain again. # Change 'subfolder' to be the folder you will use for your primary domain # followed by / then the main file for your site, index.php, index.html, etc. RewriteCond %{HTTP_HOST} ^(www.)?domain-b.com$ RewriteRule ^(/)?$ domain-b/index.html [L] httpd.conf - Path /etc/apache2/conf-available <Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> 000-default.conf - Path /etc/apache2/sites-available <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> </VirtualHost> 000-default.conf - Path /etc/apache2/sites-enabled <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> </VirtualHost> A: Issue is with these 2 conditions: # Don't change this line. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d Which means if a file or directory exists in site root dir then don't rewrite to sub-directory. Just change your rule to this: RewriteEngine on # Change domain.com to be your primary domain again. # Change 'subfolder' to be the folder you will use for your primary domain # followed by / then the main file for your site, index.php, index.html, etc. RewriteCond %{HTTP_HOST} ^(www\.)?domain-b\.com$ [NC] RewriteRule ^/?$ domain-b/index.html [L] # Change domain.com to be your primary main domain. http://domain-b.com/ RewriteCond %{HTTP_HOST} ^(www\.)?domain-b\.com$ [NC] # Change 'subfolder' to be the folder you want to redirect request to. RewriteCond %{REQUEST_URI} !^/domain-b/ [NC] # Change 'subfolder' to be the folder you want to use for your primary domain. RewriteRule ^(.*)$ /domain-b/$1 [L]
{ "pile_set_name": "StackExchange" }
Q: 000webhost service website database error On my 000webhost website I had created this SQL file, named test.sql Here is it's coding: CREATE TABLE `members` ( `id` int(4) NOT NULL auto_increment, `username` varchar(65) NOT NULL default '', `password` varchar(65) NOT NULL default '', PRIMARY KEY (`id`) ) TYPE=MyISAM AUTO_INCREMENT=2 ; -- -- Dumping data for table `members` -- INSERT INTO `members` VALUES (1, 'john', '1234'); And after that I created another php file named main_login.php Here is coding: <table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form name="form1" method="post" action="checklogin.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td colspan="3"><strong>Member Login </strong></td> </tr> <tr> <td width="78">Username</td> <td width="6">:</td> <td width="294"><input name="myusername" type="text" id="myusername"></td> </tr> <tr> <td>Password</td> <td>:</td> <td><input name="mypassword" type="text" id="mypassword"></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td><input type="submit" name="Submit" value="Login"></td> </tr> </table> </td> </form> </tr> </table> After that I prepared another php file named checklogin.php Here is coding: $host="I INSERTED MY LOCAL HOST HERE"; // Host name $username="I INSERTED MY USERNAME HERE"; // Mysql username $password="I TYPED MY PASSWORD HERE"; // Mysql password $db_name="[B]I AM CONFUSED THAT WHICH DATABASE SHOULD I NAME HERE[/B] :eek: "; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" session_register("myusername"); session_register("mypassword"); header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> In checklogin.php, 4th line, I am confused that which database name should I provide. I tried to write test.sql as I had created a table with SQL file, but while logging in it's showing error and login form is not able to fetch the SQL table data.I had already created a mySQL file in service provided by 000webhost.com and get MySQL username, MySQL database and host site (let username be SQL_user and site), but currently don't know how to use MySQL. So which file should I name in $db_name above? And also want to know that how can I add data in MySQL in 000webhost.com so that login form can fetch the login info? Thank You in advance... A: Above I had asked 2 Questions: Que 1. So which file should I name in $db_name above? Que 2. How can I add data in MySQL in 000webhost.com so that login form can fetch the login info? Here are answers: Ans 1. Here in the checklogin.php I had to write this: $host="INSERTED LOCAL HOST HERE"; // Host name $username="INSERTED USERNAME HERE"; // Mysql username $password="TYPED PASSWORD HERE"; // Mysql password $db_name="HERE WE HAVE TO INSERT MYSQL DATABASE NAME"; // Database name $tbl_name="members"; // Table name Now in above at $db_name we will be your MySQL database name, and I will have to create another table at that database. Ans 2. After opening my site Control Panel at 000webhost I will have to go on phpMyAdmin and create a database first and after putting the username, password, local host etc., I will click on "Enter phpMyAdmin" at the right side of the table it will take us to another window and there we have to create the database and this database will be the place from where the login form will fetch data.
{ "pile_set_name": "StackExchange" }
Q: How to print the entire python idle commands history to a text file How to print the entire python idle commands history to a text file. For example the list of commands I already typed A: One prints the contents of a Shell window the same as an editor or output window. Select File and then Print Window and then OK. Or use the shortcut key, which on Windows, at least, is Control-P. I verified that this works on Windows with 2.7.13 and 3.6.1. One can also save Shell content with File, Save As and then edit the result. Then print if one wants a paper copy. https://bugs.python.org/issue11838 is about making it easier to get running code from a shell log. One problem with saving just the user input is that it loses the bug information in tracebacks.
{ "pile_set_name": "StackExchange" }
Q: Как с помощью js сделать выпадающий список? Есть код php на opencart: opencart.com/catalog/view/theme/default/template/extension/module/category.tpl <div class="leftSideBar"> <?php foreach ($categories as $category) { ?> <?php if ($category['category_id'] == $category_id) { ?> <?php if ($category['children']) { ?> <?php foreach ($category['children'] as $child) { ?> <div class="container leftSideBarPadding"> <a href="<?php echo $child['href']; ?>" > <span class="boldLetter"><?php echo $child['name']; ?></span> <i class="fa fa-angle-down" aria-hidden="true"></i> </a> </div> <div class="leftSideBarLine"></div> <?php if(isset($child['children_lv3']) && count($child['children_lv3'])>0){ ?> <?php foreach ($child['children_lv3'] as $child_lv3) { ?> <div class="container leftSideBarPadding"> <a href="<?php echo $child_lv3['href']; ?>" > <span><?php echo $child_lv3['name']; ?></span> </a> </div> <div class="leftSideBarLine"></div> <?php } ?> <?php } ?> <?php } ?> <?php } ?> <?php } else { ?> <a href="<?php echo $category['href']; ?>" ><?php echo $category['name']; ?></a> <?php } ?> <?php } ?> </div> данный код выводит подкатегории категории и подподкатегории подкатегорий! Как с помощью js или с помощью css сделать чтоб при нажатии на подкатегорию - выпадали подподкатегории? у меня оно монолитом... Оно должно выпускать список 3 уровня при нажатии, как показано на картинке 1 (только нажал на одну подкатегорию открылся список, нажал на вторую - открылся второй список, нажал еще раз на подкатегорию - закрылся и т.д...) A: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div class="leftSideBar col-md-3 "> <div id="wrap"> <div id="center"> <div class="box"> <h3 class="boldLetter leftSideBarCategory">Список №1 <span class="expand">v</span> </h3> <ul class="leftSideBarUl"> <div class="leftSideBarLine"></div> <li class="leftSideBarLi"><a>Пункт №1</a></li> <div class="leftSideBarLine"></div> <li class="leftSideBarLi"><a>Пункт №1</a></li> <div class="leftSideBarLine"></div> <li class="leftSideBarLi"><a>Пункт №1</a></li> </ul> <div class="leftSideBarLine"></div> <h3 class="boldLetter leftSideBarCategory">Список №1 <span class="expand">v</span> </h3> <ul class="leftSideBarUl"> <div class="leftSideBarLine"></div> <li class="leftSideBarLi"><a>Пункт №1</a></li> <div class="leftSideBarLine"></div> <li class="leftSideBarLi"><a>Пункт №1</a></li> <div class="leftSideBarLine"></div> <li class="leftSideBarLi"><a>Пункт №1</a></li> </ul> </div> </div> $(document).ready(function(){ $("ul").hide(); $(".box h3").click(function(){ $(this).next().slideToggle(); var text = $("span",this).text(); $("span",this).text(text != "^" ? "^" : "v") }); }); </div> </body> CSS файл: .leftSideBar { border-radius: 20px 20px 20px 20px; background-color: #FFFFFF; width: 200px; border: 2px solid #CCCCCC; } .leftSideBarLine { border-bottom: 2px solid #CCCCCC; } .leftSideBarUl { padding: 0px; margin:0; overflow: hidden; } .leftSideBarLi { font-size: 13px; list-style-type: none; list-style-position: inside; padding: 10px; } .leftSideBarCategory{ padding: 10px; color: #6C6C6C; font-size: 13px; font-weight: normal; margin:0; cursor: pointer; } .expand { float: right; cursor: pointer; } .boldLetter { font-weight: 600; }
{ "pile_set_name": "StackExchange" }
Q: Jenkins without icons My instance is working fine but it's been a while since the icons were working. You can see it here. I tried restarting the instance various times without any luck. A: You had green-balls plugin "1.12-h-1" plugin installed. This plugin is designed for eclipse hudson 3.0 and incompatible with jenkins. We (cloudbees) have noticed this issue and removed it from our update center in the meantime.
{ "pile_set_name": "StackExchange" }
Q: Timely commit to DB using Golang I successfully "batched" many statements in lots of 500-1000 rows to be Inserted at once. However this was using simple for loop and manually setting it to 500-1000 loops. Something like: for i:=0;i<500;i++ { // Create a string of 500 values to be inserted at once } // Insert the 500 values Is there a way I could timely commit() like: "commit each seconds" ? Conceptually, I'd like to have something like; // Create connection to DB // Begin a transaction // Prepare a statement go timelyCommits(tx) // spawn a commit ticker for { // Constantly create string of values to be inserted like: // Values (1, "one"),(2,"two"),(3,"three")...(1000,"thousand")... // Insert without commit } func timelyCommits(tx){ for { time.Sleep(1 * time.Second) tx.Commit() } } A: Optimization is not a trivial task and may also involving database tuning, etc. Without detail knowledge about the system that you're trying to implement, it is difficult to give a proper advice. In addition to what already suggested in the answer, you may need to implement a kind of buffering, e.g. with channel which has fixed capacity. Then when buffer is FULL or timer EXPIRED, build the query then perform BULK INSERT in transaction. Try it at The Go Playground. package main import ( "fmt" "time" ) type DataBuffer struct { capacity int duration time.Duration incomingData chan interface{} full chan bool mustExit chan bool done chan bool query string args []interface{} } func NewDataBuffer(capacity int, dur time.Duration) *DataBuffer { buf := &DataBuffer { incomingData: make(chan interface{}, capacity), full: make(chan bool), args: make([]interface{}, capacity), duration: dur, mustExit: make(chan bool, 1), done: make(chan bool, 1), } return buf } func (b *DataBuffer) Append(d interface{}) { if !b.put(d) { //Notify that buffer is full //<- will wait until space available b.full <- true b.incomingData <- d } } func (b *DataBuffer) put(d interface{}) bool { //Try to append the data //If channel is full, do nothing, then return false select { case b.incomingData <- d: return true default: //channel is full return false } } func (b *DataBuffer) execTransaction() error { /* Begin transaction Insert Data Group Commit/rollback */ fmt.Print(time.Now()) fmt.Println(b.query) fmt.Println(b.args) return nil } func (b *DataBuffer) clear() { //clear args nOldArg := len(b.args) for k := 0; k < nOldArg; k++ { b.args[k] = nil } b.args = b.args[:0] b.query = "" } func (b *DataBuffer) buildQuery() bool { ndata := len(b.incomingData) if ndata == 0 { return false } k := 0 b.clear() //Build the query, adjust as needed b.query = "QUERY:" for data := range b.incomingData { b.query += fmt.Sprintf(" q%d", k) //build the query b.args = append(b.args, data) k++ if k >= ndata { break } } return true } func (b *DataBuffer) doInsert() { if b.buildQuery() { b.execTransaction() } } func (b *DataBuffer) runAsync() { defer func() { b.doInsert() fmt.Println("Last insert") close(b.done) }() timer := time.NewTimer(b.duration) for { select { case <- timer.C: b.doInsert() fmt.Println("Timer Expired") timer.Reset(b.duration) case <- b.full: if !timer.Stop() { <-timer.C } b.doInsert() fmt.Println("Full") timer.Reset(b.duration) case <- b.mustExit: if !timer.Stop() { <-timer.C } return } } } func (b *DataBuffer) Run() { go b.runAsync() } func (b *DataBuffer) Stop() { b.mustExit <- true } func (b *DataBuffer) WaitDone() { <- b.done } func main() { buf := NewDataBuffer(5, 1*time.Second) buf.Run() //simulate incoming data for k := 0; k < 30; k++ { buf.Append(k) time.Sleep(time.Duration(10*k)*time.Millisecond) } buf.Stop() buf.WaitDone() } Note: You need to implement proper error handling. The type of incomingData may be adjusted to your need
{ "pile_set_name": "StackExchange" }
Q: Checking that an additional field is not null in Leads is causing System.NullPointerException error I'm new to Apex as a Salesforce admin and I'm trying to figure out a simple Apex trigger exercise. The goal of this trigger is to ensure that when a Lead's first name or last name = 'test', the lead's status should be set to 'Disqualified'. This is my code: trigger LeadDisqualification on Lead (before insert, before update) { // If first name or last name equals 'test', Lead Status should equal Disqualified. for (Lead myLeads : Trigger.new) { if (((myLeads.FirstName != null) || (myLeads.LastName != null)) && (myLeads.FirstName.equalsIgnoreCase('test') || myLeads.LastName.equalsIgnoreCase('test'))) { myLeads.Status = 'Disqualified'; } } } As it is, when I tried to create a lead with the first name blank / null, I'm getting an error message: LeadDisqualification: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.LeadDisqualification: line 6, column 1 However, I was able to create the lead with the first name null with no issues when I updated line 5 by removing: (myLeads.LastName != null) I basically changed line 5 from: if (((myLeads.FirstName != null) || (myLeads.LastName != null)) && (myLeads.FirstName.equalsIgnoreCase('test') || myLeads.LastName.equalsIgnoreCase('test'))) { to if (((myLeads.FirstName != null)) && (myLeads.FirstName.equalsIgnoreCase('test') || myLeads.LastName.equalsIgnoreCase('test'))) { Does anyone know why removing myLeads.LastName != null would cause the null pointer exception error message to go away? Just trying to understand this! A: Note that there is a null safe way to compare values in a case insensitive manner: for (Lead record : records) { if (record.FirstName == 'test' || record.LastName == 'TEST') { // the == operator performs case-insensitive comparison // it is also null safe // the left or right operand can be null } } Regardless, from a logical perspective it is useful to know how to properly perform two separate null checks here. You should use an and join for each field. Let's consider separate loops. You would do: for (Lead record : records) { if (record.FirstName != null && record.FirstName.equalsIgnoreCase('some value')) { // do stuff } } for (Lead record : records) { if (record.LastName != null && record.LastName.equalsIgnoreCase('some value')) { // do stuff } } Now if you were to combine them, you would do: if ((record.FirstName != null && record.FirstName.equalsIgnoreCase('...')) || record.LastName != null && record.LastName.equalsIgnoreCase('...')) { // do stuff }
{ "pile_set_name": "StackExchange" }
Q: Python for loop efficiency I have this block of code, which works, but takes about 8 seconds to execute. I know that it is the second for loop, since there is a loop inside of a loop. However, I believe that I need both loops, because I need to cross-reference the tracks list. Does anybody know of a way to make this function execute faster? I can't seem to see another way of writing it. FYI : The csv file that I am using has 5570 lines, which is another reason for the function taking a "while". Thanks in advance! def load_library(filename) : library = open(filename, 'rb') reader = csv.reader(library, delimiter = '|') tracks = set([]) albums = set([]) albums1 = set([]) #albums1 is the set of albums which have already been added to the albums list. for row in reader : artist, track, album, genre, year = row track = Track(artist, track) track.set_album(album) tracks.add(track) library = open(filename, 'rb') reader = csv.reader(library, delimiter = '|') for row in reader : artist, track, album, genre, year = row a = Album(artist, album) for i in tracks : if str(i.album) == str(a.title) : a.add_track(i.title) if album not in albums1 : albums.add(a) albums1.add(album) return tracks, albums After using c.Profile : cProfile.run('load_library()') 224565 function calls in 9.776 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.002 0.002 9.776 9.776 <string>:1(<module>) 5570 0.001 0.000 0.001 0.000 musiclib.py:18(set_album) 11140 0.007 0.000 0.007 0.000 musiclib.py:23(__init__) 92784 0.028 0.000 0.037 0.000 musiclib.py:31(add_track) 5570 0.004 0.000 0.009 0.000 musiclib.py:6(__init__) 1 9.723 9.723 9.775 9.775 musiclib.py:71(load_library) 2 0.000 0.000 0.000 0.000 {_csv.reader} 16710 0.002 0.000 0.002 0.000 {method 'add' of 'set' objects} 92784 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 2 0.000 0.000 0.000 0.000 {open} A: Do this all in only one for-loop: def load_library(filename) : library = open(filename, 'rb') reader = csv.reader(library, delimiter = '|') tracks = set([]) albums = {} for row in reader : artist, track, album, genre, year = row if album not in albums: a = Album(artist, album) albums[album] = a else: a = albums[album] a.add_track(track) track = Track(artist, track) track.set_album(album) tracks.add(track) return tracks, set(albums.values())
{ "pile_set_name": "StackExchange" }
Q: How to get position from markers for tracking? (Android Mapbox) Here is the problem: I want to show the user the best route to reach a marker after the user presses a button inside the infoWindow. The problem is, I can't get the marker's Location data due to some problem with Latlng and Position classes. (I am using the Mapbox example to get the route, so I need two Position values) So basically, I need to update the variable Destination with the marker's position by clicking a button inside the custom infowindow. Yet I have no idea how can I do that even though going through a lot on searching Google and Stack Overflow. Can someone help me? (Cammack!) Thanks a bunch for the help! protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //... // Origem: Rodoviaria final Position origin = Position.fromCoordinates(-47.882645, -15.794082); // Destino: Reitoria final Position destination = Position.fromCoordinates(-47.866611, -15.762604); //... mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() { @Nullable @Override public View getInfoWindow(@NonNull Marker marker) { //... final Marker marcador = marker; botaoIr = (Button)v.findViewById(R.id.botaoIr); botaoIr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //I have been trying the method below, but I am having trouble with LatLng and Position classes! //LatLng ponto = marcador.getPosition(); //destination = new Position(ponto.getLongitude(),ponto.getLatitude()); try { getRoute(origin, destination); } catch (ServicesException servicesException) { servicesException.printStackTrace(); } } }); } }); //... } A: To create a position call fromCoordinates(). destination = Position.fromCoordinates(ponto.getLongitude(),ponto.getLatitude());
{ "pile_set_name": "StackExchange" }
Q: Definite integration $\int_{0}^{\pi}\frac{x\sin(x)}{a + \cos^2(x)}\,\mathrm dx$ I am having trouble computing the following definite integral: $$\int_{0}^{\pi}\frac{x\sin(x)}{a +\cos^2(x)}\,\mathrm dx$$ My approach was to try and pick a very easy value for $a$, and use an identity on the denominator to try and simplify. However, I could not get anywhere with this approach. A: HINT: As $\displaystyle\int_a^bf(x)\ dx=\int_a^bf(a+b-x)\ dx$ So, if $\int_a^bf(x)\ dx=I,$ $$2I=\int_a^b[f(x)+f(a+b-x)]\ dx$$ Now $\sin(\pi+0-x)=+\sin x,\cos(\pi+0-x)=-\cos x$ Finally set $\cos x=u$
{ "pile_set_name": "StackExchange" }
Q: What is the datacontext of the user control? I have a user control like so: <Grid> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding NameC}" Width="100" /> <TextBlock Text="{Binding Filename}" /> </StackPanel> </Grid> with DP in code behind: public TestUc() { InitializeComponent(); DataContext = this; } public static readonly DependencyProperty NameCProperty = DependencyProperty.Register( "NameC", typeof(string), typeof(TestUc), new PropertyMetadata(default(string))); public string NameC { get { return (string) GetValue(NameCProperty); } set { SetValue(NameCProperty, value); } } public static readonly DependencyProperty FilenameProperty = DependencyProperty.Register( "Filename", typeof (string), typeof (TestUc), new PropertyMetadata(default(string))); public string Filename { get { return (string) GetValue(FilenameProperty); } set { SetValue(FilenameProperty, value); } } Now, when using it in a window, this works fine: <Window x:Class="TestDpOnUc.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:uc="clr-namespace:TestDpOnUc" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <uc:TestUc NameC="name is xxx" Filename="This is filename" /> </Grid> But This does not: <Window x:Class="TestDpOnUc.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:uc="clr-namespace:TestDpOnUc" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <uc:TestUc NameC="{Binding Name}" Filename="{Binding FileName}" /> </Grid> public MainWindow() { InitializeComponent(); DataContext = this; Name = "name is nafsafd"; FileName = "lkjsfdalkf"; } private string _Name; public string Name { get { return _Name; } set { _Name = value; OnPropertyChanged(); } } private string _FileName; public string FileName { get { return _FileName; } set { _FileName = value; OnPropertyChanged(); } } Can someone please explain why? Why is the datacontext of the user control not automatically set to the parent - the main window? A: It's because of this line DataContext = this in UserControl constructor. You set DataContext to your user control which affects default binding context for TestUc and all children, including <uc:TestUc ... />. So at the moment <uc:TestUc NameC="{Binding Name}" Filename="{Binding FileName}" /> will look for Name and FileName properties inside UserControl. You need to remove that line but that will break bindings within the user control. <TextBlock Text="{Binding NameC}" Width="100" /> <TextBlock Text="{Binding Filename}" /> Will look for NameC and Filename in MainWindow. Solution to that is to change binding context, per binding, via either RelativeSource or ElementName binding inside UserControl <UserControl ... x:Name="myUserControl"> <Grid> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding ElementName=myUserControl, Path=NameC}" Width="100" /> <TextBlock Text="{Binding ElementName=myUserControl, Path=Filename}" /> </StackPanel> </Grid> </UserControl>
{ "pile_set_name": "StackExchange" }
Q: How to "read" a user account with Powershell I am trying to create a backup powershell script for user documents. I have created a script where I am putting on a form box the username I want to backup and then the script proceeds. The last thing is that I want to have a rule that if I put a wrong name, the script will not proceed. Does anyone knows how I can "read" the present useraccounts on a laptop, in order to create rule to cross-check the input with the useraccounts? Best regards. A: This will read all of the folders in C:\Users and attempt to find a corresponding account in AD: Get-Childitem C:\users -Directory | ForEach-Object { $profilePath = $_.FullName Get-AdUser -Filter {SamAccountName -eq $_.Name} | ForEach-Object { New-Object -TypeName PsCustomObject | Add-Member -MemberType NoteProperty -Name Name -Value $_.Name -PassThru | Add-Member -MemberType NoteProperty -Name ProfilePath -Value $profilePath -PassThru | Add-Member -MemberType NoteProperty -Name SID -Value $_.SID -PassThru } } | Format-Table Name,SID, profilePath -AutoSize Obviously you can modify to get different AD properties, if needed. Also, remove the Format-Table command in order to pipe the output objects for further manipulation. Note: This requires the AD PowerShell Module to be installed on the system you run the script on. It only outputs an object if it finds a user account, so you won't see anything for folders it finds that have no account.
{ "pile_set_name": "StackExchange" }
Q: coordinate change in a list of points I have a list(?) of rules (geometrically points) like; pts={{a->3,b->6},...} and I want to apply the logarithm to each and change the name, e.g., ptsNew = {{u -> log(3), v->log(6)},...} I tried Log@@, and also Log//@ but neither even converted the number, much less the name (from x->u and y->v). Thanks! PS Surprisingly, this didn't even work as expected. I was trying it for just the 2nd coordinate but the Log is on the outside of the rule... Table[{u = 4, v = N[Log[s1a[[i]][[2]]]]}, {i, 1, 7}] PPS Sorry to come back but I just noticed that for my list of points (that came from an NSolve[]), {{a -> -4.38426 - 3.57467 I, b -> 0.92847 - 0.0993489 I}, {a -> -4.38426 + 3.57467 I, b -> 0.92847 + 0.0993489 I}, {a -> 5.65685 - 2.42731*10^-7 I, b -> -0.707107 - 8.46156*10^-9 I}, {a -> -4.38426 + 3.57467 I, b -> 0.532424 + 0.056971 I}, {a -> -4.38426 + 3.57467 I, b -> -0.294228 + 0.642985 I}, {a -> -4.38426 - 3.57467 I, b -> -0.294228 - 0.642985 I}, {a -> -4.38426 - 3.57467 I, b -> 0.532424 - 0.056971 I}, {a -> -5.65685 + 2.43458*10^-6 I, b -> 0.707107 + 4.7445*10^-8 I}, {a -> 5.65685 + 4.92316*10^-7 I, b -> -0.707107 + 1.71621*10^-8 I}} when I use @J.M. suggestion, I get nine results again, but each result is `doubled'; {{{u -> 1.73287 - 2.45757 I, v -> 1.73287 - 2.45757 I}, {u -> -0.0685253 - 0.106597 I, v -> -0.0685253 - 0.106597 I}}, {{u -> 1.73287 + 2.45757 I, v -> 1.73287 + 2.45757 I}, {u -> -0.0685253 + 0.106597 I, v -> -0.0685253 + 0.106597 I}}, {{u -> 1.73287 - 4.29092*10^-8 I, v -> 1.73287 - 4.29092*10^-8 I}, {u -> -0.346574 - 3.14159 I, v -> -0.346574 - 3.14159 I}}, {{u -> 1.73287 + 2.45757 I, v -> 1.73287 + 2.45757 I}, {u -> -0.624622 + 0.106597 I, v -> -0.624622 + 0.106597 I}}, {{u -> 1.73287 + 2.45757 I, v -> 1.73287 + 2.45757 I}, {u -> -0.346574 + 1.99995 I, v -> -0.346574 + 1.99995 I}}, {{u -> 1.73287 - 2.45757 I, v -> 1.73287 - 2.45757 I}, {u -> -0.346574 - 1.99995 I, v -> -0.346574 - 1.99995 I}}, {{u -> 1.73287 - 2.45757 I, v -> 1.73287 - 2.45757 I}, {u -> -0.624622 - 0.106597 I, v -> -0.624622 - 0.106597 I}}, {{u -> 1.73287 + 3.14159 I, v -> 1.73287 + 3.14159 I}, {u -> -0.346574 + 6.70973*10^-8 I,v -> -0.346574 + 6.70973*10^-8 I}}, {{u -> 1.73287 + 8.703*10^-8 I,v -> 1.73287 + 8.703*10^-8 I}, {u -> -0.346574 + 3.14159 I, v -> -0.346574 + 3.14159 I}}} Not sure if it was `permuting' instead of 'combinating' the 2 arguments or what, but the only answer worked well. Just in case someone came across this. A: How about {u -> Log@a, v -> Log@b} /. pts
{ "pile_set_name": "StackExchange" }
Q: Swift - Error passing data between protocols / delegates (found nil) I am developing an application with swift 3.0. Where what I want to do is, from the "MainMapVC" class, which is the view where you have a map with a date slider (see the attached image). I want to move the slider and send that slider position (1,2 or 3) to LeftSideViewController which is the side view (the legend) updating the content depending on the selected date. View of MainMapVC: View of MainMapVC with Legend: Well, and I've come to the point where I have to pass a value between the two view controllers. But problem is that I get the error "fatal error: unexpectedly found nil while unwrapping an optional value". Basically I have a "nil" delegate. But do not find where the error is, because the definition of the delegate is like "var delegate: MainMapVCDelegate!" And I call it "delegate.moveSliderDates (datePos: Int (roundedValue))" in the "MainMapVC" class. Does anyone know where I failed in the statement of the delegate?Thanks :) I attach the code of the two classes so that you see the whole code. Class MainMapVC (first way): import UIKit protocol MainMapVCDelegate: class { func moveSliderDates(datePos: Int) } class MainMapVC: UIViewController, UISearchBarDelegate, CLLocationManagerDelegate, GMSMapViewDelegate { //MARK: VARIABLES weak var delegate: MainMapVCDelegate? = nil let step: Float = 1 @IBAction func moveSliderDates(_ sender: UISlider) { let roundedValue = round(sender.value / step) * step sender.value = roundedValue delegate?.moveSliderDates(datePos: Int(roundedValue)) } } The delegate value inside the moveSliderDates function is "nil": delegate?.moveSliderDates(datePos: Int(roundedValue)) Class LeftSideViewController (first way): import UIKit class LeftSideViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, customCellDelegate, MainMapVCDelegate { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "MainMapVC" { let secondViewController = segue.destination as! MainMapVC secondViewController.delegate = self } } func moveSliderDates(datePos: Int){ print(datePos) print("/////////////") tableSideLeft.reloadData() } not enter inside this function because the delegate of "MainVC" is "nil": Class MainMapVC (second way): let step: Float = 1 @IBAction func moveSliderDates(_ sender: UISlider) { let roundedValue = round(sender.value / step) * step sender.value = roundedValue let data:[String: Int] = ["data": Int(roundedValue)] NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: data) } Class LeftSideViewController (second way): func listnerFunction(_ notification: NSNotification) { if let data = notification.userInfo?["data"] as? String { print(data) } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(listnerFunction(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil) } Never goes into the function listnerFunction A: You get the error because you defined your delegate as force unwrapped noy-nil version by this code var delegate: LeftSideDelegate! Instead, you need to change it like this. You should not create strong reference cycle for delegate. weak var delegate: LeftSideDelegate? = nil Then for all your delegate calles, do the wrapped version delegate call delegate?.changeZindexDelivery() Other than that, change your line protocol LeftSideDelegate { into protocol LeftSideDelegate : class { Passing data between view controllers using delegate First, in the class where you want to pass the data to another view controller, declare protocol in this way protocol SampleDelegate: class { func delegateFunctionCall(data: String) } Then, create delegate variable as optional with type weak var. Call delegate method with you want to pass data or trigger action class SecondViewController: UIViewController { weak var delegate: SampleDelegate? = nil @IBAction func sendTextBackButton(sender: AnyObject) { delegate?.delegateFunctionCall(data: textField.text!) } } Finally in your view controller that you want to receive action or data, implement the protocol. When you are initiating the second view controller, set it's delegate variable to be the current view controller class FirstViewController: UIViewController, SampleDelegate { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showSecondViewController" { let secondViewController = segue.destination as! SecondViewController secondViewController.delegate = self } } func delegateFunctionCall(data: String) { label.text = data } } Passing data between view controllers using notification In the destination view controller, register a handler function that is ready to be called. You can add this registration code in view did load NotificationCenter.default.addObserver(self, selector: #selector(listnerFunction(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil) func listnerFunction(_ notification: NSNotification) { if let data = notification.userInfo?["data"] as? String { // do something with your data } } Then in another view controller, if you want to pass data, simply call this let data:[String: String] = ["data": "YourData"] NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: data)
{ "pile_set_name": "StackExchange" }
Q: How to know ".automaticDestinations-ms" files to which app relates? Does anyone know (because on Microsoft forums nobody answered me), how I can find what application has which automaticDestinations-ms file in %appdata%\microsoft\windows\recent\automaticdestinations? That's the folder where Windows 7 stores its jump lists, and I want to know how to automatically/programmatically find the relation between each file and an application. At least, even manually, I didn't find any pattern, just by looking at the extensions of the files, because some programs open files with the same extension (like images), so this method it's not OK for all programs. Do you have any other idea? Maybe knowing the format of those files? A: Clear and Manage Windows 7 Jump Lists To find application associations, open the *.automaticdestinations-ms files in Notepad. You can find file paths to items in the application jump list and figure out which app/jump list the *.automaticdestinations-ms file is associated with. Note that opening the files in Notepad, that there are (something like) spaces between characters. For example, foo.exe is "f o o . e x e" Windows 7 Jump Lists are stored in the paths listed in the following short list of filenames that are associated with specific applications: PATH: %AppData%\Microsoft\Windows\Recent\AutomaticDestinations 28c8b86deab549a1.automaticDestinations-ms = IE8 Pinned and Recent a7bd71699cd38d1c.automaticDestinations-ms = Word 2010 Pinned and Recent adecfb853d77462a.automaticDestinations-ms = Word 2007 Pinned and Recent a8c43ef36da523b1.automaticDestinations-ms = Word 2003 Pinned and Recent 1b4dd67f29cb1962.automaticDestinations-ms = Windows Explorer Pinned and Recent 918e0ecb43d17e23.automaticDestinations-ms = Notepad Pinned and Recent d7528034b5bd6f28.automaticDestinations-ms = Windows Live Mail Pinned and Recent c7a4093872176c74.automaticDestinations-ms = Paint Shop Pro Pinned and Recent b91050d8b077a4e8.automaticDestinations-ms = Media Center f5ac5390b9115fdb.automaticDestinations-ms = PowerPoint 2007 23646679aaccfae0.automaticDestinations-ms = Adobe Reader 9 aff2ffdd0862ff5c.automaticDestinations-ms = Visual Studio 2012 PATH: %AppData%\Microsoft\Windows\Recent\CustomDestinations 28c8b86deab549a1.customDestinations-ms = IE8 Frequent & Tasks The post where I found this list was here. (Most of that discussion is not very helpful. It was started in June 2009. I pulled this list out from Microsoft MVP, Ronnie Vernon's replies later in the thread – Scroll down to March 10, 2010.)
{ "pile_set_name": "StackExchange" }
Q: Kivy multi-threading and update screen I am wrote a piece of python code that handles multiple processes and it works great, but I am trying to add a Kivy based display to this code. I have updated the code to be able to use threads instead of processes, which works. The issue that I have is that I can't seem to get the threads to write back to the screen. I am using @mainthread. I found a sample code here, and was able to get the threads to update the screen, but for some reason my code doesn't seem to work. ->Edit, I have removed the extra code that I don't believe is pertinent to my question. ->Edit #2:, I have still simplified the code to what I believe is bare. To still show the issue that I have. From what I have read, it may be the x.join code that is causing me the issue, and locking up the main loop. I need to run the while loop 5 times, but can only run 2 threads at a time. Need to hold the while loop in a non-blocking state while threads finish before proceeding. Here is menu.kv <ScreenManagement>: MenuScreen: ProgramScreen: <MenuScreen>: name: 'menu' AnchorLayout: GridLayout: cols: 2 Button text: "Start Application" on_release: root.routine() <ProgramScreen>: filler1: filler1 filler2: filler2 filler3: filler3 filler4: filler4 name: 'program' GridLayout: cols: 4 Button: id: filler1 text: 'Filler 1' halign: 'center' padding_y: '300' bcolor: 1,0,1,1 Button: id: filler2 text: 'Filler 2' halign: 'center' padding_y: '300' bcolor: 1,0,0,1 Button: id: filler3 text: 'Filler 3' halign: 'center' padding_y: '300' bcolor: 1,0,1,0 Button: id: filler4 text: 'Filler 4' halign: 'center' padding_y: '40 ' bcolor: 0,0,1,1 Here is my main.py from kivy.app import App from kivy.uix.togglebutton import ToggleButton from kivy.uix.widget import Widget from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.lang import Builder from kivy.properties import * from kivy.core.window import Window from kivy.clock import Clock, mainthread import threading import time ######################################################################## class ScreenManagement(ScreenManager): pass class MenuScreen(Screen): def routine(self): self.parent.current = 'program' threading.Thread(target=ProgramScreen().build).start() class ProgramScreen(Screen): @mainthread def update_label(self, int_counter, new_text): if int_counter == 0 : print "here ", int_counter, new_text self.filler1.text = new_text elif int_counter == 1 : self.filler2.text = new_text elif int_counter == 2 : self.filler3.text = new_text elif int_counter == 3 : self.filler4.text = new_text else: self.filler1.text = "fault" #dummy function to be replaced with a function that will call GPIO for input and feedback. def func (self,value): print 'func', value, 'starting' for i in xrange(10*(value+1)): if ((i%3) == 0): self.update_label(int(value),str(i)) print value, i time.sleep(1) print 'func', value, 'finishing' def build(self): NumberofFiller = 2 NumberofCells = 5 CellCounter = 0 while CellCounter < NumberofCells: try: threads = [] print ('Counter:',CellCounter,'Fillers:',NumberofFiller,'Cells:',NumberofCells) for i in range (NumberofFiller): t = threading.Thread(target=self.func, args=((CellCounter%NumberofFiller),)) t.start() threads.append(t) CellCounter = CellCounter +1 for x in threads: #Problem I believe is here. x.join() #Need a way to pause the While loop for the first set of threads to finish before starting the next threads. # print (threads) except (KeyboardInterrupt, SystemExit): functions.cleanAndExit() ######################################################################## #Builder.load_file("Menu_red.kv") #Not needed class Menu_red2App(App): def build(self): return ScreenManagement() #---------------------------------------------------------------------- if __name__ == "__main__": Menu_red2App().run() The only way that I could find to have the screen update, after executing self.parent.current = 'program' was to run the rest of the code as a thread. But I now I can't seem to get the threads to write back to the main function to update the screen. In the end, once the text has been updated, I will need to change the color of the boxes, but that will come in due course. A: The problem is that when you start the outer thread in your routine method, you set your target to ProgramScreen().build, which will in fact create a new screen. So it will not affect the screen you have in your screenmanager. To set the target to the build method of the ProgramScreen you got in the screenmanager, you can get that screen by its name. You allready gave it the name program. So your MenuScreen class should look like this: class MenuScreen(Screen): def routine(self): self.parent.current = 'program' threading.Thread(target=self.manager.get_screen('program').build).start()
{ "pile_set_name": "StackExchange" }
Q: Same function with same inputs returns different values Lets say I have a function like follows: testFunction <- function(testInputs){ print( sum(testInputs)+1 == 2 ) return( sum(testInputs) == 1 ) } When I test this on command line with following input: c(0.65, 0.3, 0.05), it prints and returns TRUE as expected. However when I use c(1-0.3-0.05, 0.3, 0.05) I get TRUE printed and FALSE returned. Which makes no sense because it means sum(testInputs)+1 is 2 but sum(testInputs) is not 1. Here is what I think: Somehow printed value is not exactly 1 but probably 0.9999999..., and its rounded up on display. But this is only a guess. How does this work exactly? A: This is exactly a floating point problem, but the interesting thing about it for me is how it demonstrates that the return value of sum() produces this error, but with + you don't get it. See the links about floating point math in the comments. Here is how to deal with it: sum(1-0.3-0.5, 0.3, 0.05) == 1 # [1] FALSE dplyr::near(sum(1-0.3-0.05, 0.3, 0.05), 1) # [1] TRUE For me, the fascinating thing is: (1 - 0.3 - 0.05 + 0.3 + 0.05) == 1 # [1] TRUE Because you can't predict how the various implementations of floating point arithmetic will behave, you need to correct for it. Here, instead of using ==, use dplyr::near(). This problem (floating point math is inexact, and also unpredictable), is found across languages. Different implementations within a language will result in different floating point errors. As I discussed in this answer to another floating point question, dplyr::near(), like all.equal(), has a tolerance argument, here tol. It is set to .Machine$double.eps^0.5, by default. .Machine$double.eps is the smallest number that your machine can add to 1 and be able to distinguish it from 1. It's not exact, but it's on that order of magnitude. Taking the square root makes it a little bigger than that, and allows you to identify exactly those values that are off by an amount that would make a failed test for equality likely to be a floating point error. NOTE: yes, near() is in dplyr, which i almost always have loaded, so I forgot it wasn't in base... you could use all.equal(), but look at the source code of near(). It's exactly what you need, and nothing you don't: near # function (x, y, tol = .Machine$double.eps^0.5) # { # abs(x - y) < tol # } # <environment: namespace:dplyr>
{ "pile_set_name": "StackExchange" }
Q: Cloud9 IDE Not Loading Jquery I have tried many ways of importing Jquery into my project but I can never get it to work in Cloud9. My code works on other IDEs and text editors, but not on Cloud9. If any body knows more than me about this please help. Here is my project: CLOUD9 PROJECT A: It is always useful to open the browser developer tools/console for more information. In this case it says: [blocked] The page at '...' was loaded over HTTPS, but ran insecure content from 'http://codepen.io/assets/libs/fullpage/jquery.js': this content should also be loaded over HTTPS. There is your answer. For your convenience I modified it for you.
{ "pile_set_name": "StackExchange" }
Q: UIDynamicAnimator Shake with spring effect I'm trying to replace my core animation shake effect in this code let shake = CAKeyframeAnimation(keyPath: "position.x") shake.values = [0, 20, -20, 20, -15, 15, -5, 5, 0] shake.keyTimes = [0, 1/10.0, 3/10.0, 5/10.0, 6/10.0, 7/10.0, 8/10.0, 9/10.0, 1] shake.duration = 0.4 shake.additive = true circlesContainer.layer.addAnimation(shake, forKey: "shakeYourBooty") with the spring effect by combining UIPushBehavior and UIAttachmentBehavior like this if origCirclesContainerCenter == nil { origCirclesContainerCenter = circlesContainer.center } shake = UIDynamicAnimator(referenceView: self.view) let push = UIPushBehavior(items: [circlesContainer], mode: UIPushBehaviorMode.Continuous) push.pushDirection = CGVectorMake(100.0, 0.0) print(origCirclesContainerCenter) let attachement = UIAttachmentBehavior(item: circlesContainer, attachedToAnchor:origCirclesContainerCenter!) attachement.frequency = 3.0 attachement.damping = 0.5 shake.addBehavior(attachement) shake.addBehavior(push) The problem is the attachment behavior doesn't seem to work because the view does not spring back to the original position after being pushed. The animation actually pushes the view position to the right 100 points. origCirclesContainerCenter is the same on every call. Any idea? A: I changed the push behavior mode to UIPushBehaviorMode.Instantaneous to fix the problem.
{ "pile_set_name": "StackExchange" }
Q: Using an uninitialised variable in a constructor So I have a rather simple piece of code: Soldier Horseman = new Soldier("Horseman",Archer, 20); Soldier Spearman = new Soldier("Spearman",Horseman, 10); Soldier Archer = new Soldier("Archer",Spearman, 10); Where the constructor for soldier takes the arguments Soldier(String name, Soldier target, double range) The target is then used to calculate distance between the two in a method. public double DistanceCalculation() { distanceToTarget = ((Math.pow((soldierPosition[0] - soldierTarget.soldierPosition[0]), 2)) + Math.pow((soldierPosition[1] - soldierTarget.soldierPosition[1]), 2)); return distanceToTarget; However, when I try to create this code, the top most soldier cannot be created because its target doesnt exist yet. I tried using String instead of Soldier in the constructor, but then I cannot figure out how to convert string into Soldier so that the SoldierTarget.soldierPosition works. Any ideas? A: It may be a better idea to store the information about targets in a separate data structure, e.g. a HashMap<Soldier, Soldier>. Then you can make Soldier immutable, and all the circularity problems disappear. Soldier horseman = new Soldier("Horseman", 20); Soldier spearman = new Soldier("Spearman", 10); Soldier archer = new Soldier("Archer", 10); Map<Soldier, Soldier> targets = new HashMap<>(); targets.put(horseman, archer); targets.put(archer, spearman); targets.put(spearman, horseman); A: Don't set the target in the constructor. Set it in another method: Soldier target; Soldier(String name,double range) { // etc } public void setTarget( Soldier s ) { target = s; } Then you can do this: Soldier horseman = new Soldier("Horseman", 20); Soldier spearman = new Soldier("Spearman", 10); Soldier archer = new Soldier("Archer", 10); horseman.setTarget(archer); spearman.setTarget( horseman ); archer.setTarget(spearman); This way each soldier knows about his current target. Then if (for example) horseman vanquishes the archer, you can just call horseman.setTarget(spearman) to set a new target. I was assuming range was the soldier's maximum attack range, but if it is the distance to the target it should not be set in the constructor either.
{ "pile_set_name": "StackExchange" }
Q: Why is my simple pthreads program crashing with a segmentation fault? #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #include<signal.h> #include<unistd.h>//getch(); #include <termios.h>//getch(); #include <pthread.h> volatile sig_atomic_t flag = 0; char getch() { int buf=0; struct termios old= {0}; fflush(stdout); if(tcgetattr(0, &old)<0) perror("tcsetattr()"); old.c_lflag&=~ICANON; old.c_lflag&=~ECHO; old.c_cc[VMIN]=1; old.c_cc[VTIME]=0; if(tcsetattr(0, TCSANOW, &old)<0) perror("tcsetattr ICANON"); if(read(0,&buf,1)<0) perror("read()"); old.c_lflag|=ICANON; old.c_lflag|=ECHO; if(tcsetattr(0, TCSADRAIN, &old)<0) perror ("tcsetattr ~ICANON"); //printf("%c\n",buf);//to print the value typed. return buf; } void *send_function() { printf("\n Send Thread \n"); //return 0; } void my_function(int sig) { // can be called asynchronously flag = 1; // set flag } int main () { char selection;//user input(s or r) pthread_t send; while(1) { signal(SIGINT, my_function); //printf("\n Before SIGINT \n"); if(flag) { printf("\n Choose your terminal S or R \n"); selection=getch(); flag = 0; } if(selection=='s') if(pthread_create(&send,NULL,send_function(),NULL)) { fprintf(stderr, "Error creating thread\n"); return 1; } else if(selection=='r') printf("Receive Function is received"); //printf("\n After SIGINT \n"); } return 0; } Output: nivas@balakrishnan-HCL-Desktop:~/C_sample$ gcc -pthread -o thread thread.c nivas@balakrishnan-HCL-Desktop:~/C_sample$ ./thread Choose your terminal S or R Send Thread Send Thread Send Thread Send Thread Send Thread Segmentation fault (core dumped) nivas@balakrishnan-HCL-Desktop:~/C_sample$ ^C nivas@balakrishnan-HCL-Desktop:~/C_sample$ In the above program I'm getting a segmentation fault. My required output is to print "Send Thread" continuosly once I press 's'. I have looked into previous similar questions, but I can't find answer. Can anyone help me? A: You need to change the function send_function(). According to the man page, this function should take a pointer to void as an argument, and should return a pointer to void: void * send_function(void *parg) { printf("\n Send Thread \n"); return parg; } You also need to correct your function call, which includes a pair of stray parenthesis: if(pthread_create(&send,NULL,send_function,NULL)) {} As it is, your program will loop printing "Send Thread" until your system runs out of resources. You can create detached threads that release system resources when they terminate by adding these lines before the loop in main(): pthread_attr_t attr; if (pthread_attr_init(&attr) != 0) { perror("Error in pthread_attr_init()"); exit(EXIT_FAILURE); } if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) { perror("Error in pthread_attr_setdetachstate()"); exit(EXIT_FAILURE); } Then change the pthread_create() call inside the loop to: if(pthread_create(&send, &attr, send_function, NULL)) {} After this change your program should print "Send Thread" repeatedly, releasing resources after each message is printed, until you stop it.
{ "pile_set_name": "StackExchange" }
Q: The way "you" can modify a sentence Shut up you idiot! Shut up idiot! How does "you" affect the meaning of the first clause? Are they both formal ways of addressing? A: This is direct address in both cases, although it is hardly formal, so there should be a comma after "up" if this is in writing: Shut up, you idiot! Shut up, idiot! There is no significant change in meaning. This is not a polite usage.
{ "pile_set_name": "StackExchange" }
Q: How the preposition "of" is used after the article? I read a sentence in a passage "We have been taught to believe that our lives are better than the of those who came before use ideology of modern economics suggests that material progress has yielded enhanced satisfaction and well-being." In the above sentence i saw 'the' before 'of' what is special grammar behind it. Can you explain me the grammar behind it? A: This looks like a transcription error. The original passage is: We have been taught to believe that our lives are better than those who came before us. The ideology of modern economics suggests that material progress has yielded enhanced satisfaction and well-being. From the April 5 1992 New York Times. StoneyB found another passage that is even closer. The only difference between this and the question is the omission of the word "lives." We have been taught to believe that our lives are better than the lives of those who came before us. The ideology of modern economics suggests that material progress has yielded enhanced satisfaction and well-being.
{ "pile_set_name": "StackExchange" }
Q: Finder go to Clipboard I’d like to create an Apple script that will use a text path in clipboard and open a new Finder window and go to that path A: If you can use the Terminal, do open "`pbpaste`" A: Assuming that the clipboard contains a string of the form /Users/username/path/to/file, this should work: tell application "Finder" to reveal (get the clipboard as string) as POSIX file The use of the verb reveal ensures that, if a path to a file is supplied, the Finder will display that file in its containing folder rather than launching an application to open the file. If this isn't desirable, replace reveal with open.
{ "pile_set_name": "StackExchange" }
Q: How to test email headers using RSpec I'm using SendGrid's SMTP API in my Rails application to send out emails. However, I'm running into troubles testing the email header ("X-SMTPAPI") using RSpec. Here's what the email looks like (retrieving from ActionMailer::Base.deliveries): #<Mail::Message:2189335760, Multipart: false, Headers: <Date: Tue, 20 Dec 2011 16:14:25 +0800>, <From: "Acme Inc" <[email protected]>>, <To: [email protected]>, <Message-ID: <[email protected]>>, <Subject: Your Acme order>, <Mime-Version: 1.0>, <Content-Type: text/plain>, <Content-Transfer-Encoding: 7bit>, <X-SMTPAPI: {"sub":{"|last_name|":[Foo],"|first_name|":[Bar]},"to":["[email protected]"]}>> Here's my spec code (which failed): ActionMailer::Base.deliveries.last.to.should include("[email protected]") I've also tried various method to retrieve the header("X-SMTPAPI") and didn't work either: mail = ActionMailer::Base.deliveries.last mail.headers("X-SMTPAPI") #NoMethodError: undefined method `each_pair' for "X-SMTPAPI":String Help? Update (answer) Turns out, I can do this to retrieve the value of the email header: mail.header['X-SMTPAPI'].value However, the returned value is in JSON format. Then, all I need to do is to decode it: sendgrid_header = ActiveSupport::JSON.decode(mail.header['X-SMTPAPI'].value) which returns a hash, where I can do this: sendgrid_header["to"] to retrieve the array of email addresses. A: The email_spec gem has a bunch of matchers that make this easier, you can do stuff like mail.should have_header('X-SMTPAPI', some_value) mail.should deliver_to('[email protected]') And perusing the source to that gem should point you in the right direction if you don't want to use it e.g. mail.to.addrs returns you the email addresses (as opposed to stuff like 'Bob ') and mail.header['foo'] gets you the field for the foo header (depending on what you're checking you may want to call to_s on it to get the actual field value)
{ "pile_set_name": "StackExchange" }
Q: What's the difference between state.path and route.path in angular2 In reading angular2 documnet, I get confused in CanLoad param, https://angular.io/docs/ts/latest/guide/router.html In CanLoad section, it uses /${route.path}, when CanActivate uses state.url. canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { let url: string = state.url; return this.checkLogin(url); } canLoad(route: Route): boolean { let url = `/${route.path}`; return this.checkLogin(url); } What's the difference? Why doesnot use route.path directly, but wrapped with `/${}` ? A: What's the difference? Why doesnot use route.path directly, but wrapped with /${} ? `/${route.path}`; is just using string interpolation to prefix the route.path with a / ${route.path} is replaced by the result of route.path. If route.path returns foo/bar the result will be /foo/bar
{ "pile_set_name": "StackExchange" }
Q: Nginx performance when running multiple instances on the same machine I'm trying to understand the performance impact of having multiple nginx instances (masters) running on the same machine, rather than having them all load into a single instance using different server blocks. How does the use of multiple instances of nginx impact things like worker_process and worker_connections optimization? I see tons of advice indicating that worker_process should mirror the number of cores, and at most should be double the number of cores. I'm also to understand that the worker_connections should match the ulimit, or be a bit under the ulimit. Making too many connections available, or having too many workers per core is supposed to hurt performance. I have two cores and a ulimit of 1024, but I have 4 instances of nginx each of which has the following settings: worker_processes 4; worker_connections: 1024; Doesn't this have the same effect as if I had worker_processes 16; and worker_connections 4069;? Note: Let me make clear when I say nginx instances, I mean that there are 4 independent master nginx process each fed a different config file which has similar settings, and each with their own workers. Note 2: This scenario is something I've inherited and is already in place. I am trying to figure out if I should change the way nginx is configured and have an informed reason for it. A: From a system point of view, there is no inherent differences in running 4 masters with 4 server sections, or a single master with 16 server sections. It implements the same architecture : parallelized event-based processes. The worker/core ratio must be accounted wrt the total of workers across all of your masters if you have several ones. This comes from several constraints : make sure CPUs are not overloaded, thus number of workers should be <= number of cores make sure parallelization and OS scheduling is used to its best, thus number of workers should be as high as possible HTTP server workers are low on CPU usage and mostly wait on I/Os, thus it'as actually safe to allocate something between 2 or 4x the number of cores It should be a little more efficient with a single master, since a few ressources like MIME maps and so on will only be loaded once. But that's a minor point. It should be more efficient with a single master, because there is a single large pool of workers shared by all servers. If a single server momentarily requires most workers (say 16), it might get them. On multi-master configuration (say 4 masters with 4 workers), they only get to use at most what they have : 4 workers. On the other hand it might be the desired effect : strictly split in 4 instances to make sure each one always get at least the quarter of your host attention. But never more. It should be easier to configure and maintain with 1 master (think: security updates). It should be more resilient with 4 masters : you're allowed to crash or totally mess one master configuration without touching the 3 others. Unless your 4 masters use different Nginx versions, you won't benefit from uber-optimisations like having the exact set of modules compiled in for each master.
{ "pile_set_name": "StackExchange" }
Q: Generating a new variable by selection from multiple variables I have some data on diseases and age of diagnosis. Each participant was asked what diseases they have had and at what age that disease was diagnosed. There are a set of variables disease1-28 with a numeric code for each disease and another set age1-28 with the age at diagnosis in years. The diseases are placed in successive variables in the order recalled; the age of diagnosis is placed in the appropriate age variable. I would like to generate a new variable for each of several diseases giving the age of diagnosis of that disease: e.g. asthma_age_at_diagnosis Can I do this without having 28 replace statements? Example of the data: +-------------+----------+----------+----------+------+------+------+ | Participant | Disease1 | Disease2 | Disease3 | Age1 | Age2 | Age3 | +-------------+----------+----------+----------+------+------+------+ | 1 | 123 | 3 | . | 30 | 2 | . | | 2 | 122 | 123 | 5 | 23 | 51 | 44 | | 3 | 5 | . | . | 50 | . | . | +-------------+----------+----------+----------+------+------+------+ A: I give a general heads-up that a question of this form without any code of your own is often considered off-topic for Stack Overflow. Still, the Stata users around here are the people answering Stata questions (surprise) and we usually indulge questions like this if interesting and well-posed. I'd advise a different data structure, period. With your example data clear input Patient Disease1 Disease2 Disease3 Age1 Age2 Age3 1 123 3 . 30 2 . 2 122 123 5 23 51 44 3 5 . . 50 . . end You can reshape reshape long Disease Age, i(Patient) j(Order) drop if missing(Disease) list, sep(0) +--------------------------------+ | Patient Order Disease Age | |--------------------------------| 1. | 1 1 123 30 | 2. | 1 2 3 2 | 3. | 2 1 122 23 | 4. | 2 2 123 51 | 5. | 2 3 5 44 | 6. | 3 1 5 50 | +--------------------------------+ With the data in this form you can now answer lots of questions easily. I don't see that a whole bunch of new variables would make many analyses easier. Another way to see this is that you have hinted that the order in which diseases are coded is arbitrary; that being so, wiring that into the data structure is ill-advised. Even if order is important, it is still accessible as part of the dataset (variable Order). Hint: If you still want separate variables for some purposes, look at separate.
{ "pile_set_name": "StackExchange" }
Q: Differentiation using product rule? I'm stuck on differentiating this: $$f(x) = \frac{4\sin(2x)}{e^\sqrt{2x-1}}$$ I thought about using the product rule here, but when I do that I get an expression that is hard to simplify, and I need to solve for when $f(x) = 0$. Is there a simpler way of doing this? Help here would be much appreciated! A: Instead of the product rule, I think that logarithmic differentiation would make life easier. $$f(x) = 4\sin(2x) e^{-\sqrt{2x-1}}\implies \log(f(x))=\log(4)+\log(\sin(2x))-\sqrt{2x-1}$$ $$\frac{f'(x)}{f(x)}=2\cot(2x)-\frac 1 {\sqrt{2x-1}}$$ Since you care about $f'(x)=0$, this is the equation to be solved. Graphing you should notice a root "close" to $2.2$. Now, start Newton method.
{ "pile_set_name": "StackExchange" }
Q: ¿Dónde está console en la carpeta /app en un nuevo php proyecto creado con Symfony? Quería utilizar por primera vez el terminal para ejecutar un comando php con el framework Symfony. Sin embargo, he hecho un simple proyecto de creación con$ symfony new myproject A: Desde la versión 3.0 de Symfony, la utilidad de consola ha sido movida a bin/console, dentro del directorio del proyecto creado.
{ "pile_set_name": "StackExchange" }
Q: Issues about Ajax response I have used three select boxes with the same class along with a radio button. How can I get the selected values of dropdown in ajax response? My problem is, I am getting the first select box in ajax, but when I try to select the second or third, I am getting an empty value. Can you tell me where is the mistake or give me ideas for taking values in ajax? Here is the code: <td><input type="radio" id="active_btn" name="status" value="yes">Active</td> <td><select class="desig_opt" name="select_opt" ><option value="" >Select</option><option value="Admin" >Admin</option> <option value="Staff" >Staff</option></select></td> <td><input type="radio" id="deactive_btn" name="status" value="no">Deactive</td> <td><select class="desig_opt" name="select_opt" ><option value="" >Select</option><option value="Admin" >Admin</option> <option value="Staff" >Staff</option></select></td> <td><input type="radio" id="both_btn" name="status" value="both">Both</td> <td><select class="desig_opt" name="select_opt"> <option value="" >Select</option><option value="Admin" >Admin</option> <option value="Staff">Staff</option></select></td> In ajax reponse I used the line below to get the selected value: var admin=$(".desig_opt option:selected").val(); Is it the right way of taking the values? If not, can you tell me how? A: (".desig_opt option:selected") , returns an array. Try JS function test(){ var admin=$(".desig_opt option:selected"); $.each(admin, function( index, value ) { alert( $(admin[index]).val() ); }); } DEMO Maybe you could store the values in other array like function test(){ var admin=$(".desig_opt option:selected"); var data = []; $.each(admin, function( index, value ) { // validate if $(admin[index]).val() != '' before add ?? data.push($(admin[index]).val()); }); alert(data); } DEMO
{ "pile_set_name": "StackExchange" }
Q: I can't read strings written by the user I am not able to read characters, strings or numbers. I'm starting to learn js and maybe it's an easy question but I cant answer it by myself. The code I'm using is: var main = function() { "use strict"; var stdout = require("system").stdout; var stdin = require("system").stdin; stdout.write( "What is your name? " ); var name = stdin.readLine(); stdout.writeLine( "Hello, " + name ); }(); Thanks for your help and sorry if this question is quite silly. A: Vanilla Javascript doesn't support "read strings". However, if you have an html document, you could grab the input from a text box: document.getElementById('textbox_id').value
{ "pile_set_name": "StackExchange" }
Q: .htaccess RedirectMatch 301 pattern I have three patterns that I want to redirect in .htaccess. https://example.com/questions/name-of-question https://example.com/category/name-of-category https://example.com/a-4-digit-number/name-of-post (The No. 3 like: https://example.com/5485/name-of-post) all of them need a /blog/ after the domain: https://example.com/blog/questions/name-of-question https://example.com/blog/category/name-of-category https://example.com/blog/a-4-digit-number/name-of-post I used the code below for the first one, once it worked and then something happened and the htaccess got deleted. Now that I use it againg it does not redirect: RewriteEngine on Options +FollowSymLinks RedirectMatch 301 https://example.com/questions/(.*) https://example.com/blog/questions/$1 Can anyone help me with these redirects? Specially the no. 3 with the 4-digit pattern. A: Use RewriteRule directive like this to target all the 3 rules into one pattern: Options +FollowSymLinks RewriteEngine on RewriteRUle ^/?(questions|category|\d{4})/.+$ /blog/$0 [L,NC,R=301,NE]
{ "pile_set_name": "StackExchange" }
Q: Specific solution of the Burgers equation $u_t + u u_x =0$ with boundary condition $u(x,0)=e^{-x^2}$ I have difficulty with finding a specific solution to the below PDE $$\left\{\begin{matrix} u_{t}+uu_{x}=0\\ u(x,0)=e^{-x^2} \end{matrix}\right.$$ My attempt: It is stright forward to get the general solution using method of characteristic $$\frac{dt}{1} = \frac{dx}{u}=0$$ $$\frac{dt}{dx} =u$$ $$c=x-ut$$ thus $$u(x,y)=f(c)=f(x-ut)$$ How then the specific solution using the given boundary condition $u(x,0)=e^{-x^2}$ can be derived? Could I simply substitute for $x$ and $t=0$? How then the resulting equation could be simplified further? $$u(x,0)=f(x)=e^{-x^2}$$ $$u(x,y)=e^{-(x-ut)^2}$$ A: $u$ is constant along the characteristics. So given $x,t$, you need to find $x_0$ such that $$ x_0 = x - u(x_0,0) t \tag{1}$$ And then you have that $f(x,t) = u(x_0,0) = e^{-x_0^2}$. Unfortunately, solving the equation (1) often cannot be done explicitly. This is for two reasons: As in your case, the function $u(x_0,0) = e^{-x_0^2}$ is too complicated to invert. Also as in your case, there will be points for which there are multiple possible $x_0$ (for one fixed pair $(x,t)$). One way to go about it is to write your solution in "hodographic coordinates". This means that instead of writing it as $(x,t)$, we write it in $(x_0, t)$. Vis: $$ u(x_0 + e^{-x_0^2}t, t) = e^{-x_0^2} $$
{ "pile_set_name": "StackExchange" }
Q: Statically link firebird driver for dbexpress Is it possible to deploy zero-dll executable that connects to Firebird using dbExprss? If so, how? Cause I've tried to include DBXFirebird but the executable always needs dbxfb.dll. Thank you all. A: Up to Delphi 2006, you can link the dbExpress driver DLLs into your application by including the appropriate unit. Since Delphi 2007, this is no longer the case, and you have to ship the driver DLL.
{ "pile_set_name": "StackExchange" }
Q: Redis pub/sub for single receivers I am a RabbitMQ user exploring Redis and have two questions regarding the pub/sub mechanism Can I publish messages to the system where each client (consumer) removes the entry for other clients? I want to publish 100 tasks but each tasks should be processed only by 1-single subscriber. AFAIK, by default all messages are always broadcasted/published to all clients. What if one client takes 1 second to process the message, and another takes a minute. What would be the limits here? Would be some messages dropped at some point? Thanks a lot! A: 1) That's not how pub/sub works. Publish doesn't care or know about being received, it just publishes a message. Every subscriber that is subscribed will receive it and you can't stop this 2) That's up to you to handle client logic. From the sounds of it, redis pub/sub might not be the system/pattern you're looking for. You should look into zeromq especially, push and pull sockets, which instead of publishing messages, push messages to specific sockets one time. If you read through the starter documentation many patterns are explained and something will work for your specific case.
{ "pile_set_name": "StackExchange" }