qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
97,780
The timing is random and varies from 10 minutes to 2 hours between "phantom touches" on the touch buttons on refrigerator panel. The touches activate the functions, like turning on the dispenser light or trying to set an alarm. We had a similar thing happen previously with an electric cooker with a touch panel - but it stopped when we didn't run an exercise machine on the same circuit - but we've gotten rid of the exercise machine and the "phantom" touches are now happening on the refrigerator. Do we have a serious problem here? Thanks!
2016/08/20
[ "https://diy.stackexchange.com/questions/97780", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/6321/" ]
You live in a large complex. This just made the probability that someone else in the facility has a fridge or some other device that is cycling every 10 minutes to 2 hours causing spikes on the line and your phantom problems. You might try a [surge arrest outlet](http://www.homedepot.com/p/CE-TECH-1-Gang-Duplex-Surge-Protector-Outlet-5580/204294364) and see if this helps. A cheap plug in one may be a better first try.
I just wanted to post the apparent solution to this problem: We noticed that there was a faint buzzing sound coming from the circuit breaker box in the apartment. The buzzing got louder and the fridge started having phantom button inputs when we jiggled one of the [plug in circuit breakers](https://2ecffd01e1ab3e9383f0-07db7b9624bbdf022e3b5395236d5cf8.ssl.cf4.rackcdn.com/Product-800x800/2a6b2f46-26f4-4af3-93c4-fffddb293f5d.jpg) which we had used in place of the old ceramic circuit breakers. When we put the old ceramic circuit breaker back in the buzzing stopped, and the fridge has been fine since. Does this mean that we've solved the problem, or could it indicate a serious issue with our circuit breaker panel?
37,953
How to do this with regular expression? ``` Old -> New http://www.example.com/1.html -> http://www.example.com/dir/1.html http://www.example.com/2.html -> http://www.example.com/dir/2.html http://www.example.com/3.asp -> http://www.example.com/dir/3.html http://www.example.com/4.asp -> http://www.example.com/dir/4.html http://www.example.com/4_a.html -> http://www.example.com/dir/sub/4-a.html http://www.example.com/4_b.html -> http://www.example.com/dir/sub/4-b.html ``` I've tried this: ``` Redirect 301 /1.html http://www.example.com/dir/1.html Redirect 301 /2.html http://www.example.com/dir/2.html Redirect 301 /3.asp http://www.example.com/dir/3.html Redirect 301 /4.asp http://www.example.com/dir/4.html Redirect 301 /4_a.html http://www.example.com/dir/sub/4-a.html Redirect 301 /4_b.html http://www.example.com/dir/sub/4-b.html ```
2012/11/17
[ "https://webmasters.stackexchange.com/questions/37953", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/10452/" ]
This is a rather more general solution, so in that respect it might not be what you are after, but it should redirect the URLs in your question. ``` RewriteEngine on RewriteRule ^(\d)\.(html|asp)$ /dir/$1.html [R=301,L] RewriteRule ^(\d)_([a-z])\.html$ /dir/sub/$1-$2.html [R=301,L] ``` The first `RewriteRule` will match any single digit URL eg. `1.html` or `7.asp` and redirect to `/dir/1.html` or `/dir/7.html` respectively. The `$1` backreference matches the first parenthesised sub pattern in the pattern that is matched. The second `RewriteRule` matches a URL that contains a single digit followed by an underscore and then a single lowercase letter. The underscore is replaced with a hyphen in the redirect. eg. `6_g.html` is redirected to `/dir/sub/6-g.html`. --- ### Alternative (more restrictive) version If a more restrictive version is required that only matches the specific URLs stated in the question then you could do something like the following instead. Although it is arguably more "complex"... ``` RewriteRule ^([12])\.html|([34])\.asp$ /dir/$1$2.html [R=301,L] RewriteRule ^(4)_([ab])\.html$ /dir/sub/$1-$2.html [R=301,L] ``` The first rule would perhaps be easier to read if it was split into two. The two backreferences `$1` and `$2` in the first rule are mutually exclusive, when one is set, the other is empty, hence the presence of both in the *substitution* string. If you are not already using mod\_rewrite elsewhere in your `.htaccess` then mod\_alias `RedirectMatch` directives may be preferable, although this does make the regex marginally more complex because of the slash prefix that needs to be matched... ``` RedirectMatch 301 ^/(?:([12])\.html|([34])\.asp)$ /dir/$1$2.html RedirectMatch 301 ^/(4)_([ab])\.html$ /dir/sub/$1-$2.html ```
``` RewriteEngine on RewriteCond %{HTTP_HOST} ^example\.com$ [OR] RewriteCond %{HTTP_HOST} ^www\.example\.com$ RewriteRule ^1\.html$ "http\:\/\/example\.com\/dir\/1\.html" [R=301,L] RewriteCond %{HTTP_HOST} ^example\.com$ [OR] RewriteCond %{HTTP_HOST} ^www\.example\.com$ RewriteRule ^1_a\.html$ "http\:\/\/example\.com\/dir\/sub\/1\-a\.html" [R=301,L] RewriteOptions inherit ``` That should work
40,000
In a major scale, I know the chords to be: major, minor, minor, major, major, minor and diminished. What are the chords for the chromatic scale...using the C-major scale as reference...?! What I mean is, in the C-major scale as example we have C-major, D-minor, E-minor, F-major, G-major, A-minor and B-diminished, in that order using only the triads. What about the other notes like the C#, D#, etc...that makes up the chromatic scale...are they major, minor or diminished chords...?!
2015/12/05
[ "https://music.stackexchange.com/questions/40000", "https://music.stackexchange.com", "https://music.stackexchange.com/users/20606/" ]
The chords could be anything. In the C chromatic scale, for the I chord we can have: C major: C,E,G C minor: C,Eb,G C augmented: C,E,G# C half diminished: C,Eb,Gb,Bb C diminished: C,Eb,Gb,A All of the above can be used in the chromatic scale, because all of the above notes belong in the chromatic scale. The same goes for the 11 other notes in the scale.
For me the only way to make sense of your question is to interpret it as "which chords outside the key are frequently added to a piece in major?". Because otherwise the obvious answer is that if you allow any note, any chord could be added. In a major key, it is quite common to add chords from the parallel minor key. The concept of using chords from a parallel tonality is called [modal interchange](https://en.wikipedia.org/wiki/Borrowed_chord). The parallel minor key will give you chords with roots on all chromatic notes except for the b2 (the Db in the key of C) and the #4/b5 (F#/Gb). A chord with the b2 as a root can be borrowed from phrygian. If you combine the chords from the parallel (natural) minor scale and from phrygian, you get these additional triads in the key of C: `Db major | Eb major | Ab major | Bb major` Apart from these chords with root notes which are not part of the C major scale, you can also use chords with roots from the scale, but with other chord tones outside the scale. These other chord tones can also be borrowed from the parallel minor key, and the most frequently used chords are (again in C): `D diminished | F minor | G minor` Yet another source of chords from outside the major scale are [secondary dominants](https://en.wikipedia.org/wiki/Secondary_dominant) (and their related II chords), resolving to diatonic chords: `A7 => Dm | [F#m7(b5) B7] => Em | [Gm7 C7] => F | D7 => G | E7 => Am` where the arrow => means 'resolves to'. See also [this answer](https://music.stackexchange.com/questions/24814/what-kind-of-chord-progressions-am-i-using/24815#24815) to a related question.
7,013,877
> > **Possible Duplicate:** > > [Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) > > > how can I create form a list e.g [[1,2],[3,4]] or [(1,2),(3,4)] the list [1,2,3,4] list comprehension(or map, filter)doesn't seems to have map object to more than one other object. like SelectMany in C#'s LINQ
2011/08/10
[ "https://Stackoverflow.com/questions/7013877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331715/" ]
Standard libs are cool: ``` >>> import itertools >>> l = [[1,2],[3,4]] >>> list(itertools.chain(*l)) [1, 2, 3, 4] ```
You want to flatten the list. ``` [y for x in [[1,2],[3,4]] for y in x] ```
50,982,205
**Action:** Initially my app use to work as expected but after Moving react native app created on desktop to a different folder i am getting below error **Error:** Runtime is not ready for debugging on simulator while running app from vscode using command `react-native run-ios` **Tried:** `npm start` as well
2018/06/22
[ "https://Stackoverflow.com/questions/50982205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9971368/" ]
You can try deleting your android, ios and node modules folder and run the following ``` 1.> npm install // to get dependecies loaded 2.> react-native upgrade // to create ios and android folder 3.> react-native link // to link the libraries 4.> react-native run-android (or) > react-native run-ios ``` For react-native version 0.60 or more ``` 1.> npm install // to get dependecies loaded 2.> react-native upgrade --legacy // to create ios and android folder 3.> react-native link // to link the libraries 4.> react-native run-android (or) > react-native run-ios ```
Possible dupe of [Moving Create React App folder breaks working app](https://stackoverflow.com/questions/45576822) --- In case above didn't help, **deleting the ios/build folder** and running again worked for me. i.e. from your new root folder ``` rm -r ios/build npx react-native run-ios ``` Per answer in <https://github.com/facebook/react-native/issues/18793>
21,095,055
I am new to coding and and trying to learn as I go. I'm trying to create a python script that will grab and print all HEADERS from a list of urls in a txt file. It seems to be getting there but im stuck in an infinite loop with one of the urls and I have no idea why and for some reason the "-h", or "--help" wont return the `usage()`. Any help would be appreciated. Below is what I have so far: ``` #!/usr/bin/python import pycurl import cStringIO import sys, getopt buf = cStringIO.StringIO() c = pycurl.Curl() def usage(): print "-h --help, -i --urlist, -o --proxy" sys.exit() def main(argv): iurlist = None proxy = None try: opts, args = getopt.getopt(argv,"hi:o:t",["help", "iurlist=","proxy="]) if not opts: print "No options supplied" print "Type -h for help" sys.exit() except getopt.GetoptError as err: print str(err) usage() sys.exit(2) for opt, arg in opts: if opt == ("-h", "--help"): usage() sys.exit() elif opt in ("-i", "--iurlist"): iurlist = arg elif opt in ("-o", "--proxy"): proxy = arg else: assert False, "Unhandeled option" with open(iurlist) as f: iurlist = f.readlines() print iurlist try: for i in iurlist: c.setopt(c.URL, i) c.setopt(c.PROXY, proxy) c.setopt(c.HEADER, 1) c.setopt(c.FOLLOWLOCATION, 1) c.setopt(c.MAXREDIRS, 30) c.setopt(c.USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0') c.setopt(c.TIMEOUT, 8) c.setopt(c.CONNECTTIMEOUT, 5) c.setopt(c.NOBODY, 1) c.setopt(c.PROXY, proxy) c.setopt(c.WRITEFUNCTION, buf.write) c.setopt(c.SSL_VERIFYPEER, 0) c.perform() print buf.getvalue() buf.close except pycurl.error, error: errno, errstr = error print 'An error has occurred: ', errstr if __name__ == "__main__": main(sys.argv[1:]) ``` **This is the latest code:** ``` #!/usr/bin/python import pycurl import cStringIO import sys, getopt c = pycurl.Curl() def usage(): print "-h --help, -i --urlist, -o --proxy" print "Example Usage: cURLdect.py -i urlist.txt -o http://192.168.1.64:8080" sys.exit() def main(argv): iurlist = None proxy = None try: opts, args = getopt.getopt(argv,"hi:o:t",["help", "iurlist=","proxy="]) if not opts: print "No options supplied" print "Type -h for help" sys.exit() except getopt.GetoptError as err: print str(err) usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-i", "--iurlist"): iurlist = arg elif opt in ("-o", "--proxy"): proxy = arg else: assert False, "Unhandeled option" with open(iurlist) as f: iurlist = f.readlines() print iurlist try: for i in iurlist: buf = cStringIO.StringIO() c.setopt(c.WRITEFUNCTION, buf.write) c.setopt(c.PROXY, proxy) c.setopt(c.HEADER, 1) c.setopt(c.FOLLOWLOCATION, 1) c.setopt(c.MAXREDIRS, 300) c.setopt(c.USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0') c.setopt(c.TIMEOUT, 8) c.setopt(c.CONNECTTIMEOUT, 5) c.setopt(c.NOBODY, 1) c.setopt(c.SSL_VERIFYPEER, 0) c.setopt(c.URL, i) c.perform() print buf.getvalue() buf.close() except pycurl.error, error: errno, errstr = error print 'An error has occurred: ', errstr if __name__ == "__main__": main(sys.argv[1:]) ```
2014/01/13
[ "https://Stackoverflow.com/questions/21095055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3190677/" ]
This [page on github](https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories) has the answer you need. You have to switch to ssh authentication from https. Check how it is authenticating as follows. ``` $ git remote -v > origin https://github.com/USERNAME/REPOSITORY.git (fetch) > origin https://github.com/USERNAME/REPOSITORY.git (push) ``` Change your remote's URL from HTTPS to SSH with the git remote set-url command. ``` $ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git ``` Test it again with ``` $ git remote -v # Verify new remote URL > origin git@github.com:USERNAME/REPOSITORY.git (fetch) > origin git@github.com:USERNAME/REPOSITORY.git (push) ``` That's all. It will work now.
If you used for your GIT the password authentication before, but now are using SSH authentication, you need to [switch remote URLs from HTTPS to SSH](https://docs.github.com/en/github/using-git/changing-a-remotes-url#switching-remote-urls-from-https-to-ssh): ```sh git remote set-url origin git@github.com:USERNAME/REPOSITORY.git ```
625,262
I am trying to programmatically access a Windows application app.config file. In particular, I am trying to access the "system.net/mailSettings" The following code ``` Configuration config = ConfigurationManager.OpenExeConfiguration(configFileName); MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup(@"system.net/mailSettings"); Console.WriteLine(settings.Smtp.DeliveryMethod.ToString()); Console.WriteLine("host: " + settings.Smtp.Network.Host + ""); Console.WriteLine("port: " + settings.Smtp.Network.Port + ""); Console.WriteLine("Username: " + settings.Smtp.Network.UserName + ""); Console.WriteLine("Password: " + settings.Smtp.Network.Password + ""); Console.WriteLine("from: " + settings.Smtp.From + ""); ``` fails to give the host, from. it only gets the port number. The rest are null;
2009/03/09
[ "https://Stackoverflow.com/questions/625262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This seems to work ok for me: ``` MailSettingsSectionGroup mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; if (mailSettings != null) { string smtpServer = mailSettings.Smtp.Network.Host; } ``` Here's my app.config file: ``` <configuration> <system.net> <mailSettings> <smtp> <network host="mail.mydomain.com" /> </smtp> </mailSettings> </system.net> </configuration> ``` However, as stated by Nathan, you can use the application or machine configuration files to specify default host, port, and credentials values for all [SmtpClient](http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx) objects. For more information, see [<mailSettings> Element](http://msdn.microsoft.com/en-us/library/w355a94k.aspx) on MDSN.
``` private void button1_Click(object sender, EventArgs e) { try { var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; MailMessage msg = new MailMessage(); msg.Subject = "Hi Raju"; msg.To.Add("raju@hasten.in"); msg.From = new MailAddress("hasten.c@hasten.in"); msg.Body = "Hello Raju here everything is fine."; //MailSettingsSectionGroup msetting = null; string mMailHost = mailSettings.Smtp.Network.Host; SmtpClient mailClient = new SmtpClient(mMailHost); mailClient.Send(msg); MessageBox.Show("Mail Sent Succesfully..."); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } ```
29,996,337
I just installed Kony Studio . I am trying to run the HelloWorld app on the Android emulator, always gives me this error: ``` Failure rm failed for /sdcard/profiler_com.kony.HelloWorld.txt, Read-only file system Installing kony application 353 KB/s (3438511 bytes in 9.504s) pkg: /data/local/tmp/luavmandroid.apk Failure [INSTALL_FAILED_OLDER_SDK] rm failed for -f, Read-only file system Starting kony application Starting: Intent { act=android.intent.action.MAIN cmp=com.kony.HelloWorld/.Hello World } Error type 3 Error: Activity class {com.kony.HelloWorld/com.kony.HelloWorld.HelloWorld} does not exist ``` I have tried creating a new project, but didn't work.
2015/05/01
[ "https://Stackoverflow.com/questions/29996337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3518682/" ]
It is because `INSTALL_FAILED_OLDER_SDK`, You should set the minimum Android SDK API lower that your device in the project properties > Native > Android > SDK versions > Minimum
If you want to extend support to older version android OS, you need to set the > > Project Settings -> Native Tab -> Android -> SDK versions -> Minimum: to lower version > > > [![Screenshot](https://i.stack.imgur.com/zeJPT.png)](https://i.stack.imgur.com/zeJPT.png) attached. Hope this helps.
212,404
I have several files that all contain a string. This string needs to be replaced by the whole content of another file (that can possibly be multi-line). How can I do this? What I need is something like `sed -i 's/string/filename/' *` where `filename` is an actual file and not the string "filename". Additional info: The file can contain special characters such as `/` or `\` or `|` or `[` or `]`.
2015/06/26
[ "https://unix.stackexchange.com/questions/212404", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/50666/" ]
bash works well for this: ``` $ cat replace foo/bar\baz the second line $ cat file the replacement string goes >>here<< $ repl=$(<replace) $ str="here" $ while IFS= read -r line; do echo "${line//$str/$repl}" done < file ``` ``` the replacement string goes >>foo/bar\baz the second line<< ``` Awk would work, except that it will interpret backslash escapes (the `\b` in my example) ``` $ awk -v string="here" -v replacement="$(<replace)" ' {gsub(string, replacement); print} ' file the replacement string goes >>foo/baaz the second line<< ```
I got this to work: ``` $ foo='baz' $ echo "foobarbaz" | sed "s/foo/${foo}/" bazbarbaz ``` Taking that one step further, your first line would be something like: ``` $ foo=`cat filename` ``` This assumes you know the filename before you reach the line to be replaced, of course - if you don't, you have to read the line, get the filename, then do the read-and-replace.
988,473
I know that BIOS loads its first instruction from 0xFFFFFFF0, but why this specific address? I've a bunch of questions and hope you can help me with some of them, at least. **My questions:** * Why is the first BIOS instruction located at the "top" of a 4 GB RAM? * What would happen if my computer only has 1 GB of RAM? * What about systems with more than 4 GB of RAM (for example, 8 GB, 16 GB, etc.)? * Why is the stack initialized with some value (in this case, a value located at 0xFFFFFFF0)? I've read about that this afternoon, and I still don't get it.
2015/10/18
[ "https://superuser.com/questions/988473", "https://superuser.com", "https://superuser.com/users/411490/" ]
First, this has nothing to do with RAM, really. We're talking about *address space* here - even if you only have 16 MiB of memory, you still have the full 32 bits of address space on a 32-bit CPU. This already answers your first question, really - at the time this was designed, real world PCs had nowhere near the full 4 GiB of memory; they were more in the range of 1-16 MiB of memory. The address space was, for all intents and purposes, free. Now, why 0xFFFFFFF0 exactly? The CPU doesn't know how much of the BIOS there is. Some BIOSes may only take a few kilobytes, while others may take full megabytes of memory - and I'm not even getting into the various optional RAMs. The CPU must be hardwired to some address to start on - there's noöne to configure the CPU. But this is only a mapping of the address space - the address is mapped directly into the BIOS ROM chip (yes, this means you don't get access to the full 4 GiB of RAM at this point if you do have that many - but that isn't anything special, many devices require their own range in address space). On a 32-bit CPU, this address gives you full 16 bytes to do the very basic initialization - which is enough to setup your segments and, if needed, address mode (remember, x86 boots in 16-bit real mode - the address space isn't flat) and do a jump to the *real* boot "procedure". At this point, you don't use RAM at all - it's all just mapped ROM. In fact, RAM isn't even ready to be used at this point - that's one of the jobs of the BIOS POST! Now, you might be thinking - how does a 16-bit real mode access the address 0xFFFFFFF0? Sure, there's segments, so you have 20-bit address space, but that still isn't good enough. Well, there's a trick to it - the 12 high bits of the address are set until you execute your first long jump, giving you access to the high address space (while rejecting access to anything lower than 0xFFF00000 - until you execute a long jump). All this are the things that are mostly hidden from programmers (not to mention users) on modern operating systems. You usually don't have any access to anything so low level - some things are already beyond salvage (you can't switch CPU modes willy-nilly), some are exclusively handled by the OS kernel. So a nicer view comes from old-school coding on MS DOS. Another typical example of device memory being directly mapped to address space is direct access to video memory. For example, if you wanted to write text to the display fast, you wrote directly to address `B800:0000` (plus offset - in 80x25 text mode, this meant `(y * 80 + x) * 2` if my memory serves me right - two bytes per character, line by line). If you wanted to draw pixel-by-pixel, you used a graphics mode and the start address of `A000:0000` (typically, 320x200 at 8 bits per pixel). Doing anything high-performance usually meant diving into device manuals, to figure out how to access them directly. This survives to this day - it's just hidden. On Windows, you can see the memory addresses mapped to devices in the Device manager - just open properties of something like your network card, go to the Resources tab - all the Memory Range items are mappings from device memory to your main address space. And on 32-bit, you'll see that most of those devices are mapped above the 2 GiB (later 3 GiB) mark - again, to minimize conflicts with user-useable memory, though this is not really an issue with virtual memory (applications don't get anywhere near the *real, hardware* address space - they have their own virtualized chunk of memory, which might be mapped to RAM, ROM, devices or the page file, for example). As for the stack, well, it should help to understand that by default, stack grows from the top. So if you do a `push`, the new stack pointer will be at `0xFFFFFEC` - in other words, you're not trying to write to the BIOS init address :) Which of course means that the BIOS init routines can use the stack safely, before remapping it somewhere more useful. In old-school programming, before paging became the de facto default, the stack usually started on the end of RAM, and "stack overflow" happened when you started overwriting your application memory. Memory protection changed a lot of this, but in general, it maintains backwards compatibility as much as possible - note how even the most modern x86-64 CPU can *still boot MS DOS 5* - or how Windows can still run many DOS applications that have no idea about paging.
upon RESET an 8088/8086 compatible cpu executes the instructions at 0FFFF0, which is 16 bytes below the 1 megabyte limit. normally the ROM at this location (in PC implementations) would be the BIOS, so at the end of the BIOS ROM, there is a jump to the start of the BIOS rom. shown here: start vector and 'date' signature behind it, IBM 5150 PC 8KB eprom dump bios date: 10/19/1981 ``` 00001FEE FF db 0xff 00001FEF FF db 0xff 00001FF0 EA5BE000F0 jmp word 0xf000:0xe05b 00001FF5 3130 xor [bx+si],si 00001FF7 2F das 00001FF8 3139 xor [bx+di],di ``` note that the addressing are of an 8KB $2000 rom, which places the start address (the absolute far JMP, to whichever other location, in this case within the 8KB rom itself, although not the lowest possible address within that rom) at $FFFF:$0 segmented or $FFFF0 linear. as for compatibility: if some 'future' or current processor 'expects' it to have a whole lot more F's in front of the address, that doesn't matter. for compatibility of newer cpus in older systems the additional address lines remain unconnected and therefore the data on the databus is exactly the same. as long as the least significant bits remain FFFF0. (in a system with just 1mb ram and the rom positioned in the end of that ram, and nothing else, it'll happily 'think' it's talking to the higher address yet get the exact same data, because those implementations have never heard of address lines higher than A19) take note that the world is not just 'pcs'... the ibm pc was an 'accident', these processors were never specifically designed for 'pcs' and go into a whole lot of more things than just pcs (such as satellites, weapons sytems, etc). 32 and 64bit protected mode are usually -not- desired. (virtual 8086 mode is a lot more interesting as a reason to pick a newer (386+) version for example). therefore there is a lot more to 'backwards compatibility' than just 'will it run dos'.
66,865,881
I am trying to creating a carousel card slider , its working, but when I view it on mobile or tablet mode its not working , I mean cards are overlapping to each other, I want to display responsive card when I view on mobile or tablet mode, please tell me media query for my js file if you have any question please free feel to ask > > card.js > > > This is the card.js file where I design my card ``` import React from 'react' import './Card.css'; const Card = ({title,names,description,images}) => { return ( <div > <div class="card h-200" style={{ width: '20rem'}}> <img class="card-img-top" src={images} alt="Card image cap" /> <div class="card-body"> <h5 class="card-title">{title}</h5> <p class="card-text">{description}</p> <a href="#">{names} <i class="fal fa-chevron-right"></i></a> </div> </div> </div> ) } export default Card; ``` > > card.css > > > This is the card.css file where i wrote some css ``` .card-body{ margin-top: 20px; } .card{ padding: 15px; border-radius: 1px 15px 15px 15px; } .card-img-top { width: 100%; height: 15vw; object-fit: cover; } .card { margin: 0 auto; /* Added */ float: none; /* Added */ margin-bottom: 10px; /* Added */ } ``` > > cards.js > > > This is the cards.js file where i import my card file ``` import React from 'react'; import './Cards.css'; import Card from './Card'; import { Swiper, SwiperSlide } from 'swiper/react'; import SwiperCore, { Navigation, Pagination, Scrollbar, A11y } from 'swiper'; // Import Swiper styles import 'swiper/swiper.scss'; import 'swiper/components/navigation/navigation.scss'; import 'swiper/components/pagination/pagination.scss'; import 'swiper/components/scrollbar/scrollbar.scss'; SwiperCore.use([Navigation, Pagination, Scrollbar, A11y]); var swiper = new Swiper('.swiper', { slidesPerView: 4, spaceBetween: 50, }); var swiper = new Swiper('.swiper', { // Default parameters slidesPerView: 4, spaceBetween: 50, // Responsive breakpoints breakpoints: { // when window width is <= 499px 499: { slidesPerView: 1, spaceBetweenSlides: 50 }, // when window width is <= 999px 999: { slidesPerView: 2, spaceBetweenSlides: 50 } } }); const Cards = () => { return ( <Swiper spaceBetween={50} slidesPerView={4} navigation pagination={{ clickable: true }} scrollbar={{ draggable: true }} onSlideChange={() => console.log('slide change')} onSwiper={(swiper) => console.log(swiper)} > <SwiperSlide className="cards1"><Card images="https://mspoweruser.com/wp-content/uploads/2019/02/Skype-Mobile-call-experience.jpg" description="Meet Now is now available in Windows 10 taskbar so you can meet with a simple click." names="Learn more " title="Meet Now, Right Now " /></SwiperSlide> <SwiperSlide className="cards1"><Card images="https://www.microsoft.com/en-us/microsoft-365/blog/wp-content/uploads/2014/12/Skye-Lync-video.png" description="Experience HD one to one or group video calling—now with call reactions." title="Video calling for 100 people " names="Explore video calls"/></SwiperSlide> <SwiperSlide className="cards1"><Card images="https://img.dtcn.com/image/digitaltrends/skype-50-people-1200x772.jpg" description="Call landlines and mobiles from anywhere in the world at great low rates using Skype." names="See our rates" title="Use Skype to call phones "/></SwiperSlide> <SwiperSlide className="cards1"><Card images="https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2014/11/unnamed3-730x456.png" description="Read the words that are spoken during an audio or video call." names="How to set subtitles" title="Live subtitles "/></SwiperSlide> <SwiperSlide className="cards1"><Card images="https://mspoweruser.com/wp-content/uploads/2019/02/Skype-Mobile-call-experience.jpg" description="Meet Now is now available in Windows 10 taskbar so you can meet with a simple click." names="Learn more " title="Meet Now, Right Now " /></SwiperSlide> <SwiperSlide className="cards1"><Card images="https://www.microsoft.com/en-us/microsoft-365/blog/wp-content/uploads/2014/12/Skye-Lync-video.png" description="Experience HD one to one or group video calling—now with call reactions." title="Video calling for 100 people " names="Explore video calls"/></SwiperSlide> <SwiperSlide className="cards1"><Card images="https://img.dtcn.com/image/digitaltrends/skype-50-people-1200x772.jpg" description="Call landlines and mobiles from anywhere in the world at great low rates using Skype." names="See our rates" title="Use Skype to call phones "/></SwiperSlide> <SwiperSlide className="cards1"><Card images="https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2014/11/unnamed3-730x456.png" description="Read the words that are spoken during an audio or video call." names="How to set subtitles" title="Live subtitles "/></SwiperSlide> </Swiper> ); }; export default Cards; ```
2021/03/30
[ "https://Stackoverflow.com/questions/66865881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14772642/" ]
You can create a UDF to do the job: ```sql create or replace function isoweek_to_date(s string) returns date as $$ select DATEADD( DAY, WEEK * 7 - CASE WHEN DAYOFWEEKISO(DATE_FROM_PARTS(YEAR, 1, 1)) < 5 THEN 7 ELSE 0 END + 1 - DAYOFWEEKISO(DATE_FROM_PARTS(YEAR, 1, 1)), DATE_FROM_PARTS(YEAR, 1, 1) ) from (select regexp_substr(s, '[0-9]+', 1, 1) year, regexp_substr(s, '[0-9]+', 1, 2) week) $$ ; select isoweek_to_date('2021|13') // 2021-03-29 ; ``` Code taken from Hans' <https://stackoverflow.com/a/58298264/132438>.
I think the following is what you're looking for. Looks similar to Felipe/Hans' solution. It adds 12 weeks onto 2021-01-01, gets the last day of that week with `last_day` and then adds 1 to get the first day of week 13. ```sql select '2021|13' str_dt, dateadd('day', 1, last_day(dateadd('WEEK', SPLIT(str_dt, '|')[1]::int - 1, SPLIT(str_dt, '|')[0] || '-01-01'), 'week')) ```
84,856
What are the best practices in designing a 404 error page? I read so many blogs and articles regarding this. Some says about using fancy images , when some days about sticking to the basics. Are there any guidelines regarding this? What are the best practices? Which of the following details are wrong or to be followed? **Redirection** * To home page * To search page * To site map * Automatic redirection?? **Error message** * Should we explicitly state `404 Page not found` * Some other fancy user friendly messages **Images to be used** * Image relevant to the error * Image matching the type of website **Other page elements** * Should the common elements in websites like Navigation , footer etc be included? * Contrasting colour theme or same theme as that of website? Any useful guidance is appreciated **Edit:** **Whom to put the blame on?** In the error message should we specify that `the page you typed not exist` (putting the blame on the user) or some other messages taking the blame on ourselves even if the reason might be a wrong url ?
2015/09/22
[ "https://ux.stackexchange.com/questions/84856", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/73591/" ]
I'm not saying it's perfect, but we launched a new 404 page this year and we included options asking people to give us feedback when they find a broken link. Consequently we get a few emails a week which are helping us tidy up our site and fix problems. We also included an obvious search box to try and help people find what they were looking for. We're revamping our sitemap but once that's done we'll link to it again from here. I do like the Brett Terpstra solution (suggesting what page you might have been after), but I think that would have been hard for us to code, based on our CMS... <http://lawsociety.org.uk/broken-link/> [![enter image description here](https://i.stack.imgur.com/6WSGt.png)](https://i.stack.imgur.com/6WSGt.png)
I like the idea of combining humor with a 404 redirect. I am thinking of displaying our latest blogs below the message to make for engaging copy. Our current 404 page looks really bad and has a high bounce rate- <http://www.sevenatoms.com/article_writing_services.shtml>
12,407,549
I'm trying to define a custom `post` action in a controller, but I'm having some questions. This is my controller: ``` module Api module V1 class ExamplesController < ApplicationController def create_a ... end def create_b ... end end end end ``` I want both actions/methods to be `post` actions. This is what I have in my routes file: ``` namespace :api do namespace :v1 do match 'examples/create_a', :controller => 'examples', :action => 'create_a' match 'examples/create_b', :controller => 'examples', :action => 'create_b' end end ``` I can reach these two methods via `ge`t requests, but I'd like to trigger them based on an http `post`. Also, if I check via `rake routes` it does not tell me if it's a GET, PUT, POST, etc. method. It's just blank. How do I tell a route that it's supposed to be a `post` method? And how would a `post` request in the browser look like to my method? ``` url: http://localhost:3000/api/v1/examples/create_a.json/create_a header: Content-Type: application/x-www-form-urlencoded data: paramA=45&paramB&paramC ``` Is this the proper URL pattern to do a `post` to my controller action `create_a`?
2012/09/13
[ "https://Stackoverflow.com/questions/12407549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595257/" ]
yeah there is definately a bug of some sort, with the optimization. But this works ``` @mixin leftarrow($size:5px, $direction:left) { border-width: $size; border-color: transparent; border-style: solid; display: inline-block; height: 0px; width: 0px; @if $direction == "right" { border-left-color: $navbgblue; border-right-width: 0px; } @else if $direction == "left" { border-right-color: $navbgblue; border-left-width: 0px; } @else if $direction == "up" { border-bottom-color: $navbgblue; border-top-width: 0px; } @else if $direction == "down" { border-top-color: $navbgblue; border-bottom-width: 0px; } } .test{ @include leftarrow(5px, up); } ``` so i'll use that :-)
First off, you don't want to quote your variables unless you want them to be treated as strings (strings get quoted in your CSS output). It's a really good idea to have your default value be as a part of an "else" instead of an "else if". Are you looking at the generated CSS or looking at it from within something like Firebug? Because if I copy/paste your mixin as is, I get this output: ``` .test { width: 0; height: 0; border-color: transparent; border-style: solid; border-top: "5pxpx"; border-bottom: "5pxpx"; border-right: "5pxpx" blue; } ``` Here's a refactored version of your mixin with all the quotes and the extra "px" removed: ``` @mixin arrows($arrowdirection: left, $arrowsize: 5px, $arrowcolor: green) { width: 0; height: 0; border-color: transparent; border-style: solid; @if $arrowdirection == right { border-top: $arrowsize; border-bottom: $arrowsize; border-left: $arrowsize $arrowcolor; } @else if $arrowdirection == up { border-bottom: $arrowsize $arrowcolor; border-left: $arrowsize; border-right: $arrowsize; } @else if $arrowdirection == down { border-left: $arrowsize; border-right: $arrowsize; border-top: $arrowsize $arrowcolor; } @else { border-top: $arrowsize; border-bottom: $arrowsize; border-right:$arrowsize $arrowcolor; } } .test { @include arrows; } .test2 { @include arrows(right, 10px, blue); } ``` I get the following output: ``` .test { width: 0; height: 0; border-color: transparent; border-style: solid; border-top: 5px; border-bottom: 5px; border-right: 5px green; } .test2 { width: 0; height: 0; border-color: transparent; border-style: solid; border-top: 10px; border-bottom: 10px; border-left: 10px blue; } ```
187,713
In C++, what's the generic way to convert any floating point value (float) to [**fixed point**](http://en.wikipedia.org/wiki/Fixed-point_arithmetic) (int, 16:16 or 24:8)? **EDIT:** For clarification, fixed-point values have two parts to them: an integer part and a fractional part. The integer part can be represented by a signed or unsigned integer data type. The fractional part is represented by an unsigned data integer data type. Let's make an analogy with money for the sake of clarity. The fractional part may represent cents -- a fractional part of a dollar. The range of the 'cents' data type would be 0 to 99. If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts. I hope that clears things up.
2008/10/09
[ "https://Stackoverflow.com/questions/187713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
This is fine for converting from floating point to integer, but the O.P. also wanted [fixed point](http://en.wikipedia.org/wiki/Fixed-point_arithmetic). Now how you'd do that in C++, I don't know (C++ not being something I can think in readily). Perhaps try a scaled-integer approach, i.e. use a 32 or 64 bit integer and programmatically allocate the last, say, 6 digits to what's on the right hand side of the decimal point.
There isn't any built in support in C++ for fixed point numbers. Your best bet would be to write a wrapper 'FixedInt' class that takes doubles and converts them. As for a generic method to convert... the int part is easy enough, just grab the integer part of the value and store it in the upper bits... decimal part would be something along the lines of: ``` for (int i = 1; i <= precision; i++) { if (decimal_part > 1.f/(float)(i + 1) { decimal_part -= 1.f/(float)(i + 1); fixint_value |= (1 << precision - i); } } ``` although this is likely to contain bugs still
10,912,693
I'm currently using the script ``` SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Tables'; ``` However, it's not accurate, because the engine used by my MySQL tables is InnoDB (I only realised this could be an issue now, be these databases have existed for a while). Is there any way to get an exact count of every row in every table of a database with MySQL? Cheers.
2012/06/06
[ "https://Stackoverflow.com/questions/10912693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563460/" ]
I was having the same problem which led me to this question. Thanks to computerGuy12345's answer, I came up with a stored procedure that does this without having to copy-paste. As he said, beware that this will scan each table and might take a while. ``` DELIMITER $$ CREATE PROCEDURE `all_tables_rowcount`(databaseName VARCHAR(250)) BEGIN DECLARE p_done INT DEFAULT FALSE; DECLARE p_queryString varchar(250) ; DECLARE p_cur CURSOR FOR SELECT queryString FROM tmp.tableCountQueries; DECLARE CONTINUE HANDLER FOR NOT FOUND SET p_done = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.tableCountQueries; DROP TEMPORARY TABLE IF EXISTS tmp.tableCounts; CREATE TEMPORARY TABLE tmp.tableCounts(TableName varchar(250), RowCount BIGINT) ; CREATE TEMPORARY TABLE tmp.tableCountQueries(queryString varchar(250)) AS ( SELECT CONCAT( 'INSERT INTO tmp.tableCounts(TableName, RowCount) SELECT "', table_name, '", COUNT(*) AS RowCount FROM ', table_schema, '.', table_name ) AS queryString FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = databaseName ) ; OPEN p_cur; read_loop: LOOP FETCH p_cur INTO p_queryString; IF p_done THEN LEAVE read_loop; END IF; SET @queryString = p_queryString ; PREPARE rowcountTable FROM @queryString; EXECUTE rowcountTable ; END LOOP; SELECT * FROM tmp.tableCounts ; END ```
`Select Sum(column_Name) from table` ,can not give the exact count of rows in a table , it wil give total row count+1 , wil give the next data inserting row also. and one more thing is, in `sum(Column_Name)` the column\_Name should be int ,if it is varchar or char sum function wont work. soo the best thing is use `Select Count(*) from table` to get exact number of rows in a table. ThnQ, Venkat
148,865
Your challenge is to compute the [Lambert W function](https://en.wikipedia.org/wiki/Lambert_W_function). \$W(x)\$ is defined to be the real value(s) \$y\$ such that $$y = W(x) \text{ if } x = ye^y$$ where \$e = 2.718281828...\$ is [Euler's number](https://en.wikipedia.org/wiki/E_(mathematical_constant)). Sometimes, \$y\$ may not be real. ### Examples ``` W(-1) = non-real W(-0.1) = -0.11183, -3.57715 W(1) = 0.56714 W(2) = 0.85261 ``` Here's a quick graph of what this function looks like. [![enter image description here](https://i.stack.imgur.com/DZzJS.png)](https://i.stack.imgur.com/DZzJS.png) --- ### Rules Your goal is to take an input and output either nothing, 1 solution, or 2 solutions, out to 5 significant figs. You should expect float inputs within the reasonable range of `-100..100`. This is code-golf, so shortest code wins.
2017/11/23
[ "https://codegolf.stackexchange.com/questions/148865", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/58880/" ]
Casio BASIC, 192 Bytes ====================== A port of [My 05AB1E answer](https://codegolf.stackexchange.com/a/203664/94333) ``` ?→X "" If X≥-e^-1 Then 0→R While Re^R<X Isz R WhileEnd -1→L While Re^R>X .5(L+R→M If Me^M<X Then M→L Else M→R IfEnd WhileEnd If X<0 Then M◢ While Le^L<X Dsz L WhileEnd While Le^L≠X .5(L+R→M If Me^M<X Then M→R Else M→L IfEnd WhileEnd If M≠-1 Then M ``` Note that indents are actually not supported; I added them for legibility.
[Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ================================================================================== ``` x/.NSolve[#==E^x x,x,Reals]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8b9CX88vOD@nLDVa2dbWNa5CoUKnQicoNTGnOFbtv6Y1V0BRZl6JQ1q0roGeYex/AA "Wolfram Language (Mathematica) – Try It Online") Returns `x` for no-solution. This function should give all solutions because `NSolve` algorithm uses inverse functions, and there is a built-in inverse function of `x = y*(e^y)` called `ProductLog`. ### Explanation ``` #==E^x x ``` Equation `<input> = e^x * x` ``` NSolve[ ... ,x,Reals] ``` Find solutions in the domain of real numbers. ``` x/. ``` Replace `x` with the solutions. ### Alternative version, 35 bytes ``` N@ProductLog[{-1,0},#]~Cases~_Real& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d/PIaAoP6U0ucQnPz26WtdQx6BWRzm2zjmxOLW4Lj4oNTFH7b@mNVdAUWZeiUNatK6BnmHsfwA "Wolfram Language (Mathematica) – Try It Online")
41,559,398
I'd like to write non-ASCII characters (`0xfe`, `0xed`, etc) to a program's standard input. There are a lot of similar questions to this one, but I didn't find an answer, because: * I want to write single-byte characters, not unicode characters * I can't pipe the output of `echo` or something On OS X¹ you can test with: ``` nm - - ``` I'd like to write object files magic bytes (e.g. `0xfeedface`) to `nm` using standard input so I can see how it does behave and I can recode it. If I use a pipe then the second argument `-`, which means *stdin*, will never match any bytes since all the standard input will go to the first one. When using a terminal instead of a pipe, I can type `Ctrl + D` so the first one gets 'closed' and the second one start reading. I tried with `Ctrl + Shift + U` and the Unicode Hex Input of OS X but it doesn't work -- I can't write the desired characters with it. I also tried with the clipboard with `pbcopy` but it fails to read/paste non-ASCII or non-unicode characters. How can I achieve my goal? *Don't hesitate to edit as this was a difficult question to express.* ¹ The `nm` on linux does not handle *stdin*.
2017/01/10
[ "https://Stackoverflow.com/questions/41559398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5405361/" ]
Try a util like `xxd`: ``` # echo hex 52 to pipe, convert it to binary, which goes to stdout echo 52 | xxd -r ; echo R ``` Or for a more specialized util try [`ascii2binary`](http://billposer.org/Software/a2b.html) (default input is decimal): ``` # echo dec 52 to pipe, convert it to binary, which goes to stdout echo 52 | ascii2binary ; echo 4 # echo base11 52 to pipe, convert it to binary, which goes to stdout echo 52 | ascii2binary -b 11 ; echo 9 ``` Or dump a series of hex chars, showing what `hexdump` sees: ``` echo 7 ef 52 ed 19 | ascii2binary -b h | \ hexdump -v -e '/1 "%_ad# "' -e '/1 " _%_u\_\n"' 0# _bel_ 1# _ef_ 2# _R_ 3# _ed_ 4# _em_ ``` See `man xxd ascii2binary` for the various tricks these utils can do.
Using bash, you can echo the input, ``` echo -e -n '\x61\x62\x63\x64' | /path/someFile.sh --nox11 ``` or use cat, which might be more comfortable when there are several lines of prompting: ``` cat $file | /path/someFile.sh --nox11 ``` You can omit the `--nox11`, but that might help when the script spawns a new instance of terminal Note: This will not work with `/bin/sh`!
13,777,395
I have set up a subview "popup" in my application and I want to show a navController if the user taps a button on the subview popup. I've set up the button so far, but if I tap the button the navigationController appears under my popup!? I've searched for some solution but I didn't found any. The whole controller is actually displayed in a folder which you can find here: <https://github.com/jwilling/JWFolders> So the viewDidLoad belong to the folder and the rootview. I tried to make it as a subview of the popup but that doesn't work too. Does anyone know how to treat that? I've set up the popup programmaticaly and the navigationController too. Thanks in advance. My code: The navController setup: ``` - (IBAction)dothis:(id)sender { MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self]; // Set browser options. browser.wantsFullScreenLayout = YES; browser.displayActionButton = YES; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:browser]; [self presentModalViewController:navController animated:YES]; NSMutableArray *photos = [[NSMutableArray alloc] init]; MWPhoto *photo; photo = [MWPhoto photoWithFilePath:[[NSBundle mainBundle] pathForResource:@"star" ofType:@"png"]]; photo.caption = @"The star is soo beateful..."; [photos addObject:photo]; self.photos = photos; } - (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index { if (index < _photos.count) return [_photos objectAtIndex:index]; return nil; } - (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser { return _photos.count; } ``` The popup code: ``` -(IBAction)mehr:(id)sender { //the popup size and content UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 440)]; CGRect welcomeLabelRect = contentView.bounds; welcomeLabelRect.origin.y = 20; welcomeLabelRect.size.height = 40; UILabel *welcomeLabel = [[UILabel alloc] initWithFrame:welcomeLabelRect]; //an simple activityindicator activityindi = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; activityindi.frame = CGRectMake(120, 200, 40, 40); [activityindi startAnimating]; [contentView addSubview:activityindi]; //The Imageview CGRect infoimagerect = CGRectMake(5, 70, 270, 200); UIImageView *infoimage = [[UIImageView alloc] initWithFrame:infoimagerect]; //and the Button cubut = [UIButton buttonWithType:UIButtonTypeCustom]; [cubut addTarget:self action:@selector(dothis:) forControlEvents:UIControlEventTouchUpInside]; [cubut setTitle:nil forState:UIControlStateNormal]; cubut.frame = CGRectMake(5, 70, 270, 200); //retrieving data from parse.com PFQuery *query = [PFQuery queryWithClassName:@"My-Application"]; [query getObjectInBackgroundWithId:@"My-ID" block:^(PFObject *textdu, NSError *error) { if (!error) { //hide the Button if there is no image cubut.hidden=YES; //the headline of popup UIFont *welcomeLabelFont = [UIFont fontWithName:@"copperplate" size:20]; welcomeLabel.text = [textdu objectForKey:@"header"]; welcomeLabel.font = welcomeLabelFont; welcomeLabel.textColor = [UIColor whiteColor]; welcomeLabel.textAlignment = NSTextAlignmentCenter; welcomeLabel.backgroundColor = [UIColor clearColor]; welcomeLabel.shadowColor = [UIColor blackColor]; welcomeLabel.shadowOffset = CGSizeMake(0, 1); welcomeLabel.lineBreakMode = UILineBreakModeWordWrap; welcomeLabel.numberOfLines = 2; [contentView addSubview:welcomeLabel]; //the image from parse if (!error) { PFFile *imageFile = [textdu objectForKey:@"image"]; [imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) { if (!error) { UIImage *image = [UIImage imageWithData:data]; infoimage.image = image; infoimage.contentMode = UIViewContentModeScaleAspectFit; //show the button when the image appears cubut.hidden = NO; [contentView addSubview:infoimage]; //stop the activityindicator [activityindi stopAnimating]; } }]; } } else { //show some text welcomeLabel.text = @"No connection!"; [welcomeLabel sizeToFit]; //hide the button cubut.hidden = YES; [contentView addSubview:infoLabel]; //stop the activityindicator [activityindi stopAnimating]; } }]; //add the content to the KNGModal view [[KGModal sharedInstance] showWithContentView:contentView andAnimated:YES]; } ``` My viewDidLoad ``` - (void)viewDidLoad { but.hidden = YES; PFQuery *query = [PFQuery queryWithClassName:@"myapp"]; [query getObjectInBackgroundWithId:@"Rgq5vankdf" block:^(PFObject *textu, NSError *error) { if (!error) { but.hidden = NO; but.color = [UIColor colorWithRed:0.90f green:0.90f blue:0.90f alpha:1.00f]; } else { //if failure but.hidden = YES; mol.text = @"No Connection"; } }]; [super viewDidLoad]; } ``` Pictures: The button to open the folder: ![enter image description here](https://i.stack.imgur.com/1kEDa.png) The folder itself: ![enter image description here](https://i.stack.imgur.com/Ko15l.png) The popup: ![enter image description here](https://i.stack.imgur.com/VHqVQ.png) Thanks in advance.
2012/12/08
[ "https://Stackoverflow.com/questions/13777395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1779239/" ]
From the so far discussion and debugging the code you want to have the photo browser on the pop-up with a navigation controller. So here is the [sample code](http://dl.dropbox.com/u/58723521/Shared/KGModal-master-with-nav-pop-up.zip) which implements this functionality, have a look at it. I have used the same `KGModal` sample code and extended as per the requirement. I have used Xib to have a view with navigation bar. To dismiss the pop-up from any where in the app you can use the below line, as it is shared instance. ``` [[KGModal sharedInstance] hideAnimated:YES]; ``` **Update:** The reason for showing the photo browser with in folderView is, you are trying to present the photoBrowser within the folderView, so it was presenting within the folderView of very small height & not able to see any photo. So my suggestion is, as the user taps on pop-up to view photoBrowser you just remove pop-up and present the photoBrowser from the viewController class, as other than this class everything is handled through views. I have made the changes as per above & works fine, to the code given by you, download the code [here](http://dl.dropbox.com/u/58723521/Shared/sampleOfModal.zip) and have a look at it. Let me know if it fulfills your needs. Thanks
I noticed this line of code: ``` [[KGModal sharedInstance] showWithContentView: contentView andAnimated: YES]; ``` And I can only think that, since it is a singleton, it adds the `contentView` on the UIApplication's key window. If that is the case, then a modal view controller will always be below the popup. You can solve this by adding a new method to the `KGModal` class ``` - (void) showWithContentView: (UIView*) contentView inViewController: (UIViewController*) controller andAnimated: (BOOL) animated; ``` the method should show the popup in the specified controller's view; you should use that method instead. **Edit** After some more digging, I found that `KGModal` displays the popup on another window. The quickest fix would be to dismiss the popup, then show the nav controller.
69,396,576
I have the same problem that was solved here, trying to create iptables rules that block incoming HTTP/HTTPS traffic except for IPs other than Cloudflare. [Docker container accessible only via Cloudflare CDN (selected ip ranges)](https://stackoverflow.com/questions/62821274/docker-container-accessible-only-via-cloudflare-cdn-selected-ip-ranges) This works great except for one problem. My docker services include an SPA (served by Nginx) and an app server. My Nginx configuration performs a proxy\_pass which is blocked by my iptables rules. When I don't have the rules, the proxy\_pass works. My nginx.conf: ``` location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; proxy_pass http://app:80; } ``` And my ip-tables for the DOCKER-USER chain: ``` Chain DOCKER-USER (1 references) target prot opt source destination ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED ACCEPT all -- !131.0.72.0/22 anywhere ACCEPT all -- !172.64.0.0/13 anywhere ACCEPT all -- !104.24.0.0/14 anywhere ACCEPT all -- !104.16.0.0/13 anywhere ACCEPT all -- !162.158.0.0/15 anywhere ACCEPT all -- !198.41.128.0/17 anywhere ACCEPT all -- !197.234.240.0/22 anywhere ACCEPT all -- !188.114.96.0/20 anywhere ACCEPT all -- !190.93.240.0/20 anywhere ACCEPT all -- !108.162.192.0/18 anywhere ACCEPT all -- !141.101.64.0/18 anywhere ACCEPT all -- !103.31.4.0/22 anywhere ACCEPT all -- !103.22.200.0/22 anywhere ACCEPT all -- !103.21.244.0/22 anywhere ACCEPT all -- !173.245.48.0/20 anywhere DROP tcp -- anywhere anywhere multiport dports http,https ``` I feel like I need just one more iptables rule to keep iptables from blocking the internal proxy traffic, but have not figured it out.
2021/09/30
[ "https://Stackoverflow.com/questions/69396576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16997888/" ]
I think the recommended way of binding properties to pojos is to use the `@EnableConfigurationProperties` annotation like so: **KafkaConfig.java** ``` @ConfigurationProperties("kafka") @Data public class KafkaConfig { private String topic; private String event; } ``` **KafkaProducerBeans.java** ``` @Component @EnableConfigurationProperties(KafkaConfig.class) public class KafkaProducerBeans { private final KafkaConfig kafkaConfig; @Autowired public KafkaProducerBeans(KafkaConfig kafkaConfig) { this.kafkaConfig = kafkaConfig; } // [...] } ``` Refer to the official Spring Documentation for further details: * <https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties.java-bean-binding> * <https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties.enabling-annotated-types>
Add one more annotation `@EnableConfigurationProperties` on the class `KafkaConfig` **KafkaConfig.java** ``` @Configuration @EnableConfigurationProperties // new added annotation @ConfigurationProperties("kafka") @Data public class KafkaConfig { private String topic; private String event; } ```
38,655,154
I have a root viewController(v1) and Second UIViewController(v2). v2 showing on button click and v2 have container(c1). My problem is when I called v2 then c1 also load at same time but I need to load c1 after executing v2 function completely. In v2 I am fetching value from database so its taking some time.
2016/07/29
[ "https://Stackoverflow.com/questions/38655154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4112505/" ]
You just have to right code in func viewDidAppear(animated: Bool) method in child container which get executed after parent complete his loading code ``` func viewDidAppear(animated: Bool) { // code } ```
Instead of stopping the container loading, add a delegate to your child controller which V2 will call once the V2 has completed its loading. ``` @protocol LoadingDelegate { func didFinishLoading() } class ViewController V2 { func viewDidLoad() { childController.delegate = self } func finishedProcessing() { // Finsihed processing delegate. didFinishLoading() } } class ChildController<LoadingDelegate> { func didFinishLoading() { // Do your stuff here } } ``` Till the time V2 is doing its loading you can show a activity indicator in child controller
2,663,122
``` ID- DATE- NAME 10100- 2010/04/17- Name1 10100- 2010/04/14- Name2 10200- 2010/04/17- Name3 10200- 2010/04/16- Name4 10200- 2010/04/15- Name5 10400- 2010/04/01- Name6 ``` I have this fields(and others too) in one table. I need to do a query which return the ID with your respective name where more recently date for example the results for desired query in that data example will be. ``` 10100- 2010/04/17- Name1 10200- 2010/04/17- Name3 10400- 2010/04/01- Name6 ``` Ommiting ID with older dates. Then I need one query for that. thanks.
2010/04/18
[ "https://Stackoverflow.com/questions/2663122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302745/" ]
You could even do it in constant O(1) time (although it would not be very fast or efficient): There is a limited amount of nodes your computer's memory can hold, say N records. If you traverse more than N records, then you have a loop.
Detecting a loop in a linked list can be done in one of the simplest ways, which results in O(N) complexity using hashmap or O(NlogN) using a sort based approach. As you traverse the list starting from head, create a sorted list of addresses. When you insert a new address, check if the address is already there in the sorted list, which takes O(logN) complexity.
1,690,906
Given that $\frac{dy}{dx}=e^{x-y}$ and $y=1$ when $x=0$ find the exact value of $y$ when $x=1$. After my attempts. I stuck in $$y=e^{1-y}+1-e^{-1}$$ How to proceed?
2016/03/10
[ "https://math.stackexchange.com/questions/1690906", "https://math.stackexchange.com", "https://math.stackexchange.com/users/221836/" ]
A start: Rewrite as $e^y\frac{dy}{dx}=e^x$. This is a separable equation. Integrate. We get $e^y=e^x+C$. Continue.
Your attempted solution is incorrect. Hint: the differential equation $\dfrac{dy}{dx} = e^{x-y}$ is separable.
128,305
How to tag images in the image itself in a web page? I know [Taggify](http://www.taggify.net/), but... is there other options? [Orkut](http://en.blog.orkut.com/2008/06/tag-thats-me.html) also does it to tag people faces... How is it done? Anyone knows any public framework that is able to do it? See a sample bellow from Taggify: ![alt text](https://i.stack.imgur.com/gT1zq.jpg "Taggify Sample\"")
2008/09/24
[ "https://Stackoverflow.com/questions/128305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
There's a map tag in HTML that could be used in conjunction with Javascript to 'tag' different parts of an image. You can see the details [here](http://www.w3schools.com/TAGS/tag_map.asp).
You can check out Image.InfoCards (IIC) at <http://www.imageinfocards.com> . With the IIC meta-data utilities you can add meta-data in very user-friendly groups called "cards". The supplied utilities (including a Java applet) allow you to tag GIF's, JPEG's and PNG's without changing them visually. IIC is presently proprietary but there are plans to make it an open protocol in Q1 2009. The difference between IIC and others like IPTC/DIG35/DublinCore/etc is that it is much more consumer-centric and doesn't require a CS degree to understand and use it...
12,135,704
I am using a WCF service in my app.When the app is run for the first time on the iPad,I want it to call a WCF service and display the result in a UITableView.Alongwith displaying the data in UITableView,i want to store the data in Core Data so when the user is "offline"(not connected to wifi)the data will be displayed from the Core Data.The AppDelegate.m looks like this: ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if (![defaults objectForKey:@"firstRun"]) { self.firstRun = TRUE; [defaults setObject:[NSDate date] forKey:@"firstRun"]; } else { self.firstRun = FALSE;//flag does exist so this ISNT the first run } [[NSUserDefaults standardUserDefaults] synchronize]; } ``` The code in UITableView looks like this: ``` - (void)viewDidLoad { [super viewDidLoad]; [my_table setDataSource:self]; [my_table setDelegate:self]; AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; if (appDelegate.firstRun){ NSLog(@"IS FIRST RUN"); EDViPadDocSyncService *service = [[EDViPadDocSyncService alloc]init]; [service getAllCategories:self action:@selector(handleGetAllCategories:)]; } else { NSLog(@"NOT FIRST RUN"); NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Categories" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSError *errormsg; self.allCats = [managedObjectContext executeFetchRequest:fetchRequest error:&errormsg]; NSLog(@"allCATS=%@",self.allCats); self.title = @"Categories"; } } -(void)handleGetAllCategories:(id)value { if([value isKindOfClass:[NSError class]]) { NSLog(@"This is an error %@",value); return; } if([value isKindOfClass:[SoapFault class]]) { NSLog(@"this is a soap fault %@",value); return; } NSMutableArray *result = (NSMutableArray*)value; NSMutableArray *categoryList = [[NSMutableArray alloc] init]; NSMutableArray *docCount = [[NSMutableArray alloc]init]; NSMutableArray *catIdList = [[NSMutableArray alloc]init]; self.myData = [[NSMutableArray array] init]; self.myDocCount = [[NSMutableArray array]init]; self.catId = [[NSMutableArray array]init]; for (int i = 0; i < [result count]; i++) { EDVCategory *catObj = [[EDVCategory alloc]init]; catObj = [result objectAtIndex:i]; [categoryList addObject:[catObj categoryName]]; [docCount addObject:[NSNumber numberWithInt:[catObj docCount]]]; [catIdList addObject:[NSNumber numberWithInt:[catObj categoryId]]]; } self.myData = categoryList; self.myDocCount = docCount; self.catId = catIdList; [my_table reloadData]; /*store data in Core Data - START*/ NSManagedObjectContext *context = [self managedObjectContext]; NSManagedObject *newCategory; for(int j=0;j<[result count];j++) { newCategory = [NSEntityDescription insertNewObjectForEntityForName:@"Categories" inManagedObjectContext:context]; /*HOW TO STORE DATA FOR THE "CATEGORIES" OBJECT IN CORE DATA*/ } /*store data in Core Data - END*/ } ``` I am not able to figure out how to store the data received from the wcf service to the core data object directly.I know how to store it from a text box on the screen to a core data object.eg.:- ``` coreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSManagedObject *newContact; newCat = [NSEntityDescription insertNewObjectForEntityForName:@"Categories" inManagedObjectContext:context]; [newCat setValue:name.text forKey:@"name"]; name.text = @""; [context save:&error]; ``` But this doesn't help in my case.Any help is appreciated.
2012/08/27
[ "https://Stackoverflow.com/questions/12135704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1550951/" ]
In my case I try this: ``` sudo apt install openjdk-11-jdk-headless sudo apt install openjdk-8-jdk-headless ``` I use openjdk
Find in `/usr/lib/jvm/java-8-oracle/bin/jarsigner -verbose -sigalg SHA1withRSA`
28,806,965
I'm nearing the end of a program development for my computer science course. However, one of the requirements is to have a user manual within the app. I saved the user manual as a PDF inside Eclipse's workspace. It is stored under "/Documents/PDF Manual.pdf". I originally used this code: ``` URL url = getClass().getResource( fileSeparator + "Documents" + fileSeparator + "PDF Manual.pdf"); //fileSeparator = '/' on mac, & '\\' on windows File userManual = new File (url.toURI()); if (userManual.exists()) { Desktop.getDesktop().open(userManual); } ``` This works fine while running the project from eclipse, however URI returns a non hierarchical exception (as expected) when the program is exported to a jar file. I thought of playing around with url.toString(), using substring and replaceAll() to get rid of unwanted characters (%20 for the space), however this gave weird results and of course the code wouldn't work properly when it wasn't a jar file. I looked at InputStream, however this is only used to read from a file and I cannot open the file using a desktop app. Due to the process of submission, the pdf HAS to be saved inside the project folders. Also, my code has to be platform independent (or at the very least, work on windows and mac) and thus manipulating file names becomes a lot more complicated. Any suggestions? Edit: ----- After @SubOptimal 's help, this is the code I am now using: ``` String inputPdf = "Documents" + fileSeparator + "PDF Manual.pdf"; InputStream manualAsStream = getClass().getClassLoader().getResourceAsStream(inputPdf); Path tempOutput = Files.createTempFile("TempManual", ".pdf"); tempOutput.toFile().deleteOnExit(); Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING); File userManual = new File (tempOutput.toFile().getPath()); if (userManual.exists()) { Desktop.getDesktop().open(userManual); } ``` This works on mac. However, on windows manualAsStream is null for some unknown reason.
2015/03/02
[ "https://Stackoverflow.com/questions/28806965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1320185/" ]
Full working example. Tested in Windows environment. **file structure** ``` .\REPL.java .\doc\manual.pdf .\manifest.mf ``` **REPL.java** ``` package sub.optimal; import java.io.InputStream; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.awt.Desktop; public class REPL { public static void main(String[] args) throws Exception { String inputPdf = "doc/manual.pdf"; Path tempOutput = Files.createTempFile("TempManual", ".pdf"); tempOutput.toFile().deleteOnExit(); System.out.println("tempOutput: " + tempOutput); try (InputStream is = REPL.class.getClassLoader().getResourceAsStream(inputPdf)) { Files.copy(is, tempOutput, StandardCopyOption.REPLACE_EXISTING); } Desktop.getDesktop().open(tempOutput.toFile()); } } ``` **manifest.mf** ``` Main-Class: sub.optimal.REPL ``` **compile** ``` javac -d . REPL.java ``` **create JAR** ``` mkdir dist\ jar cvfm dist/REPL.jar MANIFEST.MF sub/optimal/REPL.class doc/manual.pdf ``` **execute JAR** ``` cd dist\ java -jar REPL.jar ```
Use [getResourceAsStream](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29) instead of getResource To write in the temp directory use [createTempFile](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile%28java.lang.String,%20java.lang.String%29)
15,766,492
Apropos the question ["Why does using the same count variable name in nested FOR loops work?"](https://stackoverflow.com/questions/2393458/why-does-using-the-same-count-variable-name-in-nested-for-loops-work) already posted in this forum,a count variable "i" defined in each nested loop should be considered a new variable whose scope is limited to that loop only.And we should expect that variable's value to be erased and overridden by the value of "i" which was in the outer loop (before control passed to inner loop).But in my following code, when the control comes out of the inner loop,instead of the variable "i" having the value 0 (which was it's value in the first iteration of outer loop,before control passed to inner loop),it continues to have the value 10 instead (which it got in last iteration of inner loop).Then this 10 is incremented to 11 and hence the condition of the outer loop in not satisfied and the outer loop exits. I had expected my program to print the numbers 0 to 9 horizontally 10 times, in 10 different lines.But it prints just for one line and exits. And here's another thing to it--If I use any number greater than 10 in the outer loop condition (i<=10),then it creates an infinite loop.According to my reasoning, it happens because i gets a value of 11 after the first iteration of outer loop and hence if condition is <=11 or more then the outer loop comes to another iteration.Whereupon i is again initialized to 0 in inner loop and the cycle continues. Sorry if I couldn't put my question very clearly.All I want to ask is, isn't the inner i supposed to be a different variable if we are to assume the linked question on this forum is correct?Why then the value of i continues to hold on after we exit inner loop,instead of reverting to the value of i that was there when we entered the inner loop? ``` #include <stdio.h> int main() { int i; //for (i = 0; i <= 11; i++) Creates infinite loop if this condition is used instead for (i = 0; i <= 9; i++) { for (i = 0; i <= 9; i++) { printf("%d ", i); } printf("\n"); } } ``` `OUTPUT : 0 1 2 3 4 5 6 7 8 9` PS: As a secondary question, is it impossible to print the number 0 to 9 horizontally, in 10 different lines, using nested for loop if we use the same count variable in each loop,as I have done here? (Ignore this secondary question if it's not relevant to main question)
2013/04/02
[ "https://Stackoverflow.com/questions/15766492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1915076/" ]
The answer you linked to is using *different variables with the same name*, you're simply using the same variable. Compare: ``` for(int i = 0; ... ``` to: ``` for(i = 0; ... ``` The former declares a new variable called `i`, which is how you nest loops like the linked-to answer. Not that I would ever (ever!) recommend doing so. As you've noticed, support for the former syntax wasn't added to C until C99.
If i were defined in each loop then the behaviour would be as your linked question. In your example you only define `i` once, outside any loop, then reuse it ``` int i; for(i=0; i<=9; i++) { for(i=0; i<=9; i++) { ``` is not the same as ``` for(int i=0; i<=9; i++) { for(int i=0; i<=9; i++) { ```
9,153
I usually build 8 probes, then a pylon, so I could keep building probes and not have to wait for the pylon to build (in 10-pylon you're stuck while the pylon is building). Is one of these build better than the other? [This answer](https://gaming.stackexchange.com/questions/875/what-are-the-popular-build-orders-for-protoss-in-starcraft-2/891#891) states that most Protoss go 10-pylon.
2010/10/16
[ "https://gaming.stackexchange.com/questions/9153", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/1161/" ]
There was a fun poll about this [on Team Liquid](http://www.teamliquid.net/forum/viewmessage.php?topic_id=136582). The issue with 8 Pylon is that you lose a few seconds of mining time down the line. To make up for it you have to use your first Chrono Boost before the Pylon instead of after. This will lead to a temporary advantage that will cost you in the long run. Outside of the early gateway play, this usually isn't worth it.
I've been practicing this a lot for Cannon rush openings. 8 pylon boost seems like it could maintain the mining pace of the 10 pylon if executed well. You'd lose a boost though that would've been used for building something else.
60,621,603
I was going through an **[article](https://www.geeksforgeeks.org/union-c/)** to learn about union and I had understood that the size of a Union depends upon the largest variable size and the variables share the same memory. So the concept was pretty clear for me but in the article author said that using "union" for a binary tree was worthwhile when it had two pointers to point other two child. A question arose in my mind for the "What are applications of union?" section of that article, what would be the possible explanations for pointers inside a union? The link has been given below. <https://www.geeksforgeeks.org/union-c/> So, this is it. Is there anybody who can help me out?
2020/03/10
[ "https://Stackoverflow.com/questions/60621603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10071401/" ]
> > in the article author said that using "union" for a binary tree is worthwhile when it had two pointers to point other two child...what would be the possible explanations for pointers inside a union? > > > I believe you are talking about this code snippet: ``` struct NODE { bool is_leaf; union { struct { struct NODE* left; struct NODE* right; } internal; double data; } info; }; ``` You misunderstand the author's intent here. They are using a union to implement the two different kinds of nodes in a tree: an internal node that has a left and right pointer and a leaf node which has data. This union shares memory between a `struct` and a `double`. It does **not** share memory between the left and right pointers.
I'd also inject that I really don't agree with this author. Just define a `struct` with two pointers and data, and be done. Use `calloc()` to obtain the structure and set it all to binary zeros. There's no point in "saving a few bytes of memory" anymore. If you use a `union` in this way, you *are going to* screw-up and waste a lot of time debugging.
53,064,577
So far I have this script: ``` #!/bin/sh echo type in some numbers: read input ``` From here on I'm stuck. Let's say `input=30790148`. What I want to do is add all of those integers up to get 3+0+7+9+0+1+4+8=32. How can I accomplish this?
2018/10/30
[ "https://Stackoverflow.com/questions/53064577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8849558/" ]
This one using `sed` and `bc` ``` echo "12345" | sed -e 's/\(.\)/\1\+0/g' | bc ``` It's a bit hackish though since the `+0` is not intuitive Edit: Using `&` from @PaulHodges' answer, this would shorten to: ``` echo "12345" | sed 's/./&+0/g' | bc ```
This awk one-liner may help you: ``` awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' FS="" <<< yourString ``` for example: ``` kent$ awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' FS=""<<< "123456789" 45 ```
4,520,743
I have main menu in my app supporting only landscape mode. I implement landscape restriction by setting up `UIRootViewController::shouldAutorotateToInterfaceOrientation:...` And I have another scene with portrait mode support. So the problem appears when I pass from another scene to main menu in portrait mode: the app doesn't rotate to landscape automatically, and I can't find a code method to manually rotate it. Is there a solution? Would be thankful. Edit: Excuse me, I forgot to add details. RootViewController is common for menu and another scene. And what is more - these scenes are in one common view (my app uses OpenGL) So before I enter menu from portrait scene I set `UIRootViewController::shouldAutorotateToInterfaceOrientation:` to return YES for landscape only.
2010/12/23
[ "https://Stackoverflow.com/questions/4520743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326017/" ]
To start with, I recommend against doing both `import decimal` and `from decimal import *`. Pick one and use what you need from there. Generally, I do `import whatever` and then use `whatever.what_is_needed` to keep the namespace cleaner. As commenters have already noted there's no need to create a class for something this simple (unless this is homework and your instructor requires it). Delete the class declaration, change your `def __init__(self)` into a `def main()`, and call main where you currently instantiate loan\_class. For more about main functions, see [Guido's classic post](http://www.artima.com/weblogs/viewpost.jsp?thread=4829) about them. The input values should be checked. A simple way to do this would be with a try-except block as they are converted to Decimal. The code could look something like: ``` prin_str = raw_input('Please enter your loan amount: ') try: principal = decimal.Decimal(prin_str) except decimal.InvalidOperation: print "Encountered error parsing the loan amount you entered." sys.exit(42) ``` To get this to work, you'd have to `import sys` sometime before the sys.exit() call. I usually put my imports at the start of the file. Since all your inputs are to be of the same type, you could easily make this a general use function and then call that function for each input. There does appear to be some sort of bug in the calculations. Resolving that is left as an exercise for the reader. ;-)
The logic is much the same as previous answers, but severely reformatted. Enjoy! ``` # Loan payment calculator import decimal def dollarAmt(amt): "Accept a decimal value and return it rounded to dollars and cents" # Thanks to @Martineau! # I found I had to use ROUND_UP to keep the final payment # from exceeding the standard monthly payments. return amt.quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_UP) def getAmt(msg): "Get user input and return a decimal value" return decimal.Decimal(raw_input(msg)) class MonthlyFixedPaymentLoan(object): def __init__(self, principal, yearlyRate, months): self.principal = principal self.yearlyRate = yearlyRate self.months = months self.interest = dollarAmt(principal * yearlyRate * (months/12)) self.balance = principal + self.interest self.payment = dollarAmt(self.balance / months) def __str__(self): return ("Amount borrowed: ${0:>10}\n" + "Total interest paid: ${1:>10}").format(dollarAmt(self.principal), dollarAmt(self.interest)) def payments(self): # 'month 0' yield 0, decimal.Decimal('0.00'), self.balance pmt = self.payment bal = self.balance for mo in range(1,self.months): bal -= pmt yield mo, pmt, bal # final payment yield self.months, bal, decimal.Decimal('0.00') def main(): amt = getAmt('Amount borrowed ($): ') rate = getAmt('Interest rate (%/yr): ') pd = getAmt('Loan term (years): ') loan = MonthlyFixedPaymentLoan(amt, rate/100, pd*12) print('') print(loan) print('') print('Month Payment Balance') print('----- -------- ----------') for mo,pay,rem in loan.payments(): print('{0:>4} ${1:>7} ${2:>9}'.format(mo, pay, rem)) if __name__=="__main__": main() ```
47,465,961
**Situation** I have many URLs in a file, and I need to find out how many unique URLs exist. I would like to run either a bash script or a command. `myfile.log` ``` /home/myfiles/www/wp-content/als/xm-sf0ab5df9c1262f2130a9b313192deca4-f0ab5df9c1262f2130a9b313192deca4-c23c5fbca96e8d641d148bac41017635|https://public.rgfl.org/HS/PowerPoint%20Presentations/Health%20and%20Safety%20Law.ppt,18,17 /home/myfiles/www/wp-content/als/xm-s4bf050d47df5bfaf0486a50a8528cb16-4bf050d47df5bfaf0486a50a8528cb16-c23c5fbca96e8d641d148bac41017635|https://public.rgfl.org/HS/PowerPoint%20Presentations/Health%20and%20Safety%20Law.ppt,15,14 /home/myfiles/www/wp-content/als/xm-sad122bf22152ba4823a520cc2fe59f40-ad122bf22152ba4823a520cc2fe59f40-c23c5fbca96e8d641d148bac41017635|https://public.rgfl.org/HS/PowerPoint%20Presentations/Health%20and%20Safety%20Law.ppt,17,16 /home/myfiles/www/wp-content/als/xm-s3c0f031eebceb0fd5c4334ecef15292d-3c0f031eebceb0fd5c4334ecef15292d-c23c5fbca96e8d641d148bac41017635|https://public.rgfl.org/HS/PowerPoint%20Presentations/Health%20and%20Safety%20Law.ppt,12,11 /home/myfiles/www/wp-content/als/xm-sff661e8c3b4f94957926d5434d0ad549-ff661e8c3b4f94957926d5434d0ad549-c23c5fbca96e8d641d148bac41017635|https://quality.gha.org/Portals/2/documents/HEN/Meetings/nursesinstitute/062013/nursesroleineliminatingharm_moddydunning.pptx,17,16 /home/myfiles/www/wp-content/als/xm-s32c41ec2a5440ad220008b9abfe9add2-32c41ec2a5440ad220008b9abfe9add2-c23c5fbca96e8d641d148bac41017635|https://quality.gha.org/Portals/2/documents/HEN/Meetings/nursesinstitute/062013/nursesroleineliminatingharm_moddydunning.pptx,19,18 /home/myfiles/www/wp-content/als/xm-s28787ca2f4372ddb3616d3fd53c161ab-28787ca2f4372ddb3616d3fd53c161ab-c23c5fbca96e8d641d148bac41017635|https://quality.gha.org/Portals/2/documents/HEN/Meetings/nursesinstitute/062013/nursesroleineliminatingharm_moddydunning.pptx,22,21 /home/myfiles/www/wp-content/als/xm-s89a7b68158e38391da9f0de1e636c0d5-89a7b68158e38391da9f0de1e636c0d5-c23c5fbca96e8d641d148bac41017635|https://quality.gha.org/Portals/2/documents/HEN/Meetings/nursesinstitute/062013/nursesroleineliminatingharm_moddydunning.pptx,13,12 /home/myfiles/www/wp-content/als/xm-sc4b14e10f6151995f21334061ff1d139-c4b14e10f6151995f21334061ff1d139-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hy-wire-car-2.pptx,13,12 /home/myfiles/www/wp-content/als/xm-se589d47d163e43fa0c0d68e824e2c286-e589d47d163e43fa0c0d68e824e2c286-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hy-wire-car-2.pptx,19,18 /home/myfiles/www/wp-content/als/xm-s52f897a623c539d09bfb988bfb153888-52f897a623c539d09bfb988bfb153888-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hy-wire-car-2.pptx,14,13 /home/myfiles/www/wp-content/als/xm-sccf27a904c5b88e96a3522b2e1180fed-ccf27a904c5b88e96a3522b2e1180fed-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hy-wire-car-2.pptx,18,17 /home/myfiles/www/wp-content/als/xm-s6874bf9d589708764dab754e5af06ddf-6874bf9d589708764dab754e5af06ddf-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hy-wire-car-2.pptx,17,16 /home/myfiles/www/wp-content/als/xm-s46c55ec8387dbdedd7a83b3ad541cdc1-46c55ec8387dbdedd7a83b3ad541cdc1-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hy-wire-car-2.pptx,19,18 /home/myfiles/www/wp-content/als/xm-s08cfdc15f5935b947bbaa93c7193d496-08cfdc15f5935b947bbaa93c7193d496-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hydro-power-plant.ppt,9,8 /home/myfiles/www/wp-content/als/xm-s86e267bd359c12de262c0279cee0c941-86e267bd359c12de262c0279cee0c941-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hydro-power-plant.ppt,15,14 /home/myfiles/www/wp-content/als/xm-s5aa60354d134b87842918d760ec8bc30-5aa60354d134b87842918d760ec8bc30-c23c5fbca96e8d641d148bac41017635|https://royalmechanical.files.wordpress.com/2011/06/hydro-power-plant.ppt,14,13 ``` **Desired Result**: ``` Unique Urls: 4 ```
2017/11/24
[ "https://Stackoverflow.com/questions/47465961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8851470/" ]
``` cut -d "|" -f 2 file | cut -d "," -f 1 | sort -u | wc -l ``` Output: ``` 4 ``` --- See: `man cut`, `man sort`
``` tr , '|' < myfile.log | sort -u -t '|' -k 2,2 | wc -l ``` * `tr , '|' < myfile.log` translates all commas into pipe characters * `sort -u -t '|' -k 2,2` sorts unique (`-u`), pipe delimited (`-t '|'`), in the second field only (`-k 2,2`) * `wc -l` counts the unique lines
481,516
I'm wondering if the link on the company logo, which usually goes the home page, should be: * <http://www.example.com> * <http://www.example.com/index.html> (or other index file) * /index.html (or other index file) * / (just the root) Does Google care or are there other rules?
2009/01/26
[ "https://Stackoverflow.com/questions/481516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
A or D. Hard coding the full path in removes flexibility - let the web server or the app config handle what the default is. (iirc google doesn't care any more than it would for any other link)
Relative URLs (C and D) would be resolved by clients (Google included) to absolute URLs (to B and A respectively) and therefore treated the same as their absolute counterparts. If your A permanently redirects to B, or B to A, then Google will also treat this as one resource. Google will score A+B+C+D as one page. Whichever one URL the others eventually resolve or redirect to will be considered the 'canonical' URL. The words contained in your canonical URL are important. As in the URLs of questions here on stackoverflow, the words should relate to the content. Therefore what you need to decide is whether or not you want the words 'index' and 'html' in the URL. I believe best practice for home pages is to have `http://www.example.com/index.html` permanently redirect to `http://www.example.com/` . Of course, content is still king, and all of this is just minor tweaking compared to adding quality content.
67,206
I am trying to set up OpenVPN to allow me to connect a number of laptops to my network in a way that allows the laptops to connect to specific computers via HTTP (to e.g. a server management page) and windows shares (to access files) In the test environment my laptops live in a network with a 192.168.1.X address range. The host-network has a 10.66.77.X address range The server hosting the OpenVPN server has address 10.77.10.20. I need to access some application server web pages on this machine, accessible on various ports The server with the windows shares as well as some other web based pages I need to access is on address 10.66.77.20 The config files for server and laptop are attached below. The laptop establishes the VPN connection without problems, but I cannot access any of the machines, even a simple ping fails. Maybe a routing problem? The routing table for the laptop is shown below as well - every idea is appreciated! Thanks! Maik **Server config file** ``` port 1194 dev tun tls-server ca /etc/openvpn/keys/ca.crt cert /etc/openvpn/keys/projects.crt key /etc/openvpn/keys/projects.key dh /etc/openvpn/keys/dh1024.pem server 10.8.0.0 255.255.255.0 ifconfig-pool-persist ipp.txt push "route 10.66.77.0 255.255.255.0" keepalive 10 60 inactive 600 route 10.8.0.1 255.255.255.0 user openvpn group openvpn persist-tun persist-key verb 4 ``` **client config file** ``` dev tun proto udp remote SERVERADDR 1194 resolv-retry infinite nobind persist-key persist-tun ca ca.crt cert accountingLaptop.crt key accountingLaptop.key ns-cert-type server comp-lzo verb 3 ``` **Resulting routing table on client laptop** ``` C:\Documents and Settings\User>route print =========================================================================== Interface List 0x1 ........................... MS TCP Loopback interface 0x2 ...00 23 5a 9b 64 9b ...... Atheros AR8132 PCI-E Fast Ethernet Controller - Packet Scheduler Miniport 0x3 ...00 24 2c 35 c9 6b ...... Dell Wireless 1395 WLAN Mini-Card - Packet Sched uler Miniport 0x4 ...00 ff 5e 03 43 9b ...... TAP-Win32 Adapter V9 - Packet Scheduler Miniport =========================================================================== =========================================================================== Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.129 25 10.8.0.1 255.255.255.255 10.8.0.5 10.8.0.6 1 10.8.0.4 255.255.255.252 10.8.0.6 10.8.0.6 30 10.8.0.6 255.255.255.255 127.0.0.1 127.0.0.1 30 10.66.77.0 255.255.255.0 10.8.0.5 10.8.0.6 1 10.255.255.255 255.255.255.255 10.8.0.6 10.8.0.6 30 127.0.0.0 255.0.0.0 127.0.0.1 127.0.0.1 1 192.168.1.0 255.255.255.0 192.168.1.129 192.168.1.129 25 192.168.1.129 255.255.255.255 127.0.0.1 127.0.0.1 25 192.168.1.255 255.255.255.255 192.168.1.129 192.168.1.129 25 224.0.0.0 240.0.0.0 10.8.0.6 10.8.0.6 30 224.0.0.0 240.0.0.0 192.168.1.129 192.168.1.129 25 255.255.255.255 255.255.255.255 10.8.0.6 2 1 255.255.255.255 255.255.255.255 10.8.0.6 10.8.0.6 1 255.255.255.255 255.255.255.255 192.168.1.129 192.168.1.129 1 Default Gateway: 192.168.1.1 =========================================================================== Persistent Routes: None ```
2009/09/21
[ "https://serverfault.com/questions/67206", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
the issue may be that your VPN is not NAT on the vpn server, so that the VPN clients are directly connecting to the server with the 10.8.0.0 ip, which is a network the other servers have no idea about. 2 solutions are to use iptables to masquerade as a nat on the server, or to add the routes static to the other servers.
As a rule of thumb, you need static routes for every network which is not directly connected to your laptop. So, assuming your OpenVPN server can talk to 10.66.77.20, you need to do the following * on the roaming laptops, add a route to 10.66.77.20 via the OpenVPN server IP * on 10.66.77.20, add a route to the 192.168.1.0/24 network via the OpenVPN server IP
2,472,211
What are the best practices for securing a coldfusion webpage from malicious users? (including, but not limited to, sql injection attacks) Is cfqueryparam enough?
2010/03/18
[ "https://Stackoverflow.com/questions/2472211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/296789/" ]
Although using a prebuilt solution will work, I recommend knowing all the possible issues that must be protected. Check out Hack Proofing ColdFusion at [Amazon](https://rads.stackoverflow.com/amzn/click/com/1928994776).
CfQueryParam is very important, but not nearly enough. There is a boxed solution we use at my work: <http://foundeo.com/security/>. It covers most of the bases. And even if you don't want to buy it, you can take a look at it's feature set and get an idea of the things you should be considering.
65,333,756
I have provided AmazonS3FullAccess policy for both the IAM user and group. Also the buket that I am trying to access says "Objects can be public". I have explicitly made the folder inside the bucket public. Despite all this I am getting access denied error when I tried to access it through its url. Any idea on this?
2020/12/17
[ "https://Stackoverflow.com/questions/65333756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3093728/" ]
I like using `Set` for this purpose. You can create a `Set` from your first array and then any lookup in that Set (using `Set.has`) is O(1) efficiency. ```js const arr1 = [1, 3, 4, 5, 6, 7, 8, 9, 11, 13, 16]; const arr2 = [1, 2, 3, 7, 9, 12, 16, 17]; const arr1Items = new Set(arr1); const matched = arr2.filter(el => arr1Items.has(el)); console.log(matched.length, matched); ```
The function I wrote below will give the results you want, but remember the function returns an array of arrays, even if the second parameter had only one array or was an array of elements instead of array of arrays (Works for both). ```js Arr1 = [1, 2, 3, 5, 6, 7, 8, 10, 15] Arr2 = [ [1, 3, 5, 7, 8, 9, 10, 11, 12], [2, 5, 6, 7, 9, 10], [1, 3, 5, 7, 10, 11, 13, 14, 15] ] Arr3 = [1, 5, 6, 9, 12, 15, 17] function check(base_array,search_values) { if(base_array.length===0 || search_values.length===0) { return []; } else if(Array.isArray(search_values[0]))// Check if second parameter is an array of arrays. { var result=[]; search_values.forEach(search=>{ var result_sub=[]; search.forEach(key=>{ if(base_array.includes(key)) { result_sub.push(key); } }); result.push(result_sub); }); return result; } else { var result=[]; search_values.forEach(key=>{ if(base_array.includes(key)) { result.push(key); } }); return [result]; } } console.log("Array of Arrays"); console.log(check(Arr1,Arr2)); console.log("Array of Elements"); console.log(check(Arr1,Arr3)); ``` From the returned result you can loop through the value to get the elements and the number of elements by checking length of array. ``` result.forEach(element=>{ console.log(result.length, result);// number of elements doesn't have to be passed }); ``` What the Function does is it checks if any array is empty , then returns empty array `[]`, if the second array is an array of arrays it loops through each array and then to each element in the sub array and checks if it exists in the first array, else if the array was array of elements, then it just loops through the elements and checks if it exists in the first array. And returns the result stored
38,212
> > But as for you, Bethlehem Ephrathah, Too little to be among the clans of Judah, From you One will go forth for Me to be ruler in Israel. His goings forth are from long ago, From the days of eternity (yom olam). > [‭‭Micah‬ ‭5](https://parabible.com/Micah/5):2‬ ‭NASB‬‬ > > > What are the "days of eternity" (yom olam) in Micah asserting about the ruler?
2019/01/10
[ "https://hermeneutics.stackexchange.com/questions/38212", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/28028/" ]
To understand the verse in question it helps to understand the military context: > > ESV Micah 5: > > > 1a Now **muster your troops**, O **daughterb of troops**; > **siege** is laid against us; > **with a rod they strike the judge** of Israel > on the cheek. > 2c But you, O Bethlehem Ephrathah, > who are too little [insignificant] **to be among the clans [armies] of Judah**, > from you shall come forth for me > one who is **to be ruler in Israel**, > **whose coming forth** is from of old, > from ancient days. > > > Footnotes: > a 1 Ch 4:14 in Hebrew > b 1 That is, city > c 2 Ch 5:1 in Hebrew > > > So the prophet is saying that from the city of David, Bethlehem, the house of bread, which was nothing but a few women and children, the promised ruler of Israel would arise. But then he says "whose coming forth..." which is apparently taken by the ESV to refer to his birth in Bethlehem. However, (and I'm no Hebrew guru) the word is plural and is rendered in other translations as "whose comings forth" (IE: given the context, "sorties" or "military campaigns"). Now, if I'm correct concerning this then this would be, I believe [in a notional sense](http://www.21stcr.org/multimedia-2015/1_pdf/ds_john_and_jewish_preexistence.pdf), similar to this: > > [Rom 4:17 KJV] 17 (**As it is written, I have made** thee a father of many nations,) before him whom he believed, [even] God, who quickeneth the dead, **and calleth those things which be not as though they were**. > > > But most important, I believe is the concern in the original question that perhaps the form of one usage of OLAM might tell us the meaning of a similar use. However, that isn't necessarily the case. Context is always the key factor. The NET Bible renders Micah 5:2 like this: > > NET Bible Micah 5:2 As for you, Bethlehem Ephrathah, seemingly insignificant among the clans of Judah--from you a king will emerge who will rule over Israel on my behalf, one whose origins **are in the distant past**. > > > That's about all I think we can load OLAM with in actual usage. And if his military campaigns from OLAM then we must not imagine that his first battle was in eternity past. Surely there was no war on day one! The point is that the exploits of the Messiah have been in the scriptures from long ago and in God's mind longer than that. To that agree all the scriptures. Notice this similar verbiage from the mouth of Gideon: > > [Jdg 6:14-16 NLT] (14) Then the LORD turned to him and said, "Go with the strength you have, and **rescue Israel** from the Midianites. I am sending you!" (15) "But Lord," Gideon replied, **"how can I rescue Israel? My clan is the weakest in the whole tribe of Manasseh, and I am the least in my entire family!" (16) The LORD said to him, "I will be with you. And you will destroy the Midianites as if you were fighting against one man."** > > > I should also point out that interpreting Micah 5:2 as saying that Jesus IS the "ancient of days" clashes with Daniel where the Messiah ascends and appears before God who is referred to as "the Ancient of Days": > > [Dan 7:13-14 KJV] 13 I saw in the night visions, and, behold, [one] like the Son of man came with the clouds of heaven, and came to the Ancient of days, and they brought him near before him. 14 And there was given him dominion, and glory, and a kingdom, that all people, nations, and languages, should serve him: his dominion [is] an everlasting dominion, which shall not pass away, and his kingdom [that] which shall not be destroyed. > > >
Autodidact asked: ‘***What are ‘the days of eternity’ (yom olam) in Micah*** [5:1 (BHS)] ***asserting about the ruler?***’ --- **One** We’ve understand better the meaning of the term עלם/עולם (OLM/OULM [two variants commonly used in TaNaKh]) translated ‘*eternity*’ by NASB, along with a number of translations. First of all, the basic meaning of עלם (OLM) is not ‘to be eternal’, but ‘to be indistinct, indefinite’, and, in reference to time, ‘and unsighted time’. A homologous (in a semantic way) term in Akkadian (ancient Babylonian) was DA’AMU, ‘to became dark’ (Chicago Assyrian Dictionary [= CAD] III:1). From this term – probably – was derived, through a number of linguistical steps, the English verb ‘to dim’ (referring to ‘something hard to see at’). Granted, **also ‘eternity’** (NASB et al.) **– from men’s viewpoint – could be included into the well established concept of ‘indistinctness’, because we humans cannot understand, or, simply imagine, fully, what can indicates a time without a start and/or an end. Nevertheless, there are other situations of ‘indistinctness’ that are not linked with ‘eternity’, necessarily**. For an example, we know – from the Bible account – that the earth had surely a start\*\* (ראשׁית) inside the creation time-frame (Genesis 1:1). Still, **Psalm 78:69 applies עלם (OLM) to the ‘earth’**. Also the physical ‘hills’ on the earth had a start, when God did perform the separation between waters and soil (Genesis 1:9). Still, **Deuteronomy 33:15 applies עלם (OLM) to the ‘hills’** (very interestingly, this passage has the same two sequential terms used in Micah 5:1 - BHS [קדם > עלם]). Again, **was a ancient Israelite slave able to serve his master ‘eternally’? Exodus 21:6 says he may do עלם (OLM)**. These examples would be sufficient to understand that the best translation of עלם(OLM) is one which revolves themselves around the concept of ‘indefinite, indistinct time’. Granted, **sometimes עלם (OLM) is linked with ‘eternity’ (or alike), but other times not, as we have seen**. --- **Two** Returning to Micah 5:1 (BHS), **Septuagint (LXX) translated the Hebrew term עלם (OLM) with αιωνος**, that – strangely enough – has the same meaning of עלם (for one example, the αιωνος [‘era’, ‘epoch’] mentioned in Matthew 24:3 & 28:20 had a start and – according Jesus Christ – will have an end, also). Probably, from עלם (OLM) derived a number of words that were utilized in the past, but, we also are using some of these derivative words. For example, Latin language had (the ‘>’ simbol indicates samples of passages of this term in other languages): - *olim*, ‘that time’, ‘time ago’ > Anglosaxon *hwilum*, ‘formerly, times ago’ > Old English *whilom* > Contemporary English *while* (as in the expressions like ‘long while ago’, or, ‘it takes a while to read’). * *velum*, ‘a veil’ (that is ‘something that hide’) > English *veil*. English: - *gloom*, that retains all the letters of עלם (OLM) [according John Parkhurst, ‘A Hebrew and English Lexicon’]. Icelandic: - *hilma*, ‘to hide’. In view of the information above presented **the ‘ruler’ cited by Micah had a time start**. We may understand so on the basis of the MT verbal used there יצא (‘to go out’, ‘to go forth’, ‘to spring up’, et cetera), that implies, necessarily, **an action that starts on a given time point**. So, the Micah’s ‘ruler’ must possess a beginning. Then, in this case, the bynomial link between קדם and עלם point to a translation different from the concept of ‘eternity’. In other words, **the origin of the Micah’s ‘ruler’ was ‘lost in the mists of time’, from the viewpoint of a common human**. These clues well refer – from the viewpoint of christian Bible commentators – to the Messiah Jesus Christ. Then, **the translators are justified to translate as a derivative of ‘to be eternal’ only if the Bible context permits so**. --- **Three** As regards Mac’s Musings assertions about the claimed lack of ‘precision’ of Hebrew language (regarding abstract concepts), I think Ruminator was right when he seemed to doubt about that. Mac’s Musings said: “*Hebrew does not have any abstract nouns for a start. As stated above, Hebrew is excellent (and precise) for spiritual ideas and action but not abstract thought*.” It seems a hasty conclusion, because to assert so we should have a corpus of Hebrew texts at least of a size alike the ancient Greek texts have. Unfortunately, the amount of Hebrew texts (at our disposal, today) is a risible fraction compared to the huge amount of ancient Greek texts. But, even supposing the two corpora of texts (ancient Hebrew vs ancient Greek) were alike (in amount of texts), we have to ask ourselves, ‘what an abstract noun is, really’? And, ‘did ancient Hebrew language possess abstract nouns?’ Cambridge Dictionary (online): “*A noun that refers to a thing that does not exist as a material object*”. This being the case, we may easily test the Mac’s Musings claim with the following couple of reference-book’s definitions of ‘abstract noun’: Collins Dictionary (online): “*A noun that refers to an abstract concept, as for example ‘kindness’*”. Just a moment. Ask ourselves: ‘Has the Bible Hebrew language a specific term for ‘kindness’’?. Surely it has. It is חסד, and it mentioned on hundreds of occurrences in TaNaKh. MacMillan Dictionary (online): “*A common noun that refers to a quality, idea, or feeling rather than to a person or a physical object. For example ‘thought’, ‘problem’, ‘law’, and ‘opportunity’ are all abstract nouns*.” Oops! Sorry, but the TaNaKh do possess them all: ‘thought’ = חשׁב (as in Gen 6:5); ‘problem’ = חוד (as in Pro 1:6); ‘law’ = תורה (as in hundreds of occurrences in TaNaKh). Today, it is worlwide used the term ‘Torah’. ‘opportunity’ = תאנה (as in Judges 14:4). So, avoiding to expand this argument to other topics, like Hebrew subjective and non-subjective tenses, along with the 3D structure of prepositions, and so on, we may conclude that ‘Biblical’ Hebrew has abstract nouns, because also that people (ancient Israelites) – like all people - needed to think and to speak/write through abstractions, in certain cases). I hope these information will help.
2,172,569
Did a new install of postgres 8.4 on mint ubuntu. How do I create a user for postgres and login using psql? When I type psql, it just tells me ``` psql: FATAL: Ident authentication failed for user "my-ubuntu-username" ```
2010/01/31
[ "https://Stackoverflow.com/questions/2172569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61734/" ]
you can also connect to database as "normal" user (not postgres): ``` postgres=# \connect opensim Opensim_Tester localhost; Password for user Opensim_Tester: You are now connected to database "opensim" as user "Opensim_Tester" on host "localhost" at port "5432" ```
With **this command below**, everyone can log in **PostgreSQL** just after installation. \***The default database `postgres`** is used: ```none psql -U postgres ``` You need to put **a password** after running **the command above**: ```none Password for user postgres: ```
1,562,759
In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python? (Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious).
2009/10/13
[ "https://Stackoverflow.com/questions/1562759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111836/" ]
If you're using [iPython](http://ipython.org/ "ipython homepage"), you can use **`function_name?`** to get help, and **`function_name??`** will print out the source, if it can.
You can use the \_\_doc\_\_ keyword: ``` #print the class description print string.__doc__ #print function description print open.__doc__ ```
3,485,764
I know that when developing for Xbox in XNA, you basically just set the resolution to 1280x720 and the Xbox will just take care of things, but on PC I'm having some trouble getting the resolution handled correctly. I would like it to be able to run at other resolutions, but I'm actually happy to make the game always widescreen and just be letterboxed on 4:3 screens. I can already handle scaling the game and it's components but I cannot figure out how to get it letterboxed. Obviously, this will not be necessary in windowed mode, but when running in fullscreen I just need to figure out how to get the game to only draw on part of the screen. What's the best way to do this?
2010/08/15
[ "https://Stackoverflow.com/questions/3485764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
XML forces your data to be well-structured, so that a program which does not understand the *semantics* of your data will still be able to understand its *syntax*. This allows things like XSLT, which will transform one well-formed XML document into another. It means that you can manipulate data without having to interpret it. You can see the document is well-formed and valid according to its DTD without needing to understand the contents. This was a **huge** step forward for data storage, interoperability, and machine-readability in general.
xml lets you be non-standard in a standard way :). It's ugly, it's verbose, it takes up a lot of space and it's absolutely invaluable for interoperability. Basically, xml is nice because it gives you a standard way of describing your data so that a single type of parser can handle data from disparate sources. To use a more concrete example, I used to work in the semiconductor tool industry in the days before xml. Each tool used a recipe to describe how to process a particular wafer. Every one of those tools used a different format for their recipes. Now, pity the poor person (me!) who had to take several of those tools and integrate them into a single processing system. I had to write a different parser for each recipe type, convert recipes from a common store into the format appropriate for a particular tool, it was just a nightmare. If xml had been available, all those recipes could have been defined via xml and any conversions or transformations handled with simple xlst scripts. It would have saved me literally months of development effort just for that portion of the integration code.
32,754,370
I have following code and it works just fine: ``` <script> (function(w,d,s,g,js,fjs){ g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}}; js=d.createElement(s);fjs=d.getElementsByTagName(s)[0]; js.src='https://apis.google.com/js/platform.js'; fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')}; }(window,document,'script')); </script> <script> gapi.analytics.ready(function() { var CLIENT_ID = 'my client id goes here'; gapi.analytics.auth.authorize({ container: 'auth-button', clientid: CLIENT_ID, }); /** * Creates a new DataChart instance showing sessions over the past 30 days. * It will be rendered inside an element with the id "chart-1-container". */ var dataChart1 = new gapi.analytics.googleCharts.DataChart({ query: { 'ids': 'ga:105112893', // The Demos & Tools website view. 'start-date': '30daysAgo', 'end-date': 'yesterday', 'metrics': 'ga:sessions,ga:users', 'dimensions': 'ga:date' }, chart: { 'container': 'chart-1-container', 'type': 'LINE', 'options': { 'width': '100%' } } }); dataChart1.execute(); </script> ``` It works only if I'm logged in into google. But what I want is this to be working even if I'm not logged in. How to implement that? Could you please provide a step by step approach on how to handle that?
2015/09/24
[ "https://Stackoverflow.com/questions/32754370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5318279/" ]
The Google Analytics Demos & Tools site provides a step-by-step approach on how to do that in the Embed API's server-side authorization demo: <https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/>
you can solve this by adding an acces\_token to gapi.analytics.auth.authorize() we can get access\_token by creating a service account in google analytics. <https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/> by running a bellow java code you will get the access token ``` public static String getToken() throws FileNotFoundException, IOException { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("/path-to-file/xxx-246d0882d022.json")) .createScoped(Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY)); credential.refreshToken(); access_token=credential.getAccessToken(); System.out.println(access_token); return access_token; } ``` after creating service account you will get a service account mail id, you have to add this mail id in User Managment ,and you have to enable google analytics api in your account.
5,853,912
so I have: ``` char inBuf[80] ``` and then there's another line ``` inBuf+9 ``` what does it mean when I add that +9 to the array's name?
2011/05/02
[ "https://Stackoverflow.com/questions/5853912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
This would point to the 10th element of the array. So for example: ``` *(inBuf + 9) = 10 ``` would assign 10 to the 10th element.
When you perform addition with it, an array identifier such as your `inBuf` decays to a pointer to the first element in the array, and the number added is multiplied by the size of the array element (in this case char, which has size 1) to produce a new address. So, `inBuf + 9` is the address of the 10th element in the array, which could also be expressed as `&inBuf[9]`. You can use it as in: ``` *(inBuf + 9) = '\0'; // overwrite the 10th element in inBuf with a NUL const char* p = strchr(inBuf + 9, ' '); // find space at or beyond 10th char ```
183,188
Consider the following code: I'm trying to write a \newcommand that will accept either m or n arguments, where m < n. Here m=4, n=6. I want to set things up so that if I call a newcommand, and it is passed 6 arguments, it will ignore the latter two if `\fl` is defined. The rationale for this is that I want to merge different commands depending on different options, but I want to call the commands in the same way. ``` \documentclass{article} \def\fl{} \ifdefined\fl \newcommand{\xx}[4] {#1 #2 #3 #4} \else \newcommand{\xx}[6]{% {#1 #2 #3 #4 \begin{#5} \item foo \end{#6} } } \fi \begin{document} \xx{a}{b}{c}{d}{enumerate}{enumerate} \end{document} ``` To be clear, I want to get ``` a b c d ``` if `\fl` is defined, and ``` a b c d \begin{enumerate} \item foo \end{enumerate} ``` if it is not.
2014/06/04
[ "https://tex.stackexchange.com/questions/183188", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/3406/" ]
Nothing requires you use all arguments in the replacement text: ``` \documentclass{article} \def\fl{} \ifdefined\fl \newcommand{\xx}[6] {#1 #2 #3 #4} \else \newcommand{\xx}[6]{% {#1 #2 #3 #4 \begin{#5} \item foo \end{#6} } } \fi \begin{document} \xx{a}{b}{c}{d}{enumerate}{enumerate} \end{document} ``` ### Output when `\fl` is defined ![enter image description here](https://i.stack.imgur.com/Vzc9n.png) ### Output when `\fl` is not defined ![enter image description here](https://i.stack.imgur.com/cJXUG.png) In order to get this, I just put `%` in front of `\def\fl{}` --- If the status of `\fl` is changing in the document, a more complex strategy is necessary: ``` \documentclass{article}[12pt] \makeatletter \newcommand{\xx}[4]{% #1 #2 #3 #4% \ifdefined\fl \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi {\@gobbletwo}% {\xx@aux}% } \newcommand\xx@aux[2]{% \begin{#1} \item foo \end{#2} } \begin{document} Here \verb+\fl+ is not defined \xx{a}{b}{c}{d}{enumerate}{enumerate} \bigskip \newcommand{\fl}{} Here \verb+\fl+ is defined \xx{a}{b}{c}{d}{enumerate}{enumerate} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/b1GXh.png)
Here are some options (not extensively tested in your setup though): Option A: --------- Define `\xx` to work on 4 *or* 6 arguments by peeking ahead and see whether a new group `\bgroup` is started. ![enter image description here](https://i.stack.imgur.com/jyCm3.png) ``` \documentclass{article} \makeatletter \newcommand{\xx@}[2]{% #1 #2 } \newcommand{\xx}[4]{% #1 #2 #3 #4 \@ifnextchar\bgroup\xx@\relax } \makeatother \begin{document} \xx{a}{b}{c}{d}{enumerate}{enumerate} \xx{a}{b}{c}{d} \xx{a}{b}{c}{d}{enumerate}{enumerate} \end{document} ``` This, of course, does not take `\fl` into consideration. In the above example, `\xx@` would contain the environment definition, effectively designated to handle the two last arguments. Option B: --------- Use it as you specified: ``` \documentclass{article} \def\fl{} \ifdefined\fl \newcommand{\xx}[4]{% #1 #2 #3 #4 } \else \newcommand{\xx}[6]{% #1 #2 #3 #4 #5 #6 } \fi \begin{document} \xx{a}{b}{c}{d}% or \xx{a}{b}{c}{d}{enumerate}{enumerate} \end{document} ```
1,939,333
I have user entries as filenames. Of course this is not a good idea, so I want to drop everything except `[a-z]`, `[A-Z]`, `[0-9]`, `_` and `-`. For instance: ``` my§document$is°° very&interesting___thisIs%nice445.doc.pdf ``` should become ``` my_document_is_____very_interesting___thisIs_nice445_doc.pdf ``` and then ideally ``` my_document_is_very_interesting_thisIs_nice445_doc.pdf ``` Is there a nice and elegant way for doing this?
2009/12/21
[ "https://Stackoverflow.com/questions/1939333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90691/" ]
In Rails you might also be able to use [`ActiveStorage::Filename#sanitized`](https://api.rubyonrails.org/classes/ActiveStorage/Filename.html): ``` ActiveStorage::Filename.new("foo:bar.jpg").sanitized # => "foo-bar.jpg" ActiveStorage::Filename.new("foo/bar.jpg").sanitized # => "foo-bar.jpg" ```
If you use Rails you can also use String#parameterize. This is not particularly intended for that, but you will obtain a satisfying result. ``` "my§document$is°° very&interesting___thisIs%nice445.doc.pdf".parameterize ```
32,907,190
I'm using `BreakBeforeBraces: Allman` in my `.clang-format` file, but braces in control statements (such as `if`, `for`, `while`, ...) are not being put on their own line. ``` // Currently: void foo() { while(true) { bar(); } } // What I want: void foo() { while(true) { bar(); } } ``` [I've read that](http://clang.llvm.org/docs/ClangFormatStyleOptions.html) you can set nested configuration classes for braces in `BraceWrapping`, but I could't figure out the correct YAML syntax (and JSON syntax for the sublime text plugin), and couldn't find any existing example. Is there any way of doing this?
2015/10/02
[ "https://Stackoverflow.com/questions/32907190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/598696/" ]
Achieving the desired result with a specific combination of style options is impossible at the moment. I've reported [the issue as bug 25069](https://llvm.org/bugs/show_bug.cgi?id=25069).
To work around this, I first run [artistic style](http://astyle.sourceforge.net/astyle.html#_Brace_Style_Options) with the option `-A10`, before running clang-format
623,373
I am looking to directly power a Raspberry Pi for my 3D printer from its existing power supply. The terminals on the power supply appear to be ~15 amps max output at 24V. I already have a buck converter wired up to the USB on the Pi to bring the voltage down to ~5V that the Pi wants. What I don't know how to handle is the proper size wires to use in this situation. I have a lot of 20 gauge wire that is generally used on 3D printers, but I am worried about wiring the RPi directly from the power supply with this wire. I also have 14 gauge wire, but it is too large to fit into the terminals on my buck converter, and even if it did, the buck converters are 5 amp max so that would just move the "problem" to the buck converter. Any help in how to properly wire this up would be greatly appreciated. I would prefer crimp connections where possible (my solder work is sub par at best), and would classify myself as very much "hobbyist" and basically assume I know nothing about electrical, so as specific an answer as possible would really help. To be clear, from my understanding, because the 14 gauge wire can handle the max output of the power supply, it should be used. But I also know that the max actual draw of the RPi is far lower than that, and is within the acceptable range of say, a 20 gauge wire. My concern is running 20 gauge for this circuit back to the power supply could have the potential of a fire in a short, but I have no idea how I'm supposed to remedy that. As running 14 gauge wire (even if I could) would just offload the short risk to the buck converter or maybe even the Pi.
2022/06/13
[ "https://electronics.stackexchange.com/questions/623373", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/315620/" ]
I linked to other questions that should cover the basics of your question (in comments, but I'll list them below as well). Per your additional information, regarding the concern of a fire resulting from a short, you are correct in addressing this concern. If you use a wire gauge that is too small for the power supply, but adequate for the load, there is potential that during a short condition that wire would become quite hot and potentially start a fire. The simple answer is to use a **fuse** or **circuit breaker**. This is exactly what is done in home wiring, for example. The circuit breakers are limiting current for each circuit based on its intended usage and how it has been installed. For example, in the US, 15 or 20 ampere breakers are common for circuits that use 14 and 12 gauge wire, respectively. The upstream "power supply" (the mains grid) can easily supply more current which would happily start a fire during a short were it not for the breakers or fuses. Just remember that wherever you install a fuse, the wire should be sized according to the max current that the power supply can deliver on the upstream or input side. Additional resources: * [How do I tell what gauge wire I need?](https://electronics.stackexchange.com/questions/108144/how-do-i-tell-what-gauge-wire-i-need) * [Choosing power supply, how to get the voltage and current ratings?](https://electronics.stackexchange.com/questions/34745/choosing-power-supply-how-to-get-the-voltage-and-current-ratings?noredirect=1&lq=1) * [Fuse position in relation to load and switch](https://electronics.stackexchange.com/q/183796/2028)
**The Official Answer** Often times wire size is related to your fault scenarios. If your RPI was to experience a fault and short 5V and ground together, there would be a large amperage going through the wiring. The question becomes how much is that amperage, and how long does it last, before circuit protection kicks in. Even then, it's also a question of what the circuit protection will do (not all types are a hard cut-off, like PTCs or a regulator going into thermal limit). You want your wires to survive such scenarios. And so you'd want to understand what circuit protection you are using and design to that level. [Here is a nice table for relating AWG to ampacity](https://www.engineeringtoolbox.com/wire-gauges-d_419.html). **The Hobbyist Answer** 20 AWG would be fine so long as it isn't too long. Try to keep it as short as reasonably possible, and beware of making sure your ground wire goes back to your power supply before joining with motor wires (the voltage induced by the motors over wiring would "lift" your RPI). Standard disclaimers for not burning down your house apply.
713,145
How can I set the Hostname/Description of a Mellanox/Infiniband unmanaged switch? I would like a way to abstractly distinguish quickly which switches are which when doing 'ibswitches' or 'ibnetdiscover'. For HCAs that are in Servers, the hostnames are set, which is great. Just need a solution for switches. Example: (All of the switches come up as the following "SwitchX - Mellanox Technologies") ``` [26] "S-e41d2de300756550"[25] # "SwitchX - Mellanox Technologies" lid 6 4xFDR [27] "S-e41d2de30074bc40"[21] # "SwitchX - Mellanox Technologies" lid 5 4xFDR ``` This would be beneificial when looking for ibnetdiscover and being able to quickly find which HCA card goes into which switch.... ``` vendid=0x2c9 devid=0x1011 sysimgguid=0xf45214d300514560 caguid=0xf452140300514560 Ca 1 "H-f45214d300514560" # "mgmt2 HCA-2" [1](f45214d300514560) "S-e41d2dd3007551f0"[15] # lid 11 lmc 0 "SwitchX - Mellanox Technologies" lid 10 4xFDR ```
2015/08/10
[ "https://serverfault.com/questions/713145", "https://serverfault.com", "https://serverfault.com/users/304140/" ]
You can specify "--node-name-map FILE" for ibnetdiscover and configure the mapping between GUIDs and your desired names, so this name would be shown when running ibswitches/ibnetdiscover. ``` --node-name-map <node-name-map> Specify a node name map. The node name map file maps GUIDs to more user friendly names. See file format below. ```
Even shorter answer: now you can, without an external node-name mapping file. <https://github.com/stanford-rc/ibswinfo/> (version 0.6) allows modifying node descriptions for unmanaged Infiniband switches.
874,746
I have a datagrid populated by a Linq query. When the focused row in the datagrid changes I need to set a variable equal to one of the properties in that object. I tried... ``` var selectedObject = view.GetRow(rowHandle); _selectedId = selectedObject.Id; ``` ... but the compiler doesn't care for this at all ("Embedded statement cannot be a declaration or labled statement"). It seems like the property should be easy to access. Inspecting the object during runtime shows all the properties I expect, I just don't know how to access them. How can I get access to the anonymous object's property? **Edit for Clarifications:** I happen to be using DevExpress XtraGrid control. I loaded this control with a Linq query which was composed of several different objects, therefore making the data not really conforming with any one class I already have (ie, I cannot cast this to anything). I'm using .NET 3.5. When I view the results of the view.GetRow(rowHandle) method I get an anonymous type that looks like this: ``` { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 } ``` My objective is to get the ClientId from this anonymous type so I can do other things (such as a load a form with that client record in it). I tried a couple of the suggestions in the early answers but was unable to get to a point where I could get this ClientId.
2009/05/17
[ "https://Stackoverflow.com/questions/874746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42620/" ]
Have you ever tried to use reflection? Here's a sample code snippet: ``` // use reflection to retrieve the values of the following anonymous type var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 }; System.Type type = obj.GetType(); int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null); string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null); // use the retrieved values for whatever you want... ```
This may be wrong (you may not have enough code there) but don't you need to index into the row so you choose which column you want? Or if "Id" is the column you want, you should be doing something like this: ``` var selectedObject = view.GetRow(rowHandle); _selectedId = selectedObject["Id"]; ``` This is how I'd grab the contents of a column in a datagrid. Now if the column itself is an anonymous type, then I dunno, but if you're just getting a named column with a primitive type, then this should work.
59,251,168
I'm trying to do a string search operation using python and my its not working because I have three different kind of Apostrophe in my text [![images of apostrophes](https://i.stack.imgur.com/SI84O.png)](https://i.stack.imgur.com/SI84O.png). I imported by data from word documents. Example comparison text: > > Stimmt`s and Stimmt’s or Stimmt's > > > They all return false when compared like ``` "’" == "'" ``` Any ideas on how to avoid this? **EDIT :** I think this difference in Apostrophe is caused by different such as utf-8 vs ascii (I imported by data from word documents). So replacing apostrophe is one solution but there might be other characters which might cause problem. So I'm looking for a way to make sure text is imported using proper encoding.
2019/12/09
[ "https://Stackoverflow.com/questions/59251168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11098599/" ]
If you replace all unusual forms of the apostrophe before doing anything else you avoid running into any problems: `df = df.replace("`|’", "'", regex=True)`
I think that the simplest solution will be to preprocess your data and use only one of them (e.g. replace all " ’ " with " ' " ). The characters are actually different from each other and that is the reason why you get False when comparing them. Another option is to define a Constant or an enum of a lsit type, such as: ``` APOSTROPHE = ["'","’" ...] ``` and then check if the symbol is in the list.
14,267,526
``` Class A { private Map<Oject,Object> map; public void clear() { map.clear(); } public void work() { synchronized (map) { map.put(new Object, new Object(); } } } ``` If thread A is in the middle of the `work()` method, does this mean thread B won't block if executing the `clear()` method? What is the difference between the code above and having this? ``` public void clear() { synchronized (map) { map.clear(); } } ```
2013/01/10
[ "https://Stackoverflow.com/questions/14267526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541619/" ]
Your suspicion is correct; this code has a bug. You need to lock around `clear()` as well; otherwise; you can still end up running `put()` and `clear()` concurrently. However, you should actually use a `ConcurrentHashMap()` instead.
Correct. Why would it? That's the point of the `synchronized` block - and thread B hasn't executed a `synchronized` block. In this case, it's exactly like there was no synchronisation at all.
34,351,006
I have a problem with Javascript: I'm trying to increment a number which is a string, so I need to parse it, increment the value, and assign that number to the value in the field. But I don't understand why this code doesn't work properly: ``` <button type="button" onclick="dec()" name="less" style="background-color: orange;border:none;">-</button> <script> function dec() { var x = parseInt(document.getElementById("num").value, 10); x--; document.getElementById("num").value = x; } ``` While the number is in a div like this: ``` <div id="num" style="display:inline;">0</div> ``` Where is the error?
2015/12/18
[ "https://Stackoverflow.com/questions/34351006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5457162/" ]
Use the [value attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) of the button element to pass the id, as ``` <button onClick={this.handleRemove} value={id}>Remove</button> ``` and then in handleRemove, read the value from event as: ``` handleRemove(event) { ... remove(event.target.value); ... } ``` This way you avoid creating a new function (when compared to using an arrow function) every time this component is re-rendered.
TL;DR: Don't bind function (nor use arrow functions) inside render method. See official recommendations. <https://reactjs.org/docs/faq-functions.html> --- So, there's an accepted answer and a couple more that points the same. And also there are some comments preventing people from using `bind` within the render method, and also avoiding arrow functions there for the same reason (those functions will be created once again and again on each render). But there's no example, so I'm writing one. Basically, you have to bind your functions in the constructor. ``` class Actions extends Component { static propTypes = { entity_id: PropTypes.number, contact_id: PropTypes.number, onReplace: PropTypes.func.isRequired, onTransfer: PropTypes.func.isRequired } constructor() { super(); this.onReplace = this.onReplace.bind(this); this.onTransfer = this.onTransfer.bind(this); } onReplace() { this.props.onReplace(this.props.entity_id, this.props.contact_id); } onTransfer() { this.props.onTransfer(this.props.entity_id, this.props.contact_id); } render() { return ( <div className="actions"> <button className="btn btn-circle btn-icon-only btn-default" onClick={this.onReplace} title="Replace"> <i className="fa fa-refresh"></i> </button> <button className="btn btn-circle btn-icon-only btn-default" onClick={this.onTransfer} title="Transfer"> <i className="fa fa-share"></i> </button> </div> ) } } export default Actions ``` Key lines are: *constructor* `this.onReplace = this.onReplace.bind(this);` *method* ``` onReplace() { this.props.onReplace(this.props.entity_id, this.props.contact_id); } ``` *render* ``` onClick={this.onReplace} ```
11,523,448
I have an azure web application, running MVC 4. It uses the entity framework (version 4.3.1.0) and Code First together with a data context. I have the data context in its own project, that also have all the model files. ``` public class AwesomeModelContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<License> Licenses { get; set; } public DbSet<AppSession> AppSessions { get; set; } public DbSet<EditSession> EditSessions { get; set; } public DbSet<Space> Spaces { get; set; } public DbSet<SpaceUserPrivilege> SpaceUserPrivileges { get; set; } public DbSet<File> Files { get; set; } public DbSet<Resource> Resources { get; set; } public DbSet<Team> Teams { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Remove cascading deletes, having them turned on by default scares me. modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); modelBuilder.Entity<Space>() .HasMany<SpaceUserPrivilege>(s => s.SpaceUserPrivileges) .WithRequired(p => p.Space) .WillCascadeOnDelete(true); modelBuilder.Entity<User>() .HasMany<SpaceUserPrivilege>(u => u.SpaceUserPrivileges) .WithRequired(p => p.User) .WillCascadeOnDelete(true); modelBuilder.Entity<Team>() .HasMany<User>(u => u.Users) .WithRequired() .WillCascadeOnDelete(false); // Run migrations, if any. Database.SetInitializer<AwesomeModelContext >(new MigrateDatabaseToLatestVersion<AwesomeModelContext , Configuration>()); } } ``` The relevant model is "Team" and it looks like this: ``` namespace MyAwesomeNamespace.Model { public class Team { [Key] public int Id { get; set; } public string Name { get; set; } public ICollection<User> Users { get; private set; } } } ``` That should all nice and well. These are the models for my entire web app. So now I want to add controllers so that I actually can do something with the models. So I do what I usally do, > > Right-click the controller folder, and press "add controller" > > > I name the controller "TeamController", then select the model to be "MyAwesomeNamespace.Model.Team" and the data context to "MyAwesomeNamespace.Model.AwesomeModelContext". > > > I now press Add. This results in the following message. > > "Unable to retrieve metadata for 'MyAwesomeNamespace.Model.Team'. Invalid column name 'CreatedOn'." > > > Anyone know what to do here? I can not find any solutions to this. --- Some extra info: Using Azure database (online). Using Visual Studio 2010 Pro.
2012/07/17
[ "https://Stackoverflow.com/questions/11523448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/741850/" ]
I would like to know whether you have a CreatedOn column in the Team table in your database. If you already have a database, please make sure your model class corresponds to the database table. For example, add the CreatedOn property to your model. If you want a code first approach, you can remove the database. Let Entity Framework automatically generate the database. You can also take the database first approach. Let the Entity Framework automatically generated the code from the database. Best Regards, Ming Xu.
Seems like a thing in EF Code first with migrations enabled, when you upgrade from EF4.\* to EF 5.0. And that in combination with MiniProfiler. The table existed in `dbo._MigrationHistory` under system tables. You try do a few things: 1. You can add `CreatedOn` (DateTime) column manually to `dbo._MigrationHistory` table under System tables folder. 2. You can stop detecting changes by setting `Configuration.AutoDetectChangesEnabled = false;` 3. Comment this line `MiniProfilerEF.Initialize()`, disabling EF profiling.
12,844,504
I want to parse nested JSON strings by splitting them up recursively by { }. The regex I came up with is "{([^}]\*.?)}", which I've [tested](http://java-regex-tester.appspot.com/) appropriately grabs the string I want. However, when I try to include it in my Java I get the following error: "Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )" This is my code, and where the error occurs: ``` String[] strArr = jsonText.split("\{([^}]*.?)\}"); ``` What am I doing wrong?
2012/10/11
[ "https://Stackoverflow.com/questions/12844504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436111/" ]
~~1. Curle braces have no special meaning here for regexp language, so they should not be escaped I think.~~ 2. If you want to escape them, you can. Backslash is an escape symbol for regexp, but it also should be escaped for Java itself with second backslash. 3. There are good JSON parsing libraries <https://stackoverflow.com/questions/338586/a-better-java-json-library> 4. You are using reluctant quantifier, so it won't work with nested braces, for example for `{"a", {"b", "c"}, "d"}` it will match `{"a", {"b", "c"}`
Double the backslashes: ``` String[] strArr = jsonText.split("\\{([^}]*.?)\\}"); ```
48,697,639
Hi I have a pandas df with multilevel columns: ``` sample = pd.DataFrame(pd.np.random.randn(10,2),columns=['a','b']) df = pd.concat([samp], keys=['p4'],axis=1) df ``` Output ``` p4 a b 0 0.621016 0.920448 1 0.329792 -0.674688 ``` I know I can add a column c like this: ``` df[('p4','c')] =df.p4.a - df.p4.b df ``` Output: ``` p4 a b c 0 0.621016 0.920448 -0.299432 ``` which adds the column 'c' with the right values to the level I want. My question is how do I add a large number of these columns to a large dataframe without typing out the columns manually? For example I have columns (p5,['a','b']... (p6,['a','b']) I was thinking a for loop or a list comprehension but I'm strugling to figure out how to add the large number of calculated column 'c'
2018/02/09
[ "https://Stackoverflow.com/questions/48697639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7439683/" ]
In my opinion, a loop is the most readable and maintainable way. For example: ``` for i in range(4, 11): df[('p'+str(i), 'c')] = df[('p'+str(i), 'a')] - df[('p'+str(i), 'b')] ```
I am using MultiIndex for this ``` s=df.T.groupby(level=0).apply(lambda x : x.iloc[0]-x.iloc[1]) s.index=pd.MultiIndex.from_arrays([s.index,['c']]) pd.concat([df,s.T],1) Out[956]: p4 a b c 0 -0.850052 0.960820 -1.810872 1 -0.217418 0.158515 -0.375933 2 0.873418 -0.111383 0.984802 3 -1.038039 -1.009480 -0.028559 4 -1.058257 0.656284 -1.714541 5 -0.062492 -1.738654 1.676163 6 0.103163 -0.621667 0.724830 7 0.275718 -1.090675 1.366393 8 -0.609985 0.306412 -0.916398 9 1.691826 -0.747954 2.439780 ```
8,540,679
Can some one please tell me if I should use user controls in my project as much as I can? Ff so why and if not why not?
2011/12/16
[ "https://Stackoverflow.com/questions/8540679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974330/" ]
It's an interesting question; but think of it this way. You've just written a table, listing all of your users. You show this on the List Users page of your website. On the "Find User" page, you might want to be able to show a list of users. Do you rewrite the same HTML, code, javascript, CSS as before? Or do you reuse the control, this time adding the ability to filter by a user name or other attributes? Essentially, user controls are there to package up reusable bits of your website. Rather than repeating the same code everywhere, you can package it up in a user control, and simply add it to any page you want just by adding the appropriate tag. Also, you have just made ONE control in your project responsible for dealing with some functionality - all of the logic for it is in one place and separated from other code. This is an important concept too, as it stops all of your code being jumbled together. In the users example, you can interact with a list of users through an interface, rather than mixing it with other code that might do different things. This is called [SRP](http://en.wikipedia.org/wiki/Single_responsibility_principle) and can be a good thing. As a practical example, we have a control that shows a list of our products. We can reuse the same control on the Find screen, the Admin screen, the "Products Like this" screen, and on the "Products you have chosen" screen. This code contains a lot of logic that is all in one place so it can be maintained easily, and it can be reused very simply too. User Controls can be a very good thing. So you should use them when you feel like you can package up a group of existing controls, HTML etc. It makes them reusable, and much easier to maintain. There is also the concept of **custom controls** - these are usually reimplementations of existing controls - you might have an ExtendedTextBox, for example, that validates the text as someone types it. You can read more [about both kinds of controls here](http://support.microsoft.com/kb/893667)
I would use the controls that the VS IDE Toolbox provides as much as possible. I would only roll my own control if something that the environment supplied, didn't quite do what I wanted it to do.
34,331,072
I'm using regular expression in my application and I want to test it for different combinations. How to I specify starts with 'a' and ends with 'e'?
2015/12/17
[ "https://Stackoverflow.com/questions/34331072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5681694/" ]
Your regular expression works if you add `.` before the star `*`: ``` (^ap.*e$) ``` However, for your requirements there is no need for the `p`, so this will do ``` (^a.*e$) ``` You can explain this regular expression as follows (see this [link](https://regex101.com/)) 1. `^` assert position at start of the string 2. `a` matches the character a literally (case sensitive) 3. `.*` matches any character (except newline). The quantifier `*` matches between zero and unlimited times, as many times as possible, giving back as needed 4. `e` matches the character e literally (case sensitive) 5. `$` assert position at end of the string
You can use this ``` (^ap.*e$) ``` You can try testing you REGEX on this website. <http://www.regular-expressions.info/javascriptexample.html>
37,229,950
How do I pull out all words that have the symbol "`<-`" either at the end of the word or somewhere in between but in the latter case only if the "`<-`" symbol is followed by a dot. To put it into context. Exercise 6.5.3 a. of *Hadley Wickhams - Advanced R* asks the reader to list all replacement functions in the base package. Replacement function that only have one method are indicated by the symbol `<-` right at the end of the function name. Generic functions, however, have their method name attached to the name of the replacement form (with a dot), such that the `<-` is no longer at the end of the function name. Example `split<-.data.frame` EDIT: ``` obj <- mget(ls("package:base"), inherits = TRUE) funs <- Filter(is.function, objs) ``` This is how you pull out all functions in the base package. Now I want to find only the replacement functions.
2016/05/14
[ "https://Stackoverflow.com/questions/37229950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4046004/" ]
If you want all base package replacement functions and their respective S3 methods, you can try ``` ls(envir = as.environment("package:base"), pattern = "<-") ``` With no packages loaded, this gives the following result: > > > ``` > [1] "<<-" "<-" "[<-" > [4] "[[<-" "@<-" "$<-" > [7] "attr<-" "attributes<-" "body<-" > [10] "class<-" "colnames<-" "comment<-" > [13] "[<-.data.frame" "[[<-.data.frame" "$<-.data.frame" > [16] "[<-.Date" "diag<-" "dim<-" > [19] "dimnames<-" "dimnames<-.data.frame" "Encoding<-" > [22] "environment<-" "[<-.factor" "[[<-.factor" > [25] "formals<-" "is.na<-" "is.na<-.default" > [28] "is.na<-.factor" "is.na<-.numeric_version" "length<-" > [31] "length<-.factor" "levels<-" "levels<-.factor" > [34] "mode<-" "mostattributes<-" "names<-" > [37] "names<-.POSIXlt" "[<-.numeric_version" "[[<-.numeric_version" > [40] "oldClass<-" "parent.env<-" "[<-.POSIXct" > [43] "[<-.POSIXlt" "regmatches<-" "row.names<-" > [46] "rownames<-" "row.names<-.data.frame" "row.names<-.default" > [49] "split<-" "split<-.data.frame" "split<-.default" > [52] "storage.mode<-" "substr<-" "substring<-" > [55] "units<-" "units<-.difftime" > > ``` > > Thanks to @42 for helping me improve this answer.
We can try ``` library(stringr) str_extract(v1, "\\w+<-$|\\w*<-\\.\\S+") #[1] "split<-.data.frame" NA "splitdata<-" ``` ### data ``` v1 <- c("split<-.data.frame", "split<-data", "splitdata<-") ```
391,789
Is there are way we can completely avoid illegal states rather then throwing an IllegalStateException when a method is called when it should not be? For example: ``` public interface Process { void start(); void stop(); } ``` Illegal state would be created if `stop()` is called before `start()`.
2019/05/12
[ "https://softwareengineering.stackexchange.com/questions/391789", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/336132/" ]
You can avoid illegal states by starting in a legal state and disallowing transitions into illegal states. The problem is enforcing that in a system complex enough to get useful work done. The code you posted is trivial enough that it can be fixed simply by adding another type to represent your missing state. [![enter image description here](https://i.stack.imgur.com/D9vxE.png)](https://i.stack.imgur.com/D9vxE.png) You seem to be using some Java like language so here's one way to fix your code: ``` public class Stopped { Started start() { ... } } public class Started { Stopped stop() { ... } } ``` Here the compiler is enforcing that these methods be called in order. I don't even have to look at the using code. But add a simple feature and watch it all fall apart. Lets say we're simulating an internal combustion engine. The kind in your car. That's seems like it should be fine. Those start and stop all the time. Lets add a throttle. You know, a gas peddle. When started it makes the engine rev. When stopped it floods the carburetor. That actually works fine. Add a little polymorphism. Started and stopped now both implement a throttle interface. Spiffy. Then someone up and decides that throttles are not binary. They go from 0% to 100% open. So they decide to pass numbers from 0 to 100 to the throttle method. Sounds fine. But they used an int. Can you see the problem yet? Sure 0 works. 100 works. Anything in between works. So we're fine right? Well no we're not. Before, we didn't have to look at the complex using code. We could prove our code stays in valid states just by reviewing two classes. Now we have to review everything that touches our code. The problem, of course, is that an int allows more than 0-100. We can pass negative numbers, maybe hoping to go in reverse, and we can ask the engine to give 110%. While that looks great on motivational posters it can easily put us into an invalid, undefined, state. Now you can, and should, try to fix this with validation but this is what drives us to give up on proving that code works and instead lean on testing. Our code is going out into a wild and wooly world full of code that we may never see. When that code touches our code it could pass whatever. So what you do, to prevent invalid states, is control transitions, validate input, and test the hell out of it. A single 4 byte int has billions of states. You going to test all that? Of course not. What you do is something called state [space partitioning](https://en.m.wikipedia.org/wiki/Space_partitioning). Which is a fancy way to say test the limits of your boundaries. In this case you'll want throttle tests for -1, 0, 100, and 101. That tests each side of your upper and lower boundaries. That should give you something called code coverage. Each branch of code gets exercised by tests. Even the ones that are supposed to throw an error in your face. This still won't that prove that you can never enter an invalid state. But it's the closest we can come in a language like this. If you need something more formal and provable, look into Scala.
Stopping in a stopped state would just be a nop operations, so do nothing. No IllegalStateException need be thrown, just return immediately from the method if the system is in a state where the stop operation would be meaningless. Similar with the start operation. If the system is already started, it would be a nop operation. Of course for a more complex system, with more states and operations, things can get tricky. What to do when you for example restart is called, and the system isn't started? Do you then relegate to start instead, of throw an IllegalStateException? That's a design decision, and would depend at least in part on the complexity of the states involved. If restarting is more than just stopping and starting, you can't just do a start if the system isn't stopped for example.
177,631
I want to check the quality of digitized tracks. I suppose, that a track with a lot of regular vertices has got a good quality. And a track with less regular vertices has got a poor quality. [![enter image description here](https://i.stack.imgur.com/UFBpi.png)](https://i.stack.imgur.com/UFBpi.png) Maybe, I need something like a heat map for lines?
2016/01/20
[ "https://gis.stackexchange.com/questions/177631", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/6800/" ]
Have you [tried this](http://www.qgistutorials.com/en/docs/counting_vertices.html)? A QGIS plugin to count polylines / polygons vertices and add a new column storing the number of vertices per feature. This could help sorting poor quality / good quality lines from your approach. --- **EDIT :** if you prefer doing so in PostGIS directly, try [st\_NPoints function](http://postgis.net/docs/ST_NPoints.html). The following query calculates the number of vertices in a new field. You just need to alter your table and add the new column. ``` SELECT st_NPoints(geom) FROM schema.table ; ```
Thinking of a way to visualise this. I'm going by gut-feel here, so please forgive the vagueness :) I'll assume that both tracks use the same CRS. I assume that more detailed track is the 'baseline', and you want to measure how far away the other track is. You could use PostGIS to connect each vertex on the baseline to the [closest point on the less detailed line](http://postgis.net/docs/ST_ClosestPoint.html). The length of each of these lines is the error for that vertex. You could then sweep a [1D guassian kernel](https://en.wikipedia.org/wiki/Gaussian_function) across the errors on the line to smooth out the error (e.g. using numpy/scipy). If you know Photoshop/GIMP, think "Guassian Blur", but on a line rather than a plane. The smoothed error could then be used to style the width of the line (or the nodes).
63,946
Can anyone tell me what would be the easiest and cheapest way to access the internet? How common are HotSpots (biggest cities or towns) ? Can I rely on it or would be easier to buy 'pay and go' SIM card ? I am not going to use it for any social network or anything like that (except of SE Travel :) ). Google maps, general googling and highly possible online banking (from time to time) would be mostly used.
2016/02/17
[ "https://travel.stackexchange.com/questions/63946", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/35794/" ]
Just buy a colombian prepaid simcard. Major carriers ([Claro](http://www.claro.com.co/portal/co/pc/personas/movil/catalogo-promociones/promocion/paquetes-de-datos/), [Movistar](https://www.movistar.co/descubre/internet/internet-movil-informativo/internet-prepago) or [Tigo](http://www.tigo.com.co/personas/planes/internet-prepago)). I have used Movistar and Tigo, and I could recommend movistar. It has LTE, and the coverage and signal strength are good. Movistar offers 7 (US $4.50) and 30 days plans (US $ 13), so is the cheaper and most convenient option here.
In the major cities, Bogota, Medellin, Cartagena etc you will find lots of free hotspot places like restaurants, pubs and bars. Even if you don't see hotspot advertised then feel free to ask the waiter for the logon details. Unlike in other countries most hotspots don't require any online registration, simply select the network and add the password for immediate unlimited access. If you are planning to travel about or want internet access in the street then a prepaid sim is your best bet, these are not locked so should be available to use on any cell phone. Again rural areas might suffer from weak mobile signal and hence poor internet but in most towns and cities you will get good coverage. I would recommend Claro and Movistar as the best providers.
8,774,531
I have an UINavigationBar added to my UIViewController view. I want to change the fonts properties. Note that I want to change a UINavigationBar not controller. In my app where I use UINavigationController I use `self.navigationItem.titleView = label;` to display the custom label. How can I accomplish to have a custom title in my UINavigationBar? P.S I use this to set the title text `self.navBar.topItem.title = @"Information";` of my UINavigationBar.
2012/01/08
[ "https://Stackoverflow.com/questions/8774531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507035/" ]
Just put this in your app delegate's ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions ``` From Ray Wenderlich: <http://www.raywenderlich.com/4344/user-interface-customization-in-ios-5> ``` [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0], UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8], UITextAttributeTextShadowColor, [NSValue valueWithUIOffset:UIOffsetMake(0, -1)], UITextAttributeTextShadowOffset, [UIFont fontWithName:@"STHeitiSC-Light" size:0.0], UITextAttributeFont, nil]]; ```
For iOS 13 and Swift 5. For setting the title color & font just add in *viewDidLoad()* the following line: ``` UINavigationBar.appearance().titleTextAttributes = [ .foregroundColor: UIColor.white, .font: UIFont(name: "Arial", size: 24)! ] ``` For setting the bar button item text color & font: ``` UIBarButtonItem.appearance().setTitleTextAttributes([ .foregroundColor: UIColor.white, .font: UIFont(name: GetFontNameBold(), size: 40)! ], for: UIControl.State.normal) ```
64,148,532
I am using FtpGet to extract or retrieve a file from the ftp and loading into the database and before that i am storing in a local folder. So before i use tfilecopy to the local Folder i would like to perform a check wherein if the file already exists in the local folder skip or ignore the next steps,if they dont exist then only write (tfilecopy) to the local folder. So basically i want to iterate through the list of files in the local folder based on the one i am retrieving using GlobalMap variables:dynamically and check if that file exists or not amongst the list of all the other files in that folder and perform the action. I Have created this in talend,i could either check the database to see if the file exists or directly check the local folder where there is a copy of the ftp files(if the same file already exists) skip the process. Only if it does not exist write to the local folder. Which is the best approach either to scan it in the internal folders(although there maybe sub-folders as well) by writing a tjava code Or use database script to query and only if the filename does not exist in the table,copy that file onto a target folder and write to a db table. [![Talend](https://i.stack.imgur.com/MageV.png)](https://i.stack.imgur.com/MageV.png) So primarily i am iterating through the current file from tfilelist3 and checking if they exist in tfilelist2 component using TJAVA and tfilecopy only if the file retrieved does not exist in tfilelist\_2 TJAVA: ``` String path =((String)globalMap.get("tFileList_2_CURRENT_FILEDIRECTORY")); System.out.println("PRINTING PATH in string: " +path); Path filepath=Paths.get(path); System.out.println("PRINTING PATH in PATH: " +filepath); String fileName =((String)globalMap.get("tFileList_3_CURRENT_FILE")); System.out.println("PRINTING FILENAME IN STRING: " +fileName); File file = new File(fileName); System.out.println("File is " +file); //File f = new File(path); if(file.exists()) { System.out.println("Filename: "+file); //+ path.toString()); System.out.println("Exist in location!"); // System.out.println("File EXIST " +f); } else { System.out.println("Filename: "+file); //+ path.toString()); System.out.println("Does not exist in location!"); } ``` I kinda made it little complex and i am lost now,would be great if someone could fix the remaining part and make it work,i cant seem to find a way through this maze now ! I had tried different versions and none of the seem to produce the result that i am looking for? So file.exists() only checks for the specific file in the current directory,so what if i need to check in a different directory,how do i pass the arguments? Approach 2 : [![check if file exists in a different folder before copying to desination/target](https://i.stack.imgur.com/ji0LM.png)](https://i.stack.imgur.com/ji0LM.png)
2020/10/01
[ "https://Stackoverflow.com/questions/64148532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14284366/" ]
You can create a java routine eg: ``` findFile("fileName","FilePath") ``` Invoke the routine for each file by passing the `fileName` and `filePath` as parameters.
Did you check tFileExist component ? It seems that it could be useful (only parameter is folder+filename you want to check ).
1,003,823
I'm trying to setup a Flex project using the Spring + BlazeDS integration by working through the refcard kindly posted by James Ward on refcards.dzone.com. Some problems/challenges are sticking their heads out. The Tomcat deployment is going well, all the files are on the server and I can summon main.swf through the browser. I get the following ActionScript exception when trying to make the AMF request to Spring/BlazeDS: > > RPC Fault faultString="Send failed" > faultCode="Client.Error.MessageSend" > faultDetail="Channel.Connect.Failed > error NetConnection.Call.Failed: HTTP: > Failed: url: > '<http://localhost:8080/blazeds/spring/messagebroker/amf>'" > > > When placing the "Failed: url:" URL directly in the browser, Tomcat displays the following error message: > > HTTP Status 404 - Servlet Spring MVC > Dispatcher Servlet is not available > > > I've setup all the files like James Ward instructed on his refcard, application-config.xml, web.xml and services-config.xml are all in order as far as I can see. Any ideas as to what I'm messing up? PS: I'm noticing small changes in terms of James' refcard and the stable release of the integration. Is there something that changed after the M2 release that might be biting me in the behind?
2009/06/16
[ "https://Stackoverflow.com/questions/1003823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122835/" ]
I have the same problem and I fixed it by adding backport-util-concurrent.jar and cfgatewayadapter.jar from test-drive-sample of flex-spring integration , thank you josamoto for your post , finally the integration works good . regards
If you follow along the reference card your URL would be <http://localhost:8080/dzone-server/spring/messagebroker/amf>. The context-root in the reference card is dzone-server. The key step is to make sure the URL above matches the endpoint url defined in the services-config.xml. So the matching endpoint for the above URL would be: ``` <endpoint url="http://{server.name}:{server.port}/{context.root}/spring/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/> ``` Note: this is almost the default added by creating a new flex project in Flex Builder except it has **spring** added to the endpoint URL.
17,041,268
I am having trouble submitted checkbox values and details to my database. This is my HTML: ``` <form method="get" action="check.php"> <input type="checkbox" name="checkAccount"/> <input type="hidden" name="table_name" value="masterChart" /> <input type="hidden" name="column_name" value="account" /> <p><a href='check.php'><input type="submit" class="btn btn-primary" value="Submit" /></a></p> </form> ``` This is the check.php: ``` $table = $_GET['table_name']; $column = $_GET['account']; $dbc = mysqli_connect('localhost', 'root', 'root', 'database') or die('Connection error!'); if ($value = 1) { $checkbox = "INSERT INTO login_table_display(`user`, `table`, `column`, `value`) VALUES(`:user`, '$table', '$column', `$value`)"; mysqli_query($dbc, $checkbox) or die('Database error, check!'); } header('location:index.php'); ``` As you can see above, I used variables to get other details for that checkbox to insert into the table as well. After I press submit if the checkbox is checked, this is what's seen in the url: ``` http://localhost/admin/check.php?checkAccount=on&table_name=masterChart&column_name=account ``` Any suggestions or help will be appreciated!
2013/06/11
[ "https://Stackoverflow.com/questions/17041268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2436532/" ]
The classic way to submit data is to add the value attribute to your checkboxes element in your form. On server side you have to ckeck the value for "null". ``` <input type="checkbox" name="checkAccount" value="putyourvaluehere"/> ```
// your html code shoul be like this ``` <form method="get" action="check.php"> <input type="checkbox" name="checkAccount"/> <input type="hidden" name="table_name" value="masterChart" /> <input type="hidden" name="column_name" value="account" /> <p><input type="submit" class="btn btn-primary" value="Submit" /></p> </form> <?php ``` $table = $\_GET['table\_name']; $column = $\_GET['account']; $value = isset($\_GET['checkAccount']) ? 1 : 0; $dbc = mysqli\_connect('localhost', 'root', 'root', 'database') or die('Connection error!'); if ($value == 1) { $checkbox = "INSERT INTO login\_table\_display('user', 'table', 'column', 'value') VALUES(':user', '$table', '$column', '$value')"; mysqli\_query($dbc, $checkbox) or die('Database error, check!'); } header('location:index.php'); ?>
13,177,612
In reference to my [Previous Question](https://stackoverflow.com/questions/13176567/temporary-sql-datafield/13177257#13177257) someone said in select query if I set a column data value for a table it won't going to update columns value in my table within a stored procedure, is that's right?
2012/11/01
[ "https://Stackoverflow.com/questions/13177612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1628540/" ]
No problem on **OS X 10.5** The `osascript`command on **OS X 10.4** doesn't handle UTF-8 encoded text correctly when the string contain extended ASCII character. Solution : Use the `MacRoman` encoding, `osascript` handle it without problem. ``` set myScriptAsString to quoted form of "do shell script \"touch /ü\"" do shell script "tString=$(echo " & myScriptAsString & "| iconv -t MACROMAN -f UTF8-MAC); osascript -e \"$tString\" > /dev/null 2> /dev/null & " ```
You have saved me from suicide… not for the many hours trying to use an automator Service script to process SublimeText and copying also with pbcopy… I tried it long time before. Nothing. I simply do now ``` `echo '#{s.sub(/\s+$/, '')}' | iconv -t MACROMAN -f UTF8-MAC | pbcopy` ``` Thanks! -------
40,516,231
I have a program that takes in user input for a length and a width and adds it to an array of shapes and after creating and adding each shape it prints them out after each one. BUT, if one of the values are negative (invalid) then it is not supposed to put that shape into the array (which is also not supposed to print into the updated array after each step) *Here's my output:* > > Enter 1: Add a shape > > > Enter 2: Remove a shape > > > Enter 9: Quit > > > 1 > > > What type of shape? > > > Rectangle, Triangle, or Circle? > > > Rectangle > > > Enter a length followed by a height > > > 4.0 3.0 > > > Rectangle Length: 4.0 Height: 3.0 Area: 12.0 > > > Enter 1: Add a shape > > > Enter 2: Remove a shape > > > Enter 9: Quit > > > 1 > > > What type of shape? > > > Rectangle, Triangle, or Circle? > > > Rectangle > > > Enter a length followed by a height > > > -3.0 5.0 > > > Invalid length > > > **Rectangle Length: 0.0 Height: 5.0 Area: 0.0** > > > Rectangle Length: 4.0 Height: 3.0 Area: 12.0 > > > Enter 1: Add a shape > > > Enter 2: Remove a shape > > > Enter 9: Quit > > > **That bolded portion is not supposed to be there, that is my problem** *Here's the ShapeCollection which contains my methods:* ``` private Shape[] shapes; private int index; public ShapeCollection() { this.shapes = new Shape[10]; index = 0; } public ShapeCollection(int size) { this.shapes = new Shape[size]; index = 0; } //Accessors public Shape[] getShapes() { return shapes; } //Mutators public void setShapes(Shape[] shapes) { this.shapes = shapes; } //Methods public void addShape(Shape shape) { this.sortShapes(); if (index > shapes.length - 1) { System.out.println("The shape collector is full"); } else { shapes[index] = shape; index++; } } private void sortShapes() { for (int i = 0; i < this.shapes.length; i++) { int smallestIndex = i; for (int j = i; j < this.shapes.length; j++) { if (shapes[j] != null && shapes[smallestIndex] != null) { if (shapes[j].getArea() < shapes[smallestIndex].getArea()) { smallestIndex = j; } } } if (smallestIndex != i) { Shape temp = shapes[i]; shapes[i] = shapes[smallestIndex]; shapes[smallestIndex] = temp; } } } public void removeShape(String type, double area) { this.sortShapes(); for (int i = 0; i < shapes.length; i++) { if (shapes[i].getShapeType().equalsIgnoreCase(type) && shapes[i].getArea() == area) { shapes[i] = null; index--; break; } } for (int i = 0; i < shapes.length - 1; i++) { if (shapes[i] == null && shapes[i + 1] != null) { for (int j = i; j < shapes.length - 1; j++) { shapes[j] = shapes[j + 1]; } break; } } } public void printShapes() { this.sortShapes(); for (int i = 0; i < shapes.length; i++) { if (shapes[i] != null) { System.out.println(shapes[i].getShapeType() + " " + shapes[i].toString() + " Area: " + shapes[i].getArea()); } } } ``` *Here's the Rectangle class which has the mutators and constructs:* ``` private double length; private double width; //Default construct public Rectangle() { this.length = 0.0; this.width = 0.0; } //Parameterized construct public Rectangle(double aLength, double aWidth) { this.setLength(aLength); this.setWidth(aWidth); } //Accessors public double getLength() { return this.length; } public double getWidth() { return this.width; } //Mutators public void setLength(double newLength) { if (newLength < 0) { System.out.println("Invalid length"); return; } this.length = newLength; } public void setWidth(double newWidth) { if (newWidth < 0) { System.out.println("Invalid width"); return; } this.width = newWidth; } public String getShapeType() { return "Rectangle"; } public double getArea() { return (this.getLength() * this.getWidth()); } public String toString() { return "Length: " + this.getLength() + " Height: " + this.getWidth(); } ``` *Here's the front end which you probably don't need to see:* ``` public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); boolean run = true; ShapeCollection shapes = new ShapeCollection(); System.out.println("Welcome to the Shapes collections"); while (run == true) { System.out.println("Enter 1: Add a shape\nEnter 2: Remove a shape\n" + "Enter 9: Quit"); int input = keyboard.nextInt(); if (input == 1) { System.out.println("What type of shape?\nRectangle, Triangle, or Circle?"); String type = keyboard.next(); if (type.equalsIgnoreCase("Rectangle")) { System.out.println("Enter a length followed by a height"); double length = keyboard.nextDouble(); double height = keyboard.nextDouble(); shapes.addShape(new Rectangle(length, height)); System.out.println(); shapes.printShapes(); } else if (type.equalsIgnoreCase("Triangle")) { System.out.println("Enter a base followed by a height"); double base = keyboard.nextDouble(); double height = keyboard.nextDouble(); shapes.addShape(new Triangle(base, height)); System.out.println(); shapes.printShapes(); } else if (type.equalsIgnoreCase("Circle")) { System.out.println("Enter a radius"); double radius = keyboard.nextDouble(); shapes.addShape(new Circle(radius)); System.out.println(); shapes.printShapes(); } else if (input == 2) { System.out.println("Enter the shape type"); type = keyboard.next(); System.out.println("Enter an area"); double area = keyboard.nextDouble(); shapes.removeShape(type, area); System.out.println(); shapes.printShapes(); System.out.println(); } else if (input == 9) { run = false; System.out.println("Goodbye"); } } else { System.out.println("Invalid input"); } } } ```
2016/11/09
[ "https://Stackoverflow.com/questions/40516231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7033925/" ]
The problem is, that you create a new shape and after that you are checking if the input is valid. I would suggest you check for validity on the front end. You could create a method to check: ``` public boolean isValid(double value){ if (value < 0.0) { System.out.println("Invalid Input"); return false; }else {return true;} } ```
The problem is that you are validating the input within the `Rectangle` constructor. You should validate the input *before* passing it to the constructor (and not creating the object when failing). But you could fix this broken design to a less broken one by throwing an Exception instead of just outputting the detected inconsistency. ``` /* BTW: never call public methods from a constructor !!! */ private void setWidth(double newWidth) { if (newWidth < 0) { throw new IllegalArgumentException(newWidth +" is less than 0.0!" ); } this.width = newWidth; } ``` Of cause you then have to add an `try/catch` block around your `if/else` cascade...
71,760,943
``` nc = dict(zip(nation,cap)) print("Countries and Capitals :{}".format(nc)) k = 0 while k != 5: k = input("input : ") if k == 1: break if k != 1: key = k print("The capital of {} is {} ".format(key,nc[key])) ``` #This only makes an error when I type in 1. I want it to stop the program when pressed 1. What can I do about it?
2022/04/06
[ "https://Stackoverflow.com/questions/71760943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18713105/" ]
If you also want to match `#match-this~` as a separate match, you would have to account for # while matching, as `[^~]` also matches `#` You could match what you don't want, and capture in a group what you want to keep. ``` ~[^~#]*~|((?:(?!match-this).)*match-this(?:(?!match-this)[^#~])*) ``` **Explanation** * `~[^~#]*~` Match any char except `~` or `#` between `~` * `|` Or * `(` Capture *group 1* + `(?:(?!match-this).)*` Match any char if not directly followed by \*match-this~ + `match-this` Match literally + `(?:(?!match-this)[^#~])*` Match any char except `~` or `#` if not directly followed by *match this* * `)` Close group 1 See a [regex demo](https://regex101.com/r/i8cA3Z/1) and a [Python demo](https://ideone.com/eKsjx9). Example ``` import re pattern = r"~[^~#]*~|((?:(?!match-this).)*match-this(?:(?!match-this)[^#~])*)" s = "match-this~match-this~ match-this ~match-this#match-this~match-this~match-this" res = [m for m in re.findall(pattern, s) if m] print (res) ``` Output ``` ['match-this', ' match-this ', '~match-this', '#match-this', 'match-this'] ```
For this you need [both kinds of lookarounds](https://www.regular-expressions.info/lookaround.html). This will match the 5 spots you want, and there's a reason why it only works this way and not another **and why the prefix and/or suffix can't be included**: `(?<=~)match-this(?!~)|(?<!~)match-this(?=~)|(?<!~)match-this(?!~)` Explaining lookarounds: * `(?=...)` is a positive lookahead: what comes next must match * `(?!...)` is a **negative** lookahead: what comes next must **not** match * `(?<=...)` is a positive look**behind**: what comes **before** must match * `(?<!...)` is a **negative** look**behind**: what comes **before** must **not** match Why other ways won't work: * `[^~]` is a class with negation, but it always needs one character to be there and also consumes that character for the match itself. The former is a problem for a starting text. The latter is a problem for having advanced too far, so a "don't match" character is gone already. * `(^|[^~])` would solve the first problem: either the text starts or it must be a character not matching this. We could do the same for ending texts, but this is a dead again anyway. * Only lookarounds remain, and even then we have to code all 3 variants, hence the two `|`. * As per the nature of lookarounds the character in front or behind cannot be captured. Additionally if you want to also match either a leading or a trailing character then this collides with recognizing the next potential match. It's a difference between telling the engine to "not match" a character and to tell the engine to "look out" for something without actually consuming characters and advancing the current position in the text. Also not every regex engine supports all lookarounds, so it matters where you actually want to use it. For me it works fine in *TextPad 8* and should also work fine in *PCRE* (f.e. in *PHP*). As per [regex101.com/r/CjcaWQ/1](https://regex101.com/r/CjcaWQ/1) it also works as expected by me. What irritates me: if the leading and/or trailing character of a found match is important to you, then just extract it from the input when processing all the matches, since they also come with starting positions and lengths: first match at position `0` for `10` characters means you look at input text position `-1` and `10`.
42,576,215
I'm working on a project that is using NSB, really like it but it's my first NSB solution so a bit of a noob. We have a job that needs to run every day that processes members - it is not expected to take long as the work is simple, but will potentially effect thousands of members, and in the future, perhaps tens or hundreds of thousands. Having it all happen in a single handler in one go feels wrong, but having a handler discover affected members and then fire separate events for each one sounds a bit too much in the opposite direction. I can think of a few other methods of doing it, but was wondering if there is an idiomatic way of dealing with this in NSB? Edit to clarify: I'm using `Schedule` to send a command at 3am, the handler for that will query the SQL db for a list of members who need to be processed. Processing will involve updating/inserting one or two rows per member. My question is around how to process that potentially larege list of members within NSB. Edit part 2: the job now needs to run monthly, not daily.
2017/03/03
[ "https://Stackoverflow.com/questions/42576215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1324393/" ]
I would not use a saga for this. Sagas should be lightweight and are designed for orchestration rather than performing work. They are started by messages rather than scheduled. You can achieve your ends by using the built-in [scheduler](https://docs.particular.net/nservicebus/scheduling/). I've not used it, but it looks simple enough. You could do something like: 1. configure a command message (eg StartJob) to be sent every day at 0300. 2. StartJob handler will then query the DB to get the work. Then, depending on your requirements: * If you need all the work done at once, create a single command with all the work in it, and send it to another endpoint for processing. If you use transactional MSMQ then this will succeed or fail as a unit. * If you don't care if only some work succeeds then create a command per unit of work, and dispatch to an endpoint for processing. This has the benefit that you can scale out using the [distributor](https://docs.particular.net/nservicebus/msmq/distributor/) if you needed to. > > I'm working on a project that is using NSB...We have a job that needs > to run every day... > > > Although you can use NSB for this kind of work, it's not really something I would do. There are many other approaches you could use. A SQL job or cron job would be the obvious one (and a hell of a lot quicker to develop, more performant, and simpler). Even though it does support such use cases, NServiceBus is not really designed for scheduled batch processing. I would seriously question whether you should even use NSB for this task.
A **real** NSB solution would be to get rid of the "batch" job that processes all those records in one run and find out what action(s) would cause each of these records to need processing after all. When such an action is performed you should publish an NSB event and refactor the batch job to a NSB handler that subscribes to these events so it can do the processing the moment the action is performed, running in parallel with the rest of your proces. This way there would be no need anymore for a scheduled 'start' message at 3 am, because all the work would already have been done.
120,475
I'm writing a bash script that extensively uses wget. To define all common parameters in one place I store them on variables. Here's a piece of code: ``` useragent='--user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"' cookies_file="/tmp/wget-cookies.txt" save_cookies_cmd="--save-cookies $cookies_file --keep-session-cookies" load_cookies_cmd="--load-cookies $cookies_file --keep-session-cookies" function mywget { log "#!!!!!!!!!# WGET #!!!!!!!!!# wget $quiet $useragent $load_cookies_cmd $@" wget $useragent $load_cookies_cmd "$@" } ``` Saddly isn't working. Somehow I'm missing the right way to store parameters on variables $useragent, $save\_cookies\_cmd, $load\_cookies\_cmd and caling wget passing these vars as parameters. I want the result commandline as this: ``` wget --user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0" --load-cookies /tmp/wget-cookies.txt --keep-session-cookies http://mysite.local/myfile.php ``` --- **EDIT:** My final solution: In the end my script is correctly working with this: ``` useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0" useragent_cmd="--user-agent=$useragent" cookies_file="/tmp/wget-cookies.txt" save_cookies_cmd="--save-cookies $cookies_file --keep-session-cookies" load_cookies_cmd="--load-cookies $cookies_file --keep-session-cookies" function mywget { log "#!!!!!!!!!# WGET #!!!!!!!!!# wget $load_cookies_cmd $useragent_cmd $@" wget $load_cookies_cmd "$useragent_cmd" "$@" } ``` Thanks for all your responses.
2014/03/19
[ "https://unix.stackexchange.com/questions/120475", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/63141/" ]
<http://mywiki.wooledge.org/BashFAQ/050> ``` user_agent='--user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"' cookies_file="/tmp/wget-cookies.txt" save_cookies_opts=( --save-cookies "$cookies_file" --keep-session-cookies ) load_cookies_opts=( --load-cookies "$cookies_file" --keep-session-cookies ) function mywget { log "#!!!!!!!!!# WGET #!!!!!!!!!# wget $quiet $useragent $load_cookies_cmd $@" wget "$user_agent" "${load_cookies_opts[@]}" "$@" } ``` Note that in the wget call , `"$user_agent"` is quoted. This is crucial.
``` mywget() ( echo log "wget $quiet \ userstring=${userstring:-unset} \ cookies=${cookies:-no} $@" echo wget ${userstring:+--useragent="$userstring"} \ ${cookies:+--${cookies}-cookies \ "$cookies_file" --keep-session-cookies} "$@" ) <<-PARAMS ${DQ=$(printf \\042)} ${NL= } ${userstring="${DQ}Mozilla/5.0 \ (Windows NT 6.1; WOW64; rv:27.0) \ Gecko/20100101 Firefox/27.0${DQ}"} ${cookies_file="/tmp/wget-cookies.txt"} ${cookies=save} PARAMS ``` Please forgive me, but I've taken the liberty of *`parameterizing`* your function. Because the values in *`PARAMS`* will *only* set an unset variable, you can override their values very easily - it allows you to set sane defaults and yet still change values per function call as you like. For instance, in the above function, I've set all values to *`echo`* and here's the output when run as is: ``` log wget userstring="Mozilla/5.0 \ (Windows NT 6.1; WOW64; rv:27.0) \ Gecko/20100101 Firefox/27.0" \ cookies=save wget --useragent="Mozilla/5.0 \ (Windows NT 6.1; WOW64; rv:27.0) \ Gecko/20100101 Firefox/27.0" \ --save-cookies /tmp/wget-cookies.txt \ --keep-session-cookies ``` But if I set *`"$userstring"`* to *`NULL`*: ``` userstring= mywget log wget userstring=unset cookies=save wget --save-cookies /tmp/wget-cookies.txt --keep-session-cookies ``` Or: ``` cookies=load cookies_file=/some/other/cookie.file mywget log wget userstring="Mozilla/5.0 \ (Windows NT 6.1; WOW64; rv:27.0) \ Gecko/20100101 Firefox/27.0" \ cookies=load wget --useragent="Mozilla/5.0 \ (Windows NT 6.1; WOW64; rv:27.0) \ Gecko/20100101 Firefox/27.0" \ --load-cookies /some/other/cookie.file \ --keep-session-cookies ``` Or: ``` cookies= userstring= mywget log wget userstring=unset cookies=no wget ``` I've written more on *`parameter expansion`* [here](https://unix.stackexchange.com/questions/60688/how-to-defer-variable-expansion/120142#120142) and [here](https://unix.stackexchange.com/questions/81457/trapping-errors-in-command-substitution-using-o-errtrace-ie-set-e/120008#120008).
16,697,794
I have the below code: ``` List<Check<String, String>> listAdd = new ArrayList<Check<String, String>>(); for (list1<String, String> h : list1_a) { for (list2<String, String> s : list2_a) { if (condition) { //if(!listAdd.contains(Check(h.getString(),s.getString()) listAdd.add(new Check(h.getString(),s.getString())); } } } ``` im unable to understand how to use contains when there is a list within a list. Please help.Thanks
2013/05/22
[ "https://Stackoverflow.com/questions/16697794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455116/" ]
Try this: ``` if (condition) { Check c = new Check(h.getString(), s.getString()); if (!list.contains(c)) { list.add(c); } } ``` Make sure you have `equals()` and `hashCode()` methods implemented in the `Check` class. Another approach is to switch the `java.util.List` with some implementation of the `java.util.Set` interface. The `java.util.Set` subclasses support unique objects within, so you will no longer have to worry about whether some object is present is your collection or not.
try this in place of `//if(!listAdd.contains(Check(h.getString(),s.getString());` ``` if(!listAdd.contains(new Check(h.getString(),s.getString()); ```
99,582
I have a file that contains 4n lines. Here is an excerpt from it containing 8 lines ``` 6115 8.88443 6116 6.61875 6118 16.5949 6117 19.4129 6116 6.619 6117 16.5979 6118 19.4111 6115 8.88433 ``` What I want to do is sort a block, where each block consists of 4 lines based on the first column. The output for the excerpt should look as shown below. ``` 6115 8.88443 6116 6.61875 6117 19.4129 6118 16.5949 6115 8.88433 6116 6.619 6117 16.5979 6118 19.4111 ```
2013/11/09
[ "https://unix.stackexchange.com/questions/99582", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/51025/" ]
Here are some "pure" `awk` solutions: If the indexes are always the same incrementing integer sequence (6115-6119), as in your sample-data, you can use an algorithmic "shortcut": ``` awk '{a[$1]=$0} !(NR%4){for(i=6115;i<6119;print a[i++]);}' ``` This does * Add all lines to the array `a`, distributed at index positions 6115-6119 * On every 4th line (`!(NR%4)`) , loop through the array contents to print in the desired order. --- If your numeric indexes are always the four same ones, but not an incrementing integer sequence, you'll have to sort: ``` awk '{a[$1]=$0} !(NR%4){asort(a,b); for(i=1;i<5;print b[i++]);}' ``` Note: This is with GNU awk, others may not support `asort`. --- If every block-of-four could have different numeric IDs: ``` awk '{a[$1]=$0} !(NR%4){asort(a); for(i=1;i<5;print a[i++]); delete a}' ``` Note: TIL from [@Gilles self-answer(+2) this use of `delete` is not (yet) POSIX, but universally supported](https://unix.stackexchange.com/questions/147957/delete-an-array-in-awk). --- A version with the correct™ use of `delete`: ``` awk '{a[$1]=$0} !(NR%4){asort(a); for(i=1;i<5;delete a[i++]){print a[i]}}' ``` A version without delete, using more memory and dimensions: ``` awk '{a[n][$1]=$0} !(NR%4){asort(a[n]); for(i=1;i<5;print a[n][i++]); n++} ```
You can get a clean solution with R. If the table above is in a file called "table.txt", then perform the following steps. The desired result will be in the file "tableout.txt". ``` > x = read.table("table.txt", col.names=c("a", "b")) > x a b 1 6115 8.88443 2 6116 6.61875 3 6118 16.59490 4 6117 19.41290 5 6116 6.61900 6 6117 16.59790 7 6118 19.41110 8 6115 8.88433 > x["index"] = c(rep(1, 4), rep(2, 4)) > x a b index 1 6115 8.88443 1 2 6116 6.61875 1 3 6118 16.59490 1 4 6117 19.41290 1 5 6116 6.61900 2 6 6117 16.59790 2 7 6118 19.41110 2 8 6115 8.88433 2 > xord = x[with(x, order(index, a)), ] > xord a b index 1 6115 8.88443 1 2 6116 6.61875 1 4 6117 19.41290 1 3 6118 16.59490 1 8 6115 8.88433 2 5 6116 6.61900 2 6 6117 16.59790 2 7 6118 19.41110 2 > write.table(xord[,1:2], "tableout.txt", row.names=FALSE, col.names=FALSE) ``` See also [How to sort a dataframe by column(s) in R](https://stackoverflow.com/q/1296646/350713).
14,004,546
how come the i.X and i.Y are not being updated in the fb.Entities collection? am I doing something wrong? I'm learning, Is this the correct way to update values of something in a vector? ``` for (Entity i : fb.Entities) { if (i.Serial == SerialID) { i.X = (USHORT)((data[5] << 8) + data[6]); i.Y = (USHORT)((data[7] << 8) + data[8]); break; } } ```
2012/12/22
[ "https://Stackoverflow.com/questions/14004546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1749335/" ]
If you want your current (local) work stay on top you do ``` git fetch git rebase origin/develop ``` or ``` git pull --rebase ``` Merging in the code i.e. pull when remote and local has changed, can have the effect that your local work is placed in the wrong order and is overwritten by remote changes. So if you want to just grab the remote you should do pull and fetch if you have done some work on your local. Just to keep it simple. But most of time the pull will work if you are lucky. This is what I have understood by doing some more research. However I'm not sure until I try a little experiment to verify. I think the best solution is to use git pull --rebase most of the time, makes more sense somehow. You could change the default behavior of git pull as I understand it but that can be dangerous as you might forget about it and confuse yourself even more.
Well, [`git pull`](http://git-scm.com/docs/git-pull) does [`git fetch`](http://git-scm.com/docs/git-fetch) followed by [`git merge`](http://git-scm.com/docs/git-merge). So, if you wish to automatically merge the `pull`ed repository, then you have no need for `git fetch`.
12,717,298
I have a div width at 1000px and height at 100% but when i try and make anothe div next to it (on the right) with the following properties: ``` margin-right: 20%; border: 1px solid; float: right; height: 100%; width: 10px; ``` The div appears at the bottom of where the main container div ends. What is wrong?
2012/10/03
[ "https://Stackoverflow.com/questions/12717298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1712995/" ]
You can assign float:left; or display:inline-block; to the first div.
It's somewhat confusing, but place your second div before your first in your code, then the float will affect it. Right now, the first div is display:block, which pushes down the next line. right now it's : ``` <div id="1"> <div id="2" style="float:right"> ``` change it to ``` <div id="2" style="float:right"> <div id="1"> ```
18,932
Me and my friends are going to Japan 2 weeks from now. We'll stay for 4 days in Tokyo, overnight in Hakone, 3 days in Kyoto (with a side visit to Nara) and 2 days in Osaka (Summer Sonic!!). So my question is, what is the most cost effective way to get around in these places? So I found about the [JR Pass](http://jrp.japan-rail-pass.com/common-questions/) which I find a bit pricey but it seems like I would be able to use all train services, including the Shinkansen. And that certainly would be convenient to take the Shinkansen from Tokyo to Kyoto. But I don't think it will also allow me to access buses, can it? Are there any other alternatives besides JR Pass? Or is it cheaper to just get around by bus and just buy single journey tickets when travelling between cities?
2013/07/17
[ "https://travel.stackexchange.com/questions/18932", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/2261/" ]
* [1,750 yen from Tokyo to Hakone](http://transit.loco.yahoo.co.jp/search/result?flatlon=&from=%E6%9D%B1%E4%BA%AC&tlatlon=&to=%E7%AE%B1%E6%A0%B9%E6%B9%AF%E6%9C%AC&via=&expkind=1&ym=201307&d=26&datepicker=&hh=10&m1=2&m2=0&type=1&ws=2&s=0&x=54&y=10&kw=%E7%AE%B1%E6%A0%B9%E6%B9%AF%E6%9C%AC) * [14,280 yen from Hakone to Kyoto](http://transit.loco.yahoo.co.jp/search/result?flatlon=&from=%E7%AE%B1%E6%A0%B9%E6%B9%AF%E6%9C%AC&tlatlon=&to=%E4%BA%AC%E9%83%BD&via=&shin=1&ex=1&al=1&hb=1&lb=1&sr=1&expkind=1&ym=201307&d=26&datepicker=&hh=10&m1=2&m2=0&type=1&ws=2&s=0&x=103&y=2&kw=%E4%BA%AC%E9%83%BD) * [2,000 yen for a Kyoto unlimited 2-day pass (1,200 for one day)](http://www.city.kyoto.jp/koho/eng/access/transport.html) * [610 yen x 2 for round trip from Kyoto-Nara](http://transit.loco.yahoo.co.jp/search/result?flatlon=&from=%E4%BA%AC%E9%83%BD&tlatlon=&to=%E5%A5%88%E8%89%AF&via=&expkind=1&ym=201307&d=26&datepicker=&hh=10&m1=2&m2=0&type=1&ws=2&s=0&x=0&y=0&kw=%E5%A5%88%E8%89%AF) * [390 yen from Kyoto to Osaka](http://transit.loco.yahoo.co.jp/search/result?flatlon=&from=%E6%B2%B3%E5%8E%9F%E7%94%BA&tlatlon=&to=%E6%A2%85%E7%94%B0&via=&expkind=1&ym=201307&d=26&datepicker=&hh=10&m1=2&m2=0&type=1&ws=2&s=0&x=77&y=25&kw=%E6%A2%85%E7%94%B0) The [Japan Rail Pass is 28,300](http://en.wikipedia.org/wiki/Japan_Rail_Pass) for 7 days. If you are going round trip to Tokyo-Kansai within a week it is more than worth it. If you are going one way (or will travel more than 7 days apart) it probably isn't. JR will take you from Tokyo to Hakone, Hakone/Tokyo to Kyoto, Kyoto to Nara, Nara to Osaka, Kyoto to Osaka, and Osaka to Tokyo. Within Kyoto, within Osaka, and within Tokyo you will likely have to pay for local subway or buses (and will incur those costs anyway).
[Current price in JPY is ¥29110](http://www.jrailpass.com/) for a standard 7-day pass. Anyway it is cheaper than 2 individual long-distance shinkansen trips.
170,291
I am attempting to replace JS buttons with quick actions. These button simply call a web service method and alert the result and **need no user interaction**. With quick action a modal always seems to appear and this is not desirable. I am calling the Webservice method in the `doInit` function and firing a toast event with the results and have no need for the modal popup. Seems an oversight maybe? But is there a way to accomplish this without the modal to closely mimic the JS button functionality? Ideally we could show the spinner without the modal Right now I am simply calling ``` $A.get("e.force:closeQuickAction").fire(); ``` at the end of the doInit but it is not the most ideal in way of a UI to do this IMHO as it flashes the modal on the screen briefly.
2017/04/17
[ "https://salesforce.stackexchange.com/questions/170291", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/3996/" ]
Just add the below code in your component so that it doesn't show up the modal when you click on the Quick action button ``` <aura:html tag="style"> .slds-backdrop { background: rgba(43, 40, 38, 0) !important; } .slds-fade-in-open { display:none !important; } </aura:html> ```
Add this styling on the component. ``` <aura:html tag="style"> .slds-backdrop { background: rgba(43, 40, 38, 0) !important; visibility: hidden !important; } .slds-fade-in-open { display:none !important; } .slds-modal { display: none; visibility: hidden !important; } </aura:html> ```
32,424
Wiktionary says that 教, read as きょお means "to teach". However, I have read that in dictionaries, al forms end in "-う" and not in "-お". Why is 教 different? EDIT: Yes, it says that in English wiktionary. First, the reading they give is "kyoo". Second, they define it as "1.to teach; teachings"
2016/02/24
[ "https://japanese.stackexchange.com/questions/32424", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/13658/" ]
This is a serious misunderstanding, I'm afraid. きょう is just one of the several readings ([読]{よ}み[方]{かた}) of 教. It's a so-called 'sound-reading' [音読み]{おんよみ}, which are Japanese renderings of Chinese speech. You actually misquoted this particular reading; it's きょ**う** not きょ**お**, although that would be pronounced the same way. But as far as Japanese verbs go, that's irrelevant; you have to look for the 'explanatory reading' [訓読み]{くんよみ}, which gives you a Japanese word that has (more or less) the same meaning as the original Chinese word. Wiktionary has the following to say: ### Readings ``` Goon: きょう (kyō) < けう (keu) Kan’on: こう (kō) < かう (kau) (non-Jōyō reading) Kun: おしえる (教える, oshieru), おしえ (教え, oshie), おそわる (教わる, osowaru) ``` As you can see, all of the multiple kun readings do end in -u. Only these forms may be conjugated.
All the Kun endings do end in "u". I believe it is only necessary that the Kun end in U 教 common Kun おし.えるoshi.eru おそ.わるoso.waru teach;  faith;  doctrine Radical: 攵 (rap). Strokes: 11画. Elements: 子⺹攵. Pinyin: jiào / jiāo. Hangul: 교 [gyo]. Nanori: のり / ひさ. Jōyō Kanji 2nd Grade. JLPT N4. Example compounds: キョウ 教条主義【きょうじょうしゅぎ】dogmatism 聖教【せいきょう】sacred teachings; Confucianism; Christianity 教化【きょうか】culture; education; civilization; civilisation おしえる 教える【おしえる】to teach; to inform; to instruct 英語を教える【えいごをおしえる】to teach English おそわる 教わる【おそわる】to be taught ▸ Codes and indices ▸ Find words containing 教 / beginning with 教 / ending with 教 / 教\_ / \_教
47,594,015
How can I create library bundle on Symfony 4? In Symfony 3 I use this command: `php bin/console generate:bundle` but in new version not working. And is possible use bundles like Symfony 3, for example, i have blog bundle and telegram bot bundle if not possible how to simulate in Symfony 4?
2017/12/01
[ "https://Stackoverflow.com/questions/47594015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6157616/" ]
Fabien Potencier said in the Symfony 4 best practices blog post "Bundle-less applications is just one of the best practices changes for Symfony 4". You must not generate new bundles, you can use default "App" bundle for your whole project. You can look at this url for blog post about subject [Symfony 4: Monolith vs Micro](http://fabien.potencier.org/symfony4-monolith-vs-micro.html)
Start by creating a `src/Acme/TestBundle/` directory and adding a new file called `AcmeTestBundle.php`: ```php // src/Acme/TestBundle/AcmeTestBundle.php namespace App\Acme\TestBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AcmeTestBundle extends Bundle { } ``` After add this line in config/bundles.php : ```php App\Acme\TestBundle\AcmeTestBundle::class => ['all' => true], ```
32,228,882
I am trying to add ✔ character (i.e Heavy Check Mark) in the text box. If I hardcode it as a value to the textbox it does show proper check mark in the browser. However If I try to update the value dynamically to "✔" it does not reflect in the browser. I tried ``` 1. $('#txtBox').val(result.value); 2. $('#txtBox').val('&#10004;'); 3. $('#txtBox').attr('value',result.value); 4. $('#txtBox').attr('value','&#10004;'); ``` All these combinations. Even then It do not show check mark if I try to show the check mark dynamically. Please help
2015/08/26
[ "https://Stackoverflow.com/questions/32228882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2186227/" ]
One way to do this is to directly add ✔ character. ```js $('#addChkBox').click(function () { $('#txtBox').val('✔'); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="txtBox"/> <button id="addChkBox">Add CheckBox</button> ```
Try this instead: ``` $('#txtBox').append('&#10004;'); ``` I'm not sure how you're defining `result.value`, so I can't speak to how you'd use this. Fiddle: <http://jsfiddle.net/oe16xdbr/2/>
24,412,550
I have the following table: ``` create table x ( id integer, property integer ); ``` I need to efficiently run queries that test multiple property values for a given id. For instance, I may want a query that gets all ids with a property satisfying the condition: *1 and not (2 or 3 or 4 or 5)*. If all my properties were in boolean columns ('t1' = true if property value 1 exists for id, false otherwise, etc...), then I can simply run this very fast query (assume y were such a table): ``` select * from y where t1 and not (t2 or t3 or t4 or t5); ``` Unfortunately, I have thousands of properties, so this won't do. Furthermore, there's no rhyme or reason as to the queries, so while I can bundle groups of properties into conceptual relations, the query boundaries don't respect that. Additionally, these queries are (indirectly) determined by the user, so creating views in anticipation of them won't help. Finally, we'll constantly be adding data sets with new properties whose relations may be new, vague or cross-cutting, meaning that trying to create tables of relations may become a maintenance nightmare. Hence why I chose the original schema. To try to accomplish my queries, I tried first creating a pivot on the fields involved in the query, then querying that: ``` create table pivot as ( select id, max(if(property=1,true,false)) as 't1', max(if(property=2,true,false)) as 't2', max(if(property=3,true,false)) as 't3', max(if(property=4,true,false)) as 't4', max(if(property=5,true,false)) as 't5' from x); select * from pivot where t1 and not (t2 or t3 or t4 or t5); ``` However, this is very slow. In fact, it's slower than an un-optimized home-brewed solution. I know I can produce complex queries with sub-queries, but a limited test suggested that performance would be even worse (unless I structured the query incorrectly). What can I do to speed up my queries?
2014/06/25
[ "https://Stackoverflow.com/questions/24412550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2855582/" ]
I assume that `id` is not unique and an existing record `(some_id, property_id)` means that the property is `on`. First, I would notice that `I need to efficiently run queries that test multiple property values for a given id` and `I may want a query that gets all ids with a property satisfying the condition: 1 and not (2 or 3 or 4 or 5)` may lead to completely different queries. But here is my idea. Some more assumptions: * there is always a positive condition that cuts away a significant part of ids (otherwise I would join several properties into an extra one that becomes such a condition) * any pair `(id, property)` is unique (an you even have the corresponding UNIQUE index) Now, if you have an index on `(property, id)`, then the following query will take all matching `ids` from the covering index (that is quickly): ``` SELECT id FROM t1 WHERE property = 150; ``` If this query leads to a significantly smaller result set than the whole table, you can afford to make another fast correlated subquery for another property that will significantly decrease the result set. This subquery will require another covering index `(id, property)` and the corresponding UNIQUE index is what it needs: ``` SELECT id FROM t1 WHERE property = 150 AND NOT EXISTS ( SELECT 1 FROM t2 WHERE t2.id = t1.id AND t2.property = 130 ) AND NOT EXISTS ( SELECT 1 FROM t2 WHERE t2.id = t1.id AND t2.property = 90 ); ``` If an earlier correlated subquery results to false, all the following subqueries will not be executed for the row. That is why the order is crucial. You will need to play with the properties order, and probably hardcode that in the code that executes the query. UPD: then, I afraid, you do not have much choice. The best you can do is to walk through the index in a single pass and compute what you need. The speed of the query then will mainly depend on the number of rows in your table. So, again assuming you have the UNIQUE index on (id, property), you can write something like: ``` SELECT id FROM t1 GROUP BY id HAVING COUNT(IF(property=150, 1, NULL)) AND NOT COUNT(IF(property=130, 1, NULL)) AND NOT COUNT(IF(property=90, 1, NULL)); ```
Have you considered building a table consisting of (id, propertybin), that gets populated as follows: ``` INSERT LookupTable (id, propertybin) SELECT id, sum(1 << property) FROM MyTable GROUP BY id ``` Now, propertybin holds a binary value for each ID, where each bit represents whether a property from 0 to 63 exists in MyTable. I realise you have more than 64 properties, but I think this idea could be expanded upon to hold more properties - since you now have 1 column able to hold information about 64 properties, you would "only" need, say 100 such columns to hold information of 6400 properties. Now, to find all id's satisfying a certain condition, you would use bitwise logic. For example, to find all id's having property 0, but not 1, 2, 3 or 4, use: ``` SELECT id FROM LookupTable WHERE ((propertybin ^ 0x1E) & 0x1F) = 0x1F ``` Here, we use the exclusive-OR bitwise operator `^` together with the value 0x1E = binary 11110, to filter the not-criteria. We use the AND bitwise operator `&` with the value 0x1F = binary 11111, to indicate that we are only interested in the first 5 bits. Alternatively, a sufficiently large column of type VARBINARY could possibly be used, eliminating the limitation of 64 properties per column. However, I'm unsure of the possibilities offered by MySQL to filter certain bits in a VARBINARY value.
22,466,714
Basically I know how to add one row to an external mysql database using android. Now im looking to add multiple rows at once. Heres my code so far. PHP Script ``` <?php $host="db4free.net"; //replace with database hostname $username="xxxxxx"; //replace with database username $password="xxxxxxx"; //replace with database password $db_name="xxxxxxx"; //replace with database name $con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); /* Get the value in the whichfunction parameter sent from the android application which will determine the fucntion to call. */ $getFunctionToCall = $_POST['whichfunction']; /* Depending on the value of the whichfunction parameter switch to call different function */ switch ($getFunctionToCall){ case "AddUser": echo AddUser($_POST['name'],$_POST['password']); break; } /* Function to add user to the user table */ function AddUser($name,$password){ $sql = "insert into users(name,password) values('$name','$password')"; if(mysql_query($sql)){ return 1; // Return 1 for success; }else{ return 2;// Return 2 for database error; } } ?> ``` Android Method ``` protected void SendToPhpFile() { ArrayList<NameValuePair> pp = new ArrayList<NameValuePair>(); pp.add(new BasicNameValuePair("whichfunction", "AddUser")); String[] names = {"David","Jimmy","Shane"}; String[] passwords = {"mypass1","mypass2","mypass3"}; for (int i=0;i<names.length;i++){ pp.add(new BasicNameValuePair("names[]", String.valueOf(names[i]))); pp.add(new BasicNameValuePair("passwords[]", String.valueOf(passwords[i]))); } try{ status = ""; status = CustomHttpClient.executeHttpPost(ConnectBase.link, pp); String res=status.toString(); res= res.replaceAll("\\s+",""); /* Depending on value you return if insert was successful */ if(res.equals("1")){ Toaster("Data successfully added."); }else{ Toaster(status); } }catch(Exception e){ Toaster("Data successfully added: " + e.toString()); } } ``` So I think I have the android size more or less sorted but I'm not 100%. If you guys could come up with a solution to how I've started that would be great. I've got zero experience with php so don't really know where to start when adding more than 1 row. Thank you
2014/03/17
[ "https://Stackoverflow.com/questions/22466714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2205771/" ]
Something like this maybe? ``` INSERT INTO table (name, password ) VALUES ('Name1', 'Password1'), ('Name2', 'Password2'),('Name3', 'Password3'), ('Name4', 'Password4') ```
Using **mysqli** you can not only **avoid deprecated mysql functions** but you can easily loop over insert values using prepared statements. [Referencing](http://ca1.php.net/manual/en/mysqli.prepare.php) In the following example we will be inserting usernames and passwords into the database in a safe and efficient way. ``` $x = array(array('bob','mypasswordlol'),array('your_mother','knitting5000')); $stmt = $mysqli->prepare("INSERT INTO table (`username`, `password`) VALUES (?, ?)"); foreach ( $x AS $k => $value) { $stmt->bind_param($stmt, "ss", $value[0], $value[1]); $stmt->execute(); } // close your connection ``` Hopefully this helps. Prepared statements are the bees knees when it comes to mysqli. It will help you prevent database injection and increase performance as well!
589,389
What is the correct way to declare and use a FILE \* pointer in C/C++? Should it be declared global or local? Can somebody show a good example?
2009/02/26
[ "https://Stackoverflow.com/questions/589389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It doesn't matter at all whether it's local or global. The scope of the file pointer has nothing to do with its use. In general, it's a good idea to avoid global variables as much as possible. Here's a sample showing how to copy from `input.txt` to `output.txt`: ``` #include <stdio.h> int main(void) { FILE *fin, *fout; int c; // Open both files, fail fast if either no good. if ((fin = fopen("input.txt", "r")) == NULL) { fprintf(stderr, "Cannot read from input.txt"); return 1; } if ((fout = fopen("output.txt", "w")) == NULL) { fprintf(stderr, "Cannot write to output.txt"); fclose(fin); return 1; } // Transfer character by character. while ((c = fgetc(fin)) >= 0) { fputc (c, fout); } // Close both files and exit. fclose(fin); fclose(fout); return 0; } ```
It's just an ordinary pointer like any other. ``` FILE *CreateLogFile() { return fopen("logfile.txt","w"); // allocates a FILE object and returns a pointer to it } void UsefulFunction() { FILE *pLog = CreateLogFile(); // it's safe to return a pointer from a func int resultsOfWork = DoSomeWork(); fprintf( pLog, "Work did %d\n", resultsOfWork ); // you can pass it to other functions fclose( pLog ); // just be sure to clean it up when you are done with fclose() pLog = NULL; // and it's a good idea to overwrite the pointer afterwards // so it's obvious you deleted what it points to } ```
172,802
The best way to prove that a file F existed before time t and has not been altered since then would be to post the cryptographic hash h=H(F) of the file F on the Bitcoin blockchain. When the cryptographic hash h=H(F) of the file F has been posted on a blockchain, we say that the file F has been *timestamped*. Since the cryptographic hash h cannot be changed without altering the file F, and since it will be exceedingly difficult to change the block containing h on the Bitcoin blockchain after time t, one should consider the hash h posted on the Bitcoin blockchain as a proof that the file F existed before time t and has not been altered after time t. Should academic institutions require faculty to post timestamps of all their students assignments on blockchains? My idea is for the academic institution to require faculty to post a timestamp of each assignment as soon as the assignment is turned in and also after the assignment has been graded. Timestamps are useful for promoting academic integrity. If posting timestamps for every assignment is too rigorous, then should academic institutions require faculty to post timestamps in a more limited context such as for finals, theses, or exit exams only? I personally think that posting timestamps is a good idea, but there may be some unforeseen consequences to this proposal, so I am looking for reasons why academic institution should not require timestamps of assignments to be posted on blockchains. **Advantages of secure timestamps:** 1. Timestamps are private. The timestamp h by itself gives no information about the file F being timestamped. 2. Timestamps are inexpensive. The transaction fee for posting something on the Bitcoin blockchain is currently between 2 and 3 dollars. However, it is just as effective to post the timestamps on some other blockchain like the Litecoin blockchain with lower transaction fees since the hash of the Litecoin blockchain will be periodically posted on the Bitcoin blockchain. One can reduce the fees much further by bundling many timestamps together into one transaction using Merkle roots. By using Merkle roots this way, one can post an arbitrary amount of timestamps on the blockchain using only one transaction without compromising the privacy of the data being timestamped. The cost of posting timestamps on blockchains should therefore be negligible. 3. Timestamps are censorship resistant. Since people will not be able to know the information being timestamped in the first place, it is not possible for people to censor the information being timestamped in any way. **Why secure timestamps are needed for assignments:** Timestamping assignments will create an immutable paper trail that will make it easier for instructors to maintain academic integrity without giving into the students' demands. Consider the following scenarios: 1. Suppose that students are given an examination, but at the end of class certain students beg for extra time and are quite adamant about needing extra time. If the assignments were not timestamped after being turned in, then the instructor would be more likely to give in and give the few students extra time. If the assignments were timestamped on a blockchain, then the instructor would not be able to give certain students extra time without creating verifiable a paper trail. Similarly, if students ask for an extension for an assignment that is already past due, then such an extension could not be given without creating a timestamped paper trail. 2. Suppose that a student asks to have a grade for an assignment changed. If the assignment was graded incorrectly, then the grader can change the grade and submit a new timestamp that has a memo stating that the grade was changed as well as the reason why the grade was changed. The same protocol applies in case the task was poorly worded or something that the students did not cover in class. On the other hand, if the assignment was graded correctly but the student simply wants points for an incorrect answer (or more partial credit), then it would be hard to write a timestamped memo that justifies the grade change. 3. Suppose that some students obtain a copy of the examination before the examination was given. Then students could themselves post a timestamp of this examination before it is given, and this timestamp will prove that students have obtained a copy of the examination early. There are other scenarios in which secure timestamps would be helpful for ensuring honesty and fairness for everyone. It therefore seems as if timestamping assignments will be a simple solution (though not a perfect solution) for several of these issues. **Possible pitfalls:** Here are a few reasons why it may be a bad idea to post timestamps of assignments on blockchains, but these reasons are unconvincing to me. 1. Hacks could compromise student's privacy. This is a problem, but I am not convinced that this problem is bad enough for the institutions to abandon the practice of posting timestamps on blockchains. A better solution would be to simply have better cybersecurity. 2. Posting the timestamps on blockchains will take a little bit of work. I think it is worth the small amount of work in order to help maintain academic integrity. 3. Institutions may think that they already have enough academic integrity and that this proposal is unnecessary. I am not convinced that this is the case.
2021/07/30
[ "https://academia.stackexchange.com/questions/172802", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/38616/" ]
There is existing software (e.g. moodle, gradescope, etc) that can handle timestamps without making people setup a bitcoin wallet, buy bitcoin, and make non-standard transactions ('posting').
I suspect that the main misunderstanding in this question is the assumption that what the student handed in has to change when the grade changes. Changing the material after it has been handed in would be clear fraud and there is no reason for lecturer to go along with that unless there is real bribery. This is pretty rare, mainly because students are way too poor to offer a bribe big enough to compensate for the risk the lecturer is running. However, it is quite common for grades to change. There is always a bit of room for interpretation, especially when it comes to partial points. Moreover, the key can be adjusted. I do that when I find out that a substantial portion of students misunderstood the question, so the answers to that question no longer measure what I want to test. So changing to content after it is handed in is not an issue. We don't need some machinery to prevent us from doing that, because too rare and thus a non problem. It won't prevent fraud, because there plenty of other ways to change the grade. If I were planning fraud (and I am not) I would use those other methods anyhow because they are just easier.
5,433,977
I'm pretty sure that this is a no-brainer but I didn't find any snippet of sample code. What's the best way to insert line breaks (aka the good ol' br/)? As far as I can see if I put a "br" at the beginning of an empty line, it is rendered as `<br/>` but if I have to show several lines of text, the resulting code is quite verbose: ``` .poem p | Si chiamava Tatiana, la sorella… br | Noi siamo i primi, almeno lo crediamo br | Che un tale nome arditamente nella br | Cornice d’un romanzo introduciamo. br | E che dunque? E’ piacevole, sonoro. br | Lo so che a molti privo di decoro br | Apparirà, già fuori moda, e degno br | Piuttosto d’un ancella, certo segno, br | confessiamolo pur senza paura, br | di quanto s’è noialtri al gusto avversi br | nei nostri nomi (a non parlar di versi). |br br | Credemmo conquistare la cultura, br | e non ne abbiamo preso, in conclusione, br | che la ricerca dell’affettazione. ``` Is there a better way to solve this? (incidentally I'm asking for the same thing with the image tag...)
2011/03/25
[ "https://Stackoverflow.com/questions/5433977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162293/" ]
The cleanest and easiest solution is to use the style attribute `white-space: pre;` eg: ``` .poem p(style='white-space:pre;') | Si chiamava Tatiana, la sorella… | Noi siamo i primi, almeno lo crediamo | Che un tale nome arditamente nella | Cornice d’un romanzo introduciamo. | E che dunque? E’ piacevole, sonoro. | Lo so che a molti privo di decoro | Apparirà, già fuori moda, e degno | Piuttosto d’un ancella, certo segno, | confessiamolo pur senza paura, | di quanto s’è noialtri al gusto avversi | nei nostri nomi (a non parlar di versi). |br | Credemmo conquistare la cultura, | e non ne abbiamo preso, in conclusione, | che la ricerca dell’affettazione. ```
I was generating a SASS file from PUG template and I needed `each` item on a new line. This is what worked for me: ``` //- custom-variables.pug //- GENERATE COLORS each color, idx in colors | #{idx}: #{color}; | ``` ```js const pug = require("pug"); const colors = { $primary: "#0074d9", $secondary: "#ff4136", $green: "green", }; // Compile the source code const compiledFunction = pug.compileFile("./scripts/custom-variables.pug"); console.log(compiledFunction({ colors })); // outputs: /* $primary: #0074d9; $secondary: #ff4136; $green: green; */ ```
123,028
I'd like to know whether it is okay to start a letter like this: > > Dear Bob, > > > Hi, Bob... > > > I've been doing this but not sure it is totally acceptable. Isn't "Hi, Bob" somewhat redundant as there is already "Dear Bob"? Sure, there are many ways to start a letter but what I'd like to know is if it is appropriate.
2017/03/20
[ "https://ell.stackexchange.com/questions/123028", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/10768/" ]
"Dear Mr. Jones" is a formal opening, so people sometimes begin the body with "Hi" to transition to a friendlier tone. "Dear Bob" is informal, so "Hi" would stand out as redundant. However, it would never seem appropriate to repeat the person's name in the first two phrases. Salespeople are (or were) trained to make frequent use of the person's name on the theory that it established some form of rapport. However, the practice triggers people's "salesperson radar" because it usually seems uncommon and unnatural in normal speech. So repeating the person's name in the opening of a letter would tend to be off-putting, the opposite of what you want.
Maybe, just maybe, if the "Dear" part is so long or formal or must follow a particular format that it actually ends up as its own section of the letter: If you must format your letter to open with a very formal salutation, in order to meet guidelines from your workplace/university/organisation, for example: *"Dear Sir Henry Guffington the third, Duke of Australiama, Order of the golden Kangaroo, PhD, GSSE,Golden swimming certificate, Silver swimming certificate",* But you are actually quite close to the person I could possibly imagine following that up with: *"Hi Henry, how are you going?".*
8,007,658
I am facing the issue in division of numbers in java script. Example: ``` var x= 2500, var y = 100 alert(x/y) ``` is showing 25. I need the answer in **25.00** format. What can I do? When I divide 2536/100, it gives as expected.
2011/11/04
[ "https://Stackoverflow.com/questions/8007658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206161/" ]
Try doing it this way: ``` alert((x/y).toFixed(2)) ```
is it possible to enter x and y as a dollar amount? ie 25.00 and 1.00? if so then use the parseFloat method. ``` var x = 25.00 var y = 1.00 alert(parseFloat(x/y)); ```
54,967,790
Android Studio is giving me a error in 'name' saying it has to be a "throwable tr" in log.v . Can someone explain me why? Log.v("MainActivity", "Name: ",name);
2019/03/03
[ "https://Stackoverflow.com/questions/54967790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11143146/" ]
Android Log Class documentation: * @param tag Used to identify the source of a log message. It usually identifies the class or activity where the log call occurs. * @param msg The message you would like logged. * @param tr An exception to log ``` public static int v(String tag, String msg, Throwable tr) { return printlns(LOG_ID_MAIN, VERBOSE, tag, msg, tr); } ``` -- Simply use this method : ``` Log.v("MainActivity", String.format("Name : %s", name)); ```
Make sure the third argument is a type of `Throwable`. As per the documentation, method syntax is: ``` public static int v (String tag, String msg, Throwable tr) ``` [Link to documentation](https://developer.android.com/reference/android/util/Log.html#v(java.lang.String,%20java.lang.String,%20java.lang.Throwable)) If you want to print `name`, you can write like this: ``` Log.v("MainActivity", String.format("Name : %s", name)); ```
11,233,659
I would like to timestamp my DLL file with my own Authenticode Timestamping Service. Is this possible? How could I achieve this?
2012/06/27
[ "https://Stackoverflow.com/questions/11233659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/982639/" ]
You can develop your own timestamping service. You can write TSP (RFC 3161) server but Authenticode doesn't use RFC 3161 but PKCS#7/PKCS#9 formats as described in [MSDN article](http://msdn.microsoft.com/en-us/library/windows/desktop/bb931395%28v=vs.85%29.aspx) (which you can implement as well). Our [SecureBlackbox](http://www.eldos.com/sbb/net-pki.php) components include timestamping server component which supports both formats. Update: recent updates to Authenticode use standard RFC 3161 timestamps. But the problem is to get the certificate which you will use to sign timestamps. This certificate must be issued by one of the CAs and as I understand, there exist severe requirements regarding management and infrastructure aspects of running a timestamp server. In particular you need to have a secure timestamping hardware. I didn't dig deep into this question, but these aspects are much more complicated then writing a piece of code. Still if you run your own PKI infrastructure (have your own trusted root certificates and CA certificates), then the problem of having a trusted timestamping certificate is solved automatically - you can generate your own certificate.
You need to write a custom HTTP Timestamp server. It should follow [RFC 3161](http://www.ietf.org/rfc/rfc3161.txt) Time-Stamp Protocol (TSP) rules. When you sign your DLL for authenticode with a tool such as [Signtool.exe](http://msdn.microsoft.com/en-us/library/windows/desktop/aa387764%28v=vs.85%29.aspx) from the Windows SDK, you can specify the url of the timestamp server (with the /t swich. See also /tr and /td). You would then point to your server. See here on SO for a related question: [Trusted Timestamps - understanding the format (rfc3161)](https://stackoverflow.com/questions/5045416/trusted-timestamps-understanding-the-format-rfc3161) and also: [Alternative timestamping services for Authenticode](https://stackoverflow.com/questions/2872105/alternative-timestamping-services-for-authenticode)
35,129,648
I have a simple front-end that accepts all incoming requests and serves mostly static content written in PHP. I forward qualified requests from PHP to the backend using curl and serving the responses again to the user. I have two (the number might increase over time) similar back-ends doing the heavy lifting. I want to add load balancing (random is fine) and health checks. All these software load balancers seem to be very complex and hard to setup. Is there an easy solution? I thought about implementing it my self. Should be straight-forward but probably not really battle proof.
2016/02/01
[ "https://Stackoverflow.com/questions/35129648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548788/" ]
A simple front-end cloud load-balancer should be sufficient. Enable the following apache modules : ``` a2enmod proxy proxy_http proxy_balancer ``` Then, open your `/etc/apache2/conf.d/proxy-balancerconfigure` and configure the modproxybalancer by adding the following lines : ``` BalancerMember http://10.0.0.1 BalancerMember http://10.0.0.4 ProxyPass / balancer://mycluster ``` Last, configure your proxy to allow access from all hosts. Open your `/etc/apache2/mods-enabled/proxy.conf` and replace the following : ``` Deny from all ``` To ``` Allow from all ``` Restart apache using `/etc/init.d/apache2 restart`` Hope this help you. Source : [How setup a front-end cloud load balancer in apache](https://www.elastichosts.com/blog/add-a-front-end-apache-cloud-load-balancer/) **EDIT** For a simple health checker, add this at end of each member : ``` BalancerMember http://10.0.0.4 connectiontimeout=10 retry=600 ``` **EDIT2** For an advanced health checker, see [apache mod\_proxy\_hcheck](https://httpd.apache.org/docs/trunk/mod/mod_proxy_hcheck.html) (only available for apache 2.5 and not in the official repository)
nginx is pretty easy to configure for load balancing: <http://nginx.org/en/docs/http/load_balancing.html>
31,864,391
Everytime I have to get the latest changes from the repo I have to stash my changes then do a pull and then unstash my changes again, this process gets very tedious when there's a lot of people working on the project and you have to do this many times a day. I was wondering if there's a git command that does that.
2015/08/06
[ "https://Stackoverflow.com/questions/31864391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4199880/" ]
You can write a shell alias or a git command alias to do this. ``` [alias] update = !git stash save -u && git pull && git stash pop ``` I threw `-u` in there to stash untracked files as well in case the pull adds them.
Running `git pull --rebase` may be what you are after. > > `-r` > > `--rebase[=false|true|preserve]` > > > When `true`, rebase the current branch on top of the upstream branch after fetching. If there is a remote-tracking branch corresponding to the upstream branch and the upstream branch was rebased since last fetched, the rebase uses that information to avoid rebasing non-local changes. > > > When set to `preserve`, rebase with the `--preserve-merges` option passed to `git rebase` so that locally created merge commits will not be flattened. > > > When `false`, merge the current branch into the upstream branch. > > > See `pull.rebase`, `branch.<name>.rebase` and `branch.autoSetupRebase` in [git-config](http://git-scm.com/docs/git-config) if you want to make `git pull` always use `--rebase` instead of merging. > > > You mentioned that you are working in this branch with other developers, so heed the warning from the end of that section of documentation. > > **Note** > > This is a potentially *dangerous* mode of operation. It rewrites history, which does not bode well when you published that history already. Do not use this option unless you have read [git-rebase](http://git-scm.com/docs/git-rebase) carefully. > > >
211,675
During the first scene of *Age of Ultron* we see that von Strucker's HYDRA base is protected by an electromagnetic shield developed on top of a Chitauri technology. [![[blue shield shimmering on the base](https://i.stack.imgur.com/zplTQ.jpg)](https://i.stack.imgur.com/zplTQ.jpg) The Avengers base seen in *Age of Ultron* and *Endgame* isn't significantly bigger than the HYDRA base, so the power footprint of the shield should be about the same (and, the Avengers can use the Arc Reactor technology von Strucker didn't have access to). Also, Wakanda is protected by a shield of a similar sort, able to withstand Thanos's weapons in *Infinity War*. Why is then > > the ultimate protection of the Avengers HQ being done with something resembling metal curtains, only, as seen in *Endgame*? > > >
2019/05/04
[ "https://scifi.stackexchange.com/questions/211675", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/67417/" ]
The Avengers probably never anticipated a direct attack on their facility. We don’t see one in the MCU > > until the last hour of *Avengers: Endgame*. > > > The team is generally responding to threats elsewhere; upstate New York seemingly isn’t where bad stuff tends to happen. The metal curtains in question (the Barn Door Protocol, as described in the movie), was likely designed to keep bad stuff (perhaps an enraged Hulk) in, rather than defend against attacks from outside. The Avengers themselves are there to do that.
The Avengers were probably confident that nobody would dare attack their facility due to their formidable reputation.
129,469
I install Eclipse from the Software Center so it links up and will be updated with the rest of my software. Because I am developing for Android, however, I have to install the ADT Plugin within Eclipse by going to Help > Install new software (or something to that effect). Now, I do understand that I can update Eclipse through the actual Ubuntu software center/system, but in order to update plugins and extensions within Eclipse, I have to go to Help > Check for Updates (which then scans all plugins for updates). The only issue, is that when I installed through the software center, the owner became root, and whenever I run it without root, I'm not able to update - I get the error message "Insufficient access privileges to apply this update." When I run it as root, all of my plugins disappear, because I guess I installed them as myself, not as root. I tried to install the plugins as root, but the Install New Software choice would not work. Ubuntu 12.04 and Eclipse 3.7.2-1
2012/05/01
[ "https://askubuntu.com/questions/129469", "https://askubuntu.com", "https://askubuntu.com/users/59004/" ]
The best solution is to become root using su or by logging in as the root user from the start, if you have that ability (Ubuntu users don't, unless they fixed that defect). Anyhow, once you are root, do a **chown -R user:group** to the path for your eclipse installation. Then your regular user should be able to install plugins. In the future, do not install eclipse as the root user. Root can still use eclipse when another user installs it and owns it.
To add up on @Garry's answer, what I did is create a "dev" group, add my user to it, and `chgrp -R dev <eclipse dir>`. You might want to `chmod -R g+w <eclipse dir>` as well to make sure you can write to it.
63,939,302
I have different queries for fetching data from a large table (about 100-200M rows). I've created partial indexes for my table with different predicates to fit the query because I know each query. For example, the table similar to this: ```sql CREATE TABLE public.contacts ( id int8 NOT NULL DEFAULT ssng_generate_id(8::bigint), created timestamp NOT NULL DEFAULT timezone('UTC'::text, now()), contact_pool_id int8 NOT NULL, project_id int8 NOT NULL, state_id int4 NOT NULL DEFAULT 10, order_x int4 NOT NULL, next_attempt_date timestamp NULL, CONSTRAINT contacts_pkey PRIMARY KEY (id) ); ``` And there are two types of query: ```sql SELECT * FROM contacts WHERE contact_pool_id = X AND state_id = 10 ORDER BY order_x LIMIT 1; ``` and ```sql SELECT * FROM contacts WHERE contact_pool_id = X AND state_id = 20 AND next_attemp_date <= NOW ORDER BY next_attemp_date LIMIT 1; ``` For those queries I've created partial indexes: 1. For state\_id = 10 (new contacts) ```sql CREATE INDEX ix_contacts_cpid_orderx_id_for_new ON contacts USING btree (contact_pool_id, order_x, id) WHERE state_id = 10; ``` 2. For state\_id = 20 (available contacts) ```sql CREATE INDEX ix_contacts_cpid_nextattepmdate_id_for_available ON contacts USING btree (contact_pool_id, next_attempt_date, id) WHERE state_id = 20; ``` For me, those partial indexes are faster than a single index. And what about an update and insert performance? If I change a row with state\_id = 20, will it affect only index 2 (for available contacts) or both of them will be affected?
2020/09/17
[ "https://Stackoverflow.com/questions/63939302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7087479/" ]
Yes, with a partial index you only pay the overhead of modifying the index for rows that meet the `WHERE` condition, so you will always only need to modify at most one of the indexes at the same time (unless you change `state_id` from 10 to 20 or vice versa).
Partial indexes which are not relevant to the tuple will not get updated. If PostgreSQL can do a HOT update (if the column being changed is not part of an index, and there is room on the same page for the new tuple), then even the relevant index doesn't need to get updated.
14,371
I am running a campaign in the Eberron (DnD) setting, but really, this question could apply to anyone running a game in a medieval setting. I wanted to know what level of detail/accuracy to include in the maps players purchase to provide the most realistic gaming experience. Certainly, it would be easiest to merely give the players the "completely accurate" maps provided in the campaign setting book, but I am specifically wondering what information would have been likely to appear on a medieval map (proper scale? Minor settlements and villages? Geographic features?) and how accurate this info would have been compared to "reality". Moreover, aside from the historical consideration, what kinds of info do DM/GMs feel best aids in story development, progression, and flavour?
2012/05/16
[ "https://rpg.stackexchange.com/questions/14371", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/3584/" ]
Think about what the purpose of such a map is. Medieval maps tend to fall into three categories: * road maps (for travelers by road) * coastal maps for (travelers by sea) * maps of the world (for general information) --- Road Maps ========= If it's for pilgrims and merchants traveling by road, it'll have all the major roads marked, along with inns and convenient places to stop to water the animals -- and it won't describe the wilderness or the sea at all. Take a look at the [Tabula Peutingeriana](http://en.wikipedia.org/wiki/Tabula_Peutingeriana "Tabula Peutingeriana") for an example of a classical/medieval road map. ![Tabula Peutingeriana](https://i.stack.imgur.com/ld2HO.jpg) This shows how far it is from one town to the next, a few other things you might find along the way, and some general indications of where the mountains and rivers are to help keep you oriented. Unfortunately, it's out of date. Really out of date. This copy was made in the 1200s, yet it shows cities and roads that hadn't been around since the fall of the Roman Empire. It even shows Pompeii as a city, which had been destroyed at least eleven centuries earlier. --- Coastal Maps ============ If it's for seafarers, it'll have all the harbors and rocky shoals marked, along with notes about winds and whirlpools in the sea. It won't say anything about what you'd find further inland. Take a look at some medieval seafarer's maps, called [Portolan charts](http://en.wikipedia.org/wiki/Portolan_chart "Portolan Charts"). ![Portolan Chart](https://i.stack.imgur.com/jr6KU.jpg) These actually do a pretty good job of showing what you need to know. The coastline is densely filled with ports here, divided into major and minor ones by the color of the text. --- World Maps ========== If it's a map of the whole world, it'll try to include all the regions that the mapmaker has ever heard of. The areas near home will be fairly good, but the further away you get, the more vague and fantastical you get. Take a look at any of the [Mappa Mundi](http://en.wikipedia.org/wiki/Mappa_mundi "Mappa Mundi") and see how Europe and the Mediterranean tend to have all the right parts, while India and China get pretty speculative. ![Mappa Mundi](https://i.stack.imgur.com/1LjxT.jpg) Many medieval world maps were more theological/philosophical than geographical. A typical Mappa Mundi puts the world in a round shape that's easy to comprehend, with Jerusalem at or a bit above the center, and the Garden of Eden towards the top (which is east, not north). Some medieval world maps were much more accurate. Ptolemy, in the 2nd century, compiled a [list of coordinates](https://en.wikipedia.org/wiki/Geography_%28Ptolemy%29) of locations for places throughout the known world, giving longitude and latitude for each. With these coordinates (and a projection of a sphere onto a flat sheet of paper), people during the Middle Ages could (and did) draw up a pretty decent world map. [![Ptolemy's map](https://i.stack.imgur.com/En4PR.jpg)](https://i.stack.imgur.com/En4PR.jpg) --- Modern Maps =========== Modern maps often aim for somewhere in the middle. All the maps above are of the same region (except for Ptolemy's map). Now take a look at how Google Maps renders it: ![Google Maps](https://i.stack.imgur.com/oOxDH.jpg) This map doesn't tell you how long it takes to get from one town to another, it doesn't tell you anything about the bays and harbors, and it doesn't even show rivers at all. If you're looking for those features, one of the medieval maps would be better. The modern map is like Ptolemy's map: it's all about getting the features in the right place compared to each other. The medieval road map might tell you exactly how *long* it takes to get somewhere, but the modern map tells you exactly *where* it is. A traveler doesn't need to see every little kink in the road or every administrative boundary. They need to see how to get where they're going.
Take a look at [Old Maps Online](http://www.oldmapsonline.org/); which has a large collection of historical maps available. One Caveat; despite the timeline slider going back as far as 1000AD; there don't appear to be any maps from before the mid 16th century available.
46,993
I'm getting this warning from my server console (and just happens to be for the same player each time). I'm the only mod of the server so I know no one is using commands to teleport themselves and even if they did it would leave a log. What causes this warning?
2012/01/14
[ "https://gaming.stackexchange.com/questions/46993", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/11929/" ]
This warning is generated every time a player moved to a position or at a speed which the server thinks is impossible. This can happen spuriously, as the assumptions the server makes aren't quite the same as what you can actually do (the server doesn't analyze the player's exact inputs), or it can happen due to an attempted cheat, or due to the world changing as the player attempts to pass through it (e.g. player moves through a block the server knows about but the client hasn't seen yet due to latency). Whenever this happens the server sends a message to the client resetting the player’s position to the last valid one (this can be noticed from that player’s perspective as a sudden shift).
It means that, from the perspective of the server, someone did something that *should* be impossible. This usually means flying or falling into the void.
446,215
Showing one's true colors applies to a situation where a person did something that you perceive as negative. For instance: I thought Jake was a nice guy, but at the club, he showed his true colors. Is there an idiom which would convey the idea that what a person did led you to perceive them positively thereafter? Consider: Tim was initially shy, but once we worked on that he proved to be an amazing guy. If not, is there a better way to say this?
2018/05/15
[ "https://english.stackexchange.com/questions/446215", "https://english.stackexchange.com", "https://english.stackexchange.com/users/298756/" ]
**shine through** is a common way of latent or hidden ability coming on display > > [**shine through** at Cambridge.org](https://dictionary.cambridge.org/us/dictionary/english/shine-through) > > > — phrasal verb with shine UK ​ /ʃaɪn/ US ​ /ʃaɪn/ verb shone or shined > ​ > If a quality shines through, it is strong and easy to see, usually in a particular situation: > > > *Take off your make-up and let your natural beauty shine through.* > > > *She is a quiet woman but her passion shines through in her music.* > > > It took three games starting after Bledsoes injury for the first glimpses of Tom Brady's brilliant future to shine through.
> > I thought Jake was a nice guy, but at the club, he ***was a revelation***. > > > TFD(idioms): > > **[be a revelation](https://idioms.thefreedictionary.com/revelation)** > > To be different than one anticipated, **often in a good way**. > > Dana's performance in the play **was a revelation**—I had > no idea she was such a talented actress. > > > Farlex Dictionary of Idioms. © 2015 Farlex, Inc, all rights reserved. > > >
105,702
I bought 20"\*28" Umbrella Softbox Reflector for Speedlight (Model: 6Y19. [Details & dimensions](https://www.ebay.com/itm/Portable-50-70cm-20-28-Umbrella-Softbox-Reflector-for-Speedlight-NEW-6Y19-/131620730987?_trksid=p2047675.m43663.l10137&nordt=true&rt=nc&orig_cvip=true)), assuming I can just mount it on my light stand. That was a mistake. I need this reflector softbox, for portraits and food photography. --- The problem: The soft box just came with the box, diffuser fabric and 4 spikes as you can see in the details. So one end of the spikes sticks in a corner of a soft box but the other end has nowhere to stick in. In order to use this reflector softbox, I seem to have 2 options: 1. I purchase Bowen's speedlight ring and Bowen's adapter. But it seems like they'd cost ~$20.00 a piece, costing me extra $40 in total. 2. I could buy [E27 Base socket](https://www.aliexpress.com/item/CY-ceramics-Photography-4-in-1-E27-Base-Socket-Light-Lamp-Bulb-Holder-Adapter-for-Photo/32805605370.html) for less than $20.00 - but then I'd have to be in the proximity of a power outlet. --- Question: Is there a solution, which let's me mount my manual flash and the softbox reflector on a light stand, and is also cost effective? --- EDIT I have tripod and a light stand with cold shoe mount which I'm using for shoot through umbrellas.
2019/03/05
[ "https://photo.stackexchange.com/questions/105702", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/75867/" ]
1. The link of the product is broken, but I am assuming it is simply the softboxes that have an umbrella mechanism inside to open, the flash is inside and the way to hold it is using the umbrella's rod. 2. Do not use the mount you are linking, because it is for continuous light, aka, 4 lightbulbs. 3. Look for a thing called "**E type umbrella holder**" The E type is the simplest one where you can change the angle of the system, hold an umbrella and put a flash head on the top using a hot-shoe. They are not expensive, about $10 Usd. 4. A safer type of mount is the "**S type umbrella holder**" this holds the Speedlight by the head, not by the hot shoe. 5. Try not to use an improvised solution because your flash can end on the floor.
My first guess would be to use a gobo-head or a magic arm combined with uni-clamps - the possibilities are endless. I don't know what your sticks are, what kind of contacts and screws you are talking about.
36,440,185
Currently I have created VBA code in worksheet 1 "Sheet1" as ``` Private Sub Worksheet_Activate () ``` So every time I open the worksheet the VBA code will auto run. But the problem I'm facing now is every time I open the Excel workbook, even though I added the codding in ThisWorkbook, ``` Private Sub Workbook_Open() Worksheets("Sheet1").Activate End Sub ``` the worksheet will appear first but the VBA code won't auto run. Every time I need to shift another worksheet then shift back again, then only the VBA code will run, this is very annoying, is there any solution to fix this?
2016/04/06
[ "https://Stackoverflow.com/questions/36440185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6133158/" ]
Using the [Worksheet.Activate method](https://msdn.microsoft.com/en-us/library/office/ff838003.aspx) won't do anything if that worksheet was already active. ``` Private Sub Workbook_Open() Application.ScreenUpdating = False Worksheets("Sheet2").Activate Worksheets("Sheet1").Activate Application.ScreenUpdating = True End Sub ``` Make sure that you are passing the activation trigger to another worksheet and back to Sheet1 in order to run the Worksheet\_Activate event macro or just run the code from the Workbook\_Open sub.
Make the `Worksheet_Activate` `Public` instead of `Private`, then run `Worksheet("???").Worksheet_Activate` within you `Workbook_Open` code.
25,969
I'm working on a software development project on a team with only two persons and it's not an option to consider hiring more people. This appears to be a case where one has to **respond to change over following a plan** because the team is small in comparison to the ideal 5-6 people. Do you happen to know successful cases in such conditions? If so, how was the team organized and how were they able to deliver the project with success?
2019/03/07
[ "https://pm.stackexchange.com/questions/25969", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/27189/" ]
You can adopt agile with any size of team as it is an *approach* to doing software development. As you mention in your question, one of the key aspects is to favour responding to change over following a plan. It gets a bit more complicated if you are talking about using agile *frameworks*. [The Scrum Guide](https://scrumguides.org/scrum-guide.html#team) suggests a minimum team size of 3. This is because with very small teams synchronisation is rarely an issue and so the benefits of Scrum are reduced. [Kanban](https://en.wikipedia.org/wiki/Kanban) doesn't really have a lower team size limit although you could argue again that the benefits may be slightly reduced in a team of two.
As with any team, as project manager you need to allow them to manage themselves whenever possible. This is because project managers rarely have direct line management authority over the teams. The team will need to: Agree the work (scope) to deliver Understand and agree the quality of each item in the scope Plan their work, with only 2 people this is probably best done in 1 week chunks. When estimating I would suggest "sizing" small medium or large for example and try to get things as small as possible as PM you should help the team plan, and not plan for them. If the team have any issues you should be there to help them. Go see them regularly, at least once a week, but to start with maybe daily, buy them a coffee. Get them to complete a simple quality register with dates showing when a feature was checked and if it passed or failed (this might sound over the top but people will be reluctant to tell you bad news and they might gloss over the verbal reporting but they will almost never lie in a quality register) Hope that helps
35,996,604
``` #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f; inches = i; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus (-) operator Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); } }; int main() { Distance D1(11, 10), D2(-5, 11); -D1; // apply negation D1.displayDistance(); // display D1 -D2; // apply negation D2.displayDistance(); // display D2 return 0; } ``` if a instance of Distance is to be returned in operator-() function shouldn't it be returned like new Distance(feet,inches). how this line of code is working here? //return Distance(feet,inches);
2016/03/14
[ "https://Stackoverflow.com/questions/35996604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4655470/" ]
> > if a instance of Distance is to be returned in operator-() function shouldn't it be returned like `new Distance(feet,inches)` > > > No, `new` isn't necessary here. Just return a copy. Actually the implementation of the negation operator should look like ``` Distance operator- () const { return Distance(-feet, -inches); } ``` without touching the current instances member variables (`const` guarantees that).
It appears to work due to the following reasons: 1. Internally the variables feet and inches being negated i.e., mutable values. 2. Then printing the value of D1 or D2 as the case may be. 3. Ignoring the objects being returned from the operator, which is wrong. The unary operator overloading should have been: ``` Distance & operator- () { feet = -feet; inches = -inches; return *this; } ```
177,549
Is there a word meaning both import and export? So I can ask "Is this product both importable and exportable?" like "Is this product \_\_\_\_?"
2014/06/12
[ "https://english.stackexchange.com/questions/177549", "https://english.stackexchange.com", "https://english.stackexchange.com/users/80048/" ]
In the specific example you mentioned (i.e. politics), it's called [*mudslinging*](http://www.thefreedictionary.com/mudslinging): > > the use of insults and accusations, especially unjust ones, with the aim of damaging the reputation of an opponent; efforts to discredit one's opponent by malicious or scandalous attacks. > > > More generally, it is a form of [*character assassination*](http://www.thefreedictionary.com/character+assassination) or *slander*: > > the act of deliberately attempting to destroy a person's reputation by defamatory remarks > > >
This only covers the selective use of evidence, rather than doing so against a particular figure, but [cherry picking](http://en.wikipedia.org/wiki/Cherry_picking_%28fallacy%29) may be a useful term. > > Cherry picking, suppressing evidence, or the fallacy of incomplete > evidence is the act of pointing to individual cases or data that seem > to confirm a particular position, while ignoring a significant portion > of related cases or data that may contradict that position. It is a > kind of fallacy of selective attention, the most common example of > which is the confirmation bias. Cherry picking may be committed > intentionally or unintentionally. This fallacy is a major problem in > public debate. > > >
2,340,755
i have two excel sheets An example of the two sheets are below ``` sheet1 a 1 b 2 d 1 e 3 g 1 sheet2 a b c d e f ``` i want to put a formula in b1 of sheet 2 and drag it down so that the resulting sheet 2 is ``` sheet2 a 1 b 2 c 0 d 1 e 3 f 0 explanation : - a = 1 because same value in book1 b = 2 because same value in book1 c = 0 because c does not exist in book1 d = 1 because same value in book1 e = 3 because same value in book1 f = 0 because f does not exist in book1 ``` what formula can i use in b column of sheet 2 ?
2010/02/26
[ "https://Stackoverflow.com/questions/2340755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193133/" ]
A combination of if(), iserror() and vlookup() will be your best bet here. Assuming your data from sheet1 is in a range called 'refdata', ``` =IF(ISERROR(VLOOKUP(A1,refdata,2,FALSE)),0,VLOOKUP(A1,refdata,2,FALSE)) ``` should do what you need (Where A1 is the cell containing the data you want to match on)
In Excel 2007 it looks like this: ``` =IFERROR(VLOOKUP(A1,sheet1data,2,0),) ```