source
sequence
text
stringlengths
99
98.5k
[ "cs.stackexchange", "0000070415.txt" ]
Q: Is $2^{1+\sqrt{mn}}$ an upper bound for the size of the DFA resulting from the determinisation of n DFAs of size m (all automata sizes are expressed in number of states in this question) There exist NFAs of size $n$ for which the smallest DFA recognizing the same language is of size at least $2^n$. Let $\Sigma$ be a vocabulary, and let's consider $n$ regular languages $L_i \subseteq \Sigma^*$ respectively recognized by $n$ DFAs $D_i=\{Q_i, q^0_i, F_i , \delta_i \}$ whose size are bounded by $m$. We consider the epsilon-free NFA $N$ built by merging the $n$ DFAs such as $N=\{Q=\bigcup Q_i, q^0, F=\bigcup F_i , \delta \}$ where $\delta = \bigcup \delta_i$ with the additional constraint that $\forall \sigma \in \Sigma \, \delta(q^0, \sigma) = \{q | \delta_i(q_i^0, \sigma)=q \, \, 0 \leq i \leq n \}$ (note that in $N$ the $q^0_i$ are not anymore initial states since there is a unique initial state $q^0$). Let $D_N$ be the DFA resulting from the powerset construction of $N$ and $D_N^M$ be the DFA resulting from the minimisation of $D_N$. Is the size of $D_N^M$ at most $2^{1+\sqrt{mn}}$ ? An equivalent question is : let $L \subseteq \Sigma^*$ be the language resulting from the union of the $n$ regular languages $L_i$, is the size of the smallest DFA recognizing $L$ always below $2^{1+\sqrt{mn}}$ ? I would appreciate if possible, some papers related to this problem or a proof/counter-example. Many thanks, Luz A: No. Asymptotically, the size can be as large as $\sim m^n$. Let $p_1,\dots,p_n$ denote the $n$ largest prime numbers that are at most $m$. Let $$L_i = \{x : x \not\equiv 0 \pmod{p_i}\},$$ where we assume the number $x$ is expressed in unary. Then $L = L_1 \cup \dots \cup L_n$ has the form $$L = \{x : x \not\equiv 0 \pmod q\},$$ where $q = p_1 \times \dots \times p_n$. Note that, with this construction, each $L_i$ has a DFA of size at most $m$ (in particular, of size $p_i$). However, the minimal DFA for $L$ has size $q$, which is close to $m^n$. In particular, the size of the minimal DFA for $L$ is asymptotically larger than $2^{1 + \sqrt{mn}}$ (as a function of $n$, treating $m$ as fixed). A: Let $\Sigma$ be an alphabet of size $n$. For each $\sigma \in \Sigma$, let $L_\sigma$ be the language of all words not containing $\sigma$. Each $L_\sigma$ is accepted by a DFA with $m=2$ states. It is well known that $L = \bigcup_{\sigma \in \Sigma} L_\sigma$ requires $2^n = m^n$ states to be accepted by a DFA.
[ "webmasters.stackexchange", "0000067868.txt" ]
Q: New Google SEO benefit with SSL - with only a few sections in SSL, or always on? Google just announced that SSL will affect site ranking positively: http://googlewebmastercentral.blogspot.se/2014/08/https-as-ranking-signal.html I have an Easter Island tourist agency called Easter Island Traveling for which I had planned doing a subdomain (secure.*) for doing sales, logins etc. Now, does Google want my SSL to be on for all of my site to have this SEO benefit? This would be quite radical by Google, since it would affect my site speed negatively. Or is it enough that I have SSL on a part of the site only? Thoughts? A: Yes, Google wants all of your site to be served over HTTPS. They say: Use HTTPS on all sites and pages Link leads to the exact part of production where that is specified, (though the whole video would be useful.) - Google I/O 2014 - HTTPS Everywhere. A: Since pages are ranked individually I would assume that you do not have to have it on for pages you do not care about rankings for. But it is possible that since their goal is to get sites to have always have SSL on that they may take into account whether SSL is applied to an entire website or not. It's a brand new concept so only time will tell how it really works. Other thought on this: It's such a small ranking factor that it isn't going to make any practical difference in your rankings anyway. If you're really concerned about performance (or cost) doing this should not be a priority. It isn't going to slow down your site in any practical way, either. Technically there is more overhead but it really is negligible.
[ "stackoverflow", "0055036723.txt" ]
Q: Loop by IP Address I have a working code to check the house for the ram amount on each unit. I give it an IP address and it returns the amount of ram and a few other things all nicely formatted. Can I just add a pre-done file into this to get it to accept an IP list from either .txt or .csv? I've tried piecing this code I have in another file that runs off the list but I keep getting errors. param([string]$fileInput,[string]$fileOutput ) If ( $fileInput -eq "" -OR $fileOutput -eq ""){ $list = Import-Csv $fileInput -Header name, licenseKey, keyStatus foreach( $computerName in $list){ export-csv -InputObject $computerName -append $fileOutput -Encoding utf8 } } I'm not sure the right placement for these lines in my code. write-host "" $strComputer = Read-Host "Enter Computer Name to list memory slot information" $colSlots = Get-WmiObject -Class "win32_PhysicalMemoryArray" -namespace "root\CIMV2" -computerName $strComputer $colRAM = Get-WmiObject -Class "win32_PhysicalMemory" -namespace "root\CIMV2" -computerName $strComputer $NumSlots = 0 write-host "" $colSlots | ForEach { “Total Number of Memory Slots: ” + $_.MemoryDevices $NumSlots = $_.MemoryDevices } write-host "" Read-Host "Press Enter to continue" $SlotsFilled = 0 $TotMemPopulated = 0 $colRAM | ForEach { “Memory Installed: ” + $_.DeviceLocator “Memory Size: ” + ($_.Capacity / 1GB) + ” GB” $SlotsFilled = $SlotsFilled + 1 $TotMemPopulated = $TotMemPopulated + ($_.Capacity / 1GB) # if ($_.Capacity = 0) # {write-host "found free slot"} } write-host "" write-host "=== Summary Memory Slot Info for computer:" $strComputer "===" write-host "" If (($NumSlots - $SlotsFilled) -eq 0) { write-host "ALL Slots Filled, NO EMPTY SLOTS AVAILABLE!" } write-host ($NumSlots - $SlotsFilled) " of " $NumSlots " slots Open/Available (Unpopulated)" write-host ($SlotsFilled) " of " $NumSlots " slots Used/Filled (Populated)." write-host "" write-host "Total Memory Populated = " $TotMemPopulated "GB" # A: A foreach loop would be idiomatic solution. Create a text file that contains computer names or IP addresses like this: computer1 computer2 ... computern That is, each system name or address in its own row without anything extra. Simple enough, right? Save it as, say, c:\temp\computersToCheck.txt. After you've got a list of names, change the code to support aforementioned foreach loop. # Read all the computers from the file $computers = get-content c:\temp\computersToCheck.txt # Perform an operation for each row in the file foreach ($strComputer in $computers) { $colSlots = Get-WmiObject -Class "win32_PhysicalMemoryArray" -namespace "root\CIMV2" -computerName $strComputer # Rest of the code goes here ... write-host "Total Memory Populated = " $TotMemPopulated "GB" }
[ "unix.stackexchange", "0000497638.txt" ]
Q: Re-installation of AppArmor misses some files I have Ubuntu 16.04 and lately I reinstalled AppArmor: sudo rm -rf /etc/apparmor* sudo apt-get install apparmor --reinstall sudo service apparmor restart When I am trying to parse a profile with apparmor_praser I got error: AppArmor parser error for my.profile in my.profile at line 1: Could not open 'tunables/global' I checked my ApprAmor folder and noticed it missing some files: root@ubuntu:/etc/apparmor.d# ls ./tunables/ home.d multiarch.d xdg-user-dirs.d While, before I removed the files I had these files: root@ubuntu:~# ls /etc/apparmor.d/tunables/ alias apparmorfs dovecot global home home.d kernelvars multiarch multiarch.d proc securityfs sys xdg-user-dirs xdg-user-dirs.d It seems that the installation didn't install all the dependencies libraries. I tried also these ones: apt-get install apparmor-utils apparmor-easyprof apparmor-easyprof-ubuntu But I still don't have important files such as tunables/global. Any idea how I can reinstall AppArmor as it came up with Ubuntu default installation ? A: I went to this place: https://launchpad.net/ubuntu/xenial/+source/apparmor download: https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/apparmor/2.10.95-0ubuntu2.10/apparmor_2.10.95.orig.tar.gz Inside this tar file I wend to ../profiles/apparmor.d and extracted all the content to /etc/apparmor.d by: cp -r ./apparmor.d/ /etc/apparmor.d/ But it weird that I needed to do it manually. I will be glad if someone can share automatic way to do it with apt-get.
[ "stackoverflow", "0001186642.txt" ]
Q: What's the nvelocity/C# equivalent of "if x in array"? Hacking on a Nvelocity C#/.NET view template (.cs file), I'm really missing the Python keyword "in" (as in, "foo in list"). What is the built-in for checking list/array membership? This is what my Python brain wants to do: #set ( $ignore = ['a','b','c'] ) <ul> #foreach ( $f in $blah ) #if ( $f not in $ignore ) <li> $f </li> #end #end </ul> But I am not sure what the right syntax is, if there is indeed any. I had a quick look at the Velocity Template Guide but didn't spot anything useful. A: You can use the Contains function in List, so it should be List<int> list = new List<int>{1, 2, 3, 4, 5, 6, 7}; foreach(var f in blah) if(list.Contains(f)) A: "Contains" is indeed what I was looking for. ...And in NVelocity template-speak: #set( $ignorefeatures = ["a", "b"] ) #foreach( $f in $blah ) #if ( !$ignorefeatures.Contains($f.Key) ) <tr><td> $f.Key </td><td> $f.Value </td></tr> #end #end
[ "rpg.stackexchange", "0000100109.txt" ]
Q: Do familiars have to be summoned? So the way the spell find familiar works is that you summon a fey/fiend/celestial that takes the form of a normal animal and follows your commands unquestionably. But then I see certain variant rules like this one on the Pseudodragon's entry: Some pseudodragons are willing to serve spellcasters as a familiar... At any time and for any reason, the pseudodragon can end its service as a familiar, ending the telepathic link. (Monster Manual, page 254) And then there's this in the Gazer's entry: Some beholders with wizard minions insist they take a gazer as a familiar because they can see through the eyes of these creatures. (Volo's Guide, page 126) So the implication here is that you can make familiars out of non-summoned, non fey/fiend/celestial creatures that can act on their own free will. The only problem is I can't find any rules that pertain to this in 5e. Are there any? And if not, what could I do to incorporate these kinds of familiars in a game? A: No, familiars can be gained by means other than summoning So there are three broad ways you can gain a familiar: By summoning one, using the find familiar spell; By forming a pact with a creature who will willingly be your familiar; By creating one yourself In the first case, you — the player — have control over the actions of the familiar, as detailed in the spell description. But for the second case, the DM controls the familiar's actions, not you. In other words, if you find a real pseudodragon in the game, tame it, and convince it to serve you, it becomes your familiar, but it is still an NPC. At any time, the DM may decide that you have violated the terms of your agreement/broken your mutual trust, and the familiar can leave you or betray you. It is choosing to be with you, but you don't get to decide its motivations. It is also possible to have more than one familiar this way, if you summon one and form a pact with another one. The Imp: the familiar that can be forged a pact with In MM pg 69, you will find on the sidebar an "Imp Familiar" variant. They are described as: Imps can be found in the service to mortal spellcasters, acting as advisors, spies, and familiars. An imp urges its master to acts of evil, knowing the mortal's soul is a prize the imp might ultimately claim. […] Familiar. The imp can enter into a contract to serve another creature as a familiar, forming a telepathic bond with its willing master. […] So there is the second way to get a familiar, as demonstrated in the RAW. The Homunculus: the familiar that can be created In MM pg 188, you will see the Homunculus: a tiny creature that is made by the wizard — not summoned or made a pact with. The text does not actually say the word "familiar," but its abilities as a companion are everything a familiar can do, and a little extra. A homunculus is a construct that acts as an extension of its creator, with the two sharing thoughts, senses, and language through a mystical bond. A master can have only one homunculus at a time (attempts to create another one always fail), and when its master dies, the homunculus also dies. Shared Mind. A homunculus knows everything its creator knows, including all the languages the creator can speak and read. Likewise, everything the construct senses is known to its master, even over great distances, provided both are on the same plane.
[ "stackoverflow", "0004759223.txt" ]
Q: Python select random date in current year In Python can you select a random date from a year. e.g. if the year was 2010 a date returned could be 15/06/2010 A: It's much simpler to use ordinal dates (according to which today's date is 734158): from datetime import date import random start_date = date.today().replace(day=1, month=1).toordinal() end_date = date.today().toordinal() random_day = date.fromordinal(random.randint(start_date, end_date)) This will fail for dates before 1AD. A: Not directly, but you could add a random number of days to January 1st. I guess the following should work for the Gregorian calendar: from datetime import date, timedelta import random import calendar # Assuming you want a random day of the current year firstJan = date.today().replace(day=1, month=1) randomDay = firstJan + timedelta(days = random.randint(0, 365 if calendar.isleap(firstJan.year) else 364))
[ "wordpress.stackexchange", "0000008132.txt" ]
Q: Showing Post Counts of One's (Author) Own in the admin post list How can I show user's post counts of one's (Author) own in the admin post list (edit.php) instead of all post count of the system? like published (10), Draft (5) ... of his own or logedin user. Thanks in advance. A: Have a look here for the solution (code needs optimizing, but it works): Help to condense/optimize some working code
[ "stackoverflow", "0014365875.txt" ]
Q: Qt - Cannot put an image in a table Why with the following code I just get an empty table widget? QString imgPath = "C:\\path\\to\\image.jpg"; QImage *img = new QImage(imgPath); QTableWidget *thumbnailsWidget = new QTableWidget; QTableWidgetItem *thumbnail = new QTableWidgetItem; thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img)); thumbnailsWidget->setColumnCount(5); thumbnailsWidget->setRowCount(3); thumbnailsWidget->setItem(0, 0, thumbnail); setCentralWidget(thumbnailsWidget); How can I put an image into a QTableWidgetItem? Thank you. P.S.: I noticed that the table is not really empty. Clicking on the different QTableWidgetItem elements, the empty ones become blue, the one with coordinates [0,0] is highlighted differently: cyan with a thin blue bar on the left... A: You are doing all almost right, but try to control your img, for example, like this: QString imgPath = "C:\\path\\to\\image.jpg"; QImage *img = new QImage(); bool loaded = img->load(imgPath); if (loaded) { QTableWidget *thumbnailsWidget = new QTableWidget; QTableWidgetItem *thumbnail = new QTableWidgetItem; thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img)); thumbnailsWidget->setColumnCount(5); thumbnailsWidget->setRowCount(3); thumbnailsWidget->setItem(0, 0, thumbnail); w.setCentralWidget(thumbnailsWidget); } else { qDebug()<<"Image "<<imgPath<<" was not opened!"; } Hope, it helps you! Good luck! A: OK, I had to rescale the image: thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img).scaled(100, 100));
[ "diy.stackexchange", "0000033602.txt" ]
Q: Why Do 240V Circuits Not Require Neutral? Someone told me that a 240V circuit does not require a neutral wire in the cable. Can anyone explain this phenomenon from the electricity perspective and generally explain why circuits do and do not need a neutral wire? A: In a 120/240V single split phase system, the two ungrounded (hot) legs are actually connected to the secondary winding of the distribution transformer. The transformer actually steps down the voltage to 240 volts, so the two legs are a complete 240 volt circuit. The grounded (neutral) conductor is connected to the center of the coil (center tap), which is why it provides half the voltage. Therefore, if a device requires only 240V, only two ungrounded (hot) conductors are required to supply the device. If a device runs on 120V, one ungrounded (hot) conductor and one grounded (neutral) conductor are needed. If a device needs both 120V and 240V, then two ungrounded (hot) conductors and one grounded (neutral) conductor must be used. If you connect a load between the two ungrounded legs of the circuit, you can see how you have a complete circuit through the coil. If you connect a load between one of the ungrounded conductors, and the grounded (neutral) conductor. You can also get a complete circuit, though it's only through half of the coil. Since these circuits only include half the coil, the voltage is also half (Es = EpNs/Np). A: For the second part: clothes dryers often have 240 V heaters and 120 V motors. Stoves use 240 V for the elements and 120 V for the light bulbs. These are both plug-in and need the neutral. My new electric hot-water heater is 240 V, not plug-in, and uses the old 120 V wiring. The electrician doing the install marked the "old" neutral with black tape at each end to warn that it's now hot, and that there's no neutral...... In some wiring codes, each individual plug in a duplex outlet in a kitchen needs a separate breaker. They run a 240 V line to the plug, wire two hot lines each to the hot on a different plug, wire the one neutral line to both neutrals, and break off the tab connecting the two hots.
[ "stackoverflow", "0046481817.txt" ]
Q: adding a 3.5 inch screenshot for iOS submission despite Apple dropping support for iPhone 4S I finally uploaded my app to iTunes Connect today, and it asked me for a 3.5 inch screenshot. I didn't develop this app with the iPhone 4S in mind, since Apple dropped support for the 4S on the later versions of iOS. This app has no storyboard that lets it run on a 3.5 inch iPhone 4S. Do I still have to make the app support the 4S (and submit the corresponding screenshot), despite Apple dropping support for the iPhone 4S? A: Yeah, I just ticked the "use 5.5 inch screenshot" check box and made sure my deployment target was set to iOS 10.0. Looks like Apple doesn't care if my app doesn't run on an iPhone 4S, which is nice. The app was approved within a day of submission!
[ "stackoverflow", "0039691111.txt" ]
Q: Graphql Unknown argument on field I am new to GraphQL, When ever I try to send args on (posts) child node like the bellow query I got an error msg "Unknown argument id on field posts of type user". I want to bring the some particular post only not all of it. { people(id:[1,2]) { id username posts(id:2) { title tags { name } } } } here is my Schema.js file .. var graphql = require('graphql'); var Db = require('./db'); var users = new graphql.GraphQLObjectType({ name : 'user', description : 'this is user info', fields : function(){ return { id :{ type : graphql.GraphQLInt, resolve(user){ return user.id; } }, username :{ type : graphql.GraphQLString, resolve(user){ return user.username; } }, posts:{ id:{ type : graphql.GraphQLString, resolve(post){ return post.id; } }, type: new graphql.GraphQLList(posts), resolve(user){ return user.getPosts(); } } } } }); var posts = new graphql.GraphQLObjectType({ name : 'Posts', description : 'this is post info', fields : function(){ return { id :{ type : graphql.GraphQLInt, resolve(post){ return post.id; } }, title :{ type : graphql.GraphQLString, resolve(post){ return post.title; } }, content:{ type : graphql.GraphQLString, resolve(post){ return post.content; } }, person :{ type: users, resolve(post){ return post.getUser(); } }, tags :{ type: new graphql.GraphQLList(tags), resolve(post){ return post.getTags(); } } } } }); var tags = new graphql.GraphQLObjectType({ name : 'Tags', description : 'this is Tags info', fields : function(){ return { id :{ type : graphql.GraphQLInt, resolve(tag){ return tag.id; } }, name:{ type : graphql.GraphQLString, resolve(tag){ return tag.name; } }, posts :{ type: new graphql.GraphQLList(posts), resolve(tag){ return tag.getPosts(); } } } } }); var query = new graphql.GraphQLObjectType({ name : 'query', description : 'Root query', fields : function(){ return { people :{ type : new graphql.GraphQLList(users), args :{ id:{type: new graphql.GraphQLList(graphql.GraphQLInt)}, username:{ type: graphql.GraphQLString } }, resolve(root,args){ return Db.models.user.findAll({where:args}); } }, posts:{ type : new graphql.GraphQLList(posts), args :{ id:{ type: graphql.GraphQLInt }, title:{ type: graphql.GraphQLString }, }, resolve(root,args){ return Db.models.post.findAll({where:args}); } }, tags :{ type : new graphql.GraphQLList(tags), args :{ id:{ type: graphql.GraphQLInt }, name:{ type: graphql.GraphQLString }, }, resolve(root,args){ return Db.models.tag.findAll({where:args}); } } } } }); var Schama = new graphql.GraphQLSchema({ query : query, mutation : Mutation }) module.exports = Schama; A: looks like you are missing args on users, hence, it should look like this: var users = new graphql.GraphQLObjectType({ name : 'user', description : 'this is user info', fields : function(){ return { id :{ type : graphql.GraphQLInt, resolve(user){ return user.id; } }, username :{ type : graphql.GraphQLString, resolve(user){ return user.username; } }, posts:{ args: { id:{ type : graphql.GraphQLInt, }, type: new graphql.GraphQLList(posts), resolve(user, args){ // Code here to use args.id return user.getPosts(); } } } } });
[ "serverfault", "0000498437.txt" ]
Q: HAProxy URI balancing isn't very balanced I'm attempting to use HAProxy 1.4.22 with URI balancing and hash-type consistent to load balance between 3 varnish cache backends. My understanding is that this will never accomplish a perfect balance between servers but it should be better than the results I'm seeing. The relevant part of my HAproxy config looks like: backend varnish # hash balancing balance uri hash-type consistent server varnish1 10.0.0.1:80 check observe layer7 maxconn 5000 id 1 weight 75 server varnish2 10.0.0.2:80 check observe layer7 maxconn 5000 id 2 weight 50 server varnish3 10.0.0.3:80 check observe layer7 maxconn 5000 id 3 weight 50 I've been self-testing by pointing my own hosts file at the new proxy server, and I even tried re-routing the popular homepage to a separate backend that's balanced round-robin to get that outlier off the hash balanced backend, that seems to work fine. I boosted varnish1 to a weight of 75 as a test, but it didn't seem to help. My load is being very disproportionately balanced and I don't understand why this is. One interesting tidbit is that if I reverse the IDs, the higher ID will ALWAYS get the lion's share of the traffic. Why would the ID affect balancing? Tweaking weights is well and good, but as my site's traffic patterns change (we are a news site and the most popular post can change rapidly) I don't want to have to constantly tweak weights. I understand it'll never be in perfect balance, but I was expecting better results than having one server with a lower weight getting 25 times more connections than another server with a higher weight. My goal has been to reduce DB and app server load by reducing duplication at the cache level which HAproxy URI balancing is recommended for but if it's going to be this out of balance it won't work for me at all. Any advice? A: I'm not sure if this is very helpful, but I've struggled a bit with the same problem - and this is what I've concluded; Hash-based load balancing will, as you've already established, never give you perfect load balancing. The behavior you see can simply be explained by having a few of the most visited / largest pages on the same server - by having few pages that gets a lot of traffic, and a lot of pages that get little traffic, this will be enough to skew the statistics. Your configuration is to use consistent hashing. The ID's and server weight determine the final server the hashed entry will be directed to - that is why your balancing is affected by this. The documentation is pretty clear that even though this is a good algorithm for balancing caches - it may require you to change around the IDs and increase the total weight of the servers to get a more even distribution. If you take a large sample of unique addresses (more than 1000), and you visit each of these one time - you should see that the session counter is a lot more equal across the three backends than if you allow 'ordinary' traffic against the balancer as this is affected by the traffic pattern of the site as well. My advice would be to make sure that you hash the entire URL, not just what's to the left of "?". This is controlled by using balance uri whole in the configuration. Ref. the haproxy documentation. If you have a lot of URL's which have the same base, but with varying GET-parameters - this will definitely give you improved results. I would also take into consideration how the load balancing affects the capacity of your cache servers. If it doesn't effectively affect redundancy in any way - I wouldn't worry too much about it, as getting perfect load balancing isn't something you are likely to achieve with URI-hashing. I hope this helps.
[ "superuser", "0000121798.txt" ]
Q: How to make sure that grub does use menu.lst? On my Ubuntu 9.04 ("Karmic") laptop I suspect grub does not use the /boot/grub/menu.lst file. What happens on boot is that I see a blank screen and nothing happens. When I press ESC I see a boot list which is different from what I would expect from the menu.lst file. The menu lines are different and when I choose the first entry it does not use the kernel options that are in the first entry in menu.lst. Where do the entries that grub uses come from? How can I find out what happens, is there a log? I could not find anything in /var/log/syslog or /var/log/dmesg about grub using a menu.lst. How can I set it to work like expected? Some Files: $ sudo ls -la /boot/grub/*lst -rw-r--r-- 1 root root 1558 2009-12-12 15:25 /boot/grub/command.lst -rw-r--r-- 1 root root 121 2009-12-12 15:25 /boot/grub/fs.lst -rw-r--r-- 1 root root 272 2009-12-12 15:25 /boot/grub/handler.lst -rw-r--r-- 1 root root 4576 2010-03-19 11:26 /boot/grub/menu.lst -rw-r--r-- 1 root root 1657 2009-12-12 15:25 /boot/grub/moddep.lst -rw-r--r-- 1 root root 62 2009-12-12 15:25 /boot/grub/partmap.lst -rw-r--r-- 1 root root 22 2009-12-12 15:25 /boot/grub/parttool.lst $ sudo ls -la /vm* lrwxrwxrwx 1 root root 30 2009-12-12 16:15 /vmlinuz -> boot/vmlinuz-2.6.31-16-generic lrwxrwxrwx 1 root root 30 2009-12-12 14:07 /vmlinuz.old -> boot/vmlinuz-2.6.31-14-generic $ sudo ls -la /init* lrwxrwxrwx 1 root root 33 2009-12-12 16:15 /initrd.img -> boot/initrd.img-2.6.31-16-generic lrwxrwxrwx 1 root root 33 2009-12-12 14:07 /initrd.img.old -> boot/initrd.img-2.6.31-14-generic The only menu.lst that I found: $ sudo find / -name "menu.lst" /boot/grub/menu.lst $ sudo cat /boot/grub/menu.lst # menu.lst - See: grub(8), info grub, update-grub(8) # grub-install(8), grub-floppy(8), # grub-md5-crypt, /usr/share/doc/grub # and /usr/share/doc/grub-doc/. ## default num # Set the default entry to the entry number NUM. Numbering starts from 0, and # the entry number 0 is the default if the command is not used. # # You can specify 'saved' instead of a number. In this case, the default entry # is the entry saved with the command 'savedefault'. # WARNING: If you are using dmraid do not use 'savedefault' or your # array will desync and will not let you boot your system. default 0 ## timeout sec # Set a timeout, in SEC seconds, before automatically booting the default entry # (normally the first entry defined). timeout 3 ## hiddenmenu # Hides the menu by default (press ESC to see the menu) #hiddenmenu # Pretty colours color cyan/blue white/blue ## password ['--md5'] passwd # If used in the first section of a menu file, disable all interactive editing # control (menu entry editor and command-line) and entries protected by the # command 'lock' # e.g. password topsecret # password --md5 $1$gLhU0/$aW78kHK1QfV3P2b2znUoe/ # password topsecret # examples # # title Windows 95/98/NT/2000 # root (hd0,0) # makeactive # chainloader +1 # # title Linux # root (hd0,1) # kernel /vmlinuz root=/dev/hda2 ro # Put static boot stanzas before and/or after AUTOMAGIC KERNEL LIST ### BEGIN AUTOMAGIC KERNELS LIST ## lines between the AUTOMAGIC KERNELS LIST markers will be modified ## by the debian update-grub script except for the default options below ## DO NOT UNCOMMENT THEM, Just edit them to your needs ## ## Start Default Options ## ## default kernel options ## default kernel options for automagic boot options ## If you want special options for specific kernels use kopt_x_y_z ## where x.y.z is kernel version. Minor versions can be omitted. ## e.g. kopt=root=/dev/hda1 ro ## kopt_2_6_8=root=/dev/hdc1 ro ## kopt_2_6_8_2_686=root=/dev/hdc2 ro # kopt=root=UUID=9b454298-18e1-43f7-a5bc-f56e7ed5f9c6 ro noresume ## default grub root device ## e.g. groot=(hd0,0) # groot=70fcd2b0-0ee0-4fe6-9acb-322ef74c1cdf ## should update-grub create alternative automagic boot options ## e.g. alternative=true ## alternative=false # alternative=true ## should update-grub lock alternative automagic boot options ## e.g. lockalternative=true ## lockalternative=false # lockalternative=false ## additional options to use with the default boot option, but not with the ## alternatives ## e.g. defoptions=vga=791 resume=/dev/hda5 ## defoptions=quiet splash # defoptions=apm=on acpi=off ## should update-grub lock old automagic boot options ## e.g. lockold=false ## lockold=true # lockold=false ## Xen hypervisor options to use with the default Xen boot option # xenhopt= ## Xen Linux kernel options to use with the default Xen boot option # xenkopt=console=tty0 ## altoption boot targets option ## multiple altoptions lines are allowed ## e.g. altoptions=(extra menu suffix) extra boot options ## altoptions=(recovery) single # altoptions=(recovery mode) single ## controls how many kernels should be put into the menu.lst ## only counts the first occurence of a kernel, not the ## alternative kernel options ## e.g. howmany=all ## howmany=7 # howmany=all ## specify if running in Xen domU or have grub detect automatically ## update-grub will ignore non-xen kernels when running in domU and vice versa ## e.g. indomU=detect ## indomU=true ## indomU=false # indomU=detect ## should update-grub create memtest86 boot option ## e.g. memtest86=true ## memtest86=false # memtest86=true ## should update-grub adjust the value of the default booted system ## can be true or false # updatedefaultentry=false ## should update-grub add savedefault to the default options ## can be true or false # savedefault=false ## ## End Default Options ## title Ubuntu 9.10, kernel 2.6.31-14-generic noresume uuid 70fcd2b0-0ee0-4fe6-9acb-322ef74c1cdf kernel /vmlinuz-2.6.31-14-generic root=UUID=9b454298-18e1-43f7-a5bc-f56e7ed5f9c6 ro quiet splash apm=on acpi=off noresume initrd /initrd.img-2.6.31-14-generic title Ubuntu 9.10, kernel 2.6.31-14-generic (recovery mode) uuid 70fcd2b0-0ee0-4fe6-9acb-322ef74c1cdf kernel /vmlinuz-2.6.31-14-generic root=UUID=9b454298-18e1-43f7-a5bc-f56e7ed5f9c6 ro sing le initrd /initrd.img-2.6.31-14-generic title Ubuntu 9.10, memtest86+ uuid 70fcd2b0-0ee0-4fe6-9acb-322ef74c1cdf kernel /memtest86+.bin ### END DEBIAN AUTOMAGIC KERNELS LIST These are the choices that grub displays after i press ESC: Ubuntu, Linux 2-6-31-16-generic Ubuntu, Linux 2-6-31-16-generic (recovery mode) Ubuntu, Linux 2-6-31-14-generic Ubuntu, Linux 2-6-31-14-generic (recovery mode) Memory test (memtest86+) Memory test (memtest86+, serial console 115200) A: Ubuntu 9.10 "Karmic" uses Grub2 by default, which does not use /boot/grub/menu.lst. Instead, Karmic's Grub2 uses /boot/grub/grub.cfg, which is generated from scripts located in /etc/grub.d and variables set in /etc/default/grub. It looks to me like your system was upgraded from an earlier Ubuntu (9.04/Jaunty or earlier), which used Grub1. Your /boot/grub/menu.lst file is a remnant of the upgrade process.
[ "apple.stackexchange", "0000067013.txt" ]
Q: MacBook Pro camera and microphone used by malware? Given the increasing number of reports about malware for Apple computers, I am concerned by the fact that there's no simple way to physically block the camera while I'm using my MacBook Pro. Is it possible an OSX virus or maybe an exploit in Flash could be used to activate the camera, without turning on the green recording light at the top center? Or is this impossible due to the hardware of MBP? A related question arises concerning the microphone, could it be used by malware to secretly record conversations around the computer? If so, what are the best ways of preventing this? A: I'm fairly certain the green light is hard-wired to the camera, there's no way to activate the camera without activating the light, precisely for privacy reasons. If you're really concerned about it, you can always just use a piece of electrical tape to cover the camera (or fold a piece of cardboard over the top of the lid for a non-sticky solution). Frankly I wouldn't worry too much about the risk of malware. That particular piece of malware (MacDefender) was contained fairly quickly by Apple, it's very unlikely that you could be infected by it now, unless you maintain an unpatched system. There have been a few OS X security issues lately (such as Flashback), and they get a lot of press, but the actual amount of harmful software out there for a Mac is extremely low. My advice is to keep your system up to date and avoid downloading files from questionable sources. But other than that, don't worry too much, unless you have a highly sensitive job (in which case there should be other people whose job it is to worry about it).
[ "physics.stackexchange", "0000491719.txt" ]
Q: The sign of $d\mathbf{r}$ when integrating the universal gravitational force in order to define gravitational potential energy I am trying to find gravitational potential energy by integrating the gravitational force: $$\mathbf{F}(\mathbf{r}) = - \ G \frac{Mm}{|\mathbf{r}|^2} \ \hat{\mathbf{r}}$$ where $\mathbf{r}$ is the vector from the centre of the Earth with mass $M$ towards the point of a mass $m$, and $\hat{\mathbf{r}}$ is the unit vector pointing towards the vector $\mathbf{r}$. The potential energy at a point of the distance $|\mathbf{r}|$ can be found from $$U(\mathbf{r}) = -\int_{\infty}^{r} - \ G \frac{Mm}{|\mathbf{r}|^2} \hat{\mathbf{r}} \ \cdot \ d\mathbf{r}$$ Then, removing the minus signs the expression becomes $$U(\mathbf{r}) = \int_{\infty}^{r} \ G \frac{Mm}{|\mathbf{r}|^2} \hat{\mathbf{r}} \ \cdot \ d\mathbf{r}$$ However, look at the picture below that I drew. Since I am integrating from infinity to a point r, I thought $d\mathbf{r}$ should be directed towards the opposite direction of $\hat{\mathbf{r}}$, but actually, if I calculate in that way I get $$U(\mathbf{r}) = \frac{GMm}{r},$$ in which the minus sign is omitting. From a mathematical perspective, either of $\hat{\mathbf{r}}$ and $\mathbf{r}$ direct towards the same direction, hence the scalar product should be a positive value. But I still do not understand why $\hat{\mathbf{r}}$ and $d\mathbf{r}$ should be considered the same direction whenever I am calculating. This is perhaps not accounting for the upper and lower bounds. Can anybody explain please? A: First let's do the math. For the path considered in this integral, one has $$ \hat{\bf r} \cdot {\rm d}{\bf r} = {\rm d}r $$ (pay careful attention to use of bold font here: the right hand side is a scalar not a vector). Using this we get $$ U = \int_{\infty}^r GM m \frac{1}{r^2} {\rm d}r = GMm \left[ -\frac{1}{r} \right]^r_{\infty} = - \frac{GMm}{r} $$ I think your worry is understandable, but ${\rm d}{\bf r}$ means the change in $\bf r$, and if this is in the opposite direction to $\bf r$ then this will be taken care of correctly---it will result in ${\rm d}r$ being itself negative, but it is still ${\rm d}r$ not $-{\rm d}r$. That is: $$ \mbox{if } \hat{\bf r} \cdot {\rm d}{\bf r} < 0 \;\mbox{ then } \; {\rm d}r < 0 $$ but this does not change the fact that, for the path under discussion, $$ \hat{\bf r} \cdot {\rm d}{\bf r} = {\rm d}r . $$ (For some other path this relationship would not be true; in general you would have to include the effect of an angle between $\hat{\bf r}$ and ${\rm d}{\bf r}$ that might not be either 0 or 180 degrees.)
[ "stackoverflow", "0010934953.txt" ]
Q: PHP DateTime - modify reference I'm trying to modify a DateTime object in a function passed as an reference: <?php $date = new DateTime('2012-02-12'); for($n1 = 0; $n1 < 10; $n1++) { $date->modify('first day of next month'); setDate($date, 15); echo $date->format('Y-m-d') . "<br />\n"; } function setDate(&$date, $day) { $date->setDate($date->format('Y'), $date->format('m'), $day); } ?> But the result is not as expected. Did I got something wrong with this references stuff? EDIT: Expected result: 2012-03-15 2012-04-15 ... Result with function above: 2012-03-01 2012-04-01 ... A: My PHP didn't like the 'first day of nest month' bit, but worked with '+1 month'. Since you are setting the day absolutely I wouldn't worry about it not being on the first. Or if it needs to be you can set it to the first before you go into the loop. So, this worked for me. I added the new DateTimeZone('America/New_York') so it would stop bugging me about it not being set (shared server.) And removed the pass by reference (&) bit since all objects are passed by reference by default in PHP now. <?php $date = new DateTime('2012-02-12',new DateTimeZone('America/New_York')); for($n1 = 0; $n1 < 10; $n1++) { $date->modify('+1 month'); setDate($date, 15); echo $date->format('Y-m-d') . "<br />\n"; } function setDate($date, $day) { $date->setDate($date->format('Y'), $date->format('m'), $day); } ?>
[ "stackoverflow", "0051072289.txt" ]
Q: make variable available in other function I have a function function formSubmitListener() { $(".js-form").submit(event => { event.preventDefault(); let input = fetchInput(); validateInput(input); if (isValid) { serverCall() } }); } validateInput returns a isValid boolean of true (if all fields on a form have been filled out) that I need to make available for the if statement. If at all possible I want to prevent the use of a global variable. How do I make the boolean available ? A: function formSubmitListener() { $(".js-form").submit(event => { event.preventDefault(); let input = fetchInput(); let isValid = validateInput(input); if (isValid == true) { serverCall() } }); } this might be what you want. set the validateInput(input) function call to a variable and use that variable since it will store the true/false. or another way by putting the direct function in the if where it checks whats returned function formSubmitListener() { $(".js-form").submit(event => { event.preventDefault(); let input = fetchInput(); if (validateInput(input)) { serverCall() } }); }
[ "electronics.stackexchange", "0000304696.txt" ]
Q: Why do some logic gate chips have a reversed pin layout? I am using some logic chips by Texas Instruments, namely SN74HC02N, SN74HC04N, SN74HC32N and others. When I connected them in my circuit, the SN74HC02N NOR-gate didn't work as expected, so I searched for a datasheet. It showed that the pin layout for the chip was reversed: It was Y, A, B instead of A, B, Y. The other chips from the same family and manufacturer that I have are all A, B, Y. This is very counter-intuitive and doesn't make much sense. Why does this one chip have a different pin layout? Is there an alternative version that has a A, B, Y layout? A: The NOR gate needs extra transistors, compared to NAND. In the days of single-layer metal, routing with that single layer may have required moving the "Y" output, so as to have the most compact IC layout and acceptable cost for the extra transistors.
[ "stackoverflow", "0025903158.txt" ]
Q: txtProgressBar() not showing with foreach() loop in R Some packages needed: library(utils) library(doParallel) library(xts) Create the function needed for loop CRISP = function (i){ nudata <-(crsp1[which(crsp1[,1] == paste(NAMES[1,i])),]) z=xts(coredata(nudata[,c(2)]), order.by=round(as.POSIXct(nudata[,7], format="%y-%m-%d"), units=c("days"))) colnames(z) <- NAMES[1,i] return(z) } Register DoParallel cl <- makeCluster(4, type="PSOCK") registerDoParallel(cl) n <- dim(NAMES)[2] pb <- txtProgressBar(min = 1, max = n, style=3) Use foreach() to loop all_z <- foreach(i=1:dim(NAMES)[2], .combine='merge.xts', .packages='xts') %dopar% { setTxtProgressBar(pb, i) return(CRISP(i))} REPRODUCIBLE DATA NEEDED NAMES: NAMES <- structure(list(X1 = structure(1L, .Label = "AMERICAN CAR & FDRY CO", class = "factor"), X2 = structure(1L, .Label = "ALASKA JUNEAU GOLD MNG CO", class = "factor"), X3 = structure(1L, .Label = "AMERICAN SAFETY RAZOR CORP", class = "factor"), X4 = structure(1L, .Label = "AMERICAN BRAKE SHOE & FDRY", class = "factor"), X5 = structure(1L, .Label = "ABITIBI POWER & PAPER LTD", class = "factor")), .Names = c("X1", "X2", "X3", "X4", "X5"), class = "data.frame", row.names = c(NA, -1L)) crsp1: crsp1 <- structure(list(COMNAM = structure(c(4L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 2L, 2L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("ABITIBI POWER & PAPER LTD", "ALASKA JUNEAU GOLD MNG CO", "AMERICAN BRAKE SHOE & FDRY", "AMERICAN CAR & FDRY CO", "AMERICAN SAFETY RAZOR CORP"), class = "factor"), RET = c(45553, 22625, 31216, 2897, 21995, 21995, 45553, 18171, 21995, 36821, 14301, 14530, 45553, 24793, 1409, 35194, 32919, 30210, 45553, 1, 26123, 4148, 26123, 40785, 45553, 6063, 29673, 9213, 26222, 28048), RETX = c(45262, 22610, 31102, 2875, 21989, 21989, 45262, 18164, 21989, 36626, 14281, 14511, 45262, 24761, 1393, 35018, 32778, 30102, 45262, 1, 26076, 4118, 26076, 40534, 45262, 6028, 29576, 9177, 26173, 27972), vwretd = c(NA, 0.005893, 0.001277, -0.003984, -0.000172, 0.007211, 0.001277, -0.003984, -0.000172, 0.007211, -0.000804, 0.003384, NA, 0.005893, 0.001277, -0.003984, -0.000172, 0.007211, NA, 0.005893, 0.001277, -0.003984, -0.000172, 0.007211, NA, 0.005893, 0.001277, -0.003984, -0.000172, 0.007211 ), ewretd = c(NA, 0.009516, 0.00578, -0.001927, 0.001182, 0.008453, 0.00578, -0.001927, 0.001182, 0.008453, -0.001689, 0.003312, NA, 0.009516, 0.00578, -0.001927, 0.001182, 0.008453, NA, 0.009516, 0.00578, -0.001927, 0.001182, 0.008453, NA, 0.009516, 0.00578, -0.001927, 0.001182, 0.008453), sprtrn = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), DATE = structure(c(-16072, -16070, -16068, -16067, -16066, -16065, -16068, -16067, -16066, -16065, -16064, -16063, -16072, -16070, -16068, -16067, -16066, -16065, -16072, -16070, -16068, -16067, -16066, -16065, -16072, -16070, -16068, -16067, -16066, -16065), class = c("POSIXct", "POSIXt"), tzone = "")), .Names = c("COMNAM", "RET", "RETX", "vwretd", "ewretd", "sprtrn", "DATE"), row.names = c(NA, -30L ), class = "data.frame") A: I was going to simply answer that txtProgressBar wasn't designed to be used by multiple processes, all writing to the console at the same time, but a simple test showed that it doesn't work too badly. You just have to use the makePSOCKcluster outfile="" option so that output from the workers isn't thrown away: library(doParallel) cl <- makePSOCKcluster(3, outfile="") registerDoParallel(cl) pb <- txtProgressBar(min=1, max=100, style=3) foreach(i=1:100) %dopar% { Sys.sleep(1) setTxtProgressBar(pb, i) i } Keep in mind that the results can be produced out-of-order by the workers, so the progress bar may not say 100% when the loop completes. I'm still skeptical about doing this, and I only tested this on Mac OS X, but it's worth trying.
[ "stackoverflow", "0029975926.txt" ]
Q: Match value from array and return another array from a function I was given a task to create a object based array of users. Then create a a function which takes in a parameter and returns another array matching the values compared within the first arr var users = [ { firstname : "jetlag", lastname: "son" }, { firstname : "becky", lastname: "love" }, { firstname : "just", lastname: "me" } ]; function matchName(name) { for (var i = 0; i < users.length; i++) { if(users[i].firstname == name) { return users[i]; } else { console.log('user does not exist') } } } console.log(matchName("jetlag")); I am able to match a specfic username, but what if I just enter jinto the matchName("j"), i would like to return two objects. Any help on this would be great. http://jsfiddle.net/dv9aq0m7/ Thanks. A: Your current code returns the first complete match. This code: if(users[i].firstname == name) { return users[i]; } checks that the two strings are equal and then the return statement will only return that matched value. The function also stops once it has returned any value. So you need to make two small changes. First you need to keep track of all users that fit the criteria, and you should use different logic to check that the string starts with another string. Revised code might look like this: function matchName(name) { var validUsers = []; //the array of users that pass the logic for (var i = 0; i < users.length; i++) { if(users[i].firstname.lastIndexOf(name) === 0) { //this is "starts with" logic validUsers.push(users[i]); //add the element if it's valid } } //I moved the logic for no matching users the outside the loop if (validUsers.length === 0) console.log('No matching users found') return validUsers; } Note: Based on the text you were printing, I moved the logic for printing that no users were found outside the loop by checking the number of elements in the validUsers array. This will print once only if there are no matching users. Here's a fork to your fiddle
[ "stackoverflow", "0021053443.txt" ]
Q: getting the id of the inserted row I am inserting records into a database table through plain old JDBC(as this is what the set up is in the project I am working on.. not yet migrated to Hibernate). here is my table structure employee (empid int indentity not null, empName); when I try to insert record through JDBC code insert into employee(empName) values('something') it works and a record gets inserted. However I need to get the id against the inserted row. I can try executing a separate select query to get the inserted row but might not get the correct inserted record id if 2 employee names are same. How do I get the inserted record id using JDBC. I am using preparedStatment.executeUpdate which returns 0 or 1 based on whether the record is inserted or not. A: Per the the Statement JavaDoc, you can use "RETURN_GENERATED_KEYS" like so - stmt.execute("insert into employee(empName) values('something')", Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) { return rs.getLong(1); // for example. }
[ "stackoverflow", "0060644582.txt" ]
Q: HBase Master: CodedInputStream encountered an embedded string or message which claimed to have negative size HBase 1.5 Hadoop 2.9.2 Getting this error when trying to access HBase web ui: 2020-03-11 13:43:55,295 ERROR org.mortbay.log: /master-status java.lang.IllegalArgumentException: com.google.protobuf.InvalidProtocolBufferException: CodedInputStream encountered an embedded string or message which claimed to have negative size. A: Solution Stop hbase master, backup-master, and region servers Run offline repair of hbase master table using hbase command: hbase org.apache.hadoop.hbase.util.hbck.OfflineMetaRepair` Login to Zookeeper and delete hbase root directory: deleteall /hbase note: you may need to recreate the directory and set zookeeper permissions correctly again via setAcl start HBase master, backup-master and region server
[ "math.stackexchange", "0002189967.txt" ]
Q: Behaviour of a complex series on the boundary of the disk of convergence I would like to ask you for a hint if the series $$\sum^{\infty}_{n=1}\frac{nz^{n}}{2^n}$$ with the radius of convergence $2$ may happen to converge conditionally on the boundary. It obviously does not converge absoutely for $|z|=2$ since the series becomes $\sum^{\infty}_{n=1}n$, which is divergent. My second question would be how to check the boundary behaviour of $\sum^{\infty}_{n=2}\frac{(-1)^{n}z^{n}}{\ln n}$. A: For the first question, we can see that if $|z|=2$, then $$\lim_{n\to\infty}\left|\frac{nz^n}{2^n}\right|=\lim_{n\to\infty}\frac{n|z|^n}{2^n}=\lim_{n\to\infty}\frac{n2^n}{2^n}=\lim_{n\to\infty}n=+\infty$$ Thus, it fails the term test. For the second question, we can see that the radius of convergence is $1$ by the ratio test, and if $z=-1$, it diverges by the comparison test. If $z=e^{i\theta}$ for $\theta\in(-\pi,\pi)$, then we have $$\left|\sum_{n=2}^N(-1)^nz^n\right|=\left|\frac{1-e^{i(\theta+\pi)(N+1)}}{1-e^{i(\theta+\pi)}}\right|\le\frac2{|1-e^{i(\theta+\pi)}|}$$ $$\frac1{\ln(n)}\to0,\frac1{\ln(n)}<\frac1{\ln(n+1)}$$ Thus, it is bounded for every $\theta\ne\pm\pi$ and converges by the Dirichlet test.
[ "stackoverflow", "0051357607.txt" ]
Q: Find specific x value with y in numpy array I have a numpy array[x,y] in python like this: myarr=np.array([[6,15],[5,10],[7,7],[11,7],[15,10],[13,15]]) print(np.where(myarr==15)) which holds x,y coordinates For example I need to find the x values where their y is 15 which in this case will be 6 and 13. I've tried to solve this problem with np.where but I cant find the answer. I already try this too print(np.where(myarr[1]==15)) but it give me empty values A: myarr[1] means row index 1 line. there is no 15 in row index 1 line. find in the all rows and column index 1. print ( np.where(myarr[:,1]==15) ) and x values are print ( myarr[ np.where(myarr[:,1]==15), 0 ][0] )
[ "stackoverflow", "0045101388.txt" ]
Q: How's JavaScript prototyping done right? After I've read numerous of posts about JavaScript prototyping, written by people the day after writing their first line of code, I have to ask - does anyone know how to make a proper JavaScript prototype chain? How to prototype this very simple thing (?): Continent Country Region City Neighbourhood Then this sample code would work: var södermalm = sweden["södermalm"]; console.info(södermalm.neighbourhood + " is located on the continent " + södermalm.continent); And also this: if (!sweden.neighbourhood) console.warn("Sweden is a country") A: function Continent(nameOfContinent) { this.continent = nameOfContinent; } Continent.prototype.getType = function () { return 'Continent'; } function Country(nameOfCountry, nameOfContinent) { Continent.call(this, nameOfContinent); this.country = nameOfCountry; } Country.prototype = new Continent(); Country.prototype.getType = function () { return 'Country'; } function Region(nameOfRegion, nameOfCountry, nameOfContinent) { Country.call(this, nameOfCountry, nameOfContinent); this.region = nameOfRegion; } Region.prototype = new Country(); Region.prototype.getType = function () { return 'Region'; } function City(nameOfCity, nameOfRegion, nameOfCountry, nameOfContinent) { Region.call(this, nameOfRegion, nameOfCountry, nameOfContinent); this.city = nameOfCity; } City.prototype = new Region(); City.prototype.getType = function () { return 'City'; } function Neighbourhood(nameOfNeighbourhood, nameOfCity, nameOfRegion, nameOfCountry, nameOfContinent) { City.call(this, nameOfCity, nameOfRegion, nameOfCountry, nameOfContinent); this.neighbourHood = nameOfNeighbourhood; } Neighbourhood.prototype = new City(); Neighbourhood.prototype.getType = function () { return 'Neighbourhood'; } let dehradun = new City('dehradun', 'uttarakhand', 'india', 'asia'); let divyaVihar = new Neighbourhood('divya vihar', 'dehradun', 'uttarakhand', 'india', 'asia'); console.log(divyaVihar); console.log(divyaVihar.neighbourHood + " is located on the continent " + divyaVihar.continent); console.log(divyaVihar instanceof Neighbourhood); if(!(dehradun instanceof Neighbourhood)) { console.log(dehradun.getType()) }
[ "stackoverflow", "0001947627.txt" ]
Q: EntityManager fails to instantiate using JPA/Hibernate when I add a OneToMany annotation I have been struggling with not being able to have the EntityManager be instantiated when I add a OneToMany column to a class that already has a OneToMany column. Right now the EducationInfo has a OneToOne to user, since each row will be unique to a person, but I want to be able to load all the education information given a username. I am not changing the orm.xml file when I add the column, I just drop the database so it can be recreated. class User { @Id @GeneratedValue(){val strategy = GenerationType.AUTO} var id : Int = _ @Column{val nullable = false, val length=32} var firstName : String = "" var lastName : String = "" @Column{val nullable = false, val unique = true, val length = 30} var username : String = "" @OneToMany{val fetch = FetchType.EAGER, val cascade=Array(CascadeType.ALL)} var address : java.util.List[Address] = new java.util.ArrayList[Address]() @OneToMany{val fetch = FetchType.EAGER, val cascade=Array(CascadeType.ALL), val mappedBy="user"} var educationInfo : java.util.List[EducationInfo] = new java.util.ArrayList[EducationInfo]() If I don't include the last column then my unit test works fine, but if I include this then all my unit tests fail. Here is the class it is trying to use, and the unit tests for this class works fine: @Entity @Table{val name="educationinfo"} class EducationInfo { @Id @GeneratedValue(){val strategy = GenerationType.AUTO} var id : Long = _ @Column{val nullable = false, val length = 100} var name : String = ""; @OneToOne{val fetch = FetchType.EAGER, val cascade = Array(CascadeType.PERSIST, CascadeType.REMOVE)} @JoinColumn{val name = "educationinfo_address_fk", val nullable = false} var location : Address = _ @ManyToOne{val fetch = FetchType.LAZY, val cascade=Array(CascadeType.PERSIST)} @JoinColumn{val name = "educationinfo_user_fk", val nullable = false} var user : User = _ @Column{val nullable = false, val length = 100} var degree : String = "" @Temporal(TemporalType.DATE) @Column{val nullable = true} var startyear : Date = new Date() var endyear : Date = new Date() @Column{val nullable = true, val length = 1000} var description : String = "" } I am also curious if there is some way to know what the error is that prevents the EntityManager from being instantiated, but the main problem is what may be causing a problem when I add this column to User? UPDATE: Removed a part that was in error. UPDATE 2: I changed the user column in the education entity to be @ManyToOne and all my unit tests failed. The end of my error log is this: 15035 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 15035 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 15047 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory [PersistenceUnit: jpaweb] Unable to build EntityManagerFactory [PersistenceUnit: jpaweb] Unable to build EntityManagerFactory Then EntityManager is null in every test, so it fails. UPDATE 3: The Address entity has no foreign keys to anything, as it is called from several entities. Could this problem be caused by using Apache Derby as the database? Unfortunately I don't get any error message. I run this from within maven, and though I delete the database each time I can't tell what it happening that is wrong. The @ManyToOne from EducationInfo -> User doesn't cause any problems, but @OneToMany -> EducationInfo from User does. UPDATE 4: I added a mappedBy to the User entity as suggested. I had that in another column definition, as I have five definitions that won't work, and I believe they are all for the same reason, so I am just testing with one. Unfortunately it still leads to the EntiyManagerFactory not being built so all the tests fail. FINAL UPDATE: The actual case was cannot simultaneously fetch multiple bags so I just removed the FetchType completely from EducationInfo and the problem went away. A: OneToMany's complement mapping on the other side of association is ManyToOne, it cannot be OneToOne. That's what's causing EntityManager to fail. It works when you remove the last line from User because then you're only left with OneToMany to Address and, although not shown here, presumably Address doesn't have a OneToOne link to User. I'm no Scala expert; in Java you normally get an error and a stack trace printed when EntityManager fails to initialize; error message is not always extremely descriptive but usually says what mapping it has a problem with. Perhaps you need to tweak your logging settings if you don't get that error. I didn't quite understand your model: Basically, a user should be able to have several addresses, so I expect it will become a ManyToMany, but each use can also have several instances of education information, so the need for ManyToOne. That sounds like @OneToMany from User to Address to me and (if "use" meant "user") as @OneToMany from User to EducationInfo. Right now the EducationInfo has a OneToOne to user, since each row will be unique to a person, but I want to be able to load all the education information given a username. That conflicts with above. Either you can have several EducationInfo per User or it's "unique to a person".
[ "stackoverflow", "0025378478.txt" ]
Q: Using squid to access local dev sites from iOS device fails In order to access dev sites hosted on my laptop (apache virtual host) from an iOS device for testing, I want to use squid. I installed squid by getting squidman (http://squidman.net/squidman/). In squidman interface, I set http port to 8080; provided my iOS device's IP in the Clients tab; and commented out the http_access deny to_localhost line in the Template tab (used for building squid config). I then made sure my iOS device and my laptop are connected to the same network, and entered my laptop's IP address and the port number (8080) in the HTTP proxy settings of my iOS device. Last time, this has worked on-and-off. This time, it doesn't work at all (iOS browser shows "cannot connect to the server" or "cannot connect to the proxy" when trying to access one of the local dev sites). I restarted everything just in case, which didn't help. Squid access logs are empty, so I'm not sure where to start troubleshooting this. My other option is to use Charles proxy in the same way, but I would really like to get this free alternative working. A: The problem turned out to be with the network (ping issue between devices on the WiFi); this was probably also the reason why squid has worked on-and-off for me last time. If you have the same problem: try squid (or Charles) on a different network (eg. home network if you previously tried to set it up at work) to check whether the problem disappears.
[ "stackoverflow", "0020524833.txt" ]
Q: How to compare UIImageView name in an if() structure I have some UIImageView's that i want to move around the screen. But the problem is that the background image is also an UIImageView, and therefor also drag able. I know that this != (not equal to) syntax below is not right, so I hope someone inhere can give tell me how to do it. ViewController.h : @interface ViewController : UIViewController{ IBOutlet UIImageView *circle; IBOutlet UIImageView *star; IBOutlet UIImageView *triangle; IBOutlet UIImageView *background; } ViewController.m : - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [[event allTouches] anyObject]; UITouch *drag = [[event allTouches] anyObject]; if([touch view] != background){ <---- LOOK HERE [touch view].center = [drag locationInView:self.view]; } } Hope to find some help, and thanks in advance :) A: You typically don't want to compare objects with normal (in)equality operators, but in this case I think your code will work fine. When you compare objects, the pointer address is compared, so if (obj1 == obj2) { // … } will only evaluate to TRUE if obj1 and obj2 are the same instance, which they are in this case. If you want, you can use the isEqual: method: if ([obj1 isEqual:obj2]) { // … } This test will include the above one, so there's no reason not to use this. This method will also test class equality, and add specific comparisons for the object type. For example, if you compare two NSString objects, the length of the string and the Unicode characters that make up the string must be identical to evaluate to TRUE. In this particular case, though, either will work.
[ "stackoverflow", "0040963376.txt" ]
Q: Remote port forwarding failed on Amazon EC2 I'm trying to use rsub on a remote EC2 instance. I connect to it using ssh -i keyPair.pem -R 52698:localhost:52698 [email protected] However when I successfully connect to the instance I get the welcoming error : Warning: remote port forwarding failed for listen port 52698 The goal of rsub is to set up a tunnel to be able to edit remote files over ssh from my GUI. Any help with this error is welcome! The detailed error (-v) is: OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011 debug1: Reading configuration data /Users/victor/.ssh/config debug1: /Users/victor/.ssh/config line 1: Applying options for * debug1: Reading configuration data /etc/ssh_config debug1: /etc/ssh_config line 20: Applying options for * debug1: /etc/ssh_config line 102: Applying options for * debug1: Connecting to ec2-52-53-211-179.us-west-1.compute.amazonaws.com [52.53.211.179] port 22. debug1: Connection established. debug1: identity file /Users/victor/vict0rsch.pem type -1 debug1: identity file /Users/victor/vict0rsch.pem-cert type -1 debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_6.2 debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH* debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server->client aes128-ctr [email protected] none debug1: kex: client->server aes128-ctr [email protected] none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<2048<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Server host key: RSA a5:e2:ba:33:0a:6a:4b:55:5e:62:8f:1d:d9:bd:eb:9a debug1: Host 'ec2-52-53-211-179.us-west-1.compute.amazonaws.com' is known and matches the RSA host key. debug1: Found key in /Users/victor/.ssh/known_hosts:23 debug1: ssh_rsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Offering RSA public key: /Users/victor/.ssh/id_rsa debug1: Authentications that can continue: publickey debug1: Offering RSA public key: /Users/victor/.ssh/ec2_CS224D_1.pem debug1: Server accepts key: pkalg ssh-rsa blen 279 debug1: Authentication succeeded (publickey). Authenticated to ec2-52-53-211-179.us-west-1.compute.amazonaws.com ([52.53.211.179]:22). debug1: Remote connections from LOCALHOST:52698 forwarded to local address localhost:52698 debug1: Remote connections from LOCALHOST:52698 forwarded to local address 127.0.0.1:52698 debug1: channel 0: new [client-session] debug1: Requesting [email protected] debug1: Entering interactive session. debug1: client_input_global_request: rtype [email protected] want_reply 0 debug1: remote forward success for: listen 52698, connect localhost:52698 debug1: remote forward failure for: listen 52698, connect 127.0.0.1:52698 Warning: remote port forwarding failed for listen port 52698 debug1: All remote forwarding requests processed debug1: Sending environment. A: debug1: remote forward success for: listen 52698, connect localhost:52698 debug1: remote forward failure for: listen 52698, connect 127.0.0.1:52698 Warning: remote port forwarding failed for listen port 52698 It looks like you are trying to open two different port forwarding (localhost and 127.0.0.1), which are basically the same one. Did you set up the forwarding in your ~/.ssh/config too? Running with -vvv might show more information. It can be also disabled on the server using AllowTcpForwarding in sshd_config.
[ "stackoverflow", "0038749346.txt" ]
Q: Web.config: sensitive settings The problem: I would like to run my ASP.NET MVC site locally using IIS, using my Facebook client secret. I would also like to keep the Facebook client secret out of source control. I am publishing all this to Azure, so there is no problem when I'm running my web server in the Cloud. Sensitive settings go straight into the App Service, and never get seen by source control. In principle, keeping the client secret out of source control is easy. I can just add a config source to my app settings in Web.config: <appSettings configSource="facebookClientSecret.config" /> and all of my settings can go into facebookClientSecret.config, which gets added to .gitignore. Therein lies the problem: all of my settings. I don't want to hide all settings from source control: only the sensitive ones. I have tried doing this: <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add configSource="facebookAppSecret.config" /> <add key="StorageConnectionString" value="UseDevelopmentStorage=true" /> </appSettings> But apparently that's "not allowed". Is there a way to have a subset of the app settings sourced from a separate file? A: The file attribute on appSettings fits the bill nicely. <appSettings file="facebookAppSecret.config"> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="StorageConnectionString" value="UseDevelopmentStorage=true" /> </appSettings> Settings will be pulled from the facebookAppSecret.config file as well as the <appSettings></appSettings> entries. It's worth noting also that the contents of that file should only contain a <appSettings></appSettings> block (i.e. it should not contain <?xml version="1.0" encoding="utf-8" ?><configuration>...</configuration> You will need to adjust the Build Action (should be "Content") and Copy To Output Directory project settings for the file (right click on file in Visual Studio -> Properties) so the file is included in the output directory when you build.
[ "stackoverflow", "0026967502.txt" ]
Q: GAE Error 404 after setting redirect www to naked domain on GoDaddy I have been searching an answer this redirecting problem. There are many similar question but I still cannot find how to solve. I have set my domain from GoDaddy for my GAE application as below: Set CNAME for www to ghs.googlehosted.comdomain follow to: https://cloud.google.com/appengine/docs/domain Enable my naked domain by setting A and AAAA records follow to: https://support.google.com/a/answer/2579995 From this step both of my naked domain and my www are working perfectly. However refer to the 'Site Setting' of 'Google WebMaster Tools' it is advised to decide a preferred domain either www or naked domain and set 301 redirect to the preferred one. So I decided to set my naked domain as my preferred one. In my domain setting at GAE and my account at GoDaddy I deleted CNAME for www record and create at GoDaddy 'New Subdomain Forward' of www to http of my naked domain with type 301 (Permanent). However now my www domain come with this error:. 404. That’s an error. The requested URL / was not found on this server. That’s all we know. I checked my naked domain is still work. Could anyone advise what I have been misiing? A: Finally I found solution how to solve this domain redirecting problem. I came to this help article: Updating Your Domain Name's IP Address for Forwarding from GoDaddy Support, stating that I must update the domain address manually so domain name forwarding services work correctly. But instead of replacing all of the '@' Host in A record into this forwarding address I just need to add a separate host record name it 'www' to point the www domain to 50.63.202.1 to be forwarded and left the other original A and AAAA records as they are need for the naked domain to serve from GAE Application. So after updating the records in A Host it will look like this: Host Points To @ 216.239.32.21 @ 216.239.34.21 @ 216.239.36.21 @ 216.239.38.21 www 50.63.202.1 Redirecting is work correctly now. My www domain is now redirecting to my naked domain. Off course the page will took some time to show up than point http directly to the naked domain but seems all is OK. Hope this will also help others who preferably want to set their naked domain (non-www) as the preferred domain rather than the www domain.
[ "stackoverflow", "0024620766.txt" ]
Q: Link_to redirecting wrong I'm having a strange problem with link_to, this is what happens: When I click in this link_to: <li><%= link_to "Sign up", sign_up_path %></li> It redirect to sessions/new, but I want to go to users/new I think my routes.rb is wrong but I don't see anything wrong This is my route.rb: get "sessions/new" get "sign_up" => "users#new", :as => "sign_up" get "log_in" => "sessions#new", :as => "log_in" get "log_out" => "sessions#destroy", :as => "log_out" root :to => "sessions#new" resources :users resources :sessions resources :orchestras resources :conductors resources :instruments resources :integrants If someone can help, Thanks. Update @ChrisPeters said to me see if there is a before_action redirecting me to my sessions/new I verify and I found a before_filter: before_filter :verifyUser, :only => [:orchestras, :conductors, :instruments, :integrants, :users] Because this I'm redirecting to wrong page, I change my users_controller to skip this: skip_before_action :verifyUser, only: [:new] And now it's working. Thanks @ChrisPeters. A: See if there is a before_action intercepting the request and redirecting the user to sessions#new. As you said in your update, it looks like you had missed one: before_filter :verifyUser, :only => [:orchestras, :conductors, :instruments, :integrants, :users] And you were able to resolve by calling skip_before_action: skip_before_action :verifyUser, only: [:new] One small pointer would be to rename your filter method to verify_user because snake_case is the conventional Ruby way to name your methods.
[ "craftcms.stackexchange", "0000009306.txt" ]
Q: Display an entry's level 1 categories only if the entry is not related to any of that category's children I'm struggling with how to do this in Twig... I feel like it would be easier in a full programming language. If an entry's categories look like this: A - A1 - A2 B C - C1 I need to output a list like this: A > A1 A > A2 B C > C1 I can't seem to figure out how to avoid printing all the top-level categories on their own. This is what I've managed to output: A A > A1 A > A2 B C C > C1 I have a feeling I'm going to feel dumb when someone answers this, but any help is appreciated. Edit: I've found a solution. Before listing the categories, I run a for loop on just the entry's level 2 categories and collect their parents' IDs using an empty array and the merge filter. Then, when listing the categories, I put a conditional so that level 1 categories are not listed if their ID is in the array. It seems an awkward way to do it, and I'm still interested in better solutions. A: Collecting all of the categories' ancestors is probably the way to go in that case. So the solution you already posted within your question is more or less the same as I was about to post. Instead of having a conditional in the output loop, you could also prepare an array of your bottom level category models using Craft's without filter (I always try to separate output from query / logic blocks in my templates). This works with any number of category levels. {% set allCategories = craft.categories.relatedTo(entry) %} {% set ancestorCatIds = [] %} {% for category in allCategories %} {% set ancestorCatIds = ancestorCatIds|merge(category.ancestors.ids()) %} {% endfor %} {% set bottomCatIds = allCategories.ids()|without(ancestorCatIds) %} {% set bottomCategories = craft.categories.id(bottomCatIds) %} <ul> {% for category in bottomCategories %} <li>{{ macros.catBreadcrumbs(category) }}</li> {% endfor %} </ul> I made a macro that outputs the category breadcrumbs, to have even less logic in the output block. {% macro catBreadcrumbs(category) %} {% set ancestorCategories = category.ancestors.find() %} {% set ancestorCategories = ancestorCategories|merge([category]) %} {{ ancestorCategories|join(' > ') }} {% endmacro %}
[ "stackoverflow", "0011281261.txt" ]
Q: Indent the text in docbook I want to indent my text in the article I am writing in docbook 5. I also need to add colors to my text. Is that possible? If so how? I tried indenting as follows but it was not visible when I took the html output of it.(Here I tried to align the text "Kerfun" to the center) I have no idea regarding the colour change. Can someone please tell me how? Where have I gone wrong? <dbk:para text-indent="center">Kerfun</dbk:para> <dbk:para text-indent="center"> <dbk:emphasis role="bold">Fadiah</dbk:emphasis> </dbk:para> A: You haven't specified your OS or toolchain. To format your xml: I'd suggest using the "xmllint -format" command To validate your xml: Same command could be used to ensure your document is valid against the docbook schema To colorize your xml: That very much depends on what editor you use. Personally I'm a fan of gvim which has XML high-lighting enabled by default. Update As stated I'm not a windows guy but 2 minutes of googling lead me to the following: Notepad++ appears to have an XML plugin. Source was the following link
[ "stackoverflow", "0060291809.txt" ]
Q: Create an instance, execute a long script and then kill it I'm starting to use Google Cloud Engine, what I need to do is to use the python-api to: Create a new instance (i'm already doing this) Execute a python script, a very long one taking about 12 hours Once the execution is finished, delete the instance Now im using a startup-script, but I'm having some problems as it's not loading conda correctly, and I need to run 'conda activate'. I'm actually thinking a startup script might not be the best way... Also, is there any way to monitor the progress of the script on the instance? I found this getSerialPort method, but seems I need to do a sort of busy-waiting calling it all the time and printing the output till it finishes. Thanks, Marcelo A: You need to enable interactive serial console access for a specific instance (there is also a project wide setting): gcloud compute instances add-metadata instance-name \ --metadata serial-port-enable=TRUE Then listen to the logging on the serial port: gcloud compute connect-to-serial-port instance-name
[ "stackoverflow", "0016968015.txt" ]
Q: Parse QGeoAddress::street() for just the street name I have been fighting with this for a while, so hopefully someone can help me out. I'm open to any and all suggestions. When I query QGeoAddress::street(), I (may) receive both the street number, plus the street name. I would like to get just the street name. Example: King St W -> King St W 99 King St W -> King St W 99a King St W -> King St W ... 1st St -> 1st St 99 1st St -> 1st St 99a 1st St -> 1st St ... 315 W. 42nd -> W. 42nd 42 St. Paul Drive -> St. Paul Drive I need to do this so that the location of two separate devices can be compared via the most recent street name. If a device is at "99 King St W", it is on the same street as "113 King St W", or "113a King St W". As it stands, I don't believe regex is a good, reliable solution as there are too many rules to impose and the variability of street names is working against me. Theoretically, there may be a street called "1 St", which would fail the regex normalizing "1 1st St". Writing my own fuzzy matcher may provide better results, but may fail for shorter street names. I have also considered querying a REST web service, however many of the free services have limitations on requests per day, or a minimum time between requests that would render that method too expensive. Like I say, I'd love to hear what you guys can come up with. Much appreciated :) A: As I said in the comments, the problem here is that the wrong question is being asked. But if you have to, and you can exlude PO boxes (the string ends in a number?), and you limit yourself to addresses in the USA (because you wouldn't believe some of the things you see in the UK), then you might start by detecting a leading number, then appending everything that isn't separated from it by a space. It's hardly perfect, because there'll always be people who write "99 A King St.", rather than "99a King St.". (But then, in the first, is the name of the street "King St." or "A King St."? Unless you know the street yourself, you can't be sure.) The regular expression for this would be "\\d+\\w*". Beyond that, you can try certain heuristics with the results: if they are a single word, exactly matching "St", "Street", "Ave", etc. (there are probably about 20 different words you should check, with or without trailing "." in the case of abbreviations), then you probably have just the street. But before even starting, I would insist that you query the assignment. It's well known, for example, that when inputting addresses, about all you can do is "First line:", "Second line:", etc. Even asking for a post code can be tricky.
[ "stackoverflow", "0061343306.txt" ]
Q: In python when using an if statement with or's why does is it ignore the conditions x = 5 if x == 2 or 4 or 6: print("Even") elif x == 3 or x == 5 or x == 7: print("Odd") I know the or statements should be like the bottom line but I am curious to why when run the output is always even, despite it not being in the if line. When run with the top line like the bottom it works however it treats the bottom as an else so if x was 30 it would still fall into 'odd'. Any explanation to why this is would be greatly appreciated. A: In boolean contexts python implicitly calls bool buitlin on the operands if they're not boolean already to evaluate their truth value but does not constitute them with a boolean, and note that python logical and and or are short-circuit so python starts with x == 2 which is False so it continues and sees number 4 and calls bool(4) which evaluates to True so the whole line returns 4: if 4: and because integers have a boolean value of True you whole condition evaluates to True.
[ "stackoverflow", "0050291822.txt" ]
Q: Fetch Data from json file in React.js I have a json file call data.json such as ( I use React.js): [{"id": 1,"title": "Child Bride"}, {"id": 2, "title": "Last Time I Committed Suicide, The"}, {"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, {"id": 4, "title": "Youth Without Youth"}, {"id": 5, "title": "Happy Here and Now"}, {"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"}, {"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"}, {"id": 8, "title": "Monty Python's The Meaning of Life"}, {"id": 9, "title": "Awakening, The"}, {"id": 10, "title": "Trip, The"}] Im my componentDidMount I have the below: fetch('./data/data.json') .then((response) => response.json()) .then((findresponse)=>{ console.log(findresponse.title) this.setState({ data:findresponse.title, }) }) } and in my render: <ul> <li> {this.state.title}</li>; </ul> I would like to list all the title from my json file, Otherwise it says that .then((response) => response.json()) is an anonymous function . . . How to fix this ? I'm a bit confused many thanks A: You can use async/await. It requires fewer lines of code. async getData(){ const res = await fetch('./data/data.json'); const data = await res.json(); return this.setState({data}); } In the componentDidMount() call the function i.e. componentDidMount(){ this.getData(); } Finally, in your render, you map the array of data render (){ return {<ul>{this.state.data.map(item => <li>{item.title}</li>)} </ul> ) } A: Your response isn't an object with a title property, it's an array of objects, all of which have title properties. this.setState({ data: findresponse }); and then in your render <ul> {this.state.data.map((x, i) => <li key={i}>x.title</li>)} </ul>
[ "stackoverflow", "0037596685.txt" ]
Q: Asp.Net MVC EditorFor Array with template I have a model of ClassA that has a property that is an array of ClassB. public class ClassA { public string ClassAProperty1 { get; set; } public string ClassAProperty2 { get; set; } public ClassB[] MySubCollection { get; set; } } public class ClassB { public string Prop1 { get; set; } public string Prop2 { get; set; } } I'd like to edit my instances of ClassB in a table. I've created an EditorTemplate for ClassB that creates a table row. @model ClassB <tr> <td>@Html.TextBoxFor(m => m.Prop1)</td> <td>@Html.TextBoxFor(m => m.Prop2)</td> </tr> This works great on the edit view for ClassA since MVC does all the field indexing magic itself: @Html.TextBoxFor(m => m.ClassAProperty1) @Html.TextBoxFor(m => m.ClassAProperty2) <table> <tr> <th>Col</th> <th>Col</th> </tr> @Html.EditorFor(m => m.MySubCollection) </table> However, I'd actually like to create an editor template for the array that includes the table tag like this: @model ClassB[] <table> <tr> <th>Col</th> <th>Col</th> </tr> @foreach(var item in Model) { @Html.EditorFor(m => item) } </table> So I can simply do: @Html.TextBoxFor(m => m.ClassAProperty1) @Html.TextBoxFor(m => m.ClassAProperty2) @Html.EditorFor(m => m.MySubCollection) However, the field indexing is not applied with this approach. Is there a way I can accomplish this without having to build the textbox names myself? Being a template, I don't know the property name at the time of use. A: I figured it out. Razor is pretty smart. Using a for loop instead of a foreach solves it: @for (var i = 0; i < Model.Length; i++) { @Html.EditorFor(c => Model[i]) }
[ "stackoverflow", "0053932013.txt" ]
Q: How to find what causes the futex facility to fail? I am trying to synchronize 5 processes, they have to be created from the same father. I tried inserting 5 waitpids to wait for the child process to end, but the code never reaches D4 and D5. #include <unistd.h> #include <semaphore.h> #include <stdlib.h> #include <sys/wait.h> void func1(sem_t sem1, sem_t sem2); void func2(sem_t sem1, sem_t sem2); void func3(sem_t sem1, sem_t sem2); void func4(sem_t sem1, sem_t sem2); void func5(sem_t sem1, sem_t sem2); int main() { sem_t s1; sem_t s2; sem_init(&s1, 1, -1); sem_init(&s2, 1, -1); void (*arr[5])(sem_t, sem_t) = {func1, func2, func3, func4, func5}; int pid; for (int i=0; i<5; i++) { pid = fork(); if (pid == 0) { arr[i](s1, s2); break; } } return 0; } void func1(sem_t sem1, sem_t sem2) { system("echo D1"); sem_post(&sem1); } void func2(sem_t sem1, sem_t sem2) { system("echo D2"); sem_post(&sem1); } void func3(sem_t sem1, sem_t sem2) { system("echo D3"); sem_post(&sem2); } void func4(sem_t sem1, sem_t sem2) { sem_wait(&sem1); system("echo D4"); sem_post(&sem2); } void func5(sem_t sem1, sem_t sem2) { sem_wait(&sem2); system("echo D5"); } I expect D4 to be shown after D1 and D2, and D5 to be shown last (D3 in independent from D1,D2,D4). But my code never reaches D4 because the futex facility returns an unexpected error. Output: The futex facility returned an unexpected error code.D1 D2 D3 A: You're passing the semaphores by value, which is incorrect, as the sem_t variable in each function is a copy of the original. (That's why functions such as sem_init(), sem_post(), and sem_wait() all take addresses of the semaphore as an argument.) You need to pass the semaphores by address, so each function operates on the original semaphores: void func1(sem_t *sem1, sem_t *sem2); void func2(sem_t *sem1, sem_t *sem2); void func3(sem_t *sem1, sem_t *sem2); void func4(sem_t *sem1, sem_t *sem2); void func5(sem_t *sem1, sem_t *sem2); and void (*arr[5])(sem_t *, sem_t *) = {func1, func2, func3, func4, func5}; And call the function as: arr[i](&s1, &s2); The functions should then take the form: void func1(sem_t *sem1, sem_t *sem2) { system("echo D1"); sem_post(sem1); } Note that the address passed to func1() is passed directly to sem_post(). Edit: As others have noted, you're initializing the semaphores incorrectly. You can't initialize a semaphore to a negative value. Proper shared semaphores As noted in the comments, the semphores aren't in memory shared between the multiple processes. One way to put the semphores in shared memory is to use mmap(): #include <sys/mman.h> int main() { ... // map a 4k page of shared memory (assumes a sem_t is small // enough to fit at least two) void *sharedMem = mmap( 0, 4 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0 ); // use the mmap()'d memory as shared semphores sem_t *semArray = ( sem_t * ) sharedMem; // initialize the semaphores sem_init( &( semArray[ 0 ] ), 1, 0 ); sem_init( &( semArray[ 1 ] ), 1, 0 ); The calling code becomes arr[i](&( semArray[ 0 ] ), &( semArray[ 1 ] ));
[ "stackoverflow", "0029669327.txt" ]
Q: Archiving Xcode Project Errors I am trying to archive my project to upload it in TestFlight. But I keep on getting these errors: Can anyone help me on these errors, especially with the Alamofire issues? A: please add missing icon as per suggested by xcode and then select your Project pbx file -> Targets -> General -> Deployment target. and select ios 8.0. Please also change it into plist file.
[ "stackoverflow", "0048296125.txt" ]
Q: Time triggered Azure Function and queue processing I have a Function called once a day processing all messages in a queue. But I would like to also have the retries and poison messages logic as with the Queue Trigger. Is this somehow possible? A: So at that point you function is purely a timer triggered function and from there you are no different than a console app in terms of how you would have to process messages from a queue with your own client connection, message loop, retrying and dead lettering (poison) logic. It's honestly just not the right tool for that job. One approach I suppose you could consider if you wanted to be creative so that you could benefit from using an Azure Function's built in queue trigger behavior while still controlling what time the queue is processed is actually starting and stopping the function instance itself via something like Azure Scheduler. Scheduling the starting of the function is pretty straightforward and, once started, it will immediately begin draining the queue. The challenge is knowing how to stop it. The Azure Function runtime with the queue binding won't ever stop on its own as it's reading off the queue using a pull model so it's just gonna sit there waiting for new messages to arrive, right? So stopping it is really a question of understanding the need of the business. Do you stop once there's no more messages left for that day? Do you stop at a specific time of day? Etc. There's no correct answer here, it's totally domain specific, but whatever that answer is will dictate the exact approach taken. Honestly, as I said earlier on, I'm not sure this is the right tool for the job. Yeah, it's nice that you get the retry and poison handling, but you're really going against the grain of the runtime. I would personally suggest you look into scheduling this simple console executable, executed in a task-like fashion using Azure Container Instances (some docs on that approach here). If you were counting on the auto-scale of Azure Functions, that's totally something you can get from Azure Container Instances as well.
[ "math.stackexchange", "0003128344.txt" ]
Q: What is $\sup \emptyset$ (if exists) w.r.t the usual ordering on ordinals? My textbook Introduction to Set Theory 3rd by Hrbacek and Jech defines the supremum of a set $X$ of ordinals as follows: Clearly, If $X=\emptyset$, then $\bigcup \emptyset$ is undefined. So I would like to ask what is $\sup \emptyset$ (if exists). IMHO, $\sup \emptyset = 0$ because $0$ is an upper bound of $\emptyset$. This is a vacuous truth (every element of $\emptyset$ is less than or equal to $0$). $0$ is the least ordinal. Thus if $\alpha$ is an upper bound of $\emptyset$, then $0 \le \alpha$. Thank you for your help! A: This elaborates on Greg Martin's comment: $\bigcup\emptyset$ is in fact well defined. By definition it is $$\{x:\exists y\in\emptyset(x\in y)\},$$ which is simply $\emptyset$. The intersection $\bigcap\emptyset$ is problematic - or, to put it precisely, the class $$\{x:\forall y\in\emptyset(x\in y)\}$$ is not a set (it's all of $V$). With a bit more precision: $\bigcup\mathcal{C}$ and $\bigcap\mathcal{C}$ always define a class for every class $\mathcal{C}$. Additionally we have that in case $\mathcal{C}$ is a set, the class $\bigcup\mathcal{C}$ is also a set. This is all precisely expressible and provable in, say, NBG; in ZFC (which can't directly talk about classes) we have to employ the usual classy circumlocutions. So the standard definition works (and coincides with intuition): $sup(\emptyset)=\bigcup\emptyset=\emptyset=0$. The point where we have an issue is when we try to calculuate the infimum of the emptyset, since that corresponds to $\bigcap\emptyset$.
[ "stackoverflow", "0006952014.txt" ]
Q: Silverlight: Get RowGroupHeader value in DataGridRowGroupHeader event I am grouping datagrid upto one sub-level. Like this: CollectionViewSource pageView = new CollectionViewSource(); pageView.GroupDescriptions.Add(new PropertyGroupDescription("Category")); pageView.GroupDescriptions.Add(new PropertyGroupDescription("SubCategory")); tasksDataGrid.ItemsSource = pageView.View; In my case some records doesn't have Subcategory value.Those records will display under empty row group header of Subcategory in datagrid. I would like to display directly under Category row group header instead of empty header. private void TaskDataGrid_LoadingRowGroup(object sender, DataGridRowGroupHeaderEventArgs e) { string RowGroupHeader = // how to get currently loading header value if(RowGroupHeader == string.Empty) { e.RowGroupHeader.Height = 0; } } I can't get currently loading RowGroupHeader value.How can i get RowGroupHeader value in LoadingRowGroup event. Help me on this. A: This solved the problem. private void TaskDataGrid_LoadingRowGroup(object sender, DataGridRowGroupHeaderEventArgs e) { var RowGroupHeader = (e.RowGroupHeader.DataContext as CollectionViewGroup); if (RowGroupHeader != null && RowGroupHeader.Items.Count != 0) { MasterTask task = RowGroupHeader.Items[0] as MasterTask; if (task != null && task.SubCategoryName == null) e.RowGroupHeader.Height = 0; } } Thanks djohnsonm for your help.
[ "stackoverflow", "0014813889.txt" ]
Q: asp.net mvc 3, glimpse and null reference error I installed glimpse a few days ago. Ever since I installed it I get this weird error that pops up every once in a while. I am not sure if the error is because of glimpse or was it glimpse that reveal the error to me. Any hows, if any one has a clue what can be this error all about and how can I solve it, I highly appreciate the help!!!! the stack: at System.Web.HttpContextWrapper..ctor(HttpContext httpContext) at Glimpse.AspNet.AspNetFrameworkProvider.get_HttpRequestStore() at Glimpse.Core.Framework.GlimpseRuntime.GetTabStore(String tabName) at Glimpse.Core.Extensibility.TabSetupContext.GetTabStore() at Glimpse.AspNet.GlimpseTraceListener.get_FirstWatch() at Glimpse.AspNet.GlimpseTraceListener.InternalWrite(String message, String category) at System.Diagnostics.TraceInternal.TraceEvent(TraceEventType eventType, Int32 id, String format, Object[] args) at Elmah.ErrorMailModule.ReportError(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch() A: This has been verified as a bug in Glimpse. You can track the progress of the fix on the Glimpse GitHub Issue Tracker. I expect this bug to be fixed within the next few days and available in the nightly builds and next release. UPDATE Feb 13 2013 This issue has now been fixed and will be available in Glimpse 1.0 stable, which will be out shortly. If you'd like to use it right way, grab the nightly build from Feb 13+.
[ "stackoverflow", "0061137399.txt" ]
Q: Permission error while deploying to app enginewith service account I want to deploy my app via google service account. I am using the test-version of googlecloud with billing enabled. I granted the following permissions to my service account: App Engine Administrator App Engine Deployer App Engine Service Administrator Cloud Build Service Account Cloud Build Editor Storage Administrator When I try to login via keyfile with gcloud auth activate-service-account --key-file file.json and then trying to deploy the app with the service account with the following command: gcloud --quiet --project projecid app deploy app.yaml I get the following error: (gcloud.app.deploy) Permissions error fetching application [apps/projectid]. Please make sure you are using the correct project ID and that you have permission to view applications on the project. Also I might have to say, that I am using a account ID which was used before. Do you guys have an idea what I could do? It works, when I deploy it with my normal google account and a normal login. But I need that because of gitlab-ci A: I have tried to reproduce your situation by creating a new service account and giving it the roles you listed. I have authorized access to GCP with its key using the gcloud auth activate-service-account --key-file=<KEY-FILE> command but the deployment has been successful for me. Run the gcloud auth list command to make sure you're authorized with the correct service account. Also you can try adding the --verbosity=debug flag to the deployment command to see if you can find anything useful in the error logs if the error occurs. From the error description, however, it seems that you might also have passed an incorrect project ID when deploying the application: gcloud --quiet --project projecid app deploy app.yaml - make sure it is not the case.
[ "stackoverflow", "0017331216.txt" ]
Q: Compare two times without regard to Date associated - Ruby I am trying to find the difference in time (without days/years/months) of two different days. Example: #ruby >1.9 time1 = Time.now - 1.day time2 = Time.now #code to make changes #test: time1 == time2 # TRUE My solution: time1 = time1.strftime("%H:%M").to_time time2 = time2.strftime("%H:%M").to_time #test time1 == time2 #True #passes I was wondering if there was a better way of doing this? Maybe we could keep the Date the same as time1/time2? A: I think you actually want the following: ((time2 - time1) % (60 * 60 * 24)) == 0
[ "stackoverflow", "0007268322.txt" ]
Q: How to prevent Flash from blurring an image after zooming with the `z` property? I'm currently testing various ways to zoom images (or rather, whole DisplayList hierarchies). Using scaleX and scaleY works quite well, but when I use the z property to zoom the image (by placing it further away) the image gets blurred when returning to z=0. The image is put in a Sprite ("groundLayer") and that Sprite itself is put in another Sprite ("zoomLayer"). Whenever I'm zooming I'm manipulating properties of the "zoomLayer" only. This image was taken right after returning scaleX and scaleY back to 1.0: This image was taken right after returning z back to 0.0: I've tried searching for information about this phenomena but couldn't really find anything useful. Can anyone explain what's happening there? Why is Flash blurring the image after manipulating the zproperty? Is there a way to prevent that (well, other than obviously leaving z alone)? A: whenever you introduce the 3D you are operating under a different rendering engine, it makes things blurry as hell and really should be avoided if possible. To counteract the problem when returning to its original size you need to set mc.transform.matrix3D = null; then it will return to 2D space and be rendered normally again. if you are wanting to do it while at a different point then have a look through exampes hereto try and pick out something more useful to you: I see no reason in this example why you would prefer to be using the 3d engine rather than the 2d scale.
[ "stackoverflow", "0021825556.txt" ]
Q: What is the behavior when throwing an exception without setting out parameter? What is the defined behaviour in C# for when an exception is thrown before setting the value of an out parameter, and you then try to access the parameter? public void DoSomething(int id, out control) { try { int results = Call(Id); control = new CallControl(results); } catch(Exception e) { throw new Exception("Call failed", e); } } //somewhere else DoSomething(out Control control) { try { DoSomething(1, out control); } catch() { // handle exception } } // later Control control; DoSomething(out control) control.Show(); The compiler normally complains about exiting the method before setting the out parameter. This seems to outsmart it from protecting me from myself. A: What is the defined behaviour in C# for when an exception is thrown before setting the value of an out parameter, and you then try to access the parameter? You can't do so. The variable will still not be definitely assigned, unless it's definitely assigned before the method call. If the variable was definitely assigned before the method call, then it will still be definitely assigned - but unless the method assigned a value before the exception was thrown, the variable's value will remain untouched: class Test { static void JustThrow(out int x) { throw new Exception(); } static void Main() { int y = 10; try { JustThrow(out y); } catch { // Ignore } Console.WriteLine(y); // Still prints 10 } }
[ "graphicdesign.stackexchange", "0000118850.txt" ]
Q: Gimp Python-Fu how to copy a channel Suppose I want to copy the red channel of an image (thus creating a new channel). How do I do that with Python-Fu? EDIT: basically, I need to create luminosity masks. So far, I tryed the following code: # get active layer layer = pdb.gimp_image_get_active_layer(image) # copy the selected layer layer_copy = pdb.gimp_layer_new_from_drawable(layer, image) # insert the layer_copy on top of the layers stack pdb.gimp_image_insert_layer(image, layer_copy, None, 0) # desaturate the layer pdb.gimp_drawable_desaturate(layer_copy, DESATURATE_LIGHTNESS) # select the red channel ch = pdb.gimp_channel_new_from_component(image, 0, "testchannel") pdb.gimp_image_insert_channel(image, ch, 0, 1) Unfortunately I got the error TypeError: wrong parameter type on the last command pdb.gimp_image_insert_channel(image, ch, 0, 1) A: Your third argument should be None: pdb.gimp_image_insert_channel(i, c, None,0) The doc is mostly written with the script-fu point if view, where items are just integer ids, and "no item" is therefore 0. In python-fu, you pass object references, so "no item" is None. You can do the same thing more simply (but with a bit less control) using: image.insert_channel(channel) Btw, you can also look at the python-fu object methods, using image.active_layer is a lot more readable than pdb.gimp_image_get_active_layer(image).
[ "android.stackexchange", "0000149521.txt" ]
Q: Are deleted WhatsApp messages still recoverable even after deleting a contact I deleted a particular WhatsApp conversation. Then I deleted the same contact. Now I uploaded the contact again but I am unable to see my deleted messages. I don't see the option of restoring messages after reinstalling WhatsApp. Why is this so? And is there a way out? A: If you have automatic backups sent to Google Drive, that will be your easiest solution. If not, search for a local backup on your phone itself and recover with this method: Your phone will store up to the last 7 days worth of local backup files (Google Drive will only have the most recent). If you wish to restore a local backup which is not the most recent, you will need to do the following: Download a file manager. In the File Manager, navigate to sdcard/WhatsApp/Databases. If your data is not stored on the SD card, you may see internal storage or main storage instead of sdcard. Rename the backup file you wish to restore from msgstore-YYYY-MM-DD.1.db.crypt12 to msgstore.db.crypt12. It is possible that your earlier backup may have been on an earlier protocol, such as crypt9 or crypt10. Do not change the number of the crypt extension. Uninstall WhatsApp. Install WhatsApp. Tap Restore when asked. https://www.whatsapp.com/faq/en/android/20887921
[ "stackoverflow", "0011485508.txt" ]
Q: Use of the identity function in JavaScript I use the identity function in all my JavaScript programs: function identity(value) { return value; } The reason is that I often need differentiate between primitives types (undefined, null, boolean, number and string) and object types (object and function) as returned by the typeof operator. I feel using the indentity function for this use case very succuint: if (new identity(value) == value); // value is of an object type if (new identity(value) != value); // value is of a primitive type The identity function is much smaller and simpler than the following code: function isObject(value) { var type = typeof value; return type == "object" || type == "function"; } However on reading my code a friend of mine complained that my hack is misleading and more computationally expensive than the above alternative. I don't want to remove this function from any of my programs as I believe it's an elegant hack. Then again I don't write programs solely for myself. Is there any other use case for the identity function in JavaScript? A: IMHO: new identity(value) == value means absolutely nothing and without extra comment I would have to think for a while to figure out what the intent was. On the other hand: isObject(value) is obvious from the very beginning, no matter how it is implemented. Why can't you use your hack inside a function named isObject()? BTW More suited for http://codereview.stackexchange.com. A: I updated my "speedtest" to test if the right results are returned … they aren't: If you compare with new identity(x) == x, then null is deemed an object. === works, though. Such pitfalls speak in favor of the isObject(...) solution. If you compare === 'object'/'function' in the isObject code, then it will be double as fast as your original implementation, and almost a third faster than new identity(x) === x.
[ "stackoverflow", "0033143883.txt" ]
Q: Why is UMASK setting in /etc/login.defs not honoured? I have the UMASK setting in /etc/login.defs set to 077, but when I log in and query it, I get this: $ umask 0007 A: It turns out that in modern Linux distros, PAM's pam_umask.so module controls reading the UMASK setting from /etc/login.defs . However, it tweaks the value used under certain circumstances, as described by pam_umask(8): The PAM module tries to get the umask value from the following places in the following order: · umask= argument · umask= entry in the user's GECOS field · UMASK= entry from /etc/default/login · UMASK entry from /etc/login.defs (influenced by USERGROUPS_ENAB in /etc/login.defs) See /etc/pam.d/common-session on an Ubuntu host to see how pam_umask.so is invoked. According to a comment in /etc/login.defs: If USERGROUPS_ENAB is set to "yes", that will modify this UMASK default value for private user groups, i. e. the uid is the same as gid, and username is the same as the primary group name: for these, the user permissions will be used as group permissions, e. g. 022 will become 002. Therefore it is considered standard behaviour. I'd recommend against disabling USERGROUPS_ENAB because that will stop the creation of a corresponding group upon user creation. To forcibly set the umask without changing this behaviour, create /etc/default/login containing UMASK=077 and comment out UMASK 077 in /etc/login.defs . (PAM = Pluggable Authentication Modules)
[ "photo.stackexchange", "0000100465.txt" ]
Q: Is there an app that shows location-specific times of sunrise, while considering line-of-sight obstructions, such as terrain? Taking sunrise/sunset pictures at the ocean allows for photographs where the sun is placed just above the horizontal plane. This allows for "red ball of fire" pictures, such as the following by Johannes Plenio: : When in the mountains, the terrain often obstructs the horizon so that the sun, for instance, becomes visible later in the morning. By moving the viewpoint relative to the terrain, the line of sight may become unobstructed at an earlier or later time. Since scouting and researching landscape compositions is difficult when you are unfamiliar with the local region, a software tool that helps determine what terrain features influence line of sight to the sun or moon would be a great help to me. Is there such an app, website, or other software that takes locations within a certain area, elevation data from Google's terrain map, along with the sun's position for a given morning or evening to show where the sun will rise or set? I am asking because I have yet to find a resource for this despite having purchased a few photography 'helper' apps such as SunSurveyor. Although the app allows me to approximate the time of appearance for a single location, it doesn't provide a way to show when sunlight is expected to appear or disappear over a wide area. A: The Photographer's Ephemeris is a very popular app used by landscape photographers who need to know when the Moon/Sun is going to be at specific spots. It may be of great help to you. A: I found this partial solution here at StackExchange. While I am not sure of the precision to which this calculation is made, it is a first step. Now, if only the results could be calculated for a specified area and then laid over a map as a contour plot to show sunrise and sunset times... Same goes for the moon! Thanks in advance to @erikwkolstad ☺ Not for mobile yet, but you can also use a free tool that I've developed with a colleague. It computes the actual sunrise and sunset times for any location worldwide, accounting for terrain. The example in the image is for Chamonix in France. Go to suncurves.com to find your own location. Hope you like it! I'm using it for all my outdoor shoots. EDIT I wanted to note that maker of The Photographer's Ephemeris app for iPhone and iPad also makes The Photographer's Transit which seems to addresses the issue of 'apparent rise and set of the sun/moon'. Unfortunately, it seems only to be a feature for a given location and not a contour plot of the results of the 'terrain mapping' calculation. Similarly, the iPhone and iPad app Helios Pro does the same 'apparent sunrise/set' but only for a single area. If I am missing a feature in either of the apps or have made a mistake, please let me know.
[ "stackoverflow", "0045542964.txt" ]
Q: Syntax error. in query expression -Delphi I have following query and face error and i am Using XE8 with MS Access Syntax error. in query expression 'select CCarID from tblcar where Car = (LX008)' Procedure TFNewCarAct.BtnSaveClick(Sender: TObject); begin adoQueryCCA.Close(); adoQueryCCA.SQL.Clear; adoQueryCCA.SQL.Add('INSERT INTO tblcaractivity ([CCarID],[Date],[Millage],[SerRcd],[EOType],[EOQunt],[AirFil],[GOil])'); adoQueryCCA.SQL.Add('values (select CCarID from tblcar where Car = ('+ComboBox2.Text+'))'); adoQueryCCA.SQL.Add('VALUES(:Date,:Millage,:SerRcd,:EOType,:EOQunt,:AirFil,:GOil)'); adoQueryCCA.Parameters.ParamByName('Date').Value:= Edit6.Text; adoQueryCCA.Parameters.ParamByName('Millage').Value:= Edit1.Text; adoQueryCCA.Parameters.ParamByName('SerRcd').Value:= memo1.Text; adoQueryCCA.Parameters.ParamByName('EOType').Value:= Edit2.Text; adoQueryCCA.Parameters.ParamByName('EOQunt').Value:= Edit3.Text; adoQueryCCA.Parameters.ParamByName('AirFil').Value:= Edit4.Text; adoQueryCCA.Parameters.ParamByName('GOil').Value:= Edit5.Text; adoQueryCCA.ExecSQL; ShowMessage('Done'); end; Update: procedure TFNewCarAct.FromShow(Sender: TObject); begin ADOQueryCT.Open; while Not ADOQueryCT.Eof do begin ComboBox1.Items.Add(ADOQueryCT.FieldByName('Name').AsString); ADOQueryCT.Next; end; ADOQueryCT.Close; if ComboBox1.Items.Count > 0 then ComboBox1.ItemIndex := 0; end; procedure TFNewCarAct.OnComboBox1Change(Sender: TObject); begin ComboBox2.Items.BeginUpdate; try ComboBox2.Clear; ADOQueryCC.Parameters.ParamByName('Name').Value := ComboBox1.Text; ADOQueryCC.Open; while Not ADOQueryCC.Eof do begin ComboBox2.Items.AddObject(ADOQueryCC.FieldByName('Car').AsString, ''); ADOQueryCC.Next; end; ADOQueryCC.Close; if ComboBox2.Items.Count > 0 then ComboBox2.ItemIndex := 0; finally ComboBox2.Items.EndUpdate; end; end; The Car in the comboBox2 acquire from the tblecar and want to save the FK in the tblcaractivity table. The suggestion provides by the Victoria now cause "Unspecified error". Can you help how i modify my code to save FK in tblcaractivity table. A: Give a try; Procedure TFNewCarAct.BtnSaveClick(Sender: TObject); begin adoQueryCCA.Close(); adoQueryCCA.SQL.Clear; adoQueryCCA.SQL.Add('INSERT INTO tblcaractivity ([CCarID],[Date],[Millage],[SerRcd],[EOType],[EOQunt],[AirFil],[GOil])'); adoQueryCCA.SQL.Add('VALUES(:CCarID,:Date,:Millage,:SerRcd,:EOType,:EOQunt,:AirFil,:GOil)'); adoQueryCCA.Parameters.ParamByName('CCarID').Value:= Integer(ComboBox2.Items.Objects[ComboBox2.ItemIndex]); adoQueryCCA.Parameters.ParamByName('Date').Value:= Edit6.Text; adoQueryCCA.Parameters.ParamByName('Millage').Value:= Edit1.Text; adoQueryCCA.Parameters.ParamByName('SerRcd').Value:= memo1.Text; adoQueryCCA.Parameters.ParamByName('EOType').Value:= Edit2.Text; adoQueryCCA.Parameters.ParamByName('EOQunt').Value:= Edit3.Text; adoQueryCCA.Parameters.ParamByName('AirFil').Value:= Edit4.Text; adoQueryCCA.Parameters.ParamByName('GOil').Value:= Edit5.Text; adoQueryCCA.ExecSQL; ShowMessage('Done'); end; procedure TFNewCarAct.FromShow(Sender: TObject); begin ADOQueryCT.Open; while Not ADOQueryCT.Eof do begin ComboBox1.Items.Add(ADOQueryCT.FieldByName('Name').AsString); ADOQueryCT.Next; end; ADOQueryCT.Close; if ComboBox1.Items.Count > 0 then ComboBox1.ItemIndex := 0; end; procedure TFNewCarAct.OnComboBox1Change(Sender: TObject); begin ComboBox2.Items.BeginUpdate; try ComboBox2.Clear; ADOQueryCC.Parameters.ParamByName('Name').Value := ComboBox1.Text; ADOQueryCC.Open; while Not ADOQueryCC.Eof do begin ComboBox2.Items.AddObject(ADOQueryCC.FieldByName('Car').AsString, TObject(ADOQueryCC.FieldByName('CCarID').AsInteger)); ADOQueryCC.Next; end; ADOQueryCC.Close; if ComboBox2.Items.Count > 0 then ComboBox2.ItemIndex := 0; finally ComboBox2.Items.EndUpdate; end; end;
[ "stackoverflow", "0041602168.txt" ]
Q: Can I access the 'base part' of my object as if it were an object of its own? Say I have a base class A and a derived class B that adds some extra members. Now I'd like to have a setter function for class B that acceses it's own members directly but assigns the derived members in batch using a temporary A object. Here's some example code: class A { public: int x; int y; A(int arg1, int arg2) : x(arg1), y(arg2) {} }; class B : public A { public: int z; B(int arg1, int arg2, int arg3) : A(arg1, arg2), z(arg3) {} void setB(int arg1, int arg2, int arg3) { /*something here*/ = A(arg1, arg2); this->z = arg3; } }; //edit I guess I wasn't clear that the question isn't really "Can I?" but rather "How can I?". To be even more specific: What can I put in place of /*something here*/ to make setB() actually work the same as: void setB(int arg1, int arg2, int arg3) { this->x = arg1; this->y = arg2; this->z = arg3; } A: Can I access the 'base part' of my object as if it were an object of its own? Yes. It is a complete instance of the parent class, that lives inside the derived class instance. A pointer or a reference to the derived class is convertible to a pointer/reference to the parent. A non-pointer/reference i.e. a value of derived type is convertible to the parent as well, but that creates a copy of the parent subobject, just like converting any other value type to another always creates a copy. Now I'd like to have a setter function for class B that acceses it's own members directly but assigns the derived members in batch using a temporary A object. Simply cast this or the dereferenced reference to the parent class type: (A&)*this = A(arg1, arg2); // or *(A*)this = A(arg1, arg2);
[ "stackoverflow", "0032111467.txt" ]
Q: how to get text aligned left from input box please check the result here:http://jsfiddle.net/2zjv6jcp/ the problem is that on the top i have a select box and because that box is smaller than the other textboxes (and not 80% width) the text below it (straatnaam en nummer) won't be shown and also as you can see all the labels are one up (like contactpersoon is shown before Plaats) how can i align everything good? Hi currently i have this in a fieldset: <div id="content"> <div id="formWrapper"> <form id="msform"> <fieldset id="fieldset3"> <h2 class="fs-title">Aflevergegevens</h2> <h3 class="fs-subtitle">Stap 3: Aflevergegevens</h3> <div class="fs-error"></div> <label for="locationLabel">Locatie</label> <select name="locations"> <option>test</option> </select> <label for="addressLabel" style="float:left;">Straatnaam en nummer</label><input type="text" name="address" id="address" placeholder="Straatnaam en nummer" /> <label for="postalCodeLabel">Postcode</label><input type="text" name="postalCode" id="postalCode" placeholder="Postcode" /> <label for="placeLabel">Plaats</label><input type="text" name="place" id="place" placeholder="Plaats" /> <label for="contactPersonLabel">Contactpersoon</label><input type="text" name="contactPerson" id="contactPerson" placeholder="Contactpersoon" /> <br/> <input type="button" name="previous" class="previous action-button" value="Vorige" /> <input type="submit" name="submit" class="submit action-button" value="Submit" /> <h2>JSON</h2> <pre id="result"> </pre> </fieldset> </form> </div> </div> please check the result here:http://jsfiddle.net/2zjv6jcp/ the problem is that on the top i have a select box and because that box is smaller than the other textboxes (and not 80% width) the text below it (straatnaam en nummer) won't be shown and also as you can see all the labels are one up (like contactpersoon is shown before Plaats) how can i align everything good? A: I updated the fiddle to solve some of your problems: http://jsfiddle.net/2zjv6jcp/19/ Code-Examples: <div class="wrapper"> <label for="address" style="float:left;">Straat/No</label> <input type="text" name="address" id="address" placeholder="Straatnaam en nummer" /> </div> #fieldset1 label,#fieldset3 label { width:20%; float:left; line-height:45px; } Changes: Wrapper around the elements, Corrected the label-fors (has to be exact like the input/select), Line-height for labels (will center it vertically), Paddings/margins and font for inputs/selects, Shortend the labels. Edit: I restructured the code to use less div-wrapper: http://jsfiddle.net/2zjv6jcp/19/
[ "stackoverflow", "0026338982.txt" ]
Q: logger.info is throwing null pointer exception when whole maven project is run under junit test Here is the example code class Temp { public static int someMethod() { Logger logger = LoggerFactory.getLogger(Temp.class); logger.info("Some information");//NullPointerException return 0; } } class ClassToTest { public int methodToTest() { Temp tempInstance = new Temp(); int i = temp.someMethod(); return i; } } class TestAClass { ClassToTest classToTestInstance; @Before public void setUp() { classToTestInstance = new ClassToTest(); } @Test public void testMethodToTest() { int i = classToTest.methodToTest(); } } This is a sceneario. This test case may pass. But in actual code when I run the individual test cases or run the whole test class, Test case passes but when I run the maven project under junit test It fails with NullPointerException. I can not post actual code because it is a proprietary code. Please guide me if someone has faced this type of issue. Stack trace which I am getting when I run my actual code: java.lang.NullPointerException at org.slf4j.impl.Log4jLoggerAdapter.info(Log4jLoggerAdapter.java:304) at Temp at ClassToTest at TestAClass at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at mockit.integration.junit4.internal.JUnit4TestRunnerDecorator.executeTestMethod(JUnit4TestRunnerDecorator.java:142) at mockit.integration.junit4.internal.JUnit4TestRunnerDecorator.invokeExplosively(JUnit4TestRunnerDecorator.java:71) at mockit.integration.junit4.internal.MockFrameworkMethod.invokeExplosively(MockFrameworkMethod.java:40) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) A: This problem was due to because logger was static in Temp class. If instance of Temp class is created in another test class earlier so it can not load the logger for the temp class because it is already loaded. So when we run the whole project under junit test it fails. Because logger for Temp class is somewhere in other test class is already loaded. This problem is resolved by mocking the logger with JMockit. @SubOptimal Thank you for giving time.
[ "stackoverflow", "0061814415.txt" ]
Q: How can I speed up an email-finding regular expression when searching through a massive string? I have a massive string. It looks something like this: hej34g934gj93gh398gie [email protected] e34y9u394y3h4jhhrjg [email protected] hge98gej9rg938h9g34gug Except that it's much longer (1,000,000+ characters). My goal is to find all the email addresses in this string. I've tried a number of solutions, including this one: #matches [email protected] and [email protected] re.findall(r'[\w\.-]{1,100}@[\w\.-]{1,100}', line) Although the above code technically works, it takes an insane amount of time to execute. I'm not sure if it counts as catastrophic backtracking or if it's just really inefficient, but whatever the case, it's not good enough for my use case. I suspect that there's a better way to do this. For example, if I use this regex to only search for the latter part of the email addresses: #matches @bar.com and @foo.com re.findall(r'@[\w-]{1,256}[\.]{1}[a-z.]{1,64}', line) It executes in just a few milliseconds. I'm not familiar enough with regex to write the rest, but I assume that there's some way to find the @x.x part first and then check the first part afterwards? If so, then I'm guessing that would be a lot quicker. A: You can use PyPi regex module by Matthew Barnett, that is much more powerful and stable when it comes to parsing long texts. This regex library has some basic checks for pathological cases implemented. The library author mentions at his post: The internal engine no longer interprets a form of bytecode but instead follows a linked set of nodes, and it can work breadth-wise as well as depth-first, which makes it perform much better when faced with one of those 'pathological' regexes. However, there is yet another trick you may implement in your regex: Python re (and regex, too) optimize matching at word boundary locations. Thus, if your pattern is supposed to match at a word boundary, always start your pattern with it. In your case, r'\b[\w.-]{1,100}@[\w.-]{1,100}' or r'\b\w[\w.-]{0,99}@[\w.-]{1,100}' should also work much better than the original pattern without a word boundary. Python test: import re, regex, timeit text='your_long_sting' re_pattern=re.compile(r'\b\w[\w.-]{0,99}@[\w.-]{1,100}') regex_pattern=regex.compile(r'\b\w[\w.-]{0,99}@[\w.-]{1,100}') timeit.timeit("p.findall(text)", 'from __main__ import text, re_pattern as p', number=100000) # => 6034.659449000001 timeit.timeit("p.findall(text)", 'from __main__ import text, regex_pattern as p', number=100000) # => 218.1561693
[ "stackoverflow", "0014453829.txt" ]
Q: partial ordering with L-value-ref Why this is ambiguous? template<class T> void g(T) {} // 1 template<class T> void g(T&) {} // 2 int main() { int q; g(q); } I understand that this is partial ordering context. And my, possibly erroneous, thinking is: any T& from #2 can be put in #1, but not any T from #1 is legit in #2. So partial ordering should work. A: OK. I think this is what you're looking for. Not diving into the twice-application of the parameter vs. argument type comparison, the following in the standard leaps out at me: C++11 §14.8.2.4p5 Before the partial ordering is done, certain transformations are performed on the types used for partial ordering: If P is a reference type, P is replaced by the type referred to. If A is a reference type, A is replaced by the type referred to. C++11 §14.8.2.4p6 goes on to talk about what happens when both are reference types, but that isn't applicable here (though also an interesting read). in your case, only one is, so it is stripped. From there: C++11 §14.8.2.4p7 Remove any top-level cv-qualifiers: If P is a cv-qualified type, P is replaced by the cv-unqualified version of P. If A is a cv-qualified type, A is replaced by the cv-unqualified version of A. Now both are completely equal, and thus you have your ambiguity, which I believe is solidified from C++11 §14.8.2.4p10. The text of C++11 §14.8.2.4p9 covers both being reference types which, again, is not the case here: C++11 §14.8.2.4p10 If for each type being considered a given template is at least as specialized for all types and more specialized for some set of types and the other template is not more specialized for any types or is not at least as specialized for any types, then the given template is more specialized than the other template. Otherwise, neither template is more specialized than the other. But reading the standard in this section is like deciphering greek to me, so I may be way off base. (no offense to the Greeks =P). It did, however, make me think "a const T& against a T, given the same invoke condition g(q), should also be ambiguous if everything I just read is enforced as-written." Sure enough, I tried it, and the same ambiguity was flagged. A: Your reasoning is correct when these two types are competing in a partial ordering of class template partial specializations, and it is how things work there. But when a reference type is compared against a nonreference type, the general gist is that they are ambiguous in a call scenario if nothing else makes one be preferred over the other. That is, the kind of reference of the reference type doesn't matter in overload resolution when compared against the other, so partial ordering doesnt consider it either.
[ "stackoverflow", "0007253622.txt" ]
Q: C# - How to set SharePoint permissions for user under subsite not Root level I'm trying to add permissions for a user that is under a subsite in SharePoint. I was able to successfully set the permissions for the user on the root level, but I am not sure how to approach the problem for a lower level subsite. Below is what I have at the moment but it crashes although it shows no error building in VS. Any ideas would be great foreach (SPWeb subSite in spSite2.RootWeb.GetSubwebsForCurrentUser()) { if (subSite.Name == "templates") { Console.WriteLine("\nTEMPLATES SITE"); Console.Write("\nApplying 'Read' permission to App_user Account"); spRoleAssignment = new SPRoleAssignment(SPContext.Current.Web.Users[appUserAccount]); spRoleAssignment.RoleDefinitionBindings.Add(SPContext.Current.Web.RoleDefinitions["Read"]); SPContext.Current.Web.RoleAssignments.Add(spRoleAssignment); SPContext.Current.Web.Update(); Console.ForegroundColor = ConsoleColor.Green; Console.CursorLeft = Console.BufferWidth - 16; Console.WriteLine("Applied"); Console.ForegroundColor = ConsoleColor.Gray; } } A: I'm not completely sure what you are trying to achieve nor where your code is supposed to be executed (console application or timer job or in a web part?). I see the following problems: You log to the console (which let's me assume your code runs in a console application), but you access the SPContext.Current, which is only available if your code runs in a HTTP request. You are iterating over a collection of webs. But in your for-each body the SPContext.Current.Web is updated. You do retrieve your web collection via the web.GetSubwebsForCurrentUser(), but are then changing permissions on these objects. This smells a little since updating permissions is an "admin task" and the the method GetSubwebsForCurrentUser is more likely to be used for a low level user context to avoid access denied exception. For instance to safely display a list of webs. You do update permissions/roles on a web, but a check if the web has unique role assignments is missing. You check for a web with the name "templates". Since GetSubwebsForCurrentUser is not recursive there can only be one web named "templates" in this collection. This web can be opened direclty => no need to waste resource by opening every sub web. If your task is to set role permissions on a given web "templates" (which is a 1st level sub web of your root web) you can use the follwing code: // Open the web directly since it is a direct child of the site collection. // Use a using to properly release the resources using (SPWeb web = spSite2.Open("templates")) { SPUser user = web.SiteUsers[appUserAccount]; SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Reader); if (!web.HasUniqueRoleAssignments) { web.BreakRoleInheritance(true); } spRoleAssignment = new SPRoleAssignment(user); spRoleAssignment.RoleDefinitionBindings.Add(roleDef); web.RoleAssignments.Add(spRoleAssignment); // No need to update the web when changing the permissions }
[ "stackoverflow", "0029692722.txt" ]
Q: I get the error android.os.NetworkOnMainThreadException while using AsyncTask (parse json data with gson) I want to get json data and parse them through gson. I am able to do the correct parsing, but for one example that I did, I got this error: android.os.NetworkOnMainThreadException I know that using internet on UI thread is not allowed. My example is simple: In onCreate of the activity is the code: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); kategoriListView =(ListView)findViewById(R.id.kategoriListView); new GetPlacesAsync().execute(placesUrl); } And on the AsyncTask: class GetPlacesAsync extends AsyncTask<String, Void, InputStream> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected InputStream doInBackground(String... params) { DefaultHttpClient client = new DefaultHttpClient(); String url = params[0]; HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); return getResponseEntity.getContent(); } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null; } @Override protected void onPostExecute(InputStream inputStream) { super.onPostExecute(inputStream); Reader reader = new InputStreamReader(inputStream); Gson gson = new Gson(); try { PlacesContainer places = gson.fromJson(reader, PlacesContainer.class); Toast.makeText(MainActivity.this, Integer.toString(places.getCountPlaces()), Toast.LENGTH_SHORT).show(); Toast.makeText(MainActivity.this, places.message , Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.e("READ_PLACES_ERROR", e.toString()); } } } My error is on the lines where I have used try catch block. A: onPostExecute in executed on the UI thread. Read your InputStream in doInBackground.
[ "stackoverflow", "0051181070.txt" ]
Q: Animate a button to the left and right with 20 pixels I want to have my button moved with 20 pixels to the left and I want it after 0.25 second back at the original spot. This is what i got so far: @IBOutlet weak var Like: UIButton! UIView.animate(withDuration: 0.25, animations: { var likeframe = self.Like.frame likeframe.origin.x -= 20 }, completion: { _ in UIView.animate(withDuration: 0.25) { var likeframe = self.Like.frame likeframe.origin.x += 20 } }) Please help! A: You need to change the frame itself UIView.animate(withDuration: 0.25,animations: { self.Like.frame = self.Like.frame.offsetBy(dx:-20,dy:0) }) { _ in UIView.animate(withDuration: 0.25 , animations: { self.Like.frame = self.Like.frame.offsetBy(dx:20,dy:0) }) }
[ "stackoverflow", "0027254550.txt" ]
Q: Calculating Entropy I've tried for several hours to calculate the Entropy and I know I'm missing something. Hopefully someone here can give me an idea! EDIT: I think my formula is wrong! CODE: info <- function(CLASS.FREQ){ freq.class <- CLASS.FREQ info <- 0 for(i in 1:length(freq.class)){ if(freq.class[[i]] != 0){ # zero check in class entropy <- -sum(freq.class[[i]] * log2(freq.class[[i]])) #I calculate the entropy for each class i here }else{ entropy <- 0 } info <- info + entropy # sum up entropy from all classes } return(info) } I hope my post is clear, since it's the first time I actually post here. This is my dataset: buys <- c("no", "no", "yes", "yes", "yes", "no", "yes", "no", "yes", "yes", "yes", "yes", "yes", "no") credit <- c("fair", "excellent", "fair", "fair", "fair", "excellent", "excellent", "fair", "fair", "fair", "excellent", "excellent", "fair", "excellent") student <- c("no", "no", "no","no", "yes", "yes", "yes", "no", "yes", "yes", "yes", "no", "yes", "no") income <- c("high", "high", "high", "medium", "low", "low", "low", "medium", "low", "medium", "medium", "medium", "high", "medium") age <- c(25, 27, 35, 41, 48, 42, 36, 29, 26, 45, 23, 33, 37, 44) # we change the age from categorical to numeric A: Ultimately I find no error in your code as it runs without error. The part I think you are missing is the calculation of the class frequencies and you will get your answer. Quickly running through the different objects you provide I suspect you are looking at buys. buys <- c("no", "no", "yes", "yes", "yes", "no", "yes", "no", "yes", "yes", "yes", "yes", "yes", "no") freqs <- table(buys)/length(buys) info(freqs) [1] 0.940286 As a matter of improving your code, you can simplify this dramatically as you don't need a loop if you are provided a vector of class frequencies. For example: # calculate shannon-entropy -sum(freqs * log2(freqs)) [1] 0.940286 As a side note, the function entropy.empirical is in the entropy package where you set the units to log2 allowing some more flexibility. Example: entropy.empirical(freqs, unit="log2") [1] 0.940286
[ "travel.stackexchange", "0000147711.txt" ]
Q: Can non-resident minors visiting the US go to shooting ranges in California? I'm a 16-year-old from China and will be travelling to the states soon, is it allowed for non-resident minors to go to shooting ranges and operate firearms? (with adult supervision of course) A: Most places, by law, require that all children between the ages of 8 and 18 must be accompanied and directly supervised in the shooting booth by a parent or legal guardian.
[ "stackoverflow", "0062395210.txt" ]
Q: Stop json.loads from capitalizing true or false as values I have some JSON that looks like this.. ... "aaa": "play", "bbb": "fxc", "ccc": true, "ddd": "nat", "eee": "news", ... When I call json.loads(my_json) on this string then it will convert the true into True. Is there anyway to not do this? A: As it stands, it looks like you want to effectively treat JSON booleans as if they were string literals for the terms "true" and "false". With the object_pairs_hook parameter: >>> def no_bool_convert(pairs): ... return {k: str(v).casefold() ... if isinstance(v, bool) else v for k, v in pairs} >>> json.loads('{"foo": "fxc", "ccc": true}', ... object_pairs_hook=no_bool_convert) {'foo': 'fxc', 'ccc': 'true'} Note that this does not fundamentally re-write the JSON parser; the value is still parsed as a boolean, but then convert back into a lowercase str.
[ "english.meta.stackexchange", "0000013240.txt" ]
Q: RIP Oxford “living” Dictionaries Don't know when this happened, but Oxford Living Dictionaries is no more. It is now called Lexico (powered by Oxford) whatever that means… Tsk! You'd think they'd have the decency to consult us before changing the name of their online dictionary… again (rolls eyes). Now what do we do? All those citations, attributions, acronyms: EOD, OED, OD, OLD, ODO, OMG do we have to change them all? Arggghh! Visit any post that bears a direct link to Oxford Dictionaries (online) and the name Lexico will now pop up. Oh, and it's changed colour too. It's now green. A: Mehhhhhhh, the name change isn't worth doing mass edits over. Nor is the change in URL, since you can click on most old URLs and be taken to the right page on the new site. There are many thousands of posts that link to oxforddictionaries.com (more specifically ~11k) and most of these links are still good and don't really need editing, since they just redirect to the current lexico.com site. Most. For non-critical issues like this, I fix them when I fix other issues on the same page, or if the question is already bumped and on the home page. Some links have been broken by this change, which is a more critical issue, so it might be a good idea to do some active editing, as long as we don't flood the home page. Right now, I see that the change has broken many (almost all?) of the blog links. I don't know if they're planning on reposting these articles on the new site, so I'm preparing for the worst. Not all of these URLs were saved in either of the archiving services I know of, so I've been saving Google's cached version of the page into Archive.org (the cached page is most easily found by searching Archive.is). Unfortunately saving any URLs that have not been backed up needs to be done as soon as possible, since Google caches don't last forever :/ (Yes, my method is complicated, but I do it this way for a reason.) And then there are some links to the regular dictionary entries that were broken a while ago by a different URL change, which can be found here. Plus, some URLs were also broken when another one of Oxford's dictionaries (the OALD) changed URLs; a list of posts affected by this can be found here. While I'm on the subject, I'll also note that there are old broken Google NGrams links/images in these posts. I've been fixing these every now and then for a while. With the new Lexico site, another thing I noticed is that there is now only one dictionary instead of two ("Dictionary" and "Dictionary (US)", switched via the dropdown at the top of the page). This really isn't as much of a loss as it sounds, since both dictionaries were very close in content (see links above). Therefore I would consider this another non-critical issue for most posts. There are also a couple of questions about dictionaries, especially here on meta, that could use updating (even if the links aren't technically broken) such as: What's the relationship between various Oxford dictionaries? (OED vs ODO vs ODE vs NOAD) List of common abbreviations and acronyms (NOAD, ESL, PIE...) Is Google Dictionary a valid definition reference (in particular in answers)?
[ "tex.stackexchange", "0000352030.txt" ]
Q: Change footer classicthesis which loads scrlayer-scrpage I am using the classicthesis style which loads scrlayer-scrpage. I like most parts about this style but want to change a few things. One thing I used to do in other documents is to place a colored box next to the page number in the footer. I normally did it like this: \documentclass[a4paper,11pt,fleqn]{book} \usepackage{color} \usepackage{fontspec} \setlength{\textwidth}{146.8mm} % = 210mm - 37mm - 26.2mm \setlength{\oddsidemargin}{11.6mm} % 37mm - 1in (from hoffset) \setlength{\evensidemargin}{0.8mm} % = 26.2mm - 1in (from hoffset) \setlength{\topmargin}{-2.2mm} % = 0mm -1in + 23.2mm \setlength{\textheight}{221.9mm} % = 297mm -29.5mm -31.6mm - 14mm (12 to accomodate footline with pagenumber) \setlength{\headheight}{14pt} \usepackage{fancyhdr} \fancyhf{} \renewcommand{\footrulewidth}{0pt} \fancyfoot[EL]{\makebox[0pt][r]{\color{Black}\rule[0pt]{0.55\marginparwidth} {6pt}\makebox[0.16\marginparwidth][r]{\bfseries\sffamily\color{black}\fontspec[] {MetaBoldLF-Roman}\thepage}}}% \fancyfoot[OR]{\makebox[0pt][l]{\makebox[0.16\marginparwidth][1]{\bfseries\sffamily\color{black}\fontspec[]{MetaBoldLF-Roman}\thepage}\color{Blac}\rule[0pt]{0.55\marginparwidth}{6pt}}}% \fancypagestyle{plain}{ \fancyhf{} \renewcommand{\headrulewidth}{0pt} \renewcommand{\footrulewidth}{0pt} \fancyfoot[EL]{\makebox[0pt][r]{\color{black}\rule[0pt] {0.55\marginparwidth}{6pt}\makebox[0.16\marginparwidth][r] {\bfseries\sffamily\color{black}\fontspec[]{MetaBoldLF-Roman}\thepage}}}% \fancyfoot[OR]{\makebox[0pt][l]{\makebox[0.16\marginparwidth][l] {\bfseries\sffamily\color{black}\fontspec[]{MetaBoldLF-Roman}\thepage}\color{black}\rule[0pt]{0.55\marginparwidth}{6pt}}}}% \fancypagestyle{addpagenumbersforpdfimports}{ \fancyhead{} \renewcommand{\headrulewidth}{0pt} \fancyfoot{} \fancyfoot[EL]{\makebox[0pt][r]{\color{black}\rule[0pt] {0.55\marginparwidth}{6pt}\makebox[0.16\marginparwidth][r] {\bfseries\sffamily\color{black}\fontspec[]{MetaBoldLF-Roman}\thepage}}}% \fancyfoot[OR]{\makebox[0pt][l]{\makebox[0.16\marginparwidth][l] {\bfseries\sffamily\color{black}\fontspec[]{MetaBoldLF-Roman}\thepage}\color{black}\rule[0pt]{0.55\marginparwidth}{6pt}}}}% \begin{document} \chapter{hello Word} Hello world \chapter{hello Word2} Hello world 2 \end{document} Can somebody help me translate this to the classicthesis file? Also want it to appear on the chapter starting pages. A: If I understand the question, your example does currently not really show, what you want, because it does not show the page number in the page foot on even pages or chapter pages. So I cannot decide whether or not the following is really what you expect: \documentclass[a4paper,11pt,fleqn]{book} \usepackage{color} \usepackage{fontspec} \setlength{\textwidth}{146.8mm} % = 210mm - 37mm - 26.2mm \setlength{\oddsidemargin}{11.6mm} % 37mm - 1in (from hoffset) \setlength{\evensidemargin}{0.8mm} % = 26.2mm - 1in (from hoffset) \setlength{\topmargin}{-2.2mm} % = 0mm -1in + 23.2mm \setlength{\textheight}{221.9mm} % = 297mm -29.5mm -31.6mm - 14mm (12 to accomodate footline with pagenumber) \setlength{\headheight}{14pt} % Put \marginparwidth onto the page \setlength{\marginparwidth}{\dimexpr\paperwidth-\oddsidemargin-1in-\textwidth-\marginparsep} \usepackage[footwidth=textwithmarginpar]{scrlayer-scrpage} \clearpairofpagestyles \ihead{\headmark} \rofoot*{% \makebox[\dimexpr\marginparsep+\marginparwidth\relax]{% \pagemark\hfill\rule{.55\marginparwidth}{6pt}% }% } \lefoot*{% \makebox[\dimexpr\marginparsep+\marginparwidth\relax]{% \rule{.55\marginparwidth}{6pt}\hfill\pagemark }% } \usepackage{mwe} \begin{document} \blinddocument \end{document} If you want to change the font at the page footer, just use something like \setkomafont{pagefoot}{\bfseries}% You can also use \fontspec here. If you want to change the color of the rule, e.g. red color, use either \textcolor{red}{\rule{.55\marginparwidth}{6pt}} or \addtokomafont{pagefoot}{\color{red}} \addtokomafont{pagenumber}{\normalcolor}
[ "askubuntu", "0000005241.txt" ]
Q: Ubuntu: "Editable Menu Accelerators" (on a per app basis). Where is this option? I keep seeing references to a config option calld Editable Menu Accelerators or Editable Menu Shortcut Keys. This is exactly what I need, but all the directions I've read about how to find that feature lead me to a dead-end. I am running with Ubuntu 10.4, and have checked its help file Desktop User Guide. In Section 8.2.1.4. Interface Preferences it says: "...the Interface tabbed section in the Appearance preference tool to customize the appearance of menus, menubars, and toolbars for applications that are part of GNOME." This Interface tab does not exist in Ubuntu 10.4 (... okay, who moved it?! .. where is i?) Is this feature still available? I assume it does exist, and is now accessible some other way... but how? PS: To clarify... I want to modify a menu-item accelerator for a specific app (not a system-wide hot-key) A: It seems that GNOME decided to remove the interface tab because "basically everything there is a user experience design cop-out. It only belongs in a tweak UI tool." So now the only way to enable that option is hidden deep in the gconf settings. Launch gconf-editor from the terminal or the "Run Application" dialog (Alt-F2). Navigate to desktop>gnome>interface and check can_change_accels Or just run this line in a terminal: gconftool --set /desktop/gnome/interface/can_change_accels --type=bool True
[ "stackoverflow", "0038734160.txt" ]
Q: How can I customize COUNT nodes with css I have a drupal view that show nodes title and nodes count. I got that node count from [contextual filters>content(type)>display a summary>display record count with link]. SQL query for that shows: SELECT node.type AS node_type, COUNT(node.nid) AS num_records FROM {node} node WHERE (( (node.status = '1') AND (node.type IN ('company', 'job')) )) GROUP BY node_type ORDER BY node_type ASC LIMIT 3 OFFSET 0; And it appears like: Company(2) Job(4) What I want to do is to customize COUNT(node.nid) with css. For example, change font-size of count,position of that count. How can I customize that count with css?Or any other way to get that count? A: Option 1 Override the template file for the views row. In the views interface, under advanced, click Theme: information. There you will find a list of the files that views looks for to theme styles, rows, fields etc. The one that is currently being used will be bold. The default theme files are in the modules/views/theme/ folder. You probably want to override the Row style output. Create a file with one of the names suggested in the views theme information and put it into your themes folder, then copy and paste the code from the original views template file and alter it with what output you need. A handy function to find what variables are available in a template file is get_defined_vars(). If you have the devel module installed, calling dpm(get_defined_vars()); in your template file will give you a nice way to see all the variables you can use in your template file. Option 2 Click on Rewrite Results then Rewrite the output of this field in the field settings and add your html and use replacement patterns Option 3 - probably the easiest Hide the original fields and add a Global:Custom text field and add your html and use replacement patterns in the output. Option 4 Override the template_preprocess_views_view_fields function.
[ "stackoverflow", "0023285634.txt" ]
Q: iOS CGAffineTransformScale keep left anchor I am using CGAffineTransformScale to scale down my UITableView, it is scaling it down correctly but i can't seem to set the anchor point correctly. self.myTableView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.8, 0.8); If I don't set the anchor point it scales it down from the center but as my requirement I need to keep the left top corner point fixed. For this I've used this self.myTableView.layer.anchorPoint = CGPointMake(0, 0); self.myTableView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.8, 0.8); But this doesn't set the anchor correctly.. One more thing I haven't used AutoLayout Please can anyone help me out on this…? thanks in advance.. A: Try this [self setAnchorPoint:CGPointMake(0, 0.5) forView:recognizer.view]; // for left anchor point and here setAnchorPoint -(void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view { CGPoint newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x, view.bounds.size.height * anchorPoint.y); CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x, view.bounds.size.height * view.layer.anchorPoint.y); newPoint = CGPointApplyAffineTransform(newPoint, view.transform); oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform); CGPoint position = view.layer.position; position.x -= oldPoint.x; position.x += newPoint.x; position.y -= oldPoint.y; position.y += newPoint.y; view.layer.position = position; view.layer.anchorPoint = anchorPoint; }
[ "stackoverflow", "0027827440.txt" ]
Q: How can I identify calling view controller in viewDidLoad? I have 2 View controllers in my storyboard with the same Custom Class. How can I tell which view controller is being load in viewDidLoad? A: In your storyboard, set the restoration identifier (I think it's right under where you set the storyboard ID). Then in viewDidLoad, check that identifier: - (void)viewDidLoad { NSString *restoreID = [self restorationIdentifier]; }
[ "stackoverflow", "0051373581.txt" ]
Q: How to write azure cosmos database complex select queries As below image shows I have a collections of data in cosmos-db and I need to query those collection by order.id { "id": "0f994473-5288-44e8-8bfd-a19445e6fb51", "ecom_id": "ECOM005", "create_date_time": "2018-07-04T05:30:41.6180888+00:00", "modify_date_time": "2018-07-04T06:14:35.6422331+00:00", "ecom": "", "status": "Shipped", "order": { "id": 549096652915, "email": "", "closed_at": null, "created_at": "2018-07-04T05:26:26+00:00", "updated_at": "2018-07-04T05:26:29+00:00", "number": 347, "note": null } } I wrote following query and it's gives an error SELECT * FROM NovaFulfillments f WHERE f.order.id = 549096652915 A: Your order field name conflict with sql syntax keyword.(such as order,join,select,from etc.) This is the database field naming convention. Please try below sql : SELECT * FROM NovaFulfillments f WHERE f['order'].id = 549096652915 Syntax official doc: https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-sql-query#EscapingReservedKeywords Hope it helps you.
[ "serverfault", "0000487412.txt" ]
Q: CentOS 6.4 server installation and setup I am rather new to Linux. I have chosen CentOS 6.4 to install on a PC that we will use as a web server inside the organisation (not going to be visible from outside). I have chosen to install the "Web server" profile and I have ensured that all features of Apache, MySQL and PHP are installed, and that MySQL is secured. I connected the server to the network, and I can ping it from my workstation. I can ping my workstation from the server. I can ping Google from the server. When I do /etc/init.d/httpd status it says that httpd is running. Same for MySQL. When I do /etc/init.d/httpd stop it stops it, and when I then do /etc/init.d/httpd start, it says [FAILED] without an explanation why. I have installed WebMin, and I can access it via localhost on the server, but I can not access it via the IP address or domain name from any workstation. I can also not access the index.html stored in /var/www/html. I have switched off my firewall temporarily to test further. Could you please advise what else I can do to troubleshoot this? Thanks! Below is the shortened httpd.conf if needed (comments, AddLanguage and AddIcon removed). Thanks! ========== ServerTokens OS ServerRoot "/etc/httpd" PidFile run/httpd.pid Timeout 60 KeepAlive Off MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 4000 </IfModule> <IfModule worker.c> StartServers 4 MaxClients 300 MinSpareThreads 25 MaxSpareThreads 75 ThreadsPerChild 25 MaxRequestsPerChild 0 </IfModule> Listen 80 LoadModule auth_basic_module modules/mod_auth_basic.so LoadModule auth_digest_module modules/mod_auth_digest.so LoadModule authn_file_module modules/mod_authn_file.so LoadModule authn_alias_module modules/mod_authn_alias.so LoadModule authn_anon_module modules/mod_authn_anon.so LoadModule authn_dbm_module modules/mod_authn_dbm.so LoadModule authn_default_module modules/mod_authn_default.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule authz_user_module modules/mod_authz_user.so LoadModule authz_owner_module modules/mod_authz_owner.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_dbm_module modules/mod_authz_dbm.so LoadModule authz_default_module modules/mod_authz_default.so LoadModule ldap_module modules/mod_ldap.so LoadModule authnz_ldap_module modules/mod_authnz_ldap.so LoadModule include_module modules/mod_include.so LoadModule log_config_module modules/mod_log_config.so LoadModule logio_module modules/mod_logio.so LoadModule env_module modules/mod_env.so LoadModule ext_filter_module modules/mod_ext_filter.so LoadModule mime_magic_module modules/mod_mime_magic.so LoadModule expires_module modules/mod_expires.so LoadModule deflate_module modules/mod_deflate.so LoadModule headers_module modules/mod_headers.so LoadModule usertrack_module modules/mod_usertrack.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule mime_module modules/mod_mime.so LoadModule dav_module modules/mod_dav.so LoadModule status_module modules/mod_status.so LoadModule autoindex_module modules/mod_autoindex.so LoadModule info_module modules/mod_info.so LoadModule dav_fs_module modules/mod_dav_fs.so LoadModule vhost_alias_module modules/mod_vhost_alias.so LoadModule negotiation_module modules/mod_negotiation.so LoadModule dir_module modules/mod_dir.so LoadModule actions_module modules/mod_actions.so LoadModule speling_module modules/mod_speling.so LoadModule userdir_module modules/mod_userdir.so LoadModule alias_module modules/mod_alias.so LoadModule substitute_module modules/mod_substitute.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_ftp_module modules/mod_proxy_ftp.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule proxy_ajp_module modules/mod_proxy_ajp.so LoadModule proxy_connect_module modules/mod_proxy_connect.so LoadModule cache_module modules/mod_cache.so LoadModule suexec_module modules/mod_suexec.so LoadModule disk_cache_module modules/mod_disk_cache.so LoadModule cgi_module modules/mod_cgi.so LoadModule version_module modules/mod_version.so Include conf.d/*.conf User apache Group apache ServerAdmin kobus@**********.co.za ServerName intdev.**********.co.za:80 UseCanonicalName Off DocumentRoot "/var/www/html" <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory "/var/www/html"> Options Indexes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> <IfModule mod_userdir.c> UserDir disabled </IfModule> DirectoryIndex index.html index.html.var AccessFileName .htaccess <Files ~ "^\.ht"> Order allow,deny Deny from all Satisfy All </Files> TypesConfig /etc/mime.types DefaultType text/plain <IfModule mod_mime_magic.c> MIMEMagicFile conf/magic </IfModule> HostnameLookups Off ErrorLog logs/error_log LogLevel warn LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent CustomLog logs/access_log combined ServerSignature On Alias /icons/ "/var/www/icons/" <Directory "/var/www/icons"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> <IfModule mod_dav_fs.c> DAVLockDB /var/lib/dav/lockdb </IfModule> ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" <Directory "/var/www/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory> IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable Charset=UTF-8 AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip AddIconByType (TXT,/icons/text.gif) text/* AddIcon /icons/binary.gif .bin .exe DefaultIcon /icons/unknown.gif ReadmeName README.html HeaderName HEADER.html IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t AddLanguage ca .ca LanguagePriority ca ForceLanguagePriority Prefer Fallback AddDefaultCharset UTF-8 AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddType application/x-x509-ca-cert .crt AddType application/x-pkcs7-crl .crl AddHandler type-map var AddType text/html .shtml AddOutputFilter INCLUDES .shtml Alias /error/ "/var/www/error/" <IfModule mod_negotiation.c> <IfModule mod_include.c> <Directory "/var/www/error"> AllowOverride None Options IncludesNoExec AddOutputFilter Includes html AddHandler type-map var Order allow,deny Allow from all LanguagePriority en es de fr ForceLanguagePriority Prefer Fallback </Directory> </IfModule> </IfModule> BrowserMatch "Mozilla/2" nokeepalive BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 BrowserMatch "RealPlayer 4\.0" force-response-1.0 BrowserMatch "Java/1\.0" force-response-1.0 BrowserMatch "JDK/1\.0" force-response-1.0 BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully BrowserMatch "MS FrontPage" redirect-carefully BrowserMatch "^WebDrive" redirect-carefully BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully BrowserMatch "^gnome-vfs/1.0" redirect-carefully BrowserMatch "^XML Spy" redirect-carefully BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully A: Googling "Unable to change directory to /root" I found this post: Cannot start apache (Unable to change directory to /root) Looks like you have same issue: SELinux you have enabled does not permit you to start httpd directly. Use this: service httpd start
[ "stackoverflow", "0020216009.txt" ]
Q: image does not load in chrome extension i have created one folder named "example" in that i have put all images and js and css files and html files it is looking like below i am loading images named abcd.png with below code in manifiest.json "web_accessible_resources": [ "abcd.png" ], and another code which is in SelectedTextnotification.js divGLXBubbleQuery = document.createElement('div'); divGLXBubbleQuery.id = 'GLXBubbleQuery'; divGLXBubbleQuery.innerHTML = "<img id='klematis lilac' border='0' src='abcd.png' width='150' height='113'>"; but image does not load can any body help me what i am doing wrong A: You need to use chrome.extension.getURL, in order to "convert a relative path within an extension install directory to a fully-qualified URL". Supposing SelectedTextnotification.js is a content script, you should change your cose like this: var imgURL = chrome.extension.getURL("abcd.png"); divGLXBubbleQuery.innerHTML = "<img ... src='" + imgURL + "' ...>";
[ "stackoverflow", "0048465604.txt" ]
Q: Android AIDL: Project crash after change code to kotlin from java These are the link of my project AIDL-Client, AIDL-Server. Steps: Please install both apks. Then click "BIND Device button" "IBindDeviceCallback: deviceName: tpd deviceBrand: loop" is print in client project change "AIDLService.java" to "AIDLService.kt"in AIDL-Server project then install apk. Then click "BIND Device button"" of AIDL-server project you will find the crash. java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter deviceCertifcate at android.os.Parcel.readException(Parcel.java:1697) at android.os.Parcel.readException(Parcel.java:1646) at com.loop.ILoopService$Stub$Proxy.bindDevice(ILoopService.java:88) at com.client.MainActivity$mServiceConnection$1.onServiceConnected(MainActivity.kt:53) at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1516) at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1544) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6682) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) It looks like android/kotlin's problem rather than mine. Any idea about this crash, how to fix it in kotlin? A: The reason the exception looks like it is coming from Android is because it is being passed between processes. On MainActivity.kt line 53 in your client code, you pass null to bindDevice for the deviceCertificate byte[]. The exception is telling you that this cannot be null. When you convert the service from Java to Kotlin, it treats the method parameter as non-null by default, deviceCertifcate: ByteArray. If you tell Kotlin that this parameter can be null, it will not crash. This is acheived by declaring the type with a ?, i.e. deviceCertifcate: ByteArray?. For more information see the Kotlin docs on Null-Safety. In a normal Kotlin app, this wouldn't even compile, but since this goes across process boundaries via AIDL, the compiler can't catch this issue.
[ "ux.stackexchange", "0000116556.txt" ]
Q: How can I hide some UI elements until the mobile version is out? The first picture depicts a design of notification preferences that is really strongly inspired by Backplane's solution (the second picture), because it suits my case perfectly. The client saw the original design and said that they want to include the Mobile Push notifications as well, despite there's no mobile version yet. They said they want to grey it out, so it does not bother the user, but it's still there, already implemented, ready to be used in the future. They say it's easier to put it there now, then to remake it once the mobile version exists. I was trying to explain that it makes it unnecessarily cluttered to include something that will not be used for a long while, but they kind of insisted. However the discussion has not ended yet I think, so I started to think about how to accommodate both ways. I started with taking the mobile notifications and putting them on the side, instead of in the middle (it's already within the design). Next I was thinking about hiding them altogether (not yet within the design), giving them the color of the background for example, so they're not "there" for the user to care about (my way), but it's still there, considering the code (client's way). I know it's pretty weak, but it's a first thing that came to mind that goes along both lines of thinking. Any thoughts as to why it's a bad idea? Or any other concepts to what I could do here? A: I would strongly discourage "hiding it in plain sight" like you suggested. For one, aesthetically, your table will appear very unbalanced. More significantly, though, would be the potential damage to your users' trust if they happen to stumble across this hidden feature (for example, by accidentally selecting the region of the page where this hidden feature resides). Why did they try to sneak this by me? What else are they trying to get away with? Why don't they offer this feature to me? There's not a setting to "enable mobile settings" anywhere... As a developer myself, adding something like that later would be the same amount of UI work as adding it now. The design already has room for the additional setting, so the argument that "it will take more work to redo it later" doesn't hold any water. If this feature's "enabled" state is stored in the database, then you won't have to make any changes to this site once you do release the mobile application—you'd simply update the database, which wouldn't require any changes to your codebase. From the marketing perspective, sure, add the settings in a disabled state, but be clear about why they're disabled. You can use this opportunity to "advertise" your upcoming mobile application release.
[ "stackoverflow", "0010593075.txt" ]
Q: How to alter WM_CLASS value in a Java GUI application based on Swing or NetBeans Platform? All Swing/NetBeans-based Java GUI applications seem to have the same WM_CLASS value: WM_CLASS(STRING) = "sun-awt-X11-XFramePeer", "java-lang-Thread" This parameter can be viewed by issuing xprop command and pointing to the window. The practical purpose of customizing it is to let Mac-like docks (AWN, for example (and, perhaps, Ubuntu's Unity)) distinguish the application windows and group them under the application's pinned launcher icon. For this to work StartupWMClass parameter is to be set accordingly in the .application file in ~/.local/share/applications or /usr/share/applications. Needless to say, AWN (and analogues) get confused in case more than one application uses the same string for WM_CLASS. A: This blog post found the field in Toolkit that controls it, named awtAppClassName. It suggests using reflection to modify it: Toolkit xToolkit = Toolkit.getDefaultToolkit(); java.lang.reflect.Field awtAppClassNameField = xToolkit.getClass().getDeclaredField("awtAppClassName"); awtAppClassNameField.setAccessible(true); awtAppClassNameField.set(xToolkit, applicationName);
[ "philosophy.stackexchange", "0000055873.txt" ]
Q: What are arguments against the option of immortality? I have discussed on various occasions the possibility of human immortality with people. Most of the time people thought it would be a bad idea without giving specific reasons but relying on their feelings. Are there logical (in whatever ethical system) reasons to be opposed to immortality? (Meaning humans would be worse off as a whole than before the invention.) The only thing that comes to my mind is things wouldn't change, but the good thing about living things is that they can change without dying. Especially I don't see how in any theoretical case immortality could be bad. Let's imaging a good life where you die. An immortal life can be exactly like that life you imagined, perfect and then you die. So the option of immortality seems to me to be no hindrance and always a good option. My question boils down to: Why would people be opposed to a mere option of immortality? How could a voluntary option of any kind be a bad thing? A: One argument is that an immortal life will necessarily become oppressively boring. Living forever, you'll eventually exhaust your interests and run out of enjoyable activities. Bernard Williams makes this argument in this 1973 paper. One criticism of this argument (e.g., by Fischer here) is that it's not necessary for an immortal life to become boring. Some pleasures, for instance, will remain pleasurable even if you repeat them to no end, at least given sufficiently long intervals in between. Or new activities might be created at a sufficiently high rate so as to keep you occupied forever. I vaguely remember another argument along the lines that without the prospect of death you wouldn't have an incentive to accomplish anything in life, but I can't recall where that's from, and I don't find it particularly convincing (at least in this crude version). Also, here are a couple of lectures by Shelly Kagan on the subject from his Yale course on death: Part 1, Part 2.
[ "stackoverflow", "0011634379.txt" ]
Q: username, password etc hardcoded into program - how to pick them up from a file instead? I have made some code in ECLIPSE. As you can see, the username, password, database URL, SQL Queries are hardcoded into my program. I don't want to change my code and recompile it every time I change the password, username of my database or modify the query. For that reason, I want to put these "parameters" inside a file (text, XML, json ???). I want to be able to change the parameters easily. So what should I do ? What kind of file should I use ? I want to avoid XML, json because you need to know both well. XML and JSON can be difficult when the code grows big. import java.sql.*; public class JDBCDemo { static String query = "SELECT customerno, name " + "FROM customers;"; public static void main(String[]args) { String username = "cowboy"; String password = "123456"; try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/business", username, password); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); }catch(SQLException ex){System.out.println("Exception! " + ex);} } } A: You can use Properties and read the values from a .properties file.
[ "stackoverflow", "0025030415.txt" ]
Q: angularjs filter to convert to valid directive name I want to write filter that turns for example: 'selectSingle' into this: 'select-single' That is for me to build custom directives in the ng-repeat process which excepts the 'selectSingle' value, and so. any suggestions? A: this would do it: .filter('camelToHtml', function(){ var re = /[A-Z]/g; return function(camelCase){ return camelCase.replace(re, function(match, index, original){ return "-" + match.toLowerCase() }); }; });
[ "stackoverflow", "0000971296.txt" ]
Q: How to use dll's in the same directory as an excel file This is somewhat related to my other question. I've been using a dll to acompany an excel spreadsheet. Everything is currently working with the dll and excel is using it just fine. But is it possible to specify that a dll resides in the same directory as the excel file when declaring functions? Declare Sub FortranCall Lib "Fcall.dll" (r1 As Long, ByVal num As String) Unfortunetly this doesn't work, I have to use something like: Declare Sub FortranCall Lib "C:\temp\Fcall.dll" (r1 As Long, ByVal num As String) This works, but is going to cause headaches when distributing to my office mates. Placing the dll in c:\windows\system32 etc. is not really an option either. A: Here are three possibilities for dynamically loading/calling into DLLs from VBA, including links to relevant info and some sample code. Can't say I've ever had to use any of the solutions described there, but it seems like a reasonable exploration of the options in light of VBA's need for a static path. Create a new module at runtime (you could import a .bas file from disk, no need to hard-code the module with string literals), using the VBIDE Extensibility API. Drawback: no compile-time validation; you'll need to use stringly-typed Application.Run calls to invoke it. Requires trusted programmatic access to the VBIDE API (i.e. you allow VBA to execute code that generates code that is then executed... like macro viruses do). Use the LoadLibrary Win32 API... and now you've got pointers and addresses: this scary code (.zip download) is essentially a huge unmaintainable hack that uses assembly language to enable invoking the API functions by name. Looks like it only works for a subset of supported Win32 API functions though. Change the DLL search path, but then that also requires dynamic code added at run-time, so might as well go with the above. Here's another potential solution that suggests programmatically updating the PATH environment variable prior to calling into your DLL. Not a bad idea, if it works, as you could add this to you workbook open event. Good luck! A: The way I generally take care of this is by adding: Dim CurrentPath As String CurrentPath = CurDir() ChDir (ThisWorkbook.Path) To: Private Sub Workbook_Open()
[ "stackoverflow", "0016780585.txt" ]
Q: CSS parsing Python for finding font-family given a stylesheet file. I want to find out the font-family values used all over the stylesheet. Please can someone hint me on an idea to do this? I crawled, parsed the stylesheet link using Beautifulsoup. But now im left with a big string of stylesheet. Sorry if this is a noob question. Just willing to learn. A: Try cssutils package, e.g.: import cssutils data = """ p{font-family:"Verdana"} p{font-family:"Comic Sans"} p{font-family:"Times New Roman", Times, serif} """ sheet = cssutils.parseString(data) for rule in sheet: if rule.type == rule.STYLE_RULE: # find property for property in rule.style: if property.name == 'font-family': print property.value This prints: "Verdana" "Comic Sans" "Times New Roman", Times, serif Also, see Martijn's answer here: BeautifulSoup: get css classes from html. Hope that helps.
[ "math.stackexchange", "0002201092.txt" ]
Q: Parenthesis vs brackets for matrices - next I have read Parenthesis vs brackets for matrices and I currently use brackets matrices (quaternions in 3D computing, in fact). But I still have a doubt about the strict compatibility of notations between brackets and parenthesis, as explained in the previous topic. I do think brackets are orientation dependent where parenthesis are not, which goes with comas usage… It's my question $$ \begin{pmatrix} 1, 2, 3, 6 \end{pmatrix} · \begin{pmatrix} 0, 1, 0, 0 \end{pmatrix} = \begin{pmatrix} -2, 1, 6, -3\end{pmatrix} $$ but $$ \begin{bmatrix} 1 \\ 2 \\ 3 \\ 6 \end{bmatrix} · \begin{bmatrix} 0 \\ 1 \\ 0 \\ 0 \end{bmatrix} = \begin{bmatrix} -2\\ 1\\ 6\\ -3 \end{bmatrix} $$ What's the truth ? A: Sometimes it is a matter of agreement. Many analysts use $(x_1,\ldots,x_n)$ to denote vectors of $\mathbb{R}^n$, while geometers and algebraists recommend $$ \begin{pmatrix} x_1 \\ \vdots \\ x_n \end{pmatrix}. $$ Indeed analysts often confuse, in $\mathbb{R}^n$, vectors and co-vectors (i.e. linear forms acting on vectors).
[ "stackoverflow", "0003930338.txt" ]
Q: SQL Server: Get table primary key using sql query I want to get a particular table's primary key using SQL query for SQL Server database. In MySQL I am using following query to get table primary key: SHOW KEYS FROM tablename WHERE Key_name = 'PRIMARY' What is equivalent of above query for SQL Server ?. If There is a query that will work for both MySQL and SQL Server then It will be an ideal case. A: I also found another one for SQL Server: SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1 AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema' A: Found another one: SELECT KU.table_name as TABLENAME ,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND KU.table_name='YourTableName' ORDER BY KU.TABLE_NAME ,KU.ORDINAL_POSITION ; I have tested this on SQL Server 2003/2005 A: Using SQL SERVER 2005, you can try SELECT i.name AS IndexName, OBJECT_NAME(ic.OBJECT_ID) AS TableName, COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName FROM sys.indexes AS i INNER JOIN sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID AND i.index_id = ic.index_id WHERE i.is_primary_key = 1 Found at SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database
[ "ru.stackoverflow", "0000000099.txt" ]
Q: Что сделать, чтобы приложение на Go собралось под Native Client? Что сделать, чтобы приложение на Go собралось под Native Client? A: Нужно перед сборкой задать переменную окружения GOOS. export GOOS=nacl
[ "stackoverflow", "0018801157.txt" ]
Q: External Style Sheet does not work with `h1` in XAMPP I am trying to make a navigation bar in a separate file, so that I may include it with php later. The file, nav_menu.php, contains a h1 tag, a p tag, and an ul containing a tags.I made the CSS in an External Style Sheet. I styled all the elements. The h1 tag didn't work. Why? nav_menu.php: <html> <head> <link rel="stylesheet" type="text/css" href="nav_menu.css"> </head> <body> <h1 title="School Helping Program">------ S.H.P. ------</h1> <p title="S.H.P.">School Helping Program</p> <ul> <li><a href="home.php">home</a></li> <li><a href="marks.php">marks</a></li> <li><a onclick="logout()">log out</a></li> </ul> </body> </html> nav_menu.css: <style> h1{text-align:center;color:#CC0000;}/*Here's the prolbem*/ p{font-style:italic;text-align:center;} li{float:left;} ul{list-style-type:none;margin:0;padding:0;} a{ display:block; width:180px; text-align:center; background-color:#5CB8E6; text-transform:uppercase; color:#CC0000; text-decoration:none; padding:10px 135px; cursor: pointer; } A: This is because you got <style> in first line and browser threats it as <style>\n\nh1 selector.
[ "stackoverflow", "0054494990.txt" ]
Q: Verify continuous condition with time I would like to develop a python program that, starting from a moment of time, wait 60 seconds before performing an action. Another feature that must have the program, is that if I update the initial time, it must start to check the condition. I thought about doing it with threads, but I do not know how to stop the thread and get it started again with the new start time. import thread import time # Define a function for the thread def check_message (last, timer): oldtime = time.time() print oldtime # check while time.time() - oldtime <= 60: print (time.time() - oldtime) print "One minute"+ str(time.time()) return 1 # Create two threads as follows try: named_tuple = time.localtime() # get struct_time time_string = time.strftime("%H:%M:%S", named_tuple) thread.start_new_thread(check_message , (time_string, 60)) except: print "Error: unable to start thread" while 1: pass Thanks! A: Checking times in a loop is probably not necessary here and wasteful since you can put a thread to sleep and let the kernel wake it up if the time has come. The threading library provides threading.Timer for such use cases. The difficulty in your case is, that you cannot interrupt such a sleeping thread to adjust the interval after which the specified function should be executed. I'm using a custom manager-class TimeLord in my example below, to overcome this limitation. TimeLord enables "resetting" the timer by canceling the current timer and replacing it with a new one. For this purpose TimeLord contains a wrapping intermediate worker-function and a "token"-attribute, which must be popped by a running timer-instance to execute the specified target-function. This design guarantees unique execution of the specified target-function since dict.pop() is an atomic operation. timelord.reset() is effective as long the current timer has not started its thread and popped the _token. This approach can not totally prevent potentially ineffective starts of new timer-threads when trying to "reset", but it's an uncritical redundancy when it happens since the target function can only be executed once. This code runs with Python 2 and 3: import time from datetime import datetime from threading import Timer, current_thread def f(x): print('{} {}: RUNNING TARGET FUNCTION'.format( datetime.now(), current_thread().name) ) time.sleep(x) print('{} {}: EXITING'.format(datetime.now(), current_thread().name)) class TimeLord: """ Manager Class for threading.Timer instance. Allows "resetting" `interval` as long execution of `function` has not started by canceling the old and constructing a new timer instance. """ def worker(self, *args, **kwargs): try: self.__dict__.pop("_token") # dict.pop() is atomic except KeyError: pass else: self.func(*args, **kwargs) def __init__(self, interval, function, args=None, kwargs=None): self.func = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self._token = True self._init_timer(interval) def _init_timer(self, interval): self._timer = Timer(interval, self.worker, self.args, self.kwargs) self._timer.daemon = True def start(self): self._timer.start() print('{} {}: STARTED with `interval={}`'.format( datetime.now(), self._timer.name, self._timer.interval) ) def reset(self, interval): """Cancel latest timer and start a new one if `_token` is still there. """ print('{} {}: CANCELED'.format(datetime.now(), self._timer.name)) self._timer.cancel() # reduces, but doesn't prevent, occurrences when a new timer # gets created which eventually will not succeed in popping # the `_token`. That's uncritical redundancy when it happens. # Only one thread ever will be able to execute `self.func()` if hasattr(self, "_token"): self._init_timer(interval) self.start() def cancel(self): self._timer.cancel() def join(self, timeout=None): self._timer.join(timeout=timeout) def run_demo(initial_interval): print("*** testing with initial interval {} ***".format(initial_interval)) tl = TimeLord(interval=initial_interval, function=f, args=(10,)) tl.start() print('*** {} sleeping two seconds ***'.format(datetime.now())) time.sleep(2) tl.reset(interval=6) tl.reset(interval=7) tl.join() print("-" * 70) if __name__ == '__main__': run_demo(initial_interval=5) run_demo(initial_interval=2) Example Output: *** testing with initial interval 5 *** 2019-06-05 20:58:23.448404 Thread-1: STARTED with `interval=5` *** 2019-06-05 20:58:23.448428 sleeping two seconds *** 2019-06-05 20:58:25.450483 Thread-1: CANCELED 2019-06-05 20:58:25.450899 Thread-2: STARTED with `interval=6` 2019-06-05 20:58:25.450955 Thread-2: CANCELED 2019-06-05 20:58:25.451496 Thread-3: STARTED with `interval=7` 2019-06-05 20:58:32.451592 Thread-3: RUNNING TARGET FUNCTION 2019-06-05 20:58:42.457527 Thread-3: EXITING ---------------------------------------------------------------------- *** testing with initial interval 2 *** 2019-06-05 20:58:42.457986 Thread-4: STARTED with `interval=2` *** 2019-06-05 20:58:42.458033 sleeping two seconds *** 2019-06-05 20:58:44.458058 Thread-4: RUNNING TARGET FUNCTION 2019-06-05 20:58:44.459649 Thread-4: CANCELED 2019-06-05 20:58:44.459724 Thread-4: CANCELED 2019-06-05 20:58:54.466342 Thread-4: EXITING ---------------------------------------------------------------------- Process finished with exit code 0 Note, with interval=2 the cancelations after two seconds had no effect, since the timer was already executing the target-function.
[ "stackoverflow", "0050305668.txt" ]
Q: Change background colour of navbarPage menubar in R shiny In R Shiny, I would like to change the background colour of the navbar menu. I would like to change the colour everywhere on the menu bar (including the colour of the buttons when hovering over them, or when they're inactive, etc.), except for the font, to one colour (black). However, I do not wish to change any other default colours, such as the background colour of the main part of the page. I've attempted to do so by creating a CSS file as follows: body, #selector, .container, .navbar-background { background: #000000; } I've also tried lots of other combinations and parameters, but nothing seems to work. What is the parameter in the CSS file that controls the background colour of the navbar menu bar? Note that the answer in: How to change navBarPage header background in Zebble? hasn't worked for me. A: Try .navbar-default { background-color: #b1b1b3 !important; } .navbar-default:hover { background-color: #aaaaaa !important; color: yellow; }
[ "apple.stackexchange", "0000003455.txt" ]
Q: Should I use the adapter or the battery? I want to know when my MBP's battery was fully charged it's better to unplug my adapter and use my battery power or still let use adapter power? I somewhere read that when MBP's battery was fully charged it's just use adapter for power and don't use battery, if it's true it didn't hurt adapter and reduce it's lifetime? I have Macbook Pro 13" dual core(2.53) A: Read what Apple has to say about notebook batteries: Apple’s Batteries Page Apple’s Notebook Batteries Page EDIT for the lazy(es) who don’t want to read the links: lithium-ion batteries need to be fully discharged and recharged at least once a month. Go ahead and create an iCal reminder… Leaving it plugged won’t affect it, as long as you remember to do (1) every 30 days. If you have to “store” and put your battery away for more than six months, you should definitely store the battery with a 50% charge. Reasons are listed in the corresponding link. Pay attention to temperatures, they can damage and severely hamper battery operation. I hope this makes everybody happy. Now… as a final note: the new unibody stuff coming from Apple doesn’t have removable batteries, however, the battery design is the same… those are lithium-ion batteries, no matter how fancy they make it look. Macbooks do not have a nuclear core in there, so the same rules apply, except that… well, you can’t remove it for storage, so more than ever, remember the 30 day rule.
[ "stackoverflow", "0023135558.txt" ]
Q: oracle sql views specifying further criteria If you have created a view in oracle sql like create view view_item as select * from employees Then you can call it like select * from view_item. However, I was wondering whether it's possible to further specify some creteria which is not part of the initial view specification such as select * from view_item where name='Mark' This one won't work unless I have specified it into the view beforehand. A: A view is a query that is being saved on the DBMS so where you run: create view view_item as select * from employees you just save the query somewhere in the DBMS memory. when you run : select * from view_item you actually run: select * from employees BUT - here's the fun part - for you it looks like a table, so you can append it with a where : select * from view_item where name ='Mark' will map to select * from employees where name = 'Mark' Let's take it furthere, let's say you created a view with a where clause create view view_item as select * from employees where salary < 10000 than the same query from before: select * from view_item where name ='Mark' will map to select * from employees where salary < 10000 and name = 'Mark' a DBMS is pretty cool :) you should play with it to understand exactly what's going in the background, because you can use it for permissions and other things..
[ "physics.stackexchange", "0000388079.txt" ]
Q: Majorana Flip Relations In the Supergravity book of Freedman et.al, which uses the signature $(+,-,\dots,-)$, we have defined the charge conjugation matrix for general Clifford Algebra as $(C\Gamma^{(r)})^T = -t_rC \Gamma^{(r)}$, where $\Gamma^{(r)}$ are the basis of the Clifford Algebra with rank $r$ and $t_r = \pm 1$ (Eqn. 3.44). Furthermore, the Majorana Conjugate as $\bar \lambda = \lambda^T C$ and later he states the Majorana Flip Relation (Eqn. 3.51) as $$ \bar \lambda \gamma_{\mu_1 \dots \mu_r} \chi = t_r \bar \chi \gamma_{\mu_1 \dots \mu_r} \lambda $$ However, when I calculate the expression on the right, I get an additional minus sign: \begin{align*} \bar \lambda \gamma_{\mu_1 \dots \mu_r} \chi &= \lambda^T C \gamma_{\mu_1 \dots \mu_r} \chi = (\chi^T \gamma^T_{\mu_1 \dots \mu_r} C^T \lambda)^T \\ &= -t_r (\chi^TC \gamma_{\mu_1 \dots \mu_r} \lambda)^T \\ &= - t_r\bar \chi \gamma_{\mu_1 \dots \mu_r} \lambda \end{align*} where in the last step I use that the expression $\bar \chi\gamma_{\mu_1 \dots \mu_r} \lambda$ is a scalar. He (apparently) explains the lack of the minus sign by saying: $``$The minus sign obtained by changing the order of Grassmann valued spinor components has been incorporated.$"$ I honestly have no idea what he is talking about and I also don't know where exactly my mistake in the calculation above is wrong. A: Recall that in an elementary Linear Algebra course, you proved that for two matrices $A,B$, $(AB)^T=B^T A^T$. Do this in component notation. For this proof you will commute the component of $A$ past the component of $B$. In the case where the components of $A,B$ are anti-commuting (Grassmann) numbers, the same step will give you an extra minus sign. Hence, for this latter case, $(AB)^T=-B^T A^T$.
[ "stackoverflow", "0008993854.txt" ]
Q: Is there an InnerText equivalent in BeautifulSoup? With the code below: soup = BeautifulSoup(page.read(), fromEncoding="utf-8") result = soup.find('div', {'class' :'flagPageTitle'}) I get the following html: <div id="ctl00_ContentPlaceHolder1_Item65404" class="flagPageTitle" style=" "> <span></span><p>Some text here</p> </div> How can I get Some text here without any tags? Is there InnerText equivalent in BeautifulSoup? A: All you need is: result = soup.find('div', {'class' :'flagPageTitle'}).text A: You can use findAll(text=True) to only find text nodes. result = u''.join(result.findAll(text=True)) A: You can search for <p> and get its text: soup = BeautifulSoup.BeautifulSoup(page.read(), fromEncoding="utf-8") result = soup.find('div', {'class': 'flagPageTitle'}) result = result.find('p').text
[ "stackoverflow", "0049548594.txt" ]
Q: Key Events not registering in Flex AS3 I'm currently working on a project using ActionScript 3 in Flex 4.6. I was having trouble making any key events register in my script (though mouse events were fine), and debugging lead to some very bizarre results. First of all, this is my test code: Contents of KET.mxml: <?xml version="1.0"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" name="Key Events Test" backgroundColor="#000000" horizontalAlign="center" creationComplete="setup();" enterFrame="updateFrame();" paddingLeft="0" paddingTop="0" paddingBottom="0" paddingRight="0" frameRate="60" width="960" height="720"> <mx:Script> <![CDATA[ include "KET.as"; ]]> </mx:Script> <mx:Canvas id="gamePanel" x="0" y="0" width="100%" height="100%" click="mouseClicked(event)" keyDown="keyDown(event)"/> </mx:Application> Contents of KET.as: import flash.display.*; import flash.events.*; import mx.events.*; import mx.controls.*; public static const SCREEN_WIDTH:int = 960; public static const SCREEN_HEIGHT:int = 720; private var initializationCompleted:Boolean = false; public var screenBuffer:BitmapData; private var trigger:int = 0; public function setup():void { screenBuffer = new BitmapData(SCREEN_WIDTH, SCREEN_HEIGHT, false, 0x00000000); initializationCompleted = true; } private function updateFrame():void { if (!initializationCompleted) { return; } gamePanel.graphics.clear(); gamePanel.graphics.beginBitmapFill(screenBuffer, null, false, false); gamePanel.graphics.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); gamePanel.graphics.endFill(); if (trigger == 0) { screenBuffer.fillRect(new Rectangle(480, 360, 200, 200), 0xFF000000); } else if (trigger == 1) { screenBuffer.fillRect(new Rectangle(480, 360, 200, 200), 0xFFFF0000); } else if (trigger == 2) { screenBuffer.fillRect(new Rectangle(480, 360, 200, 200), 0xFF0000FF); } } private function mouseClicked(event:MouseEvent):void { trigger = 1; } private function keyDown(event:KeyboardEvent):void { trigger = 2; } The code above, when ran, is supposed to give a black screen at the start, on which a red rectangle appears once the user clicks on it and a blue one once the user presses a key. However, the key press is completely ignored. While debugging this, I started getting some very strange results. A tutorial I have been loosely following found here shows how to check for keyboard events. Now upon following the same instructions, or even downloading and compiling the code given in the tutorial I get a fully working project, but with no keyboard controls. Now this happens regardless of how I run the resulting SWF, be it in a flash interpreter, through a browser locally or from a server. At first I thought it was due to the SWF given in the tutorial being compiled by some legacy version of Flex, but after downloading the SWF from the website directly I get the same results. The only place where it works is on the original website. So what am I doing terribly wrong here? Is there a bug in my current solution or am I just taking an incredibly wrong approach? Thanks in advance!! A: I have not tested your project, but if memory serves, a component needs to receive focus to handle keyboard events. By simply adding gamePanel.setFocus(); at the end of the updateFrame() function, I think it will work. Like this: private function updateFrame():void { if (!initializationCompleted) { return; } gamePanel.graphics.clear(); gamePanel.graphics.beginBitmapFill(screenBuffer, null, false, false); gamePanel.graphics.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); gamePanel.graphics.endFill(); if (trigger == 0) { screenBuffer.fillRect(new Rectangle(480, 360, 200, 200), 0xFF000000); } else if (trigger == 1) { screenBuffer.fillRect(new Rectangle(480, 360, 200, 200), 0xFFFF0000); } else if (trigger == 2) { screenBuffer.fillRect(new Rectangle(480, 360, 200, 200), 0xFF0000FF); } gamePanel.setFocus(); } Another option could be to add an EventListener for the whole application (be careful, if you use text fields, this EventListener will be triggered during text input). public function setup():void { screenBuffer = new BitmapData(SCREEN_WIDTH, SCREEN_HEIGHT, false, 0x00000000); systemManager.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown); initializationCompleted = true; } I hope this will help you.
[ "tex.stackexchange", "0000257357.txt" ]
Q: Problems with scrlayer-scrpage after getting the constant warning I shouldn't use fancyhdr with KOMA I decided to switch to scrlayer-scrpage. Unfortunately I can't get it to work despite of reading through the documentation. This is what I have at the moment \documentclass[12pt,ngerman]{scrreprt} \renewcommand{\familydefault}{\sfdefault} \usepackage[ansinew]{inputenc} \usepackage[T1]{fontenc} \usepackage{geometry} \geometry{verbose,tmargin=2cm,bmargin=3.5cm,lmargin=3cm,rmargin=2.5cm} \usepackage{graphicx} \usepackage{fancyhdr} \pagestyle{fancy} \lhead{\slshape \leftmark} \chead{} \rhead{{\includegraphics[height=1cm]{IMG/Logo.JPG}}} \lfoot{} \cfoot{} \rfoot{\thepage} \usepackage{color} \definecolor{mygreen}{RGB}{23,156,125} \renewcommand{\footrule}{\vbox to 0pt{\hbox to \headwidth{{\color{mygreen}\hrulefill}}}\vss} \renewcommand{\headrule}{\vbox to 0pt{\hbox to \headwidth{{\color{mygreen}\hrulefill}}}\vss} \begin{document} Hello \end{document} The result is the chapter title in the upper left corner, a logo in the upper right corner, page number in the lower right corner and two green vertical lines. I would like to have the same output with scrlayer-scrpage with two small changes. First I would like to reduce the spacing between the line and the chapter title. Second I would like to align the chapter title to the bottom border of the image. Any help would be very much appreciated. Thanks in advance Jon ************** EDIT ****************************************************** Thanks to cfr this is what I got now \documentclass[12pt,headsepline,footsepline,plainfootsepline,plainheadsepline]{scrreprt} \renewcommand{\familydefault}{\sfdefault} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{geometry} \geometry{verbose,tmargin=3.5cm,bmargin=3.5cm,lmargin=3cm,rmargin=2.5cm,headheight=33pt} \usepackage{graphicx} \usepackage{xcolor,calc} \definecolor{mygreen}{RGB}{23,156,125} \usepackage{scrlayer-scrpage} \usepackage{kantlipsum} \setkomafont{pageheadfoot}{\upshape} \setkomafont{pagehead}{\slshape} \setkomafont{headsepline}{\color{mygreen}} \setkomafont{footsepline}{\color{mygreen}} \pagestyle{scrheadings} \automark{chapter} \ihead{\leftmark\hfill \includegraphics[height=1cm]{IMG/Logo.jpg}} \ohead{} \chead{} \ofoot*{\thepage} \cfoot*{} \chead{} \ihead*{\leftmark\hfill \includegraphics[height=1cm]{IMG/Logo.jpg}} \begin{document} Hello \part{Hello} \chapter{Some chapter} \kant[1-10] \end{document} Thanks again for that. This is (after some minor changes) exactly what I wanted. But I have two follow up questions. How would I proceed when I wanted to alter the header style for certain pages (e.g. two images in the top header instead of one)? Furthermore a change from geometry to typearea was suggested. How would you incorporate this package with the current settings? Thank again A: This translates your page layout into KOMA's terms. It may not make the requested changes because I don't know what they are meant to be. Your example does not include any chapters, let alone chapter titles, and it is impossible to guess which distance you are talking about or what is meant to align with what. Note that, as originally configured, your layout will be inconsistent because both fancyhdr and scrlayer-scrpage will adjust headheight as required, changing the page dimensions in unpredictable ways. To avoid this, you need to make the height at least 33pt and to tell geometry about it. Note also that scrlayer-scrpage is designed to cooperate with typearea. By using geometry, you lose the advantages of this. Consider whether you could use KOMA's typearea instead. Here's the initial translation: \documentclass[12pt,headsepline,footsepline]{scrreprt} \renewcommand{\familydefault}{\sfdefault} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{geometry}% do you really need this? Better to use KOMA's setup if possible \geometry{verbose,tmargin=2cm,bmargin=3.5cm,lmargin=3cm,rmargin=2.5cm,headheight=33pt}% the value 33pt is obtained from console warnings output by scrlayer-scrpage - this is the minimum required value, given the inclusion of the graphic - again, it would be better if you could use typearea for this \usepackage[demo]{graphicx} \usepackage{xcolor} \definecolor{mygreen}{RGB}{23,156,125} \usepackage{scrlayer-scrpage} \setkomafont{pageheadfoot}{\upshape} \setkomafont{pagehead}{\slshape} \setkomafont{headsepline}{\color{mygreen}} \setkomafont{footsepline}{\color{mygreen}} \pagestyle{scrheadings} \automark{chapter} \ihead{\leftmark} \ohead{\includegraphics[height=1cm]{IMG/Logo.JPG}} \ofoot{\thepage} \cfoot{} \chead{} \begin{document} Hello \end{document} I am guessing that you want the same footer on plain pages as on other pages. This can be achieved using the starred versions of \cfoot and \ofoot, and adding plainfootsepline to the class options: \documentclass[12pt,headsepline,footsepline,plainfootsepline]{scrreprt} \renewcommand{\familydefault}{\sfdefault} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{geometry}% do you really need this? Better to use KOMA's setup if possible \geometry{verbose,tmargin=2cm,bmargin=3.5cm,lmargin=3cm,rmargin=2.5cm,headheight=33pt}% the value 33pt is obtained from console warnings output by scrlayer-scrpage - this is the minimum required value, given the inclusion of the graphic - again, it would be better if you could use typearea for this \usepackage[demo]{graphicx} \usepackage{xcolor} \definecolor{mygreen}{RGB}{23,156,125} \usepackage{scrlayer-scrpage,kantlipsum} \setkomafont{pageheadfoot}{\upshape} \setkomafont{pagehead}{\slshape} \setkomafont{headsepline}{\color{mygreen}} \setkomafont{footsepline}{\color{mygreen}} \pagestyle{scrheadings} \automark{chapter} \ihead{\leftmark} \ohead{\includegraphics[height=1cm]{IMG/Logo.JPG}} \ofoot*{\thepage} \cfoot*{} \chead{} \begin{document} Hello \chapter{Some chapter} \kant[1-10] \end{document} I'm guessing that the further change you want concerns the alignment of the \leftmark in the header. I'm not sure how this constitutes 2 changes, mind, since aligning with the bottom of the image will also reduce the distance.... So, I'm guessing you want something like this: In which case, it is easiest, I think, to simply define the header in one go, setting the other parts of the header empty: \documentclass[12pt,headsepline,footsepline,plainfootsepline]{scrreprt} \renewcommand{\familydefault}{\sfdefault} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{geometry}% do you really need this? Better to use KOMA's setup if possible \geometry{verbose,tmargin=2cm,bmargin=3.5cm,lmargin=3cm,rmargin=2.5cm,headheight=33pt}% the value 33pt is obtained from console warnings output by scrlayer-scrpage - this is the minimum required value, given the inclusion of the graphic - again, it would be better if you could use typearea for this \usepackage{graphicx} \usepackage{xcolor,calc} \definecolor{mygreen}{RGB}{23,156,125} \usepackage[markcase=upper]{scrlayer-scrpage} \usepackage{kantlipsum} \setkomafont{pageheadfoot}{\upshape} \setkomafont{pagehead}{\slshape} \setkomafont{headsepline}{\color{mygreen}} \setkomafont{footsepline}{\color{mygreen}} \pagestyle{scrheadings} \automark{chapter} \ihead{\leftmark\hfill \includegraphics[height=1cm]{example-image-a}} \ohead{} \chead{} \ofoot*{\thepage} \cfoot*{} \chead{} \begin{document} Hello \chapter{Some chapter} \kant[1-10] \end{document} EDIT In response to the question concerning changing the headers, you can simply redefine \ihead (or \ihead*) as you wish. Do note, however, that doing so is likely to be confusing to readers. The point of running heads is that they contain information which is consistent throughout the document (except on special pages such as the first pages of chapters etc.). Also, the headers should not distract from the body of the document. \ihead{\includegraphics[height=1cm]{example-image-b}\hfill\includegraphics[height=1cm]{example-image-a}} \kant[11-14] \ihead{\leftmark\hfill \includegraphics[height=1cm]{example-image-a}} \kant[15-20] EDIT EDIT You can produce roughly the same page layout using typearea by commenting out the calls to geometry and adding \areaset[5mm]{155mm}{272mm} However, if you are stuck with a requirement to use precisely the dimensions given, then you may need to stick to geometry even though it does not cooperate with KOMA. You need to be a bit more careful to make sure you specify adequate headheight etc. in that case.
[ "stackoverflow", "0007491577.txt" ]
Q: How can I go back to the first view from the third view directly? When I touch cancel button in the third view, I want to go back to the first view directly. How can I do that? This is the code. // this part is in the first view. SecondController *aSecondController = [[SecondController alloc] init]; UINavigationController *aNaviController = [[UINavigationController alloc] initWithRootViewController:aSecondController]; self.naviController = aNaviController; [aNaviController release]; [aSecondController release]; [self.view addSubview:naviController.view]; // this part is in the second view. ThirdController *thirdController = [[ThirdController alloc] initWithStyle:UITableViewStyleGrouped]; [self.navigationController pushViewController:thirdView]; [thirdView release]; // this part is in the third view. - (void)cancel { [self.navigationController popViewControllerAnimated:NO]; // this only goes to the second view. } popToViewController, popToRootViewController only go to the second view also. A: Set up the navigation controller in your app delegate. Make the first view controller the nav controller's root controller instead of having the first view controller own the nav controller. Then you can use -popToRootViewController:animated: as the other answers have suggested.
[ "sharepoint.stackexchange", "0000174308.txt" ]
Q: Display Common Metadata Tags as Webpart Looking to create a "common tags" pane on a homepage in SP2013 based on metadata but struggling to find a clean efficient way to do so. Found an MSDN guide on getting the term stores using a Taxonomy Session in c#: TaxonomySession session = new TaxonomySession(site); But this doesn't give me numbers of their use. Effectively, when a user clicks on the tag, it would load a search with the metadata term as the search value. Tag 1 [5] Tag 2 [3] Tag 3 [6] Has anybody done this previously, or is it a bit of a none starter? Thanks A: Haven't done this, but the way I would do it is to make a query to search (f.e. using REST) and ask to return tags as refiners (create a refinable managed property, if it's not there yet). Refiners have a RefinementCount property, which gives an approximate number of hits. Creating a link to search for each refinement result (tag) shouldn't be difficult either. This way you only do one search query to get everything that you need, which is really efficient. An example REST API query, which will return all items in search index: https://yoursite.sharepoint.com/_api/search/query?querytext='*'&refiners=%27RefinableTags%27 Once you create this refinable managed property RefinableTags you should get all possible used tags and their count in the resultset PrimaryQueryResult/RefinementResults/Refiners, for example: <d:Refiners m:type="Collection(Microsoft.Office.Server.Search.REST.Refiner)"> <d:element> <d:Entries m:type="Collection(Microsoft.Office.Server.Search.REST.RefinerEntry)"> <d:element> <d:RefinementCount m:type="Edm.Int64">452</d:RefinementCount> <d:RefinementName>Tag1</d:RefinementName> <d:RefinementToken>"ǂǂ5368617265506f696e7420417070"</d:RefinementToken> <d:RefinementValue>Tag1</d:RefinementValue> </d:element> ... </d:Entries> <d:Name>refinabletags</d:Name> </d:element> </d:Refiners> You can use RefinementCount for the count, RefinementName to display to user and RefinementToken to create a URL to a search page which refines by this tag (i.e. shows all results with that tag). You will need to URL encode this, but for clarity's sake I'll post this unencoded: https://yoursite.sharepoint.com/search/Pages/results.aspx?k=#Default={"k":"","r":[{"n":"RefinableTags","t":["\"ǂǂ5368617265506f696e7420417070\""],"o":"and","k":false,"m":null}]} Edit: just now noticed that you might want to open a search page with the taxonomy written in the search box. In that case it's even easier, just construct the search query in k parameter: https://yoursite.sharepoint.com/search/Pages/results.aspx?k=Tag1 or for more accurate results: https://yoursite.sharepoint.com/search/Pages/results.aspx?k=RefinableTags:Tag1
[ "math.stackexchange", "0000854449.txt" ]
Q: Square matrix A, and Is $A = S^2$? Given A is a square matrix. A is diagonalizable and has eigenvalues which are real (and bigger than zero). Is it necessary true that $A = S^2$? I believe it is, anyone have any ideas how to solve it? I know that if A is diagonalizable, then it has a matrix - $D$ which diagonalizes A. I mean: $P^{-1}AP = D$ But how can I deduce from here that $A = S^2$ ? A: You can take the square root of the entries in your diagonal matrix, then conjugate by $P$ to find your matrix $S$ for which $S^2=A$. That is if $$D = diag( d_1,..., d_n)$$ then we write $$\sqrt{D} = diag(\sqrt{ d_1}, ..., \sqrt{d_n})$$ Then we have $\sqrt{D}^2 = D$. Now compute $S = P \sqrt{D} P^{-1}$, which means that $$S^2 = P \sqrt{D}^2 P^{-1} = P D P^{-1} = A$$
[ "korean.stackexchange", "0000002385.txt" ]
Q: Native English Translations that capture the intended emotion of "그래야 비로소" Please provide some translations (not literal) that capture the true spirit of 그래야 비로소 Google translates it That's it. Daum's best combines the two for a very awkward Only if one does that + not. I'm really interested in what someone with a good feel of both languages would offer as some options - with a phrase like this, there must be a dozen ways to say No way jose or Not on your life (or are those two appropriate candidates?) Ah, and I suppose an example sentence is always helpful, eh? 그래야 비로소 우리의 삶에 하나님이 원하시는 열매가 열리기 시작한다. Note: the suggested phrase does not have to "fit well" into the example sentence, but should capture the feeling well, even if the sentence's literal translation has to be significantly reworded - I'm trying to capture that emotion, not the literalism A: As you say, I think the business of 'spirit capturing' is easier done for sentences than phrases. How about: Not till then shall our lives begin to bear such fruit as shall please the Lord. By itself '비로소' might have the feel of 'thenceforward' (in terms of elevation). I am afraid 'that's all there is to it' (from your comments) would not do for two reasons. It emphasizes the sufficiency of the thing suggested (as if nothing else were needed). '비로소' however emphasizes the necessity of the thing. It is low register while '비로소' is high (even slightly archaic). A: I believe the phrase if only and only then finally fits well. 무엇인가 해야 (하다 + 그래야) 비로소 무언가를 이룰 수 있다. We must do something. If only and only then we can finally achieve something (we have been longing for).